Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

embeddedScripts.test.ts

398 lines18.7 KB

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