Skip to content
Myr

reader.go

This file

Path

src/reader.go

413 lines · 9.5 KiB · Go

Last changed by

Not known.

History of this file

Take it

1package fzf23import (4	"bytes"5	"context"6	"io"7	"io/fs"8	"os"9	"path/filepath"10	"slices"11	"strings"12	"sync"13	"sync/atomic"14	"time"1516	"github.com/charlievieth/fastwalk"17	"github.com/junegunn/fzf/src/util"18)1920// Reader reads from command or standard input21type Reader struct {22	pusher   func([]byte) bool23	executor *util.Executor24	eventBox *util.EventBox25	delimNil bool26	event    int3227	finChan  chan bool28	mutex    sync.Mutex29	killed   bool30	termFunc func()31	command  *string32	wait     bool33}3435// NewReader returns new Reader object36func NewReader(pusher func([]byte) bool, eventBox *util.EventBox, executor *util.Executor, delimNil bool, wait bool) *Reader {37	return &Reader{38		pusher,39		executor,40		eventBox,41		delimNil,42		int32(EvtReady),43		make(chan bool, 1),44		sync.Mutex{},45		false,46		func() { os.Stdin.Close() },47		nil,48		wait}49}5051func (r *Reader) startEventPoller() {52	go func() {53		ptr := &r.event54		pollInterval := readerPollIntervalMin55		for {56			if atomic.CompareAndSwapInt32(ptr, int32(EvtReadNew), int32(EvtReady)) {57				r.eventBox.Set(EvtReadNew, (*string)(nil))58				pollInterval = readerPollIntervalMin59			} else if atomic.LoadInt32(ptr) == int32(EvtReadFin) {60				if r.wait {61					r.finChan <- true62				}63				return64			} else {65				pollInterval += readerPollIntervalStep66				if pollInterval > readerPollIntervalMax {67					pollInterval = readerPollIntervalMax68				}69			}70			time.Sleep(pollInterval)71		}72	}()73}7475func (r *Reader) fin(success bool) {76	atomic.StoreInt32(&r.event, int32(EvtReadFin))77	if r.wait {78		<-r.finChan79	}8081	r.mutex.Lock()82	ret := r.command83	if success || r.killed {84		ret = nil85	}86	r.mutex.Unlock()8788	r.eventBox.Set(EvtReadFin, ret)89}9091func (r *Reader) terminate() {92	r.mutex.Lock()93	r.killed = true94	if r.termFunc != nil {95		r.termFunc()96		r.termFunc = nil97	}98	r.mutex.Unlock()99}100101func (r *Reader) restart(command commandSpec, environ []string, readyChan chan bool) {102	r.event = int32(EvtReady)103	r.startEventPoller()104	success := r.readFromCommand(command.command, environ, func() {105		readyChan <- true106	})107	r.fin(success)108	removeFiles(command.tempFiles)109}110111func (r *Reader) readChannel(inputChan chan string) bool {112	for {113		item, more := <-inputChan114		if !more {115			break116		}117		if r.pusher([]byte(item)) {118			atomic.StoreInt32(&r.event, int32(EvtReadNew))119		}120	}121	return true122}123124// ReadSource reads data from the default command or from standard input125func (r *Reader) ReadSource(inputChan chan string, roots []string, opts walkerOpts, ignores []string, initCmd string, initEnv []string, readyChan chan bool) {126	r.startEventPoller()127	var success bool128	signalReady := func() {129		if readyChan != nil {130			readyChan <- true131		}132	}133	if inputChan != nil {134		signalReady()135		success = r.readChannel(inputChan)136	} else if len(initCmd) > 0 {137		success = r.readFromCommand(initCmd, initEnv, signalReady)138	} else if util.IsTty(os.Stdin) {139		cmd := os.Getenv("FZF_DEFAULT_COMMAND")140		if len(cmd) == 0 {141			signalReady()142			success = r.readFiles(roots, opts, ignores)143		} else {144			success = r.readFromCommand(cmd, initEnv, signalReady)145		}146	} else {147		signalReady()148		success = r.readFromStdin()149	}150	r.fin(success)151}152153func (r *Reader) feed(src io.Reader) {154	/*155		readerSlabSize, ae := strconv.Atoi(os.Getenv("SLAB_KB"))156		if ae != nil {157			readerSlabSize = 128 * 1024158		} else {159			readerSlabSize *= 1024160		}161		readerBufferSize, be := strconv.Atoi(os.Getenv("BUF_KB"))162		if be != nil {163			readerBufferSize = 64 * 1024164		} else {165			readerBufferSize *= 1024166		}167	*/168169	delim := byte('\n')170	trimCR := util.IsWindows()171	if r.delimNil {172		delim = '\000'173		trimCR = false174	}175176	slab := make([]byte, readerSlabSize)177	leftover := []byte{}178	var err error179	for {180		n := 0181		scope := slab[:min(len(slab), readerBufferSize)]182		for range 100 {183			n, err = src.Read(scope)184			if n > 0 || err != nil {185				break186			}187		}188189		// We're not making any progress after 100 tries. Stop.190		if n == 0 {191			break192		}193194		buf := slab[:n]195		slab = slab[n:]196197		for len(buf) > 0 {198			if i := bytes.IndexByte(buf, delim); i >= 0 {199				// Found the delimiter200				slice := buf[:i+1]201				buf = buf[i+1:]202				if trimCR && len(slice) >= 2 && slice[len(slice)-2] == byte('\r') {203					slice = slice[:len(slice)-2]204				} else {205					slice = slice[:len(slice)-1]206				}207				if len(leftover) > 0 {208					slice = append(leftover, slice...)209					leftover = []byte{}210				}211				if (err == nil || len(slice) > 0) && r.pusher(slice) {212					atomic.StoreInt32(&r.event, int32(EvtReadNew))213				}214			} else {215				// Could not find the delimiter in the buffer216				//   NOTE: We can further optimize this by keeping track of the cursor217				//   position in the slab so that a straddling item that doesn't go218				//   beyond the boundary of a slab doesn't need to be copied to219				//   another buffer. However, the performance gain is negligible in220				//   practice (< 0.1%) and is not221				//   worth the added complexity.222				leftover = append(leftover, buf...)223				break224			}225		}226227		if err == io.EOF {228			leftover = append(leftover, buf...)229			break230		}231232		if len(slab) == 0 {233			slab = make([]byte, readerSlabSize)234		}235	}236	if len(leftover) > 0 && r.pusher(leftover) {237		atomic.StoreInt32(&r.event, int32(EvtReadNew))238	}239}240241func (r *Reader) readFromStdin() bool {242	r.feed(os.Stdin)243	return true244}245246func isSymlinkToDir(path string, de os.DirEntry) bool {247	if de.Type()&fs.ModeSymlink == 0 {248		return false249	}250	if s, err := os.Stat(path); err == nil {251		return s.IsDir()252	}253	return false254}255256func trimPath(path string) string {257	bytes := stringBytes(path)258259	for len(bytes) > 1 && bytes[0] == '.' && (bytes[1] == '/' || bytes[1] == '\\') {260		bytes = bytes[2:]261	}262263	if len(bytes) == 0 {264		return "."265	}266267	return byteString(bytes)268}269270func (r *Reader) readFiles(roots []string, opts walkerOpts, ignores []string) bool {271	conf := fastwalk.Config{272		Follow: opts.follow,273		// Use forward slashes when running a Windows binary under WSL or MSYS274		ToSlash: fastwalk.DefaultToSlash(),275		Sort:    fastwalk.SortFilesFirst,276	}277278	// When following symlinks, precompute the absolute real paths of walker279	// roots so we can skip symlinks that point to an ancestor. fastwalk's280	// built-in loop detection (shouldTraverse) catches loops on the second281	// pass, but a single pass through a symlink like z: -> / already282	// traverses the entire root filesystem, causing severe resource283	// exhaustion. Skipping ancestor symlinks prevents this entirely.284	var absRoots []string285	if opts.follow {286		for _, root := range roots {287			if real, err := filepath.EvalSymlinks(root); err == nil {288				if abs, err := filepath.Abs(real); err == nil {289					absRoots = append(absRoots, filepath.Clean(abs))290				}291			}292		}293	}294295	ignoresBase := []string{}296	ignoresFull := []string{}297	ignoresSuffix := []string{}298	sep := string(os.PathSeparator)299	if _, ok := os.LookupEnv("MSYSTEM"); ok {300		sep = "/"301	}302	for _, ignore := range ignores {303		if strings.ContainsRune(ignore, os.PathSeparator) {304			if strings.HasPrefix(ignore, sep) {305				ignoresSuffix = append(ignoresSuffix, ignore)306			} else {307				// 'foo/bar' should match308				// * 'foo/bar'309				// * 'baz/foo/bar'310				// * but NOT 'bazfoo/bar'311				ignoresFull = append(ignoresFull, ignore)312				ignoresSuffix = append(ignoresSuffix, sep+ignore)313			}314		} else {315			ignoresBase = append(ignoresBase, ignore)316		}317	}318	fn := func(path string, de os.DirEntry, err error) error {319		if err != nil {320			return nil321		}322		path = trimPath(path)323		if path != "." {324			isDirSymlink := isSymlinkToDir(path, de)325			if isDirSymlink && !opts.follow {326				return filepath.SkipDir327			}328			// Skip symlinks whose target is an ancestor of (or equal to)329			// any walker root. Following such symlinks would traverse a330			// superset of the tree we're already walking.331			if isDirSymlink && len(absRoots) > 0 {332				if target, err := filepath.EvalSymlinks(path); err == nil {333					if abs, err := filepath.Abs(target); err == nil {334						abs = filepath.Clean(abs)335						if abs == string(os.PathSeparator) {336							return filepath.SkipDir337						}338						for _, absRoot := range absRoots {339							if absRoot == abs || strings.HasPrefix(absRoot, abs+string(os.PathSeparator)) {340								return filepath.SkipDir341							}342						}343					}344				}345			}346			isDir := de.IsDir() || isDirSymlink347			if isDir {348				base := filepath.Base(path)349				if !opts.hidden && base[0] == '.' && base != ".." {350					return filepath.SkipDir351				}352				if slices.Contains(ignoresBase, base) {353					return filepath.SkipDir354				}355				if slices.Contains(ignoresFull, path) {356					return filepath.SkipDir357				}358				for _, ignore := range ignoresSuffix {359					if strings.HasSuffix(path, ignore) {360						return filepath.SkipDir361					}362				}363				if path != sep {364					path += sep365				}366			}367			if ((opts.file && !isDir) || (opts.dir && isDir)) && r.pusher(stringBytes(path)) {368				atomic.StoreInt32(&r.event, int32(EvtReadNew))369			}370		}371		r.mutex.Lock()372		defer r.mutex.Unlock()373		if r.killed {374			return context.Canceled375		}376		return nil377	}378	noerr := true379	for _, root := range roots {380		noerr = noerr && (fastwalk.Walk(&conf, root, fn) == nil)381	}382	return noerr383}384385func (r *Reader) readFromCommand(command string, environ []string, signalReady func()) bool {386	r.mutex.Lock()387388	r.killed = false389	r.termFunc = nil390	r.command = &command391	exec := r.executor.ExecCommand(command, true)392	if environ != nil {393		exec.Env = environ394	}395	execOut, err := exec.StdoutPipe()396	if err != nil || exec.Start() != nil {397		signalReady()398		r.mutex.Unlock()399		return false400	}401402	// Function to call to terminate the running command403	r.termFunc = func() {404		execOut.Close()405		util.KillCommand(exec)406	}407408	signalReady()409	r.mutex.Unlock()410411	r.feed(execOut)412	return exec.Wait() == nil413}