-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsplitShellString.ts
More file actions
85 lines (82 loc) · 2.27 KB
/
splitShellString.ts
File metadata and controls
85 lines (82 loc) · 2.27 KB
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
78
79
80
81
82
83
84
85
/**
* Processes a quoted string, handling escape sequences
*
* @param {string} str - The input string containing the quoted segment.
* @param {number} start - The starting index of the quoted segment within the input string.
* @param {string} quote - The quote character used to delimit the quoted segment (e.g., '"' or "'").
* @returns {[string, number]} A tuple where the first element is the accumulated string and the second element is the position after the closing quote.
*/
export function processQuotedString(str: string, start: number, quote: string): [string, number] {
let accum = '';
let escaped = false;
for (let i = start; i < str.length; i++) {
const c = str[i];
if (escaped) {
if (c === quote) {
accum += c;
} else {
accum += '\\' + c;
}
escaped = false;
continue;
}
if (c === '\\') {
escaped = true;
continue;
}
if (c === quote) {
return [ accum, i+1 ];
}
accum += c;
}
if (escaped)
console.warn(`trailing backslash in '${str.slice(start)}'`)
console.warn(`unterminated ${quote}-quoted string '${str.slice(start)}'`);
return [ accum, str.length ];
}
/**
* Splits a shell command string into an array of arguments, handling quoted strings and escaped characters.
*
* @param {string} str - The shell command string to split.
* @returns {string[]} An array of arguments parsed from the input string.
*/
export function splitShellString(str: string): string[] {
let accum = '';
const result = [];
let escaped = false;
for (let i = 0; i < str.length; i++) {
const c = str[i];
if (escaped) {
accum += c;
escaped = false;
continue;
}
if (c === '\\') {
escaped = true;
continue;
}
if (c === '"') {
const [ value, next ] = processQuotedString(str, i + 1, '"');
accum += value;
i = next - 1;
continue;
}
if (c === "'") {
const [ value, next ] = processQuotedString(str, i + 1, "'");
accum += value;
i = next - 1;
continue;
}
if (c === ' ' || c === '\t') {
result.push(accum);
accum = '';
continue;
}
accum += c;
}
if (escaped)
console.warn(`trailing backslash in '${str}'`)
if (accum)
result.push(accum);
return result;
}