-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy pathspawn-command-options.ts
More file actions
183 lines (160 loc) · 5.4 KB
/
Copy pathspawn-command-options.ts
File metadata and controls
183 lines (160 loc) · 5.4 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
export function readWindowsEnvValue(env: NodeJS.ProcessEnv, key: string): string | undefined {
const matchedKey = Object.keys(env).find((entry) => entry.toUpperCase() === key);
return matchedKey ? env[matchedKey] : undefined;
}
function windowsExecutableExtensions(env: NodeJS.ProcessEnv): string[] {
return (readWindowsEnvValue(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD")
.split(";")
.map((value) => value.trim().toLowerCase())
.filter((value) => value.length > 0);
}
function commandCandidates(command: string, env: NodeJS.ProcessEnv): string[] {
const commandExtension = path.extname(command);
if (commandExtension.length > 0) {
return [command];
}
return windowsExecutableExtensions(env).map((extension) => `${command}${extension}`);
}
function commandHasPath(command: string): boolean {
return command.includes("/") || command.includes("\\") || path.isAbsolute(command);
}
function resolveWindowsPathCommand(command: string, env: NodeJS.ProcessEnv): string | undefined {
const candidates = commandCandidates(command, env);
const pathValue = readWindowsEnvValue(env, "PATH");
if (!pathValue) {
return undefined;
}
for (const directory of pathValue.split(";")) {
const resolved = findExistingCommandInDirectory(directory, candidates);
if (resolved) {
return resolved;
}
}
return undefined;
}
function findExistingCommandInDirectory(
directory: string,
candidates: string[],
): string | undefined {
const trimmedDirectory = directory.trim();
if (trimmedDirectory.length === 0) {
return undefined;
}
return candidates
.map((candidate) => path.join(trimmedDirectory, candidate))
.find((resolved) => fs.existsSync(resolved));
}
function resolveWindowsWrapperToken(token: string, wrapperPath: string): string | undefined {
const relative = token.match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();
if (!relative) {
return undefined;
}
const candidate = path.resolve(
path.dirname(wrapperPath),
relative.replace(/[\\/]+/g, path.sep).replace(/^[\\/]+/, ""),
);
return path.extname(candidate).toLowerCase() === ".exe" && fs.existsSync(candidate)
? candidate
: undefined;
}
function resolveWindowsWrapperExecutable(wrapperPath: string): string | undefined {
if (!fs.existsSync(wrapperPath)) {
return undefined;
}
try {
const content = fs.readFileSync(wrapperPath, "utf8");
return [...content.matchAll(/"([^"\r\n]*)"/g)]
.map((match) => resolveWindowsWrapperToken(match[1] ?? "", wrapperPath))
.find((candidate): candidate is string => candidate !== undefined);
} catch {
// Ignore unreadable wrapper scripts and let callers use their fallback.
return undefined;
}
}
export function resolveWindowsCommand(
command: string,
env: NodeJS.ProcessEnv = process.env,
): string | undefined {
const candidates = commandCandidates(command, env);
if (commandHasPath(command)) {
return candidates.find((candidate) => fs.existsSync(candidate));
}
return resolveWindowsPathCommand(command, env);
}
/**
* Resolve a Windows command to a native executable suitable for direct spawn.
*
* Batch and PowerShell shims are intentionally rejected unless they point at a
* real `.exe` entrypoint. Callers that need shell execution should use the
* command-specific shell policy instead.
*/
export function resolveWindowsExecutablePath(
command: string,
env: NodeJS.ProcessEnv = process.env,
): string | undefined {
const resolved = resolveWindowsCommand(command, env);
if (!resolved) {
return undefined;
}
const absolute = path.resolve(resolved);
const extension = path.extname(absolute).toLowerCase();
if (extension === ".exe") {
return absolute;
}
if (extension !== ".cmd" && extension !== ".bat" && extension !== ".ps1") {
return undefined;
}
const siblingExecutable = `${absolute.slice(0, -extension.length)}.exe`;
return fs.existsSync(siblingExecutable)
? siblingExecutable
: resolveWindowsWrapperExecutable(absolute);
}
function shouldUseWindowsBatchShell(
command: string,
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): boolean {
if (platform !== "win32") {
return false;
}
const resolvedCommand = resolveWindowsCommand(command, env) ?? command;
const ext = path.extname(resolvedCommand).toLowerCase();
return ext === ".cmd" || ext === ".bat";
}
export function buildSpawnCommandOptions(
command: string,
options: Parameters<typeof spawn>[2],
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): Parameters<typeof spawn>[2] {
if (!shouldUseWindowsBatchShell(command, platform, env)) {
return options;
}
return {
...options,
shell: true,
};
}
export type TerminalSpawnCommand = {
command: string;
args: string[];
killProcessGroup: boolean;
};
export function buildTerminalSpawnCommand(
command: string,
args: string[] | undefined,
): TerminalSpawnCommand {
return { command, args: args ?? [], killProcessGroup: false };
}
export function buildTerminalShellSpawnCommand(
command: string,
platform: NodeJS.Platform = process.platform,
): TerminalSpawnCommand {
if (platform === "win32") {
return { command: "cmd.exe", args: ["/d", "/s", "/c", command], killProcessGroup: true };
}
return { command: "/bin/sh", args: ["-c", command], killProcessGroup: true };
}