@taskade/cli 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +154 -2
- package/bin/cli.mjs +25 -0
- package/package.json +37 -4
- package/src/cli.mjs +146 -0
- package/src/clients.mjs +176 -0
- package/src/config-file.mjs +250 -0
- package/src/doctor.mjs +373 -0
- package/src/plug.mjs +354 -0
- package/src/system.mjs +142 -0
package/src/plug.mjs
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
// `taskade plug <client>`: connect one MCP client to the Taskade server.
|
|
2
|
+
// Sign-in (OAuth) is the default, and no token goes anywhere.
|
|
3
|
+
// `--token` puts a personal access token from TASKADE_TOKEN in a header.
|
|
4
|
+
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
CLIENTS,
|
|
8
|
+
RUN,
|
|
9
|
+
SERVER_NAME,
|
|
10
|
+
TOKEN_PAGE,
|
|
11
|
+
claudeUserFile,
|
|
12
|
+
codexConfigFile,
|
|
13
|
+
expectedEntry,
|
|
14
|
+
findClient,
|
|
15
|
+
readCodexEntry,
|
|
16
|
+
serverUrl,
|
|
17
|
+
} from "./clients.mjs";
|
|
18
|
+
import { deepEqual, lineDiff, mergedText, readConfig, writeConfig } from "./config-file.mjs";
|
|
19
|
+
import { copyToClipboard, getEnv, homeDir, mask, runCommand, tildify, which } from "./system.mjs";
|
|
20
|
+
|
|
21
|
+
/** Replace every Bearer value in a text with its first 6 characters. */
|
|
22
|
+
export function redact(text) {
|
|
23
|
+
return String(text).replace(/(Bearer\s+)([^\s"'\\]+)/g, (_, prefix, secret) => prefix + mask(secret));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function show(value) {
|
|
27
|
+
return JSON.stringify(value, null, 2)
|
|
28
|
+
.split("\n")
|
|
29
|
+
.map((line) => " " + line)
|
|
30
|
+
.join("\n");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function commandLine(file, args) {
|
|
34
|
+
return [file, ...args].map((a) => (/^[\w\-.:/=@]+$/.test(a) ? a : `'${a.replace(/'/g, "'\\''")}'`)).join(" ");
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function plug(io, opts) {
|
|
38
|
+
const out = (text = "") => io.stdout.write(redact(text) + "\n");
|
|
39
|
+
const fail = (text) => {
|
|
40
|
+
io.stderr.write(redact(text) + "\n");
|
|
41
|
+
return 1;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
if (!opts.client) return listClients(io, out);
|
|
45
|
+
|
|
46
|
+
const client = findClient(opts.client);
|
|
47
|
+
if (!client) {
|
|
48
|
+
return fail(`Unknown client: ${opts.client}\nKnown clients: ${CLIENTS.map((c) => c.id).join(", ")}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
let url;
|
|
52
|
+
try {
|
|
53
|
+
url = serverUrl(io);
|
|
54
|
+
} catch (err) {
|
|
55
|
+
return fail(err.message);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
let token = null;
|
|
59
|
+
if (opts.token) {
|
|
60
|
+
if (client.id === "claude-desktop") {
|
|
61
|
+
return fail("Claude Desktop signs in through your browser. It takes no token from this CLI.");
|
|
62
|
+
}
|
|
63
|
+
token = (getEnv(io.env, "TASKADE_TOKEN") || "").trim();
|
|
64
|
+
if (!token) return fail(`--token reads the token from TASKADE_TOKEN, and TASKADE_TOKEN is not set.\nCreate a token at ${TOKEN_PAGE}`);
|
|
65
|
+
if (/\s/.test(token)) return fail("TASKADE_TOKEN holds a space or a line break. Set it to the token only.");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const mode = opts.print ? "print" : opts.yes ? "yes" : io.interactive ? "ask" : "print";
|
|
69
|
+
const flags = [opts.project && "--project", opts.token && "--token"].filter(Boolean);
|
|
70
|
+
const applyHint = `Nothing changed. To apply it, run: ${[RUN, "plug", client.id, ...flags, "--yes"].join(" ")}`;
|
|
71
|
+
const ctx = { io, opts, out, fail, url, token, mode, applyHint, client };
|
|
72
|
+
|
|
73
|
+
switch (client.id) {
|
|
74
|
+
case "claude-code":
|
|
75
|
+
return plugClaudeCode(ctx);
|
|
76
|
+
case "codex":
|
|
77
|
+
return plugCodex(ctx);
|
|
78
|
+
case "cursor":
|
|
79
|
+
return plugJsonFile(ctx, {
|
|
80
|
+
file: join(opts.project ? io.cwd : homeDir(io), ".cursor", "mcp.json"),
|
|
81
|
+
key: "mcpServers",
|
|
82
|
+
next: token
|
|
83
|
+
? "Next: open Cursor Settings, then MCP. Cursor sends your token, so no sign-in is needed."
|
|
84
|
+
: "Next: open Cursor Settings, then MCP. Find taskade and sign in when Cursor asks.",
|
|
85
|
+
});
|
|
86
|
+
case "vscode":
|
|
87
|
+
if (opts.project) {
|
|
88
|
+
return plugJsonFile(ctx, {
|
|
89
|
+
file: join(io.cwd, ".vscode", "mcp.json"),
|
|
90
|
+
key: "servers",
|
|
91
|
+
next: token
|
|
92
|
+
? "Next: open .vscode/mcp.json in VS Code and click Start above taskade. VS Code sends your token."
|
|
93
|
+
: "Next: open .vscode/mcp.json in VS Code, click Start above taskade, and sign in when VS Code asks.",
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return plugVsCodeUser(ctx);
|
|
97
|
+
case "claude-desktop":
|
|
98
|
+
return plugClaudeDesktop(ctx);
|
|
99
|
+
default:
|
|
100
|
+
return fail(`Unknown client: ${opts.client}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function listClients(io, out) {
|
|
105
|
+
const found = CLIENTS.filter((c) => c.detect(io));
|
|
106
|
+
const missing = CLIENTS.filter((c) => !found.includes(c));
|
|
107
|
+
if (found.length === 0) {
|
|
108
|
+
out("No supported MCP client found on this machine.");
|
|
109
|
+
} else {
|
|
110
|
+
out("MCP clients on this machine:");
|
|
111
|
+
const width = Math.max(...found.map((c) => c.name.length));
|
|
112
|
+
for (const c of found) out(` ${c.name.padEnd(width)} ${RUN} plug ${c.id}`);
|
|
113
|
+
}
|
|
114
|
+
if (missing.length) out(`Not found: ${missing.map((c) => `${c.name} (${c.id})`).join(", ")}.`);
|
|
115
|
+
out();
|
|
116
|
+
out("Each command shows the change first and asks before it changes anything.");
|
|
117
|
+
out("Nothing changed.");
|
|
118
|
+
return 0;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function tokenWarning(ctx, file, isProject) {
|
|
122
|
+
ctx.out(`Warning: ${file} will hold your token. Anyone who can read the file can use your Taskade account.`);
|
|
123
|
+
if (isProject) ctx.out(`Do not commit ${file}. Add it to .gitignore.`);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function confirm(ctx, question) {
|
|
127
|
+
if (ctx.mode === "yes") return true;
|
|
128
|
+
const ok = await ctx.io.ask(`${question} [y/N] `);
|
|
129
|
+
if (!ok) ctx.out("Nothing changed.");
|
|
130
|
+
return ok;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Claude Code: its own command. The default scope is "user", so the server
|
|
134
|
+
// works in every project. --project uses the "project" scope (.mcp.json).
|
|
135
|
+
async function plugClaudeCode(ctx) {
|
|
136
|
+
const { io, opts, out, fail, url, token } = ctx;
|
|
137
|
+
const scope = opts.project ? "project" : "user";
|
|
138
|
+
const args = ["mcp", "add", "--transport", "http", "--scope", scope, SERVER_NAME, url];
|
|
139
|
+
if (token) args.push("--header", `Authorization: Bearer ${token}`);
|
|
140
|
+
const file = opts.project ? join(io.cwd, ".mcp.json") : claudeUserFile(io);
|
|
141
|
+
const config = readConfig(file, "mcpServers");
|
|
142
|
+
const existing = config.data?.mcpServers?.[SERVER_NAME];
|
|
143
|
+
const expected = expectedEntry("claude-code", url, token);
|
|
144
|
+
|
|
145
|
+
out("Claude Code adds the server with its own command:");
|
|
146
|
+
out(` ${commandLine("claude", args)}`);
|
|
147
|
+
out(
|
|
148
|
+
opts.project
|
|
149
|
+
? "Claude Code writes the server to .mcp.json in this folder, to share with your team."
|
|
150
|
+
: "Claude Code keeps the server in ~/.claude.json, for all of your projects.",
|
|
151
|
+
);
|
|
152
|
+
if (token) tokenWarning(ctx, tildify(io, file), opts.project);
|
|
153
|
+
const signIn = token
|
|
154
|
+
? "Claude Code sends your token, so no sign-in is needed."
|
|
155
|
+
: "Next: start Claude Code, type /mcp, select taskade, and sign in.";
|
|
156
|
+
|
|
157
|
+
if (existing && deepEqual(existing, expected)) {
|
|
158
|
+
out("Claude Code already has this taskade server. Already connected. Nothing changed.");
|
|
159
|
+
if (!token) out(signIn.replace("Next: ", "To sign in again: "));
|
|
160
|
+
return 0;
|
|
161
|
+
}
|
|
162
|
+
if (existing) {
|
|
163
|
+
out(`Claude Code already has a different server named taskade in ${tildify(io, file)}.`);
|
|
164
|
+
out("Current entry:");
|
|
165
|
+
out(show(existing));
|
|
166
|
+
out("New entry:");
|
|
167
|
+
out(show(expected));
|
|
168
|
+
out(`The CLI removes the current entry first: claude mcp remove --scope ${scope} taskade`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const bin = which(io, "claude");
|
|
172
|
+
if (!bin) {
|
|
173
|
+
out("The claude command is not on your PATH.");
|
|
174
|
+
out("Install Claude Code (https://code.claude.com/docs/en/setup), then run the command above.");
|
|
175
|
+
return 0;
|
|
176
|
+
}
|
|
177
|
+
if (ctx.mode === "print") {
|
|
178
|
+
out(ctx.applyHint);
|
|
179
|
+
return 0;
|
|
180
|
+
}
|
|
181
|
+
if (!(await confirm(ctx, existing ? "Replace the entry and run this command?" : "Run this command?"))) return 0;
|
|
182
|
+
|
|
183
|
+
if (existing) {
|
|
184
|
+
const removed = await runCommand(io, bin, ["mcp", "remove", "--scope", scope, SERVER_NAME]);
|
|
185
|
+
if (removed.code !== 0) return fail(`claude mcp remove failed (${removed.error || `exit code ${removed.code}`}).`);
|
|
186
|
+
}
|
|
187
|
+
const added = await runCommand(io, bin, args);
|
|
188
|
+
if (added.code !== 0) return fail(`claude mcp add failed (${added.error || `exit code ${added.code}`}).`);
|
|
189
|
+
out(`Done. ${signIn}`);
|
|
190
|
+
return 0;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Codex: `codex mcp add` then `codex mcp login`. A new Codex starts the
|
|
194
|
+
// sign-in inside `mcp add`. Then the CLI does not run `mcp login` again.
|
|
195
|
+
async function plugCodex(ctx) {
|
|
196
|
+
const { io, opts, out, fail, url, token } = ctx;
|
|
197
|
+
if (opts.project) return fail("Codex has no --project option here. Codex keeps MCP servers in ~/.codex/config.toml.");
|
|
198
|
+
const args = ["mcp", "add", SERVER_NAME, "--url", url];
|
|
199
|
+
if (token) args.push("--bearer-token-env-var", "TASKADE_TOKEN");
|
|
200
|
+
const login = ["mcp", "login", SERVER_NAME];
|
|
201
|
+
const file = codexConfigFile(io);
|
|
202
|
+
const existing = readCodexEntry(file);
|
|
203
|
+
const expected = expectedEntry("codex", url, token);
|
|
204
|
+
|
|
205
|
+
out("Codex adds the server with its own commands:");
|
|
206
|
+
out(` ${commandLine("codex", args)}`);
|
|
207
|
+
if (!token) out(` ${commandLine("codex", login)}`);
|
|
208
|
+
if (token) {
|
|
209
|
+
out("Codex reads the token from TASKADE_TOKEN each time it starts. The config file holds only the variable name.");
|
|
210
|
+
out("Set TASKADE_TOKEN in the environment where Codex runs.");
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (existing && deepEqual(existing, expected)) {
|
|
214
|
+
out("Codex already has this taskade server. Already connected. Nothing changed.");
|
|
215
|
+
if (!token) out("If Codex asks you to sign in, run: codex mcp login taskade");
|
|
216
|
+
return 0;
|
|
217
|
+
}
|
|
218
|
+
if (existing) {
|
|
219
|
+
out(`Codex already has a different server named taskade in ${tildify(io, file)}.`);
|
|
220
|
+
out("Current entry:");
|
|
221
|
+
out(show(existing));
|
|
222
|
+
out("New entry:");
|
|
223
|
+
out(show(expected));
|
|
224
|
+
out("codex mcp add replaces the current entry.");
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const bin = which(io, "codex");
|
|
228
|
+
if (!bin) {
|
|
229
|
+
out("The codex command is not on your PATH.");
|
|
230
|
+
out("Install Codex (npm install -g @openai/codex, see https://github.com/openai/codex), then run the commands above.");
|
|
231
|
+
return 0;
|
|
232
|
+
}
|
|
233
|
+
if (ctx.mode === "print") {
|
|
234
|
+
out(ctx.applyHint);
|
|
235
|
+
return 0;
|
|
236
|
+
}
|
|
237
|
+
if (!(await confirm(ctx, existing ? "Replace the entry and run these commands?" : "Run these commands?"))) return 0;
|
|
238
|
+
|
|
239
|
+
const added = await runCommand(io, bin, args, { capture: true });
|
|
240
|
+
if (added.code !== 0) return fail(`codex mcp add failed (${added.error || `exit code ${added.code}`}).`);
|
|
241
|
+
if (!token && !/logged in/i.test(added.out)) {
|
|
242
|
+
const signedIn = await runCommand(io, bin, login);
|
|
243
|
+
if (signedIn.code !== 0) {
|
|
244
|
+
return fail("The sign-in did not finish. The server is added. Run this to sign in: codex mcp login taskade");
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
out("Done. Start Codex and type /mcp to see the taskade server.");
|
|
248
|
+
return 0;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// VS Code without --project: its own command adds the server to the user profile.
|
|
252
|
+
async function plugVsCodeUser(ctx) {
|
|
253
|
+
const { io, out, fail, url, token } = ctx;
|
|
254
|
+
const entry = { name: SERVER_NAME, ...expectedEntry("vscode", url, token) };
|
|
255
|
+
const args = ["--add-mcp", JSON.stringify(entry)];
|
|
256
|
+
|
|
257
|
+
out("VS Code adds the server to your user profile with its own command:");
|
|
258
|
+
out(` ${commandLine("code", args)}`);
|
|
259
|
+
if (token) tokenWarning(ctx, "your VS Code user profile", false);
|
|
260
|
+
|
|
261
|
+
const bin = which(io, "code");
|
|
262
|
+
if (!bin) {
|
|
263
|
+
out("The code command is not on your PATH.");
|
|
264
|
+
out("Add it (https://code.visualstudio.com/docs/configure/command-line), then run the command above.");
|
|
265
|
+
out(`Or write .vscode/mcp.json in this folder: ${RUN} plug vscode --project`);
|
|
266
|
+
return 0;
|
|
267
|
+
}
|
|
268
|
+
if (ctx.mode === "print") {
|
|
269
|
+
out(ctx.applyHint);
|
|
270
|
+
return 0;
|
|
271
|
+
}
|
|
272
|
+
if (!(await confirm(ctx, "Run this command?"))) return 0;
|
|
273
|
+
const added = await runCommand(io, bin, args);
|
|
274
|
+
if (added.code !== 0) return fail(`code --add-mcp failed (${added.error || `exit code ${added.code}`}).`);
|
|
275
|
+
out(
|
|
276
|
+
token
|
|
277
|
+
? "Done. Open VS Code and use the Taskade tools in Copilot Chat agent mode."
|
|
278
|
+
: "Done. In VS Code, run MCP: List Servers, start taskade, and sign in when VS Code asks.",
|
|
279
|
+
);
|
|
280
|
+
return 0;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Claude Desktop keeps a remote server as a connector in the Claude account.
|
|
284
|
+
// No supported file entry adds a remote server with sign-in, so the CLI
|
|
285
|
+
// gives the steps and copies the URL.
|
|
286
|
+
async function plugClaudeDesktop(ctx) {
|
|
287
|
+
const { io, opts, out, fail, url, mode } = ctx;
|
|
288
|
+
if (opts.project) return fail("Claude Desktop has no project file.");
|
|
289
|
+
out("Claude Desktop adds a remote server as a custom connector in the app. Do these 3 steps:");
|
|
290
|
+
out(" 1. In Claude Desktop, open Customize, then Connectors. Older versions: Settings, then Connectors.");
|
|
291
|
+
out(` 2. Click "+ Add", then "Add custom connector". Type Taskade as the name and paste ${url} as the URL.`);
|
|
292
|
+
out(' Keep the default sign-in settings and click "Continue" until you can click "Add".');
|
|
293
|
+
out(" 3. Click Connect, sign in to Taskade, and allow access.");
|
|
294
|
+
out("Claude keeps connectors in your Claude account, not in a file on this machine. This CLI cannot add one for you.");
|
|
295
|
+
if (mode === "print") return 0;
|
|
296
|
+
const tool = await copyToClipboard(io, url);
|
|
297
|
+
out(tool ? `Copied ${url} to the clipboard (${tool}).` : "No clipboard command found. Copy the URL from step 2.");
|
|
298
|
+
return 0;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// A client that reads a JSON file: merge one entry and keep everything else.
|
|
302
|
+
async function plugJsonFile(ctx, { file, key, next }) {
|
|
303
|
+
const { io, opts, out, fail, url, token, client, mode } = ctx;
|
|
304
|
+
const entry = expectedEntry(client.id, url, token);
|
|
305
|
+
const shown = tildify(io, file);
|
|
306
|
+
const block = JSON.stringify({ [key]: { [SERVER_NAME]: entry } }, null, 2);
|
|
307
|
+
const config = readConfig(file, key);
|
|
308
|
+
|
|
309
|
+
out(`${client.name} reads ${shown}.`);
|
|
310
|
+
if (config.error) {
|
|
311
|
+
fail(`${shown}: ${config.error}. Nothing changed.`);
|
|
312
|
+
fail("Fix the file, or add this entry by hand:");
|
|
313
|
+
fail(block);
|
|
314
|
+
return 1;
|
|
315
|
+
}
|
|
316
|
+
const existing = config.data[key]?.[SERVER_NAME];
|
|
317
|
+
if (existing && deepEqual(existing, entry)) {
|
|
318
|
+
out("The file already has this taskade entry. Already connected. Nothing changed.");
|
|
319
|
+
return 0;
|
|
320
|
+
}
|
|
321
|
+
if (token) tokenWarning(ctx, shown, opts.project);
|
|
322
|
+
|
|
323
|
+
if (mode === "print") {
|
|
324
|
+
if (existing) {
|
|
325
|
+
out("The file has a different taskade entry:");
|
|
326
|
+
out(show(existing));
|
|
327
|
+
out("Replace it with this entry:");
|
|
328
|
+
} else {
|
|
329
|
+
out(config.exists ? "Add this entry to the file:" : "Create the file with this content:");
|
|
330
|
+
}
|
|
331
|
+
out(block);
|
|
332
|
+
if (token) out("The block shows only the start of your token. Write the file with --yes to put the full token in it.");
|
|
333
|
+
out(next);
|
|
334
|
+
out(ctx.applyHint);
|
|
335
|
+
return 0;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const text = mergedText(config, key, SERVER_NAME, entry);
|
|
339
|
+
out(config.exists ? "The change:" : "The new file:");
|
|
340
|
+
if (existing) out("The file has a different taskade entry. The - lines show it and the + lines show the new entry.");
|
|
341
|
+
out(lineDiff(config.exists ? config.text : "", text));
|
|
342
|
+
if (!(await confirm(ctx, `Write ${shown}?`))) return 0;
|
|
343
|
+
|
|
344
|
+
let backup;
|
|
345
|
+
try {
|
|
346
|
+
backup = writeConfig(file, text, { newMode: token ? 0o600 : 0o644 });
|
|
347
|
+
} catch (err) {
|
|
348
|
+
return fail(`Cannot write ${shown}: ${err.message}. Nothing changed.`);
|
|
349
|
+
}
|
|
350
|
+
out(`Wrote ${shown}.`);
|
|
351
|
+
if (backup) out(`Backup: ${tildify(io, backup)}`);
|
|
352
|
+
out(next);
|
|
353
|
+
return 0;
|
|
354
|
+
}
|
package/src/system.mjs
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Small helpers that touch the machine: PATH lookup, child processes,
|
|
2
|
+
// the terminal prompt, the clipboard, and paths in the home folder.
|
|
3
|
+
// Every helper reads the environment from `io.env`, not from `process.env`,
|
|
4
|
+
// so that the tests can give the CLI a temporary HOME and PATH.
|
|
5
|
+
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import { existsSync, statSync } from "node:fs";
|
|
8
|
+
import { homedir } from "node:os";
|
|
9
|
+
import { delimiter, join } from "node:path";
|
|
10
|
+
import { createInterface } from "node:readline";
|
|
11
|
+
|
|
12
|
+
/** Read an environment variable without regard to case on Windows. */
|
|
13
|
+
export function getEnv(env, name) {
|
|
14
|
+
if (env[name] !== undefined) return env[name];
|
|
15
|
+
const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase());
|
|
16
|
+
return key === undefined ? undefined : env[key];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The home folder of the user. HOME on macOS and Linux, USERPROFILE on Windows. */
|
|
20
|
+
export function homeDir(io) {
|
|
21
|
+
const value = io.platform === "win32" ? getEnv(io.env, "USERPROFILE") : getEnv(io.env, "HOME");
|
|
22
|
+
return value || homedir();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Show a path with ~ for the home folder. */
|
|
26
|
+
export function tildify(io, file) {
|
|
27
|
+
const home = homeDir(io);
|
|
28
|
+
return file.startsWith(home + (io.platform === "win32" ? "\\" : "/")) ? "~" + file.slice(home.length) : file;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Find a command on PATH. Returns the full path, or null. */
|
|
32
|
+
export function which(io, name) {
|
|
33
|
+
const dirs = (getEnv(io.env, "PATH") || "").split(io.platform === "win32" ? ";" : delimiter).filter(Boolean);
|
|
34
|
+
const exts =
|
|
35
|
+
io.platform === "win32" ? (getEnv(io.env, "PATHEXT") || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
|
|
36
|
+
for (const dir of dirs) {
|
|
37
|
+
for (const ext of exts) {
|
|
38
|
+
const candidate = join(dir, name + ext.toLowerCase());
|
|
39
|
+
try {
|
|
40
|
+
if (statSync(candidate).isFile()) return candidate;
|
|
41
|
+
} catch {
|
|
42
|
+
// Not in this folder.
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function exists(file) {
|
|
50
|
+
return existsSync(file);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// cmd.exe gives a special meaning to these characters even inside quotes.
|
|
54
|
+
const CMD_UNSAFE = /[%^&|<>!\r\n]/;
|
|
55
|
+
|
|
56
|
+
function quoteForCmd(arg) {
|
|
57
|
+
if (/^[\w\-.:/=@]+$/.test(arg)) return arg;
|
|
58
|
+
return '"' + arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1") + '"';
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Run a command with the terminal of the user. Returns the exit code and,
|
|
63
|
+
* when `capture` is true, the text that the command wrote to stdout.
|
|
64
|
+
* The captured text is also shown to the user as it arrives.
|
|
65
|
+
*/
|
|
66
|
+
export function runCommand(io, file, args, { capture = false } = {}) {
|
|
67
|
+
return new Promise((resolve) => {
|
|
68
|
+
let child;
|
|
69
|
+
const stdio = ["inherit", capture ? "pipe" : "inherit", "inherit"];
|
|
70
|
+
// Windows runs a .cmd or .bat file only through cmd.exe.
|
|
71
|
+
if (io.platform === "win32" && /\.(cmd|bat)$/i.test(file)) {
|
|
72
|
+
if ([file, ...args].some((a) => CMD_UNSAFE.test(a))) {
|
|
73
|
+
resolve({ code: -1, out: "", error: "an argument holds a character that cmd.exe changes" });
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const line = [file, ...args].map(quoteForCmd).join(" ");
|
|
77
|
+
child = spawn(line, { env: io.env, cwd: io.cwd, stdio, shell: true, windowsHide: true });
|
|
78
|
+
} else {
|
|
79
|
+
child = spawn(file, args, { env: io.env, cwd: io.cwd, stdio });
|
|
80
|
+
}
|
|
81
|
+
let out = "";
|
|
82
|
+
if (capture) {
|
|
83
|
+
child.stdout.setEncoding("utf8");
|
|
84
|
+
child.stdout.on("data", (chunk) => {
|
|
85
|
+
out += chunk;
|
|
86
|
+
io.stdout.write(chunk);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
child.on("error", (err) => resolve({ code: -1, out, error: err.message }));
|
|
90
|
+
child.on("close", (code) => resolve({ code: code ?? -1, out }));
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Copy text to the clipboard. Returns the name of the command, or null. */
|
|
95
|
+
export async function copyToClipboard(io, text) {
|
|
96
|
+
const candidates =
|
|
97
|
+
io.platform === "darwin"
|
|
98
|
+
? [["pbcopy", []]]
|
|
99
|
+
: io.platform === "win32"
|
|
100
|
+
? [["clip", []]]
|
|
101
|
+
: [
|
|
102
|
+
["wl-copy", []],
|
|
103
|
+
["xclip", ["-selection", "clipboard"]],
|
|
104
|
+
];
|
|
105
|
+
for (const [name, args] of candidates) {
|
|
106
|
+
if (name === "wl-copy" && !getEnv(io.env, "WAYLAND_DISPLAY")) continue;
|
|
107
|
+
const file = which(io, name);
|
|
108
|
+
if (!file) continue;
|
|
109
|
+
const ok = await new Promise((resolve) => {
|
|
110
|
+
const shell = io.platform === "win32" && /\.(cmd|bat)$/i.test(file);
|
|
111
|
+
const child = spawn(shell ? `"${file}"` : file, args, {
|
|
112
|
+
env: io.env,
|
|
113
|
+
stdio: ["pipe", "ignore", "ignore"],
|
|
114
|
+
shell,
|
|
115
|
+
windowsHide: true,
|
|
116
|
+
});
|
|
117
|
+
child.on("error", () => resolve(false));
|
|
118
|
+
child.on("close", (code) => resolve(code === 0));
|
|
119
|
+
child.stdin.end(text);
|
|
120
|
+
});
|
|
121
|
+
if (ok) return name;
|
|
122
|
+
}
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Ask a yes or no question on the terminal. Only "y" or "yes" is a yes. */
|
|
127
|
+
export function askOnTerminal(question, input = process.stdin, output = process.stderr) {
|
|
128
|
+
return new Promise((resolve) => {
|
|
129
|
+
const rl = createInterface({ input, output });
|
|
130
|
+
// Resolve before close: close() emits "close" at once, and that handler means "no answer".
|
|
131
|
+
rl.question(question, (answer) => {
|
|
132
|
+
resolve(/^y(es)?$/i.test(answer.trim()));
|
|
133
|
+
rl.close();
|
|
134
|
+
});
|
|
135
|
+
rl.on("close", () => resolve(false));
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Show the first 6 characters of a secret and an ellipsis. */
|
|
140
|
+
export function mask(secret) {
|
|
141
|
+
return secret.slice(0, 6) + "…";
|
|
142
|
+
}
|