Skip to content

Commit 1b9dcc8

Browse files
committed
refactor(@angular/cli): address review feedback for escapeArgForCmd
Remove redundant string conversion, add proper attribution with authoritative Microsoft documentation link, and refactor to avoid multiple re-assignments as suggested by reviewer.
1 parent 40ed9a6 commit 1b9dcc8

File tree

1 file changed

+15
-21
lines changed
  • packages/angular/cli/src/package-managers

1 file changed

+15
-21
lines changed

packages/angular/cli/src/package-managers/host.ts

Lines changed: 15 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -31,29 +31,23 @@ function escapeCommandForCmd(cmd: string): string {
3131

3232
/**
3333
* Escapes an argument for safe use in cmd.exe.
34-
* Based on the algorithm from cross-spawn (https://github.com/moxystudio/node-cross-spawn)
35-
* and https://qntm.org/cmd
34+
* Adapted from cross-spawn's `lib/util/escape.js`:
35+
* https://github.com/moxystudio/node-cross-spawn/blob/master/lib/util/escape.js
36+
*
37+
* Algorithm based on https://learn.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way
3638
*/
3739
function escapeArgForCmd(arg: string): string {
38-
// Convert to string
39-
arg = `${arg}`;
40-
41-
// Sequence of backslashes followed by a double quote:
42-
// double up all the backslashes and escape the double quote
43-
arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
44-
45-
// Sequence of backslashes followed by the end of the string
46-
// (which will become a double quote later):
47-
// double up all the backslashes
48-
arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1');
49-
50-
// Quote the whole thing
51-
arg = `"${arg}"`;
52-
53-
// Escape cmd.exe meta chars with ^
54-
arg = arg.replace(metaCharsRegExp, '^$1');
55-
56-
return arg;
40+
const processed = arg
41+
// Sequence of backslashes followed by a double quote:
42+
// double up all the backslashes and escape the double quote
43+
.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"')
44+
// Sequence of backslashes followed by the end of the string
45+
// (which will become a double quote later):
46+
// double up all the backslashes
47+
.replace(/(?=(\\+?)?)\1$/, '$1$1');
48+
49+
// Quote the whole thing and escape cmd.exe meta chars with ^
50+
return `"${processed}"`.replace(metaCharsRegExp, '^$1');
5751
}
5852

5953
/**

0 commit comments

Comments
 (0)