Skip to content
Myr

Refactor the code so that fzf can be used as a library (#3769)

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

authored by Junegunn Choi · committed by GitHub · parent 065b9e6 · Browse files · 32 files+1150 added−891 removed
This commit

State

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

Diff stats

32 files+1150 added−891 removed

  • tests:+1 added−1 removed
  • other:+1149 added−890 removed

32 files+1150 added−891 removed

modified:src/algo/algo.go+1 added-1 removed
150 unmodified lines
151152 // Extra bonus for word boundary after slash, colon, semi-colon, and comma153 bonusBoundaryDelimiter int16 = bonusBoundary + 1154155 initialCharClass charClass = charWhite155 initialCharClass = charWhite156157 // A minor optimization that can give 15%+ performance boost158 asciiCharClasses [unicode.MaxASCII + 1]charClass159
825 unmodified lines
modified:src/algo/normalize.go+1 added-1 removed
1 unmodified line
2// Reference: http://www.unicode.org/Public/UCD/latest/ucd/Index.txt34package algo56var normalized map[rune]rune = map[rune]rune{6var normalized = map[rune]rune{7 0x00E1: 'a', // WITH ACUTE, LATIN SMALL LETTER8 0x0103: 'a', // WITH BREVE, LATIN SMALL LETTER9 0x01CE: 'a', // WITH CARON, LATIN SMALL LETTER10 0x00E2: 'a', // WITH CIRCUMFLEX, LATIN SMALL LETTER
482 unmodified lines
modified:src/protector/protector.go+1 added-3 removed
1 unmodified line
23package protector45// Protect calls OS specific protections like pledge on OpenBSD6func Protect() {7 return8}6func Protect() {}
modified:src/tui/dummy.go+2 added-2 removed
6 unmodified lines
7func HasFullscreenRenderer() bool {8 return false9}1011var DefaultBorderShape BorderShape = BorderRounded11var DefaultBorderShape = BorderRounded1213func (a Attr) Merge(b Attr) Attr {14 return a | b15}
12 unmodified lines
28 Reverse = Attr(1 << 6)29 StrikeThrough = Attr(1 << 7)30)3132func (r *FullscreenRenderer) Init() {}32func (r *FullscreenRenderer) Init() error { return nil }33func (r *FullscreenRenderer) Resize(maxHeightFunc func(int) int) {}34func (r *FullscreenRenderer) Pause(bool) {}35func (r *FullscreenRenderer) Resume(bool, bool) {}36func (r *FullscreenRenderer) PassThrough(string) {}
17 unmodified lines
modified:src/tui/eventtype_string.go+26 added-25 removed
81 unmodified lines
82 _ = x[AltShiftRight-71]83 _ = x[Alt-72]84 _ = x[CtrlAlt-73]85 _ = x[Invalid-74]86 _ = x[Mouse-75]87 _ = x[DoubleClick-76]88 _ = x[LeftClick-77]89 _ = x[RightClick-78]90 _ = x[SLeftClick-79]91 _ = x[SRightClick-80]92 _ = x[ScrollUp-81]93 _ = x[ScrollDown-82]94 _ = x[SScrollUp-83]95 _ = x[SScrollDown-84]96 _ = x[PreviewScrollUp-85]97 _ = x[PreviewScrollDown-86]98 _ = x[Resize-87]99 _ = x[Change-88]100 _ = x[BackwardEOF-89]101 _ = x[Start-90]102 _ = x[Load-91]103 _ = x[Focus-92]104 _ = x[One-93]105 _ = x[Zero-94]106 _ = x[Result-95]107 _ = x[Jump-96]108 _ = x[JumpCancel-97]86 _ = x[Fatal-75]87 _ = x[Mouse-76]88 _ = x[DoubleClick-77]89 _ = x[LeftClick-78]90 _ = x[RightClick-79]91 _ = x[SLeftClick-80]92 _ = x[SRightClick-81]93 _ = x[ScrollUp-82]94 _ = x[ScrollDown-83]95 _ = x[SScrollUp-84]96 _ = x[SScrollDown-85]97 _ = x[PreviewScrollUp-86]98 _ = x[PreviewScrollDown-87]99 _ = x[Resize-88]100 _ = x[Change-89]101 _ = x[BackwardEOF-90]102 _ = x[Start-91]103 _ = x[Load-92]104 _ = x[Focus-93]105 _ = x[One-94]106 _ = x[Zero-95]107 _ = x[Result-96]108 _ = x[Jump-97]109 _ = x[JumpCancel-98]110}111111const _EventType_name = "RuneCtrlACtrlBCtrlCCtrlDCtrlECtrlFCtrlGCtrlHTabCtrlJCtrlKCtrlLCtrlMCtrlNCtrlOCtrlPCtrlQCtrlRCtrlSCtrlTCtrlUCtrlVCtrlWCtrlXCtrlYCtrlZEscCtrlSpaceCtrlDeleteCtrlBackSlashCtrlRightBracketCtrlCaretCtrlSlashShiftTabBackspaceDeletePageUpPageDownUpDownLeftRightHomeEndInsertShiftUpShiftDownShiftLeftShiftRightShiftDeleteF1F2F3F4F5F6F7F8F9F10F11F12AltBackspaceAltUpAltDownAltLeftAltRightAltShiftUpAltShiftDownAltShiftLeftAltShiftRightAltCtrlAltInvalidMouseDoubleClickLeftClickRightClickSLeftClickSRightClickScrollUpScrollDownSScrollUpSScrollDownPreviewScrollUpPreviewScrollDownResizeChangeBackwardEOFStartLoadFocusOneZeroResultJumpJumpCancel"112const _EventType_name = "RuneCtrlACtrlBCtrlCCtrlDCtrlECtrlFCtrlGCtrlHTabCtrlJCtrlKCtrlLCtrlMCtrlNCtrlOCtrlPCtrlQCtrlRCtrlSCtrlTCtrlUCtrlVCtrlWCtrlXCtrlYCtrlZEscCtrlSpaceCtrlDeleteCtrlBackSlashCtrlRightBracketCtrlCaretCtrlSlashShiftTabBackspaceDeletePageUpPageDownUpDownLeftRightHomeEndInsertShiftUpShiftDownShiftLeftShiftRightShiftDeleteF1F2F3F4F5F6F7F8F9F10F11F12AltBackspaceAltUpAltDownAltLeftAltRightAltShiftUpAltShiftDownAltShiftLeftAltShiftRightAltCtrlAltInvalidFatalMouseDoubleClickLeftClickRightClickSLeftClickSRightClickScrollUpScrollDownSScrollUpSScrollDownPreviewScrollUpPreviewScrollDownResizeChangeBackwardEOFStartLoadFocusOneZeroResultJumpJumpCancel"113113var _EventType_index = [...]uint16{0, 4, 9, 14, 19, 24, 29, 34, 39, 44, 47, 52, 57, 62, 67, 72, 77, 82, 87, 92, 97, 102, 107, 112, 117, 122, 127, 132, 135, 144, 154, 167, 183, 192, 201, 209, 218, 224, 230, 238, 240, 244, 248, 253, 257, 260, 266, 273, 282, 291, 301, 312, 314, 316, 318, 320, 322, 324, 326, 328, 330, 333, 336, 339, 351, 356, 363, 370, 378, 388, 400, 412, 425, 428, 435, 442, 447, 458, 467, 477, 487, 498, 506, 516, 525, 536, 551, 568, 574, 580, 591, 596, 600, 605, 608, 612, 618, 622, 632}114var _EventType_index = [...]uint16{0, 4, 9, 14, 19, 24, 29, 34, 39, 44, 47, 52, 57, 62, 67, 72, 77, 82, 87, 92, 97, 102, 107, 112, 117, 122, 127, 132, 135, 144, 154, 167, 183, 192, 201, 209, 218, 224, 230, 238, 240, 244, 248, 253, 257, 260, 266, 273, 282, 291, 301, 312, 314, 316, 318, 320, 322, 324, 326, 328, 330, 333, 336, 339, 351, 356, 363, 370, 378, 388, 400, 412, 425, 428, 435, 442, 447, 452, 463, 472, 482, 492, 503, 511, 521, 530, 541, 556, 573, 579, 585, 596, 601, 605, 610, 613, 617, 623, 627, 637}115116func (i EventType) String() string {117 if i < 0 || i >= EventType(len(_EventType_index)-1) {118 return "EventType(" + strconv.FormatInt(int64(i), 10) + ")"
3 unmodified lines
modified:src/tui/light_unix.go+11 added-7 removed
1 unmodified line
23package tui45import (6 "fmt"6 "errors"7 "os"8 "os/exec"9 "strings"10 "syscall"
36 unmodified lines
47func (r *LightRenderer) closePlatform() {48 // NOOP49}5051func openTtyIn() *os.File {51func openTtyIn() (*os.File, error) {52 in, err := os.OpenFile(consoleDevice, syscall.O_RDONLY, 0)53 if err != nil {54 tty := ttyname()55 if len(tty) > 0 {56 if in, err := os.OpenFile(tty, syscall.O_RDONLY, 0); err == nil {57 return in57 return in, nil58 }59 }60 fmt.Fprintln(os.Stderr, "Failed to open "+consoleDevice)61 util.Exit(2)60 return nil, errors.New("failed to open " + consoleDevice)61 }63 return in62 return in, nil63}6465func (r *LightRenderer) setupTerminal() {66 term.MakeRaw(r.fd())
17 unmodified lines
8485func (r *LightRenderer) findOffset() (row int, col int) {86 r.csi("6n")87 r.flush()88 var err error89 bytes := []byte{}90 for tries := 0; tries < offsetPollTries; tries++ {91 bytes = r.getBytesInternal(bytes, tries > 0)91 bytes, err = r.getBytesInternal(bytes, tries > 0)92 if err != nil {93 return -1, -194 }9596 offsets := offsetRegexp.FindSubmatch(bytes)97 if len(offsets) > 3 {98 // Add anything we skipped over to the input buffer99 r.buffer = append(r.buffer, offsets[1]...)
24 unmodified lines
modified:src/tui/light_windows.go+3 added-3 removed
70 unmodified lines
71 // syscall.SetNonblock() is a NOOP under Windows.72 go func() {73 fd := int(r.inHandle)74 b := make([]byte, 1)75 for {75 for !r.closed.Get() {76 // HACK: if run from PSReadline, something resets ConsoleMode to remove ENABLE_VIRTUAL_TERMINAL_INPUT.77 _ = windows.SetConsoleMode(windows.Handle(r.inHandle), consoleFlagsInput)7879 _, err := util.Read(fd, b)
10 unmodified lines
90 windows.SetConsoleMode(windows.Handle(r.outHandle), r.origStateOutput)91 windows.SetConsoleMode(windows.Handle(r.inHandle), r.origStateInput)92}9394func openTtyIn() *os.File {94func openTtyIn() (*os.File, error) {95 // not used96 return nil96 return nil, nil97}9899func (r *LightRenderer) setupTerminal() error {100 if err := windows.SetConsoleMode(windows.Handle(r.outHandle), consoleFlagsOutput); err != nil {
53 unmodified lines
modified:src/tui/light.go+33 added-16 removed
1package tui23import (4 "bytes"5 "errors"6 "fmt"7 "os"8 "regexp"9 "strconv"10 "strings"11 "time"12 "unicode/utf8"1314 "github.com/junegunn/fzf/src/util"15 "github.com/rivo/uniseg"1617 "golang.org/x/term"18)
9 unmodified lines
28)2930const consoleDevice string = "/dev/tty"3130var offsetRegexp *regexp.Regexp = regexp.MustCompile("(.*)\x1b\\[([0-9]+);([0-9]+)R")31var offsetRegexpBegin *regexp.Regexp = regexp.MustCompile("^\x1b\\[[0-9]+;[0-9]+R")32var offsetRegexp = regexp.MustCompile("(.*)\x1b\\[([0-9]+);([0-9]+)R")33var offsetRegexpBegin = regexp.MustCompile("^\x1b\\[[0-9]+;[0-9]+R")3435func (r *LightRenderer) PassThrough(str string) {36 r.queued.WriteString("\x1b7" + str + "\x1b8")37}
41 unmodified lines
79}8081// Light renderer82type LightRenderer struct {83 closed *util.AtomicBool84 theme *ColorTheme85 mouse bool86 forceBlack bool87 clearOnExit bool
37 unmodified lines
125 fg Color126 bg Color127}128126func NewLightRenderer(theme *ColorTheme, forceBlack bool, mouse bool, tabstop int, clearOnExit bool, fullscreen bool, maxHeightFunc func(int) int) Renderer {129func NewLightRenderer(theme *ColorTheme, forceBlack bool, mouse bool, tabstop int, clearOnExit bool, fullscreen bool, maxHeightFunc func(int) int) (Renderer, error) {130 in, err := openTtyIn()131 if err != nil {132 return nil, err133 }134 r := LightRenderer{135 closed: util.NewAtomicBool(false),136 theme: theme,137 forceBlack: forceBlack,138 mouse: mouse,139 clearOnExit: clearOnExit,132 ttyin: openTtyIn(),140 ttyin: in,141 yoffset: 0,142 tabstop: tabstop,143 fullscreen: fullscreen,144 upOneLine: false,145 maxHeightFunc: maxHeightFunc}138 return &r146 return &r, nil147}148149func repeat(r rune, times int) string {150 if times > 0 {
9 unmodified lines
160 }161 return value162}163156func (r *LightRenderer) Init() {164func (r *LightRenderer) Init() error {165 r.escDelay = atoi(os.Getenv("ESCDELAY"), defaultEscDelay)166167 if err := r.initPlatform(); err != nil {160 errorExit(err.Error())168 return err169 }170 r.updateTerminalSize()171 initTheme(r.theme, r.defaultTheme(), r.forceBlack)172
29 unmodified lines
202 }203 if !r.fullscreen && r.mouse {204 r.yoffset, _ = r.findOffset()205 }206 return nil207}208209func (r *LightRenderer) Resize(maxHeightFunc func(int) int) {210 r.maxHeightFunc = maxHeightFunc
30 unmodified lines
241 }242 return atoi(env, defaultValue)243}244236func (r *LightRenderer) getBytes() []byte {237 return r.getBytesInternal(r.buffer, false)245func (r *LightRenderer) getBytes() ([]byte, error) {246 bytes, err := r.getBytesInternal(r.buffer, false)247 return bytes, err248}249240func (r *LightRenderer) getBytesInternal(buffer []byte, nonblock bool) []byte {250func (r *LightRenderer) getBytesInternal(buffer []byte, nonblock bool) ([]byte, error) {251 c, ok := r.getch(nonblock)252 if !nonblock && !ok {253 r.Close()244 errorExit("Failed to read " + consoleDevice)254 return nil, errors.New("failed to read " + consoleDevice)255 }256257 retries := 0258 if c == Esc.Int() || nonblock {
22 unmodified lines
281 // This should never happen under normal conditions,282 // so terminate fzf immediately.283 if len(buffer) > maxInputBuffer {284 r.Close()275 panic(fmt.Sprintf("Input buffer overflow (%d): %v", len(buffer), buffer))285 return nil, fmt.Errorf("input buffer overflow (%d): %v", len(buffer), buffer)286 }287 }288279 return buffer289 return buffer, nil290}291292func (r *LightRenderer) GetChar() Event {293 var err error294 if len(r.buffer) == 0 {284 r.buffer = r.getBytes()295 r.buffer, err = r.getBytes()296 if err != nil {297 return Event{Fatal, 0, nil}298 }299 }300 if len(r.buffer) == 0 {287 panic("Empty buffer")301 return Event{Fatal, 0, nil}302 }303304 sz := 1305 defer func() {
22 unmodified lines
328 case Esc.Byte():329 ev := r.escSequence(&sz)330 // Second chance331 if ev.Type == Invalid {318 r.buffer = r.getBytes()332 if r.buffer, err = r.getBytes(); err != nil {333 return Event{Fatal, 0, nil}334 }335 ev = r.escSequence(&sz)336 }337 return ev338 }
414 unmodified lines
753 r.disableMouse()754 r.flush()755 r.closePlatform()756 r.restoreTerminal()757 r.closed.Set(true)758}759760func (r *LightRenderer) Top() int {761 return r.yoffset
394 unmodified lines
modified:src/tui/tcell.go+11 added-7 removed
5 unmodified lines
6 "os"7 "time"89 "github.com/gdamore/tcell/v2"10 "github.com/gdamore/tcell/v2/encoding"10 "github.com/junegunn/fzf/src/util"1112 "github.com/rivo/uniseg"13)
130 unmodified lines
144 _prevMouseButton tcell.ButtonMask145 _initialResize bool = true146)147149func (r *FullscreenRenderer) initScreen() {148func (r *FullscreenRenderer) initScreen() error {149 s, e := tcell.NewScreen()150 if e != nil {152 errorExit(e.Error())151 return e152 }153 if e = s.Init(); e != nil {155 errorExit(e.Error())154 return e155 }156 if r.mouse {157 s.EnableMouse()158 } else {159 s.DisableMouse()160 }161 _screen = s162163 return nil164}165165func (r *FullscreenRenderer) Init() {166func (r *FullscreenRenderer) Init() error {167 if os.Getenv("TERM") == "cygwin" {168 os.Setenv("TERM", "")169 }169 encoding.Register()170171 r.initScreen()171 if err := r.initScreen(); err != nil {172 return err173 }174 initTheme(r.theme, r.defaultTheme(), r.forceBlack)175176 return nil177}178179func (r *FullscreenRenderer) Top() int {180 return 0
627 unmodified lines
modified:src/tui/tui.go+2 added-8 removed
1package tui23import (4 "fmt"5 "os"4 "strconv"5 "time"67 "github.com/junegunn/fzf/src/util"
93 unmodified lines
101 Alt102 CtrlAlt103104 Invalid105 Fatal106107 Mouse108 DoubleClick109 LeftClick
413 unmodified lines
523 PxHeight int524}525526type Renderer interface {528 Init()527 Init() error528 Resize(maxHeightFunc func(int) int)529 Pause(clear bool)530 Resume(clear bool, sigcont bool)531 Clear()
151 unmodified lines
683 Scrollbar: ColorAttr{colDefault, AttrUndefined},684 }685}686688func errorExit(message string) {689 fmt.Fprintln(os.Stderr, message)690 util.Exit(2)691}692687func init() {688 Default16 = &ColorTheme{689 Colored: true,690 Input: ColorAttr{colDefault, AttrUndefined},
166 unmodified lines
modified:src/util/atexit.go+1 added-11 removed
1package util23import (4 "os"4 "sync"5)67var atExitFuncs []func()
15 unmodified lines
23 fns := atExitFuncs24 for i := len(fns) - 1; i >= 0; i-- {25 fns[i]()26 }27 atExitFuncs = nil28}2930// Exit executes any functions registered with AtExit() then exits the program31// with os.Exit(code).32//33// NOTE: It must be used instead of os.Exit() since calling os.Exit() terminates34// the program before any of the AtExit functions can run.35func Exit(code int) {36 defer os.Exit(code)37 RunAtExitFuncs()38}
modified:src/util/util_unix.go+1 added-1 removed
59 unmodified lines
60func (x *Executor) Become(stdin *os.File, environ []string, command string) {61 shellPath, err := exec.LookPath(x.shell)62 if err != nil {63 fmt.Fprintf(os.Stderr, "fzf (become): %s\n", err.Error())64 Exit(127)64 os.Exit(127)65 }66 args := append([]string{shellPath}, append(x.args, command)...)67 SetStdin(stdin)68 syscall.Exec(shellPath, args, environ)
25 unmodified lines
modified:src/util/util_windows.go+3 added-3 removed
95 unmodified lines
96 cmd.Env = environ97 err := cmd.Start()98 if err != nil {99 fmt.Fprintf(os.Stderr, "fzf (become): %s\n", err.Error())100 Exit(127)100 os.Exit(127)101 }102 err = cmd.Wait()103 if err != nil {104 if exitError, ok := err.(*exec.ExitError); ok {105 Exit(exitError.ExitCode())105 os.Exit(exitError.ExitCode())106 }107 }108 Exit(0)108 os.Exit(0)109}110111func escapeArg(s string) string {112 b := make([]byte, 0, len(s)+2)
72 unmodified lines
modified:src/actiontype_string.go+84 added-83 removed
35 unmodified lines
36 _ = x[actClose-25]37 _ = x[actDeleteChar-26]38 _ = x[actDeleteCharEof-27]39 _ = x[actEndOfLine-28]40 _ = x[actForwardChar-29]41 _ = x[actForwardWord-30]42 _ = x[actKillLine-31]43 _ = x[actKillWord-32]44 _ = x[actUnixLineDiscard-33]45 _ = x[actUnixWordRubout-34]46 _ = x[actYank-35]47 _ = x[actBackwardKillWord-36]48 _ = x[actSelectAll-37]49 _ = x[actDeselectAll-38]50 _ = x[actToggle-39]51 _ = x[actToggleSearch-40]52 _ = x[actToggleAll-41]53 _ = x[actToggleDown-42]54 _ = x[actToggleUp-43]55 _ = x[actToggleIn-44]56 _ = x[actToggleOut-45]57 _ = x[actToggleTrack-46]58 _ = x[actToggleTrackCurrent-47]59 _ = x[actToggleHeader-48]60 _ = x[actTrackCurrent-49]61 _ = x[actUntrackCurrent-50]62 _ = x[actDown-51]63 _ = x[actUp-52]64 _ = x[actPageUp-53]65 _ = x[actPageDown-54]66 _ = x[actPosition-55]67 _ = x[actHalfPageUp-56]68 _ = x[actHalfPageDown-57]69 _ = x[actOffsetUp-58]70 _ = x[actOffsetDown-59]71 _ = x[actJump-60]72 _ = x[actJumpAccept-61]73 _ = x[actPrintQuery-62]74 _ = x[actRefreshPreview-63]75 _ = x[actReplaceQuery-64]76 _ = x[actToggleSort-65]77 _ = x[actShowPreview-66]78 _ = x[actHidePreview-67]79 _ = x[actTogglePreview-68]80 _ = x[actTogglePreviewWrap-69]81 _ = x[actTransform-70]82 _ = x[actTransformBorderLabel-71]83 _ = x[actTransformHeader-72]84 _ = x[actTransformPreviewLabel-73]85 _ = x[actTransformPrompt-74]86 _ = x[actTransformQuery-75]87 _ = x[actPreview-76]88 _ = x[actChangePreview-77]89 _ = x[actChangePreviewWindow-78]90 _ = x[actPreviewTop-79]91 _ = x[actPreviewBottom-80]92 _ = x[actPreviewUp-81]93 _ = x[actPreviewDown-82]94 _ = x[actPreviewPageUp-83]95 _ = x[actPreviewPageDown-84]96 _ = x[actPreviewHalfPageUp-85]97 _ = x[actPreviewHalfPageDown-86]98 _ = x[actPrevHistory-87]99 _ = x[actPrevSelected-88]100 _ = x[actPut-89]101 _ = x[actNextHistory-90]102 _ = x[actNextSelected-91]103 _ = x[actExecute-92]104 _ = x[actExecuteSilent-93]105 _ = x[actExecuteMulti-94]106 _ = x[actSigStop-95]107 _ = x[actFirst-96]108 _ = x[actLast-97]109 _ = x[actReload-98]110 _ = x[actReloadSync-99]111 _ = x[actDisableSearch-100]112 _ = x[actEnableSearch-101]113 _ = x[actSelect-102]114 _ = x[actDeselect-103]115 _ = x[actUnbind-104]116 _ = x[actRebind-105]117 _ = x[actBecome-106]118 _ = x[actResponse-107]119 _ = x[actShowHeader-108]120 _ = x[actHideHeader-109]40 _ = x[actFatal-29]41 _ = x[actForwardChar-30]42 _ = x[actForwardWord-31]43 _ = x[actKillLine-32]44 _ = x[actKillWord-33]45 _ = x[actUnixLineDiscard-34]46 _ = x[actUnixWordRubout-35]47 _ = x[actYank-36]48 _ = x[actBackwardKillWord-37]49 _ = x[actSelectAll-38]50 _ = x[actDeselectAll-39]51 _ = x[actToggle-40]52 _ = x[actToggleSearch-41]53 _ = x[actToggleAll-42]54 _ = x[actToggleDown-43]55 _ = x[actToggleUp-44]56 _ = x[actToggleIn-45]57 _ = x[actToggleOut-46]58 _ = x[actToggleTrack-47]59 _ = x[actToggleTrackCurrent-48]60 _ = x[actToggleHeader-49]61 _ = x[actTrackCurrent-50]62 _ = x[actUntrackCurrent-51]63 _ = x[actDown-52]64 _ = x[actUp-53]65 _ = x[actPageUp-54]66 _ = x[actPageDown-55]67 _ = x[actPosition-56]68 _ = x[actHalfPageUp-57]69 _ = x[actHalfPageDown-58]70 _ = x[actOffsetUp-59]71 _ = x[actOffsetDown-60]72 _ = x[actJump-61]73 _ = x[actJumpAccept-62]74 _ = x[actPrintQuery-63]75 _ = x[actRefreshPreview-64]76 _ = x[actReplaceQuery-65]77 _ = x[actToggleSort-66]78 _ = x[actShowPreview-67]79 _ = x[actHidePreview-68]80 _ = x[actTogglePreview-69]81 _ = x[actTogglePreviewWrap-70]82 _ = x[actTransform-71]83 _ = x[actTransformBorderLabel-72]84 _ = x[actTransformHeader-73]85 _ = x[actTransformPreviewLabel-74]86 _ = x[actTransformPrompt-75]87 _ = x[actTransformQuery-76]88 _ = x[actPreview-77]89 _ = x[actChangePreview-78]90 _ = x[actChangePreviewWindow-79]91 _ = x[actPreviewTop-80]92 _ = x[actPreviewBottom-81]93 _ = x[actPreviewUp-82]94 _ = x[actPreviewDown-83]95 _ = x[actPreviewPageUp-84]96 _ = x[actPreviewPageDown-85]97 _ = x[actPreviewHalfPageUp-86]98 _ = x[actPreviewHalfPageDown-87]99 _ = x[actPrevHistory-88]100 _ = x[actPrevSelected-89]101 _ = x[actPut-90]102 _ = x[actNextHistory-91]103 _ = x[actNextSelected-92]104 _ = x[actExecute-93]105 _ = x[actExecuteSilent-94]106 _ = x[actExecuteMulti-95]107 _ = x[actSigStop-96]108 _ = x[actFirst-97]109 _ = x[actLast-98]110 _ = x[actReload-99]111 _ = x[actReloadSync-100]112 _ = x[actDisableSearch-101]113 _ = x[actEnableSearch-102]114 _ = x[actSelect-103]115 _ = x[actDeselect-104]116 _ = x[actUnbind-105]117 _ = x[actRebind-106]118 _ = x[actBecome-107]119 _ = x[actResponse-108]120 _ = x[actShowHeader-109]121 _ = x[actHideHeader-110]122}123123const _actionType_name = "actIgnoreactStartactClickactInvalidactCharactMouseactBeginningOfLineactAbortactAcceptactAcceptNonEmptyactAcceptOrPrintQueryactBackwardCharactBackwardDeleteCharactBackwardDeleteCharEofactBackwardWordactCancelactChangeBorderLabelactChangeHeaderactChangeMultiactChangePreviewLabelactChangePromptactChangeQueryactClearScreenactClearQueryactClearSelectionactCloseactDeleteCharactDeleteCharEofactEndOfLineactForwardCharactForwardWordactKillLineactKillWordactUnixLineDiscardactUnixWordRuboutactYankactBackwardKillWordactSelectAllactDeselectAllactToggleactToggleSearchactToggleAllactToggleDownactToggleUpactToggleInactToggleOutactToggleTrackactToggleTrackCurrentactToggleHeaderactTrackCurrentactUntrackCurrentactDownactUpactPageUpactPageDownactPositionactHalfPageUpactHalfPageDownactOffsetUpactOffsetDownactJumpactJumpAcceptactPrintQueryactRefreshPreviewactReplaceQueryactToggleSortactShowPreviewactHidePreviewactTogglePreviewactTogglePreviewWrapactTransformactTransformBorderLabelactTransformHeaderactTransformPreviewLabelactTransformPromptactTransformQueryactPreviewactChangePreviewactChangePreviewWindowactPreviewTopactPreviewBottomactPreviewUpactPreviewDownactPreviewPageUpactPreviewPageDownactPreviewHalfPageUpactPreviewHalfPageDownactPrevHistoryactPrevSelectedactPutactNextHistoryactNextSelectedactExecuteactExecuteSilentactExecuteMultiactSigStopactFirstactLastactReloadactReloadSyncactDisableSearchactEnableSearchactSelectactDeselectactUnbindactRebindactBecomeactResponseactShowHeaderactHideHeader"124const _actionType_name = "actIgnoreactStartactClickactInvalidactCharactMouseactBeginningOfLineactAbortactAcceptactAcceptNonEmptyactAcceptOrPrintQueryactBackwardCharactBackwardDeleteCharactBackwardDeleteCharEofactBackwardWordactCancelactChangeBorderLabelactChangeHeaderactChangeMultiactChangePreviewLabelactChangePromptactChangeQueryactClearScreenactClearQueryactClearSelectionactCloseactDeleteCharactDeleteCharEofactEndOfLineactFatalactForwardCharactForwardWordactKillLineactKillWordactUnixLineDiscardactUnixWordRuboutactYankactBackwardKillWordactSelectAllactDeselectAllactToggleactToggleSearchactToggleAllactToggleDownactToggleUpactToggleInactToggleOutactToggleTrackactToggleTrackCurrentactToggleHeaderactTrackCurrentactUntrackCurrentactDownactUpactPageUpactPageDownactPositionactHalfPageUpactHalfPageDownactOffsetUpactOffsetDownactJumpactJumpAcceptactPrintQueryactRefreshPreviewactReplaceQueryactToggleSortactShowPreviewactHidePreviewactTogglePreviewactTogglePreviewWrapactTransformactTransformBorderLabelactTransformHeaderactTransformPreviewLabelactTransformPromptactTransformQueryactPreviewactChangePreviewactChangePreviewWindowactPreviewTopactPreviewBottomactPreviewUpactPreviewDownactPreviewPageUpactPreviewPageDownactPreviewHalfPageUpactPreviewHalfPageDownactPrevHistoryactPrevSelectedactPutactNextHistoryactNextSelectedactExecuteactExecuteSilentactExecuteMultiactSigStopactFirstactLastactReloadactReloadSyncactDisableSearchactEnableSearchactSelectactDeselectactUnbindactRebindactBecomeactResponseactShowHeaderactHideHeader"125125var _actionType_index = [...]uint16{0, 9, 17, 25, 35, 42, 50, 68, 76, 85, 102, 123, 138, 159, 183, 198, 207, 227, 242, 256, 277, 292, 306, 320, 333, 350, 358, 371, 387, 399, 413, 427, 438, 449, 467, 484, 491, 510, 522, 536, 545, 560, 572, 585, 596, 607, 619, 633, 654, 669, 684, 701, 708, 713, 722, 733, 744, 757, 772, 783, 796, 803, 816, 829, 846, 861, 874, 888, 902, 918, 938, 950, 973, 991, 1015, 1033, 1050, 1060, 1076, 1098, 1111, 1127, 1139, 1153, 1169, 1187, 1207, 1229, 1243, 1258, 1264, 1278, 1293, 1303, 1319, 1334, 1344, 1352, 1359, 1368, 1381, 1397, 1412, 1421, 1432, 1441, 1450, 1459, 1470, 1483, 1496}126var _actionType_index = [...]uint16{0, 9, 17, 25, 35, 42, 50, 68, 76, 85, 102, 123, 138, 159, 183, 198, 207, 227, 242, 256, 277, 292, 306, 320, 333, 350, 358, 371, 387, 399, 407, 421, 435, 446, 457, 475, 492, 499, 518, 530, 544, 553, 568, 580, 593, 604, 615, 627, 641, 662, 677, 692, 709, 716, 721, 730, 741, 752, 765, 780, 791, 804, 811, 824, 837, 854, 869, 882, 896, 910, 926, 946, 958, 981, 999, 1023, 1041, 1058, 1068, 1084, 1106, 1119, 1135, 1147, 1161, 1177, 1195, 1215, 1237, 1251, 1266, 1272, 1286, 1301, 1311, 1327, 1342, 1352, 1360, 1367, 1376, 1389, 1405, 1420, 1429, 1440, 1449, 1458, 1467, 1478, 1491, 1504}127128func (i actionType) String() string {129 if i < 0 || i >= actionType(len(_actionType_index)-1) {130 return "actionType(" + strconv.FormatInt(int64(i), 10) + ")"
3 unmodified lines
modified:src/ansi.go+2 added-2 removed
290 unmodified lines
291}292293func parseAnsiCode(s string, delimiter byte) (int, byte, string) {294 var remaining string295 i := -1295 var i int296 if delimiter == 0 {297 // Faster than strings.IndexAny(";:")298 i = strings.IndexByte(s, ';')299 if i < 0 {
49 unmodified lines
349350 state256 := 0351 ptr := &state.fg352353 var delimiter byte = 0353 var delimiter byte354 count := 0355 for len(ansiCode) != 0 {356 var num int357 if num, delimiter, ansiCode = parseAnsiCode(ansiCode, delimiter); num != -1 {
94 unmodified lines
modified:src/cache.go+8 added-2 removed
10 unmodified lines
11 cache map[*Chunk]*queryCache12}1314// NewChunkCache returns a new ChunkCache15func NewChunkCache() ChunkCache {16 return ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}15func NewChunkCache() *ChunkCache {16 return &ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}17}1819func (cc *ChunkCache) Clear() {20 cc.mutex.Lock()21 cc.cache = make(map[*Chunk]*queryCache)22 cc.mutex.Unlock()23}2425// Add adds the list to the cache26func (cc *ChunkCache) Add(chunk *Chunk, key string, list []Result) {27 if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {28 return
59 unmodified lines
modified:src/constants.go+5 added-5 removed
65 unmodified lines
66 EvtQuit67)6869const (70 exitCancel = -171 exitOk = 072 exitNoMatch = 173 exitError = 274 exitInterrupt = 13070 ExitCancel = -171 ExitOk = 072 ExitNoMatch = 173 ExitError = 274 ExitInterrupt = 13075)
modified:src/core.go+46 added-22 removed
1// Package fzf implements fzf, a command-line fuzzy finder.2package fzf34import (5 "fmt"5 "sync"6 "time"7 "unsafe"8
16 unmodified lines
25func sbytes(data string) []byte {26 return unsafe.Slice(unsafe.StringData(data), len(data))27}2829type quitSignal struct {30 code int31 err error32}3334// Run starts fzf31func Run(opts *Options, version string, revision string) {35func Run(opts *Options) (int, error) {36 if err := postProcessOptions(opts); err != nil {37 return ExitError, err38 }3940 defer util.RunAtExitFuncs()4134 sort := opts.Sort > 035 sortCriteria = opts.Criteria3637 if opts.Version {38 if len(revision) > 0 {39 fmt.Printf("%s (%s)\n", version, revision)40 } else {41 fmt.Println(version)42 // Output channel given43 if opts.Output != nil {44 opts.Printer = func(str string) {45 opts.Output <- str46 }43 util.Exit(exitOk)47 }4849 sort := opts.Sort > 050 sortCriteria = opts.Criteria5152 // Event channel53 eventBox := util.NewEventBox()5455 // ANSI code processor
80 unmodified lines
136 if !streamingFilter {137 reader = NewReader(func(data []byte) bool {138 return chunkList.Push(data)139 }, eventBox, executor, opts.ReadZero, opts.Filter == nil)134 go reader.ReadSource(opts.WalkerRoot, opts.WalkerOpts, opts.WalkerSkip)140 go reader.ReadSource(opts.Input, opts.WalkerRoot, opts.WalkerOpts, opts.WalkerSkip)141 }142143 // Matcher144 forward := true
7 unmodified lines
152 case byBegin:153 forward = true154 }155 }156 cache := NewChunkCache()157 patternCache := make(map[string]*Pattern)158 patternBuilder := func(runes []rune) *Pattern {151 return BuildPattern(159 return BuildPattern(cache, patternCache,160 opts.Fuzzy, opts.FuzzyAlgo, opts.Extended, opts.Case, opts.Normalize, forward, withPos,161 opts.Filter == nil, opts.Nth, opts.Delimiter, runes)162 }163 inputRevision := 0164 snapshotRevision := 0157 matcher := NewMatcher(patternBuilder, sort, opts.Tac, eventBox, inputRevision)165 matcher := NewMatcher(cache, patternBuilder, sort, opts.Tac, eventBox, inputRevision)166167 // Filtering mode168 if opts.Filter != nil {169 if opts.PrintQuery {
19 unmodified lines
189 mutex.Unlock()190 }191 return false192 }, eventBox, executor, opts.ReadZero, false)185 reader.ReadSource(opts.WalkerRoot, opts.WalkerOpts, opts.WalkerSkip)193 reader.ReadSource(opts.Input, opts.WalkerRoot, opts.WalkerOpts, opts.WalkerSkip)194 } else {195 eventBox.Unwatch(EvtReadNew)196 eventBox.WaitFor(EvtReadFin)197
6 unmodified lines
204 found = true205 }206 }207 if found {200 util.Exit(exitOk)208 return ExitOk, nil209 }202 util.Exit(exitNoMatch)210 return ExitNoMatch, nil211 }212213 // Synchronous search214 if opts.Sync {
2 unmodified lines
217 }218219 // Go interactive220 go matcher.Loop()221 defer matcher.Stop()222223 // Terminal I/O215 terminal := NewTerminal(opts, eventBox, executor)224 terminal, err := NewTerminal(opts, eventBox, executor)225 if err != nil {226 return ExitError, err227 }228 maxFit := 0 // Maximum number of items that can fit on screen229 padHeight := 0230 heightUnknown := opts.Height.auto231 if heightUnknown {
37 unmodified lines
269 inputRevision++270 header = make([]string, 0, opts.HeaderLines)271 go reader.restart(command, environ)272 }273274 exitCode := ExitOk275 stop := false276 for {277 delay := true278 ticks++279 input := func() []rune {
12 unmodified lines
292 case EvtQuit:293 if reading {294 reader.terminate()295 }281 util.Exit(value.(int))296 quitSignal := value.(quitSignal)297 exitCode = quitSignal.code298 err = quitSignal.err299 stop = true300 return301 case EvtReadNew, EvtReadFin:302 if evt == EvtReadFin && nextCommand != nil {303 restart(*nextCommand, nextEnviron)304 nextCommand = nil
91 unmodified lines
396 }397 for i := 0; i < count; i++ {398 opts.Printer(val.Get(i).item.AsString(opts.Ansi))399 }381 if count > 0 {382 util.Exit(exitOk)400 if count == 0 {401 exitCode = ExitNoMatch402 }384 util.Exit(exitNoMatch)403 stop = true404 return405 }406 determine(val.final)407 }408 }
2 unmodified lines
411 }412 }413 events.Clear()414 })415 if stop {416 break417 }418 if delay && reading {419 dur := util.DurWithin(420 time.Duration(ticks)*coordinatorDelayStep,421 0, coordinatorDelayMax)422 time.Sleep(dur)423 }424 }425 return exitCode, err426}
modified:src/matcher.go+17 added-3 removed
19 unmodified lines
20}2122// Matcher is responsible for performing search23type Matcher struct {24 cache *ChunkCache25 patternBuilder func([]rune) *Pattern26 sort bool27 tac bool28 eventBox *util.EventBox
9 unmodified lines
38 reqReset39)4041// NewMatcher returns a new Matcher41func NewMatcher(patternBuilder func([]rune) *Pattern,42func NewMatcher(cache *ChunkCache, patternBuilder func([]rune) *Pattern,43 sort bool, tac bool, eventBox *util.EventBox, revision int) *Matcher {44 partitions := util.Min(numPartitionsMultiplier*runtime.NumCPU(), maxPartitions)45 return &Matcher{46 cache: cache,47 patternBuilder: patternBuilder,48 sort: sort,49 tac: tac,50 eventBox: eventBox,
10 unmodified lines
6162 for {63 var request MatchRequest6465 stop := false66 m.reqBox.Wait(func(events *util.Events) {64 for _, val := range *events {67 for t, val := range *events {68 if t == reqQuit {69 stop = true70 return71 }72 switch val := val.(type) {73 case MatchRequest:74 request = val75 default:
1 unmodified line
77 }78 }79 events.Clear()80 })81 if stop {82 break83 }8485 if request.sort != m.sort || request.revision != m.revision {86 m.sort = request.sort87 m.revision = request.revision88 m.mergerCache = make(map[string]*Merger)79 clearChunkCache()89 m.cache.Clear()90 }9192 // Restart search93 patternString := request.pattern.AsString()
151 unmodified lines
245 event = reqRetry246 }247 m.reqBox.Set(event, MatchRequest{chunks, pattern, final, sort && pattern.sortable, revision})248}249250func (m *Matcher) Stop() {251 m.reqBox.Set(reqQuit, nil)252}
modified:src/options_no_pprof.go+3 added-1 removed
1 unmodified line
2// +build !pprof34package fzf56import "errors"78func (o *Options) initProfiling() error {9 if o.CPUProfile != "" || o.MEMProfile != "" || o.BlockProfile != "" || o.MutexProfile != "" {8 errorExit("error: profiling not supported: FZF must be built with '-tags=pprof' to enable profiling")10 return errors.New("error: profiling not supported: FZF must be built with '-tags=pprof' to enable profiling")11 }12 return nil13}
modified:src/options_test.go+22 added-32 removed
78 unmodified lines
79}8081func TestSplitNth(t *testing.T) {82 {83 ranges := splitNth("..")83 ranges, _ := splitNth("..")84 if len(ranges) != 1 ||85 ranges[0].begin != rangeEllipsis ||86 ranges[0].end != rangeEllipsis {87 t.Errorf("%v", ranges)88 }89 }90 {91 ranges := splitNth("..3,1..,2..3,4..-1,-3..-2,..,2,-2,2..-2,1..-1")91 ranges, _ := splitNth("..3,1..,2..3,4..-1,-3..-2,..,2,-2,2..-2,1..-1")92 if len(ranges) != 10 ||93 ranges[0].begin != rangeEllipsis || ranges[0].end != 3 ||94 ranges[1].begin != rangeEllipsis || ranges[1].end != rangeEllipsis ||95 ranges[2].begin != 2 || ranges[2].end != 3 ||
40 unmodified lines
136 }137}138139func TestParseKeys(t *testing.T) {140 pairs := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g,ctrl-alt-a,ALT-enter,alt-SPACE", "")140 pairs, _ := parseKeyChords("ctrl-z,alt-z,f2,@,Alt-a,!,ctrl-G,J,g,ctrl-alt-a,ALT-enter,alt-SPACE", "")141 checkEvent := func(e tui.Event, s string) {142 if pairs[e] != s {143 t.Errorf("%s != %s", pairs[e], s)144 }
17 unmodified lines
162 checkEvent(tui.CtrlAltKey('m'), "ALT-enter")163 checkEvent(tui.AltKey(' '), "alt-SPACE")164165 // Synonyms166 pairs = parseKeyChords("enter,Return,space,tab,btab,esc,up,down,left,right", "")166 pairs, _ = parseKeyChords("enter,Return,space,tab,btab,esc,up,down,left,right", "")167 if len(pairs) != 9 {168 t.Error(9)169 }170 check(tui.CtrlM, "Return")
5 unmodified lines
176 check(tui.Down, "down")177 check(tui.Left, "left")178 check(tui.Right, "right")179180 pairs = parseKeyChords("Tab,Ctrl-I,PgUp,page-up,pgdn,Page-Down,Home,End,Alt-BS,Alt-BSpace,shift-left,shift-right,btab,shift-tab,return,Enter,bspace", "")180 pairs, _ = parseKeyChords("Tab,Ctrl-I,PgUp,page-up,pgdn,Page-Down,Home,End,Alt-BS,Alt-BSpace,shift-left,shift-right,btab,shift-tab,return,Enter,bspace", "")181 if len(pairs) != 11 {182 t.Error(11)183 }184 check(tui.Tab, "Ctrl-I")
20 unmodified lines
205 t.Errorf("%s != %s", pairs[e], s)206 }207 }208209 pairs := parseKeyChords(",", "")209 pairs, _ := parseKeyChords(",", "")210 checkN(len(pairs), 1)211 check(pairs, tui.Key(','), ",")212213 pairs = parseKeyChords(",,a,b", "")213 pairs, _ = parseKeyChords(",,a,b", "")214 checkN(len(pairs), 3)215 check(pairs, tui.Key('a'), "a")216 check(pairs, tui.Key('b'), "b")217 check(pairs, tui.Key(','), ",")218219 pairs = parseKeyChords("a,b,,", "")219 pairs, _ = parseKeyChords("a,b,,", "")220 checkN(len(pairs), 3)221 check(pairs, tui.Key('a'), "a")222 check(pairs, tui.Key('b'), "b")223 check(pairs, tui.Key(','), ",")224225 pairs = parseKeyChords("a,,,b", "")225 pairs, _ = parseKeyChords("a,,,b", "")226 checkN(len(pairs), 3)227 check(pairs, tui.Key('a'), "a")228 check(pairs, tui.Key('b'), "b")229 check(pairs, tui.Key(','), ",")230231 pairs = parseKeyChords("a,,,b,c", "")231 pairs, _ = parseKeyChords("a,,,b,c", "")232 checkN(len(pairs), 4)233 check(pairs, tui.Key('a'), "a")234 check(pairs, tui.Key('b'), "b")235 check(pairs, tui.Key('c'), "c")236 check(pairs, tui.Key(','), ",")237238 pairs = parseKeyChords(",,,", "")238 pairs, _ = parseKeyChords(",,,", "")239 checkN(len(pairs), 1)240 check(pairs, tui.Key(','), ",")241242 pairs = parseKeyChords(",ALT-,,", "")242 pairs, _ = parseKeyChords(",ALT-,,", "")243 checkN(len(pairs), 1)244 check(pairs, tui.AltKey(','), "ALT-,")245}246
14 unmodified lines
261 t.Errorf("invalid action argument: (%s != %s)", arg1, keymap[event][0].a)262 }263 }264 check(tui.CtrlA.AsEvent(), "", actBeginningOfLine)265 errorString := ""266 errorFn := func(e string) {267 errorString = e268 }265 parseKeymap(keymap,266 "ctrl-a:kill-line,ctrl-b:toggle-sort+up+down,c:page-up,alt-z:page-down,"+267 "f1:execute(ls {+})+abort+execute(echo \n{+})+select-all,f2:execute/echo {}, {}, {}/,f3:execute[echo '({})'],f4:execute;less {};,"+268 "alt-a:execute-Multi@echo (,),[,],/,:,;,%,{}@,alt-b:execute;echo (,),[,],/,:,@,%,{};,"+269 "x:Execute(foo+bar),X:execute/bar+baz/"+270 ",f1:+first,f1:+top"+275 ",,:abort,::accept,+:execute:++\nfoobar,Y:execute(baz)+up", errorFn)271 ",,:abort,::accept,+:execute:++\nfoobar,Y:execute(baz)+up")272 check(tui.CtrlA.AsEvent(), "", actKillLine)273 check(tui.CtrlB.AsEvent(), "", actToggleSort, actUp, actDown)274 check(tui.Key('c'), "", actPageUp)275 check(tui.Key(','), "", actAbort)
9 unmodified lines
285 check(tui.AltKey('b'), "echo (,),[,],/,:,@,%,{}", actExecute)286 check(tui.Key('+'), "++\nfoobar,Y:execute(baz)+up", actExecute)287288 for idx, char := range []rune{'~', '!', '@', '#', '$', '%', '^', '&', '*', '|', ';', '/'} {293 parseKeymap(keymap, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char), errorFn)289 parseKeymap(keymap, fmt.Sprintf("%d:execute%cfoobar%c", idx%10, char, char))290 check(tui.Key([]rune(fmt.Sprintf("%d", idx%10))[0]), "foobar", actExecute)291 }292297 parseKeymap(keymap, "f1:abort", errorFn)293 parseKeymap(keymap, "f1:abort")294 check(tui.F1.AsEvent(), "", actAbort)299 if len(errorString) > 0 {300 t.Errorf("error parsing keymap: %s", errorString)301 }295}296297func TestColorSpec(t *testing.T) {298 theme := tui.Dark256306 dark := parseTheme(theme, "dark")299 dark, _ := parseTheme(theme, "dark")300 if *dark != *theme {301 t.Errorf("colors should be equivalent")302 }303 if dark == theme {304 t.Errorf("point should not be equivalent")305 }306314 light := parseTheme(theme, "dark,light")307 light, _ := parseTheme(theme, "dark,light")308 if *light == *theme {309 t.Errorf("should not be equivalent")310 }311 if *light != *tui.Light256 {
2 unmodified lines
314 if light == theme {315 t.Errorf("point should not be equivalent")316 }317325 customized := parseTheme(theme, "fg:231,bg:232")318 customized, _ := parseTheme(theme, "fg:231,bg:232")319 if customized.Fg.Color != 231 || customized.Bg.Color != 232 {320 t.Errorf("color not customized")321 }322 if *tui.Dark256 == *customized {
4 unmodified lines
327 if *tui.Dark256 != *customized {328 t.Errorf("colors should now be equivalent: %v, %v", tui.Dark256, customized)329 }330338 customized = parseTheme(theme, "fg:231,dark,bg:232")331 customized, _ = parseTheme(theme, "fg:231,dark,bg:232")332 if customized.Fg != tui.Dark256.Fg || customized.Bg == tui.Dark256.Bg {333 t.Errorf("color not customized")334 }335}
131 unmodified lines
467 }468}469470func TestParseSingleActionList(t *testing.T) {478 actions := parseSingleActionList("Execute@foo+bar,baz@+up+up+reload:down+down", func(string) {})471 actions, _ := parseSingleActionList("Execute@foo+bar,baz@+up+up+reload:down+down")472 if len(actions) != 4 {473 t.Errorf("Invalid number of actions parsed:%d", len(actions))474 }475 if actions[0].t != actExecute || actions[0].a != "foo+bar,baz" {
7 unmodified lines
483 }484}485486func TestParseSingleActionListError(t *testing.T) {494 err := ""495 parseSingleActionList("change-query(foobar)baz", func(e string) {496 err = e497 })498 if len(err) == 0 {487 _, err := parseSingleActionList("change-query(foobar)baz")488 if err == nil {489 t.Errorf("Failed to detect error")490 }491}492
8 unmodified lines
modified:src/options.go+632 added-333 removed
1package fzf23import (4 "errors"5 "fmt"6 "os"7 "regexp"8 "strconv"
1 unmodified line
10 "unicode"1112 "github.com/junegunn/fzf/src/algo"13 "github.com/junegunn/fzf/src/tui"13 "github.com/junegunn/fzf/src/util"1415 "github.com/mattn/go-shellwords"16 "github.com/rivo/uniseg"17)1819const usage = `usage: fzf [options]19const Usage = `usage: fzf [options]2021 Search22 -x, --extended Extended-search mode23 (enabled by default; +x or --no-extended to disable)
222 unmodified lines
246func (o *previewOpts) Toggle() {247 o.hidden = !o.hidden248}249250func parseLabelPosition(opts *labelOpts, arg string) {250func parseLabelPosition(opts *labelOpts, arg string) error {251 opts.column = 0252 opts.bottom = false253 var err error254 for _, token := range splitRegexp.Split(strings.ToLower(arg), -1) {255 switch token {256 case "center":257 opts.column = 0
1 unmodified line
259 opts.bottom = true260 case "top":261 opts.bottom = false262 default:262 opts.column = atoi(token)263 opts.column, err = atoi(token)264 }265 }266 return err267}268269func (a previewOpts) aboveOrBelow() bool {270 return a.size.size > 0 && (a.position == posUp || a.position == posDown)
21 unmodified lines
292}293294// Options stores the values of command-line options295type Options struct {296 Input chan string297 Output chan string298 Bash bool299 Zsh bool300 Fish bool301 Fuzzy bool
66 unmodified lines
368 WalkerOpts walkerOpts369 WalkerRoot string370 WalkerSkip []string371 Version bool372 Help bool373 CPUProfile string374 MEMProfile string375 BlockProfile string376 MutexProfile string
82 unmodified lines
459 ClearOnExit: true,460 WalkerOpts: walkerOpts{file: true, hidden: true, follow: true},461 WalkerRoot: ".",462 WalkerSkip: []string{".git", "node_modules"},463 Help: false,464 Version: false}465}466461func help(code int) {462 os.Stdout.WriteString(usage)463 util.Exit(code)464}465466var errorContext = ""467468func errorExit(msg string) {469 os.Stderr.WriteString(errorContext + msg + "\n")470 util.Exit(exitError)471}472467func optString(arg string, prefixes ...string) (bool, string) {468 for _, prefix := range prefixes {469 if strings.HasPrefix(arg, prefix) {470 return true, arg[len(prefix):]
1 unmodified line
472 }473 return false, ""474}475482func nextString(args []string, i *int, message string) string {476func nextString(args []string, i *int, message string) (string, error) {477 if len(args) > *i+1 {478 *i++479 } else {486 errorExit(message)480 return "", errors.New(message)481 }488 return args[*i]482 return args[*i], nil483}484485func optionalNextString(args []string, i *int) (bool, string) {486 if len(args) > *i+1 && !strings.HasPrefix(args[*i+1], "-") && !strings.HasPrefix(args[*i+1], "+") {
2 unmodified lines
489 }490 return false, ""491}492499func atoi(str string) int {493func atoi(str string) (int, error) {494 num, err := strconv.Atoi(str)495 if err != nil {502 errorExit("not a valid integer: " + str)496 return 0, errors.New("not a valid integer: " + str)497 }504 return num498 return num, nil499}500507func atof(str string) float64 {501func atof(str string) (float64, error) {502 num, err := strconv.ParseFloat(str, 64)503 if err != nil {510 errorExit("not a valid number: " + str)504 return 0, errors.New("not a valid number: " + str)505 }512 return num506 return num, nil507}508515func nextInt(args []string, i *int, message string) int {509func nextInt(args []string, i *int, message string) (int, error) {510 if len(args) > *i+1 {511 *i++512 } else {519 errorExit(message)513 return 0, errors.New(message)514 }521 return atoi(args[*i])515 n, err := atoi(args[*i])516 if err != nil {517 return 0, errors.New(message)518 }519 return n, nil520}521524func optionalNumeric(args []string, i *int, defaultValue int) int {522func optionalNumeric(args []string, i *int, defaultValue int) (int, error) {523 if len(args) > *i+1 {524 if strings.IndexAny(args[*i+1], "0123456789") == 0 {525 *i++528 return atoi(args[*i])526 n, err := atoi(args[*i])527 if err != nil {528 return 0, err529 }530 return n, nil531 }532 }531 return defaultValue533 return defaultValue, nil534}535534func splitNth(str string) []Range {536func splitNth(str string) ([]Range, error) {537 if match, _ := regexp.MatchString("^[0-9,-.]+$", str); !match {536 errorExit("invalid format: " + str)538 return nil, errors.New("invalid format: " + str)539 }540541 tokens := strings.Split(str, ",")542 ranges := make([]Range, len(tokens))543 for idx, s := range tokens {544 r, ok := ParseRange(&s)545 if !ok {544 errorExit("invalid format: " + str)546 return nil, errors.New("invalid format: " + str)547 }548 ranges[idx] = r549 }548 return ranges550 return ranges, nil551}552553func delimiterRegexp(str string) Delimiter {554 // Special handling of \t
21 unmodified lines
576func isNumeric(char uint8) bool {577 return char >= '0' && char <= '9'578}579578func parseAlgo(str string) algo.Algo {580func parseAlgo(str string) (algo.Algo, error) {581 switch str {582 case "v1":581 return algo.FuzzyMatchV1583 return algo.FuzzyMatchV1, nil584 case "v2":583 return algo.FuzzyMatchV2584 default:585 errorExit("invalid algorithm (expected: v1 or v2)")585 return algo.FuzzyMatchV2, nil586 }587 return algo.FuzzyMatchV2587 return nil, errors.New("invalid algorithm (expected: v1 or v2)")588}589590func processScheme(opts *Options) {590func processScheme(opts *Options) error {591 if !algo.Init(opts.Scheme) {592 errorExit("invalid scoring scheme (expected: default|path|history)")592 return errors.New("invalid scoring scheme (expected: default|path|history)")593 }594 if opts.Scheme == "history" {595 opts.Criteria = []criterion{byScore}596 }597 return nil598}599599func parseBorder(str string, optional bool) tui.BorderShape {600func parseBorder(str string, optional bool) (tui.BorderShape, error) {601 switch str {602 case "rounded":602 return tui.BorderRounded603 return tui.BorderRounded, nil604 case "sharp":604 return tui.BorderSharp605 return tui.BorderSharp, nil606 case "bold":606 return tui.BorderBold607 return tui.BorderBold, nil608 case "block":608 return tui.BorderBlock609 return tui.BorderBlock, nil610 case "thinblock":610 return tui.BorderThinBlock611 return tui.BorderThinBlock, nil612 case "double":612 return tui.BorderDouble613 return tui.BorderDouble, nil614 case "horizontal":614 return tui.BorderHorizontal615 return tui.BorderHorizontal, nil616 case "vertical":616 return tui.BorderVertical617 return tui.BorderVertical, nil618 case "top":618 return tui.BorderTop619 return tui.BorderTop, nil620 case "bottom":620 return tui.BorderBottom621 return tui.BorderBottom, nil622 case "left":622 return tui.BorderLeft623 return tui.BorderLeft, nil624 case "right":624 return tui.BorderRight625 return tui.BorderRight, nil626 case "none":626 return tui.BorderNone627 default:628 if optional && str == "" {629 return tui.DefaultBorderShape630 }631 errorExit("invalid border style (expected: rounded|sharp|bold|block|thinblock|double|horizontal|vertical|top|bottom|left|right|none)")627 return tui.BorderNone, nil628 }633 return tui.BorderNone629 if optional && str == "" {630 return tui.DefaultBorderShape, nil631 }632 return tui.BorderNone, errors.New("invalid border style (expected: rounded|sharp|bold|block|thinblock|double|horizontal|vertical|top|bottom|left|right|none)")633}634636func parseKeyChords(str string, message string) map[tui.Event]string {637 return parseKeyChordsImpl(str, message, errorExit)635func parseKeyChords(str string, message string) (map[tui.Event]string, error) {636 return parseKeyChordsImpl(str, message)637}638640func parseKeyChordsImpl(str string, message string, exit func(string)) map[tui.Event]string {639func parseKeyChordsImpl(str string, message string) (map[tui.Event]string, error) {640 if len(str) == 0 {642 exit(message)643 return nil641 return nil, errors.New(message)642 }643644 str = regexp.MustCompile("(?i)(alt-),").ReplaceAllString(str, "$1"+string([]rune{escapedComma}))645 tokens := strings.Split(str, ",")
161 unmodified lines
807 add(tui.EventType(tui.F1.Int() + int(key[1]) - '1'))808 } else if len(runes) == 1 {809 chords[tui.Key(runes[0])] = key810 } else {813 exit("unsupported key: " + key)814 return nil811 return nil, errors.New("unsupported key: " + key)812 }813 }814 }818 return chords815 return chords, nil816}817821func parseTiebreak(str string) []criterion {818func parseTiebreak(str string) ([]criterion, error) {819 criteria := []criterion{byScore}820 hasIndex := false821 hasChunk := false822 hasLength := false823 hasBegin := false824 hasEnd := false828 check := func(notExpected *bool, name string) {825 check := func(notExpected *bool, name string) error {826 if *notExpected {830 errorExit("duplicate sort criteria: " + name)827 return errors.New("duplicate sort criteria: " + name)828 }829 if hasIndex {833 errorExit("index should be the last criterion")830 return errors.New("index should be the last criterion")831 }832 *notExpected = true833 return nil834 }835 for _, str := range strings.Split(strings.ToLower(str), ",") {836 switch str {837 case "index":840 check(&hasIndex, "index")838 if err := check(&hasIndex, "index"); err != nil {839 return nil, err840 }841 case "chunk":842 check(&hasChunk, "chunk")842 if err := check(&hasChunk, "chunk"); err != nil {843 return nil, err844 }845 criteria = append(criteria, byChunk)846 case "length":845 check(&hasLength, "length")847 if err := check(&hasLength, "length"); err != nil {848 return nil, err849 }850 criteria = append(criteria, byLength)851 case "begin":848 check(&hasBegin, "begin")852 if err := check(&hasBegin, "begin"); err != nil {853 return nil, err854 }855 criteria = append(criteria, byBegin)856 case "end":851 check(&hasEnd, "end")857 if err := check(&hasEnd, "end"); err != nil {858 return nil, err859 }860 criteria = append(criteria, byEnd)861 default:854 errorExit("invalid sort criterion: " + str)862 return nil, errors.New("invalid sort criterion: " + str)863 }864 }865 if len(criteria) > 4 {858 errorExit("at most 3 tiebreaks are allowed: " + str)866 return nil, errors.New("at most 3 tiebreaks are allowed: " + str)867 }860 return criteria868 return criteria, nil869}870871func dupeTheme(theme *tui.ColorTheme) *tui.ColorTheme {872 dupe := *theme873 return &dupe874}875868func parseTheme(defaultTheme *tui.ColorTheme, str string) *tui.ColorTheme {876func parseTheme(defaultTheme *tui.ColorTheme, str string) (*tui.ColorTheme, error) {877 var err error878 theme := dupeTheme(defaultTheme)879 rrggbb := regexp.MustCompile("^#[0-9a-fA-F]{6}$")880 for _, str := range strings.Split(strings.ToLower(str), ",") {881 switch str {
6 unmodified lines
888 case "bw", "no":889 theme = tui.NoColorTheme()890 default:891 fail := func() {892 // Let the code proceed to simplify the error handling883 errorExit("invalid color specification: " + str)893 err = errors.New("invalid color specification: " + str)894 }895 // Color is disabled896 if theme == nil {897 continue
122 unmodified lines
1020 fail()1021 }1022 }1023 }1014 return theme1024 return theme, err1025}10261017func parseWalkerOpts(str string) walkerOpts {1027func parseWalkerOpts(str string) (walkerOpts, error) {1028 opts := walkerOpts{}1029 for _, str := range strings.Split(strings.ToLower(str), ",") {1030 switch str {1031 case "file":
6 unmodified lines
1038 opts.follow = true1039 case "":1040 // Ignored1041 default:1032 errorExit("invalid walker option: " + str)1042 return opts, errors.New("invalid walker option: " + str)1043 }1044 }1045 if !opts.file && !opts.dir {1036 errorExit("at least one of 'file' or 'dir' should be specified")1046 return opts, errors.New("at least one of 'file' or 'dir' should be specified")1047 }1038 return opts1048 return opts, nil1049}10501051var (1052 executeRegexp *regexp.Regexp
35 unmodified lines
1088 if len(action) == 0 {1089 break1090 }1091 cs := string(action[0])1082 ce := ")"1092 var ce string1093 switch action[0] {1094 case ':':1095 masked += strings.Repeat(" ", len(action))1096 break Loop
32 unmodified lines
1129 masked = strings.Replace(masked, "+:", string([]rune{escapedPlus, ':'}), -1)1130 return masked1131}11321123func parseSingleActionList(str string, exit func(string)) []*action {1133func parseSingleActionList(str string) ([]*action, error) {1134 // We prepend a colon to satisfy executeRegexp and remove it later1135 masked := maskActionContents(":" + str)[1:]1126 return parseActionList(masked, str, []*action{}, false, exit)1136 return parseActionList(masked, str, []*action{}, false)1137}11381129func parseActionList(masked string, original string, prevActions []*action, putAllowed bool, exit func(string)) []*action {1139func parseActionList(masked string, original string, prevActions []*action, putAllowed bool) ([]*action, error) {1140 maskedStrings := strings.Split(masked, "+")1141 originalStrings := make([]string, len(maskedStrings))1142 idx := 01143 for i, maskedString := range maskedStrings {
168 unmodified lines
1312 case "put":1313 if putAllowed {1314 appendAction(actChar)1315 } else {1306 exit("unable to put non-printable character")1316 return nil, errors.New("unable to put non-printable character")1317 }1318 default:1319 t := isExecuteAction(specLower)1320 if t == actIgnore {
1 unmodified line
1322 actions = append(prevActions, actions...)1323 } else if specLower == "change-multi" {1324 appendAction(actChangeMulti)1325 } else {1316 exit("unknown action: " + spec)1326 return nil, errors.New("unknown action: " + spec)1327 }1328 } else {1329 offset := len(actionNameRegexp.FindString(spec))1330 var actionArg string
10 unmodified lines
1341 actions = append(actions, &action{t: t, a: actionArg})1342 }1343 switch t {1344 case actUnbind, actRebind:1335 parseKeyChordsImpl(actionArg, spec[0:offset]+" target required", exit)1345 if _, err := parseKeyChordsImpl(actionArg, spec[0:offset]+" target required"); err != nil {1346 return nil, err1347 }1348 case actChangePreviewWindow:1349 opts := previewOpts{}1350 for _, arg := range strings.Split(actionArg, "|") {1351 // Make sure that each expression is valid1340 parsePreviewWindowImpl(&opts, arg, exit)1352 if err := parsePreviewWindowImpl(&opts, arg); err != nil {1353 return nil, err1354 }1355 }1356 }1357 }1358 }1359 prevSpec = ""1360 }1347 return actions1361 return actions, nil1362}13631350func parseKeymap(keymap map[tui.Event][]*action, str string, exit func(string)) {1364func parseKeymap(keymap map[tui.Event][]*action, str string) error {1365 var err error1366 masked := maskActionContents(str)1367 idx := 01368 for _, pairStr := range strings.Split(masked, ",") {1369 origPairStr := str[idx : idx+len(pairStr)]1370 idx += len(pairStr) + 113711372 pair := strings.SplitN(pairStr, ":", 2)1373 if len(pair) < 2 {1359 exit("bind action not specified: " + origPairStr)1374 return errors.New("bind action not specified: " + origPairStr)1375 }1376 var key tui.Event1377 if len(pair[0]) == 1 && pair[0][0] == escapedColon {1378 key = tui.Key(':')
1 unmodified line
1380 key = tui.Key(',')1381 } else if len(pair[0]) == 1 && pair[0][0] == escapedPlus {1382 key = tui.Key('+')1383 } else {1369 keys := parseKeyChordsImpl(pair[0], "key name required", exit)1384 keys, err := parseKeyChordsImpl(pair[0], "key name required")1385 if err != nil {1386 return err1387 }1388 key = firstKey(keys)1389 }1390 putAllowed := key.Type == tui.Rune && unicode.IsGraphic(key.Char)1373 keymap[key] = parseActionList(pair[1], origPairStr[len(pair[0])+1:], keymap[key], putAllowed, exit)1391 keymap[key], err = parseActionList(pair[1], origPairStr[len(pair[0])+1:], keymap[key], putAllowed)1392 if err != nil {1393 return err1394 }1395 }1396 return nil1397}13981399func isExecuteAction(str string) actionType {1400 masked := maskActionContents(":" + str)[1:]
57 unmodified lines
1458 }1459 return actIgnore1460}14611440func parseToggleSort(keymap map[tui.Event][]*action, str string) {1441 keys := parseKeyChords(str, "key name required")1462func parseToggleSort(keymap map[tui.Event][]*action, str string) error {1463 keys, err := parseKeyChords(str, "key name required")1464 if err != nil {1465 return err1466 }1467 if len(keys) != 1 {1443 errorExit("multiple keys specified")1468 return errors.New("multiple keys specified")1469 }1470 keymap[firstKey(keys)] = toActions(actToggleSort)1471 return nil1472}14731474func strLines(str string) []string {1475 return strings.Split(strings.TrimSuffix(str, "\n"), "\n")1476}14771452func parseSize(str string, maxPercent float64, label string) sizeSpec {1478func parseSize(str string, maxPercent float64, label string) (sizeSpec, error) {1479 var spec = sizeSpec{}1480 var val float641481 var err error1482 percent := strings.HasSuffix(str, "%")1483 if percent {1456 val = atof(str[:len(str)-1])1484 if val, err = atof(str[:len(str)-1]); err != nil {1485 return spec, err1486 }14871488 if val < 0 {1458 errorExit(label + " must be non-negative")1489 return spec, errors.New(label + " must be non-negative")1490 }1491 if val > maxPercent {1461 errorExit(fmt.Sprintf("%s too large (max: %d%%)", label, int(maxPercent)))1492 return spec, fmt.Errorf("%s too large (max: %d%%)", label, int(maxPercent))1493 }1494 } else {1495 if strings.Contains(str, ".") {1465 errorExit(label + " (without %) must be a non-negative integer")1496 return spec, errors.New(label + " (without %) must be a non-negative integer")1497 }14981499 i, err := atoi(str)1500 if err != nil {1501 return spec, err1502 }1468 val = float64(atoi(str))1503 val = float64(i)1504 if val < 0 {1470 errorExit(label + " must be non-negative")1505 return spec, errors.New(label + " must be non-negative")1506 }1507 }1473 return sizeSpec{val, percent}1508 return sizeSpec{val, percent}, nil1509}15101476func parseHeight(str string) heightSpec {1511func parseHeight(str string) (heightSpec, error) {1512 heightSpec := heightSpec{}1513 if strings.HasPrefix(str, "~") {1514 heightSpec.auto = true1515 str = str[1:]1516 }1517 if strings.HasPrefix(str, "-") {1518 if heightSpec.auto {1484 errorExit("negative(-) height is not compatible with adaptive(~) height")1519 return heightSpec, errors.New("negative(-) height is not compatible with adaptive(~) height")1520 }1521 heightSpec.inverse = true1522 str = str[1:]1523 }15241490 size := parseSize(str, 100, "height")1525 size, err := parseSize(str, 100, "height")1526 if err != nil {1527 return heightSpec, err1528 }1529 heightSpec.size = size.size1530 heightSpec.percent = size.percent1493 return heightSpec1531 return heightSpec, nil1532}15331496func parseLayout(str string) layoutType {1534func parseLayout(str string) (layoutType, error) {1535 switch str {1536 case "default":1499 return layoutDefault1537 return layoutDefault, nil1538 case "reverse":1501 return layoutReverse1539 return layoutReverse, nil1540 case "reverse-list":1503 return layoutReverseList1504 default:1505 errorExit("invalid layout (expected: default / reverse / reverse-list)")1541 return layoutReverseList, nil1542 }1507 return layoutDefault1543 return layoutDefault, errors.New("invalid layout (expected: default / reverse / reverse-list)")1544}15451510func parseInfoStyle(str string) (infoStyle, string) {1546func parseInfoStyle(str string) (infoStyle, string, error) {1547 switch str {1548 case "default":1513 return infoDefault, ""1549 return infoDefault, "", nil1550 case "right":1515 return infoRight, ""1551 return infoRight, "", nil1552 case "inline":1517 return infoInline, defaultInfoPrefix1553 return infoInline, defaultInfoPrefix, nil1554 case "inline-right":1519 return infoInlineRight, ""1555 return infoInlineRight, "", nil1556 case "hidden":1521 return infoHidden, ""1522 default:1523 type infoSpec struct {1524 name string1525 style infoStyle1557 return infoHidden, "", nil1558 }1559 type infoSpec struct {1560 name string1561 style infoStyle1562 }1563 for _, spec := range []infoSpec{1564 {"inline", infoInline},1565 {"inline-right", infoInlineRight}} {1566 if strings.HasPrefix(str, spec.name+":") {1567 return spec.style, strings.ReplaceAll(str[len(spec.name)+1:], "\n", " "), nil1568 }1527 for _, spec := range []infoSpec{1528 {"inline", infoInline},1529 {"inline-right", infoInlineRight}} {1530 if strings.HasPrefix(str, spec.name+":") {1531 return spec.style, strings.ReplaceAll(str[len(spec.name)+1:], "\n", " ")1532 }1533 }1534 errorExit("invalid info style (expected: default|right|hidden|inline[-right][:PREFIX])")1569 }1536 return infoDefault, ""1570 return infoDefault, "", errors.New("invalid info style (expected: default|right|hidden|inline[-right][:PREFIX])")1571}15721539func parsePreviewWindow(opts *previewOpts, input string) {1540 parsePreviewWindowImpl(opts, input, errorExit)1573func parsePreviewWindow(opts *previewOpts, input string) error {1574 return parsePreviewWindowImpl(opts, input)1575}15761543func parsePreviewWindowImpl(opts *previewOpts, input string, exit func(string)) {1577func parsePreviewWindowImpl(opts *previewOpts, input string) error {1578 var err error1579 tokenRegex := regexp.MustCompile(`[:,]*(<([1-9][0-9]*)\(([^)<]+)\)|[^,:]+)`)1580 sizeRegex := regexp.MustCompile("^[0-9]+%?$")1581 offsetRegex := regexp.MustCompile(`^(\+{-?[0-9]+})?([+-][0-9]+)*(-?/[1-9][0-9]*)?$`)1582 headerRegex := regexp.MustCompile("^~(0|[1-9][0-9]*)$")1583 tokens := tokenRegex.FindAllStringSubmatch(input, -1)1584 var alternative string1585 for _, match := range tokens {1586 if len(match[2]) > 0 {1552 opts.threshold = atoi(match[2])1587 if opts.threshold, err = atoi(match[2]); err != nil {1588 return err1589 }1590 alternative = match[3]1591 continue1592 }1593 token := match[1]
52 unmodified lines
1646 case "nofollow":1647 opts.follow = false1648 default:1649 if headerRegex.MatchString(token) {1613 opts.headerLines = atoi(token[1:])1650 if opts.headerLines, err = atoi(token[1:]); err != nil {1651 return err1652 }1653 } else if sizeRegex.MatchString(token) {1615 opts.size = parseSize(token, 99, "window size")1654 if opts.size, err = parseSize(token, 99, "window size"); err != nil {1655 return err1656 }1657 } else if offsetRegex.MatchString(token) {1658 opts.scroll = token1659 } else {1619 exit("invalid preview window option: " + token)1620 return1660 return errors.New("invalid preview window option: " + token)1661 }1662 }1663 }1664 if len(alternative) > 0 {1665 alternativeOpts := *opts1666 opts.alternative = &alternativeOpts1667 opts.alternative.hidden = false1668 opts.alternative.alternative = nil1629 parsePreviewWindowImpl(opts.alternative, alternative, exit)1669 err = parsePreviewWindowImpl(opts.alternative, alternative)1670 }1671 return err1672}16731633func parseMargin(opt string, margin string) [4]sizeSpec {1674func parseMargin(opt string, margin string) ([4]sizeSpec, error) {1675 margins := strings.Split(margin, ",")1635 checked := func(str string) sizeSpec {1676 checked := func(str string) (sizeSpec, error) {1677 return parseSize(str, 49, opt)1678 }1679 switch len(margins) {1680 case 1:1640 m := checked(margins[0])1641 return [4]sizeSpec{m, m, m, m}1681 m, e := checked(margins[0])1682 return [4]sizeSpec{m, m, m, m}, e1683 case 2:1643 tb := checked(margins[0])1644 rl := checked(margins[1])1645 return [4]sizeSpec{tb, rl, tb, rl}1684 tb, e := checked(margins[0])1685 if e != nil {1686 return defaultMargin(), e1687 }1688 rl, e := checked(margins[1])1689 if e != nil {1690 return defaultMargin(), e1691 }1692 return [4]sizeSpec{tb, rl, tb, rl}, nil1693 case 3:1647 t := checked(margins[0])1648 rl := checked(margins[1])1649 b := checked(margins[2])1650 return [4]sizeSpec{t, rl, b, rl}1694 t, e := checked(margins[0])1695 if e != nil {1696 return defaultMargin(), e1697 }1698 rl, e := checked(margins[1])1699 if e != nil {1700 return defaultMargin(), e1701 }1702 b, e := checked(margins[2])1703 if e != nil {1704 return defaultMargin(), e1705 }1706 return [4]sizeSpec{t, rl, b, rl}, nil1707 case 4:1652 return [4]sizeSpec{1653 checked(margins[0]), checked(margins[1]),1654 checked(margins[2]), checked(margins[3])}1655 default:1656 errorExit("invalid " + opt + ": " + margin)1708 t, e := checked(margins[0])1709 if e != nil {1710 return defaultMargin(), e1711 }1712 r, e := checked(margins[1])1713 if e != nil {1714 return defaultMargin(), e1715 }1716 b, e := checked(margins[2])1717 if e != nil {1718 return defaultMargin(), e1719 }1720 l, e := checked(margins[3])1721 if e != nil {1722 return defaultMargin(), e1723 }1724 return [4]sizeSpec{t, r, b, l}, nil1725 }1658 return defaultMargin()1726 return [4]sizeSpec{}, errors.New("invalid " + opt + ": " + margin)1727}17281661func parseOptions(opts *Options, allArgs []string) {1729func parseOptions(opts *Options, allArgs []string) error {1730 var err error1731 var historyMax int1732 if opts.History == nil {1733 historyMax = defaultHistoryMax1734 } else {1735 historyMax = opts.History.maxSize1736 }1668 setHistory := func(path string) {1737 setHistory := func(path string) error {1738 h, e := NewHistory(path, historyMax)1739 if e != nil {1671 errorExit(e.Error())1740 return e1741 }1742 opts.History = h1743 return nil1744 }1675 setHistoryMax := func(max int) {1745 setHistoryMax := func(max int) error {1746 historyMax = max1747 if historyMax < 1 {1678 errorExit("history max must be a positive integer")1748 return errors.New("history max must be a positive integer")1749 }1750 if opts.History != nil {1751 opts.History.maxSize = historyMax1752 }1753 return nil1754 }1755 validateJumpLabels := false1756 clearExitingOpts := func() {1757 // Last-one-wins strategy1758 opts.Bash = false1759 opts.Zsh = false1760 opts.Fish = false1761 opts.Help = false1762 opts.Version = false1763 }1764 for i := 0; i < len(allArgs); i++ {1765 arg := allArgs[i]1766 switch arg {1767 case "--bash":1768 clearExitingOpts()1769 opts.Bash = true1690 if opts.Zsh || opts.Fish {1691 errorExit("cannot specify --bash with --zsh or --fish")1692 }1770 case "--zsh":1771 clearExitingOpts()1772 opts.Zsh = true1695 if opts.Bash || opts.Fish {1696 errorExit("cannot specify --zsh with --bash or --fish")1697 }1773 case "--fish":1774 clearExitingOpts()1775 opts.Fish = true1700 if opts.Bash || opts.Zsh {1701 errorExit("cannot specify --fish with --bash or --zsh")1702 }1776 case "-h", "--help":1704 help(exitOk)1777 clearExitingOpts()1778 opts.Help = true1779 case "--version":1780 clearExitingOpts()1781 opts.Version = true1782 case "-x", "--extended":1783 opts.Extended = true1784 case "-e", "--exact":1785 opts.Fuzzy = false
5 unmodified lines
1791 opts.Extended = false1792 case "+e", "--no-exact":1793 opts.Fuzzy = true1794 case "-q", "--query":1718 opts.Query = nextString(allArgs, &i, "query string required")1795 if opts.Query, err = nextString(allArgs, &i, "query string required"); err != nil {1796 return err1797 }1798 case "-f", "--filter":1720 filter := nextString(allArgs, &i, "query string required")1799 filter, err := nextString(allArgs, &i, "query string required")1800 if err != nil {1801 return err1802 }1803 opts.Filter = &filter1804 case "--literal":1805 opts.Normalize = false1806 case "--no-literal":1807 opts.Normalize = true1808 case "--algo":1727 opts.FuzzyAlgo = parseAlgo(nextString(allArgs, &i, "algorithm required (v1|v2)"))1809 str, err := nextString(allArgs, &i, "algorithm required (v1|v2)")1810 if err != nil {1811 return err1812 }1813 if opts.FuzzyAlgo, err = parseAlgo(str); err != nil {1814 return err1815 }1816 case "--scheme":1729 opts.Scheme = strings.ToLower(nextString(allArgs, &i, "scoring scheme required (default|path|history)"))1817 str, err := nextString(allArgs, &i, "scoring scheme required (default|path|history)")1818 if err != nil {1819 return err1820 }1821 opts.Scheme = strings.ToLower(str)1822 case "--expect":1731 for k, v := range parseKeyChords(nextString(allArgs, &i, "key names required"), "key names required") {1823 str, err := nextString(allArgs, &i, "key names required")1824 if err != nil {1825 return err1826 }1827 chords, err := parseKeyChords(str, "key names required")1828 if err != nil {1829 return err1830 }1831 for k, v := range chords {1832 opts.Expect[k] = v1833 }1834 case "--no-expect":1835 opts.Expect = make(map[tui.Event]string)
1 unmodified line
1837 opts.Phony = false1838 case "--disabled", "--phony":1839 opts.Phony = true1840 case "--tiebreak":1741 opts.Criteria = parseTiebreak(nextString(allArgs, &i, "sort criterion required"))1841 str, err := nextString(allArgs, &i, "sort criterion required")1842 if err != nil {1843 return err1844 }1845 if opts.Criteria, err = parseTiebreak(str); err != nil {1846 return err1847 }1848 case "--bind":1743 parseKeymap(opts.Keymap, nextString(allArgs, &i, "bind expression required"), errorExit)1849 str, err := nextString(allArgs, &i, "bind expression required")1850 if err != nil {1851 return err1852 }1853 if err := parseKeymap(opts.Keymap, str); err != nil {1854 return err1855 }1856 case "--color":1857 _, spec := optionalNextString(allArgs, &i)1858 if len(spec) == 0 {1859 opts.Theme = tui.EmptyTheme()1860 } else {1749 opts.Theme = parseTheme(opts.Theme, spec)1861 if opts.Theme, err = parseTheme(opts.Theme, spec); err != nil {1862 return err1863 }1864 }1865 case "--toggle-sort":1752 parseToggleSort(opts.Keymap, nextString(allArgs, &i, "key name required"))1866 str, err := nextString(allArgs, &i, "key name required")1867 if err != nil {1868 return err1869 }1870 if err := parseToggleSort(opts.Keymap, str); err != nil {1871 return err1872 }1873 case "-d", "--delimiter":1754 opts.Delimiter = delimiterRegexp(nextString(allArgs, &i, "delimiter required"))1874 str, err := nextString(allArgs, &i, "delimiter required")1875 if err != nil {1876 return err1877 }1878 opts.Delimiter = delimiterRegexp(str)1879 case "-n", "--nth":1756 opts.Nth = splitNth(nextString(allArgs, &i, "nth expression required"))1880 str, err := nextString(allArgs, &i, "nth expression required")1881 if err != nil {1882 return err1883 }1884 if opts.Nth, err = splitNth(str); err != nil {1885 return err1886 }1887 case "--with-nth":1758 opts.WithNth = splitNth(nextString(allArgs, &i, "nth expression required"))1888 str, err := nextString(allArgs, &i, "nth expression required")1889 if err != nil {1890 return err1891 }1892 if opts.WithNth, err = splitNth(str); err != nil {1893 return err1894 }1895 case "-s", "--sort":1760 opts.Sort = optionalNumeric(allArgs, &i, 1)1896 if opts.Sort, err = optionalNumeric(allArgs, &i, 1); err != nil {1897 return err1898 }1899 case "+s", "--no-sort":1900 opts.Sort = 01901 case "--track":1902 opts.Track = trackEnabled
7 unmodified lines
1910 opts.Case = CaseIgnore1911 case "+i":1912 opts.Case = CaseRespect1913 case "-m", "--multi":1776 opts.Multi = optionalNumeric(allArgs, &i, maxMulti)1914 if opts.Multi, err = optionalNumeric(allArgs, &i, maxMulti); err != nil {1915 return err1916 }1917 case "+m", "--no-multi":1918 opts.Multi = 01919 case "--ansi":1920 opts.Ansi = true
13 unmodified lines
1934 opts.Bold = true1935 case "--no-bold":1936 opts.Bold = false1937 case "--layout":1798 opts.Layout = parseLayout(1799 nextString(allArgs, &i, "layout required (default / reverse / reverse-list)"))1938 str, err := nextString(allArgs, &i, "layout required (default / reverse / reverse-list)")1939 if err != nil {1940 return err1941 }1942 if opts.Layout, err = parseLayout(str); err != nil {1943 return err1944 }1945 case "--reverse":1946 opts.Layout = layoutReverse1947 case "--no-reverse":1948 opts.Layout = layoutDefault
9 unmodified lines
1958 opts.Hscroll = true1959 case "--no-hscroll":1960 opts.Hscroll = false1961 case "--hscroll-off":1817 opts.HscrollOff = nextInt(allArgs, &i, "hscroll offset required")1962 if opts.HscrollOff, err = nextInt(allArgs, &i, "hscroll offset required"); err != nil {1963 return err1964 }1965 case "--scroll-off":1819 opts.ScrollOff = nextInt(allArgs, &i, "scroll offset required")1966 if opts.ScrollOff, err = nextInt(allArgs, &i, "scroll offset required"); err != nil {1967 return err1968 }1969 case "--filepath-word":1970 opts.FileWord = true1971 case "--no-filepath-word":1972 opts.FileWord = false1973 case "--info":1825 opts.InfoStyle, opts.InfoPrefix = parseInfoStyle(1826 nextString(allArgs, &i, "info style required"))1974 str, err := nextString(allArgs, &i, "info style required")1975 if err != nil {1976 return err1977 }1978 if opts.InfoStyle, opts.InfoPrefix, err = parseInfoStyle(str); err != nil {1979 return err1980 }1981 case "--no-info":1982 opts.InfoStyle = infoHidden1983 case "--inline-info":1984 opts.InfoStyle = infoInline1985 opts.InfoPrefix = defaultInfoPrefix1986 case "--no-inline-info":1987 opts.InfoStyle = infoDefault1988 case "--separator":1835 separator := nextString(allArgs, &i, "separator character required")1989 separator, err := nextString(allArgs, &i, "separator character required")1990 if err != nil {1991 return err1992 }1993 opts.Separator = &separator1994 case "--no-separator":1995 nosep := ""1996 opts.Separator = &nosep
7 unmodified lines
2004 case "--no-scrollbar":2005 noBar := ""2006 opts.Scrollbar = &noBar2007 case "--jump-labels":1851 opts.JumpLabels = nextString(allArgs, &i, "label characters required")2008 if opts.JumpLabels, err = nextString(allArgs, &i, "label characters required"); err != nil {2009 return err2010 }2011 validateJumpLabels = true2012 case "-1", "--select-1":2013 opts.Select1 = true2014 case "+1", "--no-select-1":
16 unmodified lines
2031 opts.PrintQuery = true2032 case "--no-print-query":2033 opts.PrintQuery = false2034 case "--prompt":1876 opts.Prompt = nextString(allArgs, &i, "prompt string required")2035 opts.Prompt, err = nextString(allArgs, &i, "prompt string required")2036 if err != nil {2037 return err2038 }2039 case "--pointer":1878 opts.Pointer = firstLine(nextString(allArgs, &i, "pointer sign string required"))2040 str, err := nextString(allArgs, &i, "pointer sign string required")2041 if err != nil {2042 return err2043 }2044 opts.Pointer = firstLine(str)2045 case "--marker":1880 opts.Marker = firstLine(nextString(allArgs, &i, "selected sign string required"))2046 str, err := nextString(allArgs, &i, "selected sign string required")2047 if err != nil {2048 return err2049 }2050 opts.Marker = firstLine(str)2051 case "--sync":2052 opts.Sync = true2053 case "--no-sync", "--async":2054 opts.Sync = false2055 case "--no-history":2056 opts.History = nil2057 case "--history":1888 setHistory(nextString(allArgs, &i, "history file path required"))2058 str, err := nextString(allArgs, &i, "history file path required")2059 if err != nil {2060 return err2061 }2062 if err := setHistory(str); err != nil {2063 return err2064 }2065 case "--history-size":1890 setHistoryMax(nextInt(allArgs, &i, "history max size required"))2066 n, err := nextInt(allArgs, &i, "history max size required")2067 if err != nil {2068 return err2069 }2070 if err := setHistoryMax(n); err != nil {2071 return err2072 }2073 case "--no-header":2074 opts.Header = []string{}2075 case "--no-header-lines":2076 opts.HeaderLines = 02077 case "--header":1896 opts.Header = strLines(nextString(allArgs, &i, "header string required"))2078 str, err := nextString(allArgs, &i, "header string required")2079 if err != nil {2080 return err2081 }2082 opts.Header = strLines(str)2083 case "--header-lines":1898 opts.HeaderLines = atoi(1899 nextString(allArgs, &i, "number of header lines required"))2084 if opts.HeaderLines, err = nextInt(allArgs, &i, "number of header lines required"); err != nil {2085 return err2086 }2087 case "--header-first":2088 opts.HeaderFirst = true2089 case "--no-header-first":2090 opts.HeaderFirst = false2091 case "--ellipsis":1905 opts.Ellipsis = nextString(allArgs, &i, "ellipsis string required")2092 if opts.Ellipsis, err = nextString(allArgs, &i, "ellipsis string required"); err != nil {2093 return err2094 }2095 case "--preview":1907 opts.Preview.command = nextString(allArgs, &i, "preview command required")2096 if opts.Preview.command, err = nextString(allArgs, &i, "preview command required"); err != nil {2097 return err2098 }2099 case "--no-preview":2100 opts.Preview.command = ""2101 case "--preview-window":1911 parsePreviewWindow(&opts.Preview,1912 nextString(allArgs, &i, "preview window layout required: [up|down|left|right][,SIZE[%]][,border-BORDER_OPT][,wrap][,cycle][,hidden][,+SCROLL[OFFSETS][/DENOM]][,~HEADER_LINES][,default]"))2102 str, err := nextString(allArgs, &i, "preview window layout required: [up|down|left|right][,SIZE[%]][,border-BORDER_OPT][,wrap][,cycle][,hidden][,+SCROLL[OFFSETS][/DENOM]][,~HEADER_LINES][,default]")2103 if err != nil {2104 return err2105 }2106 if err := parsePreviewWindow(&opts.Preview, str); err != nil {2107 return err2108 }2109 case "--height":1914 opts.Height = parseHeight(nextString(allArgs, &i, "height required: [~]HEIGHT[%]"))2110 str, err := nextString(allArgs, &i, "height required: [~]HEIGHT[%]")2111 if err != nil {2112 return err2113 }2114 if opts.Height, err = parseHeight(str); err != nil {2115 return err2116 }2117 case "--min-height":1916 opts.MinHeight = nextInt(allArgs, &i, "height required: HEIGHT")2118 if opts.MinHeight, err = nextInt(allArgs, &i, "height required: HEIGHT"); err != nil {2119 return err2120 }2121 case "--no-height":2122 opts.Height = heightSpec{}2123 case "--no-margin":2124 opts.Margin = defaultMargin()
2 unmodified lines
2127 case "--no-border":2128 opts.BorderShape = tui.BorderNone2129 case "--border":2130 hasArg, arg := optionalNextString(allArgs, &i)1927 opts.BorderShape = parseBorder(arg, !hasArg)2131 if opts.BorderShape, err = parseBorder(arg, !hasArg); err != nil {2132 return err2133 }2134 case "--no-border-label":2135 opts.BorderLabel.label = ""2136 case "--border-label":1931 opts.BorderLabel.label = nextString(allArgs, &i, "label required")2137 opts.BorderLabel.label, err = nextString(allArgs, &i, "label required")2138 if err != nil {2139 return err2140 }2141 case "--border-label-pos":1933 pos := nextString(allArgs, &i, "label position required (positive or negative integer or 'center')")1934 parseLabelPosition(&opts.BorderLabel, pos)2142 pos, err := nextString(allArgs, &i, "label position required (positive or negative integer or 'center')")2143 if err != nil {2144 return err2145 }2146 if err := parseLabelPosition(&opts.BorderLabel, pos); err != nil {2147 return err2148 }2149 case "--no-preview-label":2150 opts.PreviewLabel.label = ""2151 case "--preview-label":1938 opts.PreviewLabel.label = nextString(allArgs, &i, "preview label required")2152 if opts.PreviewLabel.label, err = nextString(allArgs, &i, "preview label required"); err != nil {2153 return err2154 }2155 case "--preview-label-pos":1940 pos := nextString(allArgs, &i, "preview label position required (positive or negative integer or 'center')")1941 parseLabelPosition(&opts.PreviewLabel, pos)2156 pos, err := nextString(allArgs, &i, "preview label position required (positive or negative integer or 'center')")2157 if err != nil {2158 return err2159 }2160 if err := parseLabelPosition(&opts.PreviewLabel, pos); err != nil {2161 return err2162 }2163 case "--no-unicode":2164 opts.Unicode = false2165 case "--unicode":2166 opts.Unicode = true
1 unmodified line
2168 opts.Ambidouble = true2169 case "--no-ambidouble":2170 opts.Ambidouble = false2171 case "--margin":1951 opts.Margin = parseMargin(1952 "margin",1953 nextString(allArgs, &i, "margin required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))2172 str, err := nextString(allArgs, &i, "margin required (TRBL / TB,RL / T,RL,B / T,R,B,L)")2173 if err != nil {2174 return err2175 }2176 if opts.Margin, err = parseMargin("margin", str); err != nil {2177 return err2178 }2179 case "--padding":1955 opts.Padding = parseMargin(1956 "padding",1957 nextString(allArgs, &i, "padding required (TRBL / TB,RL / T,RL,B / T,R,B,L)"))2180 str, err := nextString(allArgs, &i, "padding required (TRBL / TB,RL / T,RL,B / T,R,B,L)")2181 if err != nil {2182 return err2183 }2184 if opts.Padding, err = parseMargin("padding", str); err != nil {2185 return err2186 }2187 case "--tabstop":1959 opts.Tabstop = nextInt(allArgs, &i, "tab stop required")2188 if opts.Tabstop, err = nextInt(allArgs, &i, "tab stop required"); err != nil {2189 return err2190 }2191 case "--with-shell":1961 opts.WithShell = nextString(allArgs, &i, "shell command and flags required")2192 if opts.WithShell, err = nextString(allArgs, &i, "shell command and flags required"); err != nil {2193 return err2194 }2195 case "--listen", "--listen-unsafe":2196 given, str := optionalNextString(allArgs, &i)2197 addr := defaultListenAddr2198 if given {2199 var err error2200 addr, err = parseListenAddress(str)2201 if err != nil {1969 errorExit(err.Error())2202 return err2203 }2204 }2205 opts.ListenAddr = &addr2206 opts.Unsafe = arg == "--listen-unsafe"
4 unmodified lines
2211 opts.ClearOnExit = true2212 case "--no-clear":2213 opts.ClearOnExit = false2214 case "--walker":1982 opts.WalkerOpts = parseWalkerOpts(nextString(allArgs, &i, "walker options required [file][,dir][,follow][,hidden]"))2215 str, err := nextString(allArgs, &i, "walker options required [file][,dir][,follow][,hidden]")2216 if err != nil {2217 return err2218 }2219 if opts.WalkerOpts, err = parseWalkerOpts(str); err != nil {2220 return err2221 }2222 case "--walker-root":1984 opts.WalkerRoot = nextString(allArgs, &i, "directory required")2223 if opts.WalkerRoot, err = nextString(allArgs, &i, "directory required"); err != nil {2224 return err2225 }2226 case "--walker-skip":1986 opts.WalkerSkip = filterNonEmpty(strings.Split(nextString(allArgs, &i, "directory names to ignore required"), ","))1987 case "--version":1988 opts.Version = true2227 str, err := nextString(allArgs, &i, "directory names to ignore required")2228 if err != nil {2229 return err2230 }2231 opts.WalkerSkip = filterNonEmpty(strings.Split(str, ","))2232 case "--profile-cpu":1990 opts.CPUProfile = nextString(allArgs, &i, "file path required: cpu")2233 if opts.CPUProfile, err = nextString(allArgs, &i, "file path required: cpu"); err != nil {2234 return err2235 }2236 case "--profile-mem":1992 opts.MEMProfile = nextString(allArgs, &i, "file path required: mem")2237 if opts.MEMProfile, err = nextString(allArgs, &i, "file path required: mem"); err != nil {2238 return err2239 }2240 case "--profile-block":1994 opts.BlockProfile = nextString(allArgs, &i, "file path required: block")2241 if opts.BlockProfile, err = nextString(allArgs, &i, "file path required: block"); err != nil {2242 return err2243 }2244 case "--profile-mutex":1996 opts.MutexProfile = nextString(allArgs, &i, "file path required: mutex")2245 if opts.MutexProfile, err = nextString(allArgs, &i, "file path required: mutex"); err != nil {2246 return err2247 }2248 case "--":2249 // Ignored2250 default:2251 if match, value := optString(arg, "--algo="); match {2001 opts.FuzzyAlgo = parseAlgo(value)2252 if opts.FuzzyAlgo, err = parseAlgo(value); err != nil {2253 return err2254 }2255 } else if match, value := optString(arg, "--scheme="); match {2256 opts.Scheme = strings.ToLower(value)2257 } else if match, value := optString(arg, "-q", "--query="); match {2258 opts.Query = value
1 unmodified line
2260 opts.Filter = &value2261 } else if match, value := optString(arg, "-d", "--delimiter="); match {2262 opts.Delimiter = delimiterRegexp(value)2263 } else if match, value := optString(arg, "--border="); match {2011 opts.BorderShape = parseBorder(value, false)2264 if opts.BorderShape, err = parseBorder(value, false); err != nil {2265 return err2266 }2267 } else if match, value := optString(arg, "--border-label="); match {2268 opts.BorderLabel.label = value2269 } else if match, value := optString(arg, "--border-label-pos="); match {2015 parseLabelPosition(&opts.BorderLabel, value)2270 if err := parseLabelPosition(&opts.BorderLabel, value); err != nil {2271 return err2272 }2273 } else if match, value := optString(arg, "--preview-label="); match {2274 opts.PreviewLabel.label = value2275 } else if match, value := optString(arg, "--preview-label-pos="); match {2019 parseLabelPosition(&opts.PreviewLabel, value)2276 if err := parseLabelPosition(&opts.PreviewLabel, value); err != nil {2277 return err2278 }2279 } else if match, value := optString(arg, "--prompt="); match {2280 opts.Prompt = value2281 } else if match, value := optString(arg, "--pointer="); match {2282 opts.Pointer = firstLine(value)2283 } else if match, value := optString(arg, "--marker="); match {2284 opts.Marker = firstLine(value)2285 } else if match, value := optString(arg, "-n", "--nth="); match {2027 opts.Nth = splitNth(value)2286 if opts.Nth, err = splitNth(value); err != nil {2287 return err2288 }2289 } else if match, value := optString(arg, "--with-nth="); match {2029 opts.WithNth = splitNth(value)2290 if opts.WithNth, err = splitNth(value); err != nil {2291 return err2292 }2293 } else if match, _ := optString(arg, "-s", "--sort="); match {2294 opts.Sort = 1 // Don't care2295 } else if match, value := optString(arg, "-m", "--multi="); match {2033 opts.Multi = atoi(value)2296 if opts.Multi, err = atoi(value); err != nil {2297 return err2298 }2299 } else if match, value := optString(arg, "--height="); match {2035 opts.Height = parseHeight(value)2300 if opts.Height, err = parseHeight(value); err != nil {2301 return err2302 }2303 } else if match, value := optString(arg, "--min-height="); match {2037 opts.MinHeight = atoi(value)2304 if opts.MinHeight, err = atoi(value); err != nil {2305 return err2306 }2307 } else if match, value := optString(arg, "--layout="); match {2039 opts.Layout = parseLayout(value)2308 if opts.Layout, err = parseLayout(value); err != nil {2309 return err2310 }2311 } else if match, value := optString(arg, "--info="); match {2041 opts.InfoStyle, opts.InfoPrefix = parseInfoStyle(value)2312 if opts.InfoStyle, opts.InfoPrefix, err = parseInfoStyle(value); err != nil {2313 return err2314 }2315 } else if match, value := optString(arg, "--separator="); match {2316 opts.Separator = &value2317 } else if match, value := optString(arg, "--scrollbar="); match {2318 opts.Scrollbar = &value2319 } else if match, value := optString(arg, "--toggle-sort="); match {2047 parseToggleSort(opts.Keymap, value)2320 if err := parseToggleSort(opts.Keymap, value); err != nil {2321 return err2322 }2323 } else if match, value := optString(arg, "--expect="); match {2049 for k, v := range parseKeyChords(value, "key names required") {2324 chords, err := parseKeyChords(value, "key names required")2325 if err != nil {2326 return err2327 }2328 for k, v := range chords {2329 opts.Expect[k] = v2330 }2331 } else if match, value := optString(arg, "--tiebreak="); match {2053 opts.Criteria = parseTiebreak(value)2332 if opts.Criteria, err = parseTiebreak(value); err != nil {2333 return err2334 }2335 } else if match, value := optString(arg, "--color="); match {2055 opts.Theme = parseTheme(opts.Theme, value)2336 if opts.Theme, err = parseTheme(opts.Theme, value); err != nil {2337 return err2338 }2339 } else if match, value := optString(arg, "--bind="); match {2057 parseKeymap(opts.Keymap, value, errorExit)2340 if err := parseKeymap(opts.Keymap, value); err != nil {2341 return err2342 }2343 } else if match, value := optString(arg, "--history="); match {2059 setHistory(value)2344 if err := setHistory(value); err != nil {2345 return err2346 }2347 } else if match, value := optString(arg, "--history-size="); match {2061 setHistoryMax(atoi(value))2348 n, err := atoi(value)2349 if err != nil {2350 return err2351 }2352 if err := setHistoryMax(n); err != nil {2353 return err2354 }2355 } else if match, value := optString(arg, "--header="); match {2356 opts.Header = strLines(value)2357 } else if match, value := optString(arg, "--header-lines="); match {2065 opts.HeaderLines = atoi(value)2358 if opts.HeaderLines, err = atoi(value); err != nil {2359 return err2360 }2361 } else if match, value := optString(arg, "--ellipsis="); match {2362 opts.Ellipsis = value2363 } else if match, value := optString(arg, "--preview="); match {2364 opts.Preview.command = value2365 } else if match, value := optString(arg, "--preview-window="); match {2071 parsePreviewWindow(&opts.Preview, value)2366 if err := parsePreviewWindow(&opts.Preview, value); err != nil {2367 return err2368 }2369 } else if match, value := optString(arg, "--margin="); match {2073 opts.Margin = parseMargin("margin", value)2370 if opts.Margin, err = parseMargin("margin", value); err != nil {2371 return err2372 }2373 } else if match, value := optString(arg, "--padding="); match {2075 opts.Padding = parseMargin("padding", value)2374 if opts.Padding, err = parseMargin("padding", value); err != nil {2375 return err2376 }2377 } else if match, value := optString(arg, "--tabstop="); match {2077 opts.Tabstop = atoi(value)2378 if opts.Tabstop, err = atoi(value); err != nil {2379 return err2380 }2381 } else if match, value := optString(arg, "--with-shell="); match {2382 opts.WithShell = value2383 } else if match, value := optString(arg, "--listen="); match {2384 addr, err := parseListenAddress(value)2385 if err != nil {2083 errorExit(err.Error())2386 return err2387 }2388 opts.ListenAddr = &addr2389 opts.Unsafe = false2390 } else if match, value := optString(arg, "--listen-unsafe="); match {2391 addr, err := parseListenAddress(value)2392 if err != nil {2090 errorExit(err.Error())2393 return err2394 }2395 opts.ListenAddr = &addr2396 opts.Unsafe = true2397 } else if match, value := optString(arg, "--walker="); match {2095 opts.WalkerOpts = parseWalkerOpts(value)2398 if opts.WalkerOpts, err = parseWalkerOpts(value); err != nil {2399 return err2400 }2401 } else if match, value := optString(arg, "--walker-root="); match {2402 opts.WalkerRoot = value2403 } else if match, value := optString(arg, "--walker-skip="); match {2404 opts.WalkerSkip = filterNonEmpty(strings.Split(value, ","))2405 } else if match, value := optString(arg, "--hscroll-off="); match {2101 opts.HscrollOff = atoi(value)2406 if opts.HscrollOff, err = atoi(value); err != nil {2407 return err2408 }2409 } else if match, value := optString(arg, "--scroll-off="); match {2103 opts.ScrollOff = atoi(value)2410 if opts.ScrollOff, err = atoi(value); err != nil {2411 return err2412 }2413 } else if match, value := optString(arg, "--jump-labels="); match {2414 opts.JumpLabels = value2415 validateJumpLabels = true2416 } else {2108 errorExit("unknown option: " + arg)2417 return errors.New("unknown option: " + arg)2418 }2419 }2420 }24212422 if opts.HeaderLines < 0 {2114 errorExit("header lines must be a non-negative integer")2423 return errors.New("header lines must be a non-negative integer")2424 }24252426 if opts.HscrollOff < 0 {2118 errorExit("hscroll offset must be a non-negative integer")2427 return errors.New("hscroll offset must be a non-negative integer")2428 }24292430 if opts.ScrollOff < 0 {2122 errorExit("scroll offset must be a non-negative integer")2431 return errors.New("scroll offset must be a non-negative integer")2432 }24332434 if opts.Tabstop < 1 {2126 errorExit("tab stop must be a positive integer")2435 return errors.New("tab stop must be a positive integer")2436 }24372438 if len(opts.JumpLabels) == 0 {2130 errorExit("empty jump labels")2439 return errors.New("empty jump labels")2440 }24412442 if validateJumpLabels {2443 for _, r := range opts.JumpLabels {2444 if r < 32 || r > 126 {2136 errorExit("non-ascii jump labels are not allowed")2445 return errors.New("non-ascii jump labels are not allowed")2446 }2447 }2448 }2449 return err2450}24512452func validateSign(sign string, signOptName string) error {2453 if sign == "" {
4 unmodified lines
2458 }2459 return nil2460}24612462// This function can have side-effects and alter some global states.2463// So we run it on fzf.Run and not on ParseOptions.2152func postProcessOptions(opts *Options) {2464func postProcessOptions(opts *Options) error {2465 if opts.Ambidouble {2466 uniseg.EastAsianAmbiguousWidth = 22467 }24682469 if err := validateSign(opts.Pointer, "pointer"); err != nil {2158 errorExit(err.Error())2470 return err2471 }24722473 if err := validateSign(opts.Marker, "marker"); err != nil {2162 errorExit(err.Error())2474 return err2475 }24762165 if !opts.Version && !tui.IsLightRendererSupported() && opts.Height.size > 0 {2166 errorExit("--height option is currently not supported on this platform")2477 if !tui.IsLightRendererSupported() && opts.Height.size > 0 {2478 return errors.New("--height option is currently not supported on this platform")2479 }24802481 if opts.Scrollbar != nil {2482 runes := []rune(*opts.Scrollbar)2483 if len(runes) > 2 {2172 errorExit("--scrollbar should be given one or two characters")2484 return errors.New("--scrollbar should be given one or two characters")2485 }2486 for _, r := range runes {2487 if uniseg.StringWidth(string(r)) != 1 {2176 errorExit("scrollbar display width should be 1")2488 return errors.New("scrollbar display width should be 1")2489 }2490 }2491 }2492
45 unmodified lines
25382539 if opts.Height.auto {2540 for _, s := range []sizeSpec{opts.Margin[0], opts.Margin[2]} {2541 if s.percent {2230 errorExit("adaptive height is not compatible with top/bottom percent margin")2542 return errors.New("adaptive height is not compatible with top/bottom percent margin")2543 }2544 }2545 for _, s := range []sizeSpec{opts.Padding[0], opts.Padding[2]} {2546 if s.percent {2235 errorExit("adaptive height is not compatible with top/bottom percent padding")2547 return errors.New("adaptive height is not compatible with top/bottom percent padding")2548 }2549 }2550 }2551
2 unmodified lines
2554 if !opts.Extended || len(opts.Nth) == 1 {2555 for _, r := range opts.Nth {2556 if r.begin == rangeEllipsis && r.end == rangeEllipsis {2557 opts.Nth = make([]Range, 0)2246 return2558 break2559 }2560 }2561 }2562
13 unmodified lines
2576 theme.Cursor = boldify(theme.Cursor)2577 theme.Spinner = boldify(theme.Spinner)2578 }25792268 processScheme(opts)2580 return processScheme(opts)2581}25822271func expectsArbitraryString(opt string) bool {2272 switch opt {2273 case "-q", "--query", "-f", "--filter", "--header", "--prompt":2274 return true2275 }2276 return false2277}22782583// ParseOptions parses command-line options2280func ParseOptions() *Options {2584func ParseOptions(useDefaults bool, args []string) (*Options, error) {2585 opts := defaultOptions()25862283 for idx, arg := range os.Args[1:] {2284 if arg == "--version" && (idx == 0 || idx > 0 && !expectsArbitraryString(os.Args[idx])) {2285 opts.Version = true2286 return opts2287 }2288 }2587 if useDefaults {2588 // 1. Options from $FZF_DEFAULT_OPTS_FILE2589 if path := os.Getenv("FZF_DEFAULT_OPTS_FILE"); path != "" {2590 bytes, err := os.ReadFile(path)2591 if err != nil {2592 return nil, errors.New("$FZF_DEFAULT_OPTS_FILE: " + err.Error())2593 }25942290 // 1. Options from $FZF_DEFAULT_OPTS_FILE2291 if path := os.Getenv("FZF_DEFAULT_OPTS_FILE"); path != "" {2292 bytes, err := os.ReadFile(path)2293 if err != nil {2294 errorContext = "$FZF_DEFAULT_OPTS_FILE: "2295 errorExit(err.Error())2595 words, parseErr := shellwords.Parse(string(bytes))2596 if parseErr != nil {2597 return nil, errors.New(path + ": " + parseErr.Error())2598 }2599 if len(words) > 0 {2600 if err := parseOptions(opts, words); err != nil {2601 return nil, errors.New(path + ": " + err.Error())2602 }2603 }2604 }26052606 // 2. Options from $FZF_DEFAULT_OPTS string2298 words, parseErr := shellwords.Parse(string(bytes))2607 words, parseErr := shellwords.Parse(os.Getenv("FZF_DEFAULT_OPTS"))2608 if parseErr != nil {2300 errorContext = path + ": "2301 errorExit(parseErr.Error())2609 return nil, errors.New("$FZF_DEFAULT_OPTS: " + parseErr.Error())2610 }2611 if len(words) > 0 {2304 parseOptions(opts, words)2612 if err := parseOptions(opts, words); err != nil {2613 return nil, errors.New("$FZF_DEFAULT_OPTS: " + err.Error())2614 }2615 }2616 }26172308 // 2. Options from $FZF_DEFAULT_OPTS string2309 words, parseErr := shellwords.Parse(os.Getenv("FZF_DEFAULT_OPTS"))2310 errorContext = "$FZF_DEFAULT_OPTS: "2311 if parseErr != nil {2312 errorExit(parseErr.Error())2618 // 3. Options from command-line arguments2619 if err := parseOptions(opts, args); err != nil {2620 return nil, err2621 }2314 if len(words) > 0 {2315 parseOptions(opts, words)2316 }26222318 // 3. Options from command-line arguments2319 errorContext = ""2320 parseOptions(opts, os.Args[1:])23212623 if err := opts.initProfiling(); err != nil {2323 errorExit("failed to start pprof profiles: " + err.Error())2624 return nil, errors.New("failed to start pprof profiles: " + err.Error())2625 }26262326 postProcessOptions(opts)23272328 return opts2627 return opts, nil2628}
modified:src/pattern_test.go+18 added-26 removed
62 unmodified lines
63 t.Errorf("%v", terms)64 }65}6667func buildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,68 withPos bool, cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {69 return BuildPattern(NewChunkCache(), make(map[string]*Pattern),70 fuzzy, fuzzyAlgo, extended, caseMode, normalize, forward,71 withPos, cacheable, nth, delimiter, runes)72}7374func TestExact(t *testing.T) {68 defer clearPatternCache()69 clearPatternCache()70 pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, false, true,75 pattern := buildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, false, true,76 []Range{}, Delimiter{}, []rune("'abc"))77 chars := util.ToChars([]byte("aabbcc abc"))78 res, pos := algo.ExactMatchNaive(79 pattern.caseSensitive, pattern.normalize, pattern.forward, &chars, pattern.termSets[0][0].text, true, nil)
5 unmodified lines
85 }86}8788func TestEqual(t *testing.T) {84 defer clearPatternCache()85 clearPatternCache()86 pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune("^AbC$"))89 pattern := buildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune("^AbC$"))9091 match := func(str string, sidxExpected int, eidxExpected int) {92 chars := util.ToChars([]byte(str))93 res, pos := algo.EqualMatch(
12 unmodified lines
106 match(" AbC", 2, 5)107}108109func TestCaseSensitivity(t *testing.T) {107 defer clearPatternCache()108 clearPatternCache()109 pat1 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune("abc"))110 clearPatternCache()111 pat2 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune("Abc"))112 clearPatternCache()113 pat3 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseIgnore, false, true, false, true, []Range{}, Delimiter{}, []rune("abc"))114 clearPatternCache()115 pat4 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseIgnore, false, true, false, true, []Range{}, Delimiter{}, []rune("Abc"))116 clearPatternCache()117 pat5 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseRespect, false, true, false, true, []Range{}, Delimiter{}, []rune("abc"))118 clearPatternCache()119 pat6 := BuildPattern(true, algo.FuzzyMatchV2, false, CaseRespect, false, true, false, true, []Range{}, Delimiter{}, []rune("Abc"))110 pat1 := buildPattern(true, algo.FuzzyMatchV2, false, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune("abc"))111 pat2 := buildPattern(true, algo.FuzzyMatchV2, false, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune("Abc"))112 pat3 := buildPattern(true, algo.FuzzyMatchV2, false, CaseIgnore, false, true, false, true, []Range{}, Delimiter{}, []rune("abc"))113 pat4 := buildPattern(true, algo.FuzzyMatchV2, false, CaseIgnore, false, true, false, true, []Range{}, Delimiter{}, []rune("Abc"))114 pat5 := buildPattern(true, algo.FuzzyMatchV2, false, CaseRespect, false, true, false, true, []Range{}, Delimiter{}, []rune("abc"))115 pat6 := buildPattern(true, algo.FuzzyMatchV2, false, CaseRespect, false, true, false, true, []Range{}, Delimiter{}, []rune("Abc"))116117 if string(pat1.text) != "abc" || pat1.caseSensitive != false ||118 string(pat2.text) != "Abc" || pat2.caseSensitive != true ||119 string(pat3.text) != "abc" || pat3.caseSensitive != false ||
4 unmodified lines
124 }125}126127func TestOrigTextAndTransformed(t *testing.T) {132 pattern := BuildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune("jg"))128 pattern := buildPattern(true, algo.FuzzyMatchV2, true, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune("jg"))129 tokens := Tokenize("junegunn", Delimiter{})130 trans := Transform(tokens, []Range{{1, 1}})131132 origBytes := []byte("junegunn.choi")
25 unmodified lines
158}159160func TestCacheKey(t *testing.T) {161 test := func(extended bool, patStr string, expected string, cacheable bool) {166 clearPatternCache()167 pat := BuildPattern(true, algo.FuzzyMatchV2, extended, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune(patStr))162 pat := buildPattern(true, algo.FuzzyMatchV2, extended, CaseSmart, false, true, false, true, []Range{}, Delimiter{}, []rune(patStr))163 if pat.CacheKey() != expected {164 t.Errorf("Expected: %s, actual: %s", expected, pat.CacheKey())165 }166 if pat.cacheable != cacheable {167 t.Errorf("Expected: %t, actual: %t (%s)", cacheable, pat.cacheable, patStr)168 }174 clearPatternCache()169 }170 test(false, "foo !bar", "foo !bar", true)171 test(false, "foo | bar !baz", "foo | bar !baz", true)172 test(true, "foo bar baz", "foo\tbar\tbaz", true)
7 unmodified lines
180}181182func TestCacheable(t *testing.T) {183 test := func(fuzzy bool, str string, expected string, cacheable bool) {190 clearPatternCache()191 pat := BuildPattern(fuzzy, algo.FuzzyMatchV2, true, CaseSmart, true, true, false, true, []Range{}, Delimiter{}, []rune(str))184 pat := buildPattern(fuzzy, algo.FuzzyMatchV2, true, CaseSmart, true, true, false, true, []Range{}, Delimiter{}, []rune(str))185 if pat.CacheKey() != expected {186 t.Errorf("Expected: %s, actual: %s", expected, pat.CacheKey())187 }188 if cacheable != pat.cacheable {189 t.Errorf("Invalid Pattern.cacheable for \"%s\": %v (expected: %v)", str, pat.cacheable, cacheable)190 }198 clearPatternCache()191 }192 test(true, "foo bar", "foo\tbar", true)193 test(true, "foo 'bar", "foo\tbar", false)194 test(true, "foo !bar", "foo", false)
7 unmodified lines
modified:src/pattern.go+11 added-23 removed
58 unmodified lines
59 cacheKey string60 delimiter Delimiter61 nth []Range62 procFun map[termType]algo.Algo63 cache *ChunkCache64}6565var (66 _patternCache map[string]*Pattern67 _splitRegex *regexp.Regexp66var _splitRegex *regexp.Regexp68 _cache ChunkCache69)6768func init() {69 _splitRegex = regexp.MustCompile(" +")73 clearPatternCache()74 clearChunkCache()70}7177func clearPatternCache() {78 // We can uniquely identify the pattern for a given string since79 // search mode and caseMode do not change while the program is running80 _patternCache = make(map[string]*Pattern)81}8283func clearChunkCache() {84 _cache = NewChunkCache()85}8672// BuildPattern builds Pattern object from the given arguments88func BuildPattern(fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,73func BuildPattern(cache *ChunkCache, patternCache map[string]*Pattern, fuzzy bool, fuzzyAlgo algo.Algo, extended bool, caseMode Case, normalize bool, forward bool,74 withPos bool, cacheable bool, nth []Range, delimiter Delimiter, runes []rune) *Pattern {7576 var asString string77 if extended {
4 unmodified lines
82 } else {83 asString = string(runes)84 }8586 // We can uniquely identify the pattern for a given string since87 // search mode and caseMode do not change while the program is running101 cached, found := _patternCache[asString]88 cached, found := patternCache[asString]89 if found {90 return cached91 }92
46 unmodified lines
139 sortable: sortable,140 cacheable: cacheable,141 nth: nth,142 delimiter: delimiter,143 cache: cache,144 procFun: make(map[termType]algo.Algo)}145146 ptr.cacheKey = ptr.buildCacheKey()147 ptr.procFun[termFuzzy] = fuzzyAlgo
1 unmodified line
149 ptr.procFun[termExact] = algo.ExactMatchNaive150 ptr.procFun[termPrefix] = algo.PrefixMatch151 ptr.procFun[termSuffix] = algo.SuffixMatch152165 _patternCache[asString] = ptr153 patternCache[asString] = ptr154 return ptr155}156157func parseTerms(fuzzy bool, caseMode Case, normalize bool, str string) []termSet {
111 unmodified lines
269func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {270 // ChunkCache: Exact match271 cacheKey := p.CacheKey()272 if p.cacheable {285 if cached := _cache.Lookup(chunk, cacheKey); cached != nil {273 if cached := p.cache.Lookup(chunk, cacheKey); cached != nil {274 return cached275 }276 }277278 // Prefix/suffix cache291 space := _cache.Search(chunk, cacheKey)279 space := p.cache.Search(chunk, cacheKey)280281 matches := p.matchChunk(chunk, space, slab)282283 if p.cacheable {296 _cache.Add(chunk, cacheKey, matches)284 p.cache.Add(chunk, cacheKey, matches)285 }286 return matches287}288
126 unmodified lines
modified:src/reader.go+17 added-2 removed
91 unmodified lines
92 success := r.readFromCommand(command, environ)93 r.fin(success)94}9596func (r *Reader) readChannel(inputChan chan string) bool {97 for {98 item, more := <-inputChan99 if !more {100 break101 }102 if r.pusher([]byte(item)) {103 atomic.StoreInt32(&r.event, int32(EvtReadNew))104 }105 }106 return true107}108109// ReadSource reads data from the default command or from standard input97func (r *Reader) ReadSource(root string, opts walkerOpts, ignores []string) {110func (r *Reader) ReadSource(inputChan chan string, root string, opts walkerOpts, ignores []string) {111 r.startEventPoller()112 var success bool113 if inputChan != nil {114 success = r.readChannel(inputChan)100 if util.IsTty() {115 } else if util.IsTty() {116 cmd := os.Getenv("FZF_DEFAULT_COMMAND")117 if len(cmd) == 0 {118 success = r.readFiles(root, opts, ignores)119 } else {
158 unmodified lines
modified:src/server.go+11 added-16 removed
71 unmodified lines
72 }73 return listenAddress{parts[0], port}, nil74}7576func startHttpServer(address listenAddress, actionChannel chan []*action, responseChannel chan string) (int, error) {76func startHttpServer(address listenAddress, actionChannel chan []*action, responseChannel chan string) (net.Listener, int, error) {77 host := address.host78 port := address.port79 apiKey := os.Getenv("FZF_API_KEY")80 if !address.IsLocal() && len(apiKey) == 0 {81 return port, errors.New("FZF_API_KEY is required to allow remote access")81 return nil, port, errors.New("FZF_API_KEY is required to allow remote access")82 }83 addrStr := fmt.Sprintf("%s:%d", host, port)84 listener, err := net.Listen("tcp", addrStr)85 if err != nil {86 return port, fmt.Errorf("failed to listen on %s", addrStr)86 return nil, port, fmt.Errorf("failed to listen on %s", addrStr)87 }88 if port == 0 {89 addr := listener.Addr().String()90 parts := strings.Split(addr, ":")91 if len(parts) < 2 {92 return port, fmt.Errorf("cannot extract port: %s", addr)92 return nil, port, fmt.Errorf("cannot extract port: %s", addr)93 }94 var err error95 port, err = strconv.Atoi(parts[len(parts)-1])96 if err != nil {97 return port, err97 return nil, port, err98 }99 }100101 server := httpServer{
6 unmodified lines
108 for {109 conn, err := listener.Accept()110 if err != nil {111 if errors.Is(err, net.ErrClosed) {112 break113 } else {114 continue112 return113 }114 continue115 }116 conn.Write([]byte(server.handleHttpRequest(conn)))117 conn.Close()118 }120 listener.Close()119 }()120123 return port, nil121 return listener, port, nil122}123124// Here we are writing a simplistic HTTP server without using net/http125// package to reduce the size of the binary.
88 unmodified lines
214 return bad("incomplete request")215 }216 body = body[:contentLength]217220 errorMessage := ""221 actions := parseSingleActionList(strings.Trim(string(body), "\r\n"), func(message string) {222 errorMessage = message223 })224 if len(errorMessage) > 0 {225 return bad(errorMessage)218 actions, err := parseSingleActionList(strings.Trim(string(body), "\r\n"))219 if err != nil {220 return bad(err.Error())221 }222 if len(actions) == 0 {223 return bad("no action specified")224 }
28 unmodified lines
modified:src/terminal.go+141 added-69 removed
1package fzf23import (4 "bufio"5 "context"6 "encoding/json"7 "fmt"8 "io"9 "math"10 "net"11 "os"12 "os/signal"13 "regexp"14 "sort"
35 unmodified lines
50var whiteSuffix *regexp.Regexp51var offsetComponentRegex *regexp.Regexp52var offsetTrimCharsRegex *regexp.Regexp53var activeTempFiles []string54var activeTempFilesMutex sync.Mutex55var passThroughRegex *regexp.Regexp53var actionTypeRegex *regexp.Regexp5657const clearCode string = "\x1b[2J"5859// Number of maximum focus events to process synchronously
4 unmodified lines
64 whiteSuffix = regexp.MustCompile(`\s*$`)65 offsetComponentRegex = regexp.MustCompile(`([+-][0-9]+)|(-?/[1-9][0-9]*)`)66 offsetTrimCharsRegex = regexp.MustCompile(`[^0-9/+-]`)67 activeTempFiles = []string{}68 activeTempFilesMutex = sync.Mutex{}6970 // Parts of the preview output that should be passed through to the terminal71 // * https://github.com/tmux/tmux/wiki/FAQ#what-is-the-passthrough-escape-sequence-and-how-do-i-use-it72 // * https://sw.kovidgoyal.net/kitty/graphics-protocol
170 unmodified lines
243 padding [4]sizeSpec244 unicode bool245 listenAddr *listenAddress246 listenPort *int247 listener net.Listener248 listenUnsafe bool249 borderShape tui.BorderShape250 cleanExit bool251 executor *util.Executor
10 unmodified lines
262 hasLoadActions bool263 hasResizeActions bool264 triggerLoad bool265 reading bool262 running bool266 running *util.AtomicBool267 failed *string268 jumping jumpMode269 jumpLabels string270 printer func(string)
10 unmodified lines
281 previewed previewed282 previewBox *util.EventBox283 eventBox *util.EventBox284 mutex sync.Mutex281 initFunc func()285 initFunc func() error286 prevLines []itemLine287 suppress bool288 sigstop bool289 startChan chan fitpad286 killChan chan int290 killChan chan bool291 serverInputChan chan []*action292 serverOutputChan chan string293 eventChan chan tui.Event294 slab *util.Slab
48 unmodified lines
343 reqPreviewDisplay344 reqPreviewRefresh345 reqPreviewDelayed346 reqQuit347 reqFatal348)349350type action struct {351 t actionType
32 unmodified lines
384 actClose385 actDeleteChar386 actDeleteCharEof387 actEndOfLine388 actFatal389 actForwardChar390 actForwardWord391 actKillLine392 actKillWord
123 unmodified lines
516 pwindow tui.Window517 pwindowSize tui.TermSize518 scrollOffset int519 list []*Item520 env []string521}522523type previewResult struct {524 version int64
18 unmodified lines
543 addEvent := func(e tui.Event, a actionType) {544 keymap[e] = toActions(a)545 }546547 add(tui.Fatal, actFatal)548 add(tui.Invalid, actInvalid)549 add(tui.CtrlA, actBeginningOfLine)550 add(tui.CtrlB, actBackwardChar)551 add(tui.CtrlC, actAbort)
97 unmodified lines
649 return int(size)650}651652// NewTerminal returns new Terminal object645func NewTerminal(opts *Options, eventBox *util.EventBox, executor *util.Executor) *Terminal {653func NewTerminal(opts *Options, eventBox *util.EventBox, executor *util.Executor) (*Terminal, error) {654 input := trimQuery(opts.Query)655 var delay time.Duration656 if opts.Tac {657 delay = initialDelayTac
9 unmodified lines
667 previewBox = util.NewEventBox()668 }669 var renderer tui.Renderer670 fullscreen := !opts.Height.auto && (opts.Height.size == 0 || opts.Height.percent && opts.Height.size == 100)671 var err error672 if fullscreen {673 if tui.HasFullscreenRenderer() {674 renderer = tui.NewFullscreenRenderer(opts.Theme, opts.Black, opts.Mouse)675 } else {667 renderer = tui.NewLightRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit,676 renderer, err = tui.NewLightRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit,677 true, func(h int) int { return h })678 }679 } else {680 maxHeightFunc := func(termHeight int) int {
7 unmodified lines
688 }689 effectiveMinHeight += borderLines(opts.BorderShape)690 return util.Min(termHeight, util.Max(evaluateHeight(opts, termHeight), effectiveMinHeight))691 }683 renderer = tui.NewLightRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit, false, maxHeightFunc)692 renderer, err = tui.NewLightRenderer(opts.Theme, opts.Black, opts.Mouse, opts.Tabstop, opts.ClearOnExit, false, maxHeightFunc)693 }694 if err != nil {695 return nil, err696 }697 wordRubout := "[^\\pL\\pN][\\pL\\pN]"698 wordNext := "[\\pL\\pN][^\\pL\\pN]|(.$)"699 if opts.FileWord {700 sep := regexp.QuoteMeta(string(os.PathSeparator))
3 unmodified lines
704 keymapCopy := make(map[tui.Event][]*action)705 for key, action := range opts.Keymap {706 keymapCopy[key] = action707 }708709 t := Terminal{710 initDelay: delay,711 infoStyle: opts.InfoStyle,712 infoPrefix: opts.InfoPrefix,
53 unmodified lines
766 hasFocusActions: false,767 hasLoadActions: false,768 triggerLoad: false,769 reading: true,757 running: true,770 running: util.NewAtomicBool(true),771 failed: nil,772 jumping: jumpDisabled,773 jumpLabels: opts.JumpLabels,774 printer: opts.Printer,
12 unmodified lines
787 sigstop: false,788 slab: util.MakeSlab(slab16Size, slab32Size),789 theme: opts.Theme,790 startChan: make(chan fitpad, 1),778 killChan: make(chan int),791 killChan: make(chan bool),792 serverInputChan: make(chan []*action, 100),793 serverOutputChan: make(chan string),794 eventChan: make(chan tui.Event, 6), // (load + result + zero|one) | (focus) | (resize) | (GetChar)795 tui: renderer,783 initFunc: func() { renderer.Init() },796 initFunc: func() error { return renderer.Init() },797 executing: util.NewAtomicBool(false),798 lastAction: actStart,799 lastFocus: minItem.Index()}800 t.prompt, t.promptLen = t.parsePrompt(opts.Prompt)
43 unmodified lines
844 _, t.hasFocusActions = t.keymap[tui.Focus.AsEvent()]845 _, t.hasLoadActions = t.keymap[tui.Load.AsEvent()]846847 if t.listenAddr != nil {835 port, err := startHttpServer(*t.listenAddr, t.serverInputChan, t.serverOutputChan)848 listener, port, err := startHttpServer(*t.listenAddr, t.serverInputChan, t.serverOutputChan)849 if err != nil {837 errorExit(err.Error())850 return nil, err851 }852 t.listener = listener853 t.listenPort = &port854 }855842 return &t856 return &t, nil857}858859func (t *Terminal) environ() []string {860 env := os.Environ()
1255 unmodified lines
2116 }2117 }21182119 height := t.pwindow.Height()2106 header := []string{}2120 body := t.previewer.lines2121 headerLines := t.previewOpts.headerLines2122 // Do not enable preview header lines if it's value is too large2123 if headerLines > 0 && headerLines < util.Min(len(body), height) {2111 header = t.previewer.lines[0:headerLines]2124 header := t.previewer.lines[0:headerLines]2125 body = t.previewer.lines[headerLines:]2126 // Always redraw header2127 t.renderPreviewText(height, header, 0, false)2128 t.pwindow.MoveAndClear(t.pwindow.Y(), 0)
115 unmodified lines
2244 if y+requiredLines == height {2245 t.pwindow.Move(height-1, maxWidth-1)2246 t.previewed.filled = true2247 break Loop2235 } else {2236 t.pwindow.MoveAndClear(y+requiredLines, 0)2248 }2249 t.pwindow.MoveAndClear(y+requiredLines, 0)2250 }2251 }22522253 if len(passThroughs) > 0 && len(line) == 0 {
242 unmodified lines
2496 skipChars++2497 case 'q':2498 flags.forceUpdate = true2499 // query flag is not skipped2488 default:2489 break2500 }2501 }25022503 matchWithoutFlags := "{" + match[skipChars:]
17 unmodified lines
25212522func writeTemporaryFile(data []string, printSep string) string {2523 f, err := os.CreateTemp("", "fzf-preview-*")2524 if err != nil {2515 errorExit("Unable to create temporary file")2525 // Unable to create temporary file2526 // FIXME: Should we terminate the program?2527 return ""2528 }2529 defer f.Close()25302531 f.WriteString(strings.Join(data, printSep))2532 f.WriteString(printSep)2533 activeTempFilesMutex.Lock()2534 activeTempFiles = append(activeTempFiles, f.Name())2535 activeTempFilesMutex.Unlock()2536 return f.Name()2537}25382539func cleanTemporaryFiles() {2540 activeTempFilesMutex.Lock()2541 for _, filename := range activeTempFiles {2542 os.Remove(filename)2543 }2544 activeTempFiles = []string{}2545 activeTempFilesMutex.Unlock()2546}25472548type replacePlaceholderParams struct {2549 template string
301 unmodified lines
2851 t.deselectItem(item)2852 return true2853}28542839func (t *Terminal) killPreview(code int) {2855func (t *Terminal) killPreview() {2856 select {2841 case t.killChan <- code:2857 case t.killChan <- true:2858 default:2843 if code != exitCancel {2844 t.eventBox.Set(EvtQuit, code)2845 }2859 }2860}28612862func (t *Terminal) cancelPreview() {2850 t.killPreview(exitCancel)2863 select {2864 case t.killChan <- false:2865 default:2866 }2867}28682869func (t *Terminal) pwindowSize() tui.TermSize {2870 if t.pwindow == nil {
15 unmodified lines
2886 return minItem.Index()2887}28882889// Loop is called to start Terminal I/O2874func (t *Terminal) Loop() {2890func (t *Terminal) Loop() error {2891 // prof := profile.Start(profile.ProfilePath("/tmp/"))2892 fitpad := <-t.startChan2893 fit := fitpad.fit2894 if fit >= 0 {
15 unmodified lines
2910 }2911 return util.Min(termHeight, contentHeight+pad)2912 })2913 }29142915 // Context2916 ctx, cancel := context.WithCancel(context.Background())29172918 { // Late initialization2919 intChan := make(chan os.Signal, 1)2920 signal.Notify(intChan, os.Interrupt, syscall.SIGTERM)2921 go func() {2922 for {2923 select {2924 case <-ctx.Done():2925 return2902 for s := range intChan {2903 // Don't quit by SIGINT while executing because it should be for the executing command and not for fzf itself2904 if !(s == os.Interrupt && t.executing.Get()) {2905 t.reqBox.Set(reqQuit, nil)2926 case s := <-intChan:2927 // Don't quit by SIGINT while executing because it should be for the executing command and not for fzf itself2928 if !(s == os.Interrupt && t.executing.Get()) {2929 t.reqBox.Set(reqQuit, nil)2930 }2931 }2932 }2933 }()29342935 contChan := make(chan os.Signal, 1)2936 notifyOnCont(contChan)2937 go func() {2938 for {2914 <-contChan2915 t.reqBox.Set(reqReinit, nil)2939 select {2940 case <-ctx.Done():2941 return2942 case <-contChan:2943 t.reqBox.Set(reqReinit, nil)2944 }2945 }2946 }()29472948 if !t.tui.ShouldEmitResizeEvent() {2949 resizeChan := make(chan os.Signal, 1)2950 notifyOnResize(resizeChan) // Non-portable2951 go func() {2952 for {2924 <-resizeChan2925 t.reqBox.Set(reqResize, nil)2953 select {2954 case <-ctx.Done():2955 return2956 case <-resizeChan:2957 t.reqBox.Set(reqResize, nil)2958 }2959 }2960 }()2961 }29622963 t.mutex.Lock()2931 t.initFunc()2964 if err := t.initFunc(); err != nil {2965 t.mutex.Unlock()2966 cancel()2967 t.eventBox.Set(EvtQuit, quitSignal{ExitError, err})2968 return err2969 }2970 t.termSize = t.tui.Size()2971 t.resizeWindows(false)2972 t.window.Erase()2973 t.printPrompt()
8 unmodified lines
2982 }()29832984 // Keep the spinner spinning2985 go func() {2948 for {2986 for t.running.Get() {2987 t.mutex.Lock()2988 reading := t.reading2989 t.mutex.Unlock()2990 time.Sleep(spinnerDuration)
6 unmodified lines
29972998 if t.hasPreviewer() {2999 go func() {3000 var version int643001 stop := false3002 for {3003 var items []*Item3004 var commandTemplate string3005 var pwindow tui.Window3006 var pwindowSize tui.TermSize3007 var env []string3008 initialOffset := 03009 t.previewBox.Wait(func(events *util.Events) {3010 for req, value := range *events {3011 switch req {3012 case reqQuit:3013 stop = true3014 return3015 case reqPreviewEnqueue:3016 request := value.(previewRequest)3017 commandTemplate = request.template3018 initialOffset = request.scrollOffset3019 items = request.list3020 pwindow = request.pwindow3021 pwindowSize = request.pwindowSize3022 env = request.env3023 }3024 }3025 events.Clear()3026 })3027 if stop {3028 break3029 }3030 version++3031 // We don't display preview window if no match3032 if items[0] != nil {3033 _, query := t.Input()3034 command := t.replacePlaceholder(commandTemplate, false, string(query), items)3035 cmd := t.executor.ExecCommand(command, true)2989 env := t.environ()3036 if pwindowSize.Lines > 0 {3037 lines := fmt.Sprintf("LINES=%d", pwindowSize.Lines)3038 columns := fmt.Sprintf("COLUMNS=%d", pwindowSize.Columns)3039 env = append(env, lines)
76 unmodified lines
3116 timer := time.NewTimer(previewDelayed)3117 Loop:3118 for {3119 select {3120 case <-ctx.Done():3121 break Loop3122 case <-timer.C:3123 t.reqBox.Set(reqPreviewDelayed, version)3076 case code := <-t.killChan:3077 if code != exitCancel {3124 case immediately := <-t.killChan:3125 if immediately {3126 util.KillCommand(cmd)3079 t.eventBox.Set(EvtQuit, code)3127 } else {3128 // We can immediately kill a long-running preview program3129 // once we started rendering its partial output3130 delay := previewCancelWait
38 unmodified lines
3169 refreshPreview := func(command string) {3170 if len(command) > 0 && t.canPreview() {3171 _, list := t.buildPlusList(command, false)3172 t.cancelPreview()3126 t.previewBox.Set(reqPreviewEnqueue, previewRequest{command, t.pwindow, t.pwindowSize(), t.evaluateScrollOffset(), list})3173 t.previewBox.Set(reqPreviewEnqueue, previewRequest{command, t.pwindow, t.pwindowSize(), t.evaluateScrollOffset(), list, t.environ()})3174 }3175 }31763177 go func() {3131 var focusedIndex int32 = minItem.Index()3178 var focusedIndex = minItem.Index()3179 var version int64 = -13180 running := true3134 code := exitError3181 code := ExitError3182 exit := func(getCode func() int) {3183 if t.hasPreviewer() {3184 t.previewBox.Set(reqQuit, nil)3185 }3186 if t.listener != nil {3187 t.listener.Close()3188 }3189 t.tui.Close()3190 code = getCode()3138 if code <= exitNoMatch && t.history != nil {3191 if code <= ExitNoMatch && t.history != nil {3192 t.history.append(string(t.input))3193 }3194 running = false3195 t.mutex.Unlock()
59 unmodified lines
3255 }3256 case reqClose:3257 exit(func() int {3258 if t.output() {3206 return exitOk3259 return ExitOk3260 }3208 return exitNoMatch3261 return ExitNoMatch3262 })3263 return3264 case reqPreviewDisplay:3265 result := value.(previewResult)
19 unmodified lines
3285 t.printPreviewDelayed()3286 case reqPrintQuery:3287 exit(func() int {3288 t.printer(string(t.input))3236 return exitOk3289 return ExitOk3290 })3291 return3292 case reqQuit:3240 exit(func() int { return exitInterrupt })3293 exit(func() int { return ExitInterrupt })3294 return3295 case reqFatal:3296 exit(func() int { return ExitError })3297 return3298 }3299 }3300 t.refresh()3301 t.mutex.Unlock()3302 })3303 }3248 // prof.Stop()3249 t.killPreview(code)33043305 t.eventBox.Set(EvtQuit, quitSignal{code, nil})3306 t.running.Set(false)3307 t.killPreview()3308 cancel()3309 }()33103311 looping := true3312 _, startEvent := t.keymap[tui.Start.AsEvent()]
1 unmodified line
3314 needBarrier := true3315 barrier := make(chan bool)3316 go func() {3317 for {3259 <-barrier3260 t.eventChan <- t.tui.GetChar()3318 select {3319 case <-ctx.Done():3320 return3321 case <-barrier:3322 }3323 select {3324 case <-ctx.Done():3325 return3326 case t.eventChan <- t.tui.GetChar():3327 }3328 }3329 }()3330 previewDraggingPos := -13331 barDragging := false
87 unmodified lines
3419 if keyMatch(key, event) {3420 t.pressed = ret3421 t.reqBox.Set(reqClose, nil)3422 t.mutex.Unlock()3356 return3423 return nil3424 }3425 }34263427 actionsFor := func(eventType tui.EventType) []*action {3428 return t.keymap[eventType.AsEvent()]3429 }34303431 var doAction func(*action) bool3365 var doActions func(actions []*action) bool3366 doActions = func(actions []*action) bool {3432 doActions := func(actions []*action) bool {3433 for iter := 0; iter <= maxFocusEvents; iter++ {3434 currentIndex := t.currentIndex()3435 for _, action := range actions {3436 if !doAction(action) {
61 unmodified lines
3498 valid, list := t.buildPlusList(t.previewOpts.command, false)3499 if valid {3500 t.cancelPreview()3501 t.previewBox.Set(reqPreviewEnqueue,3436 previewRequest{t.previewOpts.command, t.pwindow, t.pwindowSize(), t.evaluateScrollOffset(), list})3502 previewRequest{t.previewOpts.command, t.pwindow, t.pwindowSize(), t.evaluateScrollOffset(), list, t.environ()})3503 }3504 } else {3505 // Discard the preview content so that it won't accidentally appear3506 // when preview window is re-enabled and previewDelay is triggered
105 unmodified lines
3612 req(reqRedrawPreviewLabel)3613 }3614 case actTransform:3615 body := t.executeCommand(a.a, false, true, true, false)3550 actions := parseSingleActionList(strings.Trim(body, "\r\n"), func(message string) {})3551 return doActions(actions)3616 if actions, err := parseSingleActionList(strings.Trim(body, "\r\n")); err == nil {3617 return doActions(actions)3618 }3619 case actTransformBorderLabel:3620 label := t.executeCommand(a.a, false, true, true, true)3621 t.borderLabelOpts.label = label3622 if t.border != nil {
23 unmodified lines
3646 if current != nil {3647 t.input = current.text.ToRunes()3648 t.cx = len(t.input)3649 }3650 case actFatal:3651 req(reqFatal)3652 case actAbort:3653 req(reqQuit)3654 case actDeleteChar:3655 t.delChar()
417 unmodified lines
4073 break4074 }40754076 if me.Down {4008 mx_cons := util.Constrain(mx-t.promptLen, 0, len(t.input))4009 if my == t.promptLine() && mx_cons >= 0 {4077 mxCons := util.Constrain(mx-t.promptLen, 0, len(t.input))4078 if my == t.promptLine() && mxCons >= 0 {4079 // Prompt4011 t.cx = mx_cons + t.xoffset4080 t.cx = mxCons + t.xoffset4081 } else if my >= min {4082 t.vset(t.offset + my - min)4083 req(reqList)4084 evt := tui.RightClick
49 unmodified lines
4134 reloadSync = a.t == actReloadSync4135 t.reading = true4136 }4137 case actUnbind:4069 keys := parseKeyChords(a.a, "PANIC")4070 for key := range keys {4071 delete(t.keymap, key)4138 if keys, err := parseKeyChords(a.a, "PANIC"); err == nil {4139 for key := range keys {4140 delete(t.keymap, key)4141 }4142 }4143 case actRebind:4074 keys := parseKeyChords(a.a, "PANIC")4075 for key := range keys {4076 if originalAction, found := t.keymapOrg[key]; found {4077 t.keymap[key] = originalAction4144 if keys, err := parseKeyChords(a.a, "PANIC"); err == nil {4145 for key := range keys {4146 if originalAction, found := t.keymapOrg[key]; found {4147 t.keymap[key] = originalAction4148 }4149 }4150 }4151 case actChangePreview:4152 if t.previewOpts.command != a.a {
138 unmodified lines
4291 for _, event := range events {4292 t.reqBox.Set(event, nil)4293 }4294 }4295 return nil4296}42974298func (t *Terminal) constrain() {4299 // count of items to display allowed by filtering
105 unmodified lines
modified:src/tokenizer_test.go+5 added-4 removed
69 unmodified lines
70 input := " abc: def: ghi: jkl"71 {72 tokens := Tokenize(input, Delimiter{})73 {74 ranges := splitNth("1,2,3")74 ranges, _ := splitNth("1,2,3")75 tx := Transform(tokens, ranges)76 if joinTokens(tx) != "abc: def: ghi: " {77 t.Errorf("%s", tx)78 }79 }80 {81 ranges := splitNth("1..2,3,2..,1")81 ranges, _ := splitNth("1..2,3,2..,1")82 tx := Transform(tokens, ranges)83 if string(joinTokens(tx)) != "abc: def: ghi: def: ghi: jklabc: " ||84 len(tx) != 4 ||85 tx[0].text.ToString() != "abc: def: " || tx[0].prefixLength != 2 ||
6 unmodified lines
92 }93 {94 tokens := Tokenize(input, delimiterRegexp(":"))95 {96 ranges := splitNth("1..2,3,2..,1")96 ranges, _ := splitNth("1..2,3,2..,1")97 tx := Transform(tokens, ranges)98 if joinTokens(tx) != " abc: def: ghi: def: ghi: jkl abc:" ||99 len(tx) != 4 ||100 tx[0].text.ToString() != " abc: def:" || tx[0].prefixLength != 0 ||
6 unmodified lines
107 }108}109110func TestTransformIndexOutOfBounds(t *testing.T) {111 s, _ := splitNth("1")111 Transform([]Token{}, splitNth("1"))112 Transform([]Token{}, s)113}
modified:test/test_go.rb+1 added-1 removed
555 unmodified lines
556 end557558 def test_expect559 test = lambda do |key, feed, expected = key|560 tmux.send_keys "seq 1 100 | #{fzf(:expect, key)}", :Enter560 tmux.send_keys "seq 1 100 | #{fzf(:expect, key, :prompt, "[#{key}]")}", :Enter561 tmux.until { |lines| assert_equal ' 100/100', lines[-2] }562 tmux.send_keys '55'563 tmux.until { |lines| assert_equal ' 1/100', lines[-2] }564 tmux.send_keys(*feed)
3233 unmodified lines
deleted:main_test.go-174 removed
1package main23import (4 "bytes"5 "fmt"6 "go/ast"7 "go/build"8 "go/importer"9 "go/parser"10 "go/token"11 "go/types"12 "io/fs"13 "os"14 "os/exec"15 "path/filepath"16 "sort"17 "strings"18 "testing"19)2021func loadPackages(t *testing.T) []*build.Package {22 // If GOROOT is not set, use `go env GOROOT` to determine it since it23 // performs more work than just runtime.GOROOT(). For context, running24 // the tests with the "-trimpath" flag causes GOROOT to not be set.25 ctxt := &build.Default26 if ctxt.GOROOT == "" {27 cmd := exec.Command("go", "env", "GOROOT")28 out, err := cmd.CombinedOutput()29 out = bytes.TrimSpace(out)30 if err != nil {31 t.Fatalf("error running command: %q: %v\n%s", cmd.Args, err, out)32 }33 ctxt.GOROOT = string(out)34 }3536 wd, err := os.Getwd()37 if err != nil {38 t.Fatal(err)39 }4041 var pkgs []*build.Package42 seen := make(map[string]bool)43 err = filepath.WalkDir(wd, func(path string, d fs.DirEntry, err error) error {44 if err != nil {45 return err46 }47 name := d.Name()48 if d.IsDir() {49 if name == "" || name[0] == '.' || name[0] == '_' || name == "vendor" || name == "tmp" {50 return filepath.SkipDir51 }52 return nil53 }54 if d.Type().IsRegular() && filepath.Ext(name) == ".go" && !strings.HasSuffix(name, "_test.go") {55 dir := filepath.Dir(path)56 if !seen[dir] {57 pkg, err := ctxt.ImportDir(dir, build.ImportComment)58 if err != nil {59 return fmt.Errorf("%s: %s", dir, err)60 }61 if pkg.ImportPath == "" || pkg.ImportPath == "." {62 importPath, err := filepath.Rel(wd, dir)63 if err != nil {64 t.Fatal(err)65 }66 pkg.ImportPath = filepath.ToSlash(filepath.Join("github.com/junegunn/fzf", importPath))67 }6869 pkgs = append(pkgs, pkg)70 seen[dir] = true71 }72 }73 return nil74 })75 if err != nil {76 t.Fatal(err)77 }7879 sort.Slice(pkgs, func(i, j int) bool {80 return pkgs[i].ImportPath < pkgs[j].ImportPath81 })82 return pkgs83}8485var sourceImporter = importer.ForCompiler(token.NewFileSet(), "source", nil)8687func checkPackageForOsExit(t *testing.T, bpkg *build.Package, allowed map[string]int) (errOsExit bool) {88 var files []*ast.File89 fset := token.NewFileSet()90 for _, name := range bpkg.GoFiles {91 filename := filepath.Join(bpkg.Dir, name)92 af, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)93 if err != nil {94 t.Fatal(err)95 }96 files = append(files, af)97 }9899 info := types.Info{100 Uses: make(map[*ast.Ident]types.Object),101 }102 conf := types.Config{103 Importer: sourceImporter,104 }105 _, err := conf.Check(bpkg.Name, fset, files, &info)106 if err != nil {107 t.Fatal(err)108 }109110 wd, err := os.Getwd()111 if err != nil {112 t.Fatal(err)113 }114115 for id, obj := range info.Uses {116 if obj.Pkg() != nil && obj.Pkg().Name() == "os" && obj.Name() == "Exit" {117 pos := fset.Position(id.Pos())118119 name, err := filepath.Rel(wd, pos.Filename)120 if err != nil {121 t.Log(err)122 name = pos.Filename123 }124 name = filepath.ToSlash(name)125126 // Check if the usage is allowed127 if allowed[name] > 0 {128 allowed[name]--129 continue130 }131132 t.Errorf("os.Exit referenced at: %s:%d:%d", name, pos.Line, pos.Column)133 errOsExit = true134 }135 }136 return errOsExit137}138139// Enforce that src/util.Exit() is used instead of os.Exit by prohibiting140// references to it anywhere else in the fzf code base.141func TestOSExitNotAllowed(t *testing.T) {142 if testing.Short() {143 t.Skip("skipping: short test")144 }145 allowed := map[string]int{146 "src/util/atexit.go": 1, // os.Exit allowed 1 time in "atexit.go"147 }148 var errOsExit bool149 for _, pkg := range loadPackages(t) {150 t.Run(pkg.ImportPath, func(t *testing.T) {151 if checkPackageForOsExit(t, pkg, allowed) {152 errOsExit = true153 }154 })155 }156 if t.Failed() && errOsExit {157 var names []string158 for name := range allowed {159 names = append(names, fmt.Sprintf("%q", name))160 }161 sort.Strings(names)162163 const errMsg = `164Test failed because os.Exit was referenced outside of the following files:165166 %s167168Use github.com/junegunn/fzf/src/util.Exit() instead to exit the program.169This is enforced because calling os.Exit() prevents the functions170registered with util.AtExit() from running.`171172 t.Errorf(errMsg, strings.Join(names, "\n "))173 }174}
modified:main.go+31 added-4 removed
1 unmodified line
23import (4 _ "embed"5 "fmt"6 "os"7 "strings"89 fzf "github.com/junegunn/fzf/src"10 "github.com/junegunn/fzf/src/protector"11)1212var version string = "0.51"13var revision string = "devel"13var version = "0.51"14var revision = "devel"1516//go:embed shell/key-bindings.bash17var bashKeyBindings []byte18
14 unmodified lines
33 fmt.Println(strings.TrimSpace(string(content)))34 fmt.Println("### end: " + label + " ###")35}3637func exit(code int, err error) {38 if err != nil {39 os.Stderr.WriteString(err.Error() + "\n")40 }41 os.Exit(code)42}4344func main() {45 protector.Protect()38 options := fzf.ParseOptions()4647 options, err := fzf.ParseOptions(true, os.Args[1:])48 if err != nil {49 exit(fzf.ExitError, err)50 return51 }52 if options.Bash {53 printScript("key-bindings.bash", bashKeyBindings)54 printScript("completion.bash", bashCompletion)55 return
7 unmodified lines
63 printScript("key-bindings.fish", fishKeyBindings)64 fmt.Println("fzf_key_bindings")65 return66 }54 fzf.Run(options, version, revision)67 if options.Help {68 fmt.Print(fzf.Usage)69 return70 }71 if options.Version {72 if len(revision) > 0 {73 fmt.Printf("%s (%s)\n", version, revision)74 } else {75 fmt.Println(version)76 }77 return78 }7980 code, err := fzf.Run(options)81 exit(code, err)82}
modified:Makefile-1 removed
77 unmodified lines
7879test: $(SOURCES)80 [ -z "$$(gofmt -s -d src)" ] || (gofmt -s -d src; exit 1)81 SHELL=/bin/sh GOOS= $(GO) test -v -tags "$(TAGS)" \82 github.com/junegunn/fzf \82 github.com/junegunn/fzf/src \83 github.com/junegunn/fzf/src/algo \84 github.com/junegunn/fzf/src/tui \85 github.com/junegunn/fzf/src/util
102 unmodified lines