Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2
3import { embeddedScripts, withEmbeddedScripts } from "./embeddedScripts.ts";
4
5function scriptsOf(command: string) {
6 return embeddedScripts(command).map((script) => {
7 script.starts.forEach((start, index) => {
8 expect(start).toBeLessThan(script.ends[index]!);
9 if (index > 0) expect(start).toBeGreaterThanOrEqual(script.ends[index - 1]!);
10 });
11 return [
12 script.language,
13 script.text,
14 command.slice(script.starts[0], script.ends.at(-1)),
15 ] as const;
16 });
17}
18
19const pythonScript = `from pathlib import Path
20import json
21
22# print every package.json name and version
23for p in sorted(Path('.').glob('**/package.json')):
24 data = json.loads(p.read_text())
25 print(f"{data['name']:16} {data.get('version', '?')}")
26`;
27
28describe("embeddedScripts", () => {
29 it("finds the script inside a Codex login-shell wrapper and the script inside that", () => {
30 const inner = `console.log('interrupt fixture tool started'); setTimeout(() => {}, 30000)`;
31 const command = `/bin/bash -lc "node -e \\"${inner}\\""`;
32 expect(scriptsOf(command)).toEqual([
33 ["shellscript", `node -e "${inner}"`, `node -e \\"${inner}\\"`],
34 ["javascript", inner, inner],
35 ]);
36 });
37
38 it("skips the -- that ends a login shell's options before the script", () => {
39 expect(scriptsOf(`bash -lc -- "python3 -c 'print(1)'"`)).toEqual([
40 ["shellscript", "python3 -c 'print(1)'", "python3 -c 'print(1)'"],
41 ["python", "print(1)", "print(1)"],
42 ]);
43 });
44
45 it.each([
46 [`bash -c -e "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
47 [`bash -c +e "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
48 [`bash -c -e -- "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
49 [`bash -c - "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
50 [`bash -c -o pipefail "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
51 [`bash -co pipefail "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
52 [`bash -c -oe pipefail "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
53 [`bash -oc pipefail "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
54 [`bash -c +o errexit "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
55 [
56 `zsh -oextendedglob -c "python3 -c 'print(1)'"`,
57 "python3 -c 'print(1)'",
58 "python",
59 "print(1)",
60 ],
61 [`zsh -c --errexit "python3 -c 'print(1)'"`, "python3 -c 'print(1)'", "python", "print(1)"],
62 ])(
63 "extracts nested scripts across POSIX shell options in %s",
64 (command, shellScript, nestedLanguage, nestedScript) => {
65 expect(scriptsOf(command).map(([language, text]) => [language, text])).toEqual([
66 ["shellscript", shellScript],
67 [nestedLanguage, nestedScript],
68 ]);
69 },
70 );
71
72 it("highlights a heredoc fed to an interpreter in that interpreter's language", () => {
73 const command = `python3 - <<'PY'\n${pythonScript}PY`;
74 expect(scriptsOf(command)).toEqual([["python", pythonScript, pythonScript]]);
75 });
76
77 it("maps escaped characters back to both source characters", () => {
78 const command = `/bin/zsh -lc "python3 - <<'PY'\nprint(\\"\\$HOME\\")\nPY"`;
79 const [shell, python] = scriptsOf(command);
80 expect(shell?.[1]).toBe(`python3 - <<'PY'\nprint("$HOME")\nPY`);
81 expect(python).toEqual(["python", `print("$HOME")\n`, `print(\\"\\$HOME\\")\n`]);
82 });
83
84 it("maps attached short inline scripts back to exact source offsets", () => {
85 expect(scriptsOf(`bash -lc "python3 -c'print(\\"\\$HOME\\")'"`)).toEqual([
86 ["shellscript", `python3 -c'print("$HOME")'`, `python3 -c'print(\\"\\$HOME\\")'`],
87 ["python", `print("$HOME")`, `print(\\"\\$HOME\\")`],
88 ]);
89 expect(scriptsOf("python3 -c'x = 1\nprint(x)'")).toEqual([
90 ["python", "x = 1\nprint(x)", "x = 1\nprint(x)"],
91 ]);
92 });
93
94 it.each([
95 [`bash -Ec 'echo hi'`, "shellscript", "echo hi"],
96 [`bash -euo pipefail -c 'echo hi'`, "shellscript", "echo hi"],
97 [`bash +x -c 'echo hi'`, "shellscript", "echo hi"],
98 [`bash -c -- -e`, "shellscript", "-e"],
99 [`bash -s -c 'echo 1' <<'EOF'\necho 2\nEOF`, "shellscript", "echo 1"],
100 [`sh --rcfile /dev/null -c 'echo SCRIPT'`, "shellscript", "echo SCRIPT"],
101 [`zsh -conoclobber 'echo hi'`, "shellscript", "echo hi"],
102 [`zsh -Oc 'echo hi'`, "shellscript", "echo hi"],
103 [`zsh -ofunctionargzero -c 'echo hi'`, "shellscript", "echo hi"],
104 [`fish -c -e "python3 -c 'print(1)'"`, "fish", "-e"],
105 [`fish -lc 'echo hi'`, "fish", "echo hi"],
106 [`fish -iNc'echo hi'`, "fish", "echo hi"],
107 [`python3 -c 'print(1)'`, "python", "print(1)"],
108 [`py -3 -c 'print(1)'`, "python", "print(1)"],
109 [`"C:\\Program Files\\Python312\\python.exe" -c 'print(1)'`, "python", "print(1)"],
110 [`node --eval "process.exit(0)"`, "javascript", "process.exit(0)"],
111 [`bun -e 'console.log(Bun.version)'`, "typescript", "console.log(Bun.version)"],
112 [`deno eval 'console.log(1)'`, "typescript", "console.log(1)"],
113 [`deno eval --config deno.json 'console.log(1)'`, "typescript", "console.log(1)"],
114 [`psql -f schema.sql -c 'select 1'`, "sql", "select 1"],
115 [`node -C development -e 'console.log(1)'`, "javascript", "console.log(1)"],
116 [
117 `node --input-type module -e "import fs from 'node:fs'"`,
118 "javascript",
119 "import fs from 'node:fs'",
120 ],
121 [
122 `node --env-file .env -e 'console.log(process.env.FOO)'`,
123 "javascript",
124 "console.log(process.env.FOO)",
125 ],
126 [`node --env-file-if-exists .env.local -e 'console.log(1)'`, "javascript", "console.log(1)"],
127 [`node --experimental-loader ./loader.mjs -e 'console.log(1)'`, "javascript", "console.log(1)"],
128 [`ruby -e 'puts 1'`, "ruby", "puts 1"],
129 [`ruby -I lib -e 'puts 1'`, "ruby", "puts 1"],
130 [`ruby -ne 'print if /foo/' input.txt`, "ruby", "print if /foo/"],
131 [`python3 -uc 'print(1)'`, "python", "print(1)"],
132 [`python3 -c'print(1)'`, "python", "print(1)"],
133 [`python3 -uc'print(1)'`, "python", "print(1)"],
134 [`python3 -uXdev -c'print(42)'`, "python", "print(42)"],
135 [`node -pe 'process.version'`, "javascript", "process.version"],
136 [`perl -E 'say 1'`, "perl", "say 1"],
137 [`perl -e'print 1'`, "perl", "print 1"],
138 [`perl -pe 's/foo/bar/' input.txt`, "perl", "s/foo/bar/"],
139 [`perl -0777e'print 1'`, "perl", "print 1"],
140 [`perl -l0123e 'print 42'`, "perl", "print 42"],
141 [`perl -0777ne 'print length' input.txt`, "perl", "print length"],
142 [`perl -I lib -Mstrict -pe 's/foo/bar/' input.txt`, "perl", "s/foo/bar/"],
143 [`perl -nwIlib -e'print 1'`, "perl", "print 1"],
144 [`perl -e'print 1;' file.txt -e 'print 2'`, "perl", "print 1;"],
145 [`ruby -ne'puts $_' input.txt`, "ruby", "puts $_"],
146 [`ruby -0777e'puts 42'`, "ruby", "puts 42"],
147 [`ruby -W0e'puts 42'`, "ruby", "puts 42"],
148 [`ruby -Kue'puts 42'`, "ruby", "puts 42"],
149 [`ruby -e'puts 1' -- -e'puts 2'`, "ruby", "puts 1"],
150 [`sqlite3 app.db "select * from users"`, "sql", "select * from users"],
151 [`pwsh -NoProfile -Command "Get-ChildItem"`, "powershell", "Get-ChildItem"],
152 [
153 `osascript -e 'tell application "Finder" to activate'`,
154 "applescript",
155 'tell application "Finder" to activate',
156 ],
157 [
158 `osascript -l JavaScript -e 'Application("Finder").activate()'`,
159 "javascript",
160 'Application("Finder").activate()',
161 ],
162 [
163 `osascript -lJavaScript <<'EOF'\nApplication("Finder").activate()\nEOF`,
164 "javascript",
165 'Application("Finder").activate()\n',
166 ],
167 [`osascript -l JavaScript -l AppleScript -e 'beep'`, "applescript", "beep"],
168 [`env FOO=1 sudo -u bob python3 -c 'print(1)'`, "python", "print(1)"],
169 [`env -- FOO=1 python3 -c 'print(1)'`, "python", "print(1)"],
170 [`timeout 30 python3 -c 'print(1)'`, "python", "print(1)"],
171 [`gtimeout 30 python3 -c 'print(1)'`, "python", "print(1)"],
172 [`timeout -k 5 30s node -e 'console.log(1)'`, "javascript", "console.log(1)"],
173 [`timeout -k5s -v -sKILL 10 bash -c 'echo hi'`, "shellscript", "echo hi"],
174 [`timeout --kill-after 5 --signal KILL 30 bash -c 'echo hi'`, "shellscript", "echo hi"],
175 [`timeout -fk 5 1.5m bash -c 'echo hi'`, "shellscript", "echo hi"],
176 [`timeout -s KILL -v -- 0 bash -c 'echo hi'`, "shellscript", "echo hi"],
177 [`timeout 30 env FOO=1 python3 -c 'print(1)'`, "python", "print(1)"],
178 [`node --eval="process.exit(0)"`, "javascript", "process.exit(0)"],
179 [`psql --command='select 1'`, "sql", "select 1"],
180 [`psql -c 'select 1' <<'EOF'\nselect 2;\nEOF`, "sql", "select 1"],
181 [`mysql -c -e 'select 1'`, "sql", "select 1"],
182 [`psql -Atc 'select 1'`, "sql", "select 1"],
183 [`mysql -Ne 'select 1'`, "sql", "select 1"],
184 [`psql app <<'EOF'\nselect 1;\nEOF`, "sql", "select 1;\n"],
185 [`echo "$(node -e 'console.log(1)')"`, "javascript", "console.log(1)"],
186 [`python3 <<< 'print(1)'`, "python", "print(1)"],
187 ])("finds the inline script in %s", (command, language, script) => {
188 expect(scriptsOf(command)).toEqual([[language, script, expect.any(String)]]);
189 });
190
191 it.each([
192 [
193 `perl -e'print 1;' -E 'say 2'`,
194 [
195 ["perl", "print 1;", "print 1;"],
196 ["perl", "say 2", "say 2"],
197 ],
198 ],
199 [
200 `ruby -e'puts 1' -e 'puts 2'`,
201 [
202 ["ruby", "puts 1", "puts 1"],
203 ["ruby", "puts 2", "puts 2"],
204 ],
205 ],
206 ])("finds repeated inline scripts in %s", (command, expected) => {
207 expect(scriptsOf(command)).toEqual(expected);
208 });
209
210 it.each([[`psql -c 'select 1' -c 'select 2'`], [`sqlite3 app.db "select 1" "select 2"`]])(
211 "finds every statement a SQL shell runs: %s",
212 (command) => {
213 expect(scriptsOf(command).map(([language, text]) => [language, text])).toEqual([
214 ["sql", "select 1"],
215 ["sql", "select 2"],
216 ]);
217 },
218 );
219
220 it.each([
221 [`psql -c 'select 1' -f - <<'EOF'\nselect 2;\nEOF`, ["select 1", "select 2;\n"]],
222 [`psql --command='select 1' -f - <<< 'select 2;'`, ["select 1", "select 2;"]],
223 ])("highlights both inline and stdin SQL in %s", (command, expected) => {
224 expect(scriptsOf(command).map(([language, text]) => [language, text])).toEqual(
225 expected.map((text) => ["sql", text]),
226 );
227 });
228
229 it.each([
230 ["the file `cat` writes", `cat > src/app.ts <<'EOF'\nconst a = 1;\nEOF`, "typescript"],
231 ["the file `tee` writes", `tee -a config.json <<EOF\n{}\nEOF`, "json"],
232 ["its delimiter", `kubectl apply -f - <<'YAML'\nkind: Pod\nYAML`, "yaml"],
233 ["the shell reading it", `bash <<'EOF'\necho hi\nEOF`, "shellscript"],
234 [
235 "a shell reading stdin with -s and operands",
236 `bash -euxs -- prod <<'EOF'\necho "$1"\nEOF`,
237 "shellscript",
238 ],
239 ["zsh with -onoclobber", `zsh -onoclobber <<'EOF'\necho hi\nEOF`, "shellscript"],
240 ["psql reading stdin with -f -", `psql -f - <<'EOF'\nselect 1;\nEOF`, "sql"],
241 ["psql reading stdin with --file=-", `psql --file=- <<'EOF'\nselect 1;\nEOF`, "sql"],
242 ["psql reading stdin with attached -f-", `psql -Atf- <<'EOF'\nselect 1;\nEOF`, "sql"],
243 ["psql mixing a file and -f -", `psql -f schema.sql -f - <<'EOF'\nselect 1;\nEOF`, "sql"],
244 ])("takes a heredoc's language from %s", (_source, command, language) => {
245 expect(scriptsOf(command).map(([lang]) => lang)).toEqual([language]);
246 });
247
248 it.each([
249 ["a script file", `python3 build.py <<EOF\ndata\nEOF`],
250 ["a module", `python3 -m json.tool <<EOF\n{}\nEOF`],
251 ["a SQL file", `psql -f migrate.sql <<EOF\ny\nEOF`],
252 ["a SQL file given with =", `psql --file=migrate.sql <<EOF\ny\nEOF`],
253 ["plain commands", `rg -n "foo" src && git status`],
254 ["an unnamed heredoc into a plain command", `git commit -F - <<'EOF'\nfix: x\nEOF`],
255 ["an empty script", `bash -lc ' '`],
256 ["a perl -i backup suffix of e", `perl -pie 's/foo/bar/' input.txt`],
257 ["a ruby -i backup suffix of e", `ruby -ie 'puts 1' input.txt`],
258 ["a python -W value of c", `python3 -Wc 'print(1)'`],
259 ["an attached python -W value starting with c", `python3 -Wc'print(1)'`],
260 ["a bundled python -X consuming the next arg", `python3 -uX -c'print(42)'`],
261 ["a bundled python -W consuming the next arg", `python3 -uW -c'print(42)'`],
262 ["an attached python -m module before -c", `python3 -mthis -c'print(42)'`],
263 ["a bundled python -m module before -c", `python3 -um this -c'print(42)'`],
264 ["an attached perl -M module starting with e", `perl -Me'print 1'`],
265 ["a bundled perl -I consuming the next arg", `perl -nwI -e'print 1'`],
266 ["an invalid perl octal switch without leading 0", `perl -7e'print 1'`],
267 ["an attached ruby -r require starting with e", `ruby -re'puts 1'`],
268 ["a ruby -K option consuming e as its encoding", `ruby -Ke 'puts 42'`],
269 ["a bundled ruby -I consuming the next arg", `ruby -wI -e'puts 42'`],
270 ["a ruby -W category before e", `ruby -W:deprecatede'puts 42'`],
271 ["a node -e flag with an attached value", `node -e'console.log(1)'`],
272 ["an attached inline flag after --", `python3 -- -c'print(1)'`],
273 [
274 "a whitespace-only attached inline script before a heredoc",
275 `python3 -c' ' <<'EOF'\nprint(2)\nEOF`,
276 ],
277 ["an empty attached python -c before a heredoc", `python3 -c'' <<'EOF'\nprint(2)\nEOF`],
278 ["an empty separate python -c before a heredoc", `python3 -c '' <<'EOF'\nprint(2)\nEOF`],
279 ["a bare python -c before a heredoc", `python3 -c <<'EOF'\nprint(2)\nEOF`],
280 ["a bare psql -c before a heredoc", `psql -c <<'EOF'\nselect 1;\nEOF`],
281 ["a psql -d database named c", `psql -dc 'select 1'`],
282 ["a bundled psql -f script file", `psql -Atf query.sql <<'EOF'\nselect 1;\nEOF`],
283 ["a bare psql -f before a heredoc", `psql -f <<'EOF'\nselect 1;\nEOF`],
284 ["a psql -f - followed by a bare -f before a heredoc", `psql -f - -f <<'EOF'\nselect 1;\nEOF`],
285 ["a duckdb -f - before a heredoc", `duckdb -f - <<'EOF'\nselect 1;\nEOF`],
286 ["a fish -C init command named c", `fish -Cc 'echo hi'`],
287 ["a shell whose -c has no script, before a heredoc", `sh -c -- <<'EOF'\necho hi\nEOF`],
288 [
289 "a shell whose -c has only trailing options before a heredoc",
290 `sh -c -e <<'EOF'\necho hi\nEOF`,
291 ],
292 [
293 "a shell whose -co option has no script after its option value",
294 `bash -co pipefail <<'EOF'\necho hi\nEOF`,
295 ],
296 [
297 "a shell with a GNU long option after -c",
298 `bash -c --rcfile /dev/null "python3 -c 'print(1)'"`,
299 ],
300 ["a shell with a GNU long option after -s", `bash -s --norc prod <<'EOF'\necho hi\nEOF`],
301 ["a zsh -o option name containing s", `zsh -oshwordsplit run.sh <<'EOF'\necho hi\nEOF`],
302 ["a ksh -o option name containing c", `ksh -onoclobber run.sh`],
303 ["a shell clearing -s with +s", `dash -s +s run.sh <<'EOF'\necho hi\nEOF`],
304 ["a heredoc `cat` sends to stdout while stderr goes to a file", `cat 2>log.ts <<'EOF'\nx\nEOF`],
305 ])("finds nothing for %s", (_case, command) => {
306 expect(scriptsOf(command)).toEqual([]);
307 });
308
309 it("trusts nothing in a command whose quoting does not parse", () => {
310 // Secret redaction removed an escaped quote's backslash, breaking the -lc argument.
311 const command = `/bin/zsh -lc "python3 -c 'token=[REDACTED_SECRET]"apiToken\\"]; print(token)'"`;
312 expect(scriptsOf(command)).toEqual([]);
313 });
314});
315
316describe("withEmbeddedScripts", () => {
317 function tokenize(text: string, language: string) {
318 if (language === "unknown") throw new Error("Language not found");
319 let lineStart = 0;
320 return text.split(/\r?\n/u).map((line) => {
321 const tokens = [...line.matchAll(/\S+|\s+/gu)].map((match) => ({
322 content: match[0],
323 offset: lineStart + match.index,
324 color: language,
325 }));
326 lineStart +=
327 line.length + (text.slice(lineStart + line.length).match(/^\r?\n/u)?.[0].length ?? 0);
328 return tokens;
329 });
330 }
331
332 function colorsOf(code: string, scripts = embeddedScripts(code)) {
333 const lines = withEmbeddedScripts(code, tokenize(code, "shellscript"), scripts, tokenize);
334 expect(lines.map((line) => line.map((token) => token.content).join("")).join("\n")).toBe(
335 code.replaceAll("\r\n", "\n"),
336 );
337 return lines.flat().map((token) => [token.content, token.color]);
338 }
339
340 it("colors each nested script with its own grammar, keeping the text", () => {
341 expect(colorsOf(`bash -lc "python3 -c 'print(1)'"`)).toEqual([
342 [`bash -lc "python3 -c '`, "shellscript"],
343 ["print(1)", "python"],
344 [`'"`, "shellscript"],
345 ]);
346 });
347
348 it("colors an escape sequence like the character it spells", () => {
349 expect(colorsOf(`bash -c "python3 -c 'print(\\"x\\")'"`)).toContainEqual([
350 `print(\\"x\\")`,
351 "python",
352 ]);
353 });
354
355 it("keeps the surrounding colors where a grammar is missing", () => {
356 const code = "cat > x.ts <<'EOF'\r\nbody\r\nEOF";
357 const [script] = embeddedScripts(code);
358 const characterColors = (scripts: ReturnType<typeof embeddedScripts>) =>
359 colorsOf(code, scripts).flatMap(([content, color]) => [...content!].map(() => color));
360 expect(characterColors([{ ...script!, language: "unknown" }])).toEqual(characterColors([]));
361 });
362});