fzf/src/reader.go

61 lines
1.1 KiB
Go
Raw Normal View History

2015-01-01 19:49:30 +00:00
package fzf
// #include <unistd.h>
import "C"
import (
"bufio"
"io"
"os"
"os/exec"
)
2015-01-11 18:01:24 +00:00
const defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`
2015-01-01 19:49:30 +00:00
2015-01-11 18:01:24 +00:00
// Reader reads from command or standard input
2015-01-01 19:49:30 +00:00
type Reader struct {
pusher func(string)
eventBox *EventBox
}
2015-01-11 18:01:24 +00:00
// ReadSource reads data from the default command or from standard input
2015-01-01 19:49:30 +00:00
func (r *Reader) ReadSource() {
if int(C.isatty(C.int(os.Stdin.Fd()))) != 0 {
cmd := os.Getenv("FZF_DEFAULT_COMMAND")
if len(cmd) == 0 {
2015-01-11 18:01:24 +00:00
cmd = defaultCommand
2015-01-01 19:49:30 +00:00
}
r.readFromCommand(cmd)
} else {
r.readFromStdin()
}
2015-01-11 18:01:24 +00:00
r.eventBox.Set(EvtReadFin, nil)
2015-01-01 19:49:30 +00:00
}
func (r *Reader) feed(src io.Reader) {
if scanner := bufio.NewScanner(src); scanner != nil {
for scanner.Scan() {
r.pusher(scanner.Text())
2015-01-11 18:01:24 +00:00
r.eventBox.Set(EvtReadNew, nil)
2015-01-01 19:49:30 +00:00
}
}
}
func (r *Reader) readFromStdin() {
r.feed(os.Stdin)
}
func (r *Reader) readFromCommand(cmd string) {
2015-01-06 17:24:13 +00:00
listCommand := exec.Command("sh", "-c", cmd)
2015-01-01 19:49:30 +00:00
out, err := listCommand.StdoutPipe()
if err != nil {
return
}
err = listCommand.Start()
if err != nil {
return
}
defer listCommand.Wait()
r.feed(out)
}