// ShellWord.literalWith: a word's literal with known plain variables // substituted structurally. Expected values were checked against GNU bash 5.3 // (`printf '<%s>' WORD` with the same variables set). import { assert, describe, it } from "@effect/vitest"; import { Option } from "effect"; import type { ShellWord } from "../src/index.js"; import { ShellAssignment, ShellSyntax, ShellWord as Word } from "../src/index.js"; const VARS: ReadonlyMap = new Map([ ["x", "V"], ["dir", "/tmp/a"], ["xy", "joined"], ["spaced", "a b"], ["star", "*.ts"], ["bracket", "[ab]"], ["ext", "@(a)"], ["empty", ""], ["subst", "$(cmd)"], ["quote", `"'`], ]); /** The only word of `input`'s only segment, as a command argument or an assignment value. */ const wordOf = (input: string): ShellWord => { const [segment] = ShellSyntax.parse(input).segments; const word = segment?.words[0] ?? segment?.assignments[0]?.value; if (word === undefined) throw new Error(`no word in ${JSON.stringify(input)}`); return word; }; const literalWith = (input: string, vars: ReadonlyMap = VARS): string | null => Option.getOrNull(Word.literalWith(wordOf(input), vars)); describe("ShellWord.literalWith", () => { describe("substitutes a plain name found in vars", () => { it.each([ ["$NAME", "$x", "V"], [`\${NAME}`, `\${x}`, "V"], ["a name next to text", "$dir/b", "/tmp/a/b"], ["a braced name before name characters", `\${x}y`, "Vy"], ["an unbraced name runs to its last name character", "$xy", "joined"], ["inside double quotes", '"$dir/b"', "/tmp/a/b"], ["braced inside double quotes", `"\${x}y"`, "Vy"], ["two in one double-quoted part", '"$x-$x"', "V-V"], ["across mixed parts", `a"$x"b'c'$x`, "aVbcV"], ["after an ANSI-C part", "$'q'$x", "qV"], ["in a localized part", '$"a $x"', "a V"], ["beside escaped double quotes", '"\\"$x\\""', '"V"'], ["beside a backslash bash keeps", '"a\\b$x"', "a\\bV"], ["beside an escaped $", '"\\$x$x"', "$xV"], ["a name joined across a backslash-newline", '"$x\\\ny"', "joined"], ["a braced name with a backslash-newline", `\${x\\\n}`, "V"], ["an assignment value", "FOO=$dir", "/tmp/a"], ])("%s", (_, input, expected) => { assert.strictEqual(literalWith(input), expected); }); }); describe("keeps quoted and escaped dollars as literal text", () => { it.each([ ["single quotes", "'$x'", "$x"], ["single quotes beside a substitution", `'$x'$x`, "$xV"], ["an escaped $", "\\$x", "$x"], ["an escaped $ in double quotes", '"\\$x"', "$x"], ["an escaped $ beside a substitution", "\\$x$x", "$xV"], ["ANSI-C quoting", "$'$x'", "$x"], ])("%s", (_, input, expected) => { assert.strictEqual(literalWith(input), expected); }); }); describe("is None for any other expansion", () => { it.each([ ["a name vars lacks", "$missing"], ["a braced name vars lacks", `"\${missing}"`], ["a known and an unknown name", '"$x$missing"'], ["a default operator", `\${x:-y}`], ["a default operator in double quotes", `"\${x:-y}"`], ["a length", `\${#x}`], ["an indirection", `\${!x}`], ["a subscript", `\${x[0]}`], ["a substring", `\${x:1}`], ["a positional parameter", "$1"], ["a braced positional parameter", `\${1}`], ["$@", '"$@"'], ["$$", "$$"], ["$?", "$?"], ["a command substitution", '"$x$(cmd)"'], ["a backtick substitution", '"`cmd`"'], ["an unquoted command substitution", "$(cmd)"], ["arithmetic", '"$((1 + 1))"'], ["legacy arithmetic", "$[1]"], ["a process substitution", "<(cmd)"], ["a tilde", "~/$x"], ["a glob", "$x*"], ["a brace span", "{a,b}$x"], ["an unterminated quote", '"$x'], ])("%s", (_, input) => { assert.isNull(literalWith(input)); }); }); describe("never splits, globs or re-reads a substituted value", () => { it.each([ ["a value with a blank, quoted", '"$spaced"', "a b"], ["a glob value, quoted", '"$star"', "*.ts"], ["a bracket value, quoted", '"$bracket"', "[ab]"], ["a value holding substitution text", '"$subst"', "$(cmd)"], ["a value holding substitution text, unquoted", "$subst", "$(cmd)"], ["a value holding quotes", "$quote", `"'`], ["an empty value, quoted", '"$empty"', ""], ["an empty value beside an empty quote", '$empty""', ""], ["an empty value beside text", "a$empty", "a"], ])("%s", (_, input, expected) => { assert.strictEqual(literalWith(input), expected); }); it.each([ ["a value bash splits", "$spaced"], ["a value bash splits, beside text", "a$spaced"], ["a value bash globs", "$star"], ["a bracket expression bash globs", "$bracket"], ["an extglob pattern", "$ext"], ["an empty value that removes the word", "$empty"], ["two empty values that remove the word", `$empty\${empty}`], ])("is None for %s unquoted", (_, input) => { assert.isNull(literalWith(input)); }); }); it("substitutes only a name, whatever keys vars holds", () => { const odd = new Map([ ["1", "one"], ["@", "all"], ["?", "status"], ["x:-y", "operator"], ["#x", "length"], ["x[0]", "element"], ]); for (const input of ["$1", `\${1}`, '"$@"', "$?", `\${x:-y}`, `\${#x}`, `\${x[0]}`]) { assert.isNull(literalWith(input, odd), input); } }); it("reads vars as a map, never through a prototype", () => { assert.isNull(literalWith("$constructor", new Map())); assert.isNull(literalWith('"$__proto__"', new Map())); assert.strictEqual(literalWith("$constructor", new Map([["constructor", "c"]])), "c"); }); it("is exactly literal with no vars", () => { for (const input of [ "git", "'a b'", '"a\\"b\\\\c\\$d\\e"', "$'a\\tb'", '$"loc"', "a\"b\"'c'", "FOO=", "$x", '"$x"', "~", "*", ]) { const word = wordOf(input); assert.deepStrictEqual(Word.literalWith(word, new Map()), word.literal, input); } }); }); /** The word at `index` of the first segment's words. */ const argOf = (input: string, index = 1): ShellWord => { const word = ShellSyntax.parse(input).segments[0]?.words[index]; if (word === undefined) throw new Error(`no word ${index} in ${JSON.stringify(input)}`); return word; }; const assigned = (word: ShellWord, vars: ReadonlyMap = VARS): string | null => Option.getOrNull(Word.literalWith(word, vars, { context: "assignment" })); // Expected values from GNU bash 5.3: `X=WORD; printf '<%s>' "$X"`, and for a // declaration builtin `export X=WORD` in a directory holding files to glob. describe("ShellWord.literalWith in an assignment context", () => { it.each([ ["a value holding blanks", "X=$spaced", "a b"], ["a value holding a glob", "X=$star", "*.ts"], ["a value holding a bracket", "X=$bracket", "[ab]"], ["a value holding an extglob opener", "X=$ext", "@(a)"], ["an empty value", "X=$empty", ""], ["an empty value beside an empty one", "X=$empty$empty", ""], ])("substitutes %s, which bash neither splits nor globs", (_, input, expected) => { assert.strictEqual(assigned(wordOf(input)), expected); assert.isNull(literalWith(input)); }); it.each([ ["a glob", "export X=*", "X=*"], ["a glob beside a value", "export X=$star*", "X=*.ts*"], ["a tilde after other text", "export X=x~/a", "X=x~/a"], ["a substituted name", "export X=$spaced", "X=a b"], ["a tilde after an expansion", "export X=$x~/a", "X=V~/a"], ])("reads %s in a declaration builtin's assignment argument as text", (_, input, expected) => { assert.strictEqual(assigned(argOf(input)), expected); }); it.each([ ["a tilde after =", "export X=~/a"], ["a tilde after :", "export X=a:~/b"], ["a tilde after a quoted run and :", 'export X="a":~/b'], ["a tilde after = with a user", "export X=~root"], ["a brace span", "export X=a{b,c}"], ["a name vars lacks", "export X=$missing"], ["a command substitution", "export X=$(cmd)"], ])("is None for %s, which bash still expands there", (_, input) => { assert.isNull(assigned(argOf(input))); }); it("is None for a tilde an assignment value starts with", () => { assert.isNull(assigned(wordOf("X=~/a"))); assert.isNull(assigned(wordOf("X=a:~/b"))); }); it("is literalWith's default reading for a word context", () => { const word = wordOf("X=$spaced"); assert.deepStrictEqual(Word.literalWith(word, VARS, { context: "word" }), Word.literalWith(word, VARS)); }); }); describe("ShellDoubleQuotedPart.pieces", () => { const piecesOf = (input: string): ReadonlyArray => { const part = argOf(input).parts[0]; if (part?.kind !== "doubleQuoted") throw new Error(`no double-quoted part in ${JSON.stringify(input)}`); return part.pieces.map((piece) => (typeof piece === "string" ? `text:${piece}` : `${piece.kind}:${piece.raw}`)); }; it("separates decoded text from each expansion", () => { // The shell text: echo "a\$b $c \"q\" \\ \` ${d:-"x y"}$(e) $((1))" const input = `echo "a\\$b $c \\"q\\" \\\\ \\\` \${d:-"x y"}$(e) $((1))"`; assert.deepStrictEqual(piecesOf(input), [ "text:a$b ", "variable:$c", 'text: "q" \\ ` ', `variable:\${d:-"x y"}`, "commandSubstitution:$(e)", "text: ", "arithmetic:$((1))", ]); }); it("removes a line continuation and keeps any other backslash", () => { assert.deepStrictEqual(piecesOf('echo "a\\\nb\\n"'), ["text:ab\\n"]); }); it("reads a localized part's text inside its $\"", () => { assert.deepStrictEqual(piecesOf('echo $"loc $x"'), ["text:loc ", "variable:$x"]); }); it("is empty for an empty string and one text piece for a literal", () => { assert.deepStrictEqual(piecesOf('echo ""'), []); assert.deepStrictEqual(piecesOf('echo "a b"'), ["text:a b"]); }); it("lists a backtick substitution as an expansion", () => { assert.deepStrictEqual(piecesOf('echo "`f` x"'), ["commandSubstitution:`f`", "text: x"]); }); }); describe("ShellAssignment.valueWith", () => { const valueWith = (input: string, vars?: ReadonlyMap): ReadonlyArray => (ShellSyntax.parse(input).segments[0]?.assignments ?? []).map((assignment) => Option.getOrNull(ShellAssignment.valueWith(assignment, vars)), ); it("reads each assignment's value as bash assigns it", () => { assert.deepStrictEqual(valueWith("A=$spaced B=* C={a,b} D=$empty cmd", VARS), ["a b", "*", "{a,b}", ""]); }); it("is None for a value bash expands", () => { assert.deepStrictEqual(valueWith("A=~/a B=$missing C=$(cmd)", VARS), [null, null, null]); }); it("reads with no vars as the value's literal", () => { assert.deepStrictEqual(valueWith("A='a b' B=$x"), ["a b", null]); }); }); // bash 5.3 expands a tilde after the first `=` and after each unquoted `:` // in any word written as an assignment, an argument or a redirection // target included (POSIX mode only in a declaration builtin's): checked // with `echo WORD` and `export WORD`. describe("a tilde in a word written as an assignment", () => { const literalOf = (input: string, index = 1): string | null => Option.getOrNull(argOf(input, index).literal); it.each([ ["export's argument", "export X=~/a"], ["export's argument after :", "export X=a:~root"], ["a later argument", "export A=1 X=~/a", 2], ["any command's argument", "make PREFIX=~/x"], ["an argument after command", "command export X=~/a", 2], ["an append", "export X+=:~/b"], ["a subscripted name", "export X[0]=~/a"], ["a quoted subscript", 'echo X["a b"]=~/a'], ["a value after a quoted run and :", 'echo X="a":~/b'], ["a tilde alone", "echo x9=~"], ["a tilde after : and a line continuation", "echo X=a:\\\n~/b"], ["a name split by a line continuation", "echo X\\\n=~/a"], ["a ~+ prefix", "echo X=~+/a"], ["a value split from its = by a line continuation", "echo X=\\\n~/a"], ["a name split inside by a line continuation", "echo XY\\\nZ=~/a"], ["a tilde-prefix ended by :", "echo X=~root:b"], ])("marks a tilde in %s", (_, input, index = 1) => { const word = argOf(input, index); assert.isTrue( word.parts.some((part) => part.kind === "tilde"), JSON.stringify(word.parts.map((part) => part.kind)), ); assert.isNull(Option.getOrNull(word.literal)); assert.isNull(Option.getOrNull(Word.literalWith(word, VARS, { context: "assignment" }))); }); it.each([ ["a quoted name", 'export "X"=~/a', "X=~/a"], ["an escaped =", "echo X\\=~/a", "X=~/a"], ["a tilde after a second =", "echo X=a=~/b", "X=a=~/b"], ["a quoted tilde suffix", 'echo X=~"/a"', "X=~/a"], ["an escaped :", "echo X=a\\:~/b", "X=a:~/b"], ["a tilde after other text", "echo X=x~/a", "X=x~/a"], ["a name with a dot", "echo a.b=~/x", "a.b=~/x"], ["an option", "echo -X=~/a", "-X=~/a"], ["no name", "echo =~/a", "=~/a"], ["a name starting with a digit", "echo 9=~/a", "9=~/a"], ["an escaped tilde", "echo X=\\~/a", "X=~/a"], ["an unclosed subscript", "echo X[a:~/b", "X[a:~/b"], ])("keeps a tilde bash leaves in %s", (_, input, expected) => { assert.strictEqual(literalOf(input), expected); assert.strictEqual(Option.getOrNull(Word.literalWith(argOf(input), VARS, { context: "assignment" })), expected); }); it("splits the tilde parts of a value after : as bash reads them", () => { assert.deepStrictEqual( argOf("export X=a:~root/x:~").parts.map((part) => `${part.kind}:${part.raw}`), ["bare:X=a:", "tilde:~root", "bare:/x:", "tilde:~"], ); }); it("marks a tilde in a redirection target written as an assignment", () => { const [redirection] = ShellSyntax.parse("echo > Y=~/r").segments[0]?.redirections ?? []; assert.isTrue(redirection?.target.kind === "word" && redirection.target.parts.some((p) => p.kind === "tilde")); }); }); // bash 5.3 ends a word-start tilde-prefix at a `:` too, in any word: // `echo ~:x ~root:x ~+:x` prints `$HOME:x /var/root:x $PWD:x`. describe("a tilde-prefix at a word's start ends at :", () => { it.each([ ["cd ~:x", "~"], ["echo ~root:x", "~root"], ["echo ~+:x", "~+"], ["echo ~-:x", "~-"], ])("marks the tilde of %s", (input, tilde) => { const word = argOf(input); assert.strictEqual(word.parts[0]?.kind, "tilde"); assert.strictEqual(word.parts[0]?.raw, tilde); assert.isNull(Option.getOrNull(word.literal)); }); it("control: a ~ after other text in an ordinary word stays text", () => { assert.strictEqual(Option.getOrNull(argOf("echo a:~").literal), "a:~"); assert.strictEqual(Option.getOrNull(argOf('echo ~":x"').literal), "~:x"); }); });