import { accessSync, constants, statSync } from "node:fs"; import { createRequire } from "node:module"; import { homedir } from "node:os"; import { basename, delimiter, resolve } from "node:path"; import { Language, Parser, type Node as SyntaxNode } from "web-tree-sitter"; const WRAPPERS = new Set([ ".", "alias", "arch", "bash", "builtin", "caffeinate", "command", "dash", "declare", "doas", "env", "eval", "exec", "export", "fd", "find", "flock", "ksh", "local", "nice", "nohup", "parallel", "readonly", "rush", "rust-parallel", "set", "setsid", "sh", "shopt", "source", "stdbuf", "sudo", "time", "timeout", "typeset", "unalias", "unset", "watch", "xargs", "zsh", ]); let parserPromise: Promise | undefined; export interface BashCommandAnalysis { /** Names of all commands in the tree, and the words that a wrapper can run. */ mentionedNames: string[]; /** Text of each mentioned command, from its name to the end of its arguments. */ mentionedTexts: string[]; /** Text after each mentioned name, to the end of its arguments. */ mentionedArguments: string[]; } export interface ResolvedHostCommand { executable: string; /** Patterns for the arguments that run on the host. */ patterns: string[]; } export type ResolvedHostCommands = ReadonlyMap; // `*` matches any text. A trailing ` *` also matches the command with no arguments. export function matchesCommandPattern(pattern: string, text: string): boolean { const optionalArguments = pattern.endsWith(" *"); const parts = (optionalArguments ? pattern.slice(0, -2) : pattern) .split("*") .map((part) => RegExp.escape(part)); const suffix = optionalArguments ? "(\\s[\\s\\S]*)?" : ""; return new RegExp(`^${parts.join("[\\s\\S]*")}${suffix}$`).test(text); } /** The first executable file named `name` in `path`. */ export function findExecutable(name: string, cwd: string, path: string): string | undefined { return path .split(delimiter) .map((directory) => resolve(cwd, directory, name)) .find((candidate) => { try { accessSync(candidate, constants.X_OK); return statSync(candidate).isFile(); } catch { return false; } }); } /** * Resolve configured host commands from PATH. An entry is a command name, followed by a * pattern for the arguments that run on the host. An entry without an argument pattern * matches the command with no arguments. */ export function resolveHostCommands( hostCommands: readonly string[], cwd: string, path: string, ): ResolvedHostCommands { const resolved = new Map(); for (const entry of hostCommands) { const [, name, pattern] = /^(\S+)\s*([\s\S]*)$/.exec(entry.trim()) ?? []; if (!name || name.includes("*") || name.includes("/")) { throw new Error(`Host command ${JSON.stringify(entry)} must start with a command name`); } const executable = findExecutable(name, cwd, path); // Shared configs can list tools that are not installed on every machine. if (!executable) { continue; } resolved.set(name, { executable, patterns: [...(resolved.get(name)?.patterns ?? []), pattern], }); } return resolved; } export function normalizedShellLiteral(value: string): string { return value.replace(/\\([\s\S])/g, "$1").replace(/["']/g, ""); } export function resolveCommandCwd(baseCwd: string, dir?: string | null): string { return resolve(baseCwd, dir ?? "."); } const CD_PREFIX = /^\s*cd\s+((?:[^\s\\;&|<>()'"`$*?[\]{}]|\\.)+|'[^']*'|"(?:[^"\\`$]|\\.)*")\s*(?:&&|;)\s*/; /** Split a leading `cd ` from a command. */ export function splitCdPrefix(command: string): { dir: string; rest: string } | undefined { const match = CD_PREFIX.exec(command); return match ? { dir: normalizedShellLiteral(match[1]!).replace(/^~(?=\/|$)/, homedir()), rest: command.slice(match[0].length), } : undefined; } async function createParser(): Promise { const require = createRequire(import.meta.url); await Parser.init({ locateFile: () => require.resolve("web-tree-sitter/web-tree-sitter.wasm"), }); const parser = new Parser(); parser.setLanguage( await Language.load(require.resolve("tree-sitter-bash/tree-sitter-bash.wasm")), ); return parser; } async function getParser(): Promise { parserPromise ??= createParser(); try { return await parserPromise; } catch (error) { parserPromise = undefined; throw error; } } function commandName(node: SyntaxNode): string | undefined { const value = node.childForFieldName("name")?.namedChild(0); if (!value) { return undefined; } if (value.type === "word" && value.namedChildCount === 0) { return value.text; } if (value.type === "raw_string") { return value.text.slice(1, -1); } if ( value.type === "string" && value.namedChildren.every((child) => child.type === "string_content") ) { return value.namedChildren.map((child) => child.text).join(""); } return undefined; } function mentionedCommands(root: SyntaxNode, command: string): BashCommandAnalysis { const mentionedNames: string[] = []; const mentionedTexts: string[] = []; const mentionedArguments: string[] = []; for (const node of root.descendantsOfType("command")) { const name = commandName(node); if (!name) { continue; } const nameNode = node.childForFieldName("name")!; mentionedNames.push(name); mentionedTexts.push(command.slice(nameNode.startIndex, node.endIndex)); mentionedArguments.push(command.slice(nameNode.endIndex, node.endIndex).trim()); // Which argument a wrapper runs depends on its options, so every plain word counts. if (WRAPPERS.has(basename(name))) { for (const argument of node.childrenForFieldName("argument")) { if (argument.type === "word" && argument.namedChildCount === 0) { mentionedNames.push(argument.text); mentionedTexts.push(command.slice(argument.startIndex, node.endIndex)); mentionedArguments.push(command.slice(argument.endIndex, node.endIndex).trim()); } } } } return { mentionedNames, mentionedTexts, mentionedArguments }; } export async function parseBashCommand(command: string): Promise { try { const tree = (await getParser()).parse(command); if (!tree) { return undefined; } try { if (tree.rootNode.hasError) { return undefined; } return mentionedCommands(tree.rootNode, command); } finally { tree.delete(); } } catch { return undefined; } }