Debian Codegraph @

src/reader.go

raw
1 package fzf
2
3 import (
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"
15
16 "github.com/charlievieth/fastwalk"
17 "github.com/junegunn/fzf/src/util"
18 )
19
20 // Reader reads from command or standard input
21 type Reader struct {
22 pusher func([]byte) bool
23 executor *util.Executor
24 eventBox *util.EventBox
25 delimNil bool
26 event int32
27 finChan chan bool
28 mutex sync.Mutex
29 killed bool
30 termFunc func()
31 command *string
32 wait bool
33 }
34
35 // NewReader returns new Reader object
36 func 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 }
50
51 func (r *Reader) startEventPoller() {
52 go func() {
53 ptr := &r.event
54 pollInterval := readerPollIntervalMin
55 for {
56 if atomic.CompareAndSwapInt32(ptr, int32(EvtReadNew), int32(EvtReady)) {
57 r.eventBox.Set(EvtReadNew, (*string)(nil))
58 pollInterval = readerPollIntervalMin
59 } else if atomic.LoadInt32(ptr) == int32(EvtReadFin) {
60 if r.wait {
61 r.finChan <- true
62 }
63 return
64 } else {
65 pollInterval += readerPollIntervalStep
66 if pollInterval > readerPollIntervalMax {
67 pollInterval = readerPollIntervalMax
68 }
69 }
70 time.Sleep(pollInterval)
71 }
72 }()
73 }
74
75 func (r *Reader) fin(success bool) {
76 atomic.StoreInt32(&r.event, int32(EvtReadFin))
77 if r.wait {
78 <-r.finChan
79 }
80
81 r.mutex.Lock()
82 ret := r.command
83 if success || r.killed {
84 ret = nil
85 }
86 r.mutex.Unlock()
87
88 r.eventBox.Set(EvtReadFin, ret)
89 }
90
91 func (r *Reader) terminate() {
92 r.mutex.Lock()
93 r.killed = true
94 if r.termFunc != nil {
95 r.termFunc()
96 r.termFunc = nil
97 }
98 r.mutex.Unlock()
99 }
100
101 func (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 <- true
106 })
107 r.fin(success)
108 removeFiles(command.tempFiles)
109 }
110
111 func (r *Reader) readChannel(inputChan chan string) bool {
112 for {
113 item, more := <-inputChan
114 if !more {
115 break
116 }
117 if r.pusher([]byte(item)) {
118 atomic.StoreInt32(&r.event, int32(EvtReadNew))
119 }
120 }
121 return true
122 }
123
124 // ReadSource reads data from the default command or from standard input
125 func (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 bool
128 signalReady := func() {
129 if readyChan != nil {
130 readyChan <- true
131 }
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 }
152
153 func (r *Reader) feed(src io.Reader) {
154 /*
155 readerSlabSize, ae := strconv.Atoi(os.Getenv("SLAB_KB"))
156 if ae != nil {
157 readerSlabSize = 128 * 1024
158 } else {
159 readerSlabSize *= 1024
160 }
161 readerBufferSize, be := strconv.Atoi(os.Getenv("BUF_KB"))
162 if be != nil {
163 readerBufferSize = 64 * 1024
164 } else {
165 readerBufferSize *= 1024
166 }
167 */
168
169 delim := byte('\n')
170 trimCR := util.IsWindows()
171 if r.delimNil {
172 delim = '\000'
173 trimCR = false
174 }
175
176 slab := make([]byte, readerSlabSize)
177 leftover := []byte{}
178 var err error
179 for {
180 n := 0
181 scope := slab[:min(len(slab), readerBufferSize)]
182 for range 100 {
183 n, err = src.Read(scope)
184 if n > 0 || err != nil {
185 break
186 }
187 }
188
189 // We're not making any progress after 100 tries. Stop.
190 if n == 0 {
191 break
192 }
193
194 buf := slab[:n]
195 slab = slab[n:]
196
197 for len(buf) > 0 {
198 if i := bytes.IndexByte(buf, delim); i >= 0 {
199 // Found the delimiter
200 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 buffer
216 // NOTE: We can further optimize this by keeping track of the cursor
217 // position in the slab so that a straddling item that doesn't go
218 // beyond the boundary of a slab doesn't need to be copied to
219 // another buffer. However, the performance gain is negligible in
220 // practice (< 0.1%) and is not
221 // worth the added complexity.
222 leftover = append(leftover, buf...)
223 break
224 }
225 }
226
227 if err == io.EOF {
228 leftover = append(leftover, buf...)
229 break
230 }
231
232 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 }
240
241 func (r *Reader) readFromStdin() bool {
242 r.feed(os.Stdin)
243 return true
244 }
245
246 func isSymlinkToDir(path string, de os.DirEntry) bool {
247 if de.Type()&fs.ModeSymlink == 0 {
248 return false
249 }
250 if s, err := os.Stat(path); err == nil {
251 return s.IsDir()
252 }
253 return false
254 }
255
256 func trimPath(path string) string {
257 bytes := stringBytes(path)
258
259 for len(bytes) > 1 && bytes[0] == '.' && (bytes[1] == '/' || bytes[1] == '\\') {
260 bytes = bytes[2:]
261 }
262
263 if len(bytes) == 0 {
264 return "."
265 }
266
267 return byteString(bytes)
268 }
269
270 func (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 MSYS
274 ToSlash: fastwalk.DefaultToSlash(),
275 Sort: fastwalk.SortFilesFirst,
276 }
277
278 // When following symlinks, precompute the absolute real paths of walker
279 // roots so we can skip symlinks that point to an ancestor. fastwalk's
280 // built-in loop detection (shouldTraverse) catches loops on the second
281 // pass, but a single pass through a symlink like z: -> / already
282 // traverses the entire root filesystem, causing severe resource
283 // exhaustion. Skipping ancestor symlinks prevents this entirely.
284 var absRoots []string
285 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 }
294
295 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 match
308 // * '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 nil
321 }
322 path = trimPath(path)
323 if path != "." {
324 isDirSymlink := isSymlinkToDir(path, de)
325 if isDirSymlink && !opts.follow {
326 return filepath.SkipDir
327 }
328 // Skip symlinks whose target is an ancestor of (or equal to)
329 // any walker root. Following such symlinks would traverse a
330 // 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.SkipDir
337 }
338 for _, absRoot := range absRoots {
339 if absRoot == abs || strings.HasPrefix(absRoot, abs+string(os.PathSeparator)) {
340 return filepath.SkipDir
341 }
342 }
343 }
344 }
345 }
346 isDir := de.IsDir() || isDirSymlink
347 if isDir {
348 base := filepath.Base(path)
349 if !opts.hidden && base[0] == '.' && base != ".." {
350 return filepath.SkipDir
351 }
352 if slices.Contains(ignoresBase, base) {
353 return filepath.SkipDir
354 }
355 if slices.Contains(ignoresFull, path) {
356 return filepath.SkipDir
357 }
358 for _, ignore := range ignoresSuffix {
359 if strings.HasSuffix(path, ignore) {
360 return filepath.SkipDir
361 }
362 }
363 if path != sep {
364 path += sep
365 }
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.Canceled
375 }
376 return nil
377 }
378 noerr := true
379 for _, root := range roots {
380 noerr = noerr && (fastwalk.Walk(&conf, root, fn) == nil)
381 }
382 return noerr
383 }
384
385 func (r *Reader) readFromCommand(command string, environ []string, signalReady func()) bool {
386 r.mutex.Lock()
387
388 r.killed = false
389 r.termFunc = nil
390 r.command = &command
391 exec := r.executor.ExecCommand(command, true)
392 if environ != nil {
393 exec.Env = environ
394 }
395 execOut, err := exec.StdoutPipe()
396 if err != nil || exec.Start() != nil {
397 signalReady()
398 r.mutex.Unlock()
399 return false
400 }
401
402 // Function to call to terminate the running command
403 r.termFunc = func() {
404 execOut.Close()
405 util.KillCommand(exec)
406 }
407
408 signalReady()
409 r.mutex.Unlock()
410
411 r.feed(execOut)
412 return exec.Wait() == nil
413 }