sumlyzer 1.2.0 → 1.3.1

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.
package/README.md CHANGED
@@ -11,34 +11,15 @@
11
11
  <a href="./LICENSE"><img src="https://img.shields.io/npm/l/sumlyzer.svg" alt="license" /></a>
12
12
  </p>
13
13
 
14
+ <p align="center"><b>A better feedback loop for monorepos organized under npm workspaces</b></p>
14
15
 
15
- ## Ever wished a faster feedback when testing your npm workspaces?
16
-
17
- `npm run test --workspaces --if-present` runs every workspace, but gives you no
18
- aggregated summary and no way to fail fast, no way to catch an early failure that scrolled off screen.
16
+ `npm run test --workspaces --if-present` runs every workspace but gives no
17
+ summary, no fail-fast, and buries an early failure under everyone else's
18
+ output. Sumlyzer fixes that, and runs workspaces concurrently too (~3.5x
19
+ faster, see [Benchmark](#benchmark)).
19
20
 
20
- Sumlyzer gives you all those possibilities and even more like concurrency or JUnit reports.
21
-
22
- ## Requirements
23
-
24
- - Node.js >= 22.0.0
25
- - An npm workspaces project (`package.json` with a `workspaces` field)
26
-
27
- ## Scope
28
-
29
- This tool is intentionally narrow: **npm workspaces** running **`node:test`**.
30
-
31
- It orchestrates `npm run <script> --workspace=<path>` for every workspace that
32
- declares the target script, and it parses node test's own output to build
33
- the global and per workspace summary.
34
-
35
- It does not support pnpm/yarn workspaces or other test runners
36
- (Jest, Vitest, Mocha etc.). (for the moment)
37
-
38
- sumlyzer forces its own `node:test` reporter onto every workspace via
39
- `NODE_OPTIONS`, so a workspace's `test` script should just run `node --test`
40
- without configuring its own `--test-reporter`.
41
- sumlyzer detects this ahead of time and skips that workspace instead of running into it.
21
+ Scope: **npm workspaces** running **`node:test`** only, for now. No
22
+ pnpm/yarn, no Jest/Vitest/Mocha.
42
23
 
43
24
  ## Install
44
25
 
@@ -52,124 +33,53 @@ npm install --save-dev sumlyzer
52
33
  npx sumlyzer [options]
53
34
  ```
54
35
 
55
- Run from the root of an npm workspaces project (where `package.json` has a
56
- `workspaces` field).
57
-
58
- Options:
36
+ Run from the root of an npm workspaces project.
59
37
 
60
38
  | Flag | Default | Description |
61
39
  | --- | --- | --- |
62
40
  | `--script <name>` | `test` | npm script to run per workspace |
63
- | `--ff` | off | fail fast: stop at the first failing workspace |
64
- | `--junit <path>` | off | write an aggregated JUnit XML report to `<path>` |
41
+ | `--ff` | off | stop at the first failing workspace |
65
42
  | `-c, --concurrency <n>` | `1` | run up to `<n>` workspaces at once |
43
+ | `--changed` | off | only run workspaces with changed files |
44
+ | `--junit <path>` | off | write an aggregated JUnit XML report |
45
+ | `--ref <ref>` | auto-detect | git ref to diff against for `--changed` |
66
46
  | `-h, --help` | | print usage |
67
47
 
68
- Exit code is `1` if any workspace fails (even if every workspace's tests passed), `0` otherwise, wire it straight into CI without extra parsing.
69
- This also applies when `--junit` can't write its report.
70
-
71
- ## Features
72
-
73
- - Aggregated pass/fail summary table.
74
- - Fail-fast (`--ff`): stop at the first failing workspace
75
- - Aggregated JUnit XML report (`--junit`), merging every workspace's own results
76
- - GitHub Actions log folding: each workspace's output collapsed into an
77
- expandable group, automatically, no flag needed
78
- - Concurrent runs (`--concurrency <n>`): run several workspaces' test scripts
79
- at once instead of one by one
80
-
81
- ## Roadmap
82
-
83
- - **Watch mode**: walking the workspace dependency graph (topological sort) so a change in
84
- one workspace also re-runs the workspaces that depend on it.
85
-
86
- ## Example
48
+ Exit code is `1` if any workspace fails, `0` otherwise — safe to drop straight into CI.
87
49
 
88
50
  ![fail fast example](https://github.com/ErwanRaulo/sumlyzer/blob/main/example.png?raw=true)
89
51
 
90
- ### Summary columns
91
-
92
- | Column | Meaning |
93
- | --------------- | ------------------------------------------------------------------------------------------------ |
94
- | `(index)` | Workspace name |
95
- | `status` | `PASS`, `FAIL`, or `SKIPPED` (reached when `--ff` stopped scheduling before this workspace ran) |
96
- | `duration` | Wall-clock time for the whole `npm run <script> --workspace=<path>` process, including npm/spawn overhead |
97
- | `tests` | Total number of tests node:test ran in that workspace |
98
- | `pass` | Number of passing tests |
99
- | `fail` | Number of failing tests |
52
+ ## Benchmark
100
53
 
101
- Skipped (`t.skip()`), todo (`t.todo()`), and cancelled tests are rare enough
102
- that a column of zeros for every workspace would just bury the one row that
103
- has a nonzero count. Instead, sumlyzer prints a footnote below the table,
104
- naming only the workspaces that actually have some, e.g. `skipped tests:
105
- flags (2)`.
54
+ 15-workspace monorepo, each workspace's `test` script doing real work (coverage + type-checking):
106
55
 
56
+ | Command | Wall-clock time |
57
+ | --- | --- |
58
+ | `npm run test --workspaces --if-present` | ~22s |
59
+ | `sumlyzer` (sequential) | ~21s |
60
+ | `sumlyzer --concurrency 8` | **~6s** |
107
61
 
108
- ### JUnit report
62
+ ## Reference
109
63
 
110
- `--junit <path>` writes a single aggregated JUnit XML report to `<path>`, merging
111
- every workspace's own `node:test` results. Each workspace runs with `node:test`'s
112
- built-in `junit` reporter enabled alongside the terminal one, and sumlyzer combines
113
- the resulting files into one document, prefixing every `<testsuite>` name with the
114
- workspace it came from so CI test-report UIs (GitLab, Jenkins, Azure DevOps, ...)
115
- can tell them apart.
64
+ - **JUnit** (`--junit <path>`): merges every workspace's `node:test` JUnit output into one file, each `<testsuite>` prefixed with its workspace name. A workspace whose script never produces one is left out, with a warning naming it.
65
+ - **GitHub Actions**: on `GITHUB_ACTIONS=true`, each workspace's output is auto-wrapped in a collapsible `::group::` block. No other CI provider has folding support yet.
66
+ - **Concurrency** (`--concurrency <n>`): workspaces finish in whatever order they complete, so output interleaves. With `--ff`, only workspaces that haven't started yet are skipped — in-flight ones run to completion.
67
+ - **Changed workspaces** (`--changed`): maps changed files to the workspace directory containing them. Ref auto-detection: uncommitted changes → diff against `HEAD`; clean tree with upstream → merge-base with upstream; clean tree with no upstream → `HEAD`.
68
+ - Own `--test-reporter` in a workspace's script is detected ahead of time and that workspace is skipped, to avoid colliding with sumlyzer's own reporter.
116
69
 
117
- ```
118
- npx sumlyzer --junit reports/junit.xml
119
- npx sumlyzer --junit reports/ # writes reports/junit.xml
120
- ```
121
-
122
- ```xml
123
- <testsuites>
124
- <testsuite name="contact › contact tests">...</testsuite>
125
- <testsuite name="scanner">...</testsuite>
126
- </testsuites>
127
- ```
128
-
129
- A workspace whose script never produces a junit file is left out of the aggregated report and sumlyzer
130
- prints a warning naming it.
131
-
132
- ### GitHub Actions log folding
133
-
134
- On GitHub Actions (detected via `GITHUB_ACTIONS=true`), each workspace's full
135
- `node:test` output is wrapped in a collapsible `::group::`/`::endgroup::`
136
- section instead of the terminal's formal.
137
-
138
- This is automatic, no flag needed, and keeps the job log short by default
139
- while still letting you expand any workspace, passing or failing, to see its
140
- full suite output.
70
+ npm doesn't have native fail-fast on `--workspaces` yet — discussed in
71
+ [npm/rfcs#575](https://github.com/npm/rfcs/issues/575) (open) and
72
+ [npm/rfcs#602](https://github.com/npm/rfcs/issues/602) (closed), see also this
73
+ [Stack Overflow answer](https://stackoverflow.com/questions/71300870/npm-workspace-command-does-not-stop-executing-when-command-fails-for-a-workspace/79989284#79989284).
74
+ Sumlyzer's `--ff` gets you there in the meantime.
141
75
 
142
- No other CI provider is currently supported: GitHub is the
143
- only one whose log folding sumlyzer has actually verified end-to-end.
144
-
145
- ### Concurrency
146
-
147
- `--concurrency <n>` runs up to `<n>` workspaces' scripts at the same time
148
- instead of one after another, which can noticeably cut wall-clock time on
149
- projects with many workspaces.
150
-
151
- Since workspaces can now finish in any order, their output interleaves in
152
- whatever order they complete, rather than following the `workspaces` list
153
- order.
154
-
155
- With `--ff`, a failure only stops workspaces that haven't started yet; any
156
- workspace already running when the failure is detected runs to completion
157
- (sumlyzer doesn't kill in-flight processes).
158
-
159
- ![Concurrent run stopping early on failure](https://github.com/ErwanRaulo/sumlyzer/blob/main/concurrency-failed.png?raw=true)
160
-
161
- ## Why
76
+ ## Roadmap
162
77
 
163
- This fail-fast behavior at the `--workspaces` level has been requested from
164
- npm more than once: [npm/rfcs#575](https://github.com/npm/rfcs/issues/575)
165
- (open) and [npm/rfcs#602](https://github.com/npm/rfcs/issues/602) (closed).
166
- Until it lands, sumlyzer's `--ff` flag gets you there, see also this
167
- [Stack Overflow answer](https://stackoverflow.com/questions/71300870/npm-workspace-command-does-not-stop-executing-when-command-fails-for-a-workspace/79989284#79989284)
168
- on the same problem.
78
+ **Watch mode** — walk the workspace dependency graph so a change in one workspace also re-runs the ones that depend on it.
169
79
 
170
80
  ## Contributing
171
81
 
172
- See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup, conventions, and how to submit changes.
82
+ See [CONTRIBUTING.md](./CONTRIBUTING.md).
173
83
 
174
84
  ## License
175
85
 
package/bin/sumlyzer.mjs CHANGED
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import { availableParallelism } from "node:os";
5
5
 
6
6
  import { main } from "../src/run.mjs";
7
- import { NoWorkspacesError, InvalidPackageJsonError, WorkspaceLaunchError } from "../src/errors.mjs";
7
+ import { NoWorkspacesError, InvalidPackageJsonError, WorkspaceLaunchError, GitDiffError } from "../src/errors.mjs";
8
8
  import { red } from "../src/reporter.mjs";
9
9
 
10
10
  function printWorkspaceError(message) {
@@ -19,6 +19,8 @@ try {
19
19
  script: { type: "string", default: "test" },
20
20
  junit: { type: "string" },
21
21
  concurrency: { type: "string", short: "c", default: "1" },
22
+ changed: { type: "boolean", default: false },
23
+ ref: { type: "string" },
22
24
  help: { type: "boolean", short: "h", default: false }
23
25
  }
24
26
  }));
@@ -42,6 +44,11 @@ if (concurrency > maxConcurrency) {
42
44
  concurrency = maxConcurrency;
43
45
  }
44
46
 
47
+ if (args.ref && !args.changed) {
48
+ console.info(`--ref only applies with --changed. Run "sumlyzer --help" for usage.`);
49
+ process.exit(1);
50
+ }
51
+
45
52
  if (args.help) {
46
53
  console.log(`sumlyzer [options]
47
54
 
@@ -54,6 +61,8 @@ Options:
54
61
  --ff fail fast: stop at the first failing workspace
55
62
  --junit <path> write an aggregated JUnit XML report to <path>
56
63
  -c, --concurrency <n> run up to <n> workspaces at once (default: 1)
64
+ --changed only run workspaces with changes (git ref auto-detected, see --ref)
65
+ --ref <ref> git ref to diff against for --changed (default: auto-detect)
57
66
  -h, --help show this help
58
67
  `);
59
68
  process.exit(0);
@@ -65,14 +74,16 @@ try {
65
74
  scriptName: args.script,
66
75
  ff: args.ff,
67
76
  junitPath: args.junit,
68
- concurrency
77
+ concurrency,
78
+ changed: args.changed,
79
+ ref: args.ref
69
80
  });
70
81
  }
71
82
  catch (error) {
72
83
  if (error instanceof NoWorkspacesError) {
73
84
  console.info(error.message);
74
85
  }
75
- else if (error instanceof InvalidPackageJsonError || error instanceof WorkspaceLaunchError) {
86
+ else if (error instanceof InvalidPackageJsonError || error instanceof WorkspaceLaunchError || error instanceof GitDiffError) {
76
87
  printWorkspaceError(error.message);
77
88
  }
78
89
  else {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sumlyzer",
3
- "version": "1.2.0",
3
+ "version": "1.3.1",
4
4
  "description": "Run every npm workspace's test script, only show output for the ones that fail, and finish with an aggregated pass/fail summary.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -17,7 +17,8 @@
17
17
  },
18
18
  "scripts": {
19
19
  "test": "node --test \"./test/*.spec.mjs\"",
20
- "test:coverage": "c8 --reporter=text --reporter=lcov --check-coverage --lines 95 --functions 95 --statements 95 --branches 85 node --test \"./test/*.spec.mjs\"",
20
+ "pretest:coverage": "mkdir -p coverage",
21
+ "test:coverage": "node --no-warnings --experimental-test-coverage --test-coverage-lines=95 --test-coverage-functions=95 --test-coverage-branches=85 --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test \"./test/*.spec.mjs\"",
21
22
  "security-scan": "node scripts/security-scan.mjs",
22
23
  "postversion": "git push && git push --tags",
23
24
  "prepublishOnly": "npm test",
@@ -54,7 +55,6 @@
54
55
  "devDependencies": {
55
56
  "@nodesecure/js-x-ray": "^16.0.0",
56
57
  "@types/node": "^26.1.1",
57
- "c8": "^12.0.0",
58
58
  "fast-xml-parser": "^5.10.1"
59
59
  },
60
60
  "dependencies": {
@@ -0,0 +1,67 @@
1
+ import { spawnSync } from "node:child_process";
2
+
3
+ import { GitDiffError } from "./errors.mjs";
4
+
5
+ function runGit(root, args, ref) {
6
+ const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
7
+
8
+ if (result.error) {
9
+ throw new GitDiffError(ref, result.error.message);
10
+ }
11
+ if (result.status !== 0) {
12
+ throw new GitDiffError(ref, result.stderr.trim() || `git exited with code ${result.status}`);
13
+ }
14
+
15
+ return result.stdout.split("\n").map((line) => line.trim()).filter(Boolean);
16
+ }
17
+
18
+ function tryGit(root, args) {
19
+ const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
20
+ return !result.error && result.status === 0 ? result.stdout.trim() : null;
21
+ }
22
+
23
+ export function getChangedFiles(root, ref) {
24
+ const tracked = runGit(root, ["diff", "--name-only", ref], ref);
25
+ const untracked = runGit(root, ["ls-files", "--others", "--exclude-standard"], ref);
26
+
27
+ return [...new Set([...tracked, ...untracked])];
28
+ }
29
+
30
+ export function resolveDefaultRef(root) {
31
+ const dirty = runGit(root, ["status", "--porcelain"], "auto-detected");
32
+ if (dirty.length > 0) {
33
+ return { ref: "HEAD", label: "HEAD", reason: "uncommitted changes" };
34
+ }
35
+
36
+ const upstream = tryGit(root, ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"]);
37
+ if (!upstream) {
38
+ return { ref: "HEAD", label: "HEAD", reason: "no upstream configured" };
39
+ }
40
+
41
+ const mergeBase = tryGit(root, ["merge-base", upstream, "HEAD"]);
42
+ if (mergeBase) {
43
+ return { ref: mergeBase, label: `merge-base with "${upstream}"`, reason: "no local changes" };
44
+ }
45
+
46
+ return { ref: upstream, label: upstream, reason: "no merge-base found" };
47
+ }
48
+
49
+ // Attributes each changed file to the resolved workspace whose directory contains
50
+ // it. A file outside every workspace directory is reported as "rootChangeFiles"
51
+ export function selectChangedWorkspaces(resolvedWorkspaces, changedFiles) {
52
+ const sorted = [...resolvedWorkspaces].sort((a, b) => b.length - a.length);
53
+ const workspaces = new Set();
54
+ const rootChangeFiles = [];
55
+
56
+ for (const file of changedFiles) {
57
+ const owner = sorted.find((wsPath) => file === wsPath || file.startsWith(`${wsPath}/`));
58
+ if (owner) {
59
+ workspaces.add(owner);
60
+ }
61
+ else {
62
+ rootChangeFiles.push(file);
63
+ }
64
+ }
65
+
66
+ return { workspaces, rootChangeFiles };
67
+ }
package/src/errors.mjs CHANGED
@@ -23,3 +23,11 @@ export class WorkspaceLaunchError extends Error {
23
23
  this.scriptName = scriptName;
24
24
  }
25
25
  }
26
+
27
+ export class GitDiffError extends Error {
28
+ constructor(ref, reason) {
29
+ super(`could not compute changed files against "${ref}" (${reason})`);
30
+ this.name = "GitDiffError";
31
+ this.ref = ref;
32
+ }
33
+ }
package/src/run.mjs CHANGED
@@ -10,6 +10,7 @@ import { buildJunitReport } from "./junit.mjs";
10
10
  import { red, dim, workspaceName, githubGroupSyntax, printWorkspaceResult, printSummary, reportOutcome } from "./reporter.mjs";
11
11
  import { NoWorkspacesError, InvalidPackageJsonError, WorkspaceLaunchError } from "./errors.mjs";
12
12
  import { hasOwnReporter, prepareEnv, parseResult } from "./runners/nodeTest.mjs";
13
+ import { getChangedFiles, resolveDefaultRef, selectChangedWorkspaces } from "./changed.mjs";
13
14
 
14
15
  const runner = { hasOwnReporter, prepareEnv, parseResult };
15
16
 
@@ -71,13 +72,18 @@ function classifyWorkspace(root, wsPath, scriptName) {
71
72
  return { kind: "absent" };
72
73
  }
73
74
 
74
- return runner.hasOwnReporter(script) ? { kind: "ownReporterConflict" } : { kind: "eligible" };
75
+ const pre = pkg.scripts?.[`pre${scriptName}`];
76
+ const post = pkg.scripts?.[`post${scriptName}`];
77
+
78
+ const hasConflict = [pre, script, post].some((command) => command && runner.hasOwnReporter(command));
79
+ return hasConflict ? { kind: "ownReporterConflict" } : { kind: "eligible", pre, script, post };
75
80
  }
76
81
 
77
82
  function listEligibleWorkspaces(root, workspaces, scriptName) {
78
83
  const eligible = [];
79
84
  const ownReporterConflicts = [];
80
85
  const invalidPackageJson = [];
86
+ const scriptCommands = new Map();
81
87
 
82
88
  for (const wsPath of workspaces) {
83
89
  const classification = classifyWorkspace(root, wsPath, scriptName);
@@ -90,15 +96,32 @@ function listEligibleWorkspaces(root, workspaces, scriptName) {
90
96
  break;
91
97
  case "eligible":
92
98
  eligible.push(wsPath);
99
+ scriptCommands.set(wsPath, { pre: classification.pre, script: classification.script, post: classification.post });
93
100
  break;
94
101
  }
95
102
  }
96
103
 
97
- return { eligible, ownReporterConflicts, invalidPackageJson };
104
+ return { eligible, ownReporterConflicts, invalidPackageJson, scriptCommands };
105
+ }
106
+
107
+ function buildWorkspacePath(root, wsPath) {
108
+ const rootDir = path.resolve(root);
109
+ const binDirs = [];
110
+ let dir = path.resolve(root, wsPath);
111
+
112
+ while (true) {
113
+ binDirs.push(path.join(dir, "node_modules", ".bin"));
114
+ if (dir === rootDir) break;
115
+ const parent = path.dirname(dir);
116
+ if (parent === dir) break;
117
+ dir = parent;
118
+ }
119
+
120
+ return [...binDirs, process.env.PATH].join(path.delimiter);
98
121
  }
99
122
 
100
- // npm spawns the actual test runner as its own child, so killing just the "npm"
101
- // process leaves that grandchild running. Giving it its own process group (POSIX)
123
+ // The spawned shell is the actual test runner's parent, so killing just it
124
+ // leaves that grandchild running. Giving it its own process group (POSIX)
102
125
  // or asking Windows to kill the whole tree ensures nothing is left behind.
103
126
  function killWorkspaceChild(child) {
104
127
  if (process.platform === "win32") {
@@ -121,15 +144,8 @@ function waitForExit(child) {
121
144
  });
122
145
  }
123
146
 
124
- async function captureWorkspaceOutput({ root, wsPath, scriptName, junitDestPath, activeChildren }) {
125
- const options = {
126
- cwd: root,
127
- shell: process.platform === "win32",
128
- detached: process.platform !== "win32",
129
- env: runner.prepareEnv(process.env, junitDestPath)
130
- };
131
-
132
- const child = spawn("npm", ["run", scriptName, "--workspace=" + wsPath], options);
147
+ async function runPhase(command, options, activeChildren) {
148
+ const child = spawn(command, options);
133
149
  activeChildren.add(child);
134
150
  const stdoutChunks = [];
135
151
  const stderrChunks = [];
@@ -139,18 +155,59 @@ async function captureWorkspaceOutput({ root, wsPath, scriptName, junitDestPath,
139
155
 
140
156
  try {
141
157
  const exitCode = await waitForExit(child);
142
-
143
- return {
144
- exitCode,
145
- stdout: Buffer.concat(stdoutChunks).toString("utf8"),
146
- stderr: Buffer.concat(stderrChunks).toString("utf8")
147
- };
158
+ return { exitCode, stdoutChunks, stderrChunks };
148
159
  }
149
160
  finally {
150
161
  activeChildren.delete(child);
151
162
  }
152
163
  }
153
164
 
165
+ // Only the main script gets sumlyzer's own node:test reporter forced onto it via
166
+ // NODE_OPTIONS. pre/post run with a plain environment: forcing our JSON reporter onto
167
+ // them too would let a hook that happens to run its own `node --test` silently overwrite
168
+ // the main script's parsed counts/JUnit report with its own, whichever phase runs last.
169
+ function buildPhaseOptions({ root, wsPath, junitDestPath }) {
170
+ const cwd = path.join(root, wsPath);
171
+ const PATH = buildWorkspacePath(root, wsPath);
172
+ const shellOptions = { cwd, shell: true, detached: process.platform !== "win32" };
173
+
174
+ return {
175
+ hook: { ...shellOptions, env: { ...process.env, PATH } },
176
+ script: { ...shellOptions, env: { ...runner.prepareEnv(process.env, junitDestPath), PATH } }
177
+ };
178
+ }
179
+
180
+ async function captureWorkspaceOutput({ root, wsPath, scriptPhases, junitDestPath, activeChildren }) {
181
+ const phaseOptions = buildPhaseOptions({ root, wsPath, junitDestPath });
182
+
183
+ const phases = [
184
+ scriptPhases.pre && { command: scriptPhases.pre, options: phaseOptions.hook },
185
+ { command: scriptPhases.script, options: phaseOptions.script },
186
+ scriptPhases.post && { command: scriptPhases.post, options: phaseOptions.hook }
187
+ ].filter(Boolean);
188
+
189
+ const stdoutChunks = [];
190
+ const stderrChunks = [];
191
+ let exitCode = 0;
192
+
193
+ for (const { command, options } of phases) {
194
+ const phase = await runPhase(command, options, activeChildren);
195
+ exitCode = phase.exitCode;
196
+ stdoutChunks.push(...phase.stdoutChunks);
197
+ stderrChunks.push(...phase.stderrChunks);
198
+
199
+ if (exitCode !== 0) {
200
+ break;
201
+ }
202
+ }
203
+
204
+ return {
205
+ exitCode,
206
+ stdout: Buffer.concat(stdoutChunks).toString("utf8"),
207
+ stderr: Buffer.concat(stderrChunks).toString("utf8")
208
+ };
209
+ }
210
+
154
211
  function killActiveChildren(activeChildren) {
155
212
  for (const child of activeChildren) {
156
213
  killWorkspaceChild(child);
@@ -175,9 +232,9 @@ async function withInterruptHandling(activeChildren, run) {
175
232
  }
176
233
  }
177
234
 
178
- async function runWorkspaceScript({ root, wsPath, scriptName, junitDestPath, activeChildren }) {
235
+ async function runWorkspaceScript({ root, wsPath, scriptPhases, junitDestPath, activeChildren }) {
179
236
  const start = Date.now();
180
- const captured = await captureWorkspaceOutput({ root, wsPath, scriptName, junitDestPath, activeChildren });
237
+ const captured = await captureWorkspaceOutput({ root, wsPath, scriptPhases, junitDestPath, activeChildren });
181
238
 
182
239
  return {
183
240
  wsPath,
@@ -224,7 +281,7 @@ function partitionResults(results, workspacesToRun) {
224
281
  return { completed, skipped };
225
282
  }
226
283
 
227
- async function runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir, concurrency }) {
284
+ async function runWorkspaces({ root, workspacesToRun, scriptName, scriptCommands, ff, junitDir, concurrency }) {
228
285
  const results = new Array(workspacesToRun.length);
229
286
  const ciGroup = githubGroupSyntax(process.env);
230
287
  const activeChildren = new Set();
@@ -243,7 +300,7 @@ async function runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir,
243
300
 
244
301
  let result;
245
302
  try {
246
- result = await runWorkspaceScript({ root, wsPath, scriptName, junitDestPath, activeChildren });
303
+ result = await runWorkspaceScript({ root, wsPath, scriptPhases: scriptCommands.get(wsPath), junitDestPath, activeChildren });
247
304
  }
248
305
  catch (error) {
249
306
  stopScheduling = true;
@@ -265,6 +322,47 @@ async function runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir,
265
322
  return partitionResults(results, workspacesToRun);
266
323
  }
267
324
 
325
+ // Resolves which ref to diff against: the explicit --ref, or an auto-detected
326
+ // one (logged so the choice is never silent).
327
+ function resolveRefToUse(root, explicitRef) {
328
+ if (explicitRef) {
329
+ return { ref: explicitRef, label: explicitRef };
330
+ }
331
+
332
+ const resolved = resolveDefaultRef(root);
333
+ console.log(dim(`--changed: no --ref given, comparing against "${resolved.label}" (${resolved.reason})`));
334
+ return resolved;
335
+ }
336
+
337
+ // Returns the filtered workspace list to run, or null when nothing should run
338
+ // (already reported to the user), so main() can return early.
339
+ function applyChangedFilter(root, resolvedWorkspaces, workspacesToRun, explicitRef) {
340
+ const { ref, label } = resolveRefToUse(root, explicitRef);
341
+
342
+ const changedFiles = getChangedFiles(root, ref);
343
+ if (changedFiles.length === 0) {
344
+ console.log(dim(`No changes detected against "${label}".`));
345
+ return null;
346
+ }
347
+
348
+ const { workspaces: changedWorkspaces, rootChangeFiles } = selectChangedWorkspaces(resolvedWorkspaces, changedFiles);
349
+
350
+ if (rootChangeFiles.length > 0) {
351
+ const suffix = rootChangeFiles.length > 1 ? ` (+${rootChangeFiles.length - 1} more)` : "";
352
+ console.log(dim(`--changed: "${rootChangeFiles[0]}"${suffix} is outside every workspace, ignoring`));
353
+ }
354
+
355
+ const filtered = workspacesToRun.filter((wsPath) => changedWorkspaces.has(wsPath));
356
+ console.log(dim(`--changed: running ${filtered.length}/${workspacesToRun.length} workspace(s) with changes since "${label}"`));
357
+
358
+ if (filtered.length === 0) {
359
+ console.log(dim("No eligible workspace changed."));
360
+ return null;
361
+ }
362
+
363
+ return filtered;
364
+ }
365
+
268
366
  const DEFAULT_JUNIT_FILENAME = "junit.xml";
269
367
 
270
368
  async function resolveJunitDestination(root, junitPath) {
@@ -291,7 +389,7 @@ async function writeJunitReport(root, junitPath, results) {
291
389
  }
292
390
  }
293
391
 
294
- export async function main({ root, scriptName, ff, junitPath, concurrency = 1 }) {
392
+ export async function main({ root, scriptName, ff, junitPath, concurrency = 1, changed = false, ref }) {
295
393
 
296
394
  const { workspaces } = readJson(path.join(root, "package.json"));
297
395
 
@@ -301,7 +399,7 @@ export async function main({ root, scriptName, ff, junitPath, concurrency = 1 })
301
399
 
302
400
  const resolvedWorkspaces = await resolveWorkspacePaths(root, workspaces);
303
401
 
304
- const { eligible: workspacesToRun, ownReporterConflicts, invalidPackageJson } = listEligibleWorkspaces(root, resolvedWorkspaces, scriptName);
402
+ const { eligible: workspacesToRun, ownReporterConflicts, invalidPackageJson, scriptCommands } = listEligibleWorkspaces(root, resolvedWorkspaces, scriptName);
305
403
 
306
404
  if (invalidPackageJson.length > 0) {
307
405
  throw new InvalidPackageJsonError(invalidPackageJson);
@@ -318,11 +416,22 @@ export async function main({ root, scriptName, ff, junitPath, concurrency = 1 })
318
416
  return;
319
417
  }
320
418
 
419
+ let finalWorkspacesToRun = workspacesToRun;
420
+ if (changed) {
421
+ finalWorkspacesToRun = applyChangedFilter(root, resolvedWorkspaces, workspacesToRun, ref);
422
+ if (finalWorkspacesToRun === null) {
423
+ if (junitPath) {
424
+ console.log(dim(`--junit: no report written to "${junitPath}" (no workspace ran)`));
425
+ }
426
+ return;
427
+ }
428
+ }
429
+
321
430
  const junitDir = junitPath ? await mkdtemp(path.join(tmpdir(), "sumlyzer-junit-")) : null;
322
431
 
323
432
  let completed, skipped;
324
433
  try {
325
- ({ completed, skipped } = await runWorkspaces({ root, workspacesToRun, scriptName, ff, junitDir, concurrency }));
434
+ ({ completed, skipped } = await runWorkspaces({ root, workspacesToRun: finalWorkspacesToRun, scriptName, scriptCommands, ff, junitDir, concurrency }));
326
435
 
327
436
  if (junitDir) {
328
437
  await writeJunitReport(root, junitPath, completed);