Add more tests of placeholder flags and simplify its logic (#2624)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* [tests] Test fzf's placeholders and escaping on practical commands This tests some reasonable commands in fzf's templates (for commands, previews, rebinds etc.), how are those commands escaped (backslashes, double quotes), and documents if the output is executable in cmd.exe. Both on Unix and Windows. * [tests] Add testing of placeholder parsing and matching Adds tests and bit of docs for the curly brackets placeholders in fzf's template strings. Also tests the "placeholder" regex. * [tests] Add more test cases of replacing placeholders focused on flags Replacing placeholders in templates is already tested, this adds tests that focus more on the parameters of placeholders - e.g. flags, token ranges. There is at least one test for each flag, not all combinations are tested though. * [refactoring] Split OS-specific function quoteEntry() to corresponding source file This is minor refactoring, and also the function's test was made crossplatform. * [refactoring] Simplify replacePlaceholder function Should be equivalent to the original, but has simpler structure.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+499 added−88 removed
- other:+499 added−88 removed
Provenance
- Commit
61339a8- Tree
e8bab76- Author
Vlastimil Ovčáčík <vovcacik@github.ovcacik.org>- Committer
GitHub <noreply@github.com>- Parent
50eb2e3
4 files changed+499 added−88 removed
modified:src/terminal_test.go+399 added-18 removed
1 package fzf2 3 import (4 "bytes"5+ "io"6+ "os"7 "regexp"8+ "strings"9 "testing"10 "text/template"11 12 "github.com/junegunn/fzf/src/util"13 )14 12-func newItem(str string) *Item {13- bytes := []byte(str)14- trimmed, _, _ := extractColor(str, nil, nil)15- return &Item{origText: &bytes, text: util.ToChars([]byte(trimmed))}16-}17-15 func TestReplacePlaceholder(t *testing.T) {16 item1 := newItem(" foo'bar \x1b[31mbaz\x1b[m")17 items1 := []*Item{item1, item1}18 items2 := []*Item{11 unmodified lines30 }31 }32 // helper function that converts template format into string and carries out the check()33 checkFormat := func(format string) {37- type quotes struct{ O, I string } // outer, inner quotes38- unixStyle := quotes{"'", "'\\''"}39- windowsStyle := quotes{"^\"", "'"}34+ type quotes struct{ O, I, S string } // outer, inner quotes, print separator35+ unixStyle := quotes{`'`, `'\''`, "\n"}36+ windowsStyle := quotes{`^"`, `'`, "\n"}37 var effectiveStyle quotes38 39 if util.IsWindows() {40 effectiveStyle = windowsStyle4 unmodified lines45 expected := templateToString(format, effectiveStyle)46 check(expected)47 }48 printsep := "\n"49+50+ /*51+ Test multiple placeholders and the function parameters.52+ */53+54 // {}, preserve ansi55 result = replacePlaceholder("echo {}", false, Delimiter{}, printsep, false, "query", items1)56 checkFormat("echo {{.O}} foo{{.I}}bar \x1b[31mbaz\x1b[m{{.O}}")57 78 unmodified lines136 regex = regexp.MustCompile("[oa]+")137 // foo'bar baz138 result = replacePlaceholder("echo {}/{1}/{3}/{2..3}", true, Delimiter{regex: regex}, printsep, false, "query", items1)139 checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}/{{.O}}f{{.O}}/{{.O}}r b{{.O}}/{{.O}}{{.I}}bar b{{.O}}")140+141+ /*142+ Test single placeholders, but focus on the placeholders' parameters (e.g. flags).143+ see: TestParsePlaceholder144+ */145+ items3 := []*Item{146+ // single line147+ newItem("1a 1b 1c 1d 1e 1f"),148+ // multi line149+ newItem("1a 1b 1c 1d 1e 1f"),150+ newItem("2a 2b 2c 2d 2e 2f"),151+ newItem("3a 3b 3c 3d 3e 3f"),152+ newItem("4a 4b 4c 4d 4e 4f"),153+ newItem("5a 5b 5c 5d 5e 5f"),154+ newItem("6a 6b 6c 6d 6e 6f"),155+ newItem("7a 7b 7c 7d 7e 7f"),156+ }157+ stripAnsi := false158+ printsep = "\n"159+ forcePlus := false160+ query := "sample query"161+162+ templateToOutput := make(map[string]string)163+ templateToFile := make(map[string]string) // same as above, but the file contents will be matched164+ // I. item type placeholder165+ templateToOutput[`{}`] = `{{.O}}1a 1b 1c 1d 1e 1f{{.O}}`166+ templateToOutput[`{+}`] = `{{.O}}1a 1b 1c 1d 1e 1f{{.O}} {{.O}}2a 2b 2c 2d 2e 2f{{.O}} {{.O}}3a 3b 3c 3d 3e 3f{{.O}} {{.O}}4a 4b 4c 4d 4e 4f{{.O}} {{.O}}5a 5b 5c 5d 5e 5f{{.O}} {{.O}}6a 6b 6c 6d 6e 6f{{.O}} {{.O}}7a 7b 7c 7d 7e 7f{{.O}}`167+ templateToOutput[`{n}`] = `0`168+ templateToOutput[`{+n}`] = `0 0 0 0 0 0 0`169+ templateToFile[`{f}`] = `1a 1b 1c 1d 1e 1f{{.S}}`170+ templateToFile[`{+f}`] = `1a 1b 1c 1d 1e 1f{{.S}}2a 2b 2c 2d 2e 2f{{.S}}3a 3b 3c 3d 3e 3f{{.S}}4a 4b 4c 4d 4e 4f{{.S}}5a 5b 5c 5d 5e 5f{{.S}}6a 6b 6c 6d 6e 6f{{.S}}7a 7b 7c 7d 7e 7f{{.S}}`171+ templateToFile[`{nf}`] = `0{{.S}}`172+ templateToFile[`{+nf}`] = `0{{.S}}0{{.S}}0{{.S}}0{{.S}}0{{.S}}0{{.S}}0{{.S}}`173+174+ // II. token type placeholders175+ templateToOutput[`{..}`] = templateToOutput[`{}`]176+ templateToOutput[`{1..}`] = templateToOutput[`{}`]177+ templateToOutput[`{..2}`] = `{{.O}}1a 1b{{.O}}`178+ templateToOutput[`{1..2}`] = templateToOutput[`{..2}`]179+ templateToOutput[`{-2..-1}`] = `{{.O}}1e 1f{{.O}}`180+ // shorthand for x..x range181+ templateToOutput[`{1}`] = `{{.O}}1a{{.O}}`182+ templateToOutput[`{1..1}`] = templateToOutput[`{1}`]183+ templateToOutput[`{-6}`] = templateToOutput[`{1}`]184+ // multiple ranges185+ templateToOutput[`{1,2}`] = templateToOutput[`{1..2}`]186+ templateToOutput[`{1,2,4}`] = `{{.O}}1a 1b 1d{{.O}}`187+ templateToOutput[`{1,2..4}`] = `{{.O}}1a 1b 1c 1d{{.O}}`188+ templateToOutput[`{1..2,-4..-3}`] = `{{.O}}1a 1b 1c 1d{{.O}}`189+ // flags190+ templateToOutput[`{+1}`] = `{{.O}}1a{{.O}} {{.O}}2a{{.O}} {{.O}}3a{{.O}} {{.O}}4a{{.O}} {{.O}}5a{{.O}} {{.O}}6a{{.O}} {{.O}}7a{{.O}}`191+ templateToOutput[`{+-1}`] = `{{.O}}1f{{.O}} {{.O}}2f{{.O}} {{.O}}3f{{.O}} {{.O}}4f{{.O}} {{.O}}5f{{.O}} {{.O}}6f{{.O}} {{.O}}7f{{.O}}`192+ templateToOutput[`{s1}`] = `{{.O}}1a {{.O}}`193+ templateToFile[`{f1}`] = `1a{{.S}}`194+ templateToOutput[`{+s1..2}`] = `{{.O}}1a 1b {{.O}} {{.O}}2a 2b {{.O}} {{.O}}3a 3b {{.O}} {{.O}}4a 4b {{.O}} {{.O}}5a 5b {{.O}} {{.O}}6a 6b {{.O}} {{.O}}7a 7b {{.O}}`195+ templateToFile[`{+sf1..2}`] = `1a 1b {{.S}}2a 2b {{.S}}3a 3b {{.S}}4a 4b {{.S}}5a 5b {{.S}}6a 6b {{.S}}7a 7b {{.S}}`196+197+ // III. query type placeholder198+ // query flag is not removed after parsing, so it gets doubled199+ // while the double q is invalid, it is useful here for testing purposes200+ templateToOutput[`{q}`] = "{{.O}}" + query + "{{.O}}"201+202+ // IV. escaping placeholder203+ templateToOutput[`\{}`] = `{}`204+ templateToOutput[`\{++}`] = `{++}`205+ templateToOutput[`{++}`] = templateToOutput[`{+}`]206+207+ for giveTemplate, wantOutput := range templateToOutput {208+ result = replacePlaceholder(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3)209+ checkFormat(wantOutput)210+ }211+ for giveTemplate, wantOutput := range templateToFile {212+ path := replacePlaceholder(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3)213+214+ data, err := readFile(path)215+ if err != nil {216+ t.Errorf("Cannot read the content of the temp file %s.", path)217+ }218+ result = string(data)219+220+ checkFormat(wantOutput)221+ }222 }223 140-func TestQuoteEntryCmd(t *testing.T) {224+func TestQuoteEntry(t *testing.T) {225+ type quotes struct{ E, O, SQ, DQ, BS string } // standalone escape, outer, single and double quotes, backslash226+ unixStyle := quotes{``, `'`, `'\''`, `"`, `\`}227+ windowsStyle := quotes{`^`, `^"`, `'`, `\^"`, `\\`}228+ var effectiveStyle quotes229+230+ if util.IsWindows() {231+ effectiveStyle = windowsStyle232+ } else {233+ effectiveStyle = unixStyle234+ }235+236 tests := map[string]string{142- `"`: `^"\^"^"`,143- `\`: `^"\\^"`,144- `\"`: `^"\\\^"^"`,145- `"\\\"`: `^"\^"\\\\\\\^"^"`,146- `&|<>()@^%!`: `^"^&^|^<^>^(^)^@^^^%^!^"`,147- `%USERPROFILE%`: `^"^%USERPROFILE^%^"`,148- `C:\Program Files (x86)\`: `^"C:\\Program Files ^(x86^)\\^"`,237+ `'`: `{{.O}}{{.SQ}}{{.O}}`,238+ `"`: `{{.O}}{{.DQ}}{{.O}}`,239+ `\`: `{{.O}}{{.BS}}{{.O}}`,240+ `\"`: `{{.O}}{{.BS}}{{.DQ}}{{.O}}`,241+ `"\\\"`: `{{.O}}{{.DQ}}{{.BS}}{{.BS}}{{.BS}}{{.DQ}}{{.O}}`,242+243+ `$`: `{{.O}}${{.O}}`,244+ `$HOME`: `{{.O}}$HOME{{.O}}`,245+ `'$HOME'`: `{{.O}}{{.SQ}}$HOME{{.SQ}}{{.O}}`,246+247+ `&`: `{{.O}}{{.E}}&{{.O}}`,248+ `|`: `{{.O}}{{.E}}|{{.O}}`,249+ `<`: `{{.O}}{{.E}}<{{.O}}`,250+ `>`: `{{.O}}{{.E}}>{{.O}}`,251+ `(`: `{{.O}}{{.E}}({{.O}}`,252+ `)`: `{{.O}}{{.E}}){{.O}}`,253+ `@`: `{{.O}}{{.E}}@{{.O}}`,254+ `^`: `{{.O}}{{.E}}^{{.O}}`,255+ `%`: `{{.O}}{{.E}}%{{.O}}`,256+ `!`: `{{.O}}{{.E}}!{{.O}}`,257+ `%USERPROFILE%`: `{{.O}}{{.E}}%USERPROFILE{{.E}}%{{.O}}`,258+ `C:\Program Files (x86)\`: `{{.O}}C:{{.BS}}Program Files {{.E}}(x86{{.E}}){{.BS}}{{.O}}`,259+ `"C:\Program Files"`: `{{.O}}{{.DQ}}C:{{.BS}}Program Files{{.DQ}}{{.O}}`,260 }261 262 for input, expected := range tests {152- escaped := quoteEntryCmd(input)263+ escaped := quoteEntry(input)264+ expected = templateToString(expected, effectiveStyle)265 if escaped != expected {266 t.Errorf("Input: %s, expected: %s, actual %s", input, expected, escaped)267 }268 }269 }270 271+// purpose of this test is to demonstrate some shortcomings of fzf's templating system on Unix272+func TestUnixCommands(t *testing.T) {273+ if util.IsWindows() {274+ t.SkipNow()275+ }276+ tests := []testCase{277+ // reference: give{template, query, items}, want{output OR match}278+279+ // 1) working examples280+281+ // paths that does not have to evaluated will work fine, when quoted282+ {give{`grep foo {}`, ``, newItems(`test`)}, want{output: `grep foo 'test'`}},283+ {give{`grep foo {}`, ``, newItems(`/home/user/test`)}, want{output: `grep foo '/home/user/test'`}},284+ {give{`grep foo {}`, ``, newItems(`./test`)}, want{output: `grep foo './test'`}},285+286+ // only placeholders are escaped as data, this will lookup tilde character in a test file in your home directory287+ // quoting the tilde is required (to be treated as string)288+ {give{`grep {} ~/test`, ``, newItems(`~`)}, want{output: `grep '~' ~/test`}},289+290+ // 2) problematic examples291+292+ // paths that need to expand some part of it won't work (special characters and variables)293+ {give{`cat {}`, ``, newItems(`~/test`)}, want{output: `cat '~/test'`}},294+ {give{`cat {}`, ``, newItems(`$HOME/test`)}, want{output: `cat '$HOME/test'`}},295+ }296+ testCommands(t, tests)297+}298+299+// purpose of this test is to demonstrate some shortcomings of fzf's templating system on Windows300+func TestWindowsCommands(t *testing.T) {301+ if !util.IsWindows() {302+ t.SkipNow()303+ }304+ tests := []testCase{305+ // reference: give{template, query, items}, want{output OR match}306+307+ // 1) working examples308+309+ // example of redundantly escaped backslash in the output, besides looking bit ugly, it won't cause any issue310+ {give{`type {}`, ``, newItems(`C:\test.txt`)}, want{output: `type ^"C:\\test.txt^"`}},311+ {give{`rg -- "package" {}`, ``, newItems(`.\test.go`)}, want{output: `rg -- "package" ^".\\test.go^"`}},312+ // example of mandatorily escaped backslash in the output, otherwise `rg -- "C:\test.txt"` is matching for tabulator313+ {give{`rg -- {}`, ``, newItems(`C:\test.txt`)}, want{output: `rg -- ^"C:\\test.txt^"`}},314+ // example of mandatorily escaped double quote in the output, otherwise `rg -- ""C:\\test.txt""` is not matching for the double quotes around the path315+ {give{`rg -- {}`, ``, newItems(`"C:\test.txt"`)}, want{output: `rg -- ^"\^"C:\\test.txt\^"^"`}},316+317+ // 2) problematic examples318+319+ // notepad++'s parser can't handle `-n"12"` generate by fzf, expects `-n12`320+ {give{`notepad++ -n{1} {2}`, ``, newItems(`12 C:\Work\Test Folder\File.txt`)}, want{output: `notepad++ -n^"12^" ^"C:\\Work\\Test Folder\\File.txt^"`}},321+322+ // cat is parsing `\"` as a part of the file path, double quote is illegal character for paths on Windows323+ // cat: "C:\\test.txt: Invalid argument324+ {give{`cat {}`, ``, newItems(`"C:\test.txt"`)}, want{output: `cat ^"\^"C:\\test.txt\^"^"`}},325+ // cat: "C:\\test.txt": Invalid argument326+ {give{`cmd /c {}`, ``, newItems(`cat "C:\test.txt"`)}, want{output: `cmd /c ^"cat \^"C:\\test.txt\^"^"`}},327+328+ // the "file" flag in the pattern won't create *.bat or *.cmd file so the command in the output tries to edit the file, instead of executing it329+ // the temp file contains: `cat "C:\test.txt"`330+ {give{`cmd /c {f}`, ``, newItems(`cat "C:\test.txt"`)}, want{match: `^cmd /c .*\fzf-preview-[0-9]{9}$`}},331+ }332+ testCommands(t, tests)333+}334+335+/*336+ Test typical valid placeholders and parsing of them.337+338+ Also since the parser assumes the input is matched with `placeholder` regex,339+ the regex is tested here as well.340+*/341+func TestParsePlaceholder(t *testing.T) {342+ // give, want pairs343+ templates := map[string]string{344+ // I. item type placeholder345+ `{}`: `{}`,346+ `{+}`: `{+}`,347+ `{n}`: `{n}`,348+ `{+n}`: `{+n}`,349+ `{f}`: `{f}`,350+ `{+nf}`: `{+nf}`,351+352+ // II. token type placeholders353+ `{..}`: `{..}`,354+ `{1..}`: `{1..}`,355+ `{..2}`: `{..2}`,356+ `{1..2}`: `{1..2}`,357+ `{-2..-1}`: `{-2..-1}`,358+ // shorthand for x..x range359+ `{1}`: `{1}`,360+ `{1..1}`: `{1..1}`,361+ `{-6}`: `{-6}`,362+ // multiple ranges363+ `{1,2}`: `{1,2}`,364+ `{1,2,4}`: `{1,2,4}`,365+ `{1,2..4}`: `{1,2..4}`,366+ `{1..2,-4..-3}`: `{1..2,-4..-3}`,367+ // flags368+ `{+1}`: `{+1}`,369+ `{+-1}`: `{+-1}`,370+ `{s1}`: `{s1}`,371+ `{f1}`: `{f1}`,372+ `{+s1..2}`: `{+s1..2}`,373+ `{+sf1..2}`: `{+sf1..2}`,374+375+ // III. query type placeholder376+ // query flag is not removed after parsing, so it gets doubled377+ // while the double q is invalid, it is useful here for testing purposes378+ `{q}`: `{qq}`,379+380+ // IV. escaping placeholder381+ `\{}`: `{}`,382+ `\{++}`: `{++}`,383+ `{++}`: `{+}`,384+ }385+386+ for giveTemplate, wantTemplate := range templates {387+ if !placeholder.MatchString(giveTemplate) {388+ t.Errorf(`given placeholder %s does not match placeholder regex, so attempt to parse it is unexpected`, giveTemplate)389+ continue390+ }391+392+ _, placeholderWithoutFlags, flags := parsePlaceholder(giveTemplate)393+ gotTemplate := placeholderWithoutFlags[:1] + flags.encodePlaceholder() + placeholderWithoutFlags[1:]394+395+ if gotTemplate != wantTemplate {396+ t.Errorf(`parsed placeholder "%s" into "%s", but want "%s"`, giveTemplate, gotTemplate, wantTemplate)397+ }398+ }399+}400+401+/* utilities section */402+403+// Item represents one line in fzf UI. Usually it is relative path to files and folders.404+func newItem(str string) *Item {405+ bytes := []byte(str)406+ trimmed, _, _ := extractColor(str, nil, nil)407+ return &Item{origText: &bytes, text: util.ToChars([]byte(trimmed))}408+}409+410+// Functions tested in this file require array of items (allItems). The array needs411+// to consist of at least two nils. This is helper function.412+func newItems(str ...string) []*Item {413+ result := make([]*Item, util.Max(len(str), 2))414+ for i, s := range str {415+ result[i] = newItem(s)416+ }417+ return result418+}419+420+// (for logging purposes)421+func (item *Item) String() string {422+ return item.AsString(true)423+}424+425 // Helper function to parse, execute and convert "text/template" to string. Panics on error.426 func templateToString(format string, data interface{}) string {427 bb := &bytes.Buffer{}428 3 unmodified lines432 }433 434 return bb.String()435 }436+437+// ad hoc types for test cases438+type give struct {439+ template string440+ query string441+ allItems []*Item442+}443+type want struct {444+ /*445+ Unix:446+ The `want.output` string is supposed to be formatted for evaluation by447+ `sh -c command` system call.448+449+ Windows:450+ The `want.output` string is supposed to be formatted for evaluation by451+ `cmd.exe /s /c "command"` system call. The `/s` switch enables so called old452+ behaviour, which is more favourable for nesting (possibly escaped)453+ special characters. This is the relevant section of `help cmd`:454+455+ ...old behavior is to see if the first character is456+ a quote character and if so, strip the leading character and457+ remove the last quote character on the command line, preserving458+ any text after the last quote character.459+ */460+ output string // literal output461+ match string // output is matched against this regex (when output is empty string)462+}463+type testCase struct {464+ give465+ want466+}467+468+func testCommands(t *testing.T, tests []testCase) {469+ // common test parameters470+ delim := "\t"471+ delimiter := Delimiter{str: &delim}472+ printsep := ""473+ stripAnsi := false474+ forcePlus := false475+476+ // evaluate the test cases477+ for idx, test := range tests {478+ gotOutput := replacePlaceholder(479+ test.give.template, stripAnsi, delimiter, printsep, forcePlus,480+ test.give.query,481+ test.give.allItems)482+ switch {483+ case test.want.output != "":484+ if gotOutput != test.want.output {485+ t.Errorf("tests[%v]:\ngave{\n\ttemplate: '%s',\n\tquery: '%s',\n\tallItems: %s}\nand got '%s',\nbut want '%s'",486+ idx,487+ test.give.template, test.give.query, test.give.allItems,488+ gotOutput, test.want.output)489+ }490+ case test.want.match != "":491+ wantMatch := strings.ReplaceAll(test.want.match, `\`, `\\`)492+ wantRegex := regexp.MustCompile(wantMatch)493+ if !wantRegex.MatchString(gotOutput) {494+ t.Errorf("tests[%v]:\ngave{\n\ttemplate: '%s',\n\tquery: '%s',\n\tallItems: %s}\nand got '%s',\nbut want '%s'",495+ idx,496+ test.give.template, test.give.query, test.give.allItems,497+ gotOutput, test.want.match)498+ }499+ default:500+ t.Errorf("tests[%v]: test case does not describe 'want' property", idx)501+ }502+ }503+}504+505+// naive encoder of placeholder flags506+func (flags placeholderFlags) encodePlaceholder() string {507+ encoded := ""508+ if flags.plus {509+ encoded += "+"510+ }511+ if flags.preserveSpace {512+ encoded += "s"513+ }514+ if flags.number {515+ encoded += "n"516+ }517+ if flags.file {518+ encoded += "f"519+ }520+ if flags.query {521+ encoded += "q"522+ }523+ return encoded524+}525+526+// can be replaced with os.ReadFile() in go 1.16+527+func readFile(path string) ([]byte, error) {528+ file, err := os.Open(path)529+ if err != nil {530+ return nil, err531+ }532+ defer file.Close()533+534+ data := make([]byte, 0, 128)535+ for {536+ if len(data) >= cap(data) {537+ d := append(data[:cap(data)], 0)538+ data = d[:len(data)]539+ }540+541+ n, err := file.Read(data[len(data):cap(data)])542+ data = data[:len(data)+n]543+ if err != nil {544+ if err == io.EOF {545+ err = nil546+ }547+ return data, err548+ }549+ }550+}modified:src/terminal_unix.go+5 added
3 unmodified lines4 5 import (6 "os"7 "os/signal"8+ "strings"9 "syscall"10 )11 12 func notifyOnResize(resizeChan chan<- os.Signal) {6 unmodified lines19 20 func notifyOnCont(resizeChan chan<- os.Signal) {21 signal.Notify(resizeChan, syscall.SIGCONT)22 }23+24+func quoteEntry(entry string) string {25+ return "'" + strings.Replace(entry, "'", "'\\''", -1) + "'"26+}modified:src/terminal_windows.go+11 added
2 unmodified lines3 package fzf4 5 import (6 "os"7+ "regexp"8+ "strings"9 )10 11 func notifyOnResize(resizeChan chan<- os.Signal) {12 // TODO5 unmodified lines18 19 func notifyOnCont(resizeChan chan<- os.Signal) {20 // NOOP21 }22+23+func quoteEntry(entry string) string {24+ escaped := strings.Replace(entry, `\`, `\\`, -1)25+ escaped = `"` + strings.Replace(escaped, `"`, `\"`, -1) + `"`26+ r, _ := regexp.Compile(`[&|<>()@^%!"]`)27+ return r.ReplaceAllStringFunc(escaped, func(match string) string {28+ return "^" + match29+ })30+}modified:src/terminal.go+84 added-70 removed
21 unmodified lines22 )23 24 // import "github.com/pkg/profile"25 26+/*27+ Placeholder regex is used to extract placeholders from fzf's template28+ strings. Acts as input validation for parsePlaceholder function.29+ Describes the syntax, but it is fairly lenient.30+31+ The following pseudo regex has been reverse engineered from the32+ implementation. It is overly strict, but better describes whats possible.33+ As such it is not useful for validation, but rather to generate test34+ cases for example.35+36+ \\?(?: # escaped type37+ {\+?s?f?RANGE(?:,RANGE)*} # token type38+ |{q} # query type39+ |{\+?n?f?} # item type (notice no mandatory element inside brackets)40+ )41+ RANGE = (?:42+ (?:-?[0-9]+)?\.\.(?:-?[0-9]+)? # ellipsis syntax for token range (x..y)43+ |-?[0-9]+ # shorthand syntax (x..x)44+ )45+*/46 var placeholder *regexp.Regexp47 var whiteSuffix *regexp.Regexp48 var offsetComponentRegex *regexp.Regexp49 var offsetTrimCharsRegex *regexp.Regexp1489 unmodified lines1539 return event.Type == key.Type && event.Char == key.Char ||1540 key.Type == tui.DoubleClick && event.Type == tui.Mouse && event.MouseEvent.Double1541 }1542 1523-func quoteEntryCmd(entry string) string {1524- escaped := strings.Replace(entry, `\`, `\\`, -1)1525- escaped = `"` + strings.Replace(escaped, `"`, `\"`, -1) + `"`1526- r, _ := regexp.Compile(`[&|<>()@^%!"]`)1527- return r.ReplaceAllStringFunc(escaped, func(match string) string {1528- return "^" + match1529- })1530-}1531-1532-func quoteEntry(entry string) string {1533- if util.IsWindows() {1534- return quoteEntryCmd(entry)1535- }1536- return "'" + strings.Replace(entry, "'", "'\\''", -1) + "'"1537-}1538-1543 func parsePlaceholder(match string) (bool, string, placeholderFlags) {1544 flags := placeholderFlags{}1545 1546 if match[0] == '\\' {17 unmodified lines1564 flags.file = true1565 skipChars++1566 case 'q':1567 flags.query = true1568+ // query flag is not skipped1569 default:1570 break1571 }1572 }79 unmodified lines1652 }1653 if selected[0] == nil {1654 selected = []*Item{}1655 }1656+1657+ // replace placeholders one by one1658 return placeholder.ReplaceAllStringFunc(template, func(match string) string {1659 escaped, match, flags := parsePlaceholder(match)1660 1654- if escaped {1655- return match1656- }1661+ // this function implements the effects a placeholder has on items1662+ var replace func(*Item) string1663 1658- // Current query1659- if match == "{q}" {1664+ // placeholder types (escaped, query type, item type, token type)1665+ switch {1666+ case escaped:1667+ return match1668+ case match == "{q}":1669 return quoteEntry(query)1661- }1662-1663- items := current1664- if flags.plus || forcePlus {1665- items = selected1666- }1667-1668- replacements := make([]string, len(items))1669-1670- if match == "{}" {1671- for idx, item := range items {1672- if flags.number {1670+ case match == "{}":1671+ replace = func(item *Item) string {1672+ switch {1673+ case flags.number:1674 n := int(item.text.Index)1675 if n < 0 {1675- replacements[idx] = ""1676- } else {1677- replacements[idx] = strconv.Itoa(n)1676+ return ""1677 }1679- } else if flags.file {1680- replacements[idx] = item.AsString(stripAnsi)1681- } else {1682- replacements[idx] = quoteEntry(item.AsString(stripAnsi))1678+ return strconv.Itoa(n)1679+ case flags.file:1680+ return item.AsString(stripAnsi)1681+ default:1682+ return quoteEntry(item.AsString(stripAnsi))1683 }1684 }1685- if flags.file {1686- return writeTemporaryFile(replacements, printsep)1685+ default:1686+ // token type and also failover (below)1687+ rangeExpressions := strings.Split(match[1:len(match)-1], ",")1688+ ranges := make([]Range, len(rangeExpressions))1689+ for idx, s := range rangeExpressions {1690+ r, ok := ParseRange(&s) // ellipsis (x..y) and shorthand (x..x) range syntax1691+ if !ok {1692+ // Invalid expression, just return the original string in the template1693+ return match1694+ }1695+ ranges[idx] = r1696 }1688- return strings.Join(replacements, " ")1689- }1697 1691- tokens := strings.Split(match[1:len(match)-1], ",")1692- ranges := make([]Range, len(tokens))1693- for idx, s := range tokens {1694- r, ok := ParseRange(&s)1695- if !ok {1696- // Invalid expression, just return the original string in the template1697- return match1698+ replace = func(item *Item) string {1699+ tokens := Tokenize(item.AsString(stripAnsi), delimiter)1700+ trans := Transform(tokens, ranges)1701+ str := joinTokens(trans)1702+1703+ // trim the last delimiter1704+ if delimiter.str != nil {1705+ str = strings.TrimSuffix(str, *delimiter.str)1706+ } else if delimiter.regex != nil {1707+ delims := delimiter.regex.FindAllStringIndex(str, -1)1708+ // make sure the delimiter is at the very end of the string1709+ if len(delims) > 0 && delims[len(delims)-1][1] == len(str) {1710+ str = str[:delims[len(delims)-1][0]]1711+ }1712+ }1713+1714+ if !flags.preserveSpace {1715+ str = strings.TrimSpace(str)1716+ }1717+ if !flags.file {1718+ str = quoteEntry(str)1719+ }1720+ return str1721 }1699- ranges[idx] = r1722 }1723 1724+ // apply 'replace' function over proper set of items and return result1725+1726+ items := current1727+ if flags.plus || forcePlus {1728+ items = selected1729+ }1730+ replacements := make([]string, len(items))1731+1732 for idx, item := range items {1703- tokens := Tokenize(item.AsString(stripAnsi), delimiter)1704- trans := Transform(tokens, ranges)1705- str := joinTokens(trans)1706- if delimiter.str != nil {1707- str = strings.TrimSuffix(str, *delimiter.str)1708- } else if delimiter.regex != nil {1709- delims := delimiter.regex.FindAllStringIndex(str, -1)1710- if len(delims) > 0 && delims[len(delims)-1][1] == len(str) {1711- str = str[:delims[len(delims)-1][0]]1712- }1713- }1714- if !flags.preserveSpace {1715- str = strings.TrimSpace(str)1716- }1717- if !flags.file {1718- str = quoteEntry(str)1719- }1720- replacements[idx] = str1733+ replacements[idx] = replace(item)1734 }1735+1736 if flags.file {1737 return writeTemporaryFile(replacements, printsep)1738 }1739 return strings.Join(replacements, " ")1048 unmodified lines