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