马宇豪
2024-07-16 f591c27b57e2418c9495bc02ae8cfff84d35bc18
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
'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, '^$&')
  }
 
  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
}
 
module.exports = {
  cmd,
  sh,
}