| 1 |
package fzf |
| 2 |
|
| 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 |
|
| 15 |
func 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 replaced |
| 29 |
} |
| 30 |
|
| 31 |
func TestReplacePlaceholder(t *testing.T) { |
| 32 |
// Pin $SHELL so the quoting style doesn't depend on the test runner's shell |
| 33 |
t.Setenv("SHELL", "cmd") |
| 34 |
|
| 35 |
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} |
| 41 |
|
| 42 |
delim := "'" |
| 43 |
var regex *regexp.Regexp |
| 44 |
|
| 45 |
var result string |
| 46 |
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 separator |
| 54 |
unixStyle := quotes{`'`, `'\''`, "\n"} |
| 55 |
windowsStyle := quotes{`^"`, `'`, "\n"} |
| 56 |
var effectiveStyle quotes |
| 57 |
|
| 58 |
if util.IsWindows() { |
| 59 |
effectiveStyle = windowsStyle |
| 60 |
} else { |
| 61 |
effectiveStyle = unixStyle |
| 62 |
} |
| 63 |
|
| 64 |
expected := templateToString(format, effectiveStyle) |
| 65 |
check(expected) |
| 66 |
} |
| 67 |
printsep := "\n" |
| 68 |
|
| 69 |
/* |
| 70 |
Test multiple placeholders and the function parameters. |
| 71 |
*/ |
| 72 |
|
| 73 |
// {}, preserve ansi |
| 74 |
result = replacePlaceholderTest("echo {}", false, Delimiter{}, printsep, false, "query", items1) |
| 75 |
checkFormat("echo {{.O}} foo{{.I}}bar \x1b[31mbaz\x1b[m{{.O}}") |
| 76 |
|
| 77 |
// {}, strip ansi |
| 78 |
result = replacePlaceholderTest("echo {}", true, Delimiter{}, printsep, false, "query", items1) |
| 79 |
checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}") |
| 80 |
|
| 81 |
// {r}, strip ansi |
| 82 |
result = replacePlaceholderTest("echo {r}", true, Delimiter{}, printsep, false, "query", items1) |
| 83 |
checkFormat("echo foo'bar baz") |
| 84 |
|
| 85 |
// {r..}, strip ansi |
| 86 |
result = replacePlaceholderTest("echo {r..}", true, Delimiter{}, printsep, false, "query", items1) |
| 87 |
checkFormat("echo foo'bar baz") |
| 88 |
|
| 89 |
// {}, with multiple items |
| 90 |
result = replacePlaceholderTest("echo {}", true, Delimiter{}, printsep, false, "query", items2) |
| 91 |
checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}") |
| 92 |
|
| 93 |
// {..}, strip leading whitespaces, preserve ansi |
| 94 |
result = replacePlaceholderTest("echo {..}", false, Delimiter{}, printsep, false, "query", items1) |
| 95 |
checkFormat("echo {{.O}}foo{{.I}}bar \x1b[31mbaz\x1b[m{{.O}}") |
| 96 |
|
| 97 |
// {..}, strip leading whitespaces, strip ansi |
| 98 |
result = replacePlaceholderTest("echo {..}", true, Delimiter{}, printsep, false, "query", items1) |
| 99 |
checkFormat("echo {{.O}}foo{{.I}}bar baz{{.O}}") |
| 100 |
|
| 101 |
// {q} |
| 102 |
result = replacePlaceholderTest("echo {} {q}", true, Delimiter{}, printsep, false, "query", items1) |
| 103 |
checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}} {{.O}}query{{.O}}") |
| 104 |
|
| 105 |
// {q}, multiple items |
| 106 |
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}}") |
| 108 |
|
| 109 |
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}}") |
| 111 |
|
| 112 |
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}}") |
| 114 |
|
| 115 |
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}}") |
| 117 |
|
| 118 |
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}}") |
| 120 |
|
| 121 |
// forcePlus |
| 122 |
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}}") |
| 124 |
|
| 125 |
// Whitespace preserving flag with "'" delimiter |
| 126 |
result = replacePlaceholderTest("echo {s1}", true, Delimiter{str: &delim}, printsep, false, "query", items1) |
| 127 |
checkFormat("echo {{.O}} foo{{.O}}") |
| 128 |
|
| 129 |
result = replacePlaceholderTest("echo {s2}", true, Delimiter{str: &delim}, printsep, false, "query", items1) |
| 130 |
checkFormat("echo {{.O}}bar baz{{.O}}") |
| 131 |
|
| 132 |
result = replacePlaceholderTest("echo {s}", true, Delimiter{str: &delim}, printsep, false, "query", items1) |
| 133 |
checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}") |
| 134 |
|
| 135 |
result = replacePlaceholderTest("echo {s..}", true, Delimiter{str: &delim}, printsep, false, "query", items1) |
| 136 |
checkFormat("echo {{.O}} foo{{.I}}bar baz{{.O}}") |
| 137 |
|
| 138 |
// Whitespace preserving flag with regex delimiter |
| 139 |
regex = regexp.MustCompile(`\w+`) |
| 140 |
|
| 141 |
result = replacePlaceholderTest("echo {s1}", true, Delimiter{regex: regex}, printsep, false, "query", items1) |
| 142 |
checkFormat("echo {{.O}} {{.O}}") |
| 143 |
|
| 144 |
result = replacePlaceholderTest("echo {s2}", true, Delimiter{regex: regex}, printsep, false, "query", items1) |
| 145 |
checkFormat("echo {{.O}}{{.I}}{{.O}}") |
| 146 |
|
| 147 |
result = replacePlaceholderTest("echo {s3}", true, Delimiter{regex: regex}, printsep, false, "query", items1) |
| 148 |
checkFormat("echo {{.O}} {{.O}}") |
| 149 |
|
| 150 |
// No match |
| 151 |
result = replacePlaceholderTest("echo {}/{+}", true, Delimiter{}, printsep, false, "query", [3][]*Item{nil, nil, nil}) |
| 152 |
check("echo /") |
| 153 |
|
| 154 |
// No match, but with selections |
| 155 |
result = replacePlaceholderTest("echo {}/{+}", true, Delimiter{}, printsep, false, "query", [3][]*Item{nil, {item1}, nil}) |
| 156 |
checkFormat("echo /{{.O}} foo{{.I}}bar baz{{.O}}") |
| 157 |
|
| 158 |
// String delimiter |
| 159 |
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}}") |
| 161 |
|
| 162 |
// Regex delimiter |
| 163 |
regex = regexp.MustCompile("[oa]+") |
| 164 |
// foo'bar baz |
| 165 |
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}}") |
| 167 |
|
| 168 |
/* |
| 169 |
Test single placeholders, but focus on the placeholders' parameters (e.g. flags). |
| 170 |
see: TestParsePlaceholder |
| 171 |
*/ |
| 172 |
items3 := [3][]*Item{ |
| 173 |
// single line |
| 174 |
{newItem("1a 1b 1c 1d 1e 1f")}, |
| 175 |
// multi line |
| 176 |
{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 := false |
| 186 |
forcePlus := false |
| 187 |
query := "sample query" |
| 188 |
|
| 189 |
templateToOutput := make(map[string]string) |
| 190 |
templateToFile := make(map[string]string) // same as above, but the file contents will be matched |
| 191 |
// I. item type placeholder |
| 192 |
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}}` |
| 200 |
|
| 201 |
// II. token type placeholders |
| 202 |
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 range |
| 208 |
templateToOutput[`{1}`] = `{{.O}}1a{{.O}}` |
| 209 |
templateToOutput[`{1..1}`] = templateToOutput[`{1}`] |
| 210 |
templateToOutput[`{-6}`] = templateToOutput[`{1}`] |
| 211 |
// multiple ranges |
| 212 |
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 |
// flags |
| 217 |
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}}` |
| 223 |
|
| 224 |
// III. query type placeholder |
| 225 |
// query flag is not removed after parsing, so it gets doubled |
| 226 |
// while the double q is invalid, it is useful here for testing purposes |
| 227 |
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}}` |
| 230 |
|
| 231 |
// IV. escaping placeholder |
| 232 |
templateToOutput[`\{}`] = `{}` |
| 233 |
templateToOutput[`\{q}`] = `{q}` |
| 234 |
templateToOutput[`\{fzf:query}`] = `{fzf:query}` |
| 235 |
templateToOutput[`\{fzf:action}`] = `{fzf:action}` |
| 236 |
templateToOutput[`\{++}`] = `{++}` |
| 237 |
templateToOutput[`{++}`] = templateToOutput[`{+}`] |
| 238 |
|
| 239 |
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) |
| 245 |
|
| 246 |
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) |
| 251 |
|
| 252 |
checkFormat(wantOutput) |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
func 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 backslash |
| 258 |
unixStyle := quotes{``, `'`, `'\''`, `"`, `\`, `\`} |
| 259 |
windowsStyle := quotes{`^`, `^"`, `'`, `\^"`, `\\`, `\`} |
| 260 |
var effectiveStyle quotes |
| 261 |
|
| 262 |
// Pin $SHELL so the quoting style doesn't depend on the test runner's shell |
| 263 |
t.Setenv("SHELL", "cmd") |
| 264 |
exec := util.NewExecutor("") |
| 265 |
|
| 266 |
if util.IsWindows() { |
| 267 |
effectiveStyle = windowsStyle |
| 268 |
} else { |
| 269 |
effectiveStyle = unixStyle |
| 270 |
} |
| 271 |
|
| 272 |
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}}`, |
| 278 |
|
| 279 |
`$`: `{{.O}}${{.O}}`, |
| 280 |
`$HOME`: `{{.O}}$HOME{{.O}}`, |
| 281 |
`'$HOME'`: `{{.O}}{{.SQ}}$HOME{{.SQ}}{{.O}}`, |
| 282 |
|
| 283 |
`&`: `{{.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 |
} |
| 297 |
|
| 298 |
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 |
} |
| 306 |
|
| 307 |
// purpose of this test is to demonstrate some shortcomings of fzf's templating system on Unix |
| 308 |
func 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} |
| 314 |
|
| 315 |
// 1) working examples |
| 316 |
|
| 317 |
// paths that does not have to evaluated will work fine, when quoted |
| 318 |
{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'`}}, |
| 321 |
|
| 322 |
// only placeholders are escaped as data, this will lookup tilde character in a test file in your home directory |
| 323 |
// quoting the tilde is required (to be treated as string) |
| 324 |
{give{`grep {} ~/test`, ``, newItems(`~`)}, want{output: `grep '~' ~/test`}}, |
| 325 |
|
| 326 |
// 2) problematic examples |
| 327 |
// (not necessarily unexpected) |
| 328 |
|
| 329 |
// 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 |
} |
| 335 |
|
| 336 |
// purpose of this test is to demonstrate some shortcomings of fzf's templating system on Windows |
| 337 |
func TestWindowsCommands(t *testing.T) { |
| 338 |
// XXX Deprecated |
| 339 |
t.SkipNow() |
| 340 |
|
| 341 |
tests := []testCase{ |
| 342 |
// reference: give{template, query, items}, want{output OR match} |
| 343 |
|
| 344 |
// 1) working examples |
| 345 |
|
| 346 |
// example of redundantly escaped backslash in the output, besides looking bit ugly, it won't cause any issue |
| 347 |
{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 tabulator |
| 350 |
{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 path |
| 352 |
{give{`rg -- {}`, ``, newItems(`"C:\test.txt"`)}, want{output: `rg -- ^"\^"C:\\test.txt\^"^"`}}, |
| 353 |
|
| 354 |
// 2) problematic examples |
| 355 |
// (not necessarily unexpected) |
| 356 |
|
| 357 |
// 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^"`}}, |
| 359 |
|
| 360 |
// cat is parsing `\"` as a part of the file path, double quote is illegal character for paths on Windows |
| 361 |
// cat: "C:\\test.txt: Invalid argument |
| 362 |
{give{`cat {}`, ``, newItems(`"C:\test.txt"`)}, want{output: `cat ^"\^"C:\\test.txt\^"^"`}}, |
| 363 |
// cat: "C:\\test.txt": Invalid argument |
| 364 |
{give{`cmd /c {}`, ``, newItems(`cat "C:\test.txt"`)}, want{output: `cmd /c ^"cat \^"C:\\test.txt\^"^"`}}, |
| 365 |
|
| 366 |
// 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 it |
| 367 |
// the temp file contains: `cat "C:\test.txt"` |
| 368 |
// TODO this should actually work |
| 369 |
{give{`cmd /c {f}`, ``, newItems(`cat "C:\test.txt"`)}, want{match: `^cmd /c .*\fzf-preview-[0-9]{9}$`}}, |
| 370 |
} |
| 371 |
testCommands(t, tests) |
| 372 |
} |
| 373 |
|
| 374 |
// purpose of this test is to demonstrate some shortcomings of fzf's templating system on Windows in Powershell |
| 375 |
func TestPowershellCommands(t *testing.T) { |
| 376 |
if !util.IsWindows() { |
| 377 |
t.SkipNow() |
| 378 |
} |
| 379 |
|
| 380 |
tests := []testCase{ |
| 381 |
// reference: give{template, query, items}, want{output OR match} |
| 382 |
|
| 383 |
/* |
| 384 |
You can read each line in the following table as a pipeline that |
| 385 |
consist of series of parsers that act upon your input (col. 1) and |
| 386 |
each cell represents the output value. |
| 387 |
|
| 388 |
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 quotes |
| 392 |
- 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) |
| 394 |
|
| 395 |
Character⁰ CommandLineToArgvW Powershell commands Native commands from Powershell Apps requiring escapes¹ | Being tested below |
| 396 |
---------- ------------------ ------------------------------ ------------------------------- -------------------------- | ------------------ |
| 397 |
" empty string² missing argument error ... ... | |
| 398 |
\" literal " unbalanced quote error ... ... | |
| 399 |
'\"' literal '"' literal " empty string empty string (match all) | yes |
| 400 |
'\\\"' literal '\"' literal \" literal " literal " | |
| 401 |
---------- ------------------ ------------------------------ ------------------------------- -------------------------- | ------------------ |
| 402 |
\ transparent transparent transparent regex error | |
| 403 |
'\' transparent literal \ literal \ regex error | yes |
| 404 |
\\ 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 above |
| 410 |
''' transparent unbalanced quote error ... ... | |
| 411 |
'''' transparent literal ' literal ' literal ' | yes |
| 412 |
---------- ------------------ ------------------------------ ------------------------------- -------------------------- | ------------------ |
| 413 |
|
| 414 |
⁰: 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, ripgrep |
| 416 |
²: interpreted as a grouping quote, affects argument parser and gets removed from the result |
| 417 |
|
| 418 |
[CommandLineToArgvW]: https://docs.microsoft.com/en-gb/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw#remarks |
| 419 |
[NativeCallsFromPowershell]: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_parsing?view=powershell-7.1#passing-arguments-that-contain-quote-characters |
| 420 |
*/ |
| 421 |
|
| 422 |
// 1) working examples |
| 423 |
|
| 424 |
{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'`}}, |
| 426 |
|
| 427 |
// example of escaping single quotes |
| 428 |
{give{`rg -- {}`, ``, newItems(`'foobar'`)}, want{output: `rg -- '''foobar'''`}}, |
| 429 |
|
| 430 |
// chaining powershells |
| 431 |
{give{`powershell -NoProfile -Command {}`, ``, newItems(`cat "C:\test.txt"`)}, want{output: `powershell -NoProfile -Command 'cat \"C:\test.txt\"'`}}, |
| 432 |
|
| 433 |
// 2) problematic examples |
| 434 |
// (not necessarily unexpected) |
| 435 |
|
| 436 |
// looking for a path string will only work with escaped backslashes |
| 437 |
{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 quotes |
| 439 |
{give{`rg -- {}`, ``, newItems(`"C:\test.txt"`)}, want{output: `rg -- '\"C:\test.txt\"'`}}, |
| 440 |
|
| 441 |
// 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\"'`}}, |
| 444 |
|
| 445 |
// the "file" flag in the pattern won't create *.ps1 file so the powershell will offload this "unknown" filetype |
| 446 |
// to explorer, which will prompt user to pick editing program for the fzf-preview file |
| 447 |
// the temp file contains: `cat "C:\test.txt"` |
| 448 |
// TODO this should actually work |
| 449 |
{give{`powershell -NoProfile -Command {f}`, ``, newItems(`cat "C:\test.txt"`)}, want{match: `^powershell -NoProfile -Command .*\fzf-temp-[0-9]+$`}}, |
| 450 |
} |
| 451 |
|
| 452 |
// to force powershell-style escaping we temporarily set environment variable that fzf honors |
| 453 |
shellBackup := os.Getenv("SHELL") |
| 454 |
os.Setenv("SHELL", "powershell") |
| 455 |
testCommands(t, tests) |
| 456 |
os.Setenv("SHELL", shellBackup) |
| 457 |
} |
| 458 |
|
| 459 |
/* |
| 460 |
Test typical valid placeholders and parsing of them. |
| 461 |
|
| 462 |
Also since the parser assumes the input is matched with `placeholder` regex, |
| 463 |
the regex is tested here as well. |
| 464 |
*/ |
| 465 |
func TestParsePlaceholder(t *testing.T) { |
| 466 |
// give, want pairs |
| 467 |
templates := map[string]string{ |
| 468 |
// I. item type placeholder |
| 469 |
`{}`: `{}`, |
| 470 |
`{+}`: `{+}`, |
| 471 |
`{n}`: `{n}`, |
| 472 |
`{+n}`: `{+n}`, |
| 473 |
`{f}`: `{f}`, |
| 474 |
`{+nf}`: `{+nf}`, |
| 475 |
|
| 476 |
// II. token type placeholders |
| 477 |
`{..}`: `{..}`, |
| 478 |
`{1..}`: `{1..}`, |
| 479 |
`{..2}`: `{..2}`, |
| 480 |
`{1..2}`: `{1..2}`, |
| 481 |
`{-2..-1}`: `{-2..-1}`, |
| 482 |
// shorthand for x..x range |
| 483 |
`{1}`: `{1}`, |
| 484 |
`{1..1}`: `{1..1}`, |
| 485 |
`{-6}`: `{-6}`, |
| 486 |
// multiple ranges |
| 487 |
`{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 |
// flags |
| 492 |
`{+1}`: `{+1}`, |
| 493 |
`{+-1}`: `{+-1}`, |
| 494 |
`{s1}`: `{s1}`, |
| 495 |
`{f1}`: `{f1}`, |
| 496 |
`{+s1..2}`: `{+s1..2}`, |
| 497 |
`{+sf1..2}`: `{+sf1..2}`, |
| 498 |
|
| 499 |
// III. query type placeholder |
| 500 |
// query flag is not removed after parsing, so it gets doubled |
| 501 |
// while the double q is invalid, it is useful here for testing purposes |
| 502 |
`{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}`, // FIXME |
| 508 |
|
| 509 |
// IV. escaping placeholder |
| 510 |
`\{}`: `{}`, |
| 511 |
`\{++}`: `{++}`, |
| 512 |
`{++}`: `{+}`, |
| 513 |
} |
| 514 |
|
| 515 |
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 |
continue |
| 519 |
} |
| 520 |
|
| 521 |
_, placeholderWithoutFlags, flags := parsePlaceholder(giveTemplate) |
| 522 |
gotTemplate := placeholderWithoutFlags[:1] + flags.encodePlaceholder() + placeholderWithoutFlags[1:] |
| 523 |
|
| 524 |
if gotTemplate != wantTemplate { |
| 525 |
t.Errorf(`parsed placeholder "%s" into "%s", but want "%s"`, giveTemplate, gotTemplate, wantTemplate) |
| 526 |
} |
| 527 |
} |
| 528 |
} |
| 529 |
|
| 530 |
func 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) + garbage |
| 551 |
passthroughs, result := extractPassThroughs(line) |
| 552 |
if result != "foobazfoobazfoobaz"+garbage || len(passthroughs) != 6 { |
| 553 |
t.Error("failed to extract passthroughs") |
| 554 |
} |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
func TestWrapPassThrough(t *testing.T) { |
| 559 |
for _, passThrough := range []string{ |
| 560 |
"\x1bPtmux;\x1b\x1b_Ga=d,d=A\x1b\x1b\\\x1b\\", // Already wrapped |
| 561 |
"\x1bP0;1;0q#0;2;0;0;0#0~~@@vv@@~~@\x1b\\", // Sixel |
| 562 |
"\x1b]1337;File=inline=1:AAAA\a", // iTerm2 |
| 563 |
} { |
| 564 |
if got := wrapPassThrough(passThrough, true); got != passThrough { |
| 565 |
t.Errorf("should have been left alone: %q -> %q", passThrough, got) |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
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 |
} |
| 573 |
|
| 574 |
// ESC characters are doubled, and the trailing carriage return is kept |
| 575 |
// outside of the wrapper |
| 576 |
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 |
} |
| 586 |
|
| 587 |
func TestIsImagePassThrough(t *testing.T) { |
| 588 |
for _, tc := range []struct { |
| 589 |
given string |
| 590 |
image bool |
| 591 |
}{ |
| 592 |
// Kitty |
| 593 |
{"\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 payload |
| 596 |
{"\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}, // query |
| 602 |
{"\x1b_Gi=1,f=100\x1b\\", false}, // transmit only, the default action |
| 603 |
{"\x1b_Gm=1;AAAA\x1b\\", false}, // continuation chunk |
| 604 |
{"\x1b_Ga=f,i=1;AAAA\x1b\\", false}, // animation frame |
| 605 |
{"\x1b_Ga=T,U=1,f=32;AAAA\x1b\\", true}, // unicode placeholder |
| 606 |
// Wrapped in the tmux passthrough sequence |
| 607 |
{"\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 |
// iTerm2 |
| 611 |
{"\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 |
// Sixel |
| 616 |
{"\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 |
} |
| 625 |
|
| 626 |
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 line |
| 636 |
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 |
} |
| 640 |
|
| 641 |
/* utilities section */ |
| 642 |
|
| 643 |
// Item represents one line in fzf UI. Usually it is relative path to files and folders. |
| 644 |
func 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 |
} |
| 649 |
|
| 650 |
// Functions tested in this file require array of items (allItems). |
| 651 |
// This is helper function. |
| 652 |
func 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 |
} |
| 659 |
|
| 660 |
// (for logging purposes) |
| 661 |
func (item *Item) String() string { |
| 662 |
return item.AsString(true) |
| 663 |
} |
| 664 |
|
| 665 |
// Helper function to parse, execute and convert "text/template" to string. Panics on error. |
| 666 |
func templateToString(format string, data any) string { |
| 667 |
bb := &bytes.Buffer{} |
| 668 |
|
| 669 |
err := template.Must(template.New("").Parse(format)).Execute(bb, data) |
| 670 |
if err != nil { |
| 671 |
panic(err) |
| 672 |
} |
| 673 |
|
| 674 |
return bb.String() |
| 675 |
} |
| 676 |
|
| 677 |
// ad hoc types for test cases |
| 678 |
type give struct { |
| 679 |
template string |
| 680 |
query string |
| 681 |
allItems [3][]*Item |
| 682 |
} |
| 683 |
type want struct { |
| 684 |
/* |
| 685 |
Unix: |
| 686 |
The `want.output` string is supposed to be formatted for evaluation by |
| 687 |
`sh -c command` system call. |
| 688 |
|
| 689 |
Windows: |
| 690 |
The `want.output` string is supposed to be formatted for evaluation by |
| 691 |
`cmd.exe /s /c "command"` system call. The `/s` switch enables so called old |
| 692 |
behaviour, which is more favourable for nesting (possibly escaped) |
| 693 |
special characters. This is the relevant section of `help cmd`: |
| 694 |
|
| 695 |
...old behavior is to see if the first character is |
| 696 |
a quote character and if so, strip the leading character and |
| 697 |
remove the last quote character on the command line, preserving |
| 698 |
any text after the last quote character. |
| 699 |
*/ |
| 700 |
output string // literal output |
| 701 |
match string // output is matched against this regex (when output is empty string) |
| 702 |
} |
| 703 |
type testCase struct { |
| 704 |
give |
| 705 |
want |
| 706 |
} |
| 707 |
|
| 708 |
func testCommands(t *testing.T, tests []testCase) { |
| 709 |
// common test parameters |
| 710 |
delim := "\t" |
| 711 |
delimiter := Delimiter{str: &delim} |
| 712 |
printsep := "" |
| 713 |
stripAnsi := false |
| 714 |
forcePlus := false |
| 715 |
|
| 716 |
// evaluate the test cases |
| 717 |
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 |
} |
| 744 |
|
| 745 |
// naive encoder of placeholder flags |
| 746 |
func (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 { // FIXME |
| 761 |
encoded += "q" |
| 762 |
} |
| 763 |
return encoded |
| 764 |
} |
| 765 |
|
| 766 |
// can be replaced with os.ReadFile() in go 1.16+ |
| 767 |
func readFile(path string) ([]byte, error) { |
| 768 |
file, err := os.Open(path) |
| 769 |
if err != nil { |
| 770 |
return nil, err |
| 771 |
} |
| 772 |
defer file.Close() |
| 773 |
|
| 774 |
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 |
} |
| 780 |
|
| 781 |
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 = nil |
| 786 |
} |
| 787 |
return data, err |
| 788 |
} |
| 789 |
} |
| 790 |
} |
| 791 |
|
| 792 |
func TestWordWrapAnsiLine(t *testing.T) { |
| 793 |
term := &Terminal{} |
| 794 |
|
| 795 |
// Simple wrapping |
| 796 |
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 |
} |
| 800 |
|
| 801 |
// No wrapping needed |
| 802 |
result = term.wordWrapAnsiLine("hello", 10, 2) |
| 803 |
if len(result) != 1 || result[0] != "hello" { |
| 804 |
t.Errorf("No wrap: %q", result) |
| 805 |
} |
| 806 |
|
| 807 |
// ANSI codes preserved across split |
| 808 |
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 |
} |
| 812 |
|
| 813 |
// Long word (no space) - no break, let character wrapping handle it |
| 814 |
result = term.wordWrapAnsiLine("abcdefghij", 5, 2) |
| 815 |
if len(result) != 1 || result[0] != "abcdefghij" { |
| 816 |
t.Errorf("Long word: %q", result) |
| 817 |
} |
| 818 |
|
| 819 |
// Multiple words with continuation wrapSignWidth |
| 820 |
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 |
} |
| 826 |
|
| 827 |
// Empty string |
| 828 |
result = term.wordWrapAnsiLine("", 10, 2) |
| 829 |
if len(result) != 1 || result[0] != "" { |
| 830 |
t.Errorf("Empty: %q", result) |
| 831 |
} |
| 832 |
|
| 833 |
// OSC 8 hyperlink preserved |
| 834 |
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 |
} |
| 838 |
|
| 839 |
// Tab handling: tab expands to tabstop-aligned width |
| 840 |
term.tabstop = 8 |
| 841 |
// "\thi there" - tab at column 0 expands to 8, total "hi" starts at 8 |
| 842 |
// maxWidth=15: "\thi" = 10 wide, "there" = 5 wide, total 16 > 15, wrap at space |
| 843 |
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 |
} |
| 847 |
|
| 848 |
// Tab as word boundary: "hello"(5) + tab(3→col8) + "world"(5) = 13 total |
| 849 |
// maxWidth=13: fits without wrapping |
| 850 |
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 tab |
| 855 |
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 |
} |
| 860 |
|
| 861 |
func TestSplitOnIND(t *testing.T) { |
| 862 |
term := &Terminal{tabstop: 8} |
| 863 |
for _, tc := range []struct { |
| 864 |
name string |
| 865 |
line string |
| 866 |
want []string |
| 867 |
}{ |
| 868 |
{ |
| 869 |
// Nothing to do, so the caller keeps the line as it read it |
| 870 |
name: "no IND", |
| 871 |
line: "foo\n", |
| 872 |
want: nil, |
| 873 |
}, |
| 874 |
{ |
| 875 |
// chafa: CUB returns to the column the row started on |
| 876 |
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 column |
| 893 |
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 |
continue |
| 922 |
} |
| 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 |
} |