reader.go
This file
Path
src/reader.go
211 lines · 4.5 KiB · Go
Last changed by
Use $SHELL instead of bash if it's known to support 'pipefail'Junegunn Choibefore adoption547e101
History of this fileTake it
1package fzf23import (4 "bufio"5 "context"6 "io"7 "os"8 "os/exec"9 "path"10 "path/filepath"11 "sync"12 "sync/atomic"13 "time"1415 "github.com/junegunn/fzf/src/util"16 "github.com/saracen/walker"17)1819// Reader reads from command or standard input20type Reader struct {21 pusher func([]byte) bool22 eventBox *util.EventBox23 delimNil bool24 event int3225 finChan chan bool26 mutex sync.Mutex27 exec *exec.Cmd28 command *string29 killed bool30 wait bool31}3233// NewReader returns new Reader object34func NewReader(pusher func([]byte) bool, eventBox *util.EventBox, delimNil bool, wait bool) *Reader {35 return &Reader{pusher, eventBox, delimNil, int32(EvtReady), make(chan bool, 1), sync.Mutex{}, nil, nil, false, wait}36}3738func (r *Reader) startEventPoller() {39 go func() {40 ptr := &r.event41 pollInterval := readerPollIntervalMin42 for {43 if atomic.CompareAndSwapInt32(ptr, int32(EvtReadNew), int32(EvtReady)) {44 r.eventBox.Set(EvtReadNew, (*string)(nil))45 pollInterval = readerPollIntervalMin46 } else if atomic.LoadInt32(ptr) == int32(EvtReadFin) {47 if r.wait {48 r.finChan <- true49 }50 return51 } else {52 pollInterval += readerPollIntervalStep53 if pollInterval > readerPollIntervalMax {54 pollInterval = readerPollIntervalMax55 }56 }57 time.Sleep(pollInterval)58 }59 }()60}6162func (r *Reader) fin(success bool) {63 atomic.StoreInt32(&r.event, int32(EvtReadFin))64 if r.wait {65 <-r.finChan66 }6768 r.mutex.Lock()69 ret := r.command70 if success || r.killed {71 ret = nil72 }73 r.mutex.Unlock()7475 r.eventBox.Set(EvtReadFin, ret)76}7778func (r *Reader) terminate() {79 r.mutex.Lock()80 defer func() { r.mutex.Unlock() }()8182 r.killed = true83 if r.exec != nil && r.exec.Process != nil {84 util.KillCommand(r.exec)85 } else if defaultCommand != "" {86 os.Stdin.Close()87 }88}8990func (r *Reader) restart(command string) {91 r.event = int32(EvtReady)92 r.startEventPoller()93 success := r.readFromCommand(nil, command)94 r.fin(success)95}9697// ReadSource reads data from the default command or from standard input98func (r *Reader) ReadSource() {99 r.startEventPoller()100 var success bool101 if util.IsTty() {102 // The default command for *nix requires a shell that supports "pipefail"103 // https://unix.stackexchange.com/a/654932/62171104 shell := "bash"105 currentShell := os.Getenv("SHELL")106 currentShellName := path.Base(currentShell)107 for _, shellName := range []string{"bash", "zsh", "ksh", "ash", "hush", "mksh", "yash"} {108 if currentShellName == shellName {109 shell = currentShell110 break111 }112 }113 cmd := os.Getenv("FZF_DEFAULT_COMMAND")114 if len(cmd) == 0 {115 if defaultCommand != "" {116 success = r.readFromCommand(&shell, defaultCommand)117 } else {118 success = r.readFiles()119 }120 } else {121 success = r.readFromCommand(nil, cmd)122 }123 } else {124 success = r.readFromStdin()125 }126 r.fin(success)127}128129func (r *Reader) feed(src io.Reader) {130 delim := byte('\n')131 if r.delimNil {132 delim = '\000'133 }134 reader := bufio.NewReaderSize(src, readerBufferSize)135 for {136 // ReadBytes returns err != nil if and only if the returned data does not137 // end in delim.138 bytea, err := reader.ReadBytes(delim)139 byteaLen := len(bytea)140 if byteaLen > 0 {141 if err == nil {142 // get rid of carriage return if under Windows:143 if util.IsWindows() && byteaLen >= 2 && bytea[byteaLen-2] == byte('\r') {144 bytea = bytea[:byteaLen-2]145 } else {146 bytea = bytea[:byteaLen-1]147 }148 }149 if r.pusher(bytea) {150 atomic.StoreInt32(&r.event, int32(EvtReadNew))151 }152 }153 if err != nil {154 break155 }156 }157}158159func (r *Reader) readFromStdin() bool {160 r.feed(os.Stdin)161 return true162}163164func (r *Reader) readFiles() bool {165 r.killed = false166 fn := func(path string, mode os.FileInfo) error {167 path = filepath.Clean(path)168 if path != "." {169 isDir := mode.Mode().IsDir()170 if isDir && filepath.Base(path)[0] == '.' {171 return filepath.SkipDir172 }173 if !isDir && r.pusher([]byte(path)) {174 atomic.StoreInt32(&r.event, int32(EvtReadNew))175 }176 }177 r.mutex.Lock()178 defer r.mutex.Unlock()179 if r.killed {180 return context.Canceled181 }182 return nil183 }184 cb := walker.WithErrorCallback(func(pathname string, err error) error {185 return nil186 })187 return walker.Walk(".", fn, cb) == nil188}189190func (r *Reader) readFromCommand(shell *string, command string) bool {191 r.mutex.Lock()192 r.killed = false193 r.command = &command194 if shell != nil {195 r.exec = util.ExecCommandWith(*shell, command, true)196 } else {197 r.exec = util.ExecCommand(command, true)198 }199 out, err := r.exec.StdoutPipe()200 if err != nil {201 r.mutex.Unlock()202 return false203 }204 err = r.exec.Start()205 r.mutex.Unlock()206 if err != nil {207 return false208 }209 r.feed(out)210 return r.exec.Wait() == nil211}