fzf/src/reader.go

72 lines
1.3 KiB
Go
Raw Normal View History

2015-01-01 14:49:30 -05:00
package fzf
import (
"bufio"
"io"
"os"
"os/exec"
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 {
pusher func(string)
2015-01-11 22:56:17 -05:00
eventBox *util.EventBox
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) {
delim := byte('\n')
if r.delimNil {
delim = '\000'
}
reader := bufio.NewReader(src)
for {
line, err := reader.ReadString(delim)
if line != "" {
// "ReadString returns err != nil if and only if the returned data does not end in delim."
if err == nil {
line = line[:len(line)-1]
}
r.pusher(line)
2015-01-11 13:01:24 -05:00
r.eventBox.Set(EvtReadNew, nil)
2015-01-01 14:49:30 -05: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) {
2015-01-06 12:24:13 -05:00
listCommand := exec.Command("sh", "-c", 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)
}