2015-01-01 14:49:30 -05:00
|
|
|
package fzf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"io"
|
|
|
|
"os"
|
2015-01-11 22:56:17 -05:00
|
|
|
|
|
|
|
"github.com/junegunn/fzf/src/util"
|
2015-01-01 14:49:30 -05:00
|
|
|
)
|
|
|
|
|
2015-01-11 13:01:24 -05:00
|
|
|
// Reader reads from command or standard input
|
2015-01-01 14:49:30 -05:00
|
|
|
type Reader struct {
|
2015-08-02 01:25:57 -04:00
|
|
|
pusher func([]byte) bool
|
2015-01-11 22:56:17 -05:00
|
|
|
eventBox *util.EventBox
|
2015-06-08 02:36:21 -04:00
|
|
|
delimNil bool
|
2015-01-01 14:49:30 -05:00
|
|
|
}
|
|
|
|
|
2015-01-11 13:01:24 -05:00
|
|
|
// ReadSource reads data from the default command or from standard input
|
2015-01-01 14:49:30 -05:00
|
|
|
func (r *Reader) ReadSource() {
|
2015-01-11 22:56:17 -05:00
|
|
|
if util.IsTty() {
|
2015-01-01 14:49:30 -05:00
|
|
|
cmd := os.Getenv("FZF_DEFAULT_COMMAND")
|
|
|
|
if len(cmd) == 0 {
|
2015-01-11 13:01:24 -05:00
|
|
|
cmd = defaultCommand
|
2015-01-01 14:49:30 -05:00
|
|
|
}
|
|
|
|
r.readFromCommand(cmd)
|
|
|
|
} else {
|
|
|
|
r.readFromStdin()
|
|
|
|
}
|
2015-01-11 13:01:24 -05:00
|
|
|
r.eventBox.Set(EvtReadFin, nil)
|
2015-01-01 14:49:30 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Reader) feed(src io.Reader) {
|
2015-06-08 02:36:21 -04:00
|
|
|
delim := byte('\n')
|
|
|
|
if r.delimNil {
|
|
|
|
delim = '\000'
|
|
|
|
}
|
2016-08-15 12:52:24 -04:00
|
|
|
reader := bufio.NewReaderSize(src, readerBufferSize)
|
2015-06-08 02:36:21 -04:00
|
|
|
for {
|
2015-08-02 01:00:18 -04:00
|
|
|
// ReadBytes returns err != nil if and only if the returned data does not
|
|
|
|
// end in delim.
|
|
|
|
bytea, err := reader.ReadBytes(delim)
|
2016-10-23 23:45:45 -04:00
|
|
|
byteaLen := len(bytea)
|
2015-08-02 01:00:18 -04:00
|
|
|
if len(bytea) > 0 {
|
2015-06-08 02:36:21 -04:00
|
|
|
if err == nil {
|
2016-10-23 23:45:45 -04:00
|
|
|
// get rid of carriage return if under Windows:
|
2016-11-06 12:15:34 -05:00
|
|
|
if util.IsWindows() && byteaLen >= 2 && bytea[byteaLen-2] == byte('\r') {
|
2016-10-23 23:45:45 -04:00
|
|
|
bytea = bytea[:byteaLen-2]
|
|
|
|
} else {
|
|
|
|
bytea = bytea[:byteaLen-1]
|
|
|
|
}
|
2015-06-02 12:48:02 -04:00
|
|
|
}
|
2015-08-02 01:25:57 -04:00
|
|
|
if r.pusher(bytea) {
|
2015-07-21 14:21:20 -04:00
|
|
|
r.eventBox.Set(EvtReadNew, nil)
|
|
|
|
}
|
2015-01-01 14:49:30 -05:00
|
|
|
}
|
2015-06-08 02:36:21 -04:00
|
|
|
if err != nil {
|
|
|
|
break
|
|
|
|
}
|
2015-01-01 14:49:30 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Reader) readFromStdin() {
|
|
|
|
r.feed(os.Stdin)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Reader) readFromCommand(cmd string) {
|
2016-02-06 11:49:29 -05:00
|
|
|
listCommand := util.ExecCommand(cmd)
|
2015-01-01 14:49:30 -05:00
|
|
|
out, err := listCommand.StdoutPipe()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
err = listCommand.Start()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer listCommand.Wait()
|
|
|
|
r.feed(out)
|
|
|
|
}
|