Skip to content

Commit b173fb0

Browse files
committed
unit test for escape-exec-path util
1 parent 8602506 commit b173fb0

File tree

2 files changed

+25
-19
lines changed

2 files changed

+25
-19
lines changed

lib/utils/escape-exec-path.js

+10-19
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
1-
'use strict'
2-
var path = require('path')
3-
var isWindows = require('./is-windows.js')
1+
const { normalize } = require('path')
2+
const isWindows = require('./is-windows.js')
43

54
/*
65
Escape the name of an executable suitable for passing to the system shell.
@@ -9,22 +8,14 @@ Windows is easy, wrap in double quotes and you're done, as there's no
98
facility to create files with quotes in their names.
109
1110
Unix-likes are a little more complicated, wrap in single quotes and escape
12-
any single quotes in the filename.
11+
any single quotes in the filename. The '"'"' construction ends the quoted
12+
block, creates a new " quoted string with ' in it. So, `foo'bar` becomes
13+
`'foo'"'"'bar'`, which is the bash way of saying `'foo' + "'" + 'bar'`.
1314
*/
1415

15-
module.exports = escapify
16+
const winQuote = str => !/ /.test(str) ? str : '"' + str + '"'
17+
const winEsc = str => normalize(str).split(/\\/).map(winQuote).join('\\')
1618

17-
function windowsQuotes (str) {
18-
if (!/ /.test(str)) return str
19-
return '"' + str + '"'
20-
}
21-
22-
function escapify (str) {
23-
if (isWindows) {
24-
return path.normalize(str).split(/\\/).map(windowsQuotes).join('\\')
25-
} else if (/[^-_.~/\w]/.test(str)) {
26-
return "'" + str.replace(/'/g, "'\"'\"'") + "'"
27-
} else {
28-
return str
29-
}
30-
}
19+
module.exports = str => isWindows ? winEsc(str)
20+
: /[^-_.~/\w]/.test(str) ? "'" + str.replace(/'/g, `'"'"'`) + "'"
21+
: str

test/lib/utils/escape-exec-path.js

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const requireInject = require('require-inject')
2+
const t = require('tap')
3+
const getEscape = win => requireInject('../../../lib/utils/escape-exec-path.js', {
4+
'../../../lib/utils/is-windows.js': win,
5+
path: require('path')[win ? 'win32' : 'posix']
6+
})
7+
8+
const winEscape = getEscape(true)
9+
const nixEscape = getEscape(false)
10+
11+
t.equal(winEscape('hello/to the/world'), 'hello\\"to the"\\world')
12+
t.equal(nixEscape(`hello/to-the/world`), `hello/to-the/world`)
13+
t.equal(nixEscape(`hello/to the/world`), `'hello/to the/world'`)
14+
t.equal(nixEscape(`hello/to%the/world`), `'hello/to%the/world'`)
15+
t.equal(nixEscape(`hello/to'the/world`), `'hello/to'"'"'the/world'`)

0 commit comments

Comments
 (0)