Skip to content

Commit 7ef15d2

Browse files
herberttnsindresorhus
authored andcommittedOct 15, 2019
Handle URL and path escaping on Windows (#146)
1 parent 66d3bc7 commit 7ef15d2

File tree

5 files changed

+93
-2
lines changed

5 files changed

+93
-2
lines changed
 

‎index.d.ts

+13
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,17 @@ declare namespace open {
3131
You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome.
3232
*/
3333
readonly app?: string | readonly string[];
34+
35+
/**
36+
Uses `encodeURI` to encode the `target` before executing it.
37+
38+
The use with targets that are not URLs is not recommended.
39+
40+
Especially useful when dealing with the [double-quotes on Windows](https://github.com/sindresorhus/open#double-quotes-on-windows) caveat.
41+
42+
@default false
43+
*/
44+
readonly url?: boolean;
3445
}
3546
}
3647

@@ -39,6 +50,8 @@ Open stuff like URLs, files, executables. Cross-platform.
3950
4051
Uses the command `open` on OS X, `start` on Windows and `xdg-open` on other platforms.
4152
53+
There is a caveat for [double-quotes on Windows](https://github.com/sindresorhus/open#double-quotes-on-windows) where all double-quotes are stripped from the `target`.
54+
4255
@param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. For example, URLs open in your default browser.
4356
@returns The [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process.
4457

‎index.js

+18-2
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ module.exports = async (target, options) => {
2626
options = {
2727
wait: false,
2828
background: false,
29+
url: false,
2930
...options
3031
};
3132

@@ -39,6 +40,13 @@ module.exports = async (target, options) => {
3940
options.app = options.app[0];
4041
}
4142

43+
// Encodes the target as if it were an URL. Especially useful to get
44+
// double-quotes through the double-quotes on windows caveat, but it
45+
// can be used in any platform.
46+
if (options.url) {
47+
target = encodeURI(target);
48+
}
49+
4250
if (process.platform === 'darwin') {
4351
command = 'open';
4452

@@ -55,8 +63,16 @@ module.exports = async (target, options) => {
5563
}
5664
} else if (process.platform === 'win32' || isWsl) {
5765
command = 'cmd' + (isWsl ? '.exe' : '');
58-
cliArguments.push('/c', 'start', '""', '/b');
59-
target = target.replace(/&/g, '^&');
66+
cliArguments.push('/s', '/c', 'start', '""', '/b');
67+
68+
// Always quoting target allows for URLs/paths to have spaces and unmarked characters, as `cmd.exe` will
69+
// interpret them as plain text to be forwarded as one unique argument. Enabling `windowsVerbatimArguments`
70+
// disables Node.js's default quotes and escapes handling (https://git.io/fjdem).
71+
// References: Issues #17, #44, #55, #77, #101 and #115 / Pull requests: #74 and #98
72+
//
73+
// As a result, all double-quotes are stripped from the `target` and do not get to your desired destination.
74+
target = `"${target}"`;
75+
childProcessOptions.windowsVerbatimArguments = true;
6076

6177
if (options.wait) {
6278
cliArguments.push('/wait');

‎index.test-d.ts

+1
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ expectType<Promise<ChildProcess>>(open('foo', {app: 'bar'}));
99
expectType<Promise<ChildProcess>>(open('foo', {app: ['bar', '--arg']}));
1010
expectType<Promise<ChildProcess>>(open('foo', {wait: true}));
1111
expectType<Promise<ChildProcess>>(open('foo', {background: true}));
12+
expectType<Promise<ChildProcess>>(open('foo', {url: true}));

‎readme.md

+33
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,39 @@ The app name is platform dependent. Don't hard code it in reusable modules. For
9393

9494
You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome.
9595

96+
##### url
97+
98+
Type: `boolean`<br>
99+
Default: `false`
100+
101+
Uses `encodeURI` to encode the target before executing it.<br>
102+
We do not recommend using it on targets that are not URLs.
103+
104+
Especially useful when dealing with the [double-quotes on Windows](#double-quotes-on-windows) caveat.
105+
106+
## Caveats
107+
108+
### Double-quotes on Windows
109+
TL;DR: All double-quotes are stripped from the `target` and do not get to your desired destination (on Windows!).
110+
111+
Due to specific behaviors of Window's Command Prompt (`cmd.exe`) regarding ampersand (`&`) characters breaking commands and URLs, double-quotes are now a special case.
112+
113+
The solution ([#146](https://github.com/sindresorhus/open/pull/146)) to this and other problems was to leverage the fact that `cmd.exe` interprets a double-quoted argument as a plain text argument just by quoting it (like Node already does). Unfortunatelly `cmd.exe` can only do **one** of two things: handle them all **OR** not handle them at all. As per its own documentation:
114+
115+
>*If /C or /K is specified, then the remainder of the command line after the switch is processed as a command line, where the following logic is used to process quote (") characters:*
116+
>
117+
> 1. *If all of the following conditions are met, then quote characters on the command line are preserved:*
118+
> - *no /S switch*
119+
> - *exactly two quote characters*
120+
> - *no special characters between the two quote characters, where special is one of: &<>()@^|*
121+
> - *there are one or more whitespace characters between the two quote characters*
122+
> - *the string between the two quote characters is the name of an executable file.*
123+
>
124+
> 2. *Otherwise, old behavior is to see if the first character is a quote character and if so, strip the leading character and remove the last quote character on the command line, preserving any text after the last quote character.*
125+
126+
The option that solved all of the problems was the second one, and for additional behavior consistency we're also now using the `/S` switch, so we **always** get the second option. The caveat is that this built-in double-quotes handling ends up stripping all of them from the command line and so far we weren't able to find a scaping method that works (if you do, please feel free to contribute!).
127+
128+
To make this caveat somewhat less impactful (at least for URLs), check out the [url option](#url). Double-quotes will be "preserved" when using it with an URL.
96129

97130
## Related
98131

‎test.js

+28
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,10 @@ test('wait for the app to close if wait: true', async () => {
3333
await open('https://sindresorhus.com', {wait: true});
3434
});
3535

36+
test('encode url if url: true', async () => {
37+
await open('https://sindresorhus.com', {url: true});
38+
});
39+
3640
test('open url in default app', async () => {
3741
await open('https://sindresorhus.com');
3842
});
@@ -50,6 +54,30 @@ test('return the child process when called', async t => {
5054
t.true('stdout' in cp);
5155
});
5256

57+
test('open url with query strings', async () => {
58+
await open('https://sindresorhus.com/?abc=123&def=456');
59+
});
60+
61+
test('open url with a fragment', async () => {
62+
await open('https://sindresorhus.com#projects');
63+
});
64+
65+
test('open url with query strings and spaces', async () => {
66+
await open('https://sindresorhus.com/?abc=123&def=456&ghi=with spaces');
67+
});
68+
69+
test('open url with query strings and a fragment', async () => {
70+
await open('https://sindresorhus.com/?abc=123&def=456#projects');
71+
});
72+
73+
test('open url with query strings and pipes', async () => {
74+
await open('https://sindresorhus.com/?abc=123&def=456&ghi=w|i|t|h');
75+
});
76+
77+
test('open url with query strings, spaces, pipes and a fragment', async () => {
78+
await open('https://sindresorhus.com/?abc=123&def=456&ghi=w|i|t|h spaces#projects');
79+
});
80+
5381
if (isWsl) {
5482
test('open url in specified windows app given a wsl path to the app', async () => {
5583
await open('https://sindresorhus.com', {app: firefoxWslName});

0 commit comments

Comments
 (0)
Please sign in to comment.