42 lines
1.2 KiB
TypeScript
42 lines
1.2 KiB
TypeScript
const PLAIN = /^[\w@%+=:,./-]+$/;
|
|
|
|
/** Renders argv as one shell-quoted line. */
|
|
export function joinArgv(argv: string[]): string {
|
|
return argv.map((arg) => (PLAIN.test(arg) ? arg : `'${arg.replaceAll("'", `'\\''`)}'`)).join(" ");
|
|
}
|
|
|
|
/** Splits a shell-quoted line back into argv: whitespace separates, single
|
|
* quotes are literal, double quotes and backslashes escape. Nothing runs it
|
|
* through a shell; the result is stored as the argument list. */
|
|
export function splitArgv(line: string): string[] {
|
|
const out: string[] = [];
|
|
let arg = "";
|
|
let started = false;
|
|
let quote: "'" | '"' | "" = "";
|
|
for (let i = 0; i < line.length; i++) {
|
|
const c = line[i];
|
|
if (quote === "'") {
|
|
if (c === "'") quote = "";
|
|
else arg += c;
|
|
} else if (c === "\\" && i + 1 < line.length && (quote === "" || '"\\$`'.includes(line[i + 1]))) {
|
|
arg += line[++i];
|
|
started = true;
|
|
} else if (quote === '"') {
|
|
if (c === '"') quote = "";
|
|
else arg += c;
|
|
} else if (c === "'" || c === '"') {
|
|
quote = c;
|
|
started = true;
|
|
} else if (/\s/.test(c)) {
|
|
if (started) out.push(arg);
|
|
arg = "";
|
|
started = false;
|
|
} else {
|
|
arg += c;
|
|
started = true;
|
|
}
|
|
}
|
|
if (started) out.push(arg);
|
|
return out;
|
|
}
|