UNPKG

856 BJavaScriptView Raw
1// take an un-split argv string and tokenize it.
2module.exports = function (argString) {
3 if (Array.isArray(argString)) {
4 return argString.map(e => typeof e !== 'string' ? e + '' : e)
5 }
6
7 argString = argString.trim()
8
9 let i = 0
10 let prevC = null
11 let c = null
12 let opening = null
13 const args = []
14
15 for (let ii = 0; ii < argString.length; ii++) {
16 prevC = c
17 c = argString.charAt(ii)
18
19 // split on spaces unless we're in quotes.
20 if (c === ' ' && !opening) {
21 if (!(prevC === ' ')) {
22 i++
23 }
24 continue
25 }
26
27 // don't split the string if we're in matching
28 // opening or closing single and double quotes.
29 if (c === opening) {
30 opening = null
31 } else if ((c === "'" || c === '"') && !opening) {
32 opening = c
33 }
34
35 if (!args[i]) args[i] = ''
36 args[i] += c
37 }
38
39 return args
40}