@smoothbricks/nx-plugin 0.3.11 → 0.3.13

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 (38) hide show
  1. package/README.md +23 -2
  2. package/dist/bounded-test-policy.d.ts +26 -0
  3. package/dist/bounded-test-policy.d.ts.map +1 -1
  4. package/dist/bounded-test-policy.js +194 -0
  5. package/dist/cargo-workspace.d.ts +67 -0
  6. package/dist/cargo-workspace.d.ts.map +1 -0
  7. package/dist/cargo-workspace.js +215 -0
  8. package/dist/cross-check-policy.d.ts +60 -1
  9. package/dist/cross-check-policy.d.ts.map +1 -1
  10. package/dist/cross-check-policy.js +65 -1
  11. package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
  12. package/dist/executors/bounded-exec/executor.js +86 -51
  13. package/dist/executors/bounded-exec/schema.d.ts +13 -0
  14. package/dist/executors/bounded-exec/schema.d.ts.map +1 -1
  15. package/dist/index.d.ts +10 -5
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +455 -95
  18. package/dist/package-target-policy.d.ts +2 -1
  19. package/dist/package-target-policy.d.ts.map +1 -1
  20. package/dist/package-target-policy.js +54 -13
  21. package/dist/workspace-config-policy.js +32 -35
  22. package/nextest.toml +79 -0
  23. package/package.json +2 -1
  24. package/src/bounded-test-policy.test.ts +304 -0
  25. package/src/bounded-test-policy.ts +218 -0
  26. package/src/cargo-workspace.ts +243 -0
  27. package/src/cross-check-policy.test.ts +24 -0
  28. package/src/cross-check-policy.ts +80 -1
  29. package/src/executors/bounded-exec/executor.test.ts +147 -3
  30. package/src/executors/bounded-exec/executor.ts +103 -53
  31. package/src/executors/bounded-exec/schema.json +7 -2
  32. package/src/executors/bounded-exec/schema.ts +13 -0
  33. package/src/index.test.ts +531 -99
  34. package/src/index.ts +527 -104
  35. package/src/package-target-policy.test.ts +50 -0
  36. package/src/package-target-policy.ts +58 -9
  37. package/src/workspace-config-policy.test.ts +15 -30
  38. package/src/workspace-config-policy.ts +32 -39
package/README.md CHANGED
@@ -30,8 +30,29 @@ Concrete targets come from concrete files:
30
30
  - `typecheck-tests:watch` is inferred from `tsconfig.test.json` and runs the same typecheck in watch mode.
31
31
  - `test:watch` is inferred when the package already defines an explicit Bun or Vitest `test` command. The plugin derives
32
32
  the corresponding watch command and makes it depend on `typecheck-tests`.
33
- - A workspace-root `Cargo.toml` provides `cargo-test`, `test`, `cargo-lint`, `mutation`, and `bench`; workspaces with
34
- `cdylib` member crates also receive the cacheable `cargo-wasm` output target.
33
+ - A workspace-root `Cargo.toml` provides `cargo-test`, `test`, `cargo-lint`, `mutation`, and `bench`.
34
+ `cargo-test-compile` is one workspace `cargo test --no-run`. Each member crate gets a cached `cargo-test-<package>`
35
+ run (`cargo nextest run --workspace -E 'package(<crate>)'`, 30s per-test timeout like `bun test --timeout=30000`)
36
+ whose inputs are that crate and its path deps, so unchanged crates are skipped. The filterset, rather than
37
+ `--package <crate>`, is what makes the run cheap: `--package` re-resolves features for that crate alone, which
38
+ fingerprints differently from the workspace build `cargo-test-compile` already paid for and rebuilds it inside the
39
+ bounded window. Those runs are chained so two cargos never share `target/`; `napi-debug` sits on that chain after
40
+ compile. Clippy uses `--target-dir target/cargo-lint` so lint can overlap tests. Workspaces with `cdylib` member
41
+ crates also receive the cacheable `cargo-wasm` output target.
42
+ - A crate whose suite outgrows one bounded window declares `[package.metadata.smoothbricks.test] shards = N`, and gets
43
+ `cargo-test-<package>-shard1..N`, each running `--partition hash:i/N` with the full bound. nextest assigns a test to a
44
+ shard by hashing its name, so the shards stay an exact partition of the crate as tests and test binaries are added,
45
+ and a stale `N` can only make a target slow — never drop a test. Omitting the key means one target, as before.
46
+ - Tests that a `nextest.toml` override singles out are lifted out of the hash into `cargo-test-<package>-exceptions`,
47
+ and the shards run the complement. An override marks a class that does not behave like the rest of the suite, and each
48
+ kind breaks a shard differently: a `test-group` only holds within one nextest run, so leaving its members to the hash
49
+ would scatter them across runs and dissolve the mutex; a raised `slow-timeout` marks a test whose cost is not the
50
+ suite's, such as a compile-fail test that rustc's a fixture for 25.6s on a cold target directory against 1.8s warm —
51
+ and every CI runner is cold. One target holds both classes, not one each: they occupy different threads, so its wall
52
+ is the max of the classes rather than their sum. The pin is derived by reading the overrides back out of
53
+ `nextest.toml`, so declaring one there is the whole change. Only a sharded crate gets this target — an unsharded crate
54
+ already runs its whole suite in a single process — and it passes on an empty set, which is the correct answer for a
55
+ platform where the singled-out tests are `cfg`-ed out.
35
56
  - Canonical `napi` package metadata provides a host `cargo-napi` target and named release targets for each configured
36
57
  triple. Linux `--use-napi-cross` targets compile C/C++ dependencies with Clang; the NAPI CLI supplies its downloaded
37
58
  GNU sysroot and toolchain flags. This avoids the bundled GCC's unsupported diagnostics-color flag without disabling
@@ -29,6 +29,32 @@ export interface ApplyBoundedTestTargetPolicyOptions {
29
29
  export declare function applyBoundedTestTargetPolicy(packageJson: BoundedTestPolicyPackageJson, options: ApplyBoundedTestTargetPolicyOptions): void;
30
30
  export declare function applyWorkspaceBoundedTestTargetPolicy(root: string, options?: PackageTargetPolicyOptions): boolean;
31
31
  export declare function checkWorkspaceBoundedTestTargetPolicy(root: string, options?: PackageTargetPolicyOptions): BoundedTestPolicyIssue[];
32
+ /**
33
+ * A cargo workspace's `test` aggregate MUST reach `cargo-test`, and `cargo-test`
34
+ * must actually RUN tests.
35
+ *
36
+ * Inference wires `test` to `cargo-test` (see `index.ts`), but two things unwire
37
+ * it silently and both leave the target green:
38
+ *
39
+ * 1. `targetDefaults.test.dependsOn` in `nx.json` REPLACES an inferred
40
+ * `dependsOn` rather than merging, and a package-local `nx.targets.test`
41
+ * replaces it outright. `nx test <project>` then executes nothing.
42
+ * 2. `dependsOn` REPLACES rather than unions at every merge layer, so a
43
+ * package-local `nx.targets['cargo-test'].dependsOn` that omits the inferred
44
+ * runner leg leaves a target that still "reaches" its dependencies while no
45
+ * test binary is ever run. Reachability alone cannot see this, because
46
+ * `cargo-test-compile` is `--no-run`. (Inference itself no longer skips a
47
+ * declared cargo key, so the executor and options survive the declaration —
48
+ * see `index.ts`.)
49
+ *
50
+ * So this checks three things: `test` reaches `cargo-test`; some target in
51
+ * `cargo-test`'s closure actually executes tests rather than only compiling them;
52
+ * and when the run is split into per-crate `cargo-test-<package>` children, their
53
+ * union equals the workspace member set. A missing child is silent once
54
+ * `--package` actually filters: the remaining targets stay green and the
55
+ * uncovered member never runs.
56
+ */
57
+ export declare function checkWorkspaceCargoTestReachabilityPolicy(root: string, options?: PackageTargetPolicyOptions): BoundedTestPolicyIssue[];
32
58
  export declare function checkBoundedTestTargetPolicy(packageJson: BoundedTestPolicyPackageJson, options: ApplyBoundedTestTargetPolicyOptions): boolean;
33
59
  export declare function boundedTestScriptAlias(projectName: string): string;
34
60
  export declare function resolveTestCommand(packageJson: BoundedTestPolicyPackageJson, defaultCommand?: string, projectJson?: BoundedTestPolicyProjectJson): string;
@@ -1 +1 @@
1
- {"version":3,"file":"bounded-test-policy.d.ts","sourceRoot":"","sources":["../src/bounded-test-policy.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,0BAA0B,EAAE,sBAAsB,EAAE,MAAM,4BAA4B,CAAC;AAErG,eAAO,MAAM,qBAAqB,yCAAyC,CAAC;AAC5E,eAAO,MAAM,uBAAuB,SAAU,CAAC;AAC/C,eAAO,MAAM,0BAA0B,QAAS,CAAC;AAKjD,eAAO,MAAM,gCAAgC,QAAS,CAAC;AAEvD,MAAM,WAAW,4BAA4B;IAC3C,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAClC,EAAE,CAAC,EAAE;QACH,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;KACnD,CAAC;CACH;AAED,MAAM,WAAW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;;;;;;;;;;;;GAwBG;AACH,wBAAgB,yCAAyC,CACvD,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,0BAA+B,GACvC,sBAAsB,EAAE,CAwC1B;AAuHD,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,4BAA4B,EACzC,OAAO,EAAE,mCAAmC,GAC3C,OAAO,CAqBT;AAmHD,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,MAAM,GAAG,MAAM,CAElE;AAED,wBAAgB,kBAAkB,CAChC,WAAW,EAAE,4BAA4B,EACzC,cAAc,SAAa,EAC3B,WAAW,CAAC,EAAE,4BAA4B,GACzC,MAAM,CAER;AA+CD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,SAAmC,GAAG,MAAM,CAa9G"}
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { dirname, join } from 'node:path';
3
+ import { CARGO_TEST_TARGET, listCargoWorkspacePackages, packageNameFromCargoTestTarget } from './cargo-workspace.js';
3
4
  export const BOUNDED_TEST_EXECUTOR = '@smoothbricks/nx-plugin:bounded-exec';
4
5
  export const BOUNDED_TEST_TIMEOUT_MS = 120_000;
5
6
  export const BOUNDED_TEST_KILL_AFTER_MS = 10_000;
@@ -46,6 +47,9 @@ export function applyWorkspaceBoundedTestTargetPolicy(root, options = {}) {
46
47
  if (checkBoundedTestTargetPolicy(packageJson, { projectName, projectJson, resolvedProject })) {
47
48
  continue;
48
49
  }
50
+ if (!boundableTestTarget(packageJson, projectJson)) {
51
+ continue;
52
+ }
49
53
  const beforePackageJson = JSON.stringify(packageJson);
50
54
  const beforeProjectJson = JSON.stringify(projectJson);
51
55
  applyBoundedTestTargetPolicy(packageJson, { projectName, projectJson });
@@ -88,6 +92,173 @@ export function checkWorkspaceBoundedTestTargetPolicy(root, options = {}) {
88
92
  }
89
93
  return issues;
90
94
  }
95
+ /**
96
+ * A cargo workspace's `test` aggregate MUST reach `cargo-test`, and `cargo-test`
97
+ * must actually RUN tests.
98
+ *
99
+ * Inference wires `test` to `cargo-test` (see `index.ts`), but two things unwire
100
+ * it silently and both leave the target green:
101
+ *
102
+ * 1. `targetDefaults.test.dependsOn` in `nx.json` REPLACES an inferred
103
+ * `dependsOn` rather than merging, and a package-local `nx.targets.test`
104
+ * replaces it outright. `nx test <project>` then executes nothing.
105
+ * 2. `dependsOn` REPLACES rather than unions at every merge layer, so a
106
+ * package-local `nx.targets['cargo-test'].dependsOn` that omits the inferred
107
+ * runner leg leaves a target that still "reaches" its dependencies while no
108
+ * test binary is ever run. Reachability alone cannot see this, because
109
+ * `cargo-test-compile` is `--no-run`. (Inference itself no longer skips a
110
+ * declared cargo key, so the executor and options survive the declaration —
111
+ * see `index.ts`.)
112
+ *
113
+ * So this checks three things: `test` reaches `cargo-test`; some target in
114
+ * `cargo-test`'s closure actually executes tests rather than only compiling them;
115
+ * and when the run is split into per-crate `cargo-test-<package>` children, their
116
+ * union equals the workspace member set. A missing child is silent once
117
+ * `--package` actually filters: the remaining targets stay green and the
118
+ * uncovered member never runs.
119
+ */
120
+ export function checkWorkspaceCargoTestReachabilityPolicy(root, options = {}) {
121
+ const issues = [];
122
+ for (const packageJsonPath of listWorkspacePackageJsonPaths(root)) {
123
+ const packageJson = readPackageJson(packageJsonPath);
124
+ const projectJsonPath = projectJsonPathForPackageJson(packageJsonPath);
125
+ const projectJson = existsSync(projectJsonPath) ? readProjectJson(projectJsonPath) : undefined;
126
+ const projectName = packageProjectName(packageJson, projectJson);
127
+ if (!projectName) {
128
+ continue;
129
+ }
130
+ const resolvedProject = resolvedProjectFor(options, projectName);
131
+ // Without a resolved graph there is nothing to judge, and without a
132
+ // cargo-test target this is not a cargo workspace.
133
+ if (!resolvedProject?.targets?.has(CARGO_TEST_TARGET) || !resolvedProject.targets.has('test')) {
134
+ continue;
135
+ }
136
+ const scope = projectJson ? 'targets' : 'nx.targets';
137
+ const path = projectJson ? projectJsonPath : packageJsonPath;
138
+ if (!resolvedTargetReaches(resolvedProject, 'test', CARGO_TEST_TARGET)) {
139
+ issues.push({
140
+ path,
141
+ message: `${scope}.test must depend on ${CARGO_TEST_TARGET} ` +
142
+ 'so the Rust tests run in the test aggregate; nx.json targetDefaults replaces the inferred dependsOn',
143
+ });
144
+ }
145
+ else if (!resolvedTargetRunsTests(resolvedProject, CARGO_TEST_TARGET)) {
146
+ issues.push({
147
+ path,
148
+ message: `${scope}.${CARGO_TEST_TARGET} reaches no target that RUNS tests — only ones that compile them. ` +
149
+ 'A declared dependsOn replaces the inferred one; spread it with "..." instead of omitting the runner leg',
150
+ });
151
+ }
152
+ else {
153
+ const coverage = cargoTestMemberCoverageIssue(root, path, scope, resolvedProject);
154
+ if (coverage !== undefined) {
155
+ issues.push(coverage);
156
+ }
157
+ }
158
+ }
159
+ return issues;
160
+ }
161
+ /**
162
+ * True when `target`, or something in its dependency closure, invokes cargo in a
163
+ * mode that executes tests. `cargo-test-compile` is deliberately excluded: it is
164
+ * `cargo test --no-run`, so it proves the binaries build and nothing about them
165
+ * running.
166
+ */
167
+ function resolvedTargetRunsTests(project, target) {
168
+ const visiting = new Set();
169
+ const visit = (targetName) => {
170
+ if (visiting.has(targetName) || !project.targets.has(targetName)) {
171
+ return false;
172
+ }
173
+ visiting.add(targetName);
174
+ const command = commandOf(project, targetName);
175
+ const runs = command !== undefined && /\btest\b|\bnextest\b/.test(command) && !command.includes('--no-run');
176
+ const reached = runs ||
177
+ (project.targetDependencies?.get(targetName) ?? []).some((dependency) => matchingResolvedTargets(dependency, project.targets).some(visit));
178
+ visiting.delete(targetName);
179
+ return reached;
180
+ };
181
+ return visit(target);
182
+ }
183
+ /**
184
+ * Per-crate nextest targets that `cargo-test` actually reaches. `cargo-test-compile`
185
+ * is excluded: it is not a runner. Members come from the same Cargo.toml walk
186
+ * inference uses; the child list is the graph, not a hand-written crate list.
187
+ */
188
+ function cargoTestPackageChildren(project) {
189
+ const packages = new Set();
190
+ const visiting = new Set();
191
+ const visit = (targetName) => {
192
+ if (visiting.has(targetName) || !project.targets.has(targetName)) {
193
+ return;
194
+ }
195
+ visiting.add(targetName);
196
+ const pkg = packageNameFromCargoTestTarget(targetName);
197
+ if (pkg !== null) {
198
+ packages.add(pkg);
199
+ }
200
+ for (const dependency of project.targetDependencies?.get(targetName) ?? []) {
201
+ for (const matched of matchingResolvedTargets(dependency, project.targets)) {
202
+ visit(matched);
203
+ }
204
+ }
205
+ };
206
+ visit(CARGO_TEST_TARGET);
207
+ return [...packages].sort((left, right) => left.localeCompare(right));
208
+ }
209
+ function cargoTestMemberCoverageIssue(workspaceRoot, path, scope, project) {
210
+ if (typeof project.root !== 'string' || project.root.length === 0) {
211
+ return undefined;
212
+ }
213
+ const members = listCargoWorkspacePackages(join(workspaceRoot, project.root)).map((pkg) => pkg.name);
214
+ if (members.length === 0) {
215
+ return undefined;
216
+ }
217
+ const children = cargoTestPackageChildren(project);
218
+ if (children.length === 0) {
219
+ return undefined;
220
+ }
221
+ const memberSet = new Set(members);
222
+ const childSet = new Set(children);
223
+ const missing = members.filter((name) => !childSet.has(name));
224
+ const extra = children.filter((name) => !memberSet.has(name));
225
+ if (missing.length === 0 && extra.length === 0) {
226
+ return undefined;
227
+ }
228
+ const details = [
229
+ ...(missing.length > 0 ? [`missing ${missing.join(', ')}`] : []),
230
+ ...(extra.length > 0 ? [`extra ${extra.join(', ')}`] : []),
231
+ ];
232
+ return {
233
+ path,
234
+ message: `${scope}.${CARGO_TEST_TARGET} per-crate children must equal workspace members that have tests ` +
235
+ `(${members.join(', ')}); ${details.join('; ')}`,
236
+ };
237
+ }
238
+ function commandOf(project, targetName) {
239
+ const options = project.targetOptions?.get(targetName);
240
+ if (options === undefined || options === null) {
241
+ return undefined;
242
+ }
243
+ const command = options.command;
244
+ return typeof command === 'string' ? command : undefined;
245
+ }
246
+ function resolvedTargetReaches(project, from, goal) {
247
+ const visiting = new Set();
248
+ const visit = (targetName) => {
249
+ if (targetName === goal) {
250
+ return true;
251
+ }
252
+ if (visiting.has(targetName) || !project.targets.has(targetName)) {
253
+ return false;
254
+ }
255
+ visiting.add(targetName);
256
+ const reached = (project.targetDependencies?.get(targetName) ?? []).some((dependency) => matchingResolvedTargets(dependency, project.targets).some(visit));
257
+ visiting.delete(targetName);
258
+ return reached;
259
+ };
260
+ return visit(from);
261
+ }
91
262
  export function checkBoundedTestTargetPolicy(packageJson, options) {
92
263
  const testTarget = options.projectJson ? options.projectJson.targets?.test : packageJson.nx?.targets?.test;
93
264
  if (!isRecord(testTarget)) {
@@ -108,6 +279,29 @@ export function checkBoundedTestTargetPolicy(packageJson, options) {
108
279
  }
109
280
  return resolvedAggregateTestIsBounded(options.resolvedProject);
110
281
  }
282
+ /**
283
+ * Apply may only rewrite a test target it can express faithfully as one
284
+ * bounded `bun test` command. A `commands` array (a multi-runner gate) would
285
+ * be flattened to the default command — deleting the very checks the target
286
+ * exists to run — and a non-bun runner (cargo, go) would inherit wall-clock
287
+ * bounds scaled for bun suites. Those targets are left in place for the check
288
+ * to report, so restructuring them stays a human decision.
289
+ */
290
+ function boundableTestTarget(packageJson, projectJson) {
291
+ const target = projectJson?.targets?.test ?? packageJson.nx?.targets?.test;
292
+ if (!isRecord(target)) {
293
+ return true;
294
+ }
295
+ if (isNoopAggregateTarget(target)) {
296
+ return true;
297
+ }
298
+ const targetOptions = isRecord(target.options) ? target.options : undefined;
299
+ if (targetOptions && Array.isArray(targetOptions.commands)) {
300
+ return false;
301
+ }
302
+ const command = resolveTargetCommand(target);
303
+ return command === null || BUN_TEST_PREFIX.test(command);
304
+ }
111
305
  function isNoopAggregateTarget(target) {
112
306
  if (target.executor !== undefined && target.executor !== 'nx:noop') {
113
307
  return false;
@@ -0,0 +1,67 @@
1
+ export interface CargoWorkspacePackage {
2
+ name: string;
3
+ dir: string;
4
+ /**
5
+ * How many bounded Nx targets this crate's tests are split across. See
6
+ * `readTestShards` for why this is declared per crate rather than inferred.
7
+ */
8
+ testShards: number;
9
+ }
10
+ export declare function listCargoWorkspacePackages(absoluteProjectRoot: string): CargoWorkspacePackage[];
11
+ export declare function cargoPackageTestInputs(absoluteProjectRoot: string, memberDir: string): Promise<string[]>;
12
+ /**
13
+ * The aggregate that actually runs a cargo workspace's tests. Named here because
14
+ * both target inference and the policy that verifies `test` reaches it need the
15
+ * same string, and a drifted copy would make the policy vacuous.
16
+ */
17
+ export declare const CARGO_TEST_TARGET = "cargo-test";
18
+ /** Prerequisite that compiles the workspace; not a per-crate runner. */
19
+ export declare const CARGO_TEST_COMPILE_TARGET = "cargo-test-compile";
20
+ /**
21
+ * Tests that nextest.toml singles out are pinned to this suffix instead of
22
+ * being sharded. Only a sharded crate has one: an unsharded crate runs its
23
+ * whole suite in a single nextest process, which is all the pin restores.
24
+ */
25
+ export declare const CARGO_TEST_EXCEPTIONS_SUFFIX = "exceptions";
26
+ /**
27
+ * A crate on one target keeps the bare name; a split crate suffixes the piece,
28
+ * so `cargo-test-cowshed-core-shard2` still reads as "cowshed-core's tests".
29
+ */
30
+ export declare function cargoTestPackageTargetName(packageName: string, piece?: string): string;
31
+ /**
32
+ * Inverse of `cargoTestPackageTargetName`, used by the reachability policy to
33
+ * check that the per-crate targets cover every workspace member. Pieces of one
34
+ * crate collapse back to that crate, so a split crate counts as covered once.
35
+ */
36
+ export declare function packageNameFromCargoTestTarget(targetName: string): string | null;
37
+ /**
38
+ * The tests nextest.toml singles out with an override, as one filterset.
39
+ *
40
+ * An override is the config author saying "this class does not behave like the
41
+ * rest of the suite", and both classes declared today break a shard, each in a
42
+ * different way:
43
+ *
44
+ * - a `test-group` is scoped to a single nextest RUN, so letting the hash
45
+ * scatter its members across shards silently dissolves it. The real-APFS
46
+ * group exists because those tests contend on Disk Arbitration
47
+ * machine-wide, where an unscoped `diskutil apfs list -plist` measured 0.7s
48
+ * idle against 14.4s while another process is attaching.
49
+ * - a raised `slow-timeout` marks a test whose cost is not the suite's cost.
50
+ * `lesser_capabilities_fail_to_compile_...` rustc's a fixture that
51
+ * `cargo test --no-run` cannot pre-build, so it costs 25.6s on a cold
52
+ * target directory against 1.8s warm. Every CI runner is cold, and left in
53
+ * a shard that spike lands on whichever 250-odd tests share it.
54
+ *
55
+ * One target for all of them rather than one each: they sit in different groups
56
+ * so they run concurrently, making the combined wall the max of the classes
57
+ * rather than their sum.
58
+ *
59
+ * Deriving this from the config that declares the classes, rather than
60
+ * restating their filters, means adding an override there is the whole change —
61
+ * the pin follows and cannot drift from what it protects.
62
+ *
63
+ * Returns null when nothing is singled out, the "nothing to pin" case.
64
+ */
65
+ export declare function exceptionalTestFilter(nextestConfigPath: string): string | null;
66
+ export declare function nextestConfigRelPath(workspaceRoot: string, projectRoot: string, configAbs: string): string;
67
+ //# sourceMappingURL=cargo-workspace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cargo-workspace.d.ts","sourceRoot":"","sources":["../src/cargo-workspace.ts"],"names":[],"mappings":"AAKA,MAAM,WAAW,qBAAqB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,wBAAgB,0BAA0B,CAAC,mBAAmB,EAAE,MAAM,GAAG,qBAAqB,EAAE,CA8B/F;AAED,wBAAsB,sBAAsB,CAAC,mBAAmB,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAwB9G;AA6ED;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,eAAe,CAAC;AAE9C,wEAAwE;AACxE,eAAO,MAAM,yBAAyB,uBAAuB,CAAC;AAE9D;;;;GAIG;AACH,eAAO,MAAM,4BAA4B,eAAe,CAAC;AAEzD;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,WAAW,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAGtF;AAED;;;;GAIG;AACH,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAQhF;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,qBAAqB,CAAC,iBAAiB,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAoB9E;AAED,wBAAgB,oBAAoB,CAAC,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAG1G"}
@@ -0,0 +1,215 @@
1
+ import { existsSync, readFileSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join, normalize, posix, relative, sep } from 'node:path';
4
+ import { parse as parseToml } from 'smol-toml';
5
+ export function listCargoWorkspacePackages(absoluteProjectRoot) {
6
+ const workspaceTomlPath = join(absoluteProjectRoot, 'Cargo.toml');
7
+ if (!existsSync(workspaceTomlPath)) {
8
+ return [];
9
+ }
10
+ const parsed = parseToml(readFileSync(workspaceTomlPath, 'utf-8'));
11
+ if (!isRecord(parsed) || !isRecord(parsed.workspace) || !Array.isArray(parsed.workspace.members)) {
12
+ return [];
13
+ }
14
+ const packages = [];
15
+ for (const member of parsed.workspace.members) {
16
+ if (typeof member !== 'string' || member.length === 0) {
17
+ continue;
18
+ }
19
+ const crateTomlPath = join(absoluteProjectRoot, member, 'Cargo.toml');
20
+ if (!existsSync(crateTomlPath)) {
21
+ continue;
22
+ }
23
+ const crateParsed = parseToml(readFileSync(crateTomlPath, 'utf-8'));
24
+ if (!isRecord(crateParsed) || !isRecord(crateParsed.package) || typeof crateParsed.package.name !== 'string') {
25
+ continue;
26
+ }
27
+ packages.push({
28
+ name: crateParsed.package.name,
29
+ dir: member.split('\\').join('/'),
30
+ testShards: readTestShards(crateParsed.package, crateTomlPath),
31
+ });
32
+ }
33
+ packages.sort((left, right) => left.name.localeCompare(right.name));
34
+ return packages;
35
+ }
36
+ export async function cargoPackageTestInputs(absoluteProjectRoot, memberDir) {
37
+ const workspacePathDeps = await workspacePathDependencies(absoluteProjectRoot);
38
+ const dirs = new Set([memberDir.split('\\').join('/')]);
39
+ const crateParsed = parseToml(await readFile(join(absoluteProjectRoot, memberDir, 'Cargo.toml'), 'utf-8'));
40
+ if (isRecord(crateParsed)) {
41
+ for (const tableName of ['dependencies', 'dev-dependencies', 'build-dependencies']) {
42
+ const table = crateParsed[tableName];
43
+ if (!isRecord(table)) {
44
+ continue;
45
+ }
46
+ for (const [depName, spec] of Object.entries(table)) {
47
+ const pathDep = pathDependencyDir(memberDir, depName, spec, workspacePathDeps);
48
+ if (pathDep !== null) {
49
+ dirs.add(pathDep);
50
+ }
51
+ }
52
+ }
53
+ }
54
+ const inputs = ['{projectRoot}/Cargo.toml', '{projectRoot}/Cargo.lock'];
55
+ for (const dir of [...dirs].sort()) {
56
+ inputs.push(`{projectRoot}/${dir}/**/*.rs`, `{projectRoot}/${dir}/Cargo.toml`);
57
+ }
58
+ inputs.push('{projectRoot}/**/.cargo/config.toml', '{projectRoot}/scripts/*.sh', '!{projectRoot}/**/target/**');
59
+ return inputs;
60
+ }
61
+ async function workspacePathDependencies(absoluteProjectRoot) {
62
+ const parsed = parseToml(await readFile(join(absoluteProjectRoot, 'Cargo.toml'), 'utf-8'));
63
+ const deps = new Map();
64
+ if (!isRecord(parsed) || !isRecord(parsed.workspace) || !isRecord(parsed.workspace.dependencies)) {
65
+ return deps;
66
+ }
67
+ for (const [name, spec] of Object.entries(parsed.workspace.dependencies)) {
68
+ if (isRecord(spec) && typeof spec.path === 'string') {
69
+ deps.set(name, spec.path.split('\\').join('/'));
70
+ }
71
+ }
72
+ return deps;
73
+ }
74
+ function pathDependencyDir(memberDir, depName, spec, workspacePathDeps) {
75
+ if (spec === undefined || spec === null) {
76
+ return null;
77
+ }
78
+ if (typeof spec === 'string') {
79
+ return null;
80
+ }
81
+ if (!isRecord(spec)) {
82
+ return null;
83
+ }
84
+ if (spec.workspace === true) {
85
+ return workspacePathDeps.get(depName) ?? null;
86
+ }
87
+ if (typeof spec.path !== 'string') {
88
+ return null;
89
+ }
90
+ const resolved = normalize(join(memberDir, spec.path));
91
+ if (resolved.startsWith('..')) {
92
+ return null;
93
+ }
94
+ return resolved.split(sep).join(posix.sep);
95
+ }
96
+ function isRecord(value) {
97
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
98
+ }
99
+ /**
100
+ * `[package.metadata.smoothbricks.test] shards = N` splits a crate's tests
101
+ * across N bounded targets, each running `--partition hash:i/N`.
102
+ *
103
+ * The COUNT is declared and the MEMBERSHIP is derived: nextest hashes each test
104
+ * name into a shard, so a new test — or a whole new test binary — is absorbed
105
+ * with no edit here and no list to forget to update. A stale count can only
106
+ * make a target slow, never make a test disappear, because the shards remain an
107
+ * exact partition of whatever the crate currently contains.
108
+ *
109
+ * It is declared rather than inferred because the only honest input is how long
110
+ * the suite takes, which target inference cannot measure. Defaulting to 1 keeps
111
+ * small crates on a single target: cowshed-cli's 226 tests run in 6.5s, so
112
+ * sharding them would buy nothing and pay a per-target cargo freshness check.
113
+ */
114
+ function readTestShards(cratePackage, crateTomlPath) {
115
+ const metadata = isRecord(cratePackage.metadata) ? cratePackage.metadata : null;
116
+ const smoothbricks = metadata && isRecord(metadata.smoothbricks) ? metadata.smoothbricks : null;
117
+ const test = smoothbricks && isRecord(smoothbricks.test) ? smoothbricks.test : null;
118
+ const shards = test?.shards;
119
+ if (shards === undefined) {
120
+ return 1;
121
+ }
122
+ if (typeof shards !== 'number' || !Number.isInteger(shards) || shards < 1) {
123
+ throw new Error(`${crateTomlPath}: smoothbricks.test.shards must be an integer >= 1, got ${String(shards)}`);
124
+ }
125
+ return shards;
126
+ }
127
+ /**
128
+ * The aggregate that actually runs a cargo workspace's tests. Named here because
129
+ * both target inference and the policy that verifies `test` reaches it need the
130
+ * same string, and a drifted copy would make the policy vacuous.
131
+ */
132
+ export const CARGO_TEST_TARGET = 'cargo-test';
133
+ /** Prerequisite that compiles the workspace; not a per-crate runner. */
134
+ export const CARGO_TEST_COMPILE_TARGET = 'cargo-test-compile';
135
+ /**
136
+ * Tests that nextest.toml singles out are pinned to this suffix instead of
137
+ * being sharded. Only a sharded crate has one: an unsharded crate runs its
138
+ * whole suite in a single nextest process, which is all the pin restores.
139
+ */
140
+ export const CARGO_TEST_EXCEPTIONS_SUFFIX = 'exceptions';
141
+ /**
142
+ * A crate on one target keeps the bare name; a split crate suffixes the piece,
143
+ * so `cargo-test-cowshed-core-shard2` still reads as "cowshed-core's tests".
144
+ */
145
+ export function cargoTestPackageTargetName(packageName, piece) {
146
+ const base = `cargo-test-${packageName}`;
147
+ return piece === undefined ? base : `${base}-${piece}`;
148
+ }
149
+ /**
150
+ * Inverse of `cargoTestPackageTargetName`, used by the reachability policy to
151
+ * check that the per-crate targets cover every workspace member. Pieces of one
152
+ * crate collapse back to that crate, so a split crate counts as covered once.
153
+ */
154
+ export function packageNameFromCargoTestTarget(targetName) {
155
+ if (!targetName.startsWith('cargo-test-') || targetName === CARGO_TEST_COMPILE_TARGET) {
156
+ return null;
157
+ }
158
+ const name = targetName
159
+ .slice('cargo-test-'.length)
160
+ .replace(new RegExp(`-(shard[1-9][0-9]*|${CARGO_TEST_EXCEPTIONS_SUFFIX})$`), '');
161
+ return name.length === 0 ? null : name;
162
+ }
163
+ /**
164
+ * The tests nextest.toml singles out with an override, as one filterset.
165
+ *
166
+ * An override is the config author saying "this class does not behave like the
167
+ * rest of the suite", and both classes declared today break a shard, each in a
168
+ * different way:
169
+ *
170
+ * - a `test-group` is scoped to a single nextest RUN, so letting the hash
171
+ * scatter its members across shards silently dissolves it. The real-APFS
172
+ * group exists because those tests contend on Disk Arbitration
173
+ * machine-wide, where an unscoped `diskutil apfs list -plist` measured 0.7s
174
+ * idle against 14.4s while another process is attaching.
175
+ * - a raised `slow-timeout` marks a test whose cost is not the suite's cost.
176
+ * `lesser_capabilities_fail_to_compile_...` rustc's a fixture that
177
+ * `cargo test --no-run` cannot pre-build, so it costs 25.6s on a cold
178
+ * target directory against 1.8s warm. Every CI runner is cold, and left in
179
+ * a shard that spike lands on whichever 250-odd tests share it.
180
+ *
181
+ * One target for all of them rather than one each: they sit in different groups
182
+ * so they run concurrently, making the combined wall the max of the classes
183
+ * rather than their sum.
184
+ *
185
+ * Deriving this from the config that declares the classes, rather than
186
+ * restating their filters, means adding an override there is the whole change —
187
+ * the pin follows and cannot drift from what it protects.
188
+ *
189
+ * Returns null when nothing is singled out, the "nothing to pin" case.
190
+ */
191
+ export function exceptionalTestFilter(nextestConfigPath) {
192
+ const parsed = parseToml(readFileSync(nextestConfigPath, 'utf-8'));
193
+ if (!isRecord(parsed)) {
194
+ return null;
195
+ }
196
+ const profiles = isRecord(parsed.profile) ? parsed.profile : {};
197
+ const filters = [];
198
+ for (const profile of Object.values(profiles)) {
199
+ const overrides = isRecord(profile) ? profile.overrides : undefined;
200
+ if (!Array.isArray(overrides)) {
201
+ continue;
202
+ }
203
+ for (const override of overrides) {
204
+ if (isRecord(override) && typeof override.filter === 'string' && override.filter.length > 0) {
205
+ filters.push(override.filter);
206
+ }
207
+ }
208
+ }
209
+ const unique = [...new Set(filters)];
210
+ return unique.length === 0 ? null : unique.map((filter) => `(${filter})`).join(' or ');
211
+ }
212
+ export function nextestConfigRelPath(workspaceRoot, projectRoot, configAbs) {
213
+ const rel = relative(join(workspaceRoot, projectRoot), configAbs);
214
+ return rel.length === 0 ? configAbs : rel.split(sep).join('/');
215
+ }
@@ -34,6 +34,58 @@ export declare const DEVENV_CROSS_PROFILE = "linux-cross";
34
34
  * build-output families, so no aggregate `build` picks it up either.
35
35
  */
36
36
  export declare const CARGO_CROSS_LINT_TARGET = "cargo-lint-cross";
37
+ /**
38
+ * Point this cargo at a project-local home so parallel Nx cargos do not
39
+ * exclusive-lock `~/.cargo/.package-cache`. Downloaded crates stay shared.
40
+ */
41
+ export declare function withProjectCargoHome(homeRel: string, command: string): string;
42
+ /**
43
+ * The prefix `cargoFrozen` writes. Exported so target inference can recognize
44
+ * the commands whose precondition `CARGO_FETCH_TARGET` supplies without
45
+ * re-spelling the flag; a second copy would silently stop matching.
46
+ */
47
+ export declare const CARGO_FROZEN_PREFIX = "cargo --frozen ";
48
+ /**
49
+ * `--frozen` is cargo's `--locked` + `--offline`. Cargo.lock and the registry
50
+ * cache are inputs: inferred cargo must not rewrite the lockfile or fetch.
51
+ * The flag sits on `cargo` so nextest sees a cargo-level option, not its own.
52
+ *
53
+ * The registry cache being an INPUT is a precondition, and offline cargo
54
+ * enforces it at RESOLUTION, before it selects a single target: an offline
55
+ * registry source only reports packages already downloaded, so one absent
56
+ * member of the lockfile's graph makes the whole workspace unresolvable with
57
+ * `no matching package named <dep> found`. The failure therefore has nothing to
58
+ * do with which targets a command builds — `build`, `check`, `test --lib` and
59
+ * `test --no-run` all fail identically on a dependency only a bench needs — and
60
+ * narrowing a command's target selection cannot cure it.
61
+ *
62
+ * Dev- and bench-only dependencies are the exposed class. A build downloads the
63
+ * normal dependency graph, so on a runner that builds before it tests those are
64
+ * warm by accident; nothing downloads a dev-dependency until something compiles
65
+ * a test target, and by then `--frozen` refuses to. `CARGO_FETCH_TARGET` below
66
+ * turns that accident into a stated dependency.
67
+ */
68
+ export declare function cargoFrozen(args: string): string;
69
+ /**
70
+ * Nx target name. Downloads one Cargo workspace's locked dependency graph so
71
+ * every `cargoFrozen` command in that workspace can resolve offline. No colons,
72
+ * per the repo's target-naming rule, and outside the `-js`/`-napi`/`-wasm` and
73
+ * platform-suffix families so no aggregate sweeps it up.
74
+ */
75
+ export declare const CARGO_FETCH_TARGET = "cargo-fetch";
76
+ /**
77
+ * `--locked` rather than bare `cargo fetch`: this downloads exactly the graph
78
+ * Cargo.lock pins and fails loudly on a stale lockfile. Without it a fetch could
79
+ * re-resolve and hand `--frozen` a cache built from a different graph than the
80
+ * lockfile names, which is the guarantee `--frozen` exists to give.
81
+ *
82
+ * `fetch` and nothing else, because fetching is the only act that needs the
83
+ * network; every compile downstream stays frozen.
84
+ *
85
+ * No `--target`: with no triple named cargo fetches every target's
86
+ * dependencies, so one run also covers `CARGO_CROSS_LINT_TARGET`'s Linux triple.
87
+ */
88
+ export declare const CARGO_FETCH_COMMAND = "cargo fetch --locked";
37
89
  /**
38
90
  * Clippy rather than `cargo check`, and `-D warnings`, because that is exactly
39
91
  * what CI's `lint` runs; a weaker local command would pass where CI fails.
@@ -51,8 +103,15 @@ export declare const CARGO_CROSS_LINT_TARGET = "cargo-lint-cross";
51
103
  *
52
104
  * `cargo fmt` is absent on purpose: formatting is target-independent and already
53
105
  * covered by `cargo-lint`, so repeating it here would only cost time.
106
+ *
107
+ * `CARGO_HOME` is per-project (`$PWD/target/cargo-lint-cross-home`). Cargo's
108
+ * package-cache flock lives in CARGO_HOME; three workspaces otherwise serialize
109
+ * on `~/.cargo/.package-cache` even with distinct `--target-dir`. Registry and
110
+ * git are linked to the host home so crates are not re-fetched. `--frozen`
111
+ * keeps that shared registry read-only: lockfile and cache are inputs.
54
112
  */
55
- export declare const CARGO_CROSS_LINT_COMMAND = "cargo clippy --workspace --all-targets --target x86_64-unknown-linux-gnu -- -D warnings";
113
+ export declare const CARGO_CROSS_LINT_COMMAND: string;
114
+ export declare const CARGO_LINT_CLIPPY_COMMAND: string;
56
115
  /** Root `package.json` script name, in the repo's `verb:qualifier` style. */
57
116
  export declare const CROSS_CHECK_SCRIPT_NAME = "check:linux";
58
117
  /**