2015-01-02 04:49:30 +09:00
|
|
|
package fzf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
2015-01-12 12:56:17 +09:00
|
|
|
|
|
|
|
"github.com/junegunn/fzf/src/util"
|
2015-01-02 04:49:30 +09:00
|
|
|
)
|
|
|
|
|
2015-01-12 03:01:24 +09:00
|
|
|
// Reader reads from command or standard input
|
2015-01-02 04:49:30 +09:00
|
|
|
type Reader struct {
|
|
|
|
pusher func(string)
|
2015-01-12 12:56:17 +09:00
|
|
|
eventBox *util.EventBox
|
2015-01-02 04:49:30 +09:00
|
|
|
}
|
|
|
|
|
2015-01-12 03:01:24 +09:00
|
|
|
// ReadSource reads data from the default command or from standard input
|
2015-01-02 04:49:30 +09:00
|
|
|
func (r *Reader) ReadSource() {
|
2015-01-12 12:56:17 +09:00
|
|
|
if util.IsTty() {
|
2015-01-02 04:49:30 +09:00
|
|
|
cmd := os.Getenv("FZF_DEFAULT_COMMAND")
|
|
|
|
if len(cmd) == 0 {
|
2015-01-12 03:01:24 +09:00
|
|
|
cmd = defaultCommand
|
2015-01-02 04:49:30 +09:00
|
|
|
}
|
|
|
|
r.readFromCommand(cmd)
|
|
|
|
} else {
|
|
|
|
r.readFromStdin()
|
|
|
|
}
|
2015-01-12 03:01:24 +09:00
|
|
|
r.eventBox.Set(EvtReadFin, nil)
|
2015-01-02 04:49:30 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Reader) feed(src io.Reader) {
|
2015-06-03 01:48:02 +09:00
|
|
|
reader := bufio.NewReader(src)
|
|
|
|
eof := false
|
|
|
|
Loop:
|
|
|
|
for !eof {
|
|
|
|
buf := []byte{}
|
|
|
|
iter := 0 // TODO: max size?
|
|
|
|
for {
|
|
|
|
// "ReadLine either returns a non-nil line or it returns an error, never both"
|
|
|
|
line, isPrefix, err := reader.ReadLine()
|
|
|
|
eof = err == io.EOF
|
|
|
|
if eof {
|
|
|
|
break
|
|
|
|
} else if err != nil {
|
|
|
|
break Loop
|
|
|
|
}
|
|
|
|
iter++
|
|
|
|
buf = append(buf, line...)
|
|
|
|
if !isPrefix {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if iter > 0 {
|
|
|
|
r.pusher(string(buf))
|
2015-01-12 03:01:24 +09:00
|
|
|
r.eventBox.Set(EvtReadNew, nil)
|
2015-01-02 04:49:30 +09:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Reader) readFromStdin() {
|
|
|
|
r.feed(os.Stdin)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *Reader) readFromCommand(cmd string) {
|
2015-01-07 02:24:13 +09:00
|
|
|
listCommand := exec.Command("sh", "-c", cmd)
|
2015-01-02 04:49:30 +09:00
|
|
|
out, err := listCommand.StdoutPipe()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
err = listCommand.Start()
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer listCommand.Wait()
|
|
|
|
r.feed(out)
|
|
|
|
}
|