Skip to content
Myr

reader.go

This file

Path

src/reader.go

376 lines · 8.1 KiB · Go

Last changed by

chore: remove redundant word in comment (#4490)longhutianjiebefore adoption978b625

History of this file

Take it

1package fzf23import (4	"bytes"5	"context"6	"io"7	"io/fs"8	"os"9	"path/filepath"10	"strings"11	"sync"12	"sync/atomic"13	"time"1415	"github.com/charlievieth/fastwalk"16	"github.com/junegunn/fzf/src/util"17)1819// Reader reads from command or standard input20type Reader struct {21	pusher   func([]byte) bool22	executor *util.Executor23	eventBox *util.EventBox24	delimNil bool25	event    int3226	finChan  chan bool27	mutex    sync.Mutex28	killed   bool29	termFunc func()30	command  *string31	wait     bool32}3334// NewReader returns new Reader object35func NewReader(pusher func([]byte) bool, eventBox *util.EventBox, executor *util.Executor, delimNil bool, wait bool) *Reader {36	return &Reader{37		pusher,38		executor,39		eventBox,40		delimNil,41		int32(EvtReady),42		make(chan bool, 1),43		sync.Mutex{},44		false,45		func() { os.Stdin.Close() },46		nil,47		wait}48}4950func (r *Reader) startEventPoller() {51	go func() {52		ptr := &r.event53		pollInterval := readerPollIntervalMin54		for {55			if atomic.CompareAndSwapInt32(ptr, int32(EvtReadNew), int32(EvtReady)) {56				r.eventBox.Set(EvtReadNew, (*string)(nil))57				pollInterval = readerPollIntervalMin58			} else if atomic.LoadInt32(ptr) == int32(EvtReadFin) {59				if r.wait {60					r.finChan <- true61				}62				return63			} else {64				pollInterval += readerPollIntervalStep65				if pollInterval > readerPollIntervalMax {66					pollInterval = readerPollIntervalMax67				}68			}69			time.Sleep(pollInterval)70		}71	}()72}7374func (r *Reader) fin(success bool) {75	atomic.StoreInt32(&r.event, int32(EvtReadFin))76	if r.wait {77		<-r.finChan78	}7980	r.mutex.Lock()81	ret := r.command82	if success || r.killed {83		ret = nil84	}85	r.mutex.Unlock()8687	r.eventBox.Set(EvtReadFin, ret)88}8990func (r *Reader) terminate() {91	r.mutex.Lock()92	r.killed = true93	if r.termFunc != nil {94		r.termFunc()95		r.termFunc = nil96	}97	r.mutex.Unlock()98}99100func (r *Reader) restart(command commandSpec, environ []string, readyChan chan bool) {101	r.event = int32(EvtReady)102	r.startEventPoller()103	success := r.readFromCommand(command.command, environ, func() {104		readyChan <- true105	})106	r.fin(success)107	removeFiles(command.tempFiles)108}109110func (r *Reader) readChannel(inputChan chan string) bool {111	for {112		item, more := <-inputChan113		if !more {114			break115		}116		if r.pusher([]byte(item)) {117			atomic.StoreInt32(&r.event, int32(EvtReadNew))118		}119	}120	return true121}122123// ReadSource reads data from the default command or from standard input124func (r *Reader) ReadSource(inputChan chan string, roots []string, opts walkerOpts, ignores []string, initCmd string, initEnv []string, readyChan chan bool) {125	r.startEventPoller()126	var success bool127	signalReady := func() {128		if readyChan != nil {129			readyChan <- true130		}131	}132	if inputChan != nil {133		signalReady()134		success = r.readChannel(inputChan)135	} else if len(initCmd) > 0 {136		success = r.readFromCommand(initCmd, initEnv, signalReady)137	} else if util.IsTty(os.Stdin) {138		cmd := os.Getenv("FZF_DEFAULT_COMMAND")139		if len(cmd) == 0 {140			signalReady()141			success = r.readFiles(roots, opts, ignores)142		} else {143			success = r.readFromCommand(cmd, initEnv, signalReady)144		}145	} else {146		signalReady()147		success = r.readFromStdin()148	}149	r.fin(success)150}151152func (r *Reader) feed(src io.Reader) {153	/*154		readerSlabSize, ae := strconv.Atoi(os.Getenv("SLAB_KB"))155		if ae != nil {156			readerSlabSize = 128 * 1024157		} else {158			readerSlabSize *= 1024159		}160		readerBufferSize, be := strconv.Atoi(os.Getenv("BUF_KB"))161		if be != nil {162			readerBufferSize = 64 * 1024163		} else {164			readerBufferSize *= 1024165		}166	*/167168	delim := byte('\n')169	trimCR := util.IsWindows()170	if r.delimNil {171		delim = '\000'172		trimCR = false173	}174175	slab := make([]byte, readerSlabSize)176	leftover := []byte{}177	var err error178	for {179		n := 0180		scope := slab[:util.Min(len(slab), readerBufferSize)]181		for i := 0; i < 100; i++ {182			n, err = src.Read(scope)183			if n > 0 || err != nil {184				break185			}186		}187188		// We're not making any progress after 100 tries. Stop.189		if n == 0 {190			break191		}192193		buf := slab[:n]194		slab = slab[n:]195196		for len(buf) > 0 {197			if i := bytes.IndexByte(buf, delim); i >= 0 {198				// Found the delimiter199				slice := buf[:i+1]200				buf = buf[i+1:]201				if trimCR && len(slice) >= 2 && slice[len(slice)-2] == byte('\r') {202					slice = slice[:len(slice)-2]203				} else {204					slice = slice[:len(slice)-1]205				}206				if len(leftover) > 0 {207					slice = append(leftover, slice...)208					leftover = []byte{}209				}210				if (err == nil || len(slice) > 0) && r.pusher(slice) {211					atomic.StoreInt32(&r.event, int32(EvtReadNew))212				}213			} else {214				// Could not find the delimiter in the buffer215				//   NOTE: We can further optimize this by keeping track of the cursor216				//   position in the slab so that a straddling item that doesn't go217				//   beyond the boundary of a slab doesn't need to be copied to218				//   another buffer. However, the performance gain is negligible in219				//   practice (< 0.1%) and is not220				//   worth the added complexity.221				leftover = append(leftover, buf...)222				break223			}224		}225226		if err == io.EOF {227			leftover = append(leftover, buf...)228			break229		}230231		if len(slab) == 0 {232			slab = make([]byte, readerSlabSize)233		}234	}235	if len(leftover) > 0 && r.pusher(leftover) {236		atomic.StoreInt32(&r.event, int32(EvtReadNew))237	}238}239240func (r *Reader) readFromStdin() bool {241	r.feed(os.Stdin)242	return true243}244245func isSymlinkToDir(path string, de os.DirEntry) bool {246	if de.Type()&fs.ModeSymlink == 0 {247		return false248	}249	if s, err := os.Stat(path); err == nil {250		return s.IsDir()251	}252	return false253}254255func trimPath(path string) string {256	bytes := stringBytes(path)257258	for len(bytes) > 1 && bytes[0] == '.' && (bytes[1] == '/' || bytes[1] == '\\') {259		bytes = bytes[2:]260	}261262	if len(bytes) == 0 {263		return "."264	}265266	return byteString(bytes)267}268269func (r *Reader) readFiles(roots []string, opts walkerOpts, ignores []string) bool {270	conf := fastwalk.Config{271		Follow: opts.follow,272		// Use forward slashes when running a Windows binary under WSL or MSYS273		ToSlash: fastwalk.DefaultToSlash(),274		Sort:    fastwalk.SortFilesFirst,275	}276	ignoresBase := []string{}277	ignoresFull := []string{}278	ignoresSuffix := []string{}279	sep := string(os.PathSeparator)280	if _, ok := os.LookupEnv("MSYSTEM"); ok {281		sep = "/"282	}283	for _, ignore := range ignores {284		if strings.ContainsRune(ignore, os.PathSeparator) {285			if strings.HasPrefix(ignore, sep) {286				ignoresSuffix = append(ignoresSuffix, ignore)287			} else {288				// 'foo/bar' should match289				// * 'foo/bar'290				// * 'baz/foo/bar'291				// * but NOT 'bazfoo/bar'292				ignoresFull = append(ignoresFull, ignore)293				ignoresSuffix = append(ignoresSuffix, sep+ignore)294			}295		} else {296			ignoresBase = append(ignoresBase, ignore)297		}298	}299	fn := func(path string, de os.DirEntry, err error) error {300		if err != nil {301			return nil302		}303		path = trimPath(path)304		if path != "." {305			isDir := de.IsDir()306			if isDir || opts.follow && isSymlinkToDir(path, de) {307				base := filepath.Base(path)308				if !opts.hidden && base[0] == '.' && base != ".." {309					return filepath.SkipDir310				}311				for _, ignore := range ignoresBase {312					if ignore == base {313						return filepath.SkipDir314					}315				}316				for _, ignore := range ignoresFull {317					if ignore == path {318						return filepath.SkipDir319					}320				}321				for _, ignore := range ignoresSuffix {322					if strings.HasSuffix(path, ignore) {323						return filepath.SkipDir324					}325				}326				if path != sep {327					path += sep328				}329			}330			if ((opts.file && !isDir) || (opts.dir && isDir)) && r.pusher(stringBytes(path)) {331				atomic.StoreInt32(&r.event, int32(EvtReadNew))332			}333		}334		r.mutex.Lock()335		defer r.mutex.Unlock()336		if r.killed {337			return context.Canceled338		}339		return nil340	}341	noerr := true342	for _, root := range roots {343		noerr = noerr && (fastwalk.Walk(&conf, root, fn) == nil)344	}345	return noerr346}347348func (r *Reader) readFromCommand(command string, environ []string, signalReady func()) bool {349	r.mutex.Lock()350351	r.killed = false352	r.termFunc = nil353	r.command = &command354	exec := r.executor.ExecCommand(command, true)355	if environ != nil {356		exec.Env = environ357	}358	execOut, err := exec.StdoutPipe()359	if err != nil || exec.Start() != nil {360		signalReady()361		r.mutex.Unlock()362		return false363	}364365	// Function to call to terminate the running command366	r.termFunc = func() {367		execOut.Close()368		util.KillCommand(exec)369	}370371	signalReady()372	r.mutex.Unlock()373374	r.feed(execOut)375	return exec.Wait() == nil376}