-
Notifications
You must be signed in to change notification settings - Fork 28.2k
/
escape.js
77 lines (64 loc) · 1.9 KB
/
escape.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict'
// eslint-disable-next-line max-len
// this code adapted from: https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
const cmd = (input, doubleEscape) => {
if (!input.length) {
return '""'
}
let result
if (!/[ \t\n\v"]/.test(input)) {
result = input
} else {
result = '"'
for (let i = 0; i <= input.length; ++i) {
let slashCount = 0
while (input[i] === '\\') {
++i
++slashCount
}
if (i === input.length) {
result += '\\'.repeat(slashCount * 2)
break
}
if (input[i] === '"') {
result += '\\'.repeat(slashCount * 2 + 1)
result += input[i]
} else {
result += '\\'.repeat(slashCount)
result += input[i]
}
}
result += '"'
}
// and finally, prefix shell meta chars with a ^
result = result.replace(/[ !^&()<>|"]/g, '^$&')
if (doubleEscape) {
result = result.replace(/[ !^&()<>|"]/g, '^$&')
}
// except for % which is escaped with another %, and only once
result = result.replace(/%/g, '%%')
return result
}
const sh = (input) => {
if (!input.length) {
return `''`
}
if (!/[\t\n\r "#$&'()*;<>?\\`|~]/.test(input)) {
return input
}
// replace single quotes with '\'' and wrap the whole result in a fresh set of quotes
const result = `'${input.replace(/'/g, `'\\''`)}'`
// if the input string already had single quotes around it, clean those up
.replace(/^(?:'')+(?!$)/, '')
.replace(/\\'''/g, `\\'`)
return result
}
// disabling the no-control-regex rule for this line as we very specifically _do_ want to
// replace those characters if they somehow exist at this point, which is highly unlikely
// eslint-disable-next-line no-control-regex
const filename = (input) => input.replace(/[<>:"/\\|?*\x00-\x31]/g, '')
module.exports = {
cmd,
sh,
filename,
}