mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-18 07:50:13 +00:00
fix(cli): printed Windows commands read folder names literally in every shell (#7769)
* fix(cli): printed Windows commands read folder names literally in PowerShell, cmd and Git Bash shellArg's Windows branch wrapped any non-plain name in double quotes, where PowerShell and Git Bash still expand $ and backticks. Names with those characters (or PowerShell's curly quotes) are now single-quoted, which both shells read literally; a name that cmd.exe would also split on & | < > ^ gets no printed path, and the hint says to run the command from the project folder. A bare comma or leading @ is quoted so PowerShell does not read an array or a splat. Ordinary names with spaces, accents and apostrophes print as before. The background preview's stop footer uses the same helper instead of JSON quoting, which left $(...) live in POSIX shells and PowerShell. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): printed Windows paths with backslashes keep them in Git Bash A Windows word containing a backslash printed bare, and Git Bash strips unquoted backslashes, so C:\Users\Bob\film reached the CLI as C:UsersBobfilm. Such words now take double quotes, which PowerShell, cmd.exe and Git Bash all read as written; trailing backslashes are doubled so they do not escape the closing quote. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): open --json gives a null stopCommand when the folder has no safe spelling When no spelling of the project folder is safe to paste in every Windows shell, the left-running preview's stopCommand held prose. It is now null, and stopCommandFromProject names the command to run from inside the project folder. The printed line is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(cli): drop a comment the nullable return type already states Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): a Windows name with no spelling common to every shell prints no path PowerShell single quotes do not group a word in cmd.exe, and Git Bash reads 'it''s' as its, so the single-quoted form printed for names with $, a backtick or a curly double quote was wrong in two of the three shells. Those names now take the existing null fallback, and the hint says to run the command from the project folder. Round-trip tests check that every printed Windows word reaches the program unchanged: through Git Bash everywhere, and through cmd.exe and PowerShell on Windows, where the CLI's Windows CI job now runs them. The names cover apostrophes, typographic quotes, mixed quotes, cmd operators and trailing backslashes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(cli): run the cmd.exe round-trip through spawnSync execFileSync's options type has no windowsVerbatimArguments, so the Windows-only cmd.exe test failed typecheck. spawnSync takes the option, and the test now also checks the exit status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(cli): expect the quoted Windows path in the relative open command On Windows a relative path holds a backslash, which shellArg now prints in double quotes so Git Bash keeps it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): a Windows name with %NAME% or ! prints no path cmd.exe expands %NAME% inside double quotes, and interactive Git Bash history-expands ! there, so neither name reads literally in every Windows shell. Both now take the null fallback. A lone % such as 100% still prints. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
80b09cc94a
commit
a07d4cf738
@@ -882,7 +882,7 @@ jobs:
|
||||
run: bun install --frozen-lockfile --ignore-scripts --linker=hoisted
|
||||
- run: bun run --filter '@hyperframes/{parsers,lint,studio-server}' build
|
||||
- run: bun run --cwd packages/core build
|
||||
- run: bun run --cwd packages/cli test src/utils/npxCommand.test.ts src/commands/skills.test.ts
|
||||
- run: bun run --cwd packages/cli test src/utils/npxCommand.test.ts src/commands/skills.test.ts src/utils/shellArg.test.ts
|
||||
env:
|
||||
HF_NPX_SHIM_E2E: "1"
|
||||
|
||||
|
||||
@@ -1172,7 +1172,10 @@ preview holds the project's edit history. So `open` first stops the project's
|
||||
`preview --background` server and says so. It leaves any other preview running,
|
||||
such as one started in a terminal, and prints the `preview --stop` command
|
||||
instead. With `--json`, the `preview` field reports `none`, `stopped` or
|
||||
`left-running`.
|
||||
`left-running`. A `left-running` preview carries its `stopCommand`. That is
|
||||
`null` when the folder's name can't be printed safely for every Windows shell,
|
||||
and `stopCommandFromProject` then holds the command to run from inside the
|
||||
project folder.
|
||||
|
||||
`catch-up` is the other half of that hand-off. Run it when the person is back
|
||||
from the desktop app, before you change anything: it lists what they asked and
|
||||
|
||||
@@ -1029,6 +1029,8 @@ export default defineCommand({
|
||||
await keepSkillsCurrent(destDir);
|
||||
}
|
||||
|
||||
const shownName = shellArg(name);
|
||||
const cdLine = shownName === null ? "go into the project folder" : `cd ${shownName}`;
|
||||
console.log();
|
||||
console.log("Get started:");
|
||||
console.log();
|
||||
@@ -1045,7 +1047,7 @@ export default defineCommand({
|
||||
console.log();
|
||||
console.log(` ${c.accent("2.")} Open this project with your AI coding agent:`);
|
||||
console.log(
|
||||
` ${c.accent(`cd ${shellArg(name)}`)} then start ${c.accent("Claude Code")}, ${c.accent("Cursor")}, or your preferred agent`,
|
||||
` ${c.accent(cdLine)} then start ${c.accent("Claude Code")}, ${c.accent("Cursor")}, or your preferred agent`,
|
||||
);
|
||||
console.log();
|
||||
console.log(` ${c.accent("3.")} Try a starter prompt:`);
|
||||
@@ -1057,13 +1059,13 @@ export default defineCommand({
|
||||
);
|
||||
console.log();
|
||||
console.log(` ${c.accent("4.")} Preview in the browser:`);
|
||||
console.log(` ${c.accent(`cd ${shellArg(name)}`)} && ${c.accent("npm run dev")}`);
|
||||
console.log(` ${c.accent(cdLine)} && ${c.accent("npm run dev")}`);
|
||||
console.log();
|
||||
console.log(` ${c.accent("5.")} Check the composition:`);
|
||||
console.log(` ${c.accent(`cd ${shellArg(name)}`)} && ${c.accent("npm run check")}`);
|
||||
console.log(` ${c.accent(cdLine)} && ${c.accent("npm run check")}`);
|
||||
console.log();
|
||||
console.log(` ${c.accent("6.")} Render to MP4 when ready:`);
|
||||
console.log(` ${c.accent(`cd ${shellArg(name)}`)} && ${c.accent("npm run render")}`);
|
||||
console.log(` ${c.accent(cdLine)} && ${c.accent("npm run render")}`);
|
||||
console.log();
|
||||
console.log(` ${c.dim(`Full docs: ${cliSourced("https://hyperframes.heygen.com")}`)}`);
|
||||
return;
|
||||
|
||||
@@ -55,6 +55,22 @@ describe("endPreviewBeforeOpening", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("gives JSON no stop command when the folder name has no safe spelling", async () => {
|
||||
const hostile = join(projectDir, "$(calc)&calc");
|
||||
const result = await endPreviewBeforeOpening(hostile, {
|
||||
status: async () => ({ pid: 999, port: 3002, projectDir: hostile }),
|
||||
stop: never,
|
||||
appInstalled: () => true,
|
||||
platform: "win32",
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
state: "left-running",
|
||||
stopCommand: null,
|
||||
stopCommandFromProject: "hyperframes preview --stop --port 3002",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the preview when the app isn't installed, since nothing will open", async () => {
|
||||
const result = await endPreviewBeforeOpening(projectDir, {
|
||||
status: async () => background,
|
||||
|
||||
@@ -29,20 +29,39 @@ const WHY_NOT: Record<Extract<DesktopOpenResult, { opened: false }>["reason"], s
|
||||
type PreviewBeforeOpen =
|
||||
| { state: "none" }
|
||||
| { state: "stopped"; port: number }
|
||||
| { state: "left-running"; port: number; stopCommand: string; error?: string };
|
||||
| {
|
||||
state: "left-running";
|
||||
port: number;
|
||||
stopCommand: string | null;
|
||||
stopCommandFromProject?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
const PREVIEW_SCAN_START_PORT = 3002;
|
||||
|
||||
function stopCommands(
|
||||
dir: string,
|
||||
port: number,
|
||||
platform: NodeJS.Platform,
|
||||
): { stopCommand: string | null; stopCommandFromProject?: string } {
|
||||
const stopCommand = previewStopCommandFor(dir, port, process.cwd(), platform);
|
||||
return stopCommand === null
|
||||
? { stopCommand, stopCommandFromProject: `hyperframes preview --stop --port ${port}` }
|
||||
: { stopCommand };
|
||||
}
|
||||
|
||||
export async function endPreviewBeforeOpening(
|
||||
dir: string,
|
||||
{
|
||||
status = readBackgroundPreviewStatus,
|
||||
stop = stopBackgroundPreview,
|
||||
appInstalled = () => desktopInstalled(),
|
||||
platform = process.platform,
|
||||
}: {
|
||||
status?: (dir: string, startPort: number) => ReturnType<typeof readBackgroundPreviewStatus>;
|
||||
stop?: (dir: string, startPort: number) => Promise<boolean>;
|
||||
appInstalled?: () => boolean;
|
||||
platform?: NodeJS.Platform;
|
||||
} = {},
|
||||
): Promise<PreviewBeforeOpen> {
|
||||
const running = await status(dir, PREVIEW_SCAN_START_PORT);
|
||||
@@ -50,7 +69,7 @@ export async function endPreviewBeforeOpening(
|
||||
const leftRunning = (error?: string): PreviewBeforeOpen => ({
|
||||
state: "left-running",
|
||||
port: running.port,
|
||||
stopCommand: previewStopCommandFor(dir, running.port),
|
||||
...stopCommands(dir, running.port, platform),
|
||||
...(error ? { error } : {}),
|
||||
});
|
||||
const startedInBackground = Boolean(running.logPath);
|
||||
@@ -75,7 +94,8 @@ function printPreview(preview: PreviewBeforeOpen, opened: boolean): void {
|
||||
? `${c.warn("◇")} Couldn't stop this project's preview (port ${preview.port}): ${preview.error}`
|
||||
: `${c.warn("◇")} A preview of this project is running (port ${preview.port}), and the app's edits wait until it stops.`,
|
||||
);
|
||||
console.log(` Stop it with: ${c.accent(preview.stopCommand)}`);
|
||||
const stop = preview.stopCommand ?? `${preview.stopCommandFromProject} from the project folder`;
|
||||
console.log(` Stop it with: ${c.accent(stop)}`);
|
||||
}
|
||||
|
||||
function printResult(project: ProjectDir, result: DesktopOpenResult): void {
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
previewLaunchMode,
|
||||
previewLaunchModeError,
|
||||
previewPortError,
|
||||
stopBackgroundCommand,
|
||||
publicPreviewPid,
|
||||
previewViteArgs,
|
||||
reportPreviewShutdown,
|
||||
@@ -854,3 +855,23 @@ describe("preview inside a host app's agent run", () => {
|
||||
expect(killOrphanedProcesses).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("stopBackgroundCommand", () => {
|
||||
it("spells the project folder so pasting the stop line runs nothing else", () => {
|
||||
expect(stopBackgroundCommand("/work/my film", "darwin")).toBe(
|
||||
'hyperframes preview "/work/my film" --stop',
|
||||
);
|
||||
expect(stopBackgroundCommand("/work/$(touch x)", "darwin")).toBe(
|
||||
"hyperframes preview '/work/$(touch x)' --stop",
|
||||
);
|
||||
expect(stopBackgroundCommand("C:\\Users\\Bob\\film", "win32")).toBe(
|
||||
'hyperframes preview "C:\\Users\\Bob\\film" --stop',
|
||||
);
|
||||
expect(stopBackgroundCommand("C:\\work\\$(calc)", "win32")).toBe(
|
||||
"hyperframes preview --stop from the project folder",
|
||||
);
|
||||
expect(stopBackgroundCommand("C:\\work\\$(calc)&calc", "win32")).toBe(
|
||||
"hyperframes preview --stop from the project folder",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -48,6 +48,7 @@ import { createRequire } from "node:module";
|
||||
import * as clack from "../ui/prompts.js";
|
||||
import { c } from "../ui/colors.js";
|
||||
import { desktopHint, insideHostApp } from "../utils/desktopApp.js";
|
||||
import { shellArg } from "../utils/shellArg.js";
|
||||
import { isDevMode } from "../utils/env.js";
|
||||
import { normalizeErrorMessage as errorMessage } from "../utils/errorMessage.js";
|
||||
import { buildNpxCommand } from "../utils/npxCommand.js";
|
||||
@@ -572,7 +573,7 @@ export default defineCommand({
|
||||
: `Running in the background. Log: ${background.logPath}`,
|
||||
"Changes reload automatically in the studio.",
|
||||
],
|
||||
footer: `Stop with: hyperframes preview ${JSON.stringify(dir)} --stop`,
|
||||
footer: `Stop with: ${stopBackgroundCommand(dir)}`,
|
||||
});
|
||||
}
|
||||
openStudioBrowser(url, projectName, {
|
||||
@@ -704,6 +705,16 @@ export function previewLaunchModeError(options: {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function stopBackgroundCommand(
|
||||
dir: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): string {
|
||||
const shown = shellArg(dir, platform);
|
||||
return shown === null
|
||||
? "hyperframes preview --stop from the project folder"
|
||||
: `hyperframes preview ${shown} --stop`;
|
||||
}
|
||||
|
||||
export function previewPortError(port: string | undefined): string | null {
|
||||
try {
|
||||
parsePort(port ?? "3002");
|
||||
|
||||
@@ -395,11 +395,26 @@ describe("openCommandFor", () => {
|
||||
"hyperframes open .",
|
||||
);
|
||||
expect(openCommandFor(join(work, "films", "a"), work)).toBe(
|
||||
`hyperframes open ${join("films", "a")}`,
|
||||
process.platform === "win32" ? 'hyperframes open "films\\a"' : "hyperframes open films/a",
|
||||
);
|
||||
expect(openCommandFor(join(work, "my film"), work)).toBe('hyperframes open "my film"');
|
||||
});
|
||||
|
||||
it("spells a Windows folder so PowerShell and Git Bash run no part of its name", () => {
|
||||
const work = resolve("work");
|
||||
expect(openCommandFor(join(work, "$(calc)"), work, "win32")).toBe(
|
||||
"hyperframes open from the project folder",
|
||||
);
|
||||
expect(openCommandFor(join(work, "$(calc)&calc"), work, "win32")).toBe(
|
||||
"hyperframes open from the project folder",
|
||||
);
|
||||
});
|
||||
|
||||
it("has no Windows stop command for a folder with no safe spelling", () => {
|
||||
const work = resolve("work");
|
||||
expect(previewStopCommandFor(join(work, "$(calc)&calc"), 3002, work, "win32")).toBeNull();
|
||||
});
|
||||
|
||||
it("names the matching `preview --stop` the same way", () => {
|
||||
const work = resolve("work");
|
||||
expect(previewStopCommandFor(work, 3002, work)).toBe(
|
||||
|
||||
@@ -247,17 +247,28 @@ function leaveIntent(dir: string, cta?: string, doc?: "storyboard"): () => void
|
||||
};
|
||||
}
|
||||
|
||||
function shownDir(dir: string, cwd: string): string {
|
||||
return shellArg(relative(cwd, dir) || ".");
|
||||
function shownDir(dir: string, cwd: string, platform: NodeJS.Platform): string | null {
|
||||
return shellArg(relative(cwd, dir) || ".", platform);
|
||||
}
|
||||
|
||||
/** The `hyperframes open` line for a project, relative to where the person is. */
|
||||
export function openCommandFor(dir: string, cwd = process.cwd()): string {
|
||||
return `hyperframes open ${shownDir(dir, cwd)}`;
|
||||
export function openCommandFor(
|
||||
dir: string,
|
||||
cwd = process.cwd(),
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): string {
|
||||
const shown = shownDir(dir, cwd, platform);
|
||||
return shown === null ? "hyperframes open from the project folder" : `hyperframes open ${shown}`;
|
||||
}
|
||||
|
||||
export function previewStopCommandFor(dir: string, port: number, cwd = process.cwd()): string {
|
||||
return `hyperframes preview ${shownDir(dir, cwd)} --stop --port ${port}`;
|
||||
export function previewStopCommandFor(
|
||||
dir: string,
|
||||
port: number,
|
||||
cwd = process.cwd(),
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): string | null {
|
||||
const shown = shownDir(dir, cwd, platform);
|
||||
return shown === null ? null : `hyperframes preview ${shown} --stop --port ${port}`;
|
||||
}
|
||||
|
||||
/** Spotlight's copies of an app with this bundle id; an updater's hidden leftover (`.X.app.installing-…`) is none. */
|
||||
@@ -309,7 +320,7 @@ export function desktopHint(
|
||||
): string | null {
|
||||
if (insideHostApp(env) || !someoneToTell(env, tty)) return null;
|
||||
if (ready && (installed ?? desktopInstalled({ platform, env }))) {
|
||||
const open = openCommandFor(dir);
|
||||
const open = openCommandFor(dir, process.cwd(), platform);
|
||||
const how =
|
||||
preview === "background"
|
||||
? `${open} (this stops the background preview)`
|
||||
|
||||
@@ -1,10 +1,43 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { join, win32 } from "node:path";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { shellArg } from "./shellArg.js";
|
||||
|
||||
const WINDOWS_ROUND_TRIP = [
|
||||
"my-video",
|
||||
"my first video",
|
||||
"it's mine",
|
||||
"o\u2019neil \u2018draft\u2019 it's",
|
||||
"\u201Alow\u201B 'n\u2019 \u2018mixed'",
|
||||
"Q&A (draft); 100% | a<b>c ^",
|
||||
"100% done",
|
||||
"서울 여행",
|
||||
"a,b",
|
||||
"@scope",
|
||||
"films\\my film",
|
||||
"C:\\Users\\Bob\\film",
|
||||
"C:\\work\\it's\\",
|
||||
];
|
||||
|
||||
// `“ ” „` end a PowerShell double-quoted string; `$` and a backtick expand in PowerShell and Git Bash,
|
||||
// `!` in interactive Git Bash, and `%NAME%` in cmd.exe.
|
||||
const WINDOWS_UNPRINTABLE = [
|
||||
"$(calc)",
|
||||
"a`b",
|
||||
"o'neil $x",
|
||||
"x\u201D;calc;\u201Dy",
|
||||
"x\u2019;calc;\u2018 $y",
|
||||
"$(calc)&calc",
|
||||
"\u201Cquoted\u201D",
|
||||
"a\nb",
|
||||
"%USERPROFILE%",
|
||||
"50% off, 20% more",
|
||||
"Hello!",
|
||||
"a!b",
|
||||
];
|
||||
|
||||
const NAMES = [
|
||||
"my-video",
|
||||
"서울여행",
|
||||
@@ -34,10 +67,25 @@ describe("shellArg", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses double quotes on Windows, where a backslash path needs none", () => {
|
||||
expect(shellArg("films\\a", "win32")).toBe("films\\a");
|
||||
it("uses double quotes on Windows, for a backslash path too", () => {
|
||||
expect(shellArg("films/a", "win32")).toBe("films/a");
|
||||
expect(shellArg("films\\a", "win32")).toBe('"films\\a"');
|
||||
expect(shellArg("C:\\Users\\Bob\\film", "win32")).toBe('"C:\\Users\\Bob\\film"');
|
||||
expect(shellArg("C:\\", "win32")).toBe('"C:\\\\"');
|
||||
expect(shellArg("my first video", "win32")).toBe('"my first video"');
|
||||
expect(shellArg("it's mine", "win32")).toBe(`"it's mine"`);
|
||||
expect(shellArg("Q&A (draft); 100%", "win32")).toBe('"Q&A (draft); 100%"');
|
||||
expect(shellArg("서울 여행", "win32")).toBe('"서울 여행"');
|
||||
});
|
||||
|
||||
it("quotes a Windows name that PowerShell would read as an array or a splat", () => {
|
||||
expect(shellArg("a,b", "win32")).toBe('"a,b"');
|
||||
expect(shellArg("@scope", "win32")).toBe('"@scope"');
|
||||
expect(shellArg("films/@scope", "win32")).toBe("films/@scope");
|
||||
});
|
||||
|
||||
it("prints nothing on Windows for a name no shell there reads literally", () => {
|
||||
for (const name of WINDOWS_UNPRINTABLE) expect(shellArg(name, "win32"), name).toBeNull();
|
||||
});
|
||||
|
||||
const root = mkdtempSync(join(tmpdir(), "hf-shell-arg-"));
|
||||
@@ -46,11 +94,61 @@ describe("shellArg", () => {
|
||||
it.skipIf(process.platform === "win32")("prints a cd that a POSIX shell runs as written", () => {
|
||||
for (const name of NAMES) {
|
||||
mkdirSync(join(root, name), { recursive: true });
|
||||
const pwd = execFileSync("/bin/sh", ["-c", `cd ${shellArg(name)} && pwd -P`], {
|
||||
const pwd = execFileSync("/bin/sh", ["-c", `cd ${shellArg(name, "darwin")} && pwd -P`], {
|
||||
cwd: root,
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(pwd.trim()).toBe(realpathSync(join(root, name)));
|
||||
}
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"prints a Windows word that Git Bash reads as written",
|
||||
() => {
|
||||
for (const name of WINDOWS_ROUND_TRIP) {
|
||||
const shown = execFileSync("/bin/bash", ["-c", `printf %s ${shellArg(name, "win32")}`], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(shown, name).toBe(name);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const argvScript = join(root, "argv.cjs");
|
||||
writeFileSync(argvScript, "process.stdout.write(JSON.stringify(process.argv.slice(2)));");
|
||||
const readArgv = (output: string): string[] => JSON.parse(output) as string[];
|
||||
|
||||
it.runIf(process.platform === "win32")(
|
||||
"prints a Windows word that cmd.exe reads as written",
|
||||
() => {
|
||||
for (const name of WINDOWS_ROUND_TRIP) {
|
||||
const line = `"${process.execPath}" "${argvScript}" ${shellArg(name, "win32")}`;
|
||||
const run = spawnSync("cmd.exe", ["/d", "/s", "/c", `"${line}"`], {
|
||||
encoding: "utf8",
|
||||
windowsVerbatimArguments: true,
|
||||
});
|
||||
expect(run.status, run.stderr).toBe(0);
|
||||
expect(readArgv(run.stdout), name).toEqual([name]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.runIf(process.platform === "win32")(
|
||||
"prints a Windows word that PowerShell reads as written",
|
||||
() => {
|
||||
for (const name of WINDOWS_ROUND_TRIP) {
|
||||
const line = `& '${process.execPath}' '${argvScript}' ${shellArg(name, "win32")}`;
|
||||
const output = execFileSync(
|
||||
"powershell.exe",
|
||||
["-NoProfile", "-EncodedCommand", Buffer.from(line, "utf16le").toString("base64")],
|
||||
{ encoding: "utf8" },
|
||||
);
|
||||
// Windows PowerShell hands a space-free word to a program unquoted, so a doubled trailing backslash stays doubled.
|
||||
expect(
|
||||
readArgv(output).map((arg) => win32.normalize(arg)),
|
||||
name,
|
||||
).toEqual([win32.normalize(name)]);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,24 @@
|
||||
const PLAIN = /^[\p{L}\p{M}\p{N}_./@:+,=-]+$/u;
|
||||
const PLAIN_WINDOWS_PATH = /^[\p{L}\p{M}\p{N}_./@:+,=\\-]+$/u;
|
||||
const PLAIN_WINDOWS_WORD_WITHOUT_BACKSLASH_COMMA_OR_SPLAT = /^(?!@)[\p{L}\p{M}\p{N}_./@:+=-]+$/u;
|
||||
const SPECIAL_IN_DOUBLE_QUOTES = /["$`\\!]/;
|
||||
const SPECIAL_IN_POWERSHELL_OR_BASH_DOUBLE_QUOTES = /["$`!\u201C-\u201E\p{Cc}]/u;
|
||||
const CMD_VARIABLE = /%[^%]+%/;
|
||||
const TRAILING_BACKSLASHES = /\\+$/;
|
||||
|
||||
/** `text` as one word of a command printed for the person to paste into their shell. */
|
||||
export function shellArg(text: string, platform: NodeJS.Platform = process.platform): string {
|
||||
if (platform === "win32") return PLAIN_WINDOWS_PATH.test(text) ? text : `"${text}"`;
|
||||
/** `text` as one word of a pasteable command; on Windows literal in PowerShell, cmd.exe and Git Bash alike, or null. */
|
||||
export function shellArg(
|
||||
text: string,
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): string | null {
|
||||
if (platform === "win32") return windowsShellArg(text);
|
||||
if (PLAIN.test(text)) return text;
|
||||
if (!SPECIAL_IN_DOUBLE_QUOTES.test(text)) return `"${text}"`;
|
||||
return `'${text.replaceAll("'", "'\\''")}'`;
|
||||
}
|
||||
|
||||
function windowsShellArg(text: string): string | null {
|
||||
if (PLAIN_WINDOWS_WORD_WITHOUT_BACKSLASH_COMMA_OR_SPLAT.test(text)) return text;
|
||||
if (SPECIAL_IN_POWERSHELL_OR_BASH_DOUBLE_QUOTES.test(text) || CMD_VARIABLE.test(text))
|
||||
return null;
|
||||
return `"${text.replace(TRAILING_BACKSLASHES, "$&$&")}"`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user