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
80 changes: 61 additions & 19 deletions packages/cli/src/open.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,79 @@
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: `windowsPath` means the file must first be given as a Windows path (WSL), and `anyExit`
* means the exit code says nothing about success.
*/
export type Opener = { cmd: string; args: string[]; windowsPath?: boolean; anyExit?: boolean };

/** 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] }];
// explorer.exe hands the file to the Windows default browser, and exits with 1 even when it did.
return [
{ cmd: 'xdg-open', args: [file] },
{ cmd: 'wslview', args: [file] },
{ cmd: 'explorer.exe', args: [file], windowsPath: true, anyExit: true },
];
}

/**
* 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). Each opener that fails hands over to the next. An opener that is still running
* after a moment is taken as success.
*/
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);
if ('refused' in commands) return commands.refused;
const failures: string[] = [];
for (const opener of commands) {
const why = await run(opener);
if (why === null) return null;
failures.push(why);
}
return failures.join('; ');
}

function run({ cmd, args, windowsPath, anyExit }: Opener): Promise<string | null> {
if (windowsPath) {
try {
args = args.map((a) => execFileSync('wslpath', ['-w', resolve(a)], { encoding: 'utf8' }).trim());
} catch {
return Promise.resolve(`wslpath couldn't convert the path for ${cmd}`);
}
}
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' ? `${cmd} not found` : e.message));
child.once('exit', (code) => finish(code && !anyExit ? `${cmd} exited with ${code}` : null));
child.unref();
});
}
29 changes: 22 additions & 7 deletions packages/cli/test/open.test.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,40 @@
import { describe, expect, it } from 'vitest';
import { browserCommand } from '../src/open';
import { browserCommands, isWsl } from '../src/open';

describe('browserCommand', () => {
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('falls back from xdg-open to wslview, then explorer.exe with a Windows path, on WSL', () => {
expect(browserCommands('/tmp/a.html', 'linux', true)).toEqual([
{ cmd: 'xdg-open', args: ['/tmp/a.html'] },
{ cmd: 'wslview', args: ['/tmp/a.html'] },
{ cmd: 'explorer.exe', args: ['/tmp/a.html'], windowsPath: true, anyExit: true },
]);
});

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);
});
});
Loading