Skip to content

Commit

Permalink
unit test for escape-exec-path util
Browse files Browse the repository at this point in the history
  • Loading branch information
isaacs authored and ruyadorno committed Jul 29, 2020
1 parent 8b6d300 commit 468bbd3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 19 deletions.
29 changes: 10 additions & 19 deletions lib/utils/escape-exec-path.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict'
var path = require('path')
var isWindows = require('./is-windows.js')
const { normalize } = require('path')
const isWindows = require('./is-windows.js')

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

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

function windowsQuotes (str) {
if (!/ /.test(str)) return str
return '"' + str + '"'
}

function escapify (str) {
if (isWindows) {
return path.normalize(str).split(/\\/).map(windowsQuotes).join('\\')
} else if (/[^-_.~/\w]/.test(str)) {
return "'" + str.replace(/'/g, "'\"'\"'") + "'"
} else {
return str
}
}
module.exports = str => isWindows ? winEsc(str)
: /[^-_.~/\w]/.test(str) ? "'" + str.replace(/'/g, `'"'"'`) + "'"
: str
15 changes: 15 additions & 0 deletions test/lib/utils/escape-exec-path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const requireInject = require('require-inject')
const t = require('tap')
const getEscape = win => requireInject('../../../lib/utils/escape-exec-path.js', {
'../../../lib/utils/is-windows.js': win,
path: require('path')[win ? 'win32' : 'posix']
})

const winEscape = getEscape(true)
const nixEscape = getEscape(false)

t.equal(winEscape('hello/to the/world'), 'hello\\"to the"\\world')
t.equal(nixEscape(`hello/to-the/world`), `hello/to-the/world`)
t.equal(nixEscape(`hello/to the/world`), `'hello/to the/world'`)
t.equal(nixEscape(`hello/to%the/world`), `'hello/to%the/world'`)
t.equal(nixEscape(`hello/to'the/world`), `'hello/to'"'"'the/world'`)

0 comments on commit 468bbd3

Please sign in to comment.