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("highlights a heredoc fed to an interpreter in that interpreter's language", () => {
46 const command = `python3 - <<'PY'\n${pythonScript}PY`;
47 expect(scriptsOf(command)).toEqual([["python", pythonScript, pythonScript]]);
48 });
49
50 it("maps escaped characters back to both source characters", () => {
51 const command = `/bin/zsh -lc "python3 - <<'PY'\nprint(\\"\\$HOME\\")\nPY"`;
52 const [shell, python] = scriptsOf(command);
53 expect(shell?.[1]).toBe(`python3 - <<'PY'\nprint("$HOME")\nPY`);
54 expect(python).toEqual(["python", `print("$HOME")\n`, `print(\\"\\$HOME\\")\n`]);
55 });
56
57 it.each([
58 [`bash -Ec 'echo hi'`, "shellscript", "echo hi"],
59 [`python3 -c 'print(1)'`, "python", "print(1)"],
60 [`py -3 -c 'print(1)'`, "python", "print(1)"],
61 [`"C:\\Program Files\\Python312\\python.exe" -c 'print(1)'`, "python", "print(1)"],
62 [`node --eval "process.exit(0)"`, "javascript", "process.exit(0)"],
63 [`bun -e 'console.log(Bun.version)'`, "typescript", "console.log(Bun.version)"],
64 [`deno eval 'console.log(1)'`, "typescript", "console.log(1)"],
65 [`deno eval --config deno.json 'console.log(1)'`, "typescript", "console.log(1)"],
66 [`psql -f schema.sql -c 'select 1'`, "sql", "select 1"],
67 [`node -C development -e 'console.log(1)'`, "javascript", "console.log(1)"],
68 [`ruby -e 'puts 1'`, "ruby", "puts 1"],
69 [`ruby -I lib -e 'puts 1'`, "ruby", "puts 1"],
70 [`perl -E 'say 1'`, "perl", "say 1"],
71 [`sqlite3 app.db "select * from users"`, "sql", "select * from users"],
72 [`pwsh -NoProfile -Command "Get-ChildItem"`, "powershell", "Get-ChildItem"],
73 [`env FOO=1 sudo -u bob python3 -c 'print(1)'`, "python", "print(1)"],
74 [`env -- FOO=1 python3 -c 'print(1)'`, "python", "print(1)"],
75 [`node --eval="process.exit(0)"`, "javascript", "process.exit(0)"],
76 [`psql --command='select 1'`, "sql", "select 1"],
77 [`mysql -c -e 'select 1'`, "sql", "select 1"],
78 [`psql app <<'EOF'\nselect 1;\nEOF`, "sql", "select 1;\n"],
79 [`echo "$(node -e 'console.log(1)')"`, "javascript", "console.log(1)"],
80 [`python3 <<< 'print(1)'`, "python", "print(1)"],
81 ])("finds the inline script in %s", (command, language, script) => {
82 expect(scriptsOf(command)).toEqual([[language, script, expect.any(String)]]);
83 });
84
85 it.each([[`psql -c 'select 1' -c 'select 2'`], [`sqlite3 app.db "select 1" "select 2"`]])(
86 "finds every statement a SQL shell runs: %s",
87 (command) => {
88 expect(scriptsOf(command).map(([language, text]) => [language, text])).toEqual([
89 ["sql", "select 1"],
90 ["sql", "select 2"],
91 ]);
92 },
93 );
94
95 it.each([
96 ["the file `cat` writes", `cat > src/app.ts <<'EOF'\nconst a = 1;\nEOF`, "typescript"],
97 ["the file `tee` writes", `tee -a config.json <<EOF\n{}\nEOF`, "json"],
98 ["its delimiter", `kubectl apply -f - <<'YAML'\nkind: Pod\nYAML`, "yaml"],
99 ["the shell reading it", `bash <<'EOF'\necho hi\nEOF`, "shellscript"],
100 ])("takes a heredoc's language from %s", (_source, command, language) => {
101 expect(scriptsOf(command).map(([lang]) => lang)).toEqual([language]);
102 });
103
104 it.each([
105 ["a script file", `python3 build.py <<EOF\ndata\nEOF`],
106 ["a module", `python3 -m json.tool <<EOF\n{}\nEOF`],
107 ["a SQL file", `psql -f migrate.sql <<EOF\ny\nEOF`],
108 ["a SQL file given with =", `psql --file=migrate.sql <<EOF\ny\nEOF`],
109 ["plain commands", `rg -n "foo" src && git status`],
110 ["an unnamed heredoc into a plain command", `git commit -F - <<'EOF'\nfix: x\nEOF`],
111 ["an empty script", `bash -lc ' '`],
112 ["a shell whose -c has no script, before a heredoc", `sh -c -- <<'EOF'\necho hi\nEOF`],
113 ["a heredoc `cat` sends to stdout while stderr goes to a file", `cat 2>log.ts <<'EOF'\nx\nEOF`],
114 ])("finds nothing for %s", (_case, command) => {
115 expect(scriptsOf(command)).toEqual([]);
116 });
117
118 it("trusts nothing in a command whose quoting does not parse", () => {
119 // Secret redaction removed an escaped quote's backslash, breaking the -lc argument.
120 const command = `/bin/zsh -lc "python3 -c 'token=[REDACTED_SECRET]"apiToken\\"]; print(token)'"`;
121 expect(scriptsOf(command)).toEqual([]);
122 });
123});
124
125describe("withEmbeddedScripts", () => {
126 function tokenize(text: string, language: string) {
127 if (language === "unknown") throw new Error("Language not found");
128 let lineStart = 0;
129 return text.split(/\r?\n/u).map((line) => {
130 const tokens = [...line.matchAll(/\S+|\s+/gu)].map((match) => ({
131 content: match[0],
132 offset: lineStart + match.index,
133 color: language,
134 }));
135 lineStart +=
136 line.length + (text.slice(lineStart + line.length).match(/^\r?\n/u)?.[0].length ?? 0);
137 return tokens;
138 });
139 }
140
141 function colorsOf(code: string, scripts = embeddedScripts(code)) {
142 const lines = withEmbeddedScripts(code, tokenize(code, "shellscript"), scripts, tokenize);
143 expect(lines.map((line) => line.map((token) => token.content).join("")).join("\n")).toBe(
144 code.replaceAll("\r\n", "\n"),
145 );
146 return lines.flat().map((token) => [token.content, token.color]);
147 }
148
149 it("colors each nested script with its own grammar, keeping the text", () => {
150 expect(colorsOf(`bash -lc "python3 -c 'print(1)'"`)).toEqual([
151 [`bash -lc "python3 -c '`, "shellscript"],
152 ["print(1)", "python"],
153 [`'"`, "shellscript"],
154 ]);
155 });
156
157 it("colors an escape sequence like the character it spells", () => {
158 expect(colorsOf(`bash -c "python3 -c 'print(\\"x\\")'"`)).toContainEqual([
159 `print(\\"x\\")`,
160 "python",
161 ]);
162 });
163
164 it("keeps the surrounding colors where a grammar is missing", () => {
165 const code = "cat > x.ts <<'EOF'\r\nbody\r\nEOF";
166 const [script] = embeddedScripts(code);
167 const characterColors = (scripts: ReturnType<typeof embeddedScripts>) =>
168 colorsOf(code, scripts).flatMap(([content, color]) => [...content!].map(() => color));
169 expect(characterColors([{ ...script!, language: "unknown" }])).toEqual(characterColors([]));
170 });
171});