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 [`fish -c -e "python3 -c 'print(1)'"`, "fish", "-e"],
102 [`fish -lc 'echo hi'`, "fish", "echo hi"],
103 [`fish -iNc'echo hi'`, "fish", "echo hi"],
104 [`python3 -c 'print(1)'`, "python", "print(1)"],
105 [`py -3 -c 'print(1)'`, "python", "print(1)"],
106 [`"C:\\Program Files\\Python312\\python.exe" -c 'print(1)'`, "python", "print(1)"],
107 [`node --eval "process.exit(0)"`, "javascript", "process.exit(0)"],
108 [`bun -e 'console.log(Bun.version)'`, "typescript", "console.log(Bun.version)"],
109 [`deno eval 'console.log(1)'`, "typescript", "console.log(1)"],
110 [`deno eval --config deno.json 'console.log(1)'`, "typescript", "console.log(1)"],
111 [`psql -f schema.sql -c 'select 1'`, "sql", "select 1"],
112 [`node -C development -e 'console.log(1)'`, "javascript", "console.log(1)"],
113 [
114 `node --input-type module -e "import fs from 'node:fs'"`,
115 "javascript",
116 "import fs from 'node:fs'",
117 ],
118 [
119 `node --env-file .env -e 'console.log(process.env.FOO)'`,
120 "javascript",
121 "console.log(process.env.FOO)",
122 ],
123 [`node --env-file-if-exists .env.local -e 'console.log(1)'`, "javascript", "console.log(1)"],
124 [`node --experimental-loader ./loader.mjs -e 'console.log(1)'`, "javascript", "console.log(1)"],
125 [`ruby -e 'puts 1'`, "ruby", "puts 1"],
126 [`ruby -I lib -e 'puts 1'`, "ruby", "puts 1"],
127 [`ruby -ne 'print if /foo/' input.txt`, "ruby", "print if /foo/"],
128 [`python3 -uc 'print(1)'`, "python", "print(1)"],
129 [`python3 -c'print(1)'`, "python", "print(1)"],
130 [`python3 -uc'print(1)'`, "python", "print(1)"],
131 [`python3 -uXdev -c'print(42)'`, "python", "print(42)"],
132 [`node -pe 'process.version'`, "javascript", "process.version"],
133 [`perl -E 'say 1'`, "perl", "say 1"],
134 [`perl -e'print 1'`, "perl", "print 1"],
135 [`perl -pe 's/foo/bar/' input.txt`, "perl", "s/foo/bar/"],
136 [`perl -0777e'print 1'`, "perl", "print 1"],
137 [`perl -l0123e 'print 42'`, "perl", "print 42"],
138 [`perl -0777ne 'print length' input.txt`, "perl", "print length"],
139 [`perl -I lib -Mstrict -pe 's/foo/bar/' input.txt`, "perl", "s/foo/bar/"],
140 [`perl -nwIlib -e'print 1'`, "perl", "print 1"],
141 [`perl -e'print 1;' file.txt -e 'print 2'`, "perl", "print 1;"],
142 [`ruby -ne'puts $_' input.txt`, "ruby", "puts $_"],
143 [`ruby -0777e'puts 42'`, "ruby", "puts 42"],
144 [`ruby -W0e'puts 42'`, "ruby", "puts 42"],
145 [`ruby -Kue'puts 42'`, "ruby", "puts 42"],
146 [`ruby -e'puts 1' -- -e'puts 2'`, "ruby", "puts 1"],
147 [`sqlite3 app.db "select * from users"`, "sql", "select * from users"],
148 [`pwsh -NoProfile -Command "Get-ChildItem"`, "powershell", "Get-ChildItem"],
149 [
150 `osascript -e 'tell application "Finder" to activate'`,
151 "applescript",
152 'tell application "Finder" to activate',
153 ],
154 [
155 `osascript -l JavaScript -e 'Application("Finder").activate()'`,
156 "javascript",
157 'Application("Finder").activate()',
158 ],
159 [
160 `osascript -lJavaScript <<'EOF'\nApplication("Finder").activate()\nEOF`,
161 "javascript",
162 'Application("Finder").activate()\n',
163 ],
164 [`osascript -l JavaScript -l AppleScript -e 'beep'`, "applescript", "beep"],
165 [`env FOO=1 sudo -u bob python3 -c 'print(1)'`, "python", "print(1)"],
166 [`env -- FOO=1 python3 -c 'print(1)'`, "python", "print(1)"],
167 [`timeout 30 python3 -c 'print(1)'`, "python", "print(1)"],
168 [`gtimeout 30 python3 -c 'print(1)'`, "python", "print(1)"],
169 [`timeout -k 5 30s node -e 'console.log(1)'`, "javascript", "console.log(1)"],
170 [`timeout -k5s -v -sKILL 10 bash -c 'echo hi'`, "shellscript", "echo hi"],
171 [`timeout --kill-after 5 --signal KILL 30 bash -c 'echo hi'`, "shellscript", "echo hi"],
172 [`timeout -fk 5 1.5m bash -c 'echo hi'`, "shellscript", "echo hi"],
173 [`timeout -s KILL -v -- 0 bash -c 'echo hi'`, "shellscript", "echo hi"],
174 [`timeout 30 env FOO=1 python3 -c 'print(1)'`, "python", "print(1)"],
175 [`node --eval="process.exit(0)"`, "javascript", "process.exit(0)"],
176 [`psql --command='select 1'`, "sql", "select 1"],
177 [`psql -c 'select 1' <<'EOF'\nselect 2;\nEOF`, "sql", "select 1"],
178 [`mysql -c -e 'select 1'`, "sql", "select 1"],
179 [`psql -Atc 'select 1'`, "sql", "select 1"],
180 [`mysql -Ne 'select 1'`, "sql", "select 1"],
181 [`psql app <<'EOF'\nselect 1;\nEOF`, "sql", "select 1;\n"],
182 [`echo "$(node -e 'console.log(1)')"`, "javascript", "console.log(1)"],
183 [`python3 <<< 'print(1)'`, "python", "print(1)"],
184 ])("finds the inline script in %s", (command, language, script) => {
185 expect(scriptsOf(command)).toEqual([[language, script, expect.any(String)]]);
186 });
187
188 it.each([
189 [
190 `perl -e'print 1;' -E 'say 2'`,
191 [
192 ["perl", "print 1;", "print 1;"],
193 ["perl", "say 2", "say 2"],
194 ],
195 ],
196 [
197 `ruby -e'puts 1' -e 'puts 2'`,
198 [
199 ["ruby", "puts 1", "puts 1"],
200 ["ruby", "puts 2", "puts 2"],
201 ],
202 ],
203 ])("finds repeated inline scripts in %s", (command, expected) => {
204 expect(scriptsOf(command)).toEqual(expected);
205 });
206
207 it.each([[`psql -c 'select 1' -c 'select 2'`], [`sqlite3 app.db "select 1" "select 2"`]])(
208 "finds every statement a SQL shell runs: %s",
209 (command) => {
210 expect(scriptsOf(command).map(([language, text]) => [language, text])).toEqual([
211 ["sql", "select 1"],
212 ["sql", "select 2"],
213 ]);
214 },
215 );
216
217 it.each([
218 [`psql -c 'select 1' -f - <<'EOF'\nselect 2;\nEOF`, ["select 1", "select 2;\n"]],
219 [`psql --command='select 1' -f - <<< 'select 2;'`, ["select 1", "select 2;"]],
220 ])("highlights both inline and stdin SQL in %s", (command, expected) => {
221 expect(scriptsOf(command).map(([language, text]) => [language, text])).toEqual(
222 expected.map((text) => ["sql", text]),
223 );
224 });
225
226 it.each([
227 ["the file `cat` writes", `cat > src/app.ts <<'EOF'\nconst a = 1;\nEOF`, "typescript"],
228 ["the file `tee` writes", `tee -a config.json <<EOF\n{}\nEOF`, "json"],
229 ["its delimiter", `kubectl apply -f - <<'YAML'\nkind: Pod\nYAML`, "yaml"],
230 ["the shell reading it", `bash <<'EOF'\necho hi\nEOF`, "shellscript"],
231 [
232 "a shell reading stdin with -s and operands",
233 `bash -euxs -- prod <<'EOF'\necho "$1"\nEOF`,
234 "shellscript",
235 ],
236 ["psql reading stdin with -f -", `psql -f - <<'EOF'\nselect 1;\nEOF`, "sql"],
237 ["psql reading stdin with --file=-", `psql --file=- <<'EOF'\nselect 1;\nEOF`, "sql"],
238 ["psql reading stdin with attached -f-", `psql -Atf- <<'EOF'\nselect 1;\nEOF`, "sql"],
239 ["psql mixing a file and -f -", `psql -f schema.sql -f - <<'EOF'\nselect 1;\nEOF`, "sql"],
240 ])("takes a heredoc's language from %s", (_source, command, language) => {
241 expect(scriptsOf(command).map(([lang]) => lang)).toEqual([language]);
242 });
243
244 it.each([
245 ["a script file", `python3 build.py <<EOF\ndata\nEOF`],
246 ["a module", `python3 -m json.tool <<EOF\n{}\nEOF`],
247 ["a SQL file", `psql -f migrate.sql <<EOF\ny\nEOF`],
248 ["a SQL file given with =", `psql --file=migrate.sql <<EOF\ny\nEOF`],
249 ["plain commands", `rg -n "foo" src && git status`],
250 ["an unnamed heredoc into a plain command", `git commit -F - <<'EOF'\nfix: x\nEOF`],
251 ["an empty script", `bash -lc ' '`],
252 ["a perl -i backup suffix of e", `perl -pie 's/foo/bar/' input.txt`],
253 ["a ruby -i backup suffix of e", `ruby -ie 'puts 1' input.txt`],
254 ["a python -W value of c", `python3 -Wc 'print(1)'`],
255 ["an attached python -W value starting with c", `python3 -Wc'print(1)'`],
256 ["a bundled python -X consuming the next arg", `python3 -uX -c'print(42)'`],
257 ["a bundled python -W consuming the next arg", `python3 -uW -c'print(42)'`],
258 ["an attached python -m module before -c", `python3 -mthis -c'print(42)'`],
259 ["a bundled python -m module before -c", `python3 -um this -c'print(42)'`],
260 ["an attached perl -M module starting with e", `perl -Me'print 1'`],
261 ["a bundled perl -I consuming the next arg", `perl -nwI -e'print 1'`],
262 ["an invalid perl octal switch without leading 0", `perl -7e'print 1'`],
263 ["an attached ruby -r require starting with e", `ruby -re'puts 1'`],
264 ["a ruby -K option consuming e as its encoding", `ruby -Ke 'puts 42'`],
265 ["a bundled ruby -I consuming the next arg", `ruby -wI -e'puts 42'`],
266 ["a ruby -W category before e", `ruby -W:deprecatede'puts 42'`],
267 ["a node -e flag with an attached value", `node -e'console.log(1)'`],
268 ["an attached inline flag after --", `python3 -- -c'print(1)'`],
269 [
270 "a whitespace-only attached inline script before a heredoc",
271 `python3 -c' ' <<'EOF'\nprint(2)\nEOF`,
272 ],
273 ["an empty attached python -c before a heredoc", `python3 -c'' <<'EOF'\nprint(2)\nEOF`],
274 ["an empty separate python -c before a heredoc", `python3 -c '' <<'EOF'\nprint(2)\nEOF`],
275 ["a bare python -c before a heredoc", `python3 -c <<'EOF'\nprint(2)\nEOF`],
276 ["a bare psql -c before a heredoc", `psql -c <<'EOF'\nselect 1;\nEOF`],
277 ["a psql -d database named c", `psql -dc 'select 1'`],
278 ["a bundled psql -f script file", `psql -Atf query.sql <<'EOF'\nselect 1;\nEOF`],
279 ["a bare psql -f before a heredoc", `psql -f <<'EOF'\nselect 1;\nEOF`],
280 ["a psql -f - followed by a bare -f before a heredoc", `psql -f - -f <<'EOF'\nselect 1;\nEOF`],
281 ["a duckdb -f - before a heredoc", `duckdb -f - <<'EOF'\nselect 1;\nEOF`],
282 ["a fish -C init command named c", `fish -Cc 'echo hi'`],
283 ["a shell whose -c has no script, before a heredoc", `sh -c -- <<'EOF'\necho hi\nEOF`],
284 [
285 "a shell whose -c has only trailing options before a heredoc",
286 `sh -c -e <<'EOF'\necho hi\nEOF`,
287 ],
288 [
289 "a shell whose -co option has no script after its option value",
290 `bash -co pipefail <<'EOF'\necho hi\nEOF`,
291 ],
292 [
293 "a shell with a GNU long option after -c",
294 `bash -c --rcfile /dev/null "python3 -c 'print(1)'"`,
295 ],
296 ["a shell with a GNU long option after -s", `bash -s --norc prod <<'EOF'\necho hi\nEOF`],
297 ["a zsh -o option name containing s", `zsh -oshwordsplit run.sh <<'EOF'\necho hi\nEOF`],
298 ["a shell clearing -s with +s", `dash -s +s run.sh <<'EOF'\necho hi\nEOF`],
299 ["a heredoc `cat` sends to stdout while stderr goes to a file", `cat 2>log.ts <<'EOF'\nx\nEOF`],
300 ])("finds nothing for %s", (_case, command) => {
301 expect(scriptsOf(command)).toEqual([]);
302 });
303
304 it("trusts nothing in a command whose quoting does not parse", () => {
305 // Secret redaction removed an escaped quote's backslash, breaking the -lc argument.
306 const command = `/bin/zsh -lc "python3 -c 'token=[REDACTED_SECRET]"apiToken\\"]; print(token)'"`;
307 expect(scriptsOf(command)).toEqual([]);
308 });
309});
310
311describe("withEmbeddedScripts", () => {
312 function tokenize(text: string, language: string) {
313 if (language === "unknown") throw new Error("Language not found");
314 let lineStart = 0;
315 return text.split(/\r?\n/u).map((line) => {
316 const tokens = [...line.matchAll(/\S+|\s+/gu)].map((match) => ({
317 content: match[0],
318 offset: lineStart + match.index,
319 color: language,
320 }));
321 lineStart +=
322 line.length + (text.slice(lineStart + line.length).match(/^\r?\n/u)?.[0].length ?? 0);
323 return tokens;
324 });
325 }
326
327 function colorsOf(code: string, scripts = embeddedScripts(code)) {
328 const lines = withEmbeddedScripts(code, tokenize(code, "shellscript"), scripts, tokenize);
329 expect(lines.map((line) => line.map((token) => token.content).join("")).join("\n")).toBe(
330 code.replaceAll("\r\n", "\n"),
331 );
332 return lines.flat().map((token) => [token.content, token.color]);
333 }
334
335 it("colors each nested script with its own grammar, keeping the text", () => {
336 expect(colorsOf(`bash -lc "python3 -c 'print(1)'"`)).toEqual([
337 [`bash -lc "python3 -c '`, "shellscript"],
338 ["print(1)", "python"],
339 [`'"`, "shellscript"],
340 ]);
341 });
342
343 it("colors an escape sequence like the character it spells", () => {
344 expect(colorsOf(`bash -c "python3 -c 'print(\\"x\\")'"`)).toContainEqual([
345 `print(\\"x\\")`,
346 "python",
347 ]);
348 });
349
350 it("keeps the surrounding colors where a grammar is missing", () => {
351 const code = "cat > x.ts <<'EOF'\r\nbody\r\nEOF";
352 const [script] = embeddedScripts(code);
353 const characterColors = (scripts: ReturnType<typeof embeddedScripts>) =>
354 colorsOf(code, scripts).flatMap(([content, color]) => [...content!].map(() => color));
355 expect(characterColors([{ ...script!, language: "unknown" }])).toEqual(characterColors([]));
356 });
357});