@smoothbricks/nx-plugin 0.4.21 → 0.4.23

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 (64) hide show
  1. package/README.md +95 -18
  2. package/dist/bin/smoo-nx-cargo-hash.js +32 -6
  3. package/dist/bin/smoo-nx-exec.js +35 -11
  4. package/dist/cargo-closure-input.d.ts +63 -0
  5. package/dist/cargo-closure-input.d.ts.map +1 -0
  6. package/dist/cargo-closure-input.js +197 -0
  7. package/dist/cargo-source-hash.d.ts +46 -2
  8. package/dist/cargo-source-hash.d.ts.map +1 -1
  9. package/dist/cargo-source-hash.js +238 -114
  10. package/dist/cross-check-policy.d.ts +14 -0
  11. package/dist/cross-check-policy.d.ts.map +1 -1
  12. package/dist/cross-check-policy.js +15 -1
  13. package/dist/ensure-built.d.ts +3 -2
  14. package/dist/ensure-built.d.ts.map +1 -1
  15. package/dist/ensure-built.js +33 -56
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +112 -76
  18. package/dist/managed-files/ci-workflow.d.ts.map +1 -1
  19. package/dist/managed-files/ci-workflow.js +12 -15
  20. package/dist/managed-files/files.d.ts.map +1 -1
  21. package/dist/managed-files/files.js +10 -0
  22. package/dist/managed-files/publish-workflow.d.ts.map +1 -1
  23. package/dist/managed-files/publish-workflow.js +12 -6
  24. package/dist/manifest-hash.d.ts.map +1 -1
  25. package/dist/manifest-hash.js +24 -30
  26. package/dist/package-target-policy.js +1 -1
  27. package/dist/platform-targets.d.ts +7 -0
  28. package/dist/platform-targets.d.ts.map +1 -1
  29. package/dist/platform-targets.js +7 -0
  30. package/dist/workspace-config-policy.d.ts +1 -1
  31. package/dist/workspace-config-policy.d.ts.map +1 -1
  32. package/dist/workspace-config-policy.js +1 -1
  33. package/managed/raw/envrc +38 -1
  34. package/managed/raw/tooling/direnv/developer-links.ts +201 -0
  35. package/managed/raw/tooling/direnv/devenv.smoo.nix +75 -51
  36. package/managed/raw/tooling/direnv/secret-references.ts +3 -1
  37. package/managed/raw/tooling/direnv/setup-environment.ts +562 -78
  38. package/managed/raw/tooling/direnv/shared-caches.sh +53 -0
  39. package/managed/raw/tooling/git-hooks/pre-push.sh +22 -1
  40. package/managed/templates/github/workflows/managed-files.yml +4 -3
  41. package/nextest.toml +5 -5
  42. package/package.json +2 -2
  43. package/src/__tests__/fixture-nx-env.ts +31 -0
  44. package/src/__tests__/in-process-nx-index.ts +9 -0
  45. package/src/bin/smoo-nx-cargo-hash.ts +29 -9
  46. package/src/bin/smoo-nx-exec.ts +40 -11
  47. package/src/cargo-closure-input.test.ts +184 -0
  48. package/src/cargo-closure-input.ts +247 -0
  49. package/src/cargo-source-hash.test.ts +104 -10
  50. package/src/cargo-source-hash.ts +290 -37
  51. package/src/cross-check-policy.ts +15 -3
  52. package/src/ensure-built.test.ts +65 -5
  53. package/src/ensure-built.ts +40 -85
  54. package/src/index.test.ts +94 -53
  55. package/src/index.ts +164 -84
  56. package/src/managed-files/ci-workflow.ts +12 -15
  57. package/src/managed-files/files.ts +10 -0
  58. package/src/managed-files/generator.test.ts +29 -0
  59. package/src/managed-files/publish-workflow.ts +17 -6
  60. package/src/manifest-hash.test.ts +21 -1
  61. package/src/manifest-hash.ts +26 -29
  62. package/src/package-target-policy.ts +1 -1
  63. package/src/platform-targets.ts +8 -0
  64. package/src/workspace-config-policy.ts +6 -1
@@ -1,21 +1,116 @@
1
- import { execFileSync } from 'node:child_process';
1
+ import { execFile, execFileSync, spawnSync } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
- import { statSync } from 'node:fs';
3
+ import { realpathSync, statSync } from 'node:fs';
4
4
  import { lstat, readdir, readFile, readlink, realpath } from 'node:fs/promises';
5
5
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
- import typia from 'typia';
7
6
 
7
+ /** The fields of `cargo metadata --format-version 1` this module reads. */
8
8
  interface CargoMetadata {
9
9
  packages: {
10
+ id: string;
10
11
  source: string | null;
11
12
  manifest_path: string;
12
13
  targets: { src_path: string }[];
13
14
  }[];
15
+ resolve: { nodes: { id: string; deps: { pkg: string }[] }[] } | null;
16
+ workspace_members: string[];
14
17
  workspace_root: string;
15
18
  }
16
19
 
17
- const parseMetadata = typia.json.createAssertParse<CargoMetadata>();
18
- const ignoredDirectories = new Set([
20
+ /**
21
+ * Narrowed field by field, not by typia: graph inference imports this module,
22
+ * and a workspace that loads the plugin from its sources runs them without
23
+ * typia's compile-time transform.
24
+ */
25
+ function parseCargoMetadata(json: string): CargoMetadata {
26
+ const member = (value: unknown, key: string): unknown =>
27
+ typeof value === 'object' && value !== null && key in value ? Reflect.get(value, key) : undefined;
28
+ const text = (value: unknown, field: string): string => {
29
+ if (typeof value !== 'string') throw new Error(`cargo metadata reported no valid ${field}`);
30
+ return value;
31
+ };
32
+ const list = (value: unknown, field: string): unknown[] => {
33
+ if (!Array.isArray(value)) throw new Error(`cargo metadata reported no valid ${field}`);
34
+ return value;
35
+ };
36
+ const document: unknown = JSON.parse(json);
37
+ const resolveGraph = member(document, 'resolve');
38
+ return {
39
+ packages: list(member(document, 'packages'), 'packages').map((pkg) => ({
40
+ id: text(member(pkg, 'id'), 'package id'),
41
+ source: member(pkg, 'source') === null ? null : text(member(pkg, 'source'), 'package source'),
42
+ manifest_path: text(member(pkg, 'manifest_path'), 'package manifest_path'),
43
+ targets: list(member(pkg, 'targets'), 'package targets').map((target) => ({
44
+ src_path: text(member(target, 'src_path'), 'target src_path'),
45
+ })),
46
+ })),
47
+ resolve:
48
+ resolveGraph === null
49
+ ? null
50
+ : {
51
+ nodes: list(member(resolveGraph, 'nodes'), 'resolve').map((node) => ({
52
+ id: text(member(node, 'id'), 'resolve node id'),
53
+ deps: list(member(node, 'deps'), 'resolve node deps').map((dependency) => ({
54
+ pkg: text(member(dependency, 'pkg'), 'resolve edge'),
55
+ })),
56
+ })),
57
+ },
58
+ workspace_members: list(member(document, 'workspace_members'), 'workspace_members').map((id) =>
59
+ text(id, 'workspace member'),
60
+ ),
61
+ workspace_root: text(member(document, 'workspace_root'), 'workspace_root'),
62
+ };
63
+ }
64
+
65
+ /** A mutable (path) package in Cargo's locked resolve. Every path is canonical. */
66
+ export interface LocalCargoPackage {
67
+ readonly id: string;
68
+ readonly directory: string;
69
+ readonly manifest: string;
70
+ /** Every target's source file: library, binaries, tests, build script. A target may live outside `directory`. */
71
+ readonly sources: readonly string[];
72
+ }
73
+
74
+ /** What locked, offline `cargo metadata` reports about one Cargo workspace's mutable packages. */
75
+ export interface CargoResolve {
76
+ /** The canonical Cargo workspace root. */
77
+ readonly root: string;
78
+ /** The workspace's own members: `root`'s manifest governs each of them. */
79
+ readonly members: ReadonlySet<string>;
80
+ readonly local: readonly LocalCargoPackage[];
81
+ /** Every dependency edge by package id, or null when Cargo reported no resolution. */
82
+ readonly edges: ReadonlyMap<string, readonly string[]> | null;
83
+ }
84
+
85
+ export interface CargoPathInputsOptions {
86
+ /** Also hash packages inside both the Nx and Cargo workspaces, for custom targets without inferred Cargo inputs. */
87
+ includeWorkspace?: boolean;
88
+ /**
89
+ * Hash only the resolved dependency closure of the local packages whose manifests lie under this directory
90
+ * (resolved like `manifestPath`), instead of every package in the Cargo workspace.
91
+ */
92
+ closure?: string;
93
+ }
94
+
95
+ /**
96
+ * Cargo's stdout, or its failure with Cargo's stderr in the message. Not
97
+ * `promisify` from `node:util`: importing that module makes Node probe color
98
+ * support at startup, and with FORCE_COLOR and NO_COLOR both set (an Nx
99
+ * inside an Nx task, in a shell that exports NO_COLOR) it warns on stderr
100
+ * under its own pid, which a runtime input would hash as a new digest on
101
+ * every run.
102
+ */
103
+ function runCargo(args: readonly string[], cwd: string): Promise<string> {
104
+ // The executor form: the workspace compiles against es2022, which has no `Promise.withResolvers`.
105
+ return new Promise((settle, reject) => {
106
+ execFile('cargo', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }, (error, stdout) =>
107
+ error === null ? settle(stdout) : reject(error),
108
+ );
109
+ });
110
+ }
111
+
112
+ /** Directories the hash never descends into: build output, VCS and volume metadata, installed packages. */
113
+ export const HASH_SKIPPED_DIRECTORIES = [
19
114
  'target',
20
115
  '.git',
21
116
  'node_modules',
@@ -26,8 +121,9 @@ const ignoredDirectories = new Set([
26
121
  '.Trashes',
27
122
  '.Spotlight-V100',
28
123
  '.DocumentRevisions-V100',
29
- ]);
30
- const ancestorInputs = ['Cargo.toml', '.cargo/config', '.cargo/config.toml'];
124
+ ] as const;
125
+ /** Files in every ancestor of a package directory that Cargo reads while building it. */
126
+ export const CARGO_ANCESTOR_INPUTS = ['Cargo.toml', '.cargo/config', '.cargo/config.toml'] as const;
31
127
 
32
128
  /**
33
129
  * Cargo owns resolution, including workspace inheritance, target dependencies,
@@ -36,44 +132,88 @@ const ancestorInputs = ['Cargo.toml', '.cargo/config', '.cargo/config.toml'];
36
132
  * registry packages are immutable inputs already identified by Cargo.lock.
37
133
  * By default, Nx's in-workspace inputs own workspace packages; includeWorkspace
38
134
  * also covers those packages for custom targets without inferred Cargo inputs.
135
+ * `closure` narrows the packages to what the local packages under one
136
+ * directory actually depend on, so an edit to an unrelated workspace member
137
+ * leaves the digest alone.
39
138
  *
40
139
  * This covers Rust sources and Cargo configuration, matching the plugin's
41
140
  * in-workspace Rust inputs. Build scripts' other data/environment inputs remain
42
- * explicit Nx inputs, just as they are for in-workspace crates.
141
+ * explicit Nx inputs, just as they are for in-workspace crates. Files git
142
+ * ignores beneath a package are left out, like Nx's own file inputs: a
143
+ * generated source is its producer's output, which the consuming target hashes
144
+ * through `dependentTasksOutputFiles`, and a tree that has not generated it yet
145
+ * must hash like one that has.
43
146
  */
44
147
  // Nx hashes a runtime input's stdout AND stderr. Cargo reports lock contention
45
148
  // on stderr ("Blocking waiting for file lock on package cache") a
46
149
  // timing-dependent number of times when Nx hashes many tasks at once, which
47
150
  // made one unchanged tree produce four different task hashes per run. Cargo's
48
- // stderr is kept for the failure path only, where execFileSync attaches it to
49
- // the thrown error.
50
- const CARGO_STDIO: ['ignore', 'pipe', 'pipe'] = ['ignore', 'pipe', 'pipe'];
151
+ // stderr is kept for the failure path only, where execFile attaches it to the
152
+ // rejected error. Git runs under the same rule.
153
+ const CHILD_STDIO: ['ignore', 'pipe', 'pipe'] = ['ignore', 'pipe', 'pipe'];
154
+
155
+ /** Locked, offline `cargo metadata` for the workspace `manifestPath` names, run from `cwd`. */
156
+ export async function readCargoResolve(manifestPath: string, cwd: string): Promise<CargoResolve> {
157
+ const stdout = await runCargo(
158
+ ['metadata', '--format-version', '1', '--locked', '--offline', '--manifest-path', resolve(manifestPath)],
159
+ cwd,
160
+ );
161
+ const metadata = parseCargoMetadata(stdout);
162
+ const local = await Promise.all(
163
+ metadata.packages
164
+ .filter((pkg) => pkg.source === null)
165
+ .map(async (pkg): Promise<LocalCargoPackage> => {
166
+ const manifest = await realpath(pkg.manifest_path);
167
+ const sources = await Promise.all(pkg.targets.map((target) => realpath(target.src_path)));
168
+ return { id: pkg.id, directory: dirname(manifest), manifest, sources };
169
+ }),
170
+ );
171
+ return {
172
+ root: await realpath(metadata.workspace_root),
173
+ members: new Set(metadata.workspace_members),
174
+ local,
175
+ edges:
176
+ metadata.resolve === null
177
+ ? null
178
+ : new Map(metadata.resolve.nodes.map((node) => [node.id, node.deps.map((dependency) => dependency.pkg)])),
179
+ };
180
+ }
181
+
182
+ /**
183
+ * The canonical root manifest of the Cargo workspace that governs `pkg`.
184
+ * Metadata's `workspace_root` describes only the invoking workspace, which is
185
+ * the answer for its own members. Any other path package asks Cargo, which
186
+ * resolves an explicit `package.workspace` as well as the ancestor search.
187
+ */
188
+ export async function governingManifest(cargo: CargoResolve, pkg: LocalCargoPackage, cwd: string): Promise<string> {
189
+ if (cargo.members.has(pkg.id)) return realpath(join(cargo.root, 'Cargo.toml'));
190
+ const stdout = await runCargo(
191
+ ['locate-project', '--workspace', '--manifest-path', pkg.manifest, '--message-format', 'plain'],
192
+ cwd,
193
+ );
194
+ return realpath(stdout.trim());
195
+ }
51
196
 
52
197
  export async function hashCargoPathInputs(
53
198
  manifestPath: string,
54
199
  workspaceRoot: string,
55
- options?: { includeWorkspace?: boolean },
200
+ options?: CargoPathInputsOptions,
56
201
  ): Promise<string> {
57
202
  const root = await realpath(workspaceRoot);
58
- const metadata = parseMetadata(
59
- execFileSync(
60
- 'cargo',
61
- ['metadata', '--format-version', '1', '--locked', '--offline', '--manifest-path', resolve(manifestPath)],
62
- { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: CARGO_STDIO },
63
- ),
64
- );
65
- const cargoRoot = await realpath(metadata.workspace_root);
203
+ const cargo = await readCargoResolve(manifestPath, root);
204
+ const members = options?.closure === undefined ? undefined : await dependencyClosure(cargo, resolve(options.closure));
205
+
66
206
  const directories = new Set<string>();
67
207
  const files = new Set<string>();
68
208
  const ancestors = new Set<string>();
69
209
  const links = new Map<string, string>();
70
- for (const pkg of metadata.packages) {
71
- if (pkg.source !== null) continue;
72
- const manifest = await realpath(pkg.manifest_path);
73
- const directory = dirname(manifest);
210
+ const packageSources: string[] = [];
211
+ for (const pkg of cargo.local) {
212
+ if (members !== undefined && !members.has(pkg.id)) continue;
213
+ const directory = pkg.directory;
74
214
  if (!options?.includeWorkspace) {
75
215
  const fromRoot = relative(root, directory);
76
- const fromCargo = relative(cargoRoot, directory);
216
+ const fromCargo = relative(cargo.root, directory);
77
217
  if (
78
218
  fromRoot !== '..' &&
79
219
  !fromRoot.startsWith(`..${sep}`) &&
@@ -86,28 +226,24 @@ export async function hashCargoPathInputs(
86
226
  continue;
87
227
  }
88
228
  directories.add(directory);
89
- files.add(manifest);
90
- // Cargo resolves explicit package.workspace ownership as well as ancestor
91
- // workspaces. Metadata's workspace_root describes only the invoking root.
92
- const governingManifest = execFileSync(
93
- 'cargo',
94
- ['locate-project', '--workspace', '--manifest-path', manifest, '--message-format', 'plain'],
95
- { cwd: root, encoding: 'utf8', stdio: CARGO_STDIO },
96
- ).trim();
97
- files.add(await realpath(governingManifest));
98
- for (const target of pkg.targets) files.add(await realpath(target.src_path));
229
+ files.add(pkg.manifest);
230
+ files.add(await governingManifest(cargo, pkg, root));
231
+ packageSources.push(...pkg.sources);
99
232
  // A member can inherit edition, lint policy, dependencies and
100
233
  // profiles from a workspace above its package directory. Those manifests
101
234
  // are not descendants of the source roots returned by Cargo metadata.
102
235
  for (let ancestor = dirname(directory); !ancestors.has(ancestor); ancestor = dirname(ancestor)) {
103
236
  ancestors.add(ancestor);
104
- for (const name of ancestorInputs) {
237
+ for (const name of CARGO_ANCESTOR_INPUTS) {
105
238
  const file = join(ancestor, name);
106
239
  if (statSync(file, { throwIfNoEntry: false })?.isFile()) files.add(await realpath(file));
107
240
  }
108
241
  }
109
242
  }
110
243
 
244
+ const ignored = gitIgnoredBeneath([...directories]);
245
+ for (const source of packageSources) if (!ignored(source)) files.add(source);
246
+ const skipped: ReadonlySet<string> = new Set(HASH_SKIPPED_DIRECTORIES);
111
247
  // Overlapping packages (a facade root plus its child crates) share one walk.
112
248
  const visited = new Set<string>();
113
249
  async function walk(directory: string): Promise<void> {
@@ -115,8 +251,9 @@ export async function hashCargoPathInputs(
115
251
  if (visited.has(canonical)) return;
116
252
  visited.add(canonical);
117
253
  for (const entry of await readdir(canonical, { withFileTypes: true })) {
118
- if (ignoredDirectories.has(entry.name)) continue;
254
+ if (skipped.has(entry.name)) continue;
119
255
  const path = join(canonical, entry.name);
256
+ if (ignored(path)) continue;
120
257
  if (entry.isSymbolicLink()) links.set(path, await readlink(path));
121
258
  const info = entry.isSymbolicLink() ? await lstat(await realpath(path)) : entry;
122
259
  if (info.isDirectory()) {
@@ -152,3 +289,119 @@ export async function hashCargoPathInputs(
152
289
  }
153
290
  return hash.digest('hex');
154
291
  }
292
+
293
+ /**
294
+ * The ids Cargo's resolve graph reaches from the local packages under
295
+ * `directory`, over every dependency kind: a target may build, test or run
296
+ * build scripts, and any of those compiles the edge's source.
297
+ */
298
+ export async function dependencyClosure(cargo: CargoResolve, directory: string): Promise<ReadonlySet<string>> {
299
+ const base = await realpath(directory);
300
+ const pending = cargo.local
301
+ .filter((pkg) => pkg.directory === base || pkg.directory.startsWith(`${base}${sep}`))
302
+ .map((pkg) => pkg.id);
303
+ if (pending.length === 0) throw new Error(`no local Cargo package lies under ${directory}`);
304
+ if (cargo.edges === null) throw new Error('cargo metadata reported no dependency resolution');
305
+ const reached = new Set<string>();
306
+ for (let id = pending.pop(); id !== undefined; id = pending.pop()) {
307
+ if (reached.has(id)) continue;
308
+ reached.add(id);
309
+ for (const dependency of cargo.edges.get(id) ?? []) pending.push(dependency);
310
+ }
311
+ return reached;
312
+ }
313
+
314
+ /**
315
+ * Whether git ignores a path beneath one of the package directories. A
316
+ * package whose own directory is ignored (an installed dependency, say) keeps
317
+ * every file, and a directory outside any git repository ignores nothing.
318
+ */
319
+ function gitIgnoredBeneath(directories: readonly string[]): (path: string) => boolean {
320
+ const byRepository = new Map<string, string[]>();
321
+ for (const directory of directories) {
322
+ const repository = gitRepository(directory);
323
+ if (repository === undefined) continue;
324
+ const members = byRepository.get(repository) ?? [];
325
+ members.push(directory);
326
+ byRepository.set(repository, members);
327
+ }
328
+ const files = new Set<string>();
329
+ const trees: string[] = [];
330
+ for (const [repository, members] of byRepository) {
331
+ const relativeMembers = members.map((member) => relative(repository, member) || '.');
332
+ // A package whose own directory git ignores is an installed tree, not a source tree with
333
+ // generated files in it. It also stays out of ls-files, which fails outright on a pathspec
334
+ // inside an ignored directory ("directory entry not superset of prefix").
335
+ const ignoredRoots = new Set(gitCheckIgnore(repository, relativeMembers));
336
+ const sourceRoots = relativeMembers.filter((member) => !ignoredRoots.has(member));
337
+ if (sourceRoots.length === 0) continue;
338
+ const installed = [...ignoredRoots].map((member) => join(repository, member));
339
+ const listing = execFileSync(
340
+ 'git',
341
+ [
342
+ '--literal-pathspecs',
343
+ '-C',
344
+ repository,
345
+ 'ls-files',
346
+ '-z',
347
+ '--others',
348
+ '--ignored',
349
+ '--exclude-standard',
350
+ '--directory',
351
+ '--',
352
+ ...sourceRoots,
353
+ ],
354
+ { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: CHILD_STDIO },
355
+ );
356
+ for (const entry of listing.split('\0')) {
357
+ if (entry.length === 0) continue;
358
+ const path = join(repository, entry);
359
+ if (!entry.endsWith('/')) {
360
+ files.add(path);
361
+ } else if (!installed.some((member) => member === path || member.startsWith(`${path}${sep}`))) {
362
+ // An ignored directory holding a nested installed package leaves that package whole.
363
+ trees.push(path);
364
+ }
365
+ }
366
+ }
367
+ return (path) => files.has(path) || trees.some((tree) => path === tree || path.startsWith(`${tree}${sep}`));
368
+ }
369
+
370
+ /** The members of `paths` (relative to `repository`) that git ignores, own patterns or an ancestor's. */
371
+ function gitCheckIgnore(repository: string, paths: readonly string[]): string[] {
372
+ const result = spawnSync('git', ['-C', repository, 'check-ignore', '-z', '--stdin'], {
373
+ input: `${paths.join('\0')}\0`,
374
+ encoding: 'utf8',
375
+ maxBuffer: 64 * 1024 * 1024,
376
+ });
377
+ // check-ignore answers 1 when nothing is ignored; only 0 carries a listing.
378
+ if (result.status === 1) return [];
379
+ if (result.status !== 0) {
380
+ throw new Error(`git check-ignore in ${repository} failed (${result.status ?? result.signal}): ${result.stderr}`);
381
+ }
382
+ return result.stdout.split('\0').filter((path) => path.length > 0);
383
+ }
384
+
385
+ /** The canonical top level of the git work tree holding `directory`, or undefined outside any repository. */
386
+ function gitRepository(directory: string): string | undefined {
387
+ try {
388
+ // The walk compares realpaths, so git's answer is canonicalized the same way.
389
+ return realpathSync(
390
+ execFileSync('git', ['-C', directory, 'rev-parse', '--show-toplevel'], {
391
+ encoding: 'utf8',
392
+ stdio: CHILD_STDIO,
393
+ }).trim(),
394
+ );
395
+ } catch (error) {
396
+ if (
397
+ typeof error === 'object' &&
398
+ error !== null &&
399
+ 'status' in error &&
400
+ error.status === 128 &&
401
+ 'stderr' in error &&
402
+ String(error.stderr).includes('not a git repository')
403
+ )
404
+ return undefined;
405
+ throw error;
406
+ }
407
+ }
@@ -116,14 +116,26 @@ export const CARGO_FETCH_COMMAND = 'cargo fetch --locked';
116
116
  * or replaying it through --config changes path resolution or precedence.
117
117
  * Cargo may serialize registry access on its package-cache lock; these checks
118
118
  * are unbounded, and correctness takes priority over overlapping that access.
119
+ *
120
+ * `target/cargo-lint-cross` stays its own directory: a foreign triple's units
121
+ * are distinct anyway, and its own lock keeps the cross check from queueing
122
+ * behind host builds.
119
123
  */
120
124
  export const CARGO_CROSS_LINT_COMMAND = `${CARGO_CROSS_LINT_GUARD}; ${cargoFrozen(
121
125
  `clippy --workspace --all-targets --target ${CARGO_LINUX_TRIPLE} --target-dir target/cargo-lint-cross -- -D warnings`,
122
126
  )}`;
123
127
 
124
- export const CARGO_LINT_CLIPPY_COMMAND = cargoFrozen(
125
- 'clippy --workspace --all-targets --target-dir target/cargo-lint -- -D warnings',
126
- );
128
+ /**
129
+ * No `--target-dir`: clippy writes the workspace's own `target/`, beside every
130
+ * dev build. Check units carry their mode in the unit hash, so they never
131
+ * collide with build units, and the host units a dev build already compiled —
132
+ * build scripts and their host-only dependencies — are reused rather than
133
+ * compiled a second time in a directory of their own. A dependency that both
134
+ * a proc-macro and ordinary code use stays a distinct unit: a dev build
135
+ * compiles it once at the target profile, while a check build needs a separate
136
+ * host copy. Distinct hashes coexist, so neither command dirties the other.
137
+ */
138
+ export const CARGO_LINT_CLIPPY_COMMAND = cargoFrozen('clippy --workspace --all-targets -- -D warnings');
127
139
 
128
140
  /** Root `package.json` script name, in the repo's `verb:qualifier` style. */
129
141
  export const CROSS_CHECK_SCRIPT_NAME = 'check:linux';
@@ -4,6 +4,7 @@ import { chmod, mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } fro
4
4
  import { tmpdir } from 'node:os';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
+ import { stripVTControlCharacters } from 'node:util';
7
8
 
8
9
  import type { Task } from 'nx/src/config/task-graph';
9
10
 
@@ -446,6 +447,26 @@ describe('smoo-nx-exec', () => {
446
447
  expect(run.stdout.split('\n')[0]).toBe(MARKER);
447
448
  });
448
449
 
450
+ it("hands the exec'd binary blocking stdio, so a pipe its output fills is never cut", async () => {
451
+ // Node leaves a pipe O_NONBLOCK on macOS, and the flag belongs to the open file description, so
452
+ // it survives execve: the binary's writes then fail with EAGAIN once the pipe holds 64 KiB and
453
+ // nobody is reading. A reader that starts late is what makes the pipe fill.
454
+ const flood = join(workspace, 'flood');
455
+ await writeFile(flood, '#!/bin/sh\nhead -c 300000 /dev/zero\n');
456
+ await chmod(flood, 0o755);
457
+ try {
458
+ const piped = Bun.spawn(
459
+ ['sh', '-c', `"$0" "$1" app:build -- ./flood | { sleep 1; tr -cd '\\000' | wc -c; }`, 'node', builtBinEntry],
460
+ { cwd: workspace, env: fixtureNxEnvironment(), stdout: 'pipe', stderr: 'pipe' },
461
+ );
462
+ const received = (await new Response(piped.stdout).text()).trim();
463
+ expect(await piped.exited).toBe(0);
464
+ expect(received).toBe('300000');
465
+ } finally {
466
+ await rm(flood, { force: true });
467
+ }
468
+ });
469
+
449
470
  it('leaves the exec\u0027d binary the caller\u0027s cwd and none of Nx\u0027s environment', async () => {
450
471
  // Invoked from a subdirectory, with the binary named relative to it: the
451
472
  // resolution the wrapper's users actually perform.
@@ -508,7 +529,7 @@ describe('smoo-nx-exec', () => {
508
529
  expect(await readFile(builds(), 'utf-8')).toBe(before);
509
530
  });
510
531
 
511
- it('runs again when a dependency\u0027s own inputs change', async () => {
532
+ it('runs again when a dependency\u0027s own inputs change, keeping stdout for the binary alone', async () => {
512
533
  const before = await readFile(builds(), 'utf-8');
513
534
  await writeFile(join(workspace, 'packages', 'lib', 'source1.txt'), 'lib changed\n');
514
535
  const changed = await runBin(workspace, ['app:build', '--', './report']);
@@ -516,6 +537,13 @@ describe('smoo-nx-exec', () => {
516
537
  expect(await readFile(join(workspace, 'packages', 'lib', 'dist', 'lib.txt'), 'utf-8')).toBe('lib changed\n');
517
538
  expect(await readFile(marker(), 'utf-8')).toBe('built\nlib changed\n');
518
539
  expect(await readFile(builds(), 'utf-8')).toBe(`${before}lib changed\n`);
540
+ // The run's log is on stderr. Stdout is the exec'd binary's and holds
541
+ // nothing else, or `wrapper | jq` reads Nx's banner as data.
542
+ expect(stripVTControlCharacters(changed.stderr)).toContain('nx run lib:build');
543
+ expect(changed.stdout.split('\n')[0], changed.stdout).toBe(MARKER);
544
+ for (const line of changed.stdout.split('\n').filter((line) => line !== '')) {
545
+ expect(line === MARKER || line.startsWith('cwd=') || /^NX_[A-Z_]+=/.test(line), line).toBe(true);
546
+ }
519
547
 
520
548
  // And the graph settles back to silence, which is only reachable if the
521
549
  // dependent-outputs task was hashed too.
@@ -544,6 +572,38 @@ describe('smoo-nx-exec', () => {
544
572
  expect(settled.stdout.split('\n')[0]).toBe(MARKER);
545
573
  });
546
574
 
575
+ it('without a binary, stays silent and exits 0 when nothing is stale', async () => {
576
+ const run = await runBin(workspace, ['app:build']);
577
+ expect(run.code, run.stdout + run.stderr).toBe(0);
578
+ expect(run.stdout).toBe('');
579
+ expect(run.stderr).toBe('');
580
+ });
581
+
582
+ it('without a binary, runs what is stale, shows that run and exits 0', async () => {
583
+ const before = await readFile(builds(), 'utf-8');
584
+ await writeFile(join(workspace, 'packages', 'lib', 'source1.txt'), 'lib checked\n');
585
+ const run = await runBin(workspace, ['app:build']);
586
+ expect(run.code, run.stdout + run.stderr).toBe(0);
587
+ // An outer `nx run nx-plugin:test` exports FORCE_COLOR, so the fixture's
588
+ // Nx styles its task lines; what the test pins is the line, not its colour.
589
+ expect(stripVTControlCharacters(run.stderr)).toContain('nx run lib:build');
590
+ expect(run.stdout).toBe('');
591
+ expect(await readFile(marker(), 'utf-8')).toBe('built\nlib checked\n');
592
+ expect(await readFile(builds(), 'utf-8')).toBe(`${before}lib checked\n`);
593
+
594
+ const settled = await runBin(workspace, ['app:build']);
595
+ expect(settled.code, settled.stdout + settled.stderr).toBe(0);
596
+ expect(settled.stdout).toBe('');
597
+ expect(settled.stderr).toBe('');
598
+ });
599
+
600
+ it('without a binary, exits with a failing target\u0027s code', async () => {
601
+ const run = await runBin(workspace, ['app:broken']);
602
+ expect(run.code).toBe(1);
603
+ expect(stripVTControlCharacters(run.stderr)).toContain('nx run app:broken');
604
+ expect(run.stdout).toBe('');
605
+ });
606
+
547
607
  it('forwards a failing target\u0027s exit code and never execs', async () => {
548
608
  const run = await runBin(workspace, ['app:broken', '--', './report']);
549
609
  expect(run.code).toBe(1);
@@ -557,7 +617,7 @@ describe('smoo-nx-exec', () => {
557
617
  });
558
618
  expect(run.code).toBe(0);
559
619
  expect(run.stderr).toContain('daemon is disabled');
560
- expect(run.stdout).toContain(MARKER);
620
+ expect(run.stdout.split('\n')[0], run.stdout).toBe(MARKER);
561
621
  });
562
622
 
563
623
  it('prints the message from a plain-object Nx rejection', async () => {
@@ -597,9 +657,9 @@ describe('smoo-nx-exec', () => {
597
657
  });
598
658
 
599
659
  it('rejects a malformed invocation with a usage error', async () => {
600
- const missingSeparator = await runBin(workspace, ['app:build']);
601
- expect(missingSeparator.code).toBe(2);
602
- expect(missingSeparator.stderr).toContain('missing `--`');
660
+ const emptyCommand = await runBin(workspace, ['app:build', '--']);
661
+ expect(emptyCommand.code).toBe(2);
662
+ expect(emptyCommand.stderr).toContain('no binary given');
603
663
 
604
664
  const badTarget = await runBin(workspace, ['build', '--', './report']);
605
665
  expect(badTarget.code).toBe(2);