Skip to content
Myr

reader.go

This file

Path

src/reader.go

278 lines · 6.1 KiB · Go

Last changed by

Refactor the code to remove global variablesJunegunn Choibefore adoption4bedd33

History of this file

Take it

1package fzf23import (4	"bytes"5	"context"6	"io"7	"os"8	"os/exec"9	"path/filepath"10	"sync"11	"sync/atomic"12	"time"1314	"github.com/charlievieth/fastwalk"15	"github.com/junegunn/fzf/src/util"16)1718// Reader reads from command or standard input19type Reader struct {20	pusher   func([]byte) bool21	executor *util.Executor22	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, executor *util.Executor, delimNil bool, wait bool) *Reader {35	return &Reader{pusher, executor, 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	r.killed = true81	if r.exec != nil && r.exec.Process != nil {82		util.KillCommand(r.exec)83	} else {84		os.Stdin.Close()85	}86	r.mutex.Unlock()87}8889func (r *Reader) restart(command commandSpec, environ []string) {90	r.event = int32(EvtReady)91	r.startEventPoller()92	success := r.readFromCommand(command.command, environ)93	r.fin(success)94	removeFiles(command.tempFiles)95}9697func (r *Reader) readChannel(inputChan chan string) bool {98	for {99		item, more := <-inputChan100		if !more {101			break102		}103		if r.pusher([]byte(item)) {104			atomic.StoreInt32(&r.event, int32(EvtReadNew))105		}106	}107	return true108}109110// ReadSource reads data from the default command or from standard input111func (r *Reader) ReadSource(inputChan chan string, root string, opts walkerOpts, ignores []string) {112	r.startEventPoller()113	var success bool114	if inputChan != nil {115		success = r.readChannel(inputChan)116	} else if util.IsTty() {117		cmd := os.Getenv("FZF_DEFAULT_COMMAND")118		if len(cmd) == 0 {119			success = r.readFiles(root, opts, ignores)120		} else {121			// We can't export FZF_* environment variables to the default command122			success = r.readFromCommand(cmd, nil)123		}124	} else {125		success = r.readFromStdin()126	}127	r.fin(success)128}129130func (r *Reader) feed(src io.Reader) {131	/*132		readerSlabSize, ae := strconv.Atoi(os.Getenv("SLAB_KB"))133		if ae != nil {134			readerSlabSize = 128 * 1024135		} else {136			readerSlabSize *= 1024137		}138		readerBufferSize, be := strconv.Atoi(os.Getenv("BUF_KB"))139		if be != nil {140			readerBufferSize = 64 * 1024141		} else {142			readerBufferSize *= 1024143		}144	*/145146	delim := byte('\n')147	trimCR := util.IsWindows()148	if r.delimNil {149		delim = '\000'150		trimCR = false151	}152153	slab := make([]byte, readerSlabSize)154	leftover := []byte{}155	var err error156	for {157		n := 0158		scope := slab[:util.Min(len(slab), readerBufferSize)]159		for i := 0; i < 100; i++ {160			n, err = src.Read(scope)161			if n > 0 || err != nil {162				break163			}164		}165166		// We're not making any progress after 100 tries. Stop.167		if n == 0 {168			break169		}170171		buf := slab[:n]172		slab = slab[n:]173174		for len(buf) > 0 {175			if i := bytes.IndexByte(buf, delim); i >= 0 {176				// Found the delimiter177				slice := buf[:i+1]178				buf = buf[i+1:]179				if trimCR && len(slice) >= 2 && slice[len(slice)-2] == byte('\r') {180					slice = slice[:len(slice)-2]181				} else {182					slice = slice[:len(slice)-1]183				}184				if len(leftover) > 0 {185					slice = append(leftover, slice...)186					leftover = []byte{}187				}188				if (err == nil || len(slice) > 0) && r.pusher(slice) {189					atomic.StoreInt32(&r.event, int32(EvtReadNew))190				}191			} else {192				// Could not find the delimiter in the buffer193				//   NOTE: We can further optimize this by keeping track of the cursor194				//   position in the slab so that a straddling item that doesn't go195				//   beyond the boundary of a slab doesn't need to be copied to196				//   another buffer. However, the performance gain is negligible in197				//   practice (< 0.1%) and is not198				//   worth the added complexity.199				leftover = append(leftover, buf...)200				break201			}202		}203204		if err == io.EOF {205			leftover = append(leftover, buf...)206			break207		}208209		if len(slab) == 0 {210			slab = make([]byte, readerSlabSize)211		}212	}213	if len(leftover) > 0 && r.pusher(leftover) {214		atomic.StoreInt32(&r.event, int32(EvtReadNew))215	}216}217218func (r *Reader) readFromStdin() bool {219	r.feed(os.Stdin)220	return true221}222223func (r *Reader) readFiles(root string, opts walkerOpts, ignores []string) bool {224	r.killed = false225	conf := fastwalk.Config{Follow: opts.follow}226	fn := func(path string, de os.DirEntry, err error) error {227		if err != nil {228			return nil229		}230		path = filepath.Clean(path)231		if path != "." {232			isDir := de.IsDir()233			if isDir {234				base := filepath.Base(path)235				if !opts.hidden && base[0] == '.' {236					return filepath.SkipDir237				}238				for _, ignore := range ignores {239					if ignore == base {240						return filepath.SkipDir241					}242				}243			}244			if ((opts.file && !isDir) || (opts.dir && isDir)) && r.pusher([]byte(path)) {245				atomic.StoreInt32(&r.event, int32(EvtReadNew))246			}247		}248		r.mutex.Lock()249		defer r.mutex.Unlock()250		if r.killed {251			return context.Canceled252		}253		return nil254	}255	return fastwalk.Walk(&conf, root, fn) == nil256}257258func (r *Reader) readFromCommand(command string, environ []string) bool {259	r.mutex.Lock()260	r.killed = false261	r.command = &command262	r.exec = r.executor.ExecCommand(command, true)263	if environ != nil {264		r.exec.Env = environ265	}266	out, err := r.exec.StdoutPipe()267	if err != nil {268		r.mutex.Unlock()269		return false270	}271	err = r.exec.Start()272	r.mutex.Unlock()273	if err != nil {274		return false275	}276	r.feed(out)277	return r.exec.Wait() == nil278}