forked from jackwener/OpenCLI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexternal.ts
More file actions
246 lines (213 loc) · 7.62 KB
/
external.ts
File metadata and controls
246 lines (213 loc) · 7.62 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { fileURLToPath } from 'node:url';
import { spawnSync, execFileSync } from 'node:child_process';
import yaml from 'js-yaml';
import chalk from 'chalk';
import { log } from './logger.js';
import { EXIT_CODES, getErrorMessage } from './errors.js';
import { getUserExternalClisConfigPath } from './user-opencli-paths.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export interface ExternalCliInstall {
mac?: string;
linux?: string;
windows?: string;
default?: string;
}
export interface ExternalCliConfig {
name: string;
binary: string;
description?: string;
homepage?: string;
tags?: string[];
install?: ExternalCliInstall;
}
function getUserRegistryPath(): string {
return getUserExternalClisConfigPath();
}
let _cachedExternalClis: ExternalCliConfig[] | null = null;
export function loadExternalClis(): ExternalCliConfig[] {
if (_cachedExternalClis) return _cachedExternalClis;
const configs = new Map<string, ExternalCliConfig>();
// 1. Load built-in
const builtinPath = path.resolve(__dirname, 'external-clis.yaml');
try {
if (fs.existsSync(builtinPath)) {
const raw = fs.readFileSync(builtinPath, 'utf8');
const parsed = (yaml.load(raw) || []) as ExternalCliConfig[];
for (const item of parsed) configs.set(item.name, item);
}
} catch (err) {
log.warn(`Failed to parse built-in external-clis.yaml: ${getErrorMessage(err)}`);
}
// 2. Load user custom
const userPath = getUserRegistryPath();
try {
if (fs.existsSync(userPath)) {
const raw = fs.readFileSync(userPath, 'utf8');
const parsed = (yaml.load(raw) || []) as ExternalCliConfig[];
for (const item of parsed) {
configs.set(item.name, item); // Overwrite built-in if duplicated
}
}
} catch (err) {
log.warn(`Failed to parse user external-clis.yaml: ${getErrorMessage(err)}`);
}
_cachedExternalClis = Array.from(configs.values()).sort((a, b) => a.name.localeCompare(b.name));
return _cachedExternalClis;
}
export function isBinaryInstalled(binary: string): boolean {
try {
const isWindows = os.platform() === 'win32';
execFileSync(isWindows ? 'where' : 'which', [binary], { stdio: 'ignore' });
return true;
} catch {
return false;
}
}
export function getInstallCmd(installConfig?: ExternalCliInstall): string | null {
if (!installConfig) return null;
const platform = os.platform();
if (platform === 'darwin' && installConfig.mac) return installConfig.mac;
if (platform === 'linux' && installConfig.linux) return installConfig.linux;
if (platform === 'win32' && installConfig.windows) return installConfig.windows;
if (installConfig.default) return installConfig.default;
return null;
}
/**
* Safely parses a command string into a binary and argument list.
* Rejects commands containing shell operators (&&, ||, |, ;, >, <, `) that
* cannot be safely expressed as execFileSync arguments.
*
* Args:
* cmd: Raw command string from YAML config (e.g. "brew install gh")
*
* Returns:
* Object with `binary` and `args` fields, or throws on unsafe input.
*/
export function parseCommand(cmd: string): { binary: string; args: string[] } {
const shellOperators = /&&|\|\|?|;|[><`$#\n\r]|\$\(/;
if (shellOperators.test(cmd)) {
throw new Error(
`Install command contains unsafe shell operators and cannot be executed securely: "${cmd}". ` +
`Please install the tool manually.`
);
}
// Tokenise respecting single- and double-quoted segments (no variable expansion).
const tokens: string[] = [];
const re = /(?:"([^"]*)")|(?:'([^']*)')|(\S+)/g;
let match: RegExpExecArray | null;
while ((match = re.exec(cmd)) !== null) {
tokens.push(match[1] ?? match[2] ?? match[3]);
}
if (tokens.length === 0) {
throw new Error(`Install command is empty.`);
}
const [binary, ...args] = tokens;
return { binary, args };
}
function shouldRetryWithCmdShim(binary: string, err: unknown): boolean {
const code = err instanceof Error ? (err as NodeJS.ErrnoException).code : undefined;
return os.platform() === 'win32' && !path.extname(binary) && code === 'ENOENT';
}
function runInstallCommand(cmd: string): void {
const { binary, args } = parseCommand(cmd);
try {
execFileSync(binary, args, { stdio: 'inherit' });
} catch (err) {
if (shouldRetryWithCmdShim(binary, err)) {
execFileSync(`${binary}.cmd`, args, { stdio: 'inherit' });
return;
}
throw err;
}
}
export function installExternalCli(cli: ExternalCliConfig): boolean {
if (!cli.install) {
console.error(chalk.red(`No auto-install command configured for '${cli.name}'.`));
console.error(`Please install '${cli.binary}' manually.`);
return false;
}
const cmd = getInstallCmd(cli.install);
if (!cmd) {
console.error(chalk.red(`No install command for your platform (${os.platform()}) for '${cli.name}'.`));
if (cli.homepage) console.error(`See: ${cli.homepage}`);
return false;
}
console.log(chalk.cyan(`🔹 '${cli.name}' is not installed. Auto-installing...`));
console.log(chalk.dim(`$ ${cmd}`));
try {
runInstallCommand(cmd);
console.log(chalk.green(`✅ Installed '${cli.name}' successfully.\n`));
return true;
} catch (err) {
console.error(chalk.red(`❌ Failed to install '${cli.name}': ${getErrorMessage(err)}`));
return false;
}
}
export function executeExternalCli(name: string, args: string[], preloaded?: ExternalCliConfig[]): void {
const configs = preloaded ?? loadExternalClis();
const cli = configs.find((c) => c.name === name);
if (!cli) {
throw new Error(`External CLI '${name}' not found in registry.`);
}
// 1. Check if installed
if (!isBinaryInstalled(cli.binary)) {
// 2. Try to auto install
const success = installExternalCli(cli);
if (!success) {
process.exitCode = EXIT_CODES.SERVICE_UNAVAIL;
return;
}
}
// 3. Passthrough execution with stdio inherited
const result = spawnSync(cli.binary, args, { stdio: 'inherit' });
if (result.error) {
console.error(chalk.red(`Failed to execute '${cli.binary}': ${result.error.message}`));
process.exitCode = EXIT_CODES.GENERIC_ERROR;
return;
}
if (result.status !== null) {
process.exitCode = result.status;
}
}
export interface RegisterOptions {
binary?: string;
install?: string;
description?: string;
}
export function registerExternalCli(name: string, opts?: RegisterOptions): void {
const userPath = getUserRegistryPath();
const configDir = path.dirname(userPath);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
let items: ExternalCliConfig[] = [];
if (fs.existsSync(userPath)) {
try {
const raw = fs.readFileSync(userPath, 'utf8');
items = (yaml.load(raw) || []) as ExternalCliConfig[];
} catch {
// Ignore
}
}
const existingIndex = items.findIndex((c) => c.name === name);
const newItem: ExternalCliConfig = {
name,
binary: opts?.binary || name,
};
if (opts?.description) newItem.description = opts.description;
if (opts?.install) newItem.install = { default: opts.install };
if (existingIndex >= 0) {
items[existingIndex] = { ...items[existingIndex], ...newItem };
console.log(chalk.green(`Updated '${name}' in user registry.`));
} else {
items.push(newItem);
console.log(chalk.green(`Registered '${name}' in user registry.`));
}
const dump = yaml.dump(items, { indent: 2, sortKeys: true });
fs.writeFileSync(userPath, dump, 'utf8');
_cachedExternalClis = null; // Invalidate cache so next load reflects the change
console.log(chalk.dim(userPath));
}