Skip to content
Myr

reader.go

This file

Path

src/reader.go

373 lines · 8.1 KiB · Go

Last changed by

Fix lint warnings (#4586)phaniumbefore adoption91fab3b

History of this file

Take it

The walk stopped after 200 commits: lines older than 1a8f633 point at it.

[fish] Fix for file/dir names containing newlinesbitraidbefore adoption1a8f633

lines 1–9why, one step back
1package fzf
23import (4 "bytes"5 "context"6 "io"7 "io/fs"8 "os"9 "path/filepath"

Fix lint warnings (#4586)phaniumbefore adoption91fab3b

line 10why, one step back
10 "slices"

[fish] Fix for file/dir names containing newlinesbitraidbefore adoption1a8f633

lines 11–181why, one step back
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[:util.Min(len(slab), readerBufferSize)]

Fix lint warnings (#4586)phaniumbefore adoption91fab3b

line 182why, one step back
182 for range 100 {

[fish] Fix for file/dir names containing newlinesbitraidbefore adoption1a8f633

lines 183–288why, one step back
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 }277 ignoresBase := []string{}278 ignoresFull := []string{}279 ignoresSuffix := []string{}280 sep := string(os.PathSeparator)281 if _, ok := os.LookupEnv("MSYSTEM"); ok {282 sep = "/"283 }284 for _, ignore := range ignores {285 if strings.ContainsRune(ignore, os.PathSeparator) {286 if strings.HasPrefix(ignore, sep) {287 ignoresSuffix = append(ignoresSuffix, ignore)288 } else {

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

line 289why, one step back
289 // 'foo/bar' should match

[fish] Fix for file/dir names containing newlinesbitraidbefore adoption1a8f633

lines 290–311why, one step back
290 // * 'foo/bar'
291 // * 'baz/foo/bar'292 // * but NOT 'bazfoo/bar'293 ignoresFull = append(ignoresFull, ignore)294 ignoresSuffix = append(ignoresSuffix, sep+ignore)295 }296 } else {297 ignoresBase = append(ignoresBase, ignore)298 }299 }300 fn := func(path string, de os.DirEntry, err error) error {301 if err != nil {302 return nil303 }304 path = trimPath(path)305 if path != "." {306 isDir := de.IsDir()307 if isDir || opts.follow && isSymlinkToDir(path, de) {308 base := filepath.Base(path)309 if !opts.hidden && base[0] == '.' && base != ".." {310 return filepath.SkipDir311 }

Fix lint warnings (#4586)phaniumbefore adoption91fab3b

lines 312–313why, one step back
312 if slices.Contains(ignoresBase, base) {
313 return filepath.SkipDir

[fish] Fix for file/dir names containing newlinesbitraidbefore adoption1a8f633

line 314why, one step back
314 }

Fix lint warnings (#4586)phaniumbefore adoption91fab3b

lines 315–316why, one step back
315 if slices.Contains(ignoresFull, path) {
316 return filepath.SkipDir

[fish] Fix for file/dir names containing newlinesbitraidbefore adoption1a8f633

lines 317–373why, one step back
317 }
318 for _, ignore := range ignoresSuffix {319 if strings.HasSuffix(path, ignore) {320 return filepath.SkipDir321 }322 }323 if path != sep {324 path += sep325 }326 }327 if ((opts.file && !isDir) || (opts.dir && isDir)) && r.pusher(stringBytes(path)) {328 atomic.StoreInt32(&r.event, int32(EvtReadNew))329 }330 }331 r.mutex.Lock()332 defer r.mutex.Unlock()333 if r.killed {334 return context.Canceled335 }336 return nil337 }338 noerr := true339 for _, root := range roots {340 noerr = noerr && (fastwalk.Walk(&conf, root, fn) == nil)341 }342 return noerr343}344345func (r *Reader) readFromCommand(command string, environ []string, signalReady func()) bool {346 r.mutex.Lock()347348 r.killed = false349 r.termFunc = nil350 r.command = &command351 exec := r.executor.ExecCommand(command, true)352 if environ != nil {353 exec.Env = environ354 }355 execOut, err := exec.StdoutPipe()356 if err != nil || exec.Start() != nil {357 signalReady()358 r.mutex.Unlock()359 return false360 }361362 // Function to call to terminate the running command363 r.termFunc = func() {364 execOut.Close()365 util.KillCommand(exec)366 }367368 signalReady()369 r.mutex.Unlock()370371 r.feed(execOut)372 return exec.Wait() == nil373}