Skip to content
Myr

Refactor the code to remove global variables

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 c5fb0c4 · Browse files · 7 files+85 added−76 removed
This commit

State

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

Diff stats

7 files+85 added−76 removed

  • other:+85 added−76 removed

7 files+85 added−76 removed

modified:src/ansi.go+1 added-1 removed
310 unmodified lines
311 if len(s) > 0 {312 // Inlined version of strconv.Atoi() that only handles positive313 // integers and does not allocate on error.314 code := 0315 for _, ch := range sbytes(s) {315 for _, ch := range stringBytes(s) {316 ch -= '0'317 if ch > 9 {318 return -1, delimiter, remaining319 }
132 unmodified lines
modified:src/core.go+10 added-24 removed
2 unmodified lines
34import (5 "sync"6 "time"7 "unsafe"78 "github.com/junegunn/fzf/src/util"9)10
5 unmodified lines
16Matcher -> EvtSearchFin -> Terminal (update list)17Matcher -> EvtHeader -> Terminal (update header)18*/1921func ustring(data []byte) string {22 return unsafe.String(unsafe.SliceData(data), len(data))23}2425func sbytes(data string) []byte {26 return unsafe.Slice(unsafe.StringData(data), len(data))27}2829type quitSignal struct {30 code int31 err error32}3320// Run starts fzf21func Run(opts *Options) (int, error) {22 if err := postProcessOptions(opts); err != nil {23 return ExitError, err
23 unmodified lines
47 if opts.Ansi {48 if opts.Theme.Colored {49 ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {50 prevLineAnsiState = lineAnsiState65 trimmed, offsets, newState := extractColor(ustring(data), lineAnsiState, nil)51 trimmed, offsets, newState := extractColor(byteString(data), lineAnsiState, nil)52 lineAnsiState = newState67 return util.ToChars(sbytes(trimmed)), offsets53 return util.ToChars(stringBytes(trimmed)), offsets54 }55 } else {56 // When color is disabled but ansi option is given,57 // we simply strip out ANSI codes from the input58 ansiProcessor = func(data []byte) (util.Chars, *[]ansiOffset) {73 trimmed, _, _ := extractColor(ustring(data), nil, nil)74 return util.ToChars(sbytes(trimmed)), nil59 trimmed, _, _ := extractColor(byteString(data), nil, nil)60 return util.ToChars(stringBytes(trimmed)), nil61 }62 }63 }64
3 unmodified lines
68 header := make([]string, 0, opts.HeaderLines)69 if len(opts.WithNth) == 0 {70 chunkList = NewChunkList(func(item *Item, data []byte) bool {71 if len(header) < opts.HeaderLines {86 header = append(header, ustring(data))72 header = append(header, byteString(data))73 eventBox.Set(EvtHeader, header)74 return false75 }76 item.text, item.colors = ansiProcessor(data)
2 unmodified lines
79 return true80 })81 } else {82 chunkList = NewChunkList(func(item *Item, data []byte) bool {97 tokens := Tokenize(ustring(data), opts.Delimiter)83 tokens := Tokenize(byteString(data), opts.Delimiter)84 if opts.Ansi && opts.Theme.Colored && len(tokens) > 1 {85 var ansiState *ansiState86 if prevLineAnsiState != nil {87 ansiStateDup := *prevLineAnsiState
15 unmodified lines
103 header = append(header, transformed)104 eventBox.Set(EvtHeader, header)105 return false106 }121 item.text, item.colors = ansiProcessor(sbytes(transformed))107 item.text, item.colors = ansiProcessor(stringBytes(transformed))108 item.text.TrimTrailingWhitespaces()109 item.text.Index = itemIndex110 item.origText = &data111 itemIndex++
114 unmodified lines
226227 // Event coordination228 reading := true229 ticks := 0244 var nextCommand *string230 var nextCommand *commandSpec231 var nextEnviron []string232 eventBox.Watch(EvtReadNew)233 total := 0234 query := []rune{}
12 unmodified lines
247248 useSnapshot := false249 var snapshot []*Chunk250 var count int265 restart := func(command string, environ []string) {251 restart := func(command commandSpec, environ []string) {252 reading = true253 chunkList.Clear()254 itemIndex = 0255 inputRevision++
57 unmodified lines
313 }314 matcher.Reset(snapshot, input(), false, !reading, sort, snapshotRevision)315316 case EvtSearchNew:331 var command *string317 var command *commandSpec318 var environ []string319 var changed bool320 switch val := value.(type) {321 case searchRequest:
91 unmodified lines
added:src/functions.go+35 added
1package fzf23import (4 "os"5 "strings"6 "unsafe"7)89func writeTemporaryFile(data []string, printSep string) string {10 f, err := os.CreateTemp("", "fzf-preview-*")11 if err != nil {12 // Unable to create temporary file13 // FIXME: Should we terminate the program?14 return ""15 }16 defer f.Close()1718 f.WriteString(strings.Join(data, printSep))19 f.WriteString(printSep)20 return f.Name()21}2223func removeFiles(files []string) {24 for _, filename := range files {25 os.Remove(filename)26 }27}2829func stringBytes(data string) []byte {30 return unsafe.Slice(unsafe.StringData(data), len(data))31}3233func byteString(data []byte) string {34 return unsafe.String(unsafe.SliceData(data), len(data))35}
modified:src/reader.go+3 added-2 removed
84 unmodified lines
85 }86 r.mutex.Unlock()87}8889func (r *Reader) restart(command string, environ []string) {89func (r *Reader) restart(command commandSpec, environ []string) {90 r.event = int32(EvtReady)91 r.startEventPoller()92 success := r.readFromCommand(command, environ)92 success := r.readFromCommand(command.command, environ)93 r.fin(success)94 removeFiles(command.tempFiles)95}9697func (r *Reader) readChannel(inputChan chan string) bool {98 for {
180 unmodified lines
modified:src/terminal_test.go+2 added-1 removed
11 unmodified lines
12 "github.com/junegunn/fzf/src/util"13)1415func replacePlaceholderTest(template string, stripAnsi bool, delimiter Delimiter, printsep string, forcePlus bool, query string, allItems []*Item) string {16 return replacePlaceholder(replacePlaceholderParams{16 replaced, _ := replacePlaceholder(replacePlaceholderParams{17 template: template,18 stripAnsi: stripAnsi,19 delimiter: delimiter,20 printsep: printsep,
3 unmodified lines
24 lastAction: actBackwardDeleteCharEof,25 prompt: "prompt",26 executor: util.NewExecutor(""),27 })28 return replaced29}3031func TestReplacePlaceholder(t *testing.T) {32 item1 := newItem(" foo'bar \x1b[31mbaz\x1b[m")
627 unmodified lines
modified:src/terminal.go+32 added-46 removed
48 unmodified lines
49var placeholder *regexp.Regexp50var whiteSuffix *regexp.Regexp51var offsetComponentRegex *regexp.Regexp52var offsetTrimCharsRegex *regexp.Regexp53var activeTempFiles []string54var activeTempFilesMutex sync.Mutex53var passThroughRegex *regexp.Regexp5455const clearCode string = "\x1b[2J"56
4 unmodified lines
61 placeholder = regexp.MustCompile(`\\?(?:{[+sf]*[0-9,-.]*}|{q}|{fzf:(?:query|action|prompt)}|{\+?f?nf?})`)62 whiteSuffix = regexp.MustCompile(`\s*$`)63 offsetComponentRegex = regexp.MustCompile(`([+-][0-9]+)|(-?/[1-9][0-9]*)`)64 offsetTrimCharsRegex = regexp.MustCompile(`[^0-9/+-]`)67 activeTempFiles = []string{}68 activeTempFilesMutex = sync.Mutex{}6566 // Parts of the preview output that should be passed through to the terminal67 // * https://github.com/tmux/tmux/wiki/FAQ#what-is-the-passthrough-escape-sequence-and-how-do-i-use-it68 // * https://sw.kovidgoyal.net/kitty/graphics-protocol
41 unmodified lines
110 *s = pausedState111 }112}113114type commandSpec struct {115 command string116 tempFiles []string117}118119type quitSignal struct {120 code int121 err error122}123124type previewer struct {125 version int64126 lines []string127 offset int
384 unmodified lines
512513type searchRequest struct {514 sort bool515 sync bool510 command *string516 command *commandSpec517 environ []string518 changed bool519}520
2014 unmodified lines
2535 }2536 return2537}25382533func writeTemporaryFile(data []string, printSep string) string {2534 f, err := os.CreateTemp("", "fzf-preview-*")2535 if err != nil {2536 // Unable to create temporary file2537 // FIXME: Should we terminate the program?2538 return ""2539 }2540 defer f.Close()25412542 f.WriteString(strings.Join(data, printSep))2543 f.WriteString(printSep)2544 activeTempFilesMutex.Lock()2545 activeTempFiles = append(activeTempFiles, f.Name())2546 activeTempFilesMutex.Unlock()2547 return f.Name()2548}25492550func cleanTemporaryFiles() {2551 activeTempFilesMutex.Lock()2552 for _, filename := range activeTempFiles {2553 os.Remove(filename)2554 }2555 activeTempFiles = []string{}2556 activeTempFilesMutex.Unlock()2557}25582539type replacePlaceholderParams struct {2540 template string2541 stripAnsi bool2542 delimiter Delimiter
5 unmodified lines
2548 prompt string2549 executor *util.Executor2550}25512572func (t *Terminal) replacePlaceholder(template string, forcePlus bool, input string, list []*Item) string {2552func (t *Terminal) replacePlaceholder(template string, forcePlus bool, input string, list []*Item) (string, []string) {2553 return replacePlaceholder(replacePlaceholderParams{2554 template: template,2555 stripAnsi: t.ansi,2556 delimiter: t.delimiter,
12 unmodified lines
2569 return 02570 }25712572 // We only need the current item to calculate the scroll offset2593 offsetExpr := offsetTrimCharsRegex.ReplaceAllString(2594 t.replacePlaceholder(t.previewOpts.scroll, false, "", []*Item{t.currentItem(), nil}), "")2573 replaced, tempFiles := t.replacePlaceholder(t.previewOpts.scroll, false, "", []*Item{t.currentItem(), nil})2574 removeFiles(tempFiles)2575 offsetExpr := offsetTrimCharsRegex.ReplaceAllString(replaced, "")25762577 atoi := func(s string) int {2578 n, e := strconv.Atoi(s)2579 if e != nil {
19 unmodified lines
2599 }2600 return util.Max(0, base)2601}26022622func replacePlaceholder(params replacePlaceholderParams) string {2603func replacePlaceholder(params replacePlaceholderParams) (string, []string) {2604 tempFiles := []string{}2605 current := params.allItems[:1]2606 selected := params.allItems[1:]2607 if current[0] == nil {2608 current = []*Item{}
2 unmodified lines
2611 selected = []*Item{}2612 }26132614 // replace placeholders one by one2633 return placeholder.ReplaceAllStringFunc(params.template, func(match string) string {2615 replaced := placeholder.ReplaceAllStringFunc(params.template, func(match string) string {2616 escaped, match, flags := parsePlaceholder(match)26172618 // this function implements the effects a placeholder has on items2619 var replace func(*Item) string
74 unmodified lines
2694 replacements[idx] = replace(item)2695 }26962697 if flags.file {2716 return writeTemporaryFile(replacements, params.printsep)2698 file := writeTemporaryFile(replacements, params.printsep)2699 tempFiles = append(tempFiles, file)2700 return file2701 }2702 return strings.Join(replacements, " ")2703 })27042705 return replaced, tempFiles2706}27072708func (t *Terminal) redraw() {2709 t.tui.Clear()
8 unmodified lines
2718 // return an empty string in those cases2719 if !valid && !capture {2720 return line2721 }2736 command := t.replacePlaceholder(template, forcePlus, string(t.input), list)2722 command, tempFiles := t.replacePlaceholder(template, forcePlus, string(t.input), list)2723 cmd := t.executor.ExecCommand(command, false)2724 cmd.Env = t.environ()2725 t.executing.Set(true)2726 if !background {
22 unmodified lines
2749 cmd.Run()2750 }2751 }2752 t.executing.Set(false)2767 cleanTemporaryFiles()2753 removeFiles(tempFiles)2754 return line2755}27562757func (t *Terminal) hasPreviewer() bool {
269 unmodified lines
3027 version++3028 // We don't display preview window if no match3029 if items[0] != nil {3030 _, query := t.Input()3045 command := t.replacePlaceholder(commandTemplate, false, string(query), items)3031 command, tempFiles := t.replacePlaceholder(commandTemplate, false, string(query), items)3032 cmd := t.executor.ExecCommand(command, true)3033 if pwindowSize.Lines > 0 {3034 lines := fmt.Sprintf("LINES=%d", pwindowSize.Lines)3035 columns := fmt.Sprintf("COLUMNS=%d", pwindowSize.Columns)
113 unmodified lines
3149 cmd.Wait() // NOTE: We should not call Wait before EOF3150 finishChan <- true // Tell Goroutine 3 to stop3151 <-reapChan // Goroutine 2 and 3 finished3152 <-reapChan3153 removeFiles(tempFiles)3154 } else {3155 // Failed to start the command. Report the error immediately.3156 t.reqBox.Set(reqPreviewDisplay, previewResult{version, []string{err.Error()}, 0, ""})3157 }31713172 cleanTemporaryFiles()3158 } else {3159 t.reqBox.Set(reqPreviewDisplay, previewResult{version, nil, 0, ""})3160 }3161 }
165 unmodified lines
3327 barDragging := false3328 pbarDragging := false3329 wasDown := false3330 for looping {3346 var newCommand *string3331 var newCommand *commandSpec3332 var reloadSync bool3333 changed := false3334 beof := false3335 queryChanged := false
116 unmodified lines
3452 t.serverOutputChan <- t.dumpStatus(parseGetParams(a.a))3453 case actBecome:3454 valid, list := t.buildPlusList(a.a, false)3455 if valid {3456 // We do not remove temp files in this case3471 command := t.replacePlaceholder(a.a, false, string(t.input), list)3457 command, _ := t.replacePlaceholder(a.a, false, string(t.input), list)3458 t.tui.Close()3459 if t.history != nil {3460 t.history.append(string(t.input))3461 }
663 unmodified lines
4125 slot, _, forceUpdate := hasPreviewFlags(a.a)4126 valid = !slot || forceUpdate4127 }4128 if valid {4143 command := t.replacePlaceholder(a.a, false, string(t.input), list)4144 newCommand = &command4129 command, tempFiles := t.replacePlaceholder(a.a, false, string(t.input), list)4130 newCommand = &commandSpec{command, tempFiles}4131 reloadSync = a.t == actReloadSync4132 t.reading = true4133 }4134 case actUnbind:
267 unmodified lines
modified:src/tokenizer.go+2 added-2 removed
89 unmodified lines
90 ret := make([]Token, len(tokens))9192 prefixLength := begin93 for idx := range tokens {94 chars := util.ToChars(sbytes(tokens[idx]))94 chars := util.ToChars(stringBytes(tokens[idx]))95 ret[idx] = Token{&chars, int32(prefixLength)}96 prefixLength += chars.Length()97 }98 return ret
87 unmodified lines
186 minIdx := 0187 if r.begin == r.end {188 idx := r.begin189 if idx == rangeEllipsis {190 chars := util.ToChars(sbytes(joinTokens(tokens)))190 chars := util.ToChars(stringBytes(joinTokens(tokens)))191 parts = append(parts, &chars)192 } else {193 if idx < 0 {194 idx += numTokens + 1
59 unmodified lines