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
106 changes: 87 additions & 19 deletions packages/cli/src/open.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,105 @@
import { spawn } from 'node:child_process';
import { execFileSync, spawn } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';

/** The command that opens a file in the default browser on `platform`, or why it can't be done safely. */
export function browserCommand(
/**
* 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.
*/
export type Opener = { cmd: string; args: string[]; orAt?: string; startFile?: string };

// 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';

/** 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 {
if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true;
try {
return /microsoft/i.test(readFileSync('/proc/version', 'utf8'));
} catch {
return false;
}
}

/** The commands that may open a file in the default browser on `platform`, in order, or why it can't be done safely. */
export function browserCommands(
file: string,
platform: NodeJS.Platform = process.platform,
): { cmd: string; args: string[] } | { refused: string } {
if (platform === 'darwin') return { cmd: 'open', args: [file] };
wsl = platform === 'linux' && isWsl(),
): Opener[] | { refused: string } {
if (platform === 'darwin') return [{ cmd: 'open', args: [file] }];
// `start` is a cmd builtin, and its first quoted argument is the window title.
// Quoted, cmd takes & | < > ^ ( ) literally; it still expands %VAR% inside quotes, and " would end the quoting.
if (platform === 'win32')
return /["%]/.test(file)
? { refused: 'the path has a " or % that cmd would interpret' }
: { cmd: 'cmd', args: ['/c', 'start', '""', `"${file}"`] };
return { cmd: 'xdg-open', args: [file] };
: [{ cmd: 'cmd', args: ['/c', 'start', '""', `"${file}"`] }];
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] },
];
}

/** 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 {
// 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();
}

/**
* Opens `file` in the default browser; resolves null once the opener has handed it off, or why it couldn't (no
* opener installed, a headless machine). An opener that is still running after a moment is taken as success.
* Opens `file` in the default browser; resolves null once an opener has handed it off, or why none could (no opener
* installed, a headless machine).
*/
export function openInBrowser(file: string): Promise<string | null> {
const command = browserCommand(file);
if ('refused' in command) return Promise.resolve(command.refused);
const { cmd, args } = command;
return new Promise((resolve) => {
export async function openInBrowser(file: string): Promise<string | null> {
const commands = browserCommands(file);
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> {
const failures: string[] = [];
for (const opener of openers) {
const why = await run(opener, windowsPath);
if (why === null) return null;
failures.push(why);
}
return failures.join('; ');
}

async function run({ cmd, args, orAt, startFile }: 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);
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> {
return new Promise((done) => {
const child = spawn(cmd, args, { stdio: 'ignore', detached: true, windowsVerbatimArguments: cmd === 'cmd' });
const timer = setTimeout(() => resolve(null), 3000);
const done = (why: string | null) => {
const timer = setTimeout(() => done(null), 3000);
const finish = (why: string | null) => {
clearTimeout(timer);
resolve(why);
done(why);
};
child.once('error', (e) => done((e as NodeJS.ErrnoException).code === 'ENOENT' ? `${cmd} not found` : e.message));
child.once('exit', (code) => done(code ? `${cmd} exited with ${code}` : null));
child.once('error', (e) => finish((e as NodeJS.ErrnoException).code === 'ENOENT' ? NOT_FOUND : `failed (${e.message})`));
child.once('exit', (code, signal) => finish(code ? `exited with ${code}` : signal ? `was killed by ${signal}` : null));
child.unref();
});
}
80 changes: 73 additions & 7 deletions packages/cli/test/open.test.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,91 @@
import { describe, expect, it } from 'vitest';
import { browserCommand } from '../src/open';
import { browserCommands, isWsl, openWith, startCommand } from '../src/open';

describe('browserCommand', () => {
const NODE = process.execPath;
const MISSING = 'stackmap-no-such-opener';
const exits = (code: number) => ({ cmd: NODE, args: ['-e', `process.exit(${code})`] });

describe('browserCommands', () => {
it('uses the native opener on darwin and linux', () => {
expect(browserCommand('/tmp/a b.html', 'darwin')).toEqual({ cmd: 'open', args: ['/tmp/a b.html'] });
expect(browserCommand('/tmp/a.html', 'linux')).toEqual({ cmd: 'xdg-open', args: ['/tmp/a.html'] });
expect(browserCommands('/tmp/a b.html', 'darwin')).toEqual([{ cmd: 'open', args: ['/tmp/a b.html'] }]);
expect(browserCommands('/tmp/a.html', 'linux', false)).toEqual([{ cmd: 'xdg-open', args: ['/tmp/a.html'] }]);
});

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']);
});

it('quotes the path for cmd on win32', () => {
expect(browserCommand('C:\\d\\a.html', 'win32')).toEqual({ cmd: 'cmd', args: ['/c', 'start', '""', '"C:\\d\\a.html"'] });
expect(browserCommands('C:\\d\\a.html', 'win32')).toEqual([{ cmd: 'cmd', args: ['/c', 'start', '""', '"C:\\d\\a.html"'] }]);
});

it('keeps spaces and cmd metacharacters inside the quotes', () => {
const file = 'C:\\Users\\First Last\\a&b (1).html';
expect(browserCommand(file, 'win32')).toEqual({ cmd: 'cmd', args: ['/c', 'start', '""', `"${file}"`] });
expect(browserCommands(file, 'win32')).toEqual([{ cmd: 'cmd', args: ['/c', 'start', '""', `"${file}"`] }]);
});

it('refuses win32 paths with a % or " that cmd would interpret', () => {
for (const file of ['C:\\d\\100%.html', 'C:\\d\\a"b.html']) {
const result = browserCommand(file, 'win32');
const result = browserCommands(file, 'win32');
expect('refused' in result && typeof result.refused).toBe('string');
}
});
});

describe('isWsl', () => {
it('trusts the variables WSL sets', () => {
expect(isWsl({ WSL_DISTRO_NAME: 'Ubuntu' })).toBe(true);
expect(isWsl({ WSL_INTEROP: '/run/WSL/1_interop' })).toBe(true);
});
});

describe('startCommand', () => {
it('doubles every quote PowerShell would end the string on', () => {
expect(startCommand("C:\\d\\it's.html")).toBe("Start-Process -FilePath 'C:\\d\\it''s.html'");
expect(startCommand('C:\\d\\it’s.html')).toBe("Start-Process -FilePath 'C:\\d\\it’’s.html'");
});
});

describe('openWith', () => {
it('hands over to the next opener when one is missing or exits non-zero', async () => {
expect(await openWith([{ cmd: MISSING, args: [] }, exits(3), exits(0)])).toBeNull();
});

it('reports every opener that failed when none opened', async () => {
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 () => {
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`);
});

it('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)`;
const windowsPath = (file: string) => {
if (file !== "/home/u/it's.html") throw new Error(`unexpected ${file}`);
return "\\\\wsl.localhost\\Ubuntu\\home\\u\\it's.html";
};
expect(await openWith([{ cmd: NODE, args: ['-e', check], startFile: "/home/u/it's.html" }], windowsPath)).toBeNull();
});

it('says whether wslpath is missing or could not convert the path', async () => {
const opener = { cmd: NODE, args: ['-e', ''], startFile: '/home/u/a.html' };
const missing = () => {
throw Object.assign(new Error('spawnSync wslpath ENOENT'), { code: 'ENOENT' });
};
const failing = () => {
throw new Error('Command failed: wslpath -w /home/u/a.html');
};
expect(await openWith([opener], missing)).toBe('wslpath not found');
expect(await openWith([opener], failing)).toBe("wslpath couldn't convert the path");
});
});
Loading