-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutility.js
More file actions
95 lines (81 loc) · 2.32 KB
/
Copy pathutility.js
File metadata and controls
95 lines (81 loc) · 2.32 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
86
87
88
89
90
91
92
93
94
95
const path = require("path");
const os = require("os");
function tokenizeCommand(command) {
const tokens = [];
let currentToken = "";
let inDoubleQuotes = false;
let inSingleQuotes = false;
for (let i = 0; i < command.length; i++) {
const char = command[i];
const nextChar = command[i + 1];
if (char === "\\" && !inSingleQuotes && !inDoubleQuotes && nextChar) {
// Backslash outside quotes - always escapes the next character literally
currentToken += nextChar;
i++;
} else if (char === '"' && !inSingleQuotes) {
inDoubleQuotes = !inDoubleQuotes;
// Don't add the quote character to the token
} else if (char === "'" && !inDoubleQuotes) {
inSingleQuotes = !inSingleQuotes;
// Don't add the quote character to the token
} else if (char === "\\" && inDoubleQuotes && nextChar) {
// Backslash in double quotes - escape the next character
// Only escape special characters: ", ', \, $
if (nextChar === '"' || nextChar === "'" || nextChar === "\\" || nextChar === "$") {
currentToken += nextChar;
i++; // Skip the next character
} else {
currentToken += char;
}
} else if ((char === " " || char === "\t") && !inDoubleQuotes && !inSingleQuotes) {
if (currentToken) {
tokens.push(currentToken);
currentToken = "";
}
} else {
currentToken += char;
}
}
if (currentToken) {
tokens.push(currentToken);
}
return tokens;
}
function groupTokens(tokens) {
const groups = [];
let currentGroup = [];
for (const token of tokens) {
if (token === "|") {
if (currentGroup.length > 0) {
groups.push(currentGroup);
currentGroup = [];
}
} else {
currentGroup.push(token);
}
}
if (currentGroup.length > 0) {
groups.push(currentGroup);
}
return groups;
}
function computeAbsolutePath(pathStr) {
if (!pathStr) {
return process.cwd();
}
// Handle home directory
if (pathStr.startsWith("~")) {
pathStr = pathStr.replace("~", os.homedir());
}
// If already absolute, return as is
if (path.isAbsolute(pathStr)) {
return pathStr;
}
// Resolve relative to current working directory
return path.resolve(process.cwd(), pathStr);
}
module.exports = {
tokenizeCommand,
groupTokens,
computeAbsolutePath,
};