ic-mops 2.0.1 → 2.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.
Files changed (189) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/RELEASE.md +198 -0
  3. package/bundle/cli.tgz +0 -0
  4. package/check-requirements.ts +3 -8
  5. package/cli.ts +94 -11
  6. package/commands/bench/bench-canister.mo +17 -6
  7. package/commands/bench.ts +13 -16
  8. package/commands/build.ts +5 -6
  9. package/commands/check.ts +121 -0
  10. package/commands/format.ts +3 -18
  11. package/commands/lint.ts +92 -0
  12. package/commands/sync.ts +2 -8
  13. package/commands/test/test.ts +10 -20
  14. package/commands/toolchain/index.ts +21 -8
  15. package/commands/toolchain/lintoko.ts +54 -0
  16. package/commands/toolchain/toolchain-utils.ts +2 -0
  17. package/commands/watch/error-checker.ts +8 -2
  18. package/commands/watch/warning-checker.ts +8 -2
  19. package/constants.ts +23 -0
  20. package/dist/check-requirements.js +3 -8
  21. package/dist/cli.js +73 -11
  22. package/dist/commands/bench/bench-canister.mo +17 -6
  23. package/dist/commands/bench.js +7 -15
  24. package/dist/commands/build.js +5 -6
  25. package/dist/commands/check.d.ts +6 -0
  26. package/dist/commands/check.js +82 -0
  27. package/dist/commands/format.js +3 -16
  28. package/dist/commands/lint.d.ts +7 -0
  29. package/dist/commands/lint.js +69 -0
  30. package/dist/commands/sync.js +2 -7
  31. package/dist/commands/test/test.js +10 -18
  32. package/dist/commands/toolchain/index.d.ts +2 -2
  33. package/dist/commands/toolchain/index.js +18 -7
  34. package/dist/commands/toolchain/lintoko.d.ts +8 -0
  35. package/dist/commands/toolchain/lintoko.js +36 -0
  36. package/dist/commands/toolchain/toolchain-utils.d.ts +1 -0
  37. package/dist/commands/toolchain/toolchain-utils.js +1 -0
  38. package/dist/commands/watch/error-checker.js +8 -2
  39. package/dist/commands/watch/warning-checker.js +8 -2
  40. package/dist/constants.d.ts +15 -0
  41. package/dist/constants.js +21 -0
  42. package/dist/environments/nodejs/cli.js +6 -1
  43. package/dist/error.d.ts +1 -1
  44. package/dist/helpers/autofix-motoko.d.ts +26 -0
  45. package/dist/helpers/autofix-motoko.js +150 -0
  46. package/dist/helpers/get-moc-version.d.ts +2 -0
  47. package/dist/helpers/get-moc-version.js +10 -1
  48. package/dist/mops.d.ts +1 -0
  49. package/dist/mops.js +12 -1
  50. package/dist/package.json +3 -2
  51. package/dist/tests/build-no-dfx.test.d.ts +1 -0
  52. package/dist/tests/build-no-dfx.test.js +9 -0
  53. package/dist/tests/build.test.d.ts +1 -0
  54. package/dist/tests/build.test.js +18 -0
  55. package/dist/tests/check-candid.test.d.ts +1 -0
  56. package/dist/tests/check-candid.test.js +20 -0
  57. package/dist/tests/check-fix.test.d.ts +1 -0
  58. package/dist/tests/check-fix.test.js +89 -0
  59. package/dist/tests/check.test.d.ts +1 -0
  60. package/dist/tests/check.test.js +37 -0
  61. package/dist/tests/cli.test.js +4 -57
  62. package/dist/tests/helpers.d.ts +22 -0
  63. package/dist/tests/helpers.js +43 -0
  64. package/dist/tests/lint.test.d.ts +1 -0
  65. package/dist/tests/lint.test.js +15 -0
  66. package/dist/tests/moc-args.test.d.ts +1 -0
  67. package/dist/tests/moc-args.test.js +17 -0
  68. package/dist/tests/toolchain.test.d.ts +1 -0
  69. package/dist/tests/toolchain.test.js +11 -0
  70. package/dist/types.d.ts +8 -1
  71. package/dist/wasm/pkg/nodejs/wasm_bg.wasm +0 -0
  72. package/dist/wasm/pkg/web/wasm_bg.wasm +0 -0
  73. package/environments/nodejs/cli.ts +7 -1
  74. package/error.ts +1 -1
  75. package/helpers/autofix-motoko.ts +240 -0
  76. package/helpers/get-moc-version.ts +12 -1
  77. package/mops.ts +15 -1
  78. package/package.json +3 -2
  79. package/tests/__snapshots__/build-no-dfx.test.ts.snap +11 -0
  80. package/tests/__snapshots__/build.test.ts.snap +77 -0
  81. package/tests/__snapshots__/check-candid.test.ts.snap +73 -0
  82. package/tests/__snapshots__/check-fix.test.ts.snap +261 -0
  83. package/tests/__snapshots__/check.test.ts.snap +81 -0
  84. package/tests/__snapshots__/lint.test.ts.snap +78 -0
  85. package/tests/build/no-dfx/mops.toml +5 -0
  86. package/tests/build/no-dfx/src/Main.mo +5 -0
  87. package/tests/build-no-dfx.test.ts +10 -0
  88. package/tests/build.test.ts +24 -0
  89. package/tests/check/error/Error.mo +7 -0
  90. package/tests/check/error/mops.toml +2 -0
  91. package/tests/check/fix/M0223.mo +11 -0
  92. package/tests/check/fix/M0236.mo +11 -0
  93. package/tests/check/fix/M0237.mo +11 -0
  94. package/tests/check/fix/Ok.mo +7 -0
  95. package/tests/check/fix/edit-suggestions.mo +143 -0
  96. package/tests/check/fix/mops.toml +5 -0
  97. package/tests/check/fix/overlapping.mo +10 -0
  98. package/tests/check/fix/transitive-lib.mo +9 -0
  99. package/tests/check/fix/transitive-main.mo +9 -0
  100. package/tests/check/moc-args/Warning.mo +5 -0
  101. package/tests/check/moc-args/mops.toml +2 -0
  102. package/tests/check/success/Ok.mo +5 -0
  103. package/tests/check/success/Warning.mo +5 -0
  104. package/tests/check/success/mops.toml +2 -0
  105. package/tests/check-candid.test.ts +22 -0
  106. package/tests/check-fix.test.ts +134 -0
  107. package/tests/check.test.ts +51 -0
  108. package/tests/cli.test.ts +4 -74
  109. package/tests/helpers.ts +58 -0
  110. package/tests/lint/lints/no-bool-switch.toml +9 -0
  111. package/tests/lint/mops.toml +4 -0
  112. package/tests/lint/src/NoBoolSwitch.mo +8 -0
  113. package/tests/lint/src/Ok.mo +5 -0
  114. package/tests/lint.test.ts +17 -0
  115. package/tests/moc-args.test.ts +19 -0
  116. package/tests/toolchain/mock +2 -0
  117. package/tests/toolchain/mops.toml +2 -0
  118. package/tests/toolchain.test.ts +12 -0
  119. package/types.ts +8 -1
  120. package/wasm/Cargo.lock +101 -54
  121. package/wasm/pkg/nodejs/wasm_bg.wasm +0 -0
  122. package/wasm/pkg/web/wasm_bg.wasm +0 -0
  123. package/.DS_Store +0 -0
  124. package/bundle/bench/bench-canister.mo +0 -121
  125. package/bundle/bench/user-bench.mo +0 -10
  126. package/bundle/bin/moc-wrapper.sh +0 -40
  127. package/bundle/bin/mops.js +0 -3
  128. package/bundle/cli.js +0 -2144
  129. package/bundle/declarations/bench/bench.did +0 -30
  130. package/bundle/declarations/bench/bench.did.d.ts +0 -33
  131. package/bundle/declarations/bench/bench.did.js +0 -30
  132. package/bundle/declarations/bench/index.d.ts +0 -50
  133. package/bundle/declarations/bench/index.js +0 -40
  134. package/bundle/declarations/main/index.d.ts +0 -50
  135. package/bundle/declarations/main/index.js +0 -40
  136. package/bundle/declarations/main/main.did +0 -428
  137. package/bundle/declarations/main/main.did.d.ts +0 -348
  138. package/bundle/declarations/main/main.did.js +0 -406
  139. package/bundle/declarations/storage/index.d.ts +0 -50
  140. package/bundle/declarations/storage/index.js +0 -30
  141. package/bundle/declarations/storage/storage.did +0 -46
  142. package/bundle/declarations/storage/storage.did.d.ts +0 -40
  143. package/bundle/declarations/storage/storage.did.js +0 -38
  144. package/bundle/package.json +0 -36
  145. package/bundle/templates/README.md +0 -13
  146. package/bundle/templates/licenses/Apache-2.0 +0 -202
  147. package/bundle/templates/licenses/Apache-2.0-NOTICE +0 -13
  148. package/bundle/templates/licenses/MIT +0 -21
  149. package/bundle/templates/mops-publish.yml +0 -17
  150. package/bundle/templates/mops-test.yml +0 -24
  151. package/bundle/templates/src/lib.mo +0 -15
  152. package/bundle/templates/test/lib.test.mo +0 -4
  153. package/bundle/wasm_bg.wasm +0 -0
  154. package/bundle/xhr-sync-worker.js +0 -59
  155. package/dist/wasm/pkg/bundler/package.json +0 -20
  156. package/dist/wasm/pkg/bundler/wasm.d.ts +0 -3
  157. package/dist/wasm/pkg/bundler/wasm.js +0 -5
  158. package/dist/wasm/pkg/bundler/wasm_bg.js +0 -93
  159. package/dist/wasm/pkg/bundler/wasm_bg.wasm +0 -0
  160. package/dist/wasm/pkg/bundler/wasm_bg.wasm.d.ts +0 -8
  161. package/tests/__snapshots__/cli.test.ts.snap +0 -202
  162. package/tests/build/success/.dfx/local/canister_ids.json +0 -17
  163. package/tests/build/success/.dfx/local/canisters/bar/bar.did +0 -3
  164. package/tests/build/success/.dfx/local/canisters/bar/bar.most +0 -4
  165. package/tests/build/success/.dfx/local/canisters/bar/bar.wasm +0 -0
  166. package/tests/build/success/.dfx/local/canisters/bar/constructor.did +0 -3
  167. package/tests/build/success/.dfx/local/canisters/bar/index.js +0 -42
  168. package/tests/build/success/.dfx/local/canisters/bar/init_args.txt +0 -1
  169. package/tests/build/success/.dfx/local/canisters/bar/service.did +0 -3
  170. package/tests/build/success/.dfx/local/canisters/bar/service.did.d.ts +0 -7
  171. package/tests/build/success/.dfx/local/canisters/bar/service.did.js +0 -4
  172. package/tests/build/success/.dfx/local/canisters/foo/constructor.did +0 -3
  173. package/tests/build/success/.dfx/local/canisters/foo/foo.did +0 -3
  174. package/tests/build/success/.dfx/local/canisters/foo/foo.most +0 -4
  175. package/tests/build/success/.dfx/local/canisters/foo/foo.wasm +0 -0
  176. package/tests/build/success/.dfx/local/canisters/foo/index.js +0 -42
  177. package/tests/build/success/.dfx/local/canisters/foo/init_args.txt +0 -1
  178. package/tests/build/success/.dfx/local/canisters/foo/service.did +0 -3
  179. package/tests/build/success/.dfx/local/canisters/foo/service.did.d.ts +0 -7
  180. package/tests/build/success/.dfx/local/canisters/foo/service.did.js +0 -4
  181. package/tests/build/success/.dfx/local/lsp/ucwa4-rx777-77774-qaada-cai.did +0 -3
  182. package/tests/build/success/.dfx/local/lsp/ulvla-h7777-77774-qaacq-cai.did +0 -3
  183. package/tests/build/success/.dfx/local/network-id +0 -4
  184. package/wasm/pkg/bundler/package.json +0 -20
  185. package/wasm/pkg/bundler/wasm.d.ts +0 -3
  186. package/wasm/pkg/bundler/wasm.js +0 -5
  187. package/wasm/pkg/bundler/wasm_bg.js +0 -93
  188. package/wasm/pkg/bundler/wasm_bg.wasm +0 -0
  189. package/wasm/pkg/bundler/wasm_bg.wasm.d.ts +0 -8
package/dist/cli.js CHANGED
@@ -9,11 +9,13 @@ import { add } from "./commands/add.js";
9
9
  import { bench } from "./commands/bench.js";
10
10
  import { build, DEFAULT_BUILD_OUTPUT_DIR } from "./commands/build.js";
11
11
  import { bump } from "./commands/bump.js";
12
+ import { check } from "./commands/check.js";
12
13
  import { checkCandid } from "./commands/check-candid.js";
13
14
  import { docsCoverage } from "./commands/docs-coverage.js";
14
15
  import { docs } from "./commands/docs.js";
15
16
  import { format } from "./commands/format.js";
16
17
  import { init } from "./commands/init.js";
18
+ import { lint } from "./commands/lint.js";
17
19
  import { installAll } from "./commands/install/install-all.js";
18
20
  import { addMaintainer, printMaintainers, removeMaintainer, } from "./commands/maintainer.js";
19
21
  import { outdated } from "./commands/outdated.js";
@@ -30,8 +32,9 @@ import { toolchain } from "./commands/toolchain/index.js";
30
32
  import { update } from "./commands/update.js";
31
33
  import { getPrincipal, getUserProp, importPem, setUserProp, } from "./commands/user.js";
32
34
  import { watch } from "./commands/watch/watch.js";
33
- import { apiVersion, checkApiCompatibility, checkConfigFile, getNetworkFile, setNetwork, version, } from "./mops.js";
35
+ import { apiVersion, checkApiCompatibility, checkConfigFile, getGlobalMocArgs, getNetworkFile, readConfig, setNetwork, version, } from "./mops.js";
34
36
  import { resolvePackages } from "./resolve-packages.js";
37
+ import { TOOLCHAINS } from "./commands/toolchain/toolchain-utils.js";
35
38
  events.setMaxListeners(20);
36
39
  // Change working directory for `npm run mops`
37
40
  let cwd = process.env["MOPS_CWD"];
@@ -43,6 +46,17 @@ if (fs.existsSync(networkFile)) {
43
46
  globalThis.MOPS_NETWORK = fs.readFileSync(networkFile).toString() || "ic";
44
47
  }
45
48
  let program = new Command();
49
+ function parseExtraArgs(variadicArgs) {
50
+ const rawArgs = process.argv.slice(2);
51
+ const dashDashIndex = rawArgs.indexOf("--");
52
+ const extraArgs = dashDashIndex !== -1 ? rawArgs.slice(dashDashIndex + 1) : [];
53
+ const args = variadicArgs
54
+ ? extraArgs.length > 0
55
+ ? variadicArgs.slice(0, variadicArgs.length - extraArgs.length)
56
+ : variadicArgs
57
+ : [];
58
+ return { extraArgs, args };
59
+ }
46
60
  program.name("mops");
47
61
  // --version
48
62
  program.version(`CLI ${version()}\nAPI ${apiVersion}`, "-v --version");
@@ -109,7 +123,7 @@ program
109
123
  return;
110
124
  }
111
125
  if (options.toolchain) {
112
- await toolchain.ensureToolchainInited({ strict: false });
126
+ await toolchain.checkToolchainInited({ strict: false });
113
127
  }
114
128
  let ok = await installAll(options);
115
129
  if (options.toolchain) {
@@ -175,10 +189,22 @@ program
175
189
  installFromLockFile: true,
176
190
  });
177
191
  }
178
- await toolchain.ensureToolchainInited({ strict: false });
192
+ await toolchain.checkToolchainInited({ strict: false });
179
193
  let sourcesArr = await sources(options);
180
194
  console.log(sourcesArr.join("\n"));
181
195
  });
196
+ // moc-args
197
+ program
198
+ .command("moc-args")
199
+ .description("Print global moc compiler flags from [moc] config section")
200
+ .action(async () => {
201
+ checkConfigFile(true);
202
+ let config = readConfig();
203
+ let args = getGlobalMocArgs(config);
204
+ if (args.length) {
205
+ console.log(args.join("\n"));
206
+ }
207
+ });
182
208
  // search
183
209
  program
184
210
  .command("search <text>")
@@ -211,17 +237,37 @@ program
211
237
  .addOption(new Option("--verbose", "Verbose console output"))
212
238
  .addOption(new Option("--output, -o <output>", "Output directory").default(DEFAULT_BUILD_OUTPUT_DIR))
213
239
  .allowUnknownOption(true) // TODO: restrict unknown before "--"
214
- .action(async (canisters, options, command) => {
240
+ .action(async (canisters, options) => {
241
+ checkConfigFile(true);
242
+ const { extraArgs, args } = parseExtraArgs(canisters);
243
+ await installAll({
244
+ silent: true,
245
+ lock: "ignore",
246
+ installFromLockFile: true,
247
+ });
248
+ await build(args.length ? args : undefined, {
249
+ ...options,
250
+ extraArgs,
251
+ });
252
+ });
253
+ // check
254
+ program
255
+ .command("check <files...>")
256
+ .description("Check Motoko entrypoint files for syntax errors and type issues (including transitively imported files)")
257
+ .option("--verbose", "Verbose console output")
258
+ .addOption(new Option("--fix", "Apply autofixes to all files, including transitively imported ones"))
259
+ .allowUnknownOption(true)
260
+ .action(async (files, options) => {
215
261
  checkConfigFile(true);
216
- const extraArgsIndex = command.args.indexOf("--");
262
+ const { extraArgs, args: fileList } = parseExtraArgs(files);
217
263
  await installAll({
218
264
  silent: true,
219
265
  lock: "ignore",
220
266
  installFromLockFile: true,
221
267
  });
222
- await build(canisters.length ? canisters : undefined, {
268
+ await check(fileList, {
223
269
  ...options,
224
- extraArgs: extraArgsIndex !== -1 ? command.args.slice(extraArgsIndex + 1) : [],
270
+ extraArgs,
225
271
  });
226
272
  });
227
273
  // check-candid
@@ -446,7 +492,7 @@ toolchainCommand
446
492
  toolchainCommand
447
493
  .command("use")
448
494
  .description("Install specified tool version and update mops.toml")
449
- .addArgument(new Argument("<tool>").choices(["moc", "wasmtime", "pocket-ic"]))
495
+ .addArgument(new Argument("<tool>").choices(TOOLCHAINS))
450
496
  .addArgument(new Argument("[version]"))
451
497
  .action(async (tool, version) => {
452
498
  if (!checkConfigFile()) {
@@ -457,7 +503,7 @@ toolchainCommand
457
503
  toolchainCommand
458
504
  .command("update")
459
505
  .description("Update specified tool or all tools to the latest version and update mops.toml")
460
- .addArgument(new Argument("[tool]").choices(["moc", "wasmtime", "pocket-ic"]))
506
+ .addArgument(new Argument("[tool]").choices(TOOLCHAINS))
461
507
  .action(async (tool) => {
462
508
  if (!checkConfigFile()) {
463
509
  process.exit(1);
@@ -466,8 +512,8 @@ toolchainCommand
466
512
  });
467
513
  toolchainCommand
468
514
  .command("bin")
469
- .description('Get path to the tool binary\n<tool> can be one of "moc", "wasmtime", "pocket-ic"')
470
- .addArgument(new Argument("<tool>").choices(["moc", "wasmtime", "pocket-ic"]))
515
+ .description(`Get path to the tool binary\n<tool> can be one of ${TOOLCHAINS.map((s) => `"${s}"`).join(", ")}`)
516
+ .addArgument(new Argument("<tool>").choices(TOOLCHAINS))
471
517
  .addOption(new Option("--fallback", "Fallback to the moc that comes with dfx if moc is not specified in the [toolchain] section"))
472
518
  .action(async (tool, options) => {
473
519
  let bin = await toolchain.bin(tool, options);
@@ -516,6 +562,22 @@ program
516
562
  process.exit(1);
517
563
  }
518
564
  });
565
+ // lint
566
+ program
567
+ .command("lint [filter]")
568
+ .description("Lint Motoko code")
569
+ .addOption(new Option("--verbose", "Verbose output"))
570
+ .addOption(new Option("--fix", "Apply fixes"))
571
+ .addOption(new Option("-r, --rules <directory...>", "Directories containing rules (can be used multiple times)"))
572
+ .allowUnknownOption(true)
573
+ .action(async (filter, options) => {
574
+ checkConfigFile(true);
575
+ const { extraArgs } = parseExtraArgs();
576
+ await lint(filter, {
577
+ ...options,
578
+ extraArgs,
579
+ });
580
+ });
519
581
  // docs
520
582
  const docsCommand = new Command("docs").description("Documentation management");
521
583
  docsCommand
@@ -2,14 +2,25 @@ import Nat64 "mo:core/Nat64";
2
2
  import Nat "mo:core/Nat";
3
3
  import Runtime "mo:core/Runtime";
4
4
  import InternetComputer "mo:core/InternetComputer";
5
- import Int64 "mo:core/Int64";
6
5
  import Region "mo:core/Region";
7
6
  import Prim "mo:prim";
8
- import Bench "mo:bench";
9
7
 
10
8
  import UserBench "./user-bench"; // file path will be replaced with the *.bench.mo file path
11
9
 
12
10
  persistent actor class () {
11
+ type BenchSchema = {
12
+ name : Text;
13
+ description : Text;
14
+ rows : [Text];
15
+ cols : [Text];
16
+ };
17
+
18
+ type Bench = {
19
+ getVersion : () -> Nat;
20
+ getSchema : () -> BenchSchema;
21
+ runCell : (Nat, Nat) -> ();
22
+ };
23
+
13
24
  type BenchResult = {
14
25
  instructions : Int;
15
26
  rts_mutator_instructions : Int;
@@ -23,16 +34,16 @@ persistent actor class () {
23
34
  rts_reclaimed : Int;
24
35
  };
25
36
 
26
- transient var benchOpt : ?Bench.Bench = null;
37
+ transient var benchOpt : ?Bench = null;
27
38
 
28
- public func init() : async Bench.BenchSchema {
39
+ public func init() : async BenchSchema {
29
40
  let bench = UserBench.init();
30
41
  benchOpt := ?bench;
31
42
  ignore Region.grow(Region.new(), 1);
32
43
  bench.getSchema();
33
44
  };
34
45
 
35
- public query func getSchema() : async Bench.BenchSchema {
46
+ public query func getSchema() : async BenchSchema {
36
47
  let ?bench = benchOpt else Runtime.trap("bench not initialized");
37
48
  bench.getSchema();
38
49
  };
@@ -41,7 +52,7 @@ persistent actor class () {
41
52
  {
42
53
  instructions = 0;
43
54
  rts_heap_size = Prim.rts_heap_size();
44
- stable_memory_size = Int64.toInt(Int64.fromNat64(Prim.stableMemorySize())) * 65536;
55
+ stable_memory_size = Prim.rts_stable_memory_size() * 65536;
45
56
  rts_stable_memory_size = Prim.rts_stable_memory_size();
46
57
  rts_logical_stable_memory_size = Prim.rts_logical_stable_memory_size();
47
58
  rts_memory_size = Prim.rts_memory_size();
@@ -11,24 +11,15 @@ import stringWidth from "string-width";
11
11
  import { filesize } from "filesize";
12
12
  import terminalSize from "terminal-size";
13
13
  import { SemVer } from "semver";
14
- import { getRootDir, readConfig, readDfxJson } from "../mops.js";
14
+ import { getGlobalMocArgs, getRootDir, readConfig, readDfxJson, } from "../mops.js";
15
15
  import { parallel } from "../parallel.js";
16
16
  import { absToRel } from "./test/utils.js";
17
17
  import { getMocVersion } from "../helpers/get-moc-version.js";
18
18
  import { getDfxVersion } from "../helpers/get-dfx-version.js";
19
19
  import { getMocPath } from "../helpers/get-moc-path.js";
20
20
  import { sources } from "./sources.js";
21
+ import { MOTOKO_GLOB_CONFIG } from "../constants.js";
21
22
  import { BenchReplica } from "./bench-replica.js";
22
- let ignore = [
23
- "**/node_modules/**",
24
- "**/.mops/**",
25
- "**/.vessel/**",
26
- "**/.git/**",
27
- ];
28
- let globConfig = {
29
- nocase: true,
30
- ignore: ignore,
31
- };
32
23
  export async function bench(filter = "", optionsArg = {}) {
33
24
  let config = readConfig();
34
25
  let dfxJson = readDfxJson();
@@ -75,7 +66,7 @@ export async function bench(filter = "", optionsArg = {}) {
75
66
  if (filter) {
76
67
  globStr = `**/bench?(mark)/**/*${filter}*.mo`;
77
68
  }
78
- let files = globSync(path.join(rootDir, globStr), globConfig);
69
+ let files = globSync(path.join(rootDir, globStr), MOTOKO_GLOB_CONFIG);
79
70
  if (!files.length) {
80
71
  if (filter) {
81
72
  options.silent ||
@@ -104,12 +95,13 @@ export async function bench(filter = "", optionsArg = {}) {
104
95
  }
105
96
  }
106
97
  await replica.start({ silent: options.silent });
98
+ let globalMocArgs = getGlobalMocArgs(config);
107
99
  if (!process.env.CI && !options.silent) {
108
100
  console.log("Deploying canisters...");
109
101
  }
110
102
  await parallel(os.cpus().length, files, async (file) => {
111
103
  try {
112
- await deployBenchFile(file, options, replica);
104
+ await deployBenchFile(file, options, replica, globalMocArgs);
113
105
  }
114
106
  catch (err) {
115
107
  console.error("Unexpected error. Stopping replica...");
@@ -200,7 +192,7 @@ function getMocArgs(options) {
200
192
  }
201
193
  return args;
202
194
  }
203
- async function deployBenchFile(file, options, replica) {
195
+ async function deployBenchFile(file, options, replica, globalMocArgs) {
204
196
  let rootDir = getRootDir();
205
197
  let tempDir = path.join(rootDir, ".mops/.bench/", path.parse(file).name);
206
198
  let canisterName = path.parse(file).name;
@@ -214,7 +206,7 @@ async function deployBenchFile(file, options, replica) {
214
206
  let mocPath = getMocPath();
215
207
  let mocArgs = getMocArgs(options);
216
208
  options.verbose && console.time(`build ${canisterName}`);
217
- await execaCommand(`${mocPath} -c --idl canister.mo ${mocArgs} ${(await sources({ cwd: tempDir })).join(" ")}`, {
209
+ await execaCommand(`${mocPath} -c --idl canister.mo ${globalMocArgs.join(" ")} ${mocArgs} ${(await sources({ cwd: tempDir })).join(" ")}`, {
218
210
  cwd: tempDir,
219
211
  stdio: options.verbose ? "pipe" : ["pipe", "ignore", "pipe"],
220
212
  });
@@ -4,18 +4,18 @@ import { exists } from "fs-extra";
4
4
  import { mkdir, readFile, writeFile } from "node:fs/promises";
5
5
  import { join } from "node:path";
6
6
  import { cliError } from "../error.js";
7
- import { getMocPath } from "../helpers/get-moc-path.js";
8
7
  import { isCandidCompatible } from "../helpers/is-candid-compatible.js";
9
8
  import { getWasmBindings } from "../wasm.js";
10
- import { readConfig } from "../mops.js";
9
+ import { getGlobalMocArgs, readConfig } from "../mops.js";
11
10
  import { sourcesArgs } from "./sources.js";
11
+ import { toolchain } from "./toolchain/index.js";
12
12
  export const DEFAULT_BUILD_OUTPUT_DIR = ".mops/.build";
13
13
  export async function build(canisterNames, options) {
14
14
  if (canisterNames?.length == 0) {
15
15
  cliError("No canisters specified to build");
16
16
  }
17
17
  let outputDir = options.outputDir ?? DEFAULT_BUILD_OUTPUT_DIR;
18
- let mocPath = getMocPath();
18
+ let mocPath = await toolchain.bin("moc", { fallback: true });
19
19
  let canisters = {};
20
20
  let config = readConfig();
21
21
  if (config.canisters) {
@@ -43,7 +43,6 @@ export async function build(canisterNames, options) {
43
43
  ? Object.fromEntries(Object.entries(canisters).filter(([name]) => canisterNames.includes(name)))
44
44
  : canisters;
45
45
  for (let [canisterName, canister] of Object.entries(filteredCanisters)) {
46
- options.verbose && console.time(`build canister ${canisterName}`);
47
46
  console.log(chalk.blue("build canister"), chalk.bold(canisterName));
48
47
  let motokoPath = canister.main;
49
48
  if (!motokoPath) {
@@ -56,8 +55,8 @@ export async function build(canisterNames, options) {
56
55
  "-o",
57
56
  wasmPath,
58
57
  motokoPath,
59
- ...(options.extraArgs ?? []),
60
58
  ...(await sourcesArgs()).flat(),
59
+ ...getGlobalMocArgs(config),
61
60
  ];
62
61
  if (config.build?.args) {
63
62
  if (typeof config.build.args === "string") {
@@ -71,6 +70,7 @@ export async function build(canisterNames, options) {
71
70
  }
72
71
  args.push(...canister.args);
73
72
  }
73
+ args.push(...(options.extraArgs ?? []));
74
74
  const isPublicCandid = true; // always true for now to reduce corner cases
75
75
  const candidVisibility = isPublicCandid ? "icp:public" : "icp:private";
76
76
  if (isPublicCandid) {
@@ -139,7 +139,6 @@ export async function build(canisterNames, options) {
139
139
  }
140
140
  cliError(`Error while compiling canister ${canisterName}${err?.message ? `\n${err.message}` : ""}`);
141
141
  }
142
- options.verbose && console.timeEnd(`build canister ${canisterName}`);
143
142
  }
144
143
  console.log(chalk.green(`\n✓ Built ${Object.keys(filteredCanisters).length} canister${Object.keys(filteredCanisters).length == 1 ? "" : "s"} successfully`));
145
144
  }
@@ -0,0 +1,6 @@
1
+ export interface CheckOptions {
2
+ verbose: boolean;
3
+ fix: boolean;
4
+ extraArgs: string[];
5
+ }
6
+ export declare function check(files: string | string[], options?: Partial<CheckOptions>): Promise<void>;
@@ -0,0 +1,82 @@
1
+ import { relative } from "node:path";
2
+ import chalk from "chalk";
3
+ import { execa } from "execa";
4
+ import { cliError } from "../error.js";
5
+ import { getGlobalMocArgs, readConfig } from "../mops.js";
6
+ import { autofixMotoko } from "../helpers/autofix-motoko.js";
7
+ import { getMocSemVer } from "../helpers/get-moc-version.js";
8
+ import { sourcesArgs } from "./sources.js";
9
+ import { toolchain } from "./toolchain/index.js";
10
+ const MOC_ALL_LIBS_MIN_VERSION = "1.3.0";
11
+ function supportsAllLibsFlag() {
12
+ const version = getMocSemVer();
13
+ return version ? version.compare(MOC_ALL_LIBS_MIN_VERSION) >= 0 : false;
14
+ }
15
+ export async function check(files, options = {}) {
16
+ const fileList = Array.isArray(files) ? files : [files];
17
+ if (fileList.length === 0) {
18
+ cliError("No Motoko files specified for checking");
19
+ }
20
+ const config = readConfig();
21
+ const mocPath = await toolchain.bin("moc", { fallback: true });
22
+ const sources = await sourcesArgs();
23
+ const globalMocArgs = getGlobalMocArgs(config);
24
+ // --all-libs enables richer diagnostics with edit suggestions from moc (requires moc >= 1.3.0)
25
+ const allLibs = supportsAllLibsFlag();
26
+ if (!allLibs) {
27
+ console.log(chalk.yellow(`moc < ${MOC_ALL_LIBS_MIN_VERSION}: some diagnostic hints may be missing`));
28
+ }
29
+ else if (options.verbose) {
30
+ console.log(chalk.blue("check"), chalk.gray("Using --all-libs for richer diagnostics"));
31
+ }
32
+ const mocArgs = [
33
+ "--check",
34
+ ...(allLibs ? ["--all-libs"] : []),
35
+ ...sources.flat(),
36
+ ...globalMocArgs,
37
+ ...(options.extraArgs ?? []),
38
+ ];
39
+ if (options.fix) {
40
+ if (options.verbose) {
41
+ console.log(chalk.blue("check"), chalk.gray("Attempting to fix files"));
42
+ }
43
+ const fixResult = await autofixMotoko(mocPath, fileList, mocArgs);
44
+ if (fixResult) {
45
+ for (const [file, codes] of fixResult.fixedFiles) {
46
+ const unique = [...new Set(codes)].sort();
47
+ const n = codes.length;
48
+ const rel = relative(process.cwd(), file);
49
+ console.log(chalk.green(`Fixed ${rel} (${n} ${n === 1 ? "fix" : "fixes"}: ${unique.join(", ")})`));
50
+ }
51
+ const fileCount = fixResult.fixedFiles.size;
52
+ console.log(chalk.green(`\n✓ ${fixResult.totalFixCount} ${fixResult.totalFixCount === 1 ? "fix" : "fixes"} applied to ${fileCount} ${fileCount === 1 ? "file" : "files"}`));
53
+ }
54
+ else {
55
+ if (options.verbose) {
56
+ console.log(chalk.yellow("No fixes were needed"));
57
+ }
58
+ }
59
+ }
60
+ for (const file of fileList) {
61
+ try {
62
+ const args = [file, ...mocArgs];
63
+ if (options.verbose) {
64
+ console.log(chalk.blue("check"), chalk.gray("Running moc:"));
65
+ console.log(chalk.gray(mocPath, JSON.stringify(args)));
66
+ }
67
+ const result = await execa(mocPath, args, {
68
+ stdio: "inherit",
69
+ reject: false,
70
+ });
71
+ if (result.exitCode !== 0) {
72
+ cliError(`✗ Check failed for file ${file} (exit code: ${result.exitCode})`);
73
+ }
74
+ if (!options.fix) {
75
+ console.log(chalk.green(`✓ ${file}`));
76
+ }
77
+ }
78
+ catch (err) {
79
+ cliError(`Error while checking ${file}${err?.message ? `\n${err.message}` : ""}`);
80
+ }
81
+ }
82
+ }
@@ -7,26 +7,13 @@ import motokoPlugin from "prettier-plugin-motoko";
7
7
  import { getRootDir } from "../mops.js";
8
8
  import { absToRel } from "./test/utils.js";
9
9
  import { parallel } from "../parallel.js";
10
- let ignore = [
11
- "**/node_modules/**",
12
- "**/.mops/**",
13
- "**/.vessel/**",
14
- "**/.git/**",
15
- "**/dist/**",
16
- ];
17
- let globConfig = {
18
- nocase: true,
19
- ignore: ignore,
20
- };
10
+ import { MOTOKO_GLOB_CONFIG } from "../constants.js";
21
11
  export async function format(filter, options = {}, signal, onProgress) {
22
12
  let startTime = Date.now();
23
13
  let rootDir = getRootDir();
24
- let globStr = "**/*.mo";
25
- if (filter) {
26
- globStr = `**/*${filter}*.mo`;
27
- }
14
+ let globStr = filter ? `**/*${filter}*.mo` : "**/*.mo";
28
15
  let files = globSync(path.join(rootDir, globStr), {
29
- ...globConfig,
16
+ ...MOTOKO_GLOB_CONFIG,
30
17
  cwd: rootDir,
31
18
  });
32
19
  let invalidFiles = 0;
@@ -0,0 +1,7 @@
1
+ export interface LintOptions {
2
+ verbose: boolean;
3
+ fix: boolean;
4
+ rules?: string[];
5
+ extraArgs: string[];
6
+ }
7
+ export declare function lint(filter: string | undefined, options: Partial<LintOptions>): Promise<void>;
@@ -0,0 +1,69 @@
1
+ import chalk from "chalk";
2
+ import { execa } from "execa";
3
+ import { globSync } from "glob";
4
+ import path from "node:path";
5
+ import { cliError } from "../error.js";
6
+ import { getRootDir, readConfig } from "../mops.js";
7
+ import { toolchain } from "./toolchain/index.js";
8
+ import { MOTOKO_GLOB_CONFIG } from "../constants.js";
9
+ import { existsSync } from "node:fs";
10
+ export async function lint(filter, options) {
11
+ let config = readConfig();
12
+ let rootDir = getRootDir();
13
+ let lintokoBinPath = config.toolchain?.lintoko
14
+ ? await toolchain.bin("lintoko")
15
+ : "lintoko";
16
+ let globStr = filter ? `**/*${filter}*.mo` : "**/*.mo";
17
+ let filesToLint = globSync(path.join(rootDir, globStr), {
18
+ ...MOTOKO_GLOB_CONFIG,
19
+ cwd: rootDir,
20
+ });
21
+ if (filesToLint.length === 0) {
22
+ cliError(`No files found for filter '${filter}'`);
23
+ }
24
+ let args = [];
25
+ if (options.verbose) {
26
+ args.push("--verbose");
27
+ }
28
+ if (options.fix) {
29
+ args.push("--fix");
30
+ }
31
+ const rules = options.rules && options.rules.length > 0
32
+ ? options.rules
33
+ : ["lint", "lints"].filter((d) => existsSync(path.join(rootDir, d)));
34
+ rules.forEach((rule) => args.push("--rules", rule));
35
+ if (config.lint?.args) {
36
+ if (typeof config.lint.args === "string") {
37
+ cliError(`[lint] config 'args' should be an array of strings in mops.toml config file`);
38
+ }
39
+ args.push(...config.lint.args);
40
+ }
41
+ if (options.extraArgs && options.extraArgs.length > 0) {
42
+ args.push(...options.extraArgs);
43
+ }
44
+ args.push(...filesToLint);
45
+ try {
46
+ if (options.verbose) {
47
+ console.log(chalk.blue("lint"), chalk.gray("Running lintoko:"));
48
+ console.log(chalk.gray(lintokoBinPath));
49
+ console.log(chalk.gray(JSON.stringify(args)));
50
+ }
51
+ const result = await execa(lintokoBinPath, args, {
52
+ cwd: rootDir,
53
+ stdio: "inherit",
54
+ reject: false,
55
+ });
56
+ if (result.exitCode !== 0) {
57
+ cliError(`Lint failed with exit code ${result.exitCode}`);
58
+ }
59
+ if (options.fix) {
60
+ console.log(chalk.green("✓ Lint fixes applied"));
61
+ }
62
+ else {
63
+ console.log(chalk.green("✓ Lint succeeded"));
64
+ }
65
+ }
66
+ catch (err) {
67
+ cliError(`Error while running lintoko${err?.message ? `\n${err.message}` : ""}`);
68
+ }
69
+ }
@@ -7,6 +7,7 @@ import { add } from "./add.js";
7
7
  import { remove } from "./remove.js";
8
8
  import { checkIntegrity } from "../integrity.js";
9
9
  import { getMocPath } from "../helpers/get-moc-path.js";
10
+ import { MOTOKO_IGNORE_PATTERNS } from "../constants.js";
10
11
  export async function sync({ lock } = {}) {
11
12
  if (!checkConfigFile()) {
12
13
  return;
@@ -31,19 +32,13 @@ export async function sync({ lock } = {}) {
31
32
  }
32
33
  await checkIntegrity(lock);
33
34
  }
34
- let ignore = [
35
- "**/node_modules/**",
36
- "**/.vessel/**",
37
- "**/.git/**",
38
- "**/.mops/**",
39
- ];
40
35
  async function getUsedPackages() {
41
36
  let rootDir = getRootDir();
42
37
  let mocPath = getMocPath();
43
38
  let files = globSync("**/*.mo", {
44
39
  cwd: rootDir,
45
40
  nocase: true,
46
- ignore: ignore,
41
+ ignore: MOTOKO_IGNORE_PATTERNS,
47
42
  });
48
43
  let packages = new Set();
49
44
  for (let file of files) {
@@ -10,7 +10,7 @@ import chokidar from "chokidar";
10
10
  import debounce from "debounce";
11
11
  import { SemVer } from "semver";
12
12
  import { sources } from "../sources.js";
13
- import { getRootDir, readConfig } from "../../mops.js";
13
+ import { getGlobalMocArgs, getRootDir, readConfig } from "../../mops.js";
14
14
  import { parallel } from "../../parallel.js";
15
15
  import { MMF1 } from "./mmf1.js";
16
16
  import { absToRel, pipeMMF, pipeStderrToMMF, pipeStdoutToMMF, } from "./utils.js";
@@ -21,16 +21,7 @@ import { SilentReporter } from "./reporters/silent-reporter.js";
21
21
  import { toolchain } from "../toolchain/index.js";
22
22
  import { Replica } from "../replica.js";
23
23
  import { getDfxVersion } from "../../helpers/get-dfx-version.js";
24
- let ignore = [
25
- "**/node_modules/**",
26
- "**/.mops/**",
27
- "**/.vessel/**",
28
- "**/.git/**",
29
- ];
30
- let globConfig = {
31
- nocase: true,
32
- ignore: ignore,
33
- };
24
+ import { MOTOKO_GLOB_CONFIG, MOTOKO_IGNORE_PATTERNS } from "../../constants.js";
34
25
  let replica = new Replica();
35
26
  let replicaStartPromise;
36
27
  async function startReplicaOnce(replica, type) {
@@ -94,7 +85,7 @@ export async function test(filter = "", options = {}) {
94
85
  console.log(chalk.gray(`Press ${chalk.gray("Ctrl+C")} to exit.`));
95
86
  }, 200);
96
87
  let watcher = chokidar.watch([path.join(rootDir, "**/*.mo"), path.join(rootDir, "mops.toml")], {
97
- ignored: ignore,
88
+ ignored: MOTOKO_IGNORE_PATTERNS,
98
89
  ignoreInitial: true,
99
90
  });
100
91
  watcher.on("all", () => {
@@ -118,16 +109,15 @@ async function runAll(reporterName, filter = "", mode = "interpreter", replicaTy
118
109
  export async function testWithReporter(reporterName, filter = "", defaultMode = "interpreter", replicaType, watch = false, signal) {
119
110
  let rootDir = getRootDir();
120
111
  let files = [];
121
- let libFiles = globSync("**/test?(s)/lib.mo", globConfig);
112
+ let libFiles = globSync("**/test?(s)/lib.mo", MOTOKO_GLOB_CONFIG);
122
113
  if (libFiles[0]) {
123
114
  files = [libFiles[0]];
124
115
  }
125
116
  else {
126
- let globStr = "**/test?(s)/**/*.test.mo";
127
- if (filter) {
128
- globStr = `**/test?(s)/**/*${filter}*.mo`;
129
- }
130
- files = globSync(path.join(rootDir, globStr), globConfig);
117
+ let globStr = filter
118
+ ? `**/test?(s)/**/*${filter}*.mo`
119
+ : "**/test?(s)/**/*.test.mo";
120
+ files = globSync(path.join(rootDir, globStr), MOTOKO_GLOB_CONFIG);
131
121
  }
132
122
  if (!files.length) {
133
123
  if (filter) {
@@ -162,6 +152,7 @@ export async function testWithReporter(reporterName, filter = "", defaultMode =
162
152
  reporter.addFiles(files);
163
153
  let config = readConfig();
164
154
  let sourcesArr = await sources();
155
+ let globalMocArgs = getGlobalMocArgs(config);
165
156
  if (!mocPath) {
166
157
  mocPath = await toolchain.bin("moc", { fallback: true });
167
158
  }
@@ -207,6 +198,7 @@ export async function testWithReporter(reporterName, filter = "", defaultMode =
207
198
  "--hide-warnings",
208
199
  "--error-detail=2",
209
200
  ...sourcesArr.join(" ").split(" "),
201
+ ...globalMocArgs,
210
202
  file,
211
203
  ].filter((x) => x);
212
204
  // interpret
@@ -1,5 +1,5 @@
1
1
  import { Tool } from "../../types.js";
2
- declare function ensureToolchainInited({ strict }?: {
2
+ declare function checkToolchainInited({ strict }?: {
3
3
  strict?: boolean | undefined;
4
4
  }): Promise<boolean>;
5
5
  declare function init({ reset, silent }?: {
@@ -21,6 +21,6 @@ export declare let toolchain: {
21
21
  update: typeof update;
22
22
  bin: typeof bin;
23
23
  installAll: typeof installAll;
24
- ensureToolchainInited: typeof ensureToolchainInited;
24
+ checkToolchainInited: typeof checkToolchainInited;
25
25
  };
26
26
  export {};