sumlyzer 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,13 +11,14 @@
11
11
  <a href="./LICENSE"><img src="https://img.shields.io/npm/l/sumlyzer.svg" alt="license" /></a>
12
12
  </p>
13
13
 
14
-
15
14
  ## 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.
19
15
 
20
- Sumlyzer gives you all those possibilities and even more like concurrency or JUnit reports.
16
+ `npm run test --workspaces --if-present` runs every workspace, but gives no
17
+ aggregated summary, no fail-fast, and lets an early failure scroll off screen
18
+ unnoticed.
19
+
20
+ Sumlyzer gives you all those possibilities and even more like concurrency
21
+ (~3.5x faster on a real 15-workspace monorepo, see [Benchmark](#benchmark)) or JUnit reports.
21
22
 
22
23
  ## Requirements
23
24
 
@@ -26,19 +27,17 @@ Sumlyzer gives you all those possibilities and even more like concurrency or JUn
26
27
 
27
28
  ## Scope
28
29
 
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.
30
+ Intentionally narrow: **npm workspaces** running **`node:test`**. It does not
31
+ support pnpm/yarn workspaces or other test runners (Jest, Vitest, Mocha etc.) for the moment.
34
32
 
35
- It does not support pnpm/yarn workspaces or other test runners
36
- (Jest, Vitest, Mocha etc.). (for the moment)
33
+ It runs each workspace's script directly (no `npm run` in between) but still
34
+ chains its `pre`/`post` lifecycle scripts (e.g. `pretest`) itself, with the
35
+ same semantics as `npm run`: a failing `pre<script>` skips the rest, and a
36
+ failing `post<script>` still fails the workspace even if the main script passed.
37
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.
38
+ sumlyzer forces its own `node:test` reporter via `NODE_OPTIONS`, so a
39
+ workspace that sets its own `--test-reporter` is detected ahead of time
40
+ and skipped instead of colliding with it.
42
41
 
43
42
  ## Install
44
43
 
@@ -63,20 +62,25 @@ Options:
63
62
  | `--ff` | off | fail fast: stop at the first failing workspace |
64
63
  | `--junit <path>` | off | write an aggregated JUnit XML report to `<path>` |
65
64
  | `-c, --concurrency <n>` | `1` | run up to `<n>` workspaces at once |
65
+ | `--changed` | off | only run workspaces with changed files (git ref auto-detected, see `--ref`) |
66
+ | `--ref <ref>` | auto-detect | git ref to diff against for `--changed` |
66
67
  | `-h, --help` | | print usage |
67
68
 
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.
69
+ Exit code is `1` if any workspace fails, `0` otherwise. Safe to wire straight
70
+ into CI without extra parsing. This also applies when `--junit` can't write
71
+ its report.
70
72
 
71
- ## Features
73
+ ## Benchmark
72
74
 
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
75
+ Measured on a real 15-workspace monorepo where each workspace's `test` script does real work (coverage + type-checking), averaged over a few runs on the same machine:
76
+
77
+ | Command | Wall-clock time |
78
+ | ----------------------------------------- | ---------------- |
79
+ | `npm run test --workspaces --if-present` | ~22s |
80
+ | `sumlyzer` (default, sequential) | ~21s |
81
+ | `sumlyzer --concurrency 8` | **~6s** |
82
+
83
+ See [Concurrency](#concurrency) for where that gain comes from.
80
84
 
81
85
  ## Roadmap
82
86
 
@@ -93,7 +97,7 @@ This also applies when `--junit` can't write its report.
93
97
  | --------------- | ------------------------------------------------------------------------------------------------ |
94
98
  | `(index)` | Workspace name |
95
99
  | `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 |
100
+ | `duration` | Wall-clock time for the workspace's script process, including spawn overhead |
97
101
  | `tests` | Total number of tests node:test ran in that workspace |
98
102
  | `pass` | Number of passing tests |
99
103
  | `fail` | Number of failing tests |
@@ -104,6 +108,7 @@ has a nonzero count. Instead, sumlyzer prints a footnote below the table,
104
108
  naming only the workspaces that actually have some, e.g. `skipped tests:
105
109
  flags (2)`.
106
110
 
111
+ ## Reference
107
112
 
108
113
  ### JUnit report
109
114
 
@@ -112,7 +117,7 @@ every workspace's own `node:test` results. Each workspace runs with `node:test`'
112
117
  built-in `junit` reporter enabled alongside the terminal one, and sumlyzer combines
113
118
  the resulting files into one document, prefixing every `<testsuite>` name with the
114
119
  workspace it came from so CI test-report UIs (GitLab, Jenkins, Azure DevOps, ...)
115
- can tell them apart.
120
+ can tell them apart.
116
121
 
117
122
  ```
118
123
  npx sumlyzer --junit reports/junit.xml
@@ -133,11 +138,10 @@ prints a warning naming it.
133
138
 
134
139
  On GitHub Actions (detected via `GITHUB_ACTIONS=true`), each workspace's full
135
140
  `node:test` output is wrapped in a collapsible `::group::`/`::endgroup::`
136
- section instead of the terminal's formal.
141
+ section instead of the terminal's format.
137
142
 
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.
143
+ This is automatic, no flag needed, keeping the job log short while still
144
+ letting you expand any workspace's full output.
141
145
 
142
146
  No other CI provider is currently supported: GitHub is the
143
147
  only one whose log folding sumlyzer has actually verified end-to-end.
@@ -145,8 +149,9 @@ only one whose log folding sumlyzer has actually verified end-to-end.
145
149
  ### Concurrency
146
150
 
147
151
  `--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.
152
+ instead of one after another (something npm doesn't support natively)
153
+ which can noticeably cut wall-clock time on projects with
154
+ many workspaces (see [Benchmark](#benchmark)).
150
155
 
151
156
  Since workspaces can now finish in any order, their output interleaves in
152
157
  whatever order they complete, rather than following the `workspaces` list
@@ -158,6 +163,27 @@ workspace already running when the failure is detected runs to completion
158
163
 
159
164
  ![Concurrent run stopping early on failure](https://github.com/ErwanRaulo/sumlyzer/blob/main/concurrency-failed.png?raw=true)
160
165
 
166
+ ### Changed workspaces
167
+
168
+ `--changed` only runs workspaces whose own files changed according to git,
169
+ skipping the rest. It maps each changed file to the workspace directory that
170
+ contains it.
171
+
172
+ ```
173
+ npx sumlyzer --changed
174
+ npx sumlyzer --changed --ref origin/main
175
+ ```
176
+
177
+ Without `--ref`, the git ref to diff against is auto-detected:
178
+
179
+ - Uncommitted changes present → diff against `HEAD` (the local dev loop).
180
+ - Clean working tree with an upstream branch configured → diff against the
181
+ merge-base with that upstream, so commits already on the branch count as
182
+ "changed" without pulling in unrelated commits the upstream picked up in
183
+ the meantime.
184
+ - Clean working tree with no upstream configured (or no common ancestor, e.g.
185
+ a shallow clone) → `HEAD`, which reports "no changes".
186
+
161
187
  ## Why
162
188
 
163
189
  This fail-fast behavior at the `--workspaces` level has been requested from
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.0",
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);