Skip to content
Myr

terminal_test.go

This file

Path

src/terminal_test.go

929 lines · 36.1 KiB · Go

Last changed by

Pin $SHELL to cmd in TestQuoteEntry and TestReplacePlaceholderCyrusbefore adoptionf7ae439

History of this file

Take it

1package fzf23import (4	"bytes"5	"io"6	"os"7	"regexp"8	"strings"9	"testing"10	"text/template"1112	"github.com/junegunn/fzf/src/util"13)1415func replacePlaceholderTest(template string, stripAnsi bool, delimiter Delimiter, printsep string, forcePlus bool, query string, allItems [3][]*Item) string {16	replaced, _ := replacePlaceholder(replacePlaceholderParams{17		template:   template,18		stripAnsi:  stripAnsi,19		delimiter:  delimiter,20		printsep:   printsep,21		forcePlus:  forcePlus,22		query:      query,23		allItems:   allItems,24		lastAction: actBackwardDeleteCharEof,25		prompt:     "prompt",26		executor:   util.NewExecutor(""),27	})28	return replaced29}3031func TestReplacePlaceholder(t *testing.T) {32	// Pin $SHELL so the quoting style doesn't depend on the test runner's shell33	t.Setenv("SHELL", "cmd")3435	item1 := newItem("  foo'bar \x1b[31mbaz\x1b[m")36	items1 := [3][]*Item{{item1}, {item1}, nil}37	items2 := [3][]*Item{38		{newItem("foo'bar \x1b[31mbaz\x1b[m")},39		{newItem("foo'bar \x1b[31mbaz\x1b[m"),40			newItem("FOO'BAR \x1b[31mBAZ\x1b[m")}, nil}4142	delim := "'"43	var regex *regexp.Regexp4445	var result string46	check := func(expected string) {47		if result != expected {48			t.Errorf("expected: %s, actual: %s", expected, result)49		}50	}51	// helper function that converts template format into string and carries out the check()52	checkFormat := func(format string) {53		type quotes struct{ O, I, S string } // outer, inner quotes, print separator54		unixStyle := quotes{`'`, `'\''`, "\n"}55		windowsStyle := quotes{`^"`, `'`, "\n"}56		var effectiveStyle quotes5758		if util.IsWindows() {59			effectiveStyle = windowsStyle60		} else {61			effectiveStyle = unixStyle62		}6364		expected := templateToString(format, effectiveStyle)65		check(expected)66	}67	printsep := "\n"6869	/*70		Test multiple placeholders and the function parameters.71	*/7273	// {}, preserve ansi74	result = replacePlaceholderTest("echo {}", false, Delimiter{}, printsep, false, "query", items1)75	checkFormat("echo {{.O}}  foo{{.I}}bar \x1b[31mbaz\x1b[m{{.O}}")7677	// {}, strip ansi78	result = replacePlaceholderTest("echo {}", true, Delimiter{}, printsep, false, "query", items1)79	checkFormat("echo {{.O}}  foo{{.I}}bar baz{{.O}}")8081	// {r}, strip ansi82	result = replacePlaceholderTest("echo {r}", true, Delimiter{}, printsep, false, "query", items1)83	checkFormat("echo   foo'bar baz")8485	// {r..}, strip ansi86	result = replacePlaceholderTest("echo {r..}", true, Delimiter{}, printsep, false, "query", items1)87	checkFormat("echo foo'bar baz")8889	// {}, with multiple items90	result = replacePlaceholderTest("echo {}", true, Delimiter{}, printsep, false, "query", items2)91	checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}")9293	// {..}, strip leading whitespaces, preserve ansi94	result = replacePlaceholderTest("echo {..}", false, Delimiter{}, printsep, false, "query", items1)95	checkFormat("echo {{.O}}foo{{.I}}bar \x1b[31mbaz\x1b[m{{.O}}")9697	// {..}, strip leading whitespaces, strip ansi98	result = replacePlaceholderTest("echo {..}", true, Delimiter{}, printsep, false, "query", items1)99	checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}")100101	// {q}102	result = replacePlaceholderTest("echo {} {q}", true, Delimiter{}, printsep, false, "query", items1)103	checkFormat("echo {{.O}}  foo{{.I}}bar baz{{.O}} {{.O}}query{{.O}}")104105	// {q}, multiple items106	result = replacePlaceholderTest("echo {+}{q}{+}", true, Delimiter{}, printsep, false, "query 'string'", items2)107	checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}} {{.O}}FOO{{.I}}BAR BAZ{{.O}}{{.O}}query {{.I}}string{{.I}}{{.O}}{{.O}}foo{{.I}}bar baz{{.O}} {{.O}}FOO{{.I}}BAR BAZ{{.O}}")108109	result = replacePlaceholderTest("echo {}{q}{}", true, Delimiter{}, printsep, false, "query 'string'", items2)110	checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}{{.O}}query {{.I}}string{{.I}}{{.O}}{{.O}}foo{{.I}}bar baz{{.O}}")111112	result = replacePlaceholderTest("echo {1}/{2}/{2,1}/{-1}/{-2}/{}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items1)113	checkFormat("echo {{.O}}foo{{.I}}bar{{.O}}/{{.O}}baz{{.O}}/{{.O}}bazfoo{{.I}}bar{{.O}}/{{.O}}baz{{.O}}/{{.O}}foo{{.I}}bar{{.O}}/{{.O}}  foo{{.I}}bar baz{{.O}}/{{.O}}foo{{.I}}bar baz{{.O}}/{n.t}/{}/{1}/{q}/{{.O}}{{.O}}")114115	result = replacePlaceholderTest("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, false, "query", items2)116	checkFormat("echo {{.O}}foo{{.I}}bar{{.O}}/{{.O}}baz{{.O}}/{{.O}}baz{{.O}}/{{.O}}foo{{.I}}bar{{.O}}/{{.O}}foo{{.I}}bar baz{{.O}}/{n.t}/{}/{1}/{q}/{{.O}}{{.O}}")117118	result = replacePlaceholderTest("echo {+1}/{+2}/{+-1}/{+-2}/{+..}/{n.t}/\\{}/\\{1}/\\{q}/{+3}", true, Delimiter{}, printsep, false, "query", items2)119	checkFormat("echo {{.O}}foo{{.I}}bar{{.O}} {{.O}}FOO{{.I}}BAR{{.O}}/{{.O}}baz{{.O}} {{.O}}BAZ{{.O}}/{{.O}}baz{{.O}} {{.O}}BAZ{{.O}}/{{.O}}foo{{.I}}bar{{.O}} {{.O}}FOO{{.I}}BAR{{.O}}/{{.O}}foo{{.I}}bar baz{{.O}} {{.O}}FOO{{.I}}BAR BAZ{{.O}}/{n.t}/{}/{1}/{q}/{{.O}}{{.O}} {{.O}}{{.O}}")120121	// forcePlus122	result = replacePlaceholderTest("echo {1}/{2}/{-1}/{-2}/{..}/{n.t}/\\{}/\\{1}/\\{q}/{3}", true, Delimiter{}, printsep, true, "query", items2)123	checkFormat("echo {{.O}}foo{{.I}}bar{{.O}} {{.O}}FOO{{.I}}BAR{{.O}}/{{.O}}baz{{.O}} {{.O}}BAZ{{.O}}/{{.O}}baz{{.O}} {{.O}}BAZ{{.O}}/{{.O}}foo{{.I}}bar{{.O}} {{.O}}FOO{{.I}}BAR{{.O}}/{{.O}}foo{{.I}}bar baz{{.O}} {{.O}}FOO{{.I}}BAR BAZ{{.O}}/{n.t}/{}/{1}/{q}/{{.O}}{{.O}} {{.O}}{{.O}}")124125	// Whitespace preserving flag with "'" delimiter126	result = replacePlaceholderTest("echo {s1}", true, Delimiter{str: &delim}, printsep, false, "query", items1)127	checkFormat("echo {{.O}}  foo{{.O}}")128129	result = replacePlaceholderTest("echo {s2}", true, Delimiter{str: &delim}, printsep, false, "query", items1)130	checkFormat("echo {{.O}}bar baz{{.O}}")131132	result = replacePlaceholderTest("echo {s}", true, Delimiter{str: &delim}, printsep, false, "query", items1)133	checkFormat("echo {{.O}}  foo{{.I}}bar baz{{.O}}")134135	result = replacePlaceholderTest("echo {s..}", true, Delimiter{str: &delim}, printsep, false, "query", items1)136	checkFormat("echo {{.O}}  foo{{.I}}bar baz{{.O}}")137138	// Whitespace preserving flag with regex delimiter139	regex = regexp.MustCompile(`\w+`)140141	result = replacePlaceholderTest("echo {s1}", true, Delimiter{regex: regex}, printsep, false, "query", items1)142	checkFormat("echo {{.O}}  {{.O}}")143144	result = replacePlaceholderTest("echo {s2}", true, Delimiter{regex: regex}, printsep, false, "query", items1)145	checkFormat("echo {{.O}}{{.I}}{{.O}}")146147	result = replacePlaceholderTest("echo {s3}", true, Delimiter{regex: regex}, printsep, false, "query", items1)148	checkFormat("echo {{.O}} {{.O}}")149150	// No match151	result = replacePlaceholderTest("echo {}/{+}", true, Delimiter{}, printsep, false, "query", [3][]*Item{nil, nil, nil})152	check("echo /")153154	// No match, but with selections155	result = replacePlaceholderTest("echo {}/{+}", true, Delimiter{}, printsep, false, "query", [3][]*Item{nil, {item1}, nil})156	checkFormat("echo /{{.O}}  foo{{.I}}bar baz{{.O}}")157158	// String delimiter159	result = replacePlaceholderTest("echo {}/{1}/{2}", true, Delimiter{str: &delim}, printsep, false, "query", items1)160	checkFormat("echo {{.O}}  foo{{.I}}bar baz{{.O}}/{{.O}}foo{{.O}}/{{.O}}bar baz{{.O}}")161162	// Regex delimiter163	regex = regexp.MustCompile("[oa]+")164	// foo'bar baz165	result = replacePlaceholderTest("echo {}/{1}/{3}/{2..3}", true, Delimiter{regex: regex}, printsep, false, "query", items1)166	checkFormat("echo {{.O}}  foo{{.I}}bar baz{{.O}}/{{.O}}f{{.O}}/{{.O}}r b{{.O}}/{{.O}}{{.I}}bar b{{.O}}")167168	/*169		Test single placeholders, but focus on the placeholders' parameters (e.g. flags).170		see: TestParsePlaceholder171	*/172	items3 := [3][]*Item{173		// single line174		{newItem("1a 1b 1c 1d 1e 1f")},175		// multi line176		{newItem("1a 1b 1c 1d 1e 1f"),177			newItem("2a 2b 2c 2d 2e 2f"),178			newItem("3a 3b 3c 3d 3e 3f"),179			newItem("4a 4b 4c 4d 4e 4f"),180			newItem("5a 5b 5c 5d 5e 5f"),181			newItem("6a 6b 6c 6d 6e 6f"),182			newItem("7a 7b 7c 7d 7e 7f")},183		nil,184	}185	stripAnsi := false186	forcePlus := false187	query := "sample query"188189	templateToOutput := make(map[string]string)190	templateToFile := make(map[string]string) // same as above, but the file contents will be matched191	// I. item type placeholder192	templateToOutput[`{}`] = `{{.O}}1a 1b 1c 1d 1e 1f{{.O}}`193	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}}`194	templateToOutput[`{n}`] = `0`195	templateToOutput[`{+n}`] = `0 0 0 0 0 0 0`196	templateToFile[`{f}`] = `1a 1b 1c 1d 1e 1f{{.S}}`197	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}}`198	templateToFile[`{nf}`] = `0{{.S}}`199	templateToFile[`{+nf}`] = `0{{.S}}0{{.S}}0{{.S}}0{{.S}}0{{.S}}0{{.S}}0{{.S}}`200201	// II. token type placeholders202	templateToOutput[`{..}`] = templateToOutput[`{}`]203	templateToOutput[`{1..}`] = templateToOutput[`{}`]204	templateToOutput[`{..2}`] = `{{.O}}1a 1b{{.O}}`205	templateToOutput[`{1..2}`] = templateToOutput[`{..2}`]206	templateToOutput[`{-2..-1}`] = `{{.O}}1e 1f{{.O}}`207	// shorthand for x..x range208	templateToOutput[`{1}`] = `{{.O}}1a{{.O}}`209	templateToOutput[`{1..1}`] = templateToOutput[`{1}`]210	templateToOutput[`{-6}`] = templateToOutput[`{1}`]211	// multiple ranges212	templateToOutput[`{1,2}`] = templateToOutput[`{1..2}`]213	templateToOutput[`{1,2,4}`] = `{{.O}}1a 1b 1d{{.O}}`214	templateToOutput[`{1,2..4}`] = `{{.O}}1a 1b 1c 1d{{.O}}`215	templateToOutput[`{1..2,-4..-3}`] = `{{.O}}1a 1b 1c 1d{{.O}}`216	// flags217	templateToOutput[`{+1}`] = `{{.O}}1a{{.O}} {{.O}}2a{{.O}} {{.O}}3a{{.O}} {{.O}}4a{{.O}} {{.O}}5a{{.O}} {{.O}}6a{{.O}} {{.O}}7a{{.O}}`218	templateToOutput[`{+-1}`] = `{{.O}}1f{{.O}} {{.O}}2f{{.O}} {{.O}}3f{{.O}} {{.O}}4f{{.O}} {{.O}}5f{{.O}} {{.O}}6f{{.O}} {{.O}}7f{{.O}}`219	templateToOutput[`{s1}`] = `{{.O}}1a {{.O}}`220	templateToFile[`{f1}`] = `1a{{.S}}`221	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}}`222	templateToFile[`{+sf1..2}`] = `1a 1b {{.S}}2a 2b {{.S}}3a 3b {{.S}}4a 4b {{.S}}5a 5b {{.S}}6a 6b {{.S}}7a 7b {{.S}}`223224	// III. query type placeholder225	// query flag is not removed after parsing, so it gets doubled226	// while the double q is invalid, it is useful here for testing purposes227	templateToOutput[`{q}`] = "{{.O}}" + query + "{{.O}}"228	templateToOutput[`{fzf:query}`] = "{{.O}}" + query + "{{.O}}"229	templateToOutput[`{fzf:action} {fzf:prompt}`] = `backward-delete-char-eof {{.O}}prompt{{.O}}`230231	// IV. escaping placeholder232	templateToOutput[`\{}`] = `{}`233	templateToOutput[`\{q}`] = `{q}`234	templateToOutput[`\{fzf:query}`] = `{fzf:query}`235	templateToOutput[`\{fzf:action}`] = `{fzf:action}`236	templateToOutput[`\{++}`] = `{++}`237	templateToOutput[`{++}`] = templateToOutput[`{+}`]238239	for giveTemplate, wantOutput := range templateToOutput {240		result = replacePlaceholderTest(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3)241		checkFormat(wantOutput)242	}243	for giveTemplate, wantOutput := range templateToFile {244		path := replacePlaceholderTest(giveTemplate, stripAnsi, Delimiter{}, printsep, forcePlus, query, items3)245246		data, err := readFile(path)247		if err != nil {248			t.Errorf("Cannot read the content of the temp file %s.", path)249		}250		result = string(data)251252		checkFormat(wantOutput)253	}254}255256func TestQuoteEntry(t *testing.T) {257	type quotes struct{ E, O, SQ, DQ, BS, PB string } // standalone escape, outer, single and double quotes, doubled and plain backslash258	unixStyle := quotes{``, `'`, `'\''`, `"`, `\`, `\`}259	windowsStyle := quotes{`^`, `^"`, `'`, `\^"`, `\\`, `\`}260	var effectiveStyle quotes261262	// Pin $SHELL so the quoting style doesn't depend on the test runner's shell263	t.Setenv("SHELL", "cmd")264	exec := util.NewExecutor("")265266	if util.IsWindows() {267		effectiveStyle = windowsStyle268	} else {269		effectiveStyle = unixStyle270	}271272	tests := map[string]string{273		`'`:     `{{.O}}{{.SQ}}{{.O}}`,274		`"`:     `{{.O}}{{.DQ}}{{.O}}`,275		`\`:     `{{.O}}{{.BS}}{{.O}}`,276		`\"`:    `{{.O}}{{.BS}}{{.DQ}}{{.O}}`,277		`"\\\"`: `{{.O}}{{.DQ}}{{.BS}}{{.BS}}{{.BS}}{{.DQ}}{{.O}}`,278279		`$`:       `{{.O}}${{.O}}`,280		`$HOME`:   `{{.O}}$HOME{{.O}}`,281		`'$HOME'`: `{{.O}}{{.SQ}}$HOME{{.SQ}}{{.O}}`,282283		`&`:                       `{{.O}}{{.E}}&{{.O}}`,284		`|`:                       `{{.O}}{{.E}}|{{.O}}`,285		`<`:                       `{{.O}}{{.E}}<{{.O}}`,286		`>`:                       `{{.O}}{{.E}}>{{.O}}`,287		`(`:                       `{{.O}}{{.E}}({{.O}}`,288		`)`:                       `{{.O}}{{.E}}){{.O}}`,289		`@`:                       `{{.O}}@{{.O}}`,290		`^`:                       `{{.O}}{{.E}}^{{.O}}`,291		`%`:                       `{{.O}}{{.E}}%{{.O}}`,292		`!`:                       `{{.O}}{{.E}}!{{.O}}`,293		`%USERPROFILE%`:           `{{.O}}{{.E}}%USERPROFILE{{.E}}%{{.O}}`,294		`C:\Program Files (x86)\`: `{{.O}}C:{{.PB}}Program Files {{.E}}(x86{{.E}}){{.BS}}{{.O}}`,295		`"C:\Program Files"`:      `{{.O}}{{.DQ}}C:{{.PB}}Program Files{{.DQ}}{{.O}}`,296	}297298	for input, expected := range tests {299		escaped := exec.QuoteEntry(input)300		expected = templateToString(expected, effectiveStyle)301		if escaped != expected {302			t.Errorf("Input: %s, expected: %s, actual %s", input, expected, escaped)303		}304	}305}306307// purpose of this test is to demonstrate some shortcomings of fzf's templating system on Unix308func TestUnixCommands(t *testing.T) {309	if util.IsWindows() {310		t.SkipNow()311	}312	tests := []testCase{313		// reference: give{template, query, items}, want{output OR match}314315		// 1) working examples316317		// paths that does not have to evaluated will work fine, when quoted318		{give{`grep foo {}`, ``, newItems(`test`)}, want{output: `grep foo 'test'`}},319		{give{`grep foo {}`, ``, newItems(`/home/user/test`)}, want{output: `grep foo '/home/user/test'`}},320		{give{`grep foo {}`, ``, newItems(`./test`)}, want{output: `grep foo './test'`}},321322		// only placeholders are escaped as data, this will lookup tilde character in a test file in your home directory323		// quoting the tilde is required (to be treated as string)324		{give{`grep {} ~/test`, ``, newItems(`~`)}, want{output: `grep '~' ~/test`}},325326		// 2) problematic examples327		// (not necessarily unexpected)328329		// paths that need to expand some part of it won't work (special characters and variables)330		{give{`cat {}`, ``, newItems(`~/test`)}, want{output: `cat '~/test'`}},331		{give{`cat {}`, ``, newItems(`$HOME/test`)}, want{output: `cat '$HOME/test'`}},332	}333	testCommands(t, tests)334}335336// purpose of this test is to demonstrate some shortcomings of fzf's templating system on Windows337func TestWindowsCommands(t *testing.T) {338	// XXX Deprecated339	t.SkipNow()340341	tests := []testCase{342		// reference: give{template, query, items}, want{output OR match}343344		// 1) working examples345346		// example of redundantly escaped backslash in the output, besides looking bit ugly, it won't cause any issue347		{give{`type {}`, ``, newItems(`C:\test.txt`)}, want{output: `type ^"C:\\test.txt^"`}},348		{give{`rg -- "package" {}`, ``, newItems(`.\test.go`)}, want{output: `rg -- "package" ^".\\test.go^"`}},349		// example of mandatorily escaped backslash in the output, otherwise `rg -- "C:\test.txt"` is matching for tabulator350		{give{`rg -- {}`, ``, newItems(`C:\test.txt`)}, want{output: `rg -- ^"C:\\test.txt^"`}},351		// example of mandatorily escaped double quote in the output, otherwise `rg -- ""C:\\test.txt""` is not matching for the double quotes around the path352		{give{`rg -- {}`, ``, newItems(`"C:\test.txt"`)}, want{output: `rg -- ^"\^"C:\\test.txt\^"^"`}},353354		// 2) problematic examples355		// (not necessarily unexpected)356357		// notepad++'s parser can't handle `-n"12"` generate by fzf, expects `-n12`358		{give{`notepad++ -n{1} {2}`, ``, newItems(`12	C:\Work\Test Folder\File.txt`)}, want{output: `notepad++ -n^"12^" ^"C:\\Work\\Test Folder\\File.txt^"`}},359360		// cat is parsing `\"` as a part of the file path, double quote is illegal character for paths on Windows361		// cat: "C:\\test.txt: Invalid argument362		{give{`cat {}`, ``, newItems(`"C:\test.txt"`)}, want{output: `cat ^"\^"C:\\test.txt\^"^"`}},363		// cat: "C:\\test.txt": Invalid argument364		{give{`cmd /c {}`, ``, newItems(`cat "C:\test.txt"`)}, want{output: `cmd /c ^"cat \^"C:\\test.txt\^"^"`}},365366		// 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 it367		// the temp file contains: `cat "C:\test.txt"`368		// TODO this should actually work369		{give{`cmd /c {f}`, ``, newItems(`cat "C:\test.txt"`)}, want{match: `^cmd /c .*\fzf-preview-[0-9]{9}$`}},370	}371	testCommands(t, tests)372}373374// purpose of this test is to demonstrate some shortcomings of fzf's templating system on Windows in Powershell375func TestPowershellCommands(t *testing.T) {376	if !util.IsWindows() {377		t.SkipNow()378	}379380	tests := []testCase{381		// reference: give{template, query, items}, want{output OR match}382383		/*384			You can read each line in the following table as a pipeline that385			consist of series of parsers that act upon your input (col. 1) and386			each cell represents the output value.387388			For example:389			 - exec.Command("program.exe", `\''`)390			   - goes to win32 api which will process it transparently as it contains no special characters, see [CommandLineToArgvW][].391			     - powershell command will receive it as is, that is two arguments: a literal backslash and empty string in single quotes392			     - native command run via/from powershell will receive only one argument: a literal backslash. Because extra parsing rules apply, see [NativeCallsFromPowershell][].393			       - some¹ apps have internal parser, that requires one more level of escaping (yes, this is completely application-specific, but see terminal_test.go#TestWindowsCommands)394395			Character⁰   CommandLineToArgvW   Powershell commands              Native commands from Powershell   Apps requiring escapes¹    | Being tested below396			----------   ------------------   ------------------------------   -------------------------------   -------------------------- | ------------------397			"            empty string²        missing argument error           ...                               ...                        |398			\"           literal "            unbalanced quote error           ...                               ...                        |399			'\"'         literal '"'          literal "                        empty string                      empty string (match all)   | yes400			'\\\"'       literal '\"'         literal \"                       literal "                         literal "                  |401			----------   ------------------   ------------------------------   -------------------------------   -------------------------- | ------------------402			\            transparent          transparent                      transparent                       regex error                |403			'\'          transparent          literal \                        literal \                         regex error                | yes404			\\           transparent          transparent                      transparent                       literal \                  |405			'\\'         transparent          literal \\                       literal \\                        literal \                  |406			----------   ------------------   ------------------------------   -------------------------------   -------------------------- | ------------------407			'            transparent          unbalanced quote error           ...                               ...                        |408			\'           transparent          literal \ and unb. quote error   ...                               ...                        |409			\''          transparent          literal \ and empty string       literal \                         regex error                | no, but given as example above410			'''          transparent          unbalanced quote error           ...                               ...                        |411			''''         transparent          literal '                        literal '                         literal '                  | yes412			----------   ------------------   ------------------------------   -------------------------------   -------------------------- | ------------------413414			⁰: charatecter or characters 'x' as an argument to a program in go's call: exec.Command("program.exe", `x`)415			¹: native commands like grep, git grep, ripgrep416			²: interpreted as a grouping quote, affects argument parser and gets removed from the result417418			[CommandLineToArgvW]: https://docs.microsoft.com/en-gb/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw#remarks419			[NativeCallsFromPowershell]: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing?view=powershell-7.1#passing-arguments-that-contain-quote-characters420		*/421422		// 1) working examples423424		{give{`Get-Content {}`, ``, newItems(`C:\test.txt`)}, want{output: `Get-Content 'C:\test.txt'`}},425		{give{`rg -- "package" {}`, ``, newItems(`.\test.go`)}, want{output: `rg -- "package" '.\test.go'`}},426427		// example of escaping single quotes428		{give{`rg -- {}`, ``, newItems(`'foobar'`)}, want{output: `rg -- '''foobar'''`}},429430		// chaining powershells431		{give{`powershell -NoProfile -Command {}`, ``, newItems(`cat "C:\test.txt"`)}, want{output: `powershell -NoProfile -Command 'cat \"C:\test.txt\"'`}},432433		// 2) problematic examples434		// (not necessarily unexpected)435436		// looking for a path string will only work with escaped backslashes437		{give{`rg -- {}`, ``, newItems(`C:\test.txt`)}, want{output: `rg -- 'C:\test.txt'`}},438		// looking for a literal double quote will only work with triple escaped double quotes439		{give{`rg -- {}`, ``, newItems(`"C:\test.txt"`)}, want{output: `rg -- '\"C:\test.txt\"'`}},440441		// Get-Content (i.e. cat alias) is parsing `"` as a part of the file path, returns an error:442		// Get-Content : Cannot find drive. A drive with the name '"C:' does not exist.443		{give{`cat {}`, ``, newItems(`"C:\test.txt"`)}, want{output: `cat '\"C:\test.txt\"'`}},444445		// the "file" flag in the pattern won't create *.ps1 file so the powershell will offload this "unknown" filetype446		// to explorer, which will prompt user to pick editing program for the fzf-preview file447		// the temp file contains: `cat "C:\test.txt"`448		// TODO this should actually work449		{give{`powershell -NoProfile -Command {f}`, ``, newItems(`cat "C:\test.txt"`)}, want{match: `^powershell -NoProfile -Command .*\fzf-temp-[0-9]+$`}},450	}451452	// to force powershell-style escaping we temporarily set environment variable that fzf honors453	shellBackup := os.Getenv("SHELL")454	os.Setenv("SHELL", "powershell")455	testCommands(t, tests)456	os.Setenv("SHELL", shellBackup)457}458459/*460Test typical valid placeholders and parsing of them.461462Also since the parser assumes the input is matched with `placeholder` regex,463the regex is tested here as well.464*/465func TestParsePlaceholder(t *testing.T) {466	// give, want pairs467	templates := map[string]string{468		// I. item type placeholder469		`{}`:    `{}`,470		`{+}`:   `{+}`,471		`{n}`:   `{n}`,472		`{+n}`:  `{+n}`,473		`{f}`:   `{f}`,474		`{+nf}`: `{+nf}`,475476		// II. token type placeholders477		`{..}`:     `{..}`,478		`{1..}`:    `{1..}`,479		`{..2}`:    `{..2}`,480		`{1..2}`:   `{1..2}`,481		`{-2..-1}`: `{-2..-1}`,482		// shorthand for x..x range483		`{1}`:    `{1}`,484		`{1..1}`: `{1..1}`,485		`{-6}`:   `{-6}`,486		// multiple ranges487		`{1,2}`:         `{1,2}`,488		`{1,2,4}`:       `{1,2,4}`,489		`{1,2..4}`:      `{1,2..4}`,490		`{1..2,-4..-3}`: `{1..2,-4..-3}`,491		// flags492		`{+1}`:      `{+1}`,493		`{+-1}`:     `{+-1}`,494		`{s1}`:      `{s1}`,495		`{f1}`:      `{f1}`,496		`{+s1..2}`:  `{+s1..2}`,497		`{+sf1..2}`: `{+sf1..2}`,498499		// III. query type placeholder500		// query flag is not removed after parsing, so it gets doubled501		// while the double q is invalid, it is useful here for testing purposes502		`{q}`:        `{qq}`,503		`{q:1}`:      `{qq:1}`,504		`{q:2..}`:    `{qq:2..}`,505		`{q:..}`:     `{qq:..}`,506		`{q:2..-1}`:  `{qq:2..-1}`,507		`{q:s2..-1}`: `{sqq:2..-1}`, // FIXME508509		// IV. escaping placeholder510		`\{}`:   `{}`,511		`\{++}`: `{++}`,512		`{++}`:  `{+}`,513	}514515	for giveTemplate, wantTemplate := range templates {516		if !placeholder.MatchString(giveTemplate) {517			t.Errorf(`given placeholder %s does not match placeholder regex, so attempt to parse it is unexpected`, giveTemplate)518			continue519		}520521		_, placeholderWithoutFlags, flags := parsePlaceholder(giveTemplate)522		gotTemplate := placeholderWithoutFlags[:1] + flags.encodePlaceholder() + placeholderWithoutFlags[1:]523524		if gotTemplate != wantTemplate {525			t.Errorf(`parsed placeholder "%s" into "%s", but want "%s"`, giveTemplate, gotTemplate, wantTemplate)526		}527	}528}529530func TestExtractPassthroughs(t *testing.T) {531	for _, middle := range []string{532		"\x1bPtmux;\x1b\x1bbar\x1b\\",533		"\x1bPtmux;\x1b\x1bbar\x1bbar\x1b\\",534		"\x1b]1337;bar\x1b\\",535		"\x1b]1337;bar\x1bbar\x1b\\",536		"\x1b]1337;bar\a",537		"\x1b_Ga=T,f=32,s=1258,v=1295,c=74,r=35,m=1\x1b\\",538		"\x1b_Ga=T,f=32,s=1258,v=1295,c=74,r=35,m=1\x1b\\\r",539		"\x1b_Ga=T,f=32,s=1258,v=1295,c=74,r=35,m=1\x1bbar\x1b\\\r",540		"\x1b_Gm=1;AAAAAAAAA=\x1b\\",541		"\x1b_Gm=1;AAAAAAAAA=\x1b\\\r",542		"\x1b_Gm=1;\x1bAAAAAAAAA=\x1b\\\r",543	} {544		line := "foo" + middle + "baz"545		loc := findPassThrough(line)546		if loc == nil || line[0:loc[0]] != "foo" || line[loc[1]:] != "baz" {547			t.Error("failed to find passthrough")548		}549		garbage := "\x1bPtmux;\x1b]1337;\x1b_Ga=\x1b]1337;bar\x1b."550		line = strings.Repeat("foo"+middle+middle+"baz", 3) + garbage551		passthroughs, result := extractPassThroughs(line)552		if result != "foobazfoobazfoobaz"+garbage || len(passthroughs) != 6 {553			t.Error("failed to extract passthroughs")554		}555	}556}557558func TestWrapPassThrough(t *testing.T) {559	for _, passThrough := range []string{560		"\x1bPtmux;\x1b\x1b_Ga=d,d=A\x1b\x1b\\\x1b\\", // Already wrapped561		"\x1bP0;1;0q#0;2;0;0;0#0~~@@vv@@~~@\x1b\\",    // Sixel562		"\x1b]1337;File=inline=1:AAAA\a",              // iTerm2563	} {564		if got := wrapPassThrough(passThrough, true); got != passThrough {565			t.Errorf("should have been left alone: %q -> %q", passThrough, got)566		}567	}568569	kitty := "\x1b_Ga=d,d=A\x1b\\"570	if got := wrapPassThrough(kitty, false); got != kitty {571		t.Errorf("should have been left alone outside of tmux: %q", got)572	}573574	// ESC characters are doubled, and the trailing carriage return is kept575	// outside of the wrapper576	for _, test := range []struct{ input, want string }{577		{kitty, "\x1bPtmux;\x1b\x1b_Ga=d,d=A\x1b\x1b\\\x1b\\"},578		{kitty + "\r", "\x1bPtmux;\x1b\x1b_Ga=d,d=A\x1b\x1b\\\x1b\\\r"},579		{"\x1b_Gm=1;\x1bAAA=\x1b\\", "\x1bPtmux;\x1b\x1b_Gm=1;\x1b\x1bAAA=\x1b\x1b\\\x1b\\"},580	} {581		if got := wrapPassThrough(test.input, true); got != test.want {582			t.Errorf("expected %q, got %q", test.want, got)583		}584	}585}586587func TestIsImagePassThrough(t *testing.T) {588	for _, tc := range []struct {589		given string590		image bool591	}{592		// Kitty593		{"\x1b_Ga=T,f=32,s=1258,v=1295,c=74,r=35,m=1\x1b\\", true},594		{"\x1b_Ga=p,i=1\x1b\\", true},595		// The action key is not always first, and a put carries no payload596		{"\x1b_Gi=1,a=p\x1b\\", true},597		{"\x1b_Ga=p\x1b\\", true},598		{"\x1b_Ga=T,f=100\x1b\\\r", true},599		{"\x1b_Gi=1,a=d\x1b\\", false},600		{"\x1b_Ga=d,d=A\x1b\\", false},          // 'kitten icat --clear'601		{"\x1b_Ga=q,i=1\x1b\\", false},          // query602		{"\x1b_Gi=1,f=100\x1b\\", false},        // transmit only, the default action603		{"\x1b_Gm=1;AAAA\x1b\\", false},         // continuation chunk604		{"\x1b_Ga=f,i=1;AAAA\x1b\\", false},     // animation frame605		{"\x1b_Ga=T,U=1,f=32;AAAA\x1b\\", true}, // unicode placeholder606		// Wrapped in the tmux passthrough sequence607		{"\x1bPtmux;\x1b\x1b_Ga=T,f=100\x1b\x1b\\\x1b\\", true},608		{"\x1bPtmux;\x1b\x1b_Ga=d,d=A\x1b\x1b\\\x1b\\", false},609		{"\x1bPtmux;\x1b\x1b_Gi=1,a=p\x1b\x1b\\\x1b\\", true},610		// iTerm2611		{"\x1b]1337;File=inline=1:AAAA\a", true},612		{"\x1b]1337;MultipartFile=inline=1\a", true},613		{"\x1b]1337;SetUserVar=foo=YmFy\a", false},614		{"\x1b]1337;CurrentDir=/tmp\a", false},615		// Sixel616		{"\x1bP0;1;0q#0;2;0;0;0#0~~@@vv@@~~@\x1b\\", true},617		{"\x1bPq#0~~\x1b\\", true},618		{"\x1bPtmux;\x1b\x1bP0;1;0q#0~~\x1b\x1b\\\x1b\\", true},619		{"", false},620	} {621		if actual := isImagePassThrough(tc.given); actual != tc.image {622			t.Errorf("expected %v for %q, got %v", tc.image, tc.given, actual)623		}624	}625626	if containsImage([]string{"foo", "bar"}) {627		t.Error("plain text carries no image")628	}629	if !containsImage([]string{"foo", "bar\x1b_Ga=T,f=100\x1b\\baz"}) {630		t.Error("failed to find an image in a line")631	}632	if containsImage([]string{"foo\x1b_Ga=d,d=A\x1b\\"}) {633		t.Error("a delete command is not an image")634	}635	// The image is not the first passthrough on the line636	if !containsImage([]string{"\x1b_Ga=d,d=A\x1b\\text\x1b_Ga=T,f=100;AAAA\x1b\\"}) {637		t.Error("failed to look past an earlier passthrough")638	}639}640641/* utilities section */642643// Item represents one line in fzf UI. Usually it is relative path to files and folders.644func newItem(str string) *Item {645	bytes := []byte(str)646	trimmed, _, _ := extractColor(str, nil, nil)647	return &Item{origText: &bytes, text: util.ToChars([]byte(trimmed))}648}649650// Functions tested in this file require array of items (allItems).651// This is helper function.652func newItems(str ...string) [3][]*Item {653	result := make([]*Item, len(str))654	for i, s := range str {655		result[i] = newItem(s)656	}657	return [3][]*Item{result, nil, nil}658}659660// (for logging purposes)661func (item *Item) String() string {662	return item.AsString(true)663}664665// Helper function to parse, execute and convert "text/template" to string. Panics on error.666func templateToString(format string, data any) string {667	bb := &bytes.Buffer{}668669	err := template.Must(template.New("").Parse(format)).Execute(bb, data)670	if err != nil {671		panic(err)672	}673674	return bb.String()675}676677// ad hoc types for test cases678type give struct {679	template string680	query    string681	allItems [3][]*Item682}683type want struct {684	/*685		Unix:686		The `want.output` string is supposed to be formatted for evaluation by687		`sh -c command` system call.688689		Windows:690		The `want.output` string is supposed to be formatted for evaluation by691		`cmd.exe /s /c "command"` system call. The `/s` switch enables so called old692		behaviour, which is more favourable for nesting (possibly escaped)693		special characters. This is the relevant section of `help cmd`:694695		...old behavior is to see if the first character is696		a quote character and if so, strip the leading character and697		remove the last quote character on the command line, preserving698		any text after the last quote character.699	*/700	output string // literal output701	match  string // output is matched against this regex (when output is empty string)702}703type testCase struct {704	give705	want706}707708func testCommands(t *testing.T, tests []testCase) {709	// common test parameters710	delim := "\t"711	delimiter := Delimiter{str: &delim}712	printsep := ""713	stripAnsi := false714	forcePlus := false715716	// evaluate the test cases717	for idx, test := range tests {718		gotOutput := replacePlaceholderTest(719			test.template, stripAnsi, delimiter, printsep, forcePlus,720			test.query,721			test.allItems)722		switch {723		case test.output != "":724			if gotOutput != test.output {725				t.Errorf("tests[%v]:\ngave{\n\ttemplate: '%s',\n\tquery: '%s',\n\tallItems: %s}\nand got '%s',\nbut want '%s'",726					idx,727					test.template, test.query, test.allItems,728					gotOutput, test.output)729			}730		case test.match != "":731			wantMatch := strings.ReplaceAll(test.match, `\`, `\\`)732			wantRegex := regexp.MustCompile(wantMatch)733			if !wantRegex.MatchString(gotOutput) {734				t.Errorf("tests[%v]:\ngave{\n\ttemplate: '%s',\n\tquery: '%s',\n\tallItems: %s}\nand got '%s',\nbut want '%s'",735					idx,736					test.template, test.query, test.allItems,737					gotOutput, test.match)738			}739		default:740			t.Errorf("tests[%v]: test case does not describe 'want' property", idx)741		}742	}743}744745// naive encoder of placeholder flags746func (flags placeholderFlags) encodePlaceholder() string {747	encoded := ""748	if flags.plus {749		encoded += "+"750	}751	if flags.preserveSpace {752		encoded += "s"753	}754	if flags.number {755		encoded += "n"756	}757	if flags.file {758		encoded += "f"759	}760	if flags.forceUpdate { // FIXME761		encoded += "q"762	}763	return encoded764}765766// can be replaced with os.ReadFile() in go 1.16+767func readFile(path string) ([]byte, error) {768	file, err := os.Open(path)769	if err != nil {770		return nil, err771	}772	defer file.Close()773774	data := make([]byte, 0, 128)775	for {776		if len(data) >= cap(data) {777			d := append(data[:cap(data)], 0)778			data = d[:len(data)]779		}780781		n, err := file.Read(data[len(data):cap(data)])782		data = data[:len(data)+n]783		if err != nil {784			if err == io.EOF {785				err = nil786			}787			return data, err788		}789	}790}791792func TestWordWrapAnsiLine(t *testing.T) {793	term := &Terminal{}794795	// Simple wrapping796	result := term.wordWrapAnsiLine("hello world", 7, 2)797	if len(result) != 2 || result[0] != "hello" || result[1] != "world" {798		t.Errorf("Simple: %q", result)799	}800801	// No wrapping needed802	result = term.wordWrapAnsiLine("hello", 10, 2)803	if len(result) != 1 || result[0] != "hello" {804		t.Errorf("No wrap: %q", result)805	}806807	// ANSI codes preserved across split808	result = term.wordWrapAnsiLine("\x1b[31mhello \x1b[32mworld", 8, 2)809	if len(result) != 2 || result[0] != "\x1b[31mhello" || result[1] != "\x1b[32mworld" {810		t.Errorf("ANSI: %q", result)811	}812813	// Long word (no space) - no break, let character wrapping handle it814	result = term.wordWrapAnsiLine("abcdefghij", 5, 2)815	if len(result) != 1 || result[0] != "abcdefghij" {816		t.Errorf("Long word: %q", result)817	}818819	// Multiple words with continuation wrapSignWidth820	result = term.wordWrapAnsiLine("aa bb cc dd", 5, 2)821	// max=5 for first line, max=3 for continuations (5-2)822	// "aa bb" (5 wide), split at second space -> "aa bb" | "cc" | "dd"823	if len(result) != 3 || result[0] != "aa bb" || result[1] != "cc" || result[2] != "dd" {824		t.Errorf("Multiple words: %q", result)825	}826827	// Empty string828	result = term.wordWrapAnsiLine("", 10, 2)829	if len(result) != 1 || result[0] != "" {830		t.Errorf("Empty: %q", result)831	}832833	// OSC 8 hyperlink preserved834	result = term.wordWrapAnsiLine("\x1b]8;;http://example.com\x1b\\click here\x1b]8;;\x1b\\", 8, 2)835	if len(result) != 2 {836		t.Errorf("Hyperlink split count: %d, %q", len(result), result)837	}838839	// Tab handling: tab expands to tabstop-aligned width840	term.tabstop = 8841	// "\thi there" - tab at column 0 expands to 8, total "hi" starts at 8842	// maxWidth=15: "\thi" = 10 wide, "there" = 5 wide, total 16 > 15, wrap at space843	result = term.wordWrapAnsiLine("\thi there", 15, 2)844	if len(result) != 2 || result[0] != "\thi" || result[1] != "there" {845		t.Errorf("Tab: %q", result)846	}847848	// Tab as word boundary: "hello"(5) + tab(3→col8) + "world"(5) = 13 total849	// maxWidth=13: fits without wrapping850	result = term.wordWrapAnsiLine("hello\tworld", 13, 2)851	if len(result) != 1 || result[0] != "hello\tworld" {852		t.Errorf("Tab no wrap: %q", result)853	}854	// maxWidth=12: 13 > 12, wraps at tab855	result = term.wordWrapAnsiLine("hello\tworld", 12, 2)856	if len(result) != 2 || result[0] != "hello" || result[1] != "world" {857		t.Errorf("Tab wrap: %q", result)858	}859}860861func TestSplitOnIND(t *testing.T) {862	term := &Terminal{tabstop: 8}863	for _, tc := range []struct {864		name string865		line string866		want []string867	}{868		{869			// Nothing to do, so the caller keeps the line as it read it870			name: "no IND",871			line: "foo\n",872			want: nil,873		},874		{875			// chafa: CUB returns to the column the row started on876			name: "rows at column 0",877			line: "AAA\x1b[3D\x1bDBBB\x1b[3D\x1bDCCC\n",878			want: []string{"AAA\x1b[3D\n", "BBB\x1b[3D\n", "CCC\n"},879		},880		{881			// 'printf "  "; chafa ...'882			name: "indented rows",883			line: "  AAA\x1b[3D\x1bDBBB\x1b[3D\x1bDCCC\n",884			want: []string{"  AAA\x1b[3D\n", "  BBB\x1b[3D\n", "  CCC\n"},885		},886		{887			name: "tab indent expands to the tab stop",888			line: "\tAAA\x1b[3D\x1bDBBB\x1b[3D\x1bDCCC\n",889			want: []string{"\tAAA\x1b[3D\n", "        BBB\x1b[3D\n", "        CCC\n"},890		},891		{892			// IND on its own keeps the column893			name: "bare IND",894			line: "AB\x1bDCD\n",895			want: []string{"AB\n", "  CD\n"},896		},897		{898			name: "CUB without a parameter moves back one",899			line: "AB\x1b[D\x1bDCD\n",900			want: []string{"AB\x1b[D\n", " CD\n"},901		},902		{903			name: "CUB past the left edge is clamped",904			line: "AB\x1b[9D\x1bDCD\n",905			want: []string{"AB\x1b[9D\n", "CD\n"},906		},907		{908			name: "SGR codes take no column",909			line: "\x1b[31mAB\x1b[m\x1b[2D\x1bDCD\n",910			want: []string{"\x1b[31mAB\x1b[m\x1b[2D\n", "CD\n"},911		},912		{913			name: "pass-throughs take no column",914			line: "\x1b_Ga=T,c=2,r=1\x1b\\AB\x1b[2D\x1bDCD\n",915			want: []string{"\x1b_Ga=T,c=2,r=1\x1b\\AB\x1b[2D\n", "CD\n"},916		},917	} {918		got := term.splitOnIND(tc.line)919		if len(got) != len(tc.want) {920			t.Errorf("%s: got %q, want %q", tc.name, got, tc.want)921			continue922		}923		for idx, line := range got {924			if line != tc.want[idx] {925				t.Errorf("%s: line %d: got %q, want %q", tc.name, idx, line, tc.want[idx])926			}927		}928	}929}