reader.go
This file
Path
src/reader.go
370 lines · 8.0 KiB · Go
Last changed by
Extend --walker-skip to support multi-component patternsJunegunn Choibefore adoption7d95489
History of this fileTake it
The walk stopped after 200 commits: lines older than 368294e point at it.
Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 1–6why, one step back1package fzf23import (4 "bytes"5 "context"6 "io"--walker-skip should also handle symlinks to directoriesJunegunn Choibefore adoption9dc3ed6
line 7why, one step back7 "io/fs"Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 8–9why, one step back8 "os"9 "path/filepath"Extend --walker-skip to support multi-component patternsJunegunn Choibefore adoption7d95489
line 10why, one step back10 "strings"Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 11–27why, one step back11 "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.MutexFix reader regression (#4070)Junegunn Choibefore adoptionacdf265
line 28why, one step back28 killed boolFix race in reload actionJunegunn Choibefore adoptiondcb4c3d
line 29why, one step back29 termFunc func()Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 30–35why, one step back30 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 {Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d
lines 36–43why, one step back36 return &Reader{37 pusher,38 executor,39 eventBox,40 delimNil,41 int32(EvtReady),42 make(chan bool, 1),43 sync.Mutex{},Fix reader regression (#4070)Junegunn Choibefore adoptionacdf265
line 44why, one step back44 false,Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d
lines 45–47why, one step back45 func() { os.Stdin.Close() },46 nil,47 wait}Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 48–81why, one step back48}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.commandFix reader regression (#4070)Junegunn Choibefore adoptionacdf265
line 82why, one step back82 if success || r.killed {Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 83–91why, one step back83 ret = nil84 }85 r.mutex.Unlock()8687 r.eventBox.Set(EvtReadFin, ret)88}8990func (r *Reader) terminate() {91 r.mutex.Lock()Fix reader regression (#4070)Junegunn Choibefore adoptionacdf265
line 92why, one step back92 r.killed = trueFix race in reload actionJunegunn Choibefore adoptiondcb4c3d
lines 93–95why, one step back93 if r.termFunc != nil {94 r.termFunc()95 r.termFunc = nilReduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 96–99why, one step back96 }97 r.mutex.Unlock()98}99Remove possible races (#4070)Junegunn Choibefore adoption19495eb
line 100why, one step back100func (r *Reader) restart(command commandSpec, environ []string, readyChan chan bool) {Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 101–102why, one step back101 r.event = int32(EvtReady)102 r.startEventPoller()Remove possible races (#4070)Junegunn Choibefore adoption19495eb
lines 103–107why, one step back103 success := r.readFromCommand(command.command, environ, func() {104 readyChan <- true105 })106 r.fin(success)107 removeFiles(command.tempFiles)Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 108–123why, one step back108}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 inputAllow walking multiple root directories (#4109)msabathierbefore adoptionbee80a7
line 124why, one step back124func (r *Reader) ReadSource(inputChan chan string, roots []string, opts walkerOpts, ignores []string, initCmd string, initEnv []string, readyChan chan bool) {Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 125–126why, one step back125 r.startEventPoller()126 var success boolRemove possible races (#4070)Junegunn Choibefore adoption19495eb
lines 127–131why, one step back127 signalReady := func() {128 if readyChan != nil {129 readyChan <- true130 }131 }Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
line 132why, one step back132 if inputChan != nil {Remove possible races (#4070)Junegunn Choibefore adoption19495eb
line 133why, one step back133 signalReady()Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
line 134why, one step back134 success = r.readChannel(inputChan)Fix incompatibility of adaptive height and 'start:reload'Junegunn Choibefore adoption587df59
line 135why, one step back135 } else if len(initCmd) > 0 {Remove possible races (#4070)Junegunn Choibefore adoption19495eb
line 136why, one step back136 success = r.readFromCommand(initCmd, initEnv, signalReady)Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 137–139why, one step back137 } else if util.IsTty(os.Stdin) {138 cmd := os.Getenv("FZF_DEFAULT_COMMAND")139 if len(cmd) == 0 {Remove possible races (#4070)Junegunn Choibefore adoption19495eb
line 140why, one step back140 signalReady()Allow walking multiple root directories (#4109)msabathierbefore adoptionbee80a7
line 141why, one step back141 success = r.readFiles(roots, opts, ignores)Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
line 142why, one step back142 } else {Remove possible races (#4070)Junegunn Choibefore adoption19495eb
line 143why, one step back143 success = r.readFromCommand(cmd, initEnv, signalReady)Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 144–145why, one step back144 }145 } else {Remove possible races (#4070)Junegunn Choibefore adoption19495eb
line 146why, one step back146 signalReady()Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 147–244why, one step back147 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}244--walker-skip should also handle symlinks to directoriesJunegunn Choibefore adoption9dc3ed6
lines 245–254why, one step back245func 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}254Update charlievieth/fastwalk to use forward-slashes on WSL and MSYS (#3907)Charlie Viethbefore adoption2dbc874
lines 255–268why, one step back255func 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}268Allow walking multiple root directories (#4109)msabathierbefore adoptionbee80a7
line 269why, one step back269func (r *Reader) readFiles(roots []string, opts walkerOpts, ignores []string) bool {Update charlievieth/fastwalk to use forward-slashes on WSL and MSYS (#3907)Charlie Viethbefore adoption2dbc874
lines 270–273why, one step back270 conf := fastwalk.Config{271 Follow: opts.follow,272 // Use forward slashes when running a Windows binary under WSL or MSYS273 ToSlash: fastwalk.DefaultToSlash(),Update fastwalk to v1.0.8 for better MSYS detection and sorting (#3930)Charlie Viethbefore adoptiona2c365e
line 274why, one step back274 Sort: fastwalk.SortFilesFirst,Update charlievieth/fastwalk to use forward-slashes on WSL and MSYS (#3907)Charlie Viethbefore adoption2dbc874
line 275why, one step back275 }Extend --walker-skip to support multi-component patternsJunegunn Choibefore adoption7d95489
lines 276–295why, one step back276 ignoresBase := []string{}277 ignoresFull := []string{}278 ignoresSuffix := []string{}279 sep := string(os.PathSeparator)280 for _, ignore := range ignores {281 if strings.ContainsRune(ignore, os.PathSeparator) {282 if strings.HasPrefix(ignore, sep) {283 ignoresSuffix = append(ignoresSuffix, ignore)284 } else {285 // 'foo/bar' should match match286 // * 'foo/bar'287 // * 'baz/foo/bar'288 // * but NOT 'bazfoo/bar'289 ignoresFull = append(ignoresFull, ignore)290 ignoresSuffix = append(ignoresSuffix, sep+ignore)291 }292 } else {293 ignoresBase = append(ignoresBase, ignore)294 }295 }Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 296–299why, one step back296 fn := func(path string, de os.DirEntry, err error) error {297 if err != nil {298 return nil299 }Update charlievieth/fastwalk to use forward-slashes on WSL and MSYS (#3907)Charlie Viethbefore adoption2dbc874
line 300why, one step back300 path = trimPath(path)Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 301–302why, one step back301 if path != "." {302 isDir := de.IsDir()--walker-skip should also handle symlinks to directoriesJunegunn Choibefore adoption9dc3ed6
line 303why, one step back303 if isDir || opts.follow && isSymlinkToDir(path, de) {Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
line 304why, one step back304 base := filepath.Base(path)walker: Do not treat '..' as a hidden entryJunegunn Choibefore adoptiond65c610
line 305why, one step back305 if !opts.hidden && base[0] == '.' && base != ".." {Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 306–307why, one step back306 return filepath.SkipDir307 }Extend --walker-skip to support multi-component patternsJunegunn Choibefore adoption7d95489
line 308why, one step back308 for _, ignore := range ignoresBase {Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
line 309why, one step back309 if ignore == base {Extend --walker-skip to support multi-component patternsJunegunn Choibefore adoption7d95489
lines 310–319why, one step back310 return filepath.SkipDir311 }312 }313 for _, ignore := range ignoresFull {314 if ignore == path {315 return filepath.SkipDir316 }317 }318 for _, ignore := range ignoresSuffix {319 if strings.HasSuffix(path, ignore) {Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 320–323why, one step back320 return filepath.SkipDir321 }322 }323 }Remove --walker-path-sepJunegunn Choibefore adoption8f4c23f
line 324why, one step back324 if ((opts.file && !isDir) || (opts.dir && isDir)) && r.pusher(stringBytes(path)) {Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 325–329why, one step back325 atomic.StoreInt32(&r.event, int32(EvtReadNew))326 }327 }328 r.mutex.Lock()329 defer r.mutex.Unlock()Fix reader regression (#4070)Junegunn Choibefore adoptionacdf265
line 330why, one step back330 if r.killed {Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 331–334why, one step back331 return context.Canceled332 }333 return nil334 }Allow walking multiple root directories (#4109)msabathierbefore adoptionbee80a7
lines 335–339why, one step back335 noerr := true336 for _, root := range roots {337 noerr = noerr && (fastwalk.Walk(&conf, root, fn) == nil)338 }339 return noerrReduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 340–341why, one step back340}341Remove possible races (#4070)Junegunn Choibefore adoption19495eb
lines 342–344why, one step back342func (r *Reader) readFromCommand(command string, environ []string, signalReady func()) bool {343 r.mutex.Lock()344Fix reader regression (#4070)Junegunn Choibefore adoptionacdf265
line 345why, one step back345 r.killed = falseFix race in reload actionJunegunn Choibefore adoptiondcb4c3d
line 346why, one step back346 r.termFunc = nilReduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
line 347why, one step back347 r.command = &commandFix race in reload actionJunegunn Choibefore adoptiondcb4c3d
line 348why, one step back348 exec := r.executor.ExecCommand(command, true)Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
line 349why, one step back349 if environ != nil {Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d
line 350why, one step back350 exec.Env = environReduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
line 351why, one step back351 }Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d
lines 352–353why, one step back352 execOut, err := exec.StdoutPipe()353 if err != nil || exec.Start() != nil {Fix reader regression (#4070)Junegunn Choibefore adoptionacdf265
line 354why, one step back354 signalReady()Remove possible races (#4070)Junegunn Choibefore adoption19495eb
lines 355–356why, one step back355 r.mutex.Unlock()356 return falseReduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 357–358why, one step back357 }358Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d
lines 359–362why, one step back359 // Function to call to terminate the running command360 r.termFunc = func() {361 execOut.Close()362 util.KillCommand(exec)Reduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
lines 363–364why, one step back363 }364Remove possible races (#4070)Junegunn Choibefore adoption19495eb
lines 365–366why, one step back365 signalReady()366 r.mutex.Unlock()Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d
lines 367–369why, one step back367368 r.feed(execOut)369 return exec.Wait() == nilReduce flickering of the list when the list is truncated by --tailJunegunn Choibefore adoption368294e
line 370why, one step back370}