Skip to content
Myr

reader.go

This file

Path

src/reader.go

334 lines · 7.1 KiB · Go

Last changed by

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

History of this file

Take it

The walk stopped after 200 commits: lines older than 5b204c5 point at it.

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 1–6why, one step back
1package fzf
23import (4 "bytes"5 "context"6 "io"

--walker-skip should also handle symlinks to directoriesJunegunn Choibefore adoption9dc3ed6

line 7why, one step back
7 "io/fs"

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 8–26why, one step back
8 "os"
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.Mutex

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

line 27why, one step back
27 termFunc func()

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 28–33why, one step back
28 command *string
29 wait bool30}3132// NewReader returns new Reader object33func NewReader(pusher func([]byte) bool, eventBox *util.EventBox, executor *util.Executor, delimNil bool, wait bool) *Reader {

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

lines 34–44why, one step back
34 return &Reader{
35 pusher,36 executor,37 eventBox,38 delimNil,39 int32(EvtReady),40 make(chan bool, 1),41 sync.Mutex{},42 func() { os.Stdin.Close() },43 nil,44 wait}

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 45–70why, one step back
45}
4647func (r *Reader) startEventPoller() {48 go func() {49 ptr := &r.event50 pollInterval := readerPollIntervalMin51 for {52 if atomic.CompareAndSwapInt32(ptr, int32(EvtReadNew), int32(EvtReady)) {53 r.eventBox.Set(EvtReadNew, (*string)(nil))54 pollInterval = readerPollIntervalMin55 } else if atomic.LoadInt32(ptr) == int32(EvtReadFin) {56 if r.wait {57 r.finChan <- true58 }59 return60 } else {61 pollInterval += readerPollIntervalStep62 if pollInterval > readerPollIntervalMax {63 pollInterval = readerPollIntervalMax64 }65 }66 time.Sleep(pollInterval)67 }68 }()69}70

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

lines 71–74why, one step back
71func (r *Reader) wasKilled() bool {
72 return r.termFunc == nil73}74

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 75–82why, one step back
75func (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.command

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

line 83why, one step back
83 if success || r.wasKilled() {

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 84–92why, one step back
84 ret = nil
85 }86 r.mutex.Unlock()8788 r.eventBox.Set(EvtReadFin, ret)89}9091func (r *Reader) terminate() {92 r.mutex.Lock()

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

lines 93–95why, one step back
93 if r.termFunc != nil {
94 r.termFunc()95 r.termFunc = nil

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 96–99why, one step back
96 }
97 r.mutex.Unlock()98}99

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

line 100why, one step back
100func (r *Reader) restart(command commandSpec, environ []string, readyChan chan bool) {

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 101–102why, one step back
101 r.event = int32(EvtReady)
102 r.startEventPoller()

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

lines 103–107why, one step back
103 success := r.readFromCommand(command.command, environ, func() {
104 readyChan <- true105 })106 r.fin(success)107 removeFiles(command.tempFiles)

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 108–123why, one step back
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 input

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

line 124why, one step back
124func (r *Reader) ReadSource(inputChan chan string, root string, opts walkerOpts, ignores []string, initCmd string, initEnv []string, readyChan chan bool) {

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 125–126why, one step back
125 r.startEventPoller()
126 var success bool

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

lines 127–131why, one step back
127 signalReady := func() {
128 if readyChan != nil {129 readyChan <- true130 }131 }

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 132why, one step back
132 if inputChan != nil {

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

line 133why, one step back
133 signalReady()

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 134why, one step back
134 success = r.readChannel(inputChan)

Fix incompatibility of adaptive height and 'start:reload'Junegunn Choibefore adoption587df59

line 135why, one step back
135 } else if len(initCmd) > 0 {

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

line 136why, one step back
136 success = r.readFromCommand(initCmd, initEnv, signalReady)

execute: Open separate handles to /dev/tty (in, out, err)Junegunn Choibefore adoption3dee877

line 137why, one step back
137 } else if util.IsTty(os.Stdin) {

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 138–139why, one step back
138 cmd := os.Getenv("FZF_DEFAULT_COMMAND")
139 if len(cmd) == 0 {

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

line 140why, one step back
140 signalReady()

Remove --walker-path-sepJunegunn Choibefore adoption8f4c23f

line 141why, one step back
141 success = r.readFiles(root, opts, ignores)

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 142why, one step back
142 } else {

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

line 143why, one step back
143 success = r.readFromCommand(cmd, initEnv, signalReady)

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 144–145why, one step back
144 }
145 } else {

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

line 146why, one step back
146 signalReady()

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 147–244why, one step back
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}244

--walker-skip should also handle symlinks to directoriesJunegunn Choibefore adoption9dc3ed6

lines 245–254why, one step back
245func 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}254

Update charlievieth/fastwalk to use forward-slashes on WSL and MSYS (#3907)Charlie Viethbefore adoption2dbc874

lines 255–268why, one step back
255func 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}268

Remove --walker-path-sepJunegunn Choibefore adoption8f4c23f

line 269why, one step back
269func (r *Reader) readFiles(root 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 back
270 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 back
274 Sort: fastwalk.SortFilesFirst,

Update charlievieth/fastwalk to use forward-slashes on WSL and MSYS (#3907)Charlie Viethbefore adoption2dbc874

line 275why, one step back
275 }

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 276–279why, one step back
276 fn := func(path string, de os.DirEntry, err error) error {
277 if err != nil {278 return nil279 }

Update charlievieth/fastwalk to use forward-slashes on WSL and MSYS (#3907)Charlie Viethbefore adoption2dbc874

line 280why, one step back
280 path = trimPath(path)

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 281–282why, one step back
281 if path != "." {
282 isDir := de.IsDir()

--walker-skip should also handle symlinks to directoriesJunegunn Choibefore adoption9dc3ed6

line 283why, one step back
283 if isDir || opts.follow && isSymlinkToDir(path, de) {

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 284why, one step back
284 base := filepath.Base(path)

walker: Do not treat '..' as a hidden entryJunegunn Choibefore adoptiond65c610

line 285why, one step back
285 if !opts.hidden && base[0] == '.' && base != ".." {

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 286–293why, one step back
286 return filepath.SkipDir
287 }288 for _, ignore := range ignores {289 if ignore == base {290 return filepath.SkipDir291 }292 }293 }

Remove --walker-path-sepJunegunn Choibefore adoption8f4c23f

line 294why, one step back
294 if ((opts.file && !isDir) || (opts.dir && isDir)) && r.pusher(stringBytes(path)) {

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 295–299why, one step back
295 atomic.StoreInt32(&r.event, int32(EvtReadNew))
296 }297 }298 r.mutex.Lock()299 defer r.mutex.Unlock()

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

line 300why, one step back
300 if r.wasKilled() {

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

lines 301–307why, one step back
301 return context.Canceled
302 }303 return nil304 }305 return fastwalk.Walk(&conf, root, fn) == nil306}307

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

lines 308–310why, one step back
308func (r *Reader) readFromCommand(command string, environ []string, signalReady func()) bool {
309 r.mutex.Lock()310

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

line 311why, one step back
311 r.termFunc = nil

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 312why, one step back
312 r.command = &command

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

line 313why, one step back
313 exec := r.executor.ExecCommand(command, true)

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 314why, one step back
314 if environ != nil {

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

line 315why, one step back
315 exec.Env = environ

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 316why, one step back
316 }

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

lines 317–318why, one step back
317 execOut, err := exec.StdoutPipe()
318 if err != nil || exec.Start() != nil {

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

lines 319–320why, one step back
319 r.mutex.Unlock()
320 return false

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 321why, one step back
321 }

Immediately close standard output of the child processJunegunn Choibefore adoptione042143

line 322why, one step back
322

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

lines 323–326why, one step back
323 // Function to call to terminate the running command
324 r.termFunc = func() {325 execOut.Close()326 util.KillCommand(exec)

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 327why, one step back
327 }

Immediately close standard output of the child processJunegunn Choibefore adoptione042143

line 328why, one step back
328

Remove possible races (#4070)Junegunn Choibefore adoption19495eb

lines 329–330why, one step back
329 signalReady()
330 r.mutex.Unlock()

Fix race in reload actionJunegunn Choibefore adoptiondcb4c3d

lines 331–333why, one step back
331
332 r.feed(execOut)333 return exec.Wait() == nil

Change default pointer and marker characterJunegunn Choibefore adoption5b204c5

line 334why, one step back
334}