Open History to see the last commit
1import { getFiletypeFromFileName } from "@pierre/diffs";
2import {
3 parse,
4 type Command,
5 type DoubleQuotedChild,
6 type HereDoc,
7 type Word,
8 type WordPart,
9} from "unbash";
10
11/**
12 * `starts[i]` and `ends[i]` are the span of the original command that spells
13 * `text[i]`, so a quoted `\"` maps back to both of its characters.
14 */
15export interface EmbeddedScript {
16 readonly language: string;
17 readonly text: string;
18 readonly starts: ReadonlyArray<number>;
19 readonly ends: ReadonlyArray<number>;
20}
21
22interface MappedText {
23 readonly text: string;
24 readonly starts: ReadonlyArray<number>;
25 readonly ends: ReadonlyArray<number>;
26}
27
28interface Interpreter {
29 readonly language: string;
30 readonly inline: (flag: string) => boolean;
31 readonly valueOptions?: ReadonlySet<string>;
32 readonly scriptFileOptions?: ReadonlySet<string>;
33 readonly stdin: "always" | "without-script-file" | "never";
34 readonly positionalScript?: number;
35 readonly repeatable?: boolean;
36 readonly subcommand?: string;
37 /** PowerShell matches parameters case-insensitively; the lists above are lowercase. */
38 readonly ignoreCase?: boolean;
39}
40
41const MAX_DEPTH = 4;
42
43const flagIn =
44 (...flags: string[]) =>
45 (flag: string) =>
46 flags.includes(flag);
47
48const SHELL: Interpreter = {
49 language: "shellscript",
50 inline: (flag) => /^-[a-z]*c[a-z]*$/u.test(flag),
51 valueOptions: new Set(["-o", "-O", "--rcfile", "--init-file"]),
52 stdin: "without-script-file",
53};
54
55const PYTHON: Interpreter = {
56 language: "python",
57 inline: flagIn("-c"),
58 valueOptions: new Set(["-W", "-X"]),
59 scriptFileOptions: new Set(["-m"]),
60 stdin: "without-script-file",
61};
62
63const SQL_SHELL = {
64 language: "sql",
65 valueOptions: new Set([
66 "-d",
67 "-h",
68 "-u",
69 "-U",
70 "--dbname",
71 "--host",
72 "--user",
73 "--username",
74 "-separator",
75 "-nullvalue",
76 "-init",
77 ]),
78 stdin: "always",
79 repeatable: true,
80} satisfies Omit<Interpreter, "inline">;
81
82const INTERPRETERS: Record<string, Interpreter> = {
83 sh: SHELL,
84 bash: SHELL,
85 zsh: SHELL,
86 dash: SHELL,
87 ash: SHELL,
88 ksh: SHELL,
89 fish: { language: "fish", inline: flagIn("-c", "--command"), stdin: "without-script-file" },
90 node: {
91 language: "javascript",
92 inline: flagIn("-e", "--eval", "-p", "--print"),
93 valueOptions: new Set(["-r", "--require", "--import", "--loader", "-C", "--conditions"]),
94 stdin: "without-script-file",
95 },
96 bun: { language: "typescript", inline: flagIn("-e", "--eval", "-p", "--print"), stdin: "never" },
97 deno: {
98 language: "typescript",
99 inline: () => false,
100 // `--env-file` takes its optional path only as `--env-file=path`.
101 valueOptions: new Set(["-c", "--config", "--import-map", "--ext"]),
102 stdin: "never",
103 subcommand: "eval",
104 },
105 ruby: {
106 language: "ruby",
107 inline: flagIn("-e"),
108 valueOptions: new Set(["-r", "-I", "-C"]),
109 stdin: "without-script-file",
110 },
111 perl: { language: "perl", inline: flagIn("-e", "-E"), stdin: "without-script-file" },
112 osascript: {
113 language: "applescript",
114 inline: flagIn("-e"),
115 valueOptions: new Set(["-l", "-s"]),
116 stdin: "without-script-file",
117 },
118 pwsh: {
119 language: "powershell",
120 inline: flagIn("-c", "-command"),
121 valueOptions: new Set(["-executionpolicy", "-workingdirectory", "-windowstyle"]),
122 scriptFileOptions: new Set(["-f", "-file", "-encodedcommand"]),
123 stdin: "never",
124 ignoreCase: true,
125 },
126 psql: {
127 ...SQL_SHELL,
128 inline: flagIn("-c", "--command"),
129 scriptFileOptions: new Set(["-f", "--file"]),
130 },
131 mysql: { ...SQL_SHELL, inline: flagIn("-e", "--execute") },
132 sqlite3: { ...SQL_SHELL, inline: flagIn("-cmd"), positionalScript: 1 },
133 duckdb: {
134 ...SQL_SHELL,
135 inline: flagIn("-c", "-cmd"),
136 scriptFileOptions: new Set(["-f"]),
137 positionalScript: 1,
138 },
139};
140INTERPRETERS.powershell = INTERPRETERS.pwsh!;
141INTERPRETERS.mariadb = INTERPRETERS.mysql!;
142
143const PROGRAM_WRAPPERS: Record<string, ReadonlySet<string>> = {
144 env: new Set(["-u", "--unset", "-C", "--chdir"]),
145 sudo: new Set(["-u", "--user", "-g", "--group", "-C", "-D", "--chdir"]),
146 nice: new Set(["-n", "--adjustment"]),
147 nohup: new Set(),
148 exec: new Set(["-a"]),
149 command: new Set(),
150 builtin: new Set(),
151};
152
153const DELIMITER_LANGUAGES: Record<string, string> = {
154 py: "python",
155 python: "python",
156 js: "javascript",
157 javascript: "javascript",
158 ts: "typescript",
159 typescript: "typescript",
160 sql: "sql",
161 json: "json",
162 yaml: "yaml",
163 yml: "yaml",
164 toml: "toml",
165 sh: "shellscript",
166 bash: "shellscript",
167 shell: "shellscript",
168 rb: "ruby",
169 ruby: "ruby",
170 html: "html",
171 css: "css",
172 md: "markdown",
173 markdown: "markdown",
174 xml: "xml",
175 diff: "diff",
176 patch: "diff",
177};
178
179/**
180 * Returns nothing for a command that does not parse cleanly; where a broken
181 * quote ends cannot be trusted.
182 */
183export function embeddedScripts(command: string): EmbeddedScript[] {
184 const identity = Array.from({ length: command.length }, (_, index) => index);
185 return scriptsIn(
186 { text: command, starts: identity, ends: identity.map((index) => index + 1) },
187 0,
188 );
189}
190
191function scriptsIn(source: MappedText, depth: number): EmbeddedScript[] {
192 const script = parse(source.text);
193 if (script.errors?.length) return [];
194 const found: EmbeddedScript[] = [];
195 forEachCommand(script.commands, (command) => {
196 for (const { language, mapped } of commandScripts(command, source.text)) {
197 if (mapped.text.trim() === "") continue;
198 const embedded: EmbeddedScript = {
199 language,
200 text: mapped.text,
201 starts: mapped.starts.map((start) => source.starts[start]!),
202 ends: mapped.ends.map((end) => source.ends[end - 1]!),
203 };
204 found.push(embedded);
205 if (language === "shellscript" && depth + 1 < MAX_DEPTH) {
206 found.push(...scriptsIn(embedded, depth + 1));
207 }
208 }
209 });
210 return found;
211}
212
213function isNode(value: unknown): value is { readonly type: string } {
214 return typeof value === "object" && value !== null && "type" in value;
215}
216
217function forEachCommand(
218 node: unknown,
219 visit: (command: Command) => void,
220 seen = new WeakSet<object>(),
221): void {
222 if (Array.isArray(node)) {
223 for (const child of node) forEachCommand(child, visit, seen);
224 return;
225 }
226 if (!isNode(node) || seen.has(node)) return;
227 seen.add(node);
228 switch (node.type) {
229 case "Command":
230 visit(node as Command);
231 break;
232 case "CommandExpansion":
233 case "ProcessSubstitution": {
234 const { script } = node as Extract<WordPart, { type: "CommandExpansion" }>;
235 if (script && !script.errors?.length && script.source === undefined) {
236 forEachCommand(script.commands, visit, seen);
237 }
238 return;
239 }
240 }
241 // Word parts are lazy getters, which Object.values skips.
242 if ("parts" in node) forEachCommand(node.parts, visit, seen);
243 for (const value of Object.values(node)) {
244 if (typeof value === "object") forEachCommand(value, visit, seen);
245 }
246}
247
248function programName(word: Word): string {
249 // Bash reads `C:\Python312\python.exe` unquoted as escapes; Windows meant a path.
250 const path = /\\/u.test(word.text) ? word.text.replace(/^["']|["']$/gu, "") : word.value;
251 return (path.split(/[\\/]/u).at(-1) ?? "").toLowerCase().replace(/\.exe$/u, "");
252}
253
254function interpreterFor(name: string): Interpreter | undefined {
255 if (/^python(?:\d+(?:\.\d+)?)?$|^pypy3?$|^py$/u.test(name)) return PYTHON;
256 return Object.hasOwn(INTERPRETERS, name) ? INTERPRETERS[name] : undefined;
257}
258
259function programIndex(words: ReadonlyArray<Word>): number {
260 let index = 0;
261 while (index < words.length) {
262 const name = programName(words[index]!);
263 if (!Object.hasOwn(PROGRAM_WRAPPERS, name)) return index;
264 const valueOptions = PROGRAM_WRAPPERS[name]!;
265 index += 1;
266 let optionsEnded = false;
267 while (index < words.length) {
268 const value = words[index]!.value;
269 const isOption = !optionsEnded && value.startsWith("-");
270 if (isOption && value === "--") optionsEnded = true;
271 // `env -- FOO=1 cmd` still takes assignments after the options end.
272 if (isOption || /^[A-Za-z_]\w*=/u.test(value)) {
273 index += isOption && valueOptions.has(value) ? 2 : 1;
274 } else {
275 break;
276 }
277 }
278 }
279 return index;
280}
281
282function commandScripts(
283 command: Command,
284 source: string,
285): Array<{ language: string; mapped: MappedText }> {
286 if (!command.name) return [];
287 const words = [command.name, ...command.args.filter((arg): arg is Word => arg.type === "Word")];
288 const index = programIndex(words);
289 const program = words[index];
290 if (!program) return [];
291 const name = programName(program);
292 const interpreter = interpreterFor(name);
293 const args = words.slice(index + 1);
294 const scripts: Array<{ language: string; mapped: MappedText }> = [];
295
296 let readsStdinScript = false;
297 if (interpreter) {
298 const found = interpreterArgs(interpreter, args);
299 for (const script of found.scripts) {
300 const mapped = wordText(script.word, source);
301 if (!mapped) continue;
302 const start = script.inValue ? mapped.text.indexOf("=") + 1 : 0;
303 scripts.push({ language: interpreter.language, mapped: sliceMapped(mapped, start) });
304 }
305 readsStdinScript =
306 interpreter.stdin !== "never" && found.scripts.length === 0 && !found.scriptFromFile;
307 }
308
309 const stdinLanguage = readsStdinScript ? interpreter?.language : undefined;
310 const writtenLanguage = writtenFileLanguage(name, command, args);
311 for (const redirect of command.redirects) {
312 const toStdin = isDescriptor(redirect.descriptor, 0);
313 if (redirect.type === "HereString" && toStdin && stdinLanguage && redirect.target) {
314 const mapped = wordText(redirect.target, source);
315 if (mapped) scripts.push({ language: stdinLanguage, mapped });
316 }
317 if (redirect.type === "HereDoc") {
318 const language =
319 (toStdin ? (stdinLanguage ?? writtenLanguage) : undefined) ?? delimiterLanguage(redirect);
320 if (language) scripts.push({ language, mapped: hereDocText(redirect, source) });
321 }
322 }
323 return scripts;
324}
325
326function isDescriptor(descriptor: HereDoc["descriptor"], fd: number): boolean {
327 return (
328 descriptor === undefined || (descriptor.type === "FileDescriptor" && descriptor.value === fd)
329 );
330}
331
332interface ScriptArgument {
333 readonly word: Word;
334 readonly inValue: boolean;
335}
336
337function interpreterArgs(
338 interpreter: Interpreter,
339 args: ReadonlyArray<Word>,
340): { scripts: ScriptArgument[]; scriptFromFile: boolean } {
341 const positionals: Word[] = [];
342 const scripts: ScriptArgument[] = [];
343 const whole = (word: Word): ScriptArgument => ({ word, inValue: false });
344 let optionsEnded = false;
345 let scriptFromFile = false;
346 for (let index = 0; index < args.length; index += 1) {
347 const arg = args[index]!;
348 const flag = interpreter.ignoreCase ? arg.value.toLowerCase() : arg.value;
349 if (!optionsEnded && flag === "--") {
350 optionsEnded = true;
351 continue;
352 }
353 if (!optionsEnded && flag.startsWith("-") && flag !== "-") {
354 const [name = flag, value] = flag.startsWith("--") ? flag.split(/=(.*)/su) : [flag];
355 if (interpreter.scriptFileOptions?.has(name)) {
356 if (!interpreter.repeatable) return { scripts, scriptFromFile: true };
357 // SQL shells run `-f` files and `-c` statements alike, in order.
358 scriptFromFile = true;
359 if (value === undefined) index += 1;
360 continue;
361 }
362 if (interpreter.inline(name)) {
363 const next = args[index + 1];
364 if (value !== undefined) scripts.push({ word: arg, inValue: true });
365 else if (next) scripts.push(whole(next));
366 if (!interpreter.repeatable) return { scripts, scriptFromFile: false };
367 if (value === undefined) index += 1;
368 continue;
369 }
370 if (value === undefined && interpreter.valueOptions?.has(flag)) index += 1;
371 continue;
372 }
373 positionals.push(arg);
374 if (interpreter.stdin === "without-script-file" && !interpreter.subcommand) break;
375 }
376
377 if (interpreter.subcommand) {
378 if (positionals[0]?.value !== interpreter.subcommand) return { scripts, scriptFromFile: true };
379 return { scripts: positionals.slice(1, 2).map(whole), scriptFromFile: false };
380 }
381 if (interpreter.positionalScript !== undefined) {
382 scripts.push(...positionals.slice(interpreter.positionalScript).map(whole));
383 }
384 // SQL shells take databases as positional arguments, not script files.
385 if (interpreter.stdin === "always") return { scripts, scriptFromFile };
386 const first = positionals[0];
387 return { scripts, scriptFromFile: first !== undefined && first.value !== "-" };
388}
389
390function sliceMapped(mapped: MappedText, start: number): MappedText {
391 if (start === 0) return mapped;
392 return {
393 text: mapped.text.slice(start),
394 starts: mapped.starts.slice(start),
395 ends: mapped.ends.slice(start),
396 };
397}
398
399function writtenFileLanguage(
400 name: string,
401 command: Command,
402 args: ReadonlyArray<Word>,
403): string | undefined {
404 let path: string | undefined;
405 if (name === "cat") {
406 for (const redirect of command.redirects) {
407 if (
408 redirect.type === "Redirect" &&
409 [">", ">>", ">|", "&>", "&>>"].includes(redirect.operator) &&
410 isDescriptor(redirect.descriptor, 1)
411 ) {
412 path = redirect.target?.value;
413 }
414 }
415 } else if (name === "tee") {
416 path = args.find((arg) => !arg.value.startsWith("-"))?.value;
417 }
418 if (!path) return undefined;
419 const language = getFiletypeFromFileName(path);
420 return language === "text" ? undefined : language;
421}
422
423function delimiterLanguage(hereDoc: HereDoc): string | undefined {
424 const name = hereDoc.delimiter?.value.toLowerCase();
425 return name && Object.hasOwn(DELIMITER_LANGUAGES, name) ? DELIMITER_LANGUAGES[name] : undefined;
426}
427
428function hereDocText(hereDoc: HereDoc, source: string): MappedText {
429 const { pos, end } = hereDoc.body;
430 const starts = Array.from({ length: end - pos }, (_, index) => pos + index);
431 return {
432 text: source.slice(pos, end),
433 starts,
434 ends: starts.map((start) => start + 1),
435 };
436}
437
438/**
439 * Expansions such as `$HOME` stay as written. Returns undefined for spellings
440 * it cannot map.
441 */
442function wordText(word: Word, source: string): MappedText | undefined {
443 const builder = new MappedTextBuilder();
444 const parts: ReadonlyArray<WordPart> = word.parts ?? [
445 { type: "Literal", pos: word.pos, end: word.end, text: word.text, value: word.value },
446 ];
447 for (const part of parts) {
448 switch (part.type) {
449 case "Literal":
450 if (!builder.addEscaped(part, false)) return undefined;
451 break;
452 case "SingleQuoted":
453 builder.addRaw(part.value, part.pos + 1);
454 break;
455 case "DoubleQuoted":
456 case "LocaleString":
457 for (const child of part.parts) {
458 if (!builder.addDoubleQuotedChild(child)) return undefined;
459 }
460 break;
461 case "AnsiCQuoted":
462 // $'…' escapes such as \x41 do not map character for character.
463 if (part.value !== part.text.slice(2, -1)) return undefined;
464 builder.addRaw(part.value, part.pos + 2);
465 break;
466 default:
467 builder.addRaw(source.slice(part.pos, part.end), part.pos);
468 }
469 }
470 return builder.build();
471}
472
473class MappedTextBuilder {
474 private text = "";
475 private readonly starts: number[] = [];
476 private readonly ends: number[] = [];
477
478 addRaw(text: string, pos: number) {
479 for (let index = 0; index < text.length; index += 1) this.push(text[index]!, pos + index, 1);
480 }
481
482 addDoubleQuotedChild(child: DoubleQuotedChild): boolean {
483 if (child.type === "Literal") return this.addEscaped(child, true);
484 this.addRaw(child.text, child.pos);
485 return true;
486 }
487
488 addEscaped(literal: { pos: number; text: string; value: string }, doubleQuoted: boolean) {
489 const before = this.text.length;
490 const { text, pos } = literal;
491 for (let index = 0; index < text.length; index += 1) {
492 const next = text[index + 1];
493 if (
494 text[index] === "\\" &&
495 next !== undefined &&
496 (!doubleQuoted || '$`"\\\n'.includes(next))
497 ) {
498 // A backslash-newline joins lines and spells nothing.
499 if (next !== "\n") this.push(next, pos + index, 2);
500 index += 1;
501 } else {
502 this.push(text[index]!, pos + index, 1);
503 }
504 }
505 return this.text.slice(before) === literal.value;
506 }
507
508 build(): MappedText {
509 return { text: this.text, starts: this.starts, ends: this.ends };
510 }
511
512 private push(character: string, start: number, length: number) {
513 this.text += character;
514 this.starts.push(start);
515 this.ends.push(start + length);
516 }
517}