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
Provenance
- Commit
4bedd33- Tree
10ef749- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
c5fb0c4
7 files changed+85 added−76 removed
modified:src/ansi.go+1 added-1 removed
310 unmodified lines311 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 linesmodified:src/core.go+10 added-24 removed
2 unmodified lines3 4 import (5 "sync"6 "time"7- "unsafe"7 8 "github.com/junegunn/fzf/src/util"9 )10 5 unmodified lines16 Matcher -> EvtSearchFin -> Terminal (update list)17 Matcher -> EvtHeader -> Terminal (update header)18 */19 21-func ustring(data []byte) string {22- return unsafe.String(unsafe.SliceData(data), len(data))23-}24-25-func sbytes(data string) []byte {26- return unsafe.Slice(unsafe.StringData(data), len(data))27-}28-29-type quitSignal struct {30- code int31- err error32-}33-20 // Run starts fzf21 func Run(opts *Options) (int, error) {22 if err := postProcessOptions(opts); err != nil {23 return ExitError, err23 unmodified lines47 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 lines68 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 lines79 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 := *prevLineAnsiState15 unmodified lines103 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 lines226 227 // 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 lines247 248 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 lines313 }314 matcher.Reset(snapshot, input(), false, !reading, sort, snapshotRevision)315 316 case EvtSearchNew:331- var command *string317+ var command *commandSpec318 var environ []string319 var changed bool320 switch val := value.(type) {321 case searchRequest:91 unmodified linesadded:src/functions.go+35 added
1+package fzf2+3+import (4+ "os"5+ "strings"6+ "unsafe"7+)8+9+func 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()17+18+ f.WriteString(strings.Join(data, printSep))19+ f.WriteString(printSep)20+ return f.Name()21+}22+23+func removeFiles(files []string) {24+ for _, filename := range files {25+ os.Remove(filename)26+ }27+}28+29+func stringBytes(data string) []byte {30+ return unsafe.Slice(unsafe.StringData(data), len(data))31+}32+33+func byteString(data []byte) string {34+ return unsafe.String(unsafe.SliceData(data), len(data))35+}modified:src/reader.go+3 added-2 removed
84 unmodified lines85 }86 r.mutex.Unlock()87 }88 89-func (r *Reader) restart(command string, environ []string) {89+func (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 }96 97 func (r *Reader) readChannel(inputChan chan string) bool {98 for {180 unmodified linesmodified:src/terminal_test.go+2 added-1 removed
11 unmodified lines12 "github.com/junegunn/fzf/src/util"13 )14 15 func 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 lines24 lastAction: actBackwardDeleteCharEof,25 prompt: "prompt",26 executor: util.NewExecutor(""),27 })28+ return replaced29 }30 31 func TestReplacePlaceholder(t *testing.T) {32 item1 := newItem(" foo'bar \x1b[31mbaz\x1b[m")627 unmodified linesmodified:src/terminal.go+32 added-46 removed
48 unmodified lines49 var placeholder *regexp.Regexp50 var whiteSuffix *regexp.Regexp51 var offsetComponentRegex *regexp.Regexp52 var offsetTrimCharsRegex *regexp.Regexp53-var activeTempFiles []string54-var activeTempFilesMutex sync.Mutex53 var passThroughRegex *regexp.Regexp54 55 const clearCode string = "\x1b[2J"56 4 unmodified lines61 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{}65 66 // 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-protocol41 unmodified lines110 *s = pausedState111 }112 }113 114+type commandSpec struct {115+ command string116+ tempFiles []string117+}118+119+type quitSignal struct {120+ code int121+ err error122+}123+124 type previewer struct {125 version int64126 lines []string127 offset int384 unmodified lines512 513 type searchRequest struct {514 sort bool515 sync bool510- command *string516+ command *commandSpec517 environ []string518 changed bool519 }520 2014 unmodified lines2535 }2536 return2537 }2538 2533-func 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()2541-2542- 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-}2549-2550-func cleanTemporaryFiles() {2551- activeTempFilesMutex.Lock()2552- for _, filename := range activeTempFiles {2553- os.Remove(filename)2554- }2555- activeTempFiles = []string{}2556- activeTempFilesMutex.Unlock()2557-}2558-2539 type replacePlaceholderParams struct {2540 template string2541 stripAnsi bool2542 delimiter Delimiter5 unmodified lines2548 prompt string2549 executor *util.Executor2550 }2551 2572-func (t *Terminal) replacePlaceholder(template string, forcePlus bool, input string, list []*Item) string {2552+func (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 lines2569 return 02570 }2571 2572 // 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, "")2576 2577 atoi := func(s string) int {2578 n, e := strconv.Atoi(s)2579 if e != nil {19 unmodified lines2599 }2600 return util.Max(0, base)2601 }2602 2622-func replacePlaceholder(params replacePlaceholderParams) string {2603+func 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 lines2611 selected = []*Item{}2612 }2613 2614 // 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)2617 2618 // this function implements the effects a placeholder has on items2619 var replace func(*Item) string74 unmodified lines2694 replacements[idx] = replace(item)2695 }2696 2697 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 })2704+2705+ return replaced, tempFiles2706 }2707 2708 func (t *Terminal) redraw() {2709 t.tui.Clear()8 unmodified lines2718 // 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 lines2749 cmd.Run()2750 }2751 }2752 t.executing.Set(false)2767- cleanTemporaryFiles()2753+ removeFiles(tempFiles)2754 return line2755 }2756 2757 func (t *Terminal) hasPreviewer() bool {269 unmodified lines3027 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 lines3149 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 }3171-3172- cleanTemporaryFiles()3158 } else {3159 t.reqBox.Set(reqPreviewDisplay, previewResult{version, nil, 0, ""})3160 }3161 }165 unmodified lines3327 barDragging := false3328 pbarDragging := false3329 wasDown := false3330 for looping {3346- var newCommand *string3331+ var newCommand *commandSpec3332 var reloadSync bool3333 changed := false3334 beof := false3335 queryChanged := false116 unmodified lines3452 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 lines4125 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 linesmodified:src/tokenizer.go+2 added-2 removed
89 unmodified lines90 ret := make([]Token, len(tokens))91 92 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 ret87 unmodified lines186 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 + 159 unmodified lines