-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathbin.ts
321 lines (298 loc) · 9.43 KB
/
bin.ts
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/env node
// Copyright 2024 the JSR authors. MIT license.
import * as kl from "kolorist";
import * as fs from "node:fs";
import * as path from "node:path";
import { parseArgs } from "node:util";
import {
install,
publish,
remove,
runScript,
showPackageInfo,
} from "./commands";
import {
DenoJson,
ExecError,
findProjectDir,
JsrPackage,
JsrPackageNameError,
NpmPackage,
Package,
prettyTime,
readJson,
setDebug,
} from "./utils";
import { PkgManagerName } from "./pkg_manager";
const args = process.argv.slice(2);
function prettyPrintRow(rows: [string, string][]) {
let max = 0;
for (let i = 0; i < rows.length; i++) {
const len = rows[i][0].length;
max = len > max ? len : max;
}
return rows
.map((row) => ` ${kl.green(row[0].padStart(max))} ${row[1]}`)
.join("\n");
}
function printHelp() {
console.log(`jsr.io cli for node
Usage:
${
prettyPrintRow([
["jsr add @std/log", 'Install the "@std/log" package from jsr.io.'],
[
"jsr remove @std/log",
'Remove the "@std/log" package from the project.',
],
])
}
Commands:
${
prettyPrintRow([
["<script>", "Run a script from the package.json file"],
["run <script>", "Run a script from the package.json file"],
["i, install, add", "Install one or more JSR packages."],
["r, uninstall, remove", "Remove one or more JSR packages."],
["publish", "Publish a package to the JSR registry."],
["info, show, view", "Show package information."],
])
}
Options:
${
prettyPrintRow([
[
"-P, --save-prod",
"Package will be added to dependencies. This is the default.",
],
["-D, --save-dev", "Package will be added to devDependencies."],
["-O, --save-optional", "Package will be added to optionalDependencies."],
["--npm", "Use npm to remove and install packages."],
["--yarn", "Use yarn to remove and install packages."],
["--pnpm", "Use pnpm to remove and install packages."],
["--bun", "Use bun to remove and install packages."],
[
"--from-jsr-config",
"Install 'jsr:*' and 'npm:*' packages from jsr config file as npm packages.",
],
["--verbose", "Show additional debugging information."],
["-h, --help", "Show this help text."],
["-v, --version", "Print the version number."],
])
}
Publish Options:
${
prettyPrintRow([
[
"--token <Token>",
"The API token to use when publishing. If unset, interactive authentication will be used.",
],
[
"--dry-run",
"Prepare the package for publishing performing all checks and validations without uploading.",
],
["--allow-slow-types", "Allow publishing with slow types."],
[
"--provenance",
"From CI/CD system, publicly links the package to where it was built and published from.",
],
])
}
Environment variables:
${
prettyPrintRow([
["JSR_URL", "Use a different registry URL for the publish command."],
[
"DENO_BIN_PATH",
"Use specified Deno binary instead of local downloaded one.",
],
])
}
`);
}
function getPackages(positionals: string[], allowEmpty: boolean): JsrPackage[] {
const pkgArgs = positionals.slice(1);
const packages = pkgArgs.map((p) => JsrPackage.from(p));
if (!allowEmpty && pkgArgs.length === 0) {
console.error(kl.red(`Missing packages argument.`));
console.log();
printHelp();
process.exit(1);
}
return packages;
}
if (args.length === 0) {
printHelp();
process.exit(0);
} else if (args.some((arg) => arg === "-h" || arg === "--help")) {
printHelp();
process.exit(0);
} else if (args.some((arg) => arg === "-v" || arg === "--version")) {
const version = JSON.parse(
fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf-8"),
).version as string;
console.log(version);
process.exit(0);
} else {
const cmd = args[0];
// Bypass cli argument validation for publish command. The underlying
// `deno publish` cli is under active development and args may change
// frequently.
if (cmd === "publish") {
const binFolder = path.join(__dirname, "..", ".download");
run(async () => {
const projectInfo = await findProjectDir(process.cwd());
return publish(process.cwd(), {
binFolder,
publishArgs: args.slice(1),
pkgJsonPath: projectInfo.pkgJsonPath,
});
});
} else if (cmd === "view" || cmd === "show" || cmd === "info") {
const pkgName = args[1];
if (pkgName === undefined) {
console.log(kl.red(`Missing package name.`));
printHelp();
process.exit(1);
}
run(async () => {
await showPackageInfo(pkgName);
});
} else {
const options = parseArgs({
args,
allowPositionals: true,
options: {
"save-prod": { type: "boolean", default: true, short: "P" },
"save-dev": { type: "boolean", default: false, short: "D" },
"save-optional": { type: "boolean", default: false, short: "O" },
"dry-run": { type: "boolean", default: false },
"allow-slow-types": { type: "boolean", default: false },
"from-jsr-config": { type: "boolean", default: false },
token: { type: "string" },
config: { type: "string", short: "c" },
"no-config": { type: "boolean" },
check: { type: "string" },
"no-check": { type: "string" },
quiet: { type: "boolean", short: "q" },
npm: { type: "boolean", default: false },
yarn: { type: "boolean", default: false },
pnpm: { type: "boolean", default: false },
bun: { type: "boolean", default: false },
debug: { type: "boolean", default: false },
help: { type: "boolean", default: false, short: "h" },
version: { type: "boolean", default: false, short: "v" },
},
});
if (options.values.debug || process.env.DEBUG) {
setDebug(true);
}
if (options.positionals.length === 0) {
printHelp();
process.exit(0);
}
const pkgManagerName: PkgManagerName | null = options.values.pnpm
? "pnpm"
: options.values.yarn
? "yarn"
: options.values.bun
? "bun"
: options.values.npm
? "npm"
: null;
if (cmd === "i" || cmd === "install" || cmd === "add") {
run(async () => {
const packages: Package[] = getPackages(options.positionals, true);
if (options.values["from-jsr-config"]) {
if (packages.length > 0) {
console.error(
kl.red(
"The flag '--from-jsr-config' cannot be used when package names are passed to the install command.",
),
);
process.exit(1);
}
const projectInfo = await findProjectDir(process.cwd());
const jsrFile = projectInfo.jsrJsonPath || projectInfo.denoJsonPath;
if (jsrFile === null) {
console.error(
`Could not find either jsr.json, jsr.jsonc, deno.json or deno.jsonc file in the project.`,
);
process.exit(1);
}
const json = await readJson<DenoJson>(jsrFile);
if (json.imports !== null && typeof json.imports === "object") {
for (const specifier of Object.values(json.imports)) {
if (specifier.startsWith("jsr:")) {
const raw = specifier.slice("jsr:".length);
packages.push(JsrPackage.from(raw));
} else if (specifier.startsWith("npm:")) {
const raw = specifier.slice("npm:".length);
packages.push(NpmPackage.from(raw));
}
}
}
}
await install(packages, {
mode: options.values["save-dev"]
? "dev"
: options.values["save-optional"]
? "optional"
: "prod",
pkgManagerName,
});
});
} else if (cmd === "r" || cmd === "uninstall" || cmd === "remove") {
run(async () => {
const packages = getPackages(options.positionals, false);
await remove(packages, { pkgManagerName });
});
} else if (cmd === "run") {
const script = options.positionals[1];
if (!script) {
console.error(kl.red(`Missing script argument.`));
console.log();
printHelp();
process.exit(1);
}
run(async () => {
await runScript(process.cwd(), script, { pkgManagerName });
});
} else {
const packageJsonPath = path.join(process.cwd(), "package.json");
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(
fs.readFileSync(packageJsonPath, "utf-8"),
);
if (packageJson.scripts && packageJson.scripts[cmd]) {
run(async () => {
await runScript(process.cwd(), cmd, { pkgManagerName });
});
} else {
console.error(kl.red(`Unknown command: ${cmd}`));
console.log();
printHelp();
process.exit(1);
}
}
}
}
}
async function run(fn: () => Promise<void>) {
const start = Date.now();
try {
await fn();
const time = Date.now() - start;
console.log();
console.log(`${kl.green("Completed")} in ${prettyTime(time)}`);
} catch (err) {
if (err instanceof JsrPackageNameError) {
console.log(kl.red(err.message));
process.exit(1);
} else if (err instanceof ExecError) {
console.log(kl.red(err.message));
process.exit(err.code);
}
throw err;
}
}