-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcli.ts
More file actions
executable file
·869 lines (793 loc) · 21.9 KB
/
cli.ts
File metadata and controls
executable file
·869 lines (793 loc) · 21.9 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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
import { Argument, Command, Option } from "commander";
import events from "node:events";
import fs from "node:fs";
import process from "node:process";
import { resolve } from "node:path";
import { getNetwork } from "./api/network.js";
import { cacheSize, cleanCache, show } from "./cache.js";
import { add } from "./commands/add.js";
import { bench } from "./commands/bench.js";
import { build } from "./commands/build.js";
import { bump } from "./commands/bump.js";
import { check } from "./commands/check.js";
import { checkCandid } from "./commands/check-candid.js";
import { checkStable } from "./commands/check-stable.js";
import { docsCoverage } from "./commands/docs-coverage.js";
import { docs } from "./commands/docs.js";
import { format } from "./commands/format.js";
import { info } from "./commands/info.js";
import { init } from "./commands/init.js";
import { lint } from "./commands/lint.js";
import { installAll } from "./commands/install/install-all.js";
import {
addMaintainer,
printMaintainers,
removeMaintainer,
} from "./commands/maintainer.js";
import { outdated } from "./commands/outdated.js";
import { addOwner, printOwners, removeOwner } from "./commands/owner.js";
import { publish } from "./commands/publish.js";
import { remove } from "./commands/remove.js";
import { search } from "./commands/search.js";
import * as self from "./commands/self.js";
import { sources } from "./commands/sources.js";
import { sync } from "./commands/sync.js";
import { template } from "./commands/template.js";
import { test } from "./commands/test/test.js";
import { toolchain } from "./commands/toolchain/index.js";
import { update } from "./commands/update.js";
import {
getPrincipal,
getUserProp,
importPem,
setUserProp,
} from "./commands/user.js";
import { migrateNew, migrateFreeze } from "./commands/migrate.js";
import { watch } from "./commands/watch/watch.js";
import {
apiVersion,
checkApiCompatibility,
checkConfigFile,
getGlobalMocArgs,
getNetworkFile,
readConfig,
setNetwork,
version,
} from "./mops.js";
import { resolvePackages } from "./resolve-packages.js";
import { Tool } from "./types.js";
import { TOOLCHAINS } from "./commands/toolchain/toolchain-utils.js";
declare global {
// eslint-disable-next-line no-var
var MOPS_NETWORK: string;
// eslint-disable-next-line no-var
var mopsReplicaTestRunning: boolean;
}
events.setMaxListeners(20);
// Change working directory for `npm run mops`
let cwd = process.env["MOPS_CWD"];
if (cwd) {
process.chdir(resolve(cwd));
}
let networkFile = getNetworkFile();
if (fs.existsSync(networkFile)) {
globalThis.MOPS_NETWORK = fs.readFileSync(networkFile).toString() || "ic";
}
let program = new Command();
function parseExtraArgs(variadicArgs?: string[]): {
extraArgs: string[];
args: string[];
} {
const rawArgs = process.argv.slice(2);
const dashDashIndex = rawArgs.indexOf("--");
const extraArgs =
dashDashIndex !== -1 ? rawArgs.slice(dashDashIndex + 1) : [];
const args = variadicArgs
? extraArgs.length > 0
? variadicArgs.slice(0, variadicArgs.length - extraArgs.length)
: variadicArgs
: [];
return { extraArgs, args };
}
program.name("mops");
// --version
program.version(`CLI ${version()}\nAPI ${apiVersion}`, "-v --version");
// init
program
.command("init")
.description("Initialize a new project or package in the current directory")
.option("-y, --yes", "Accept all defaults")
.action(async (options) => {
await init(options);
});
// add
program
.command("add <pkg>")
.description("Install the package and save it to mops.toml")
.option("--dev", "Add to [dev-dependencies] section")
.option("--verbose")
.addOption(
new Option("--lock <action>", "Lockfile action").choices([
"update",
"ignore",
]),
)
.action(async (pkg, options) => {
if (!checkConfigFile()) {
process.exit(1);
}
await add(pkg, options);
});
// remove
program
.command("remove <pkg>")
.alias("rm")
.description("Remove package and update mops.toml")
.option("--dev", "Remove from dev-dependencies instead of dependencies")
.option("--verbose", "Show more information")
.option("--dry-run", "Do not actually remove anything")
.addOption(
new Option("--lock <action>", "Lockfile action").choices([
"update",
"ignore",
]),
)
.action(async (pkg, options) => {
if (!checkConfigFile()) {
process.exit(1);
}
await remove(pkg, options);
});
// install
program
.command("install")
.alias("i")
.description("Install all dependencies specified in mops.toml")
.option("--no-toolchain", "Do not install toolchain")
.option("--verbose")
.addOption(
new Option("--lock <action>", "Lockfile action").choices([
"check",
"update",
"ignore",
]),
)
.action(async (options) => {
if (!checkConfigFile()) {
process.exit(1);
}
let compatible = await checkApiCompatibility();
if (!compatible) {
return;
}
if (options.toolchain) {
await toolchain.checkToolchainInited({ strict: false });
}
let ok = await installAll(options);
if (options.toolchain) {
await toolchain.installAll(options);
}
// check conflicts
await resolvePackages({ conflicts: "warning" });
if (!ok) {
process.exit(1);
}
});
// publish
program
.command("publish")
.description("Publish package to the mops registry")
.option("--no-docs", "Do not generate docs")
.option("--no-test", "Do not run tests")
.option("--no-bench", "Do not run benchmarks")
.option("--verbose")
.action(async (options) => {
if (!checkConfigFile()) {
process.exit(1);
}
let compatible = await checkApiCompatibility();
if (compatible) {
await publish(options);
}
});
// set-network
program
.command("set-network <network>")
.alias("sn")
.description("Set network local|staging|ic")
.action(async (network) => {
await setNetwork(network);
console.log(`Selected '${network}' network`);
});
// get-network
program
.command("get-network")
.alias("gn")
.description("Get network")
.action(async () => {
console.log(getNetwork());
});
// sources
program
.command("sources")
.description("for dfx packtool")
.option("--no-install", "Do not install dependencies before running sources")
.addOption(
new Option(
"--conflicts <action>",
"What to do with dependency version conflicts",
)
.choices(["ignore", "warning", "error"])
.default("warning"),
)
.action(async (options) => {
if (!checkConfigFile()) {
process.exit(1);
}
if (options.install) {
await installAll({
silent: true,
lock: "ignore",
threads: 6,
installFromLockFile: true,
});
}
await toolchain.checkToolchainInited({ strict: false });
let sourcesArr = await sources(options);
console.log(sourcesArr.join("\n"));
});
// moc-args
program
.command("moc-args")
.description("Print global moc compiler flags from [moc] config section")
.action(async () => {
checkConfigFile(true);
let config = readConfig();
let args = getGlobalMocArgs(config);
if (args.length) {
console.log(args.join("\n"));
}
});
// search
program
.command("search <text>")
.description("Search for packages")
.action(async (text) => {
await search(text);
});
// info
program
.command("info <pkg>")
.description("Show detailed information about a package from the registry")
.option("--versions", "List all published versions, one per line")
.action(async (pkg: string, options) => {
await info(pkg, options);
});
// cache
program
.command("cache")
.description("Manage cache")
.addArgument(new Argument("<sub>").choices(["size", "clean", "show"]))
.action(async (sub) => {
if (sub == "clean") {
await cleanCache();
console.log("Cache cleaned");
} else if (sub == "size") {
let size = await cacheSize();
console.log("Cache size is " + size);
} else if (sub == "show") {
console.log(show());
}
});
// build
program
.command("build [canisters...]")
.description("Build a canister")
.addOption(new Option("--verbose", "Verbose console output"))
.addOption(new Option("--output, -o <output>", "Output directory"))
.allowUnknownOption(true) // TODO: restrict unknown before "--"
.action(async (canisters, options) => {
checkConfigFile(true);
const { extraArgs, args } = parseExtraArgs(canisters);
await installAll({
silent: true,
lock: "ignore",
installFromLockFile: true,
});
await build(args.length ? args : undefined, {
...options,
outputDir: options.output,
extraArgs,
});
});
// check
program
.command("check [args...]")
.description(
"Check Motoko canisters or files for syntax errors and type issues. Arguments can be canister names or file paths. If no arguments are given, checks all canisters from mops.toml. Also runs stable compatibility checks for canisters with [check-stable] configured, and runs linting if lintoko is configured in [toolchain]",
)
.option("--verbose", "Verbose console output")
.addOption(
new Option(
"--fix",
"Apply autofixes to all files, including transitively imported ones",
),
)
.allowUnknownOption(true)
.action(async (args, options) => {
checkConfigFile(true);
const { extraArgs, args: argList } = parseExtraArgs(args);
await installAll({
silent: true,
lock: "ignore",
installFromLockFile: true,
});
await check(argList, {
...options,
extraArgs,
});
});
// check-candid
program
.command("check-candid <new-candid> <original-candid>")
.description("Check Candid interface compatibility between two Candid files")
.action(async (newCandid, originalCandid) => {
checkConfigFile(true);
await installAll({
silent: true,
lock: "ignore",
installFromLockFile: true,
});
await checkCandid(newCandid, originalCandid);
});
// check-stable
program
.command("check-stable [args...]")
.description(
"Check stable variable compatibility. With no arguments, checks all canisters with [check-stable] configured. Arguments can be canister names or an old file path followed by an optional canister name",
)
.option("--verbose", "Verbose console output")
.allowUnknownOption(true)
.action(async (args, options) => {
checkConfigFile(true);
const { extraArgs, args: argList } = parseExtraArgs(args);
await installAll({
silent: true,
lock: "ignore",
installFromLockFile: true,
});
await checkStable(argList, {
...options,
extraArgs,
});
});
// test
program
.command("test [filter]")
.description("Run tests")
.addOption(
new Option("-r, --reporter <reporter>", "Test reporter").choices([
"verbose",
"compact",
"files",
"silent",
]),
)
.addOption(
new Option("--mode <mode>", "Test mode")
.choices(["interpreter", "wasi", "replica"])
.default("interpreter"),
)
.addOption(
new Option(
"--replica <replica>",
"Which replica to use to run tests in replica mode",
).choices(["dfx", "pocket-ic"]),
)
.option("-w, --watch", "Enable watch mode")
.option("--verbose", "Verbose output")
.action(async (filter, options) => {
checkConfigFile(true);
await installAll({
silent: true,
lock: "ignore",
installFromLockFile: true,
});
await test(filter, options);
});
// bench
program
.command("bench [filter]")
.description("Run benchmarks")
.addOption(
new Option(
"--replica <replica>",
"Which replica to use to run benchmarks",
).choices(["dfx", "pocket-ic"]),
)
.addOption(
new Option("--gc <gc>", "Garbage collector")
.choices(["copying", "compacting", "generational", "incremental"])
.default("copying"),
)
.addOption(
new Option("--save", "Save benchmark results to .bench/<filename>.json"),
)
.addOption(
new Option(
"--compare",
"Run benchmark and compare results with .bench/<filename>.json",
),
)
// .addOption(new Option('--force-gc', 'Force GC'))
.addOption(new Option("--verbose", "Show more information"))
.action(async (filter, options) => {
checkConfigFile(true);
await installAll({
silent: true,
lock: "ignore",
installFromLockFile: true,
});
await bench(filter, options);
});
// template
program
.command("template")
.description("Apply template")
.action(async () => {
if (!checkConfigFile()) {
process.exit(1);
}
await template();
});
// mops user *
const userCommand = new Command("user").description("User management");
// user get-principal
userCommand
.command("get-principal")
.description("Print your principal")
.action(async () => {
await getPrincipal();
});
// user import
userCommand
.command("import <data>")
.description("Import .pem file data to use as identity")
.addOption(
new Option("--no-encrypt", "Do not ask for a password to encrypt identity"),
)
.action(async (data, options) => {
await importPem(data, options);
await getPrincipal();
});
// user set <prop> <value>
userCommand
.command("set")
.addArgument(
new Argument("<prop>").choices([
"name",
"site",
"email",
"github",
"twitter",
]),
)
.addArgument(new Argument("<value>"))
.description("Set user property")
.action(async (prop, value) => {
await setUserProp(prop, value);
});
// user get <prop>
userCommand
.command("get")
.addArgument(
new Argument("<prop>").choices([
"name",
"site",
"email",
"github",
"twitter",
]),
)
.description("Get user property")
.action(async (prop) => {
await getUserProp(prop);
});
program.addCommand(userCommand);
// mops owner *
const ownerCommand = new Command("owner").description(
"Package owner management",
);
// mops owner list
ownerCommand
.command("list")
.description("List package owners")
.action(async () => {
await printOwners();
});
// mops owner add
ownerCommand
.command("add <principal>")
.description("Add package owner")
.addOption(new Option("--yes", "Do not ask for confirmation"))
.action(async (data, options) => {
await addOwner(data, options.yes);
});
// mops owner remove
ownerCommand
.command("remove <principal>")
.description("Remove package owner")
.addOption(new Option("--yes", "Do not ask for confirmation"))
.action(async (data, options) => {
await removeOwner(data, options.yes);
});
program.addCommand(ownerCommand);
// mops maintainer *
const maintainerCommand = new Command("maintainer").description(
"Package maintainer management",
);
// mops maintainer list
maintainerCommand
.command("list")
.description("List package maintainers")
.action(async () => {
await printMaintainers();
});
// mops maintainer add
maintainerCommand
.command("add <principal>")
.description("Add package maintainer")
.addOption(new Option("--yes", "Do not ask for confirmation"))
.action(async (data, options) => {
await addMaintainer(data, options.yes);
});
// mops maintainer remove
maintainerCommand
.command("remove <principal>")
.description("Remove package maintainer")
.addOption(new Option("--yes", "Do not ask for confirmation"))
.action(async (data, options) => {
await removeMaintainer(data, options.yes);
});
program.addCommand(maintainerCommand);
// bump
program
.command("bump [major|minor|patch]")
.description("Bump current package version")
.action(async (part) => {
await bump(part);
});
// sync
program
.command("sync")
.description("Add missing packages and remove unused packages")
.addOption(
new Option("--lock <action>", "Lockfile action").choices([
"update",
"ignore",
]),
)
.action(async (options) => {
await sync(options);
});
// outdated
program
.command("outdated")
.description("Print outdated dependencies specified in mops.toml")
.addOption(
new Option(
"--major",
"Allow updates that cross the caret bound (major versions, or for 0.x.y packages, minor versions)",
),
)
.action(async (options) => {
await outdated(options);
});
// update
program
.command("update [pkg]")
.description("Update dependencies specified in mops.toml")
.addOption(
new Option(
"--major",
"Allow updates that cross the caret bound (major versions, or for 0.x.y packages, minor versions)",
),
)
.addOption(
new Option("--lock <action>", "Lockfile action").choices([
"update",
"ignore",
]),
)
.action(async (pkg, options) => {
await update(pkg, options);
});
// toolchain
const toolchainCommand = new Command("toolchain").description(
"Toolchain management",
);
toolchainCommand
.command("init")
.description("One-time initialization of toolchain management")
.action(async () => {
await toolchain.init();
});
toolchainCommand
.command("reset")
.description("Uninstall toolchain management")
.action(async () => {
await toolchain.init({ reset: true });
});
toolchainCommand
.command("use")
.description("Install specified tool version and update mops.toml")
.addArgument(new Argument("<tool>").choices(TOOLCHAINS))
.addArgument(new Argument("[version]"))
.action(async (tool, version) => {
if (!checkConfigFile()) {
process.exit(1);
}
await toolchain.use(tool, version);
});
toolchainCommand
.command("update")
.description(
"Update specified tool or all tools to the latest version and update mops.toml",
)
.addArgument(new Argument("[tool]").choices(TOOLCHAINS))
.action(async (tool?: Tool) => {
if (!checkConfigFile()) {
process.exit(1);
}
await toolchain.update(tool);
});
toolchainCommand
.command("bin")
.description(
`Get path to the tool binary\n<tool> can be one of ${TOOLCHAINS.map((s) => `"${s}"`).join(", ")}`,
)
.addArgument(new Argument("<tool>").choices(TOOLCHAINS))
.addOption(
new Option(
"--fallback",
"Fallback to the moc that comes with dfx if moc is not specified in the [toolchain] section",
),
)
.action(async (tool, options) => {
let bin = await toolchain.bin(tool, options);
console.log(bin);
});
program.addCommand(toolchainCommand);
// migrate
const migrateCommand = new Command("migrate").description(
"Manage enhanced migration chains",
);
migrateCommand
.command("new <name> [canister]")
.description("Create a new migration file in the next-migration directory")
.action(async (name, canister) => {
checkConfigFile(true);
await migrateNew(name, canister);
});
migrateCommand
.command("freeze [canister]")
.description("Move the next migration into the frozen chain")
.action(async (canister) => {
checkConfigFile(true);
await migrateFreeze(canister);
});
program.addCommand(migrateCommand);
// self
const selfCommand = new Command("self").description("Mops CLI management");
selfCommand
.command("update")
.description("Update mops CLI to the latest version")
.action(async () => {
await self.update();
});
selfCommand
.command("uninstall")
.description("Uninstall mops CLI")
.action(async () => {
await self.uninstall();
});
program.addCommand(selfCommand);
// watch
program
.command("watch")
.description(
"Watch *.mo files and check for syntax errors, warnings, run tests, generate declarations and deploy canisters",
)
.option(
"-e, --error",
"Check Motoko canisters or *.mo files for syntax errors",
)
.option("-w, --warning", "Check Motoko canisters or *.mo files for warnings")
.option("-f, --format", "Format Motoko code")
.option("-t, --test", "Run tests")
.option("-g, --generate", "Generate declarations for Motoko canisters")
.option("-d, --deploy", "Deploy Motoko canisters")
.action(async (options) => {
checkConfigFile(true);
await watch(options);
});
// format
program
.command("format [filter]")
.alias("fmt")
.description("Format Motoko code")
.addOption(
new Option("--check", "Check code formatting (do not change source files)"),
)
.action(async (filter, options) => {
checkConfigFile(true);
let { ok } = await format(filter, options);
if (!ok) {
process.exit(1);
}
});
// lint
program
.command("lint [filter]")
.description("Lint Motoko code")
.addOption(new Option("--verbose", "Verbose output"))
.addOption(new Option("--fix", "Apply fixes"))
.addOption(
new Option(
"-r, --rules <directory...>",
"Directories containing rules (can be used multiple times)",
),
)
.allowUnknownOption(true)
.action(async (filter, options) => {
checkConfigFile(true);
const { extraArgs } = parseExtraArgs();
await lint(filter, {
...options,
extraArgs,
});
});
// docs
const docsCommand = new Command("docs").description("Documentation management");
docsCommand
.command("generate")
.description("Generate documentation for Motoko code")
.addOption(new Option("--source <source>", "Source directory").default("src"))
.addOption(
new Option("--output, -o <output>", "Output directory").default("docs"),
)
.addOption(
new Option("--format <format>", "Output format")
.default("md")
.choices(["md", "adoc", "html"]),
)
.action(async (options) => {
checkConfigFile(true);
await docs(options);
});
docsCommand
.command("coverage")
.description("Documentation coverage report")
.addOption(
new Option(
"-s, --source <source>",
"Source directory (with .mo files)",
).default("src"),
)
.addOption(
new Option("-r, --reporter <reporter>", "Coverage reporter")
.choices(["files", "compact", "missing", "verbose"])
.default("files"),
)
.addOption(
new Option(
"-t, --threshold <threshold>",
"Coverage threshold (0-100). If total coverage is below threshold, exit with error code 1",
).default(70),
)
.action(async (options) => {
checkConfigFile(true);
await docsCoverage(options);
});
program.addCommand(docsCommand);
program.parse();