You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
fzf/src/reader.go

81 lines
1.6 KiB
Go

10 years ago
package fzf
import (
"bufio"
"io"
"os"
"github.com/junegunn/fzf/src/util"
10 years ago
)
10 years ago
// Reader reads from command or standard input
10 years ago
type Reader struct {
pusher func([]byte) bool
eventBox *util.EventBox
delimNil bool
10 years ago
}
10 years ago
// ReadSource reads data from the default command or from standard input
10 years ago
func (r *Reader) ReadSource() {
var success bool
if util.IsTty() {
10 years ago
cmd := os.Getenv("FZF_DEFAULT_COMMAND")
if len(cmd) == 0 {
10 years ago
cmd = defaultCommand
10 years ago
}
success = r.readFromCommand(cmd)
10 years ago
} else {
success = r.readFromStdin()
10 years ago
}
r.eventBox.Set(EvtReadFin, success)
10 years ago
}
func (r *Reader) feed(src io.Reader) {
delim := byte('\n')
if r.delimNil {
delim = '\000'
}
reader := bufio.NewReaderSize(src, readerBufferSize)
for {
// ReadBytes returns err != nil if and only if the returned data does not
// end in delim.
bytea, err := reader.ReadBytes(delim)
byteaLen := len(bytea)
if len(bytea) > 0 {
if err == nil {
// get rid of carriage return if under Windows:
if util.IsWindows() && byteaLen >= 2 && bytea[byteaLen-2] == byte('\r') {
bytea = bytea[:byteaLen-2]
} else {
bytea = bytea[:byteaLen-1]
}
}
if r.pusher(bytea) {
r.eventBox.Set(EvtReadNew, true)
}
10 years ago
}
if err != nil {
break
}
10 years ago
}
}
func (r *Reader) readFromStdin() bool {
10 years ago
r.feed(os.Stdin)
return true
10 years ago
}
func (r *Reader) readFromCommand(cmd string) bool {
listCommand := util.ExecCommand(cmd)
10 years ago
out, err := listCommand.StdoutPipe()
if err != nil {
return false
10 years ago
}
err = listCommand.Start()
if err != nil {
return false
10 years ago
}
r.feed(out)
return listCommand.Wait() == nil
10 years ago
}