shellwords
Version:
Manipulate strings according to the word parsing rules of the UNIX Bourne shell.
64 lines (63 loc) • 1.54 kB
JavaScript
// src/shellwords.ts
var scan = (string, pattern, callback) => {
let result = "";
while (string.length > 0) {
const match = string.match(pattern);
if (match && match.index != null && match[0] != null) {
result += string.slice(0, match.index);
result += callback(match);
string = string.slice(match.index + match[0].length);
} else {
result += string;
string = "";
}
}
return result;
};
var split = (line = "") => {
const words = [];
let field = "";
scan(
line,
/\s*(?:([^\s\\'"]+)|'((?:[^'\\]|\\.)*)'|"((?:[^"\\]|\\.)*)"|(\\.?)|(\S))(\s|$)?/,
(match) => {
const [_raw, word, sq, dq, escape2, garbage, separator] = match;
if (garbage != null) {
throw new Error(`Unmatched quote: ${line}`);
}
if (word) {
field += word;
} else {
let addition;
if (sq) {
addition = sq;
} else if (dq) {
addition = dq;
} else if (escape2) {
addition = escape2;
}
if (addition) {
field += addition.replace(/\\(?=.)/, "");
}
}
if (separator != null) {
words.push(field);
field = "";
}
}
);
if (field) {
words.push(field);
}
return words;
};
var escape = (str = "") => {
return str.replace(/([^A-Za-z0-9_\-.,:/@\n])/g, "\\$1").replace(/\n/g, "'\n'");
};
var join = (array) => array.map((element) => escape(element)).join(" ");
export {
escape,
join,
split
};
//# sourceMappingURL=index.js.map