-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
index.js
42 lines (40 loc) · 1.21 KB
/
index.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
exports.quote = function (xs) {
return xs.map(function (s) {
if (/["\s]/.test(s) && !/'/.test(s)) {
return "'" + s.replace(/(['\\])/g, '\\$1') + "'";
}
else if (/["'\s]/.test(s)) {
return '"' + s.replace(/(["\\$`(){}!#&*|])/g, '\\$1') + '"';
}
else {
return s.replace(/([\\$`(){}!#&*|])/g, '\\$1');
}
}).join(' ');
};
exports.parse = function (s, env) {
if (!env) env = {};
return s.match(/(['"])((\\\1|[^\1])*?)\1|(\\ |\S)+/g)
.map(function (s) {
if (/^'/.test(s)) {
return s
.replace(/^'|'$/g, '')
.replace(/\\(["'\\$`(){}!#&*|])/g, '$1')
;
}
else if (/^"/.test(s)) {
return interpolate(s.replace(/^"|"$/g, ''));
}
else return interpolate(s);
})
;
function interpolate (s) {
return s
.replace(/(^|[^\\])\$(\w+)/g, getVar)
.replace(/(^|[^\\])\${(\w+)}/g, getVar)
.replace(/\\([ "'\\$`(){}!#&*|])/g, '$1')
;
}
function getVar (_, pre, key) {
return pre + String(env[key] || '');
}
};