Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 43 additions & 21 deletions packages/cli/src/open.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,27 @@ import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';

/**
* One way to open a file. `orAt` is where `cmd` lives when it isn't on the PATH. `startFile` is a file for
* PowerShell to start (WSL): its Windows path goes on the end of `args`, as an encoded command.
* One way to open a file. `orAt` finds `cmd` when it isn't on the PATH. `startFile` is a file for PowerShell to
* start (WSL): its Windows path goes on the end of `args`, as an encoded command. `wait` is how long, in ms, the
* opener gets to exit before it counts as having handed the file off.
*/
export type Opener = { cmd: string; args: string[]; orAt?: string; startFile?: string };
export type Opener = { cmd: string; args: string[]; orAt?: () => string; startFile?: string; wait?: number };

// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`; this is the default mount.
const POWERSHELL = '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
const NOT_FOUND = 'not found';
// xdg-open can turn into the browser itself and never exit, so a short wait has to count as a hand-off.
const HANDED_OFF = 3000;
// A Windows program started through WSL interop can take longer than that to load, and its exit code is the only
// sign that nothing opened.
const WINDOWS_START = 15000;

// WSL leaves the Windows directories off the PATH under `appendWindowsPath=false`, and `automount.root` moves /mnt.
function powershell(): string {
try {
return wslpath('-u', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe');
} catch {
return '/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe';
}
}

/** Whether this Linux is WSL, where a stock distro has no xdg-open but Windows has a browser. */
export function isWsl(env: NodeJS.ProcessEnv = process.env): boolean {
Expand Down Expand Up @@ -38,22 +51,26 @@ export function browserCommands(
if (!wsl) return [{ cmd: 'xdg-open', args: [file] }];
// The browser is on the Windows side. xdg-open comes last: with no Linux browser it can exit 0 having opened
// nothing, which would end the chain. PowerShell, unlike explorer.exe, exits non-zero when it couldn't start the file.
return [
{ cmd: 'wslview', args: [file] },
{ cmd: 'powershell.exe', orAt: POWERSHELL, args: ['-NoProfile', '-NonInteractive', '-EncodedCommand'], startFile: file },
{ cmd: 'xdg-open', args: [file] },
];
const start: Opener = {
cmd: 'powershell.exe',
orAt: powershell,
args: ['-NoProfile', '-NonInteractive', '-EncodedCommand'],
startFile: file,
wait: WINDOWS_START,
};
// wslview hands the path to PowerShell with quoting of its own, so it only gets paths PowerShell reads literally.
const viaWslview: Opener[] = /[$`'"‘’‚‛“”„]/.test(file) ? [] : [{ cmd: 'wslview', args: [file], wait: WINDOWS_START }];
return [...viaWslview, start, { cmd: 'xdg-open', args: [file] }];
}

/** The PowerShell command that opens `windowsPath` with its default app. */
export function startCommand(windowsPath: string): string {
// PowerShell ends a single-quoted string on the curly quotes too; a doubled one is the only escape.
return `Start-Process -FilePath '${windowsPath.replace(/['‘’‚‛]/g, '$&$&')}'`;
}

function wslpath(file: string): string {
function wslpath(to: '-w' | '-u', path: string): string {
// stderr is dropped so that wslpath's own message doesn't land ahead of the warning.
return execFileSync('wslpath', ['-w', file], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
return execFileSync('wslpath', [to, path], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
}

/**
Expand All @@ -65,8 +82,10 @@ export async function openInBrowser(file: string): Promise<string | null> {
return 'refused' in commands ? commands.refused : openWith(commands);
}

/** Tries each opener until one hands the file off; resolves null then, or why every one of them failed. */
export async function openWith(openers: Opener[], windowsPath: (file: string) => string = wslpath): Promise<string | null> {
export async function openWith(
openers: Opener[],
windowsPath: (file: string) => string = (file) => wslpath('-w', file),
): Promise<string | null> {
const failures: string[] = [];
for (const opener of openers) {
const why = await run(opener, windowsPath);
Expand All @@ -76,24 +95,27 @@ export async function openWith(openers: Opener[], windowsPath: (file: string) =>
return failures.join('; ');
}

async function run({ cmd, args, orAt, startFile }: Opener, windowsPath: (file: string) => string): Promise<string | null> {
async function run(
{ cmd, args, orAt, startFile, wait = HANDED_OFF }: Opener,
windowsPath: (file: string) => string,
): Promise<string | null> {
if (startFile !== undefined) {
try {
args = [...args, Buffer.from(startCommand(windowsPath(resolve(startFile))), 'utf16le').toString('base64')];
} catch (e) {
return (e as NodeJS.ErrnoException).code === 'ENOENT' ? 'wslpath not found' : "wslpath couldn't convert the path";
}
}
let why = await launch(cmd, args);
if (why === NOT_FOUND && orAt) why = await launch(orAt, args);
let why = await launch(cmd, args, wait);
if (why === NOT_FOUND && orAt) why = await launch(orAt(), args, wait);
return why === null ? null : `${cmd} ${why}`;
}

/** Resolves null once the command exits cleanly or is still running after a moment, else what went wrong. */
function launch(cmd: string, args: string[]): Promise<string | null> {
/** Resolves null once the command exits cleanly or is still running after `wait` ms, else what went wrong. */
function launch(cmd: string, args: string[], wait: number): Promise<string | null> {
return new Promise((done) => {
const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: cmd === 'cmd' });
const timer = setTimeout(() => done(null), 3000);
const timer = setTimeout(() => done(null), wait);
const finish = (why: string | null) => {
clearTimeout(timer);
done(why);
Expand Down
32 changes: 25 additions & 7 deletions packages/cli/test/open.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { describe, expect, it } from 'vitest';
import { browserCommands, isWsl, openWith, startCommand } from '../src/open';
import { browserCommands, isWsl, openWith, startCommand, type Opener } from '../src/open';

const NODE = process.execPath;
const MISSING = 'stackmap-no-such-opener';
const exits = (code: number) => ({ cmd: NODE, args: ['-e', `process.exit(${code})`] });
// A Windows host has no signal exit status, and its path.resolve puts a drive on a POSIX path.
const posix = it.skipIf(process.platform === 'win32');

describe('browserCommands', () => {
it('uses the native opener on darwin and linux', () => {
Expand All @@ -12,8 +14,18 @@ describe('browserCommands', () => {
});

it('tries the Windows side first on WSL, and xdg-open last', () => {
const commands = browserCommands('/tmp/a.html', 'linux', true);
expect(Array.isArray(commands) && commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'xdg-open']);
const commands = browserCommands('/tmp/a.html', 'linux', true) as Opener[];
expect(commands.map((c) => c.cmd)).toEqual(['wslview', 'powershell.exe', 'xdg-open']);
// run() puts the encoded command straight after the last argument.
expect(commands[1]).toMatchObject({ startFile: '/tmp/a.html', orAt: expect.any(Function) });
expect(commands[1]!.args.at(-1)).toBe('-EncodedCommand');
});

it('keeps a path PowerShell would expand or unquote away from wslview', () => {
for (const file of ['/home/u/$(x)/a.html', '/home/u/a`b.html', "/home/u/it's.html", '/home/u/a"b.html']) {
const commands = browserCommands(file, 'linux', true) as Opener[];
expect(commands.map((c) => c.cmd)).toEqual(['powershell.exe', 'xdg-open']);
}
});

it('quotes the path for cmd on win32', () => {
Expand Down Expand Up @@ -56,17 +68,23 @@ describe('openWith', () => {
expect(await openWith([{ cmd: MISSING, args: [] }, exits(1)])).toBe(`${MISSING} not found; ${NODE} exited with 1`);
});

it('takes an opener killed by a signal as failed', async () => {
posix('takes an opener killed by a signal as failed', async () => {
const killed = { cmd: NODE, args: ['-e', "process.kill(process.pid, 'SIGKILL')"] };
expect(await openWith([killed])).toBe(`${NODE} was killed by SIGKILL`);
});

it('finds an opener that is off the PATH at its known location', async () => {
expect(await openWith([{ cmd: MISSING, orAt: NODE, args: ['-e', ''] }])).toBeNull();
expect(await openWith([{ cmd: MISSING, orAt: `/${MISSING}`, args: [] }])).toBe(`${MISSING} not found`);
expect(await openWith([{ cmd: MISSING, orAt: () => NODE, args: ['-e', ''] }])).toBeNull();
expect(await openWith([{ cmd: MISSING, orAt: () => `/${MISSING}`, args: [] }])).toBe(`${MISSING} not found`);
});

it('waits as long as the opener asks before taking it as handed off', async () => {
const slow = { cmd: NODE, args: ['-e', 'setTimeout(() => process.exit(1), 1000)'] };
expect(await openWith([{ ...slow, wait: 100 }])).toBeNull();
expect(await openWith([{ ...slow, wait: 30000 }])).toBe(`${NODE} exited with 1`);
});

it('hands PowerShell the Windows path of the file as an encoded command', async () => {
posix('hands PowerShell the Windows path of the file as an encoded command', async () => {
const want = "Start-Process -FilePath '\\\\wsl.localhost\\Ubuntu\\home\\u\\it''s.html'";
// The child exits 0 only when the argument after its own decodes to the command.
const check = `process.exit(Buffer.from(process.argv[1], 'base64').toString('utf16le') === ${JSON.stringify(want)} ? 0 : 7)`;
Expand Down
Loading