bivium 0.9.0 → 0.11.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/docs/tuning.md CHANGED
@@ -175,7 +175,8 @@ under the config's file.
175
175
  Two cases aren't dead.
176
176
  An ignored file the graph reads still starts a walk to the tests that
177
177
  reach it.
178
- A change outside the roots runs everything.
178
+ A change outside the roots runs everything; `check` reports that apart,
179
+ as a [glob outside the roots](#globs-outside-the-roots).
179
180
 
180
181
  A glob that's dead on purpose goes in `deadGlobs` with a reason:
181
182
 
@@ -189,6 +190,28 @@ deadGlobs: [
189
190
  ],
190
191
  ```
191
192
 
193
+ ## Globs outside the roots
194
+
195
+ A change to a file outside `roots` runs everything,
196
+ so a glob that points outside them never selects only its file's tests.
197
+ `check` fails on such a glob, in the same places it looks for dead ones,
198
+ and names the path to add to `roots`:
199
+
200
+ ```console
201
+ $ bunx bivium check
202
+ bivium can follow every file a test reaches
203
+ 1 glob outside roots
204
+
205
+ glob outside `roots`: a change to a match runs everything · 1 glob in 1 file
206
+ └ tests/scripts/strings.test.ts:1 reads i18n/strings.json: 1 match outside…
207
+ fix add `i18n` to `roots`: a change outside them runs everything
208
+
209
+ ✗ 1 glob outside roots · checked in 261 ms · --all for every file
210
+ ```
211
+
212
+ A match that's ignored, a `self` file or a suite's `wiring` doesn't
213
+ count: a change to it already does what the config says.
214
+
192
215
  ## Related
193
216
 
194
217
  - [Config](config.md): every key named here
package/errors.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  BiviumError2,
3
3
  didYouMean2
4
- } from "./shared-211m8fjt.js";
4
+ } from "./shared-p3qfqmwd.js";
5
+ import"./shared-mpjk8met.js";
5
6
  export {
6
7
  BiviumError2 as BiviumError,
7
8
  didYouMean2 as didYouMean
package/index.d.ts CHANGED
@@ -204,8 +204,31 @@ export interface SuiteConfig {
204
204
  * to. Default: `<name>-tests`.
205
205
  */
206
206
  output?: string;
207
+ /**
208
+ * The suite's recorded test durations, in the format of `bun test
209
+ * --timings`: `{ "version": 1, "files": { "<path>": <ms> } }`, keyed by
210
+ * repository path. Shards balance by them, and `bivium run` passes the
211
+ * files longest first. A missing file, or one that doesn't parse (with a
212
+ * warning), counts every test the same. A change to it selects nothing.
213
+ * Default: `.bivium/timings/<name>.json`.
214
+ */
215
+ timings?: string;
216
+ /**
217
+ * Splits the selection into shards for a CI matrix, balanced by
218
+ * `timings`: a count, or the fewest shards whose slowest one is
219
+ * estimated at most `targetMs`, up to `max`. Never more shards than
220
+ * selected files. Default: no shards.
221
+ */
222
+ shards?: number | ShardTarget;
207
223
  }
208
224
  export type Globs = string | readonly string[];
225
+ /** How many shards: the fewest that keep each within `targetMs`. */
226
+ export interface ShardTarget {
227
+ /** The longest a shard may take, by `timings`. */
228
+ targetMs: number;
229
+ /** The most shards to split into, up to 256. */
230
+ max: number;
231
+ }
209
232
  /**
210
233
  * Replaces the coarse seeds of some changed files with finer ones from a
211
234
  * semantic diff: a stylesheet change seeded with the sources that render a
@@ -277,6 +300,12 @@ export type NarrowResult = {
277
300
  export interface PlanResult<Suite extends string = string> {
278
301
  /** Each suite's tests: `all`, `none`, or the files that can be affected. */
279
302
  suites: Record<Suite, Selection>;
303
+ /**
304
+ * Per suite, each selected test that needs only some of its
305
+ * `@depends-on-each` cases → those cases: the matches a change reaches. A
306
+ * test not listed runs every case, and a full run lists none.
307
+ */
308
+ cases: Record<Suite, Record<string, string[]>>;
280
309
  /** Why a suite runs in full. */
281
310
  reasons: string[];
282
311
  /** The same, as data: one per reason, in order. */
@@ -302,6 +331,14 @@ export interface PlanResult<Suite extends string = string> {
302
331
  name: string;
303
332
  result: NarrowResult;
304
333
  }[];
334
+ /**
335
+ * Each suite with `shards` → its selection split into shards, balanced
336
+ * by its `timings`; a selection of all lists every test, and none
337
+ * gives no shards.
338
+ */
339
+ shards: Partial<Record<Suite, Shard[]>>;
340
+ /** Each suite with `shards` → what its shards were balanced by. */
341
+ timings: Partial<Record<Suite, ShardTimings>>;
305
342
  }
306
343
  /** A suite's selected tests. */
307
344
  export type Selection = {
@@ -334,6 +371,31 @@ export interface FullRunCause<Suite extends string = string> {
334
371
  /** The sentence `reasons` has for it. */
335
372
  message: string;
336
373
  }
374
+ /** One shard of a suite's selection, its files longest first. */
375
+ export interface Shard {
376
+ /** Its number, from 1. */
377
+ shard: number;
378
+ files: string[];
379
+ /** The sum of its files' recorded durations, the median for the rest. */
380
+ estimatedMs: number;
381
+ }
382
+ /** What a suite's shards were balanced by. */
383
+ export interface ShardTimings {
384
+ /** The suite's `timings` file, repository-relative. */
385
+ file: string;
386
+ /** How many of the files split have a recorded duration. */
387
+ timed: number;
388
+ /**
389
+ * What a file with no recorded duration counts as: the median of the
390
+ * suite's recorded ones, or 1 when it has none.
391
+ */
392
+ medianMs: number;
393
+ /**
394
+ * What's wrong with a timings file that doesn't parse, which is then
395
+ * read as empty, so the split is by count.
396
+ */
397
+ problem?: string;
398
+ }
337
399
  /** Types a config. Returns it unchanged. */
338
400
  export declare function defineConfig<Suite extends string>(config: Config<Suite>): Config<Suite>;
339
401
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bivium",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Run only the tests your change can reach.",
5
5
  "license": "MIT",
6
6
  "author": "Eric Liu (https://github.com/metonym)",
@@ -0,0 +1,26 @@
1
+ import {
2
+ FLAGS2,
3
+ outFor2,
4
+ usageError2,
5
+ parseArgs2,
6
+ json2,
7
+ commandAt2,
8
+ COMMANDS2,
9
+ EVERY_FLAG2,
10
+ unknownFlag2,
11
+ fail2
12
+ } from "./shared-jee85qxj.js";
13
+ import"./shared-p3qfqmwd.js";
14
+ import"./shared-mpjk8met.js";
15
+ export {
16
+ COMMANDS2 as COMMANDS,
17
+ EVERY_FLAG2 as EVERY_FLAG,
18
+ FLAGS2 as FLAGS,
19
+ commandAt2 as commandAt,
20
+ fail2 as fail,
21
+ json2 as json,
22
+ outFor2 as outFor,
23
+ parseArgs2 as parseArgs,
24
+ unknownFlag2 as unknownFlag,
25
+ usageError2 as usageError
26
+ };
@@ -0,0 +1,103 @@
1
+ import {
2
+ showCursor2,
3
+ cursorHidden2
4
+ } from "./shared-mpjk8met.js";
5
+
6
+ // src/live.ts
7
+ var EXIT_INTERRUPTED = 130;
8
+ var EXIT_TERMINATED = 143;
9
+ var ERASE_ECHO = "\r\x1B[2K";
10
+ var exitCodeOf = (signal) => signal === "SIGINT" ? EXIT_INTERRUPTED : EXIT_TERMINATED;
11
+ function handleInterrupt(options) {
12
+ const { process: target } = options;
13
+ const controller = new AbortController;
14
+ const exits = options.exit ?? true;
15
+ const secondExits = options.secondExit ?? true;
16
+ const echo = options.echo ?? (options.terminal ? "erase" : "keep");
17
+ const state = { restored: false, stoppedBy: undefined, forced: undefined };
18
+ let markStopped = () => {};
19
+ const stopped = new Promise((resolve) => {
20
+ markStopped = resolve;
21
+ });
22
+ const restore = () => {
23
+ if (state.restored)
24
+ return;
25
+ state.restored = true;
26
+ const input = options.input;
27
+ if (input?.isTTY === true && input.isRaw !== false) {
28
+ input.setRawMode?.(false);
29
+ }
30
+ if (options.terminal && cursorHidden2())
31
+ options.write(showCursor2());
32
+ };
33
+ const quit = (code) => {
34
+ restore();
35
+ target.exit(code);
36
+ };
37
+ const stop = (signal, echoed) => {
38
+ if (echoed) {
39
+ if (echo === "erase")
40
+ options.write(ERASE_ECHO);
41
+ else if (echo === "newline")
42
+ options.write(`
43
+ `);
44
+ }
45
+ if (!secondExits && state.forced !== undefined)
46
+ return;
47
+ if (state.stoppedBy !== undefined) {
48
+ state.forced = signal;
49
+ options.onQuit?.();
50
+ if (secondExits) {
51
+ quit(exitCodeOf(signal));
52
+ } else {
53
+ restore();
54
+ markStopped(state.stoppedBy);
55
+ }
56
+ return;
57
+ }
58
+ state.stoppedBy = signal;
59
+ controller.abort();
60
+ const end = () => {
61
+ restore();
62
+ markStopped(signal);
63
+ if (exits && (secondExits || state.forced === undefined)) {
64
+ target.exit(exitCodeOf(signal));
65
+ }
66
+ };
67
+ Promise.resolve().then(() => options.onStop?.(signal)).then(end, end);
68
+ };
69
+ const onInt = () => stop("SIGINT", true);
70
+ const onTerm = () => stop("SIGTERM", false);
71
+ const dispose = () => {
72
+ target.off("SIGINT", onInt);
73
+ target.off("SIGTERM", onTerm);
74
+ target.off("exit", restore);
75
+ };
76
+ target.on("SIGINT", onInt);
77
+ target.on("SIGTERM", onTerm);
78
+ target.on("exit", restore);
79
+ return {
80
+ signal: controller.signal,
81
+ get stoppedBy() {
82
+ return state.stoppedBy;
83
+ },
84
+ get forced() {
85
+ return state.forced;
86
+ },
87
+ stopped,
88
+ interrupt: () => stop("SIGINT", false),
89
+ settle: () => new Promise((resolve) => {
90
+ setImmediate(() => {
91
+ if (state.stoppedBy === undefined)
92
+ dispose();
93
+ resolve(state.stoppedBy);
94
+ });
95
+ }),
96
+ dispose
97
+ };
98
+ }
99
+ export {
100
+ EXIT_INTERRUPTED,
101
+ exitCodeOf,
102
+ handleInterrupt
103
+ };
@@ -0,0 +1,164 @@
1
+ import {
2
+ plural2
3
+ } from "./shared-mpjk8met.js";
4
+ import {
5
+ walksByTypes,
6
+ importersOf,
7
+ sorted
8
+ } from "./shared-wxem8d5w.js";
9
+
10
+ // src/fanin.ts
11
+ function fanIn2(graph, suite) {
12
+ const ids = new Map;
13
+ const nodes = [...graph.keys()];
14
+ for (const [i, node] of nodes.entries())
15
+ ids.set(node, i);
16
+ const matches = new Map;
17
+ const matching = (re) => {
18
+ let found = matches.get(re.source);
19
+ if (!found) {
20
+ found = [];
21
+ for (const [i, node] of nodes.entries())
22
+ if (re.test(node))
23
+ found.push(i);
24
+ matches.set(re.source, found);
25
+ }
26
+ return found;
27
+ };
28
+ const forward = [];
29
+ const direct = [];
30
+ for (const node of nodes) {
31
+ const deps = graph.get(node);
32
+ const out = [];
33
+ const read = [];
34
+ if (deps) {
35
+ for (const file of deps.files) {
36
+ if (!suite.types && deps.types?.has(file))
37
+ continue;
38
+ const id = ids.get(file);
39
+ if (id !== undefined)
40
+ out.push(id);
41
+ }
42
+ for (const re of deps.patterns)
43
+ out.push(...matching(re));
44
+ for (const re of [...deps.reads, ...deps.lists ?? []]) {
45
+ read.push(...matching(re));
46
+ }
47
+ }
48
+ forward.push(out);
49
+ direct.push(read);
50
+ }
51
+ const counts = new Uint32Array(nodes.length);
52
+ const stamp = new Int32Array(nodes.length).fill(-1);
53
+ const stack = [];
54
+ for (const [t, test] of nodes.entries()) {
55
+ if (!suite.isTest(test))
56
+ continue;
57
+ const reached = [];
58
+ const visit = (id) => {
59
+ if (stamp[id] === t)
60
+ return;
61
+ stamp[id] = t;
62
+ reached.push(id);
63
+ };
64
+ visit(t);
65
+ stack.push(t);
66
+ for (let at = stack.pop();at !== undefined; at = stack.pop()) {
67
+ for (const next of byId(forward, at)) {
68
+ if (stamp[next] === t)
69
+ continue;
70
+ visit(next);
71
+ stack.push(next);
72
+ }
73
+ }
74
+ for (const id of [...reached]) {
75
+ for (const read of byId(direct, id))
76
+ visit(read);
77
+ }
78
+ for (const id of reached)
79
+ counts[id] = byId(counts, id) + 1;
80
+ }
81
+ const result = new Map;
82
+ for (const [i, node] of nodes.entries())
83
+ result.set(node, byId(counts, i));
84
+ return result;
85
+ }
86
+ function byId(list, id) {
87
+ const value = list[id];
88
+ if (value === undefined) {
89
+ throw new Error(`bivium: fanin: no node with id ${id}.`);
90
+ }
91
+ return value;
92
+ }
93
+ function graphReport2(graph, suites) {
94
+ const counts = suites.map((suite) => [suite.name, fanIn2(graph, suite)]);
95
+ const unknown = [...graph].filter(([, deps]) => deps.unknown.length > 0).map(([node]) => node);
96
+ const everyChange = walksByTypes(graph, unknown, {
97
+ includeUnknown: false,
98
+ readers: false
99
+ });
100
+ return {
101
+ suites: Object.fromEntries(suites.map((suite) => [
102
+ suite.name,
103
+ {
104
+ total: [...graph.keys()].filter(suite.isTest).length,
105
+ everyChange: sorted(everyChange(suite.types)).filter(suite.isTest)
106
+ }
107
+ ])),
108
+ nodes: [...graph].map(([node, deps]) => ({
109
+ node,
110
+ imports: sorted(deps.files),
111
+ importers: sorted(importersOf(graph, node)),
112
+ fanIn: Object.fromEntries(counts.map(([name, count]) => [name, count.get(node) ?? 0])),
113
+ unknown: deps.unknown.length > 0
114
+ }))
115
+ };
116
+ }
117
+ function buckets(total) {
118
+ const list = [
119
+ [0, 0],
120
+ [1, 1]
121
+ ];
122
+ for (let low = 2, high = 10;low < total; low = high + 1, high *= 10) {
123
+ list.push([low, Math.min(high, total - 1)]);
124
+ }
125
+ if (total > 1)
126
+ list.push([total, total]);
127
+ return list;
128
+ }
129
+ function formatGraph2(report, top) {
130
+ const lines = [];
131
+ const files = report.nodes.filter(({ node }) => !node.startsWith("pkg:") && !node.includes("#"));
132
+ for (const [name, { total: tests, everyChange }] of Object.entries(report.suites)) {
133
+ const any = everyChange.length;
134
+ lines.push(`${name}: ${plural2(tests, "test")}${any > 0 ? `; ${any} run on any change (\`bivium check\` says why)` : ""}`);
135
+ const ranked = files.map(({ node, fanIn: reach }) => [node, reach[name] ?? 0]).filter(([, count]) => count > 0).sort(([a, x], [b, y]) => y - x || (a < b ? -1 : 1));
136
+ const width = Math.max(String(tests).length, 5);
137
+ if (ranked.length > 0) {
138
+ lines.push(` ${"tests".padStart(width)} file`);
139
+ for (const [id, count] of ranked.slice(0, top)) {
140
+ lines.push(` ${String(count).padStart(width)} ${id}`);
141
+ }
142
+ if (ranked.length > top) {
143
+ lines.push(` … ${ranked.length - top} more (--top <n> shows more)`);
144
+ }
145
+ }
146
+ lines.push(` files by how many ${name} tests a change to one selects:`);
147
+ const rows = buckets(tests).map(([low, high]) => {
148
+ const label = low === high ? String(low) : `${low}–${high}`;
149
+ const count = files.filter(({ fanIn: reach }) => {
150
+ const n = reach[name] ?? 0;
151
+ return n >= low && n <= high;
152
+ }).length;
153
+ return [label, count];
154
+ });
155
+ const labelWidth = Math.max(...rows.map(([label]) => label.length));
156
+ for (const [label, count] of rows) {
157
+ lines.push(` ${label.padStart(labelWidth)} ${count}`);
158
+ }
159
+ }
160
+ return lines.join(`
161
+ `);
162
+ }
163
+
164
+ export { fanIn2, graphReport2, formatGraph2 };