Skip to content
Myr

Add --tail=NUM to limit the number of items to keep in memory

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Junegunn Choi · committed by Junegunn Choi · parent 4c83d85 · Browse files · 10 files+226 added−56 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

10 files+226 added−56 removed

  • other:+226 added−56 removed

10 files+226 added−56 removed

modified:man/man1/fzf.1+10 added
97 unmodified lines
98.TP99.B "+s, --no-sort"100Do not sort the result101.TP102.B "--tail=NUM"103Maximum number of items to keep in memory. This is useful when you want to104browse an endless stream of data (e.g. log stream) with fzf while limiting105memory usage.106.RS107e.g.108 \fB# Interactive filtering of a log stream109 tail -f *.log | fzf --tail 100000 --tac --no-sort --exact\fR110.RE111.TP112.B "--track"113Make fzf track the current selection when the result list is updated.114This can be useful when browsing logs using fzf with sorting disabled. It is115not recommended to use this option with \fB--tac\fR as the resulting behavior
1521 unmodified lines
modified:src/chunklist_test.go+39 added-3 removed
15 unmodified lines
16 return true17 })1819 // Snapshot20 snapshot, count := cl.Snapshot()20 snapshot, count, _ := cl.Snapshot(0)21 if len(snapshot) > 0 || count > 0 {22 t.Error("Snapshot should be empty now")23 }24
6 unmodified lines
31 t.Error("Snapshot should not have changed")32 }3334 // But the new snapshot should contain the added items35 snapshot, count = cl.Snapshot()35 snapshot, count, _ = cl.Snapshot(0)36 if len(snapshot) != 1 && count != 2 {37 t.Error("Snapshot should not be empty now")38 }39
20 unmodified lines
60 t.Error("Snapshot should stay the same")61 }6263 // New snapshot64 snapshot, count = cl.Snapshot()64 snapshot, count, _ = cl.Snapshot(0)65 if len(snapshot) != 3 || !snapshot[0].IsFull() ||66 !snapshot[1].IsFull() || snapshot[2].IsFull() || count != chunkSize*2+2 {67 t.Error("Expected two full chunks and one more chunk")68 }
8 unmodified lines
77 if lastChunkCount != 2 {78 t.Error("Unexpected number of items:", lastChunkCount)79 }80}8182func TestChunkListTail(t *testing.T) {83 cl := NewChunkList(func(item *Item, s []byte) bool {84 item.text = util.ToChars(s)85 return true86 })87 total := chunkSize*2 + chunkSize/288 for i := 0; i < total; i++ {89 cl.Push([]byte(fmt.Sprintf("item %d", i)))90 }9192 snapshot, count, changed := cl.Snapshot(0)93 assertCount := func(expected int, shouldChange bool) {94 if count != expected || CountItems(snapshot) != expected {95 t.Errorf("Unexpected count: %d (expected: %d)", count, expected)96 }97 if changed != shouldChange {98 t.Error("Unexpected change status")99 }100 }101 assertCount(total, false)102103 tail := chunkSize + chunkSize/2104 snapshot, count, changed = cl.Snapshot(tail)105 assertCount(tail, true)106107 snapshot, count, changed = cl.Snapshot(tail)108 assertCount(tail, false)109110 snapshot, count, changed = cl.Snapshot(0)111 assertCount(tail, false)112113 tail = chunkSize / 2114 snapshot, count, changed = cl.Snapshot(tail)115 assertCount(tail, true)116}
modified:src/chunklist.go+44 added-4 removed
46 unmodified lines
47func CountItems(cs []*Chunk) int {48 if len(cs) == 0 {49 return 050 }51 return chunkSize*(len(cs)-1) + cs[len(cs)-1].count51 if len(cs) == 1 {52 return cs[0].count53 }5455 // First chunk might not be full due to --tail=N56 return cs[0].count + chunkSize*(len(cs)-2) + cs[len(cs)-1].count57}5859// Push adds the item to the list60func (cl *ChunkList) Push(data []byte) bool {
15 unmodified lines
76 cl.mutex.Unlock()77}7879// Snapshot returns immutable snapshot of the ChunkList75func (cl *ChunkList) Snapshot() ([]*Chunk, int) {80func (cl *ChunkList) Snapshot(tail int) ([]*Chunk, int, bool) {81 cl.mutex.Lock()8283 changed := false84 if tail > 0 && CountItems(cl.chunks) > tail {85 changed = true86 // Find the number of chunks to keep87 numChunks := 088 for left, i := tail, len(cl.chunks)-1; left > 0 && i >= 0; i-- {89 numChunks++90 left -= cl.chunks[i].count91 }9293 // Copy the chunks to keep94 ret := make([]*Chunk, numChunks)95 copy(ret, cl.chunks[len(cl.chunks)-numChunks:])9697 for left, i := tail, len(ret)-1; i >= 0; i-- {98 chunk := ret[i]99 if chunk.count > left {100 newChunk := *chunk101 newChunk.count = left102 oldCount := chunk.count103 for i := 0; i < left; i++ {104 newChunk.items[i] = chunk.items[oldCount-left+i]105 }106 ret[i] = &newChunk107 break108 }109 left -= chunk.count110 }111 cl.chunks = ret112 }113114 ret := make([]*Chunk, len(cl.chunks))115 copy(ret, cl.chunks)11681 // Duplicate the last chunk117 // Duplicate the first and the last chunk118 if cnt := len(ret); cnt > 0 {119 if tail > 0 && cnt > 1 {120 newChunk := *ret[0]121 ret[0] = &newChunk122 }123 newChunk := *ret[cnt-1]124 ret[cnt-1] = &newChunk125 }126127 cl.mutex.Unlock()88 return ret, CountItems(ret)128 return ret, CountItems(ret), changed129}
modified:src/core.go+37 added-7 removed
16 unmodified lines
17Matcher -> EvtSearchFin -> Terminal (update list)18Matcher -> EvtHeader -> Terminal (update header)19*/2021type revision struct {22 major int23 minor int24}2526func (r *revision) bumpMajor() {27 r.major++28 r.minor = 029}3031func (r *revision) bumpMinor() {32 r.minor++33}3435func (r revision) equals(other revision) bool {36 return r.major == other.major && r.minor == other.minor37}3839func (r revision) compatible(other revision) bool {40 return r.major == other.major41}4243// Run starts fzf44func Run(opts *Options) (int, error) {45 if opts.Tmux != nil && len(os.Getenv("TMUX")) > 0 && opts.Tmux.index >= opts.Height.index {46 return runTmux(os.Args, opts)
129 unmodified lines
176 return BuildPattern(cache, patternCache,177 opts.Fuzzy, opts.FuzzyAlgo, opts.Extended, opts.Case, opts.Normalize, forward, withPos,178 opts.Filter == nil, opts.Nth, opts.Delimiter, runes)179 }158 inputRevision := 0159 snapshotRevision := 0180 inputRevision := revision{}181 snapshotRevision := revision{}182 matcher := NewMatcher(cache, patternBuilder, sort, opts.Tac, eventBox, inputRevision)183184 // Filtering mode185 if opts.Filter != nil {
25 unmodified lines
211 } else {212 eventBox.Unwatch(EvtReadNew)213 eventBox.WaitFor(EvtReadFin)214193 snapshot, _ := chunkList.Snapshot()215 // NOTE: Streaming filter is inherently not compatible with --tail216 snapshot, _, _ := chunkList.Snapshot(opts.Tail)217 merger, _ := matcher.scan(MatchRequest{218 chunks: snapshot,219 pattern: pattern})220 for i := 0; i < merger.Length(); i++ {
62 unmodified lines
283 restart := func(command commandSpec, environ []string) {284 reading = true285 chunkList.Clear()286 itemIndex = 0264 inputRevision++287 inputRevision.bumpMajor()288 header = make([]string, 0, opts.HeaderLines)289 go reader.restart(command, environ)290 }291
36 unmodified lines
328 if useSnapshot && evt == EvtReadFin {329 useSnapshot = false330 }331 if !useSnapshot {309 if snapshotRevision != inputRevision {332 if !snapshotRevision.compatible(inputRevision) {333 query = []rune{}334 }312 snapshot, count = chunkList.Snapshot()335 var changed bool336 snapshot, count, changed = chunkList.Snapshot(opts.Tail)337 if changed {338 inputRevision.bumpMinor()339 }340 snapshotRevision = inputRevision341 }342 total = count343 terminal.UpdateCount(total, !reading, value.(*string))
31 unmodified lines
375 if !changed {376 break377 }378 if !useSnapshot {352 newSnapshot, newCount := chunkList.Snapshot()379 newSnapshot, newCount, changed := chunkList.Snapshot(opts.Tail)380 if changed {381 inputRevision.bumpMinor()382 }383 // We want to avoid showing empty list when reload is triggered384 // and the query string is changed at the same time i.e. command != nil && changed385 if command == nil || newCount > 0 {386 if snapshotRevision != inputRevision {
65 unmodified lines
modified:src/matcher.go+19 added-16 removed
14 unmodified lines
15 chunks []*Chunk16 pattern *Pattern17 final bool18 sort bool19 revision int19 revision revision20}2122// Matcher is responsible for performing search23type Matcher struct {
5 unmodified lines
29 reqBox *util.EventBox30 partitions int31 slab []*util.Slab32 mergerCache map[string]*Merger33 revision int33 revision revision34}3536const (37 reqRetry util.EventType = iota
1 unmodified line
39)4041// NewMatcher returns a new Matcher42func NewMatcher(cache *ChunkCache, patternBuilder func([]rune) *Pattern,43 sort bool, tac bool, eventBox *util.EventBox, revision int) *Matcher {43 sort bool, tac bool, eventBox *util.EventBox, revision revision) *Matcher {44 partitions := util.Min(numPartitionsMultiplier*runtime.NumCPU(), maxPartitions)45 return &Matcher{46 cache: cache,47 patternBuilder: patternBuilder,
33 unmodified lines
81 if stop {82 break83 }8485 cacheCleared := false86 if request.sort != m.sort || request.revision != m.revision {87 m.sort = request.sort88 m.revision = request.revision89 m.mergerCache = make(map[string]*Merger)90 m.cache.Clear()91 cacheCleared = true92 }9394 // Restart search95 patternString := request.pattern.AsString()96 var merger *Merger97 cancelled := false98 count := CountItems(request.chunks)9998 foundCache := false99 if count == prevCount {100 // Look up mergerCache101 if cached, found := m.mergerCache[patternString]; found {102 foundCache = true103 merger = cached100 if !cacheCleared {101 if count == prevCount {102 // Look up mergerCache103 if cached, found := m.mergerCache[patternString]; found {104 merger = cached105 }106 } else {107 // Invalidate mergerCache108 prevCount = count109 m.mergerCache = make(map[string]*Merger)110 }105 } else {106 // Invalidate mergerCache107 prevCount = count108 m.mergerCache = make(map[string]*Merger)111 }112111 if !foundCache {113 if merger == nil {114 merger, cancelled = m.scan(request)115 }116117 if !cancelled {
43 unmodified lines
161 if pattern.IsEmpty() {162 return PassMerger(&request.chunks, m.tac, request.revision), false163 }164165 minIndex := request.chunks[0].items[0].Index()166 cancelled := util.NewAtomicBool(false)167168 slices := m.sliceChunks(request.chunks)169 numSlices := len(slices)
63 unmodified lines
233 for range slices {234 partialResult := <-resultChan235 partialResults[partialResult.index] = partialResult.matches236 }234 return NewMerger(pattern, partialResults, m.sort, m.tac, request.revision), false237 return NewMerger(pattern, partialResults, m.sort, m.tac, request.revision, minIndex), false238}239240// Reset is called to interrupt/signal the ongoing search238func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool, final bool, sort bool, revision int) {241func (m *Matcher) Reset(chunks []*Chunk, patternRunes []rune, cancel bool, final bool, sort bool, revision revision) {242 pattern := m.patternBuilder(patternRunes)243244 var event util.EventType245 if cancel {
10 unmodified lines
modified:src/merger_test.go+8 added-7 removed
21 unmodified lines
22 return Result{item: &Item{text: chars}}23}2425func TestEmptyMerger(t *testing.T) {26 r := revision{}26 assert(t, EmptyMerger(0).Length() == 0, "Not empty")27 assert(t, EmptyMerger(0).count == 0, "Invalid count")28 assert(t, len(EmptyMerger(0).lists) == 0, "Invalid lists")29 assert(t, len(EmptyMerger(0).merged) == 0, "Invalid merged list")27 assert(t, EmptyMerger(r).Length() == 0, "Not empty")28 assert(t, EmptyMerger(r).count == 0, "Invalid count")29 assert(t, len(EmptyMerger(r).lists) == 0, "Invalid lists")30 assert(t, len(EmptyMerger(r).merged) == 0, "Invalid merged list")31}3233func buildLists(partiallySorted bool) ([][]Result, []Result) {34 numLists := 4
22 unmodified lines
57 lists, items := buildLists(false)58 cnt := len(items)5960 // Not sorted: same order60 mg := NewMerger(nil, lists, false, false, 0)61 mg := NewMerger(nil, lists, false, false, revision{}, 0)62 assert(t, cnt == mg.Length(), "Invalid Length")63 for i := 0; i < cnt; i++ {64 assert(t, items[i] == mg.Get(i), "Invalid Get")65 }
3 unmodified lines
69 lists, items := buildLists(true)70 cnt := len(items)7172 // Sorted sorted order72 mg := NewMerger(nil, lists, true, false, 0)73 mg := NewMerger(nil, lists, true, false, revision{}, 0)74 assert(t, cnt == mg.Length(), "Invalid Length")75 sort.Sort(ByRelevance(items))76 for i := 0; i < cnt; i++ {77 if items[i] != mg.Get(i) {
1 unmodified line
79 }80 }8182 // Inverse order82 mg2 := NewMerger(nil, lists, true, false, 0)83 mg2 := NewMerger(nil, lists, true, false, revision{}, 0)84 for i := cnt - 1; i >= 0; i-- {85 if items[i] != mg2.Get(i) {86 t.Error("Not sorted", items[i], mg2.Get(i))87 }
2 unmodified lines
modified:src/merger.go+23 added-9 removed
1 unmodified line
23import "fmt"45// EmptyMerger is a Merger with no data6func EmptyMerger(revision int) *Merger {7 return NewMerger(nil, [][]Result{}, false, false, revision)6func EmptyMerger(revision revision) *Merger {7 return NewMerger(nil, [][]Result{}, false, false, revision, 0)8}910// Merger holds a set of locally sorted lists of items and provides the view of11// a single, globally-sorted list
7 unmodified lines
19 tac bool20 final bool21 count int22 pass bool23 revision int23 revision revision24 minIndex int3225}2627// PassMerger returns a new Merger that simply returns the items in the28// original order28func PassMerger(chunks *[]*Chunk, tac bool, revision int) *Merger {29func PassMerger(chunks *[]*Chunk, tac bool, revision revision) *Merger {30 var minIndex int3231 if len(*chunks) > 0 {32 minIndex = (*chunks)[0].items[0].Index()33 }34 mg := Merger{35 pattern: nil,36 chunks: chunks,37 tac: tac,38 count: 0,39 pass: true,35 revision: revision}40 revision: revision,41 minIndex: minIndex}4243 for _, chunk := range *mg.chunks {44 mg.count += chunk.count45 }46 return &mg47}4849// NewMerger returns a new Merger44func NewMerger(pattern *Pattern, lists [][]Result, sorted bool, tac bool, revision int) *Merger {50func NewMerger(pattern *Pattern, lists [][]Result, sorted bool, tac bool, revision revision, minIndex int32) *Merger {51 mg := Merger{52 pattern: pattern,53 lists: lists,54 merged: []Result{},
2 unmodified lines
57 sorted: sorted,58 tac: tac,59 final: false,60 count: 0,55 revision: revision}61 revision: revision,62 minIndex: minIndex}6364 for _, list := range mg.lists {65 mg.count += len(list)66 }67 return &mg68}6970// Revision returns revision number64func (mg *Merger) Revision() int {71func (mg *Merger) Revision() revision {72 return mg.revision73}7475// Length returns the number of items
11 unmodified lines
87// FindIndex returns the index of the item with the given item index88func (mg *Merger) FindIndex(itemIndex int32) int {89 index := -190 if mg.pass {84 index = int(itemIndex)91 index = int(itemIndex - mg.minIndex)92 if mg.tac {93 index = mg.count - index - 194 }95 } else {
12 unmodified lines
108 if mg.chunks != nil {109 if mg.tac {110 idx = mg.count - idx - 1111 }112 firstChunk := (*mg.chunks)[0]113 if firstChunk.count < chunkSize && idx >= firstChunk.count {114 idx -= firstChunk.count115116 chunk := (*mg.chunks)[idx/chunkSize+1]117 return Result{item: &chunk.items[idx%chunkSize]}118 }119 chunk := (*mg.chunks)[idx/chunkSize]120 return Result{item: &chunk.items[idx%chunkSize]}121 }122
50 unmodified lines
modified:src/options.go+18 added
39 unmodified lines
40 --with-nth=N[,..] Transform the presentation of each line using41 field index expressions42 -d, --delimiter=STR Field delimiter regex (default: AWK-style)43 +s, --no-sort Do not sort the result44 --tail=NUM Maximum number of items to keep in memory45 --track Track the current selection when the result is updated46 --tac Reverse the order of the input47 --disabled Do not perform search48 --tiebreak=CRI[,..] Comma-separated list of sort criteria to apply
372 unmodified lines
421 Delimiter Delimiter422 Sort int423 Track trackOption424 Tac bool425 Tail int426 Criteria []criterion427 Multi int428 Ansi bool429 Mouse bool
1667 unmodified lines
2097 case "--tac":2098 opts.Tac = true2099 case "--no-tac":2100 opts.Tac = false2101 case "--tail":2102 if opts.Tail, err = nextInt(allArgs, &i, "number of items to keep required"); err != nil {2103 return err2104 }2105 if opts.Tail <= 0 {2106 return errors.New("number of items to keep must be a positive integer")2107 }2108 case "--no-tail":2109 opts.Tail = 02110 case "-i", "--ignore-case":2111 opts.Case = CaseIgnore2112 case "+i", "--no-ignore-case":2113 opts.Case = CaseRespect
527 unmodified lines
2641 }2642 } else if match, value := optString(arg, "--jump-labels="); match {2643 opts.JumpLabels = value2644 validateJumpLabels = true2645 } else if match, value := optString(arg, "--tail="); match {2646 if opts.Tail, err = atoi(value); err != nil {2647 return err2648 }2649 if opts.Tail <= 0 {2650 return errors.New("number of items to keep must be a positive integer")2651 }2652 } else {2653 return errors.New("unknown option: " + arg)2654 }2655 }
268 unmodified lines
modified:src/terminal.go+20 added-9 removed
158 unmodified lines
159 hasBar bool160 result Result161 empty bool162 other bool163 minIndex int32164}165166func (t *Terminal) markEmptyLine(line int) {167 t.prevLines[line] = itemLine{firstLine: line, empty: true}
133 unmodified lines
301 printsep string302 merger *Merger303 selected map[int32]selectedItem304 version int64304 revision int305 revision revision306 reqBox *util.EventBox307 initialPreviewOpts previewOpts308 previewOpts previewOpts309 activePreviewOpts *previewOpts
512 unmodified lines
822 jumpLabels: opts.JumpLabels,823 printer: opts.Printer,824 printsep: opts.PrintSep,825 proxyScript: opts.ProxyScript,825 merger: EmptyMerger(0),826 merger: EmptyMerger(revision{}),827 selected: make(map[int32]selectedItem),828 reqBox: util.NewEventBox(),829 initialPreviewOpts: opts.Preview,830 previewOpts: opts.Preview,
333 unmodified lines
1164// UpdateList updates Merger to display the list1165func (t *Terminal) UpdateList(merger *Merger, triggerResultEvent bool) {1166 t.mutex.Lock()1167 prevIndex := minItem.Index()1167 reset := t.revision != merger.Revision()1168 if !reset && t.track != trackDisabled {1168 newRevision := merger.Revision()1169 if t.revision.compatible(newRevision) && t.track != trackDisabled {1170 if t.merger.Length() > 0 {1171 prevIndex = t.currentIndex()1172 } else if merger.Length() > 0 {1173 prevIndex = merger.First().item.Index()1174 }1175 }1176 t.progress = 1001177 t.merger = merger1177 if reset {1178 t.selected = make(map[int32]selectedItem)1179 t.revision = merger.Revision()1178 if !t.revision.equals(newRevision) {1179 if !t.revision.compatible(newRevision) { // Reloaded: clear selection1180 t.selected = make(map[int32]selectedItem)1181 } else { // Trimmed by --tail: filter selection by index1182 filtered := make(map[int32]selectedItem)1183 for k, v := range t.selected {1184 if k >= merger.minIndex {1185 filtered[k] = v1186 }1187 }1188 t.selected = filtered1189 }1190 t.revision = newRevision1191 t.version++1192 }1193 if t.triggerLoad {1194 t.triggerLoad = false
774 unmodified lines
1969 }19701971 // Avoid unnecessary redraw1972 newLine := itemLine{firstLine: line, cy: index + t.offset, current: current, selected: selected, label: label,1962 result: result, queryLen: len(t.input), width: 0, hasBar: line >= barRange[0] && line < barRange[1]}1973 result: result, queryLen: len(t.input), width: 0, hasBar: line >= barRange[0] && line < barRange[1], minIndex: t.merger.minIndex}1974 prevLine := t.prevLines[line]1964 forceRedraw := prevLine.other || prevLine.firstLine != newLine.firstLine1975 forceRedraw := prevLine.other || prevLine.firstLine != newLine.firstLine || prevLine.minIndex != t.merger.minIndex1976 printBar := func(lineNum int, forceRedraw bool) bool {1977 return t.printBar(lineNum, forceRedraw, barRange)1978 }1979
2746 unmodified lines
modified:CHANGELOG.md+8 added-1 removed
40 unmodified lines
41 - To use `--tmux` in Vim plugin:42 ```vim43 let g:fzf_layout = { 'tmux': '100%,70%' }44 ```45- Better Windows Support45- (Windows) fzf now works on Git bash (mintty) out of the box via winpty integration46 - fzf now works on Git bash (mintty) out of the box via winpty integration47 - Many fixes and improvements for Windows48- Added `--tail=NUM` option to limit the number of items to keep in memory. This is useful when you want to browse an endless stream of data (e.g. log stream) with fzf while limiting memory usage.49 ```sh50 # Interactive filtering of a log stream51 tail -f *.log | fzf --tail 100000 --tac --no-sort --exact52 ```53- man page is now embedded in the binary; `fzf --man` to see it54- Changed the default `--scroll-off` to 3, as we think it's a better default55- Process started by `execute` action now directly writes to and reads from `/dev/tty`. Manual `/dev/tty` redirection for interactive programs is no longer required.56 ```sh
2092 unmodified lines