bivium 0.6.2 → 0.8.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/cli.js CHANGED
@@ -1,12 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- version,
4
- githubOutputPath,
5
3
  BiviumError2,
6
- didYouMean,
4
+ didYouMean2
5
+ } from "./shared-211m8fjt.js";
6
+ import {
7
7
  globToRegExp,
8
- inRoot,
9
- sorted,
8
+ inRoot2
9
+ } from "./shared-550cvwt2.js";
10
+ import {
11
+ githubOutputPath,
12
+ nowMs,
13
+ environment,
14
+ agentVariable,
15
+ version,
10
16
  QUERY,
11
17
  UNDECLARED_READS,
12
18
  RELATIVE,
@@ -21,12 +27,31 @@ import {
21
27
  walksByTypes,
22
28
  importersOf,
23
29
  affectedBy,
30
+ sorted,
31
+ PLAIN,
32
+ createPaint,
33
+ wantsColor,
34
+ isDumb,
35
+ SEPARATOR,
36
+ branch,
37
+ NOTE_INDENT,
38
+ closingLine,
39
+ failLine,
40
+ truncateWords,
41
+ truncatePath,
42
+ textWidth,
43
+ MEASURE,
44
+ RULE,
45
+ aligned,
46
+ headerRow,
47
+ plural,
48
+ SILENT,
49
+ createProgress,
24
50
  formatSelection,
25
51
  orphanOf,
26
- plural,
27
- computePlan,
28
- prepare
29
- } from "./shared.js";
52
+ computePlan2,
53
+ prepare2
54
+ } from "./shared-9qcbzxw3.js";
30
55
 
31
56
  // src/main.ts
32
57
  import { spawnSync } from "node:child_process";
@@ -199,6 +224,30 @@ function formatGraph(report, top) {
199
224
  `);
200
225
  }
201
226
 
227
+ // src/human.ts
228
+ function duration(ms) {
229
+ if (ms < 999.5)
230
+ return `${Math.round(ms)} ms`;
231
+ const s = ms / 1000;
232
+ return `${s < 999.5 ? s.toPrecision(3) : Math.round(s)} s`;
233
+ }
234
+ function wrapped(text, first, hang) {
235
+ const lines = [];
236
+ let line = first;
237
+ let empty = true;
238
+ for (const word of text.split(" ")) {
239
+ if (!empty && textWidth(line) + 1 + textWidth(word) > MEASURE) {
240
+ lines.push(line);
241
+ line = hang + word;
242
+ continue;
243
+ }
244
+ line += empty ? word : ` ${word}`;
245
+ empty = false;
246
+ }
247
+ lines.push(line);
248
+ return lines;
249
+ }
250
+
202
251
  // src/locate.ts
203
252
  import { readFile } from "node:fs/promises";
204
253
  import { isAbsolute, join } from "node:path";
@@ -395,7 +444,7 @@ function spellers(config, { graph }) {
395
444
  continue;
396
445
  if (node.startsWith("pkg:") || node.includes("#"))
397
446
  continue;
398
- if (suite.isTest(node) || (reached.get(node) ?? 0) > 0 && suite.roots.some((root) => inRoot(node, root))) {
447
+ if (suite.isTest(node) || (reached.get(node) ?? 0) > 0 && suite.roots.some((root) => inRoot2(node, root))) {
399
448
  const suites = found.get(node);
400
449
  suites ? suites.push(suite) : found.set(node, [suite]);
401
450
  }
@@ -416,7 +465,7 @@ function withNames(graph, targets) {
416
465
  ...[...graph.get(file)?.barrel?.keys() ?? []].map((name) => `${file}#${name}`)
417
466
  ]);
418
467
  }
419
- async function spelledPaths(root, config, computed) {
468
+ async function spelledPaths(root, config, computed, done = () => {}) {
420
469
  const { graph } = computed;
421
470
  const files = new Set;
422
471
  const dirs = new Map;
@@ -434,7 +483,10 @@ async function spelledPaths(root, config, computed) {
434
483
  const spelling = spellers(config, computed);
435
484
  const nodes = [...spelling.keys()];
436
485
  const sources = await Promise.all(nodes.map((node) => sourceOf(root, node)));
486
+ const every = Math.max(1, Math.ceil(nodes.length / 20));
437
487
  for (const [i, node] of nodes.entries()) {
488
+ if (i % every === 0)
489
+ done(i / nodes.length);
438
490
  const source = sources[i];
439
491
  const suites = spelling.get(node) ?? [];
440
492
  const through = [
@@ -746,7 +798,8 @@ function unreachedFiles(config, { graph }, spelled) {
746
798
  }
747
799
  return found;
748
800
  }
749
- async function check(root, config, computed) {
801
+ async function check(root, config, computed, step = () => {}) {
802
+ step("finding what the graph can't read", 0.05);
750
803
  const nodes = [...computed.graph].filter(([, deps]) => deps.unknown.length > 0).map(([node]) => node);
751
804
  const testsOf = (node) => {
752
805
  const reach = walksByTypes(computed.graph, [node], {
@@ -779,8 +832,11 @@ async function check(root, config, computed) {
779
832
  file,
780
833
  reason
781
834
  }));
835
+ step("finding dead globs", 0.1);
782
836
  const dead = await findDeadGlobs(root, config, computed);
783
- const spelled = await spelledPaths(root, config, computed);
837
+ const spelling = "finding paths nothing declares";
838
+ const spelled = await spelledPaths(root, config, computed, (ratio) => step(spelling, 0.15 + 0.8 * ratio));
839
+ step("finding files no test reaches", 0.95);
784
840
  const unreached = unreachedFiles(config, computed, [
785
841
  ...spelled.undeclared,
786
842
  ...spelled.orphaned
@@ -817,19 +873,6 @@ function widening(report) {
817
873
  function failed(report, max) {
818
874
  return max !== undefined && widening(report).length > max || report.unlistedUnknowns.length > 0 || report.staleKnownUnknowns.length > 0 || report.deadGlobs.length > 0 || report.staleDeadGlobs.length > 0 || report.undeclaredPaths.length > 0;
819
875
  }
820
- function pushUnknown(lines, { node, causes, tests, known }, shown) {
821
- lines.push(known === undefined ? node : `${node} (known: ${known})`);
822
- for (const { cause, at, fix } of causes) {
823
- const first = shown.get(fix);
824
- if (first === undefined)
825
- shown.set(fix, node);
826
- lines.push(` ✗ ${cause}${at ? ` ${at}` : ""}`, ` fix: ${first === undefined ? fix : `as for ${first}`}`);
827
- }
828
- if (tests.length > 0) {
829
- const more = tests.length > 3 ? `, and ${tests.length - 3} more` : "";
830
- lines.push(` runs on any change: ${tests.slice(0, 3).join(", ")}${more}`);
831
- }
832
- }
833
876
  function categoryOf(cause) {
834
877
  if (cause.startsWith("unresolved ")) {
835
878
  const specifier = QUOTED.exec(cause)?.[1] ?? "";
@@ -851,13 +894,9 @@ function categoryOf(cause) {
851
894
  return cause;
852
895
  }
853
896
  var POSITION = /(?: in <>)? at \d+.*$/;
854
- var BLANK_LINES = /\n{3,}/g;
855
897
  function byCount(counts) {
856
898
  return Object.fromEntries([...counts].sort(([a, x], [b, y]) => y - x || (a < b ? -1 : 1)));
857
899
  }
858
- function counted(counts) {
859
- return Object.entries(counts).map(([what, count]) => `${count} ${what}`);
860
- }
861
900
  function summarize(report) {
862
901
  const widen = widening(report);
863
902
  const causes = new Map;
@@ -887,172 +926,321 @@ function summarize(report) {
887
926
  unreached: report.unreached.length
888
927
  };
889
928
  }
890
- function summaryLines(report) {
891
- const counts = summarize(report);
892
- const lines = [];
893
- if (counts.unknown > 0) {
894
- const { unknown, testsOnAnyChange: tests } = counts;
895
- lines.push(`${plural(unknown, "node")} with unknown dependencies ${unknown === 1 ? "reaches" : "reach"} ${plural(tests, "test")}, which ${tests === 1 ? "runs" : "run"} on any change:`);
896
- lines.push(...counted(counts.unknownByCause).map((line) => ` ${line}`));
897
- }
898
- if (counts.unknownNoTestReaches > 0) {
899
- lines.push(`${plural(counts.unknownNoTestReaches, "more node")} with unknown dependencies no test reaches`);
900
- }
901
- if (counts.fallbacks > 0) {
902
- lines.push(`${plural(counts.fallbacks, "file")} read by the regex extractor: ${counted(counts.fallbackReasons).join(", ")}`);
903
- }
904
- const problems = [
905
- [
906
- counts.unparsedTsconfigs,
907
- "tsconfig file that doesn't parse",
908
- "tsconfig files that don't parse"
909
- ],
910
- [counts.deadGlobs, "dead glob", "dead globs"],
911
- [
912
- counts.staleDeadGlobs,
913
- "stale `deadGlobs` entry",
914
- "stale `deadGlobs` entries"
915
- ],
916
- [
917
- counts.unlistedUnknowns,
918
- "unknown not in `knownUnknowns`",
919
- "unknowns not in `knownUnknowns`"
920
- ],
921
- [
922
- counts.staleKnownUnknowns,
923
- "stale `knownUnknowns` entry",
924
- "stale `knownUnknowns` entries"
925
- ],
926
- [
927
- counts.undeclaredPaths,
928
- "path spelled in code that nothing declares",
929
- "paths spelled in code that nothing declares"
930
- ],
931
- [
932
- counts.unreached,
933
- "file under a suite's root that no test reaches",
934
- "files under a suite's root that no test reaches"
935
- ]
936
- ];
937
- for (const [count, one, many] of problems) {
938
- if (count > 0)
939
- lines.push(plural(count, one, many));
929
+ var SHOWN = 3;
930
+ var BRANCH_WIDTH = " ├ ".length;
931
+ function sharedFix(examples) {
932
+ const counts = new Map;
933
+ for (const { fix } of examples) {
934
+ if (fix !== undefined)
935
+ counts.set(fix, (counts.get(fix) ?? 0) + 1);
940
936
  }
941
- return lines.length === 0 ? [] : ["Summary:", ...lines.map((line) => ` ${line}`), ""];
942
- }
943
- var UNREACHED_SHOWN = 10;
944
- function pushUnreached(lines, unreached) {
945
- if (unreached.length === 0)
946
- return;
947
- lines.push("", "Files under a suite's root that no test reaches: a change to one runs the whole suite:");
948
- for (const suite of new Set(unreached.map((entry) => entry.suite))) {
949
- const entries = unreached.filter((entry) => entry.suite === suite);
950
- lines.push(` ${suite} (${entries.length})`);
951
- for (const { file, fix } of entries.slice(0, UNREACHED_SHOWN)) {
952
- lines.push(` ${file}`, ` fix: ${fix}`);
953
- }
954
- const rest = entries.slice(UNREACHED_SHOWN);
955
- if (rest.length === 0)
956
- continue;
957
- const dirs = new Map;
958
- for (const { file } of rest) {
959
- const dir = posix2.dirname(file);
960
- dirs.set(dir, (dirs.get(dir) ?? 0) + 1);
961
- }
962
- const counts = [...dirs].sort(([a, x], [b, y]) => y - x || (a < b ? -1 : 1)).map(([dir, count]) => `${dir}/ (${count})`);
963
- lines.push(` … ${rest.length} more in ${counts.slice(0, 5).join(", ")}${counts.length > 5 ? ", …" : ""} (--json lists each)`);
964
- }
965
- }
966
- function pushUndeclared(lines, spelled) {
967
- if (spelled.length === 0)
937
+ const [top] = [...counts].sort(([, a], [, b]) => b - a);
938
+ if (top === undefined)
968
939
  return;
969
- lines.push("", "Paths spelled in code that nothing declares: a change there doesn't select the tests that reach the file:");
970
- let file;
971
- for (const { file: node, path, dir, at, fix } of spelled) {
972
- if (node !== file)
973
- lines.push(` ${node}`);
974
- file = node;
975
- lines.push(` ✗ ${dir ? `${path}/` : path}${at ? ` ${at}` : ""}`, ` fix: ${fix}`);
976
- }
977
- }
978
- function formatReport(report, max) {
979
- const lines = summaryLines(report);
980
- const widen = widening(report);
981
- const shown = new Map;
982
- for (const unknown of widen)
983
- pushUnknown(lines, unknown, shown);
984
- const idle = report.unknown.filter((node) => node.tests.length === 0);
985
- if (idle.length > 0) {
986
- lines.push("", "Unknown, but no test depends on them, so they widen nothing:");
987
- for (const unknown of idle)
988
- pushUnknown(lines, unknown, shown);
989
- }
990
- if (report.fallbacks.length > 0) {
991
- lines.push("", "Read by the regex extractor, which the lexer couldn't read:");
992
- for (const { file, reason } of report.fallbacks) {
993
- lines.push(` ${file}: ${reason}`);
994
- }
995
- }
996
- pushUndeclared(lines, report.undeclaredPaths);
997
- pushUnreached(lines, report.unreached);
998
- if (report.unparsedTsconfigs.length > 0) {
999
- lines.push("", "tsconfig files that don't parse, whose `paths` are ignored:");
1000
- for (const { file, reason } of report.unparsedTsconfigs) {
1001
- lines.push(` ${file}: ${reason}`);
1002
- }
940
+ return top[1] > 1 || examples.length === 1 ? top[0] : undefined;
941
+ }
942
+ function fixLines({ paint, all }, first, fix) {
943
+ const label = `${first}${paint.good("fix")} `;
944
+ if (all) {
945
+ return {
946
+ lines: wrapped(fix, label, " ".repeat(textWidth(label))),
947
+ cut: false
948
+ };
1003
949
  }
1004
- if (report.deadGlobs.length > 0) {
1005
- lines.push("", "Dead globs: a change to what they match, or to some of it, selects nothing:");
1006
- let node;
1007
- for (const dead of report.deadGlobs) {
1008
- if (dead.node !== node)
1009
- lines.push(` ${dead.node}`);
1010
- node = dead.node;
1011
- lines.push(` ✗ ${dead.kind} ${dead.glob}: ${summary(dead)}${dead.at ? ` ${dead.at}` : ""}`, ` fix: ${dead.fix}`);
950
+ const shown = truncateWords(fix, MEASURE - textWidth(label));
951
+ return { lines: [`${label}${shown}`], cut: shown !== fix };
952
+ }
953
+ function renderSection(view, { title, count, examples }) {
954
+ const { paint, all } = view;
955
+ const lines = [`${paint.bold(title)}${paint.dim(`${SEPARATOR}${count}`)}`];
956
+ const shared = sharedFix(examples);
957
+ const shown = all ? examples : examples.slice(0, SHOWN);
958
+ const hidden = examples.length - shown.length;
959
+ let cut = hidden > 0;
960
+ const detailWidth = Math.min(40, Math.max(0, ...shown.map(({ detail }) => textWidth(detail ?? ""))));
961
+ const placeMax = Math.max(30, MEASURE - BRANCH_WIDTH - (detailWidth > 0 ? detailWidth + 2 : 0));
962
+ const places = shown.map(({ place }) => {
963
+ const fitted = all ? place : truncatePath(place, placeMax);
964
+ cut ||= fitted !== place;
965
+ return fitted;
966
+ });
967
+ const placeWidth = Math.max(0, ...places.map(textWidth));
968
+ for (const [i, example] of shown.entries()) {
969
+ const glyph = paint.dim(branch(i, hidden > 0 ? shown.length + 1 : shown.length));
970
+ const place = places[i] ?? "";
971
+ let detail = example.detail ?? "";
972
+ if (detail !== "" && !all) {
973
+ const room = MEASURE - BRANCH_WIDTH - placeWidth - 2;
974
+ const fitted = truncateWords(detail, room);
975
+ cut ||= fitted !== detail;
976
+ detail = fitted;
1012
977
  }
1013
- }
1014
- if (report.staleDeadGlobs.length > 0) {
1015
- lines.push("", "`deadGlobs` entries that match no dead glob:");
1016
- for (const { file, glob, fix } of report.staleDeadGlobs) {
1017
- lines.push(` ${file}: ${glob}`, ` fix: ${fix}`);
978
+ lines.push(detail === "" ? ` ${glyph}${place}` : ` ${glyph}${place.padEnd(placeWidth)} ${paint.dim(detail)}`);
979
+ if (example.fix !== undefined && example.fix !== shared) {
980
+ const note = fixLines(view, NOTE_INDENT, example.fix);
981
+ lines.push(...note.lines);
982
+ cut ||= note.cut;
1018
983
  }
1019
984
  }
1020
- if (report.staleKnownUnknowns.length > 0) {
1021
- lines.push("", "`knownUnknowns` entries whose dependencies are known:");
1022
- for (const { file, fix } of report.staleKnownUnknowns) {
1023
- lines.push(` ${file}`, ` fix: ${fix}`);
985
+ if (hidden > 0) {
986
+ lines.push(` ${paint.dim(`└ ${hidden} more`)}`);
987
+ }
988
+ if (shared !== undefined) {
989
+ const line = fixLines(view, " ", shared);
990
+ lines.push(...line.lines);
991
+ cut ||= line.cut;
992
+ }
993
+ return { lines, cut };
994
+ }
995
+ var UNRESOLVED = "unresolved ";
996
+ function countOf(hits, files, noun) {
997
+ return hits === files && noun !== "import" ? plural(files, "file") : `${plural(hits, noun)} in ${plural(files, "file")}`;
998
+ }
999
+ function causeSections(widen) {
1000
+ const byCategory = new Map;
1001
+ for (const { node, causes, known } of widen) {
1002
+ for (const { cause, at, fix } of causes) {
1003
+ const category = categoryOf(cause);
1004
+ const named = cause.startsWith(UNRESOLVED) ? cause.slice(UNRESOLVED.length) : cause === category ? "" : cause;
1005
+ const detail = [named, known === undefined ? "" : `known: ${known}`].filter((part) => part !== "").join(SEPARATOR);
1006
+ const example = { place: at ?? node, fix };
1007
+ if (detail !== "")
1008
+ example.detail = detail;
1009
+ const hits = byCategory.get(category) ?? [];
1010
+ hits.push({ node, example });
1011
+ byCategory.set(category, hits);
1024
1012
  }
1025
1013
  }
1026
- const count = widen.length;
1027
- const limit = max === undefined ? "" : ` (at most ${max})`;
1028
- lines.push("", `${count} ${count === 1 ? "node" : "nodes"} with unknown dependencies ${count === 1 ? "reaches" : "reach"} a test${limit}: each such test runs on any change.`);
1029
- const unlisted = report.unlistedUnknowns.length;
1030
- if (unlisted > 0) {
1031
- lines.push(`${unlisted} of them not in \`knownUnknowns\`: fix ${unlisted === 1 ? "it" : "them"}, or list ${unlisted === 1 ? "it" : "them"} with a reason.`);
1032
- }
1033
- if (idle.length > 0) {
1034
- lines.push(`${idle.length} more no test reaches.`);
1035
- }
1036
- const staleKnown = report.staleKnownUnknowns.length;
1037
- if (staleKnown > 0) {
1038
- lines.push(`${plural(staleKnown, "stale `knownUnknowns` entry", "stale `knownUnknowns` entries")}.`);
1039
- }
1040
- const undeclared = report.undeclaredPaths.length;
1041
- if (undeclared > 0) {
1042
- lines.push(`${plural(undeclared, "path", "paths")} spelled in code that nothing declares.`);
1043
- }
1044
- const dead = report.deadGlobs.length;
1045
- const stale = report.staleDeadGlobs.length;
1046
- if (dead > 0) {
1047
- lines.push(`${plural(dead, "dead glob")} not in \`deadGlobs\`.`);
1014
+ return [...byCategory].map(([category, hits]) => {
1015
+ const files = new Set(hits.map(({ node }) => node)).size;
1016
+ const noun = category.includes("import") ? "import" : "place";
1017
+ return {
1018
+ files,
1019
+ section: {
1020
+ title: category,
1021
+ count: countOf(hits.length, files, noun),
1022
+ examples: hits.map(({ example }) => example)
1023
+ }
1024
+ };
1025
+ }).sort((a, b) => b.files - a.files || (a.section.title < b.section.title ? -1 : 1)).map(({ section }) => section);
1026
+ }
1027
+ var filesIn = (entries) => new Set(entries.map(({ file }) => file)).size;
1028
+ function otherSections(report) {
1029
+ const sections = [];
1030
+ const add = (section) => {
1031
+ if (section.examples.length > 0)
1032
+ sections.push(section);
1033
+ };
1034
+ const spelled = report.undeclaredPaths;
1035
+ add({
1036
+ title: "path spelled in code that nothing declares",
1037
+ count: `${plural(spelled.length, "path")} in ${plural(filesIn(spelled), "file")}`,
1038
+ examples: spelled.map(({ file, path, dir, at, fix }) => ({
1039
+ place: at ?? file,
1040
+ detail: dir ? `${path}/` : path,
1041
+ fix
1042
+ }))
1043
+ });
1044
+ const dead = report.deadGlobs;
1045
+ add({
1046
+ title: "dead glob: a change to what it matches selects nothing",
1047
+ count: `${plural(dead.length, "glob")} in ${plural(new Set(dead.map(({ node }) => node)).size, "file")}`,
1048
+ examples: dead.map((found) => ({
1049
+ place: found.at ?? found.node,
1050
+ detail: `${found.kind} ${found.glob}: ${summary(found)}`,
1051
+ fix: found.fix
1052
+ }))
1053
+ });
1054
+ add({
1055
+ title: "`deadGlobs` entry that matches no dead glob",
1056
+ count: plural(report.staleDeadGlobs.length, "entry", "entries"),
1057
+ examples: report.staleDeadGlobs.map(({ file, glob, fix }) => ({
1058
+ place: file,
1059
+ detail: glob,
1060
+ fix
1061
+ }))
1062
+ });
1063
+ add({
1064
+ title: "unknown not in `knownUnknowns`",
1065
+ count: plural(report.unlistedUnknowns.length, "file"),
1066
+ examples: report.unlistedUnknowns.map((node) => ({
1067
+ place: node,
1068
+ fix: "make its dependencies known, or list it in `knownUnknowns` with a reason"
1069
+ }))
1070
+ });
1071
+ add({
1072
+ title: "`knownUnknowns` entry whose dependencies are known",
1073
+ count: plural(report.staleKnownUnknowns.length, "entry", "entries"),
1074
+ examples: report.staleKnownUnknowns.map(({ file, reason, fix }) => ({
1075
+ place: file,
1076
+ detail: reason,
1077
+ fix
1078
+ }))
1079
+ });
1080
+ for (const suite of new Set(report.unreached.map(({ suite }) => suite))) {
1081
+ const entries = report.unreached.filter((entry) => entry.suite === suite);
1082
+ add({
1083
+ title: "no test reaches: a change runs the whole suite",
1084
+ count: `${plural(entries.length, "file")} in suite ${suite}`,
1085
+ examples: entries.map(({ file, fix }) => ({ place: file, fix }))
1086
+ });
1048
1087
  }
1049
- if (stale > 0) {
1050
- lines.push(`${plural(stale, "stale `deadGlobs` entry", "stale `deadGlobs` entries")}.`);
1088
+ add({
1089
+ title: "tsconfig that doesn't parse, whose `paths` are ignored",
1090
+ count: plural(report.unparsedTsconfigs.length, "file"),
1091
+ examples: report.unparsedTsconfigs.map(({ file, reason }) => ({
1092
+ place: file,
1093
+ detail: reason
1094
+ }))
1095
+ });
1096
+ add({
1097
+ title: "read by the regex extractor",
1098
+ count: `${plural(report.fallbacks.length, "file")} the lexer couldn't read`,
1099
+ examples: report.fallbacks.map(({ file, reason }) => ({
1100
+ place: file,
1101
+ detail: reason
1102
+ }))
1103
+ });
1104
+ const idle = report.unknown.filter((node) => node.tests.length === 0);
1105
+ add({
1106
+ title: "unknown, but no test reaches it, so it widens nothing",
1107
+ count: plural(idle.length, "file"),
1108
+ examples: idle.flatMap(({ node, causes, known }) => causes.map(({ cause, at }) => ({
1109
+ place: at ?? node,
1110
+ detail: known === undefined ? cause : `${cause}${SEPARATOR}known: ${known}`
1111
+ })))
1112
+ });
1113
+ return sections;
1114
+ }
1115
+ function verdict(paint, counts) {
1116
+ const { unknown, testsOnAnyChange: tests } = counts;
1117
+ if (unknown === 0) {
1118
+ return paint.good("bivium can follow every file a test reaches");
1119
+ }
1120
+ return `${paint.bad(`${plural(unknown, "file")} bivium can't follow`)} ${unknown === 1 ? "sends" : "send"} ${paint.bold(String(tests))} ${tests === 1 ? "test" : "tests"} to every change`;
1121
+ }
1122
+ function context(counts, max) {
1123
+ const parts = [
1124
+ max === undefined ? "" : `at most ${max} allowed`,
1125
+ counts.undeclaredPaths > 0 ? plural(counts.undeclaredPaths, "undeclared path") : "",
1126
+ counts.deadGlobs > 0 ? plural(counts.deadGlobs, "dead glob") : "",
1127
+ counts.staleDeadGlobs > 0 ? plural(counts.staleDeadGlobs, "stale `deadGlobs` entry", "stale `deadGlobs` entries") : "",
1128
+ counts.unlistedUnknowns > 0 ? `${counts.unlistedUnknowns} not in \`knownUnknowns\`` : "",
1129
+ counts.staleKnownUnknowns > 0 ? plural(counts.staleKnownUnknowns, "stale `knownUnknowns` entry", "stale `knownUnknowns` entries") : "",
1130
+ counts.unreached > 0 ? `${plural(counts.unreached, "file")} no test reaches` : "",
1131
+ counts.unparsedTsconfigs > 0 ? plural(counts.unparsedTsconfigs, "tsconfig that doesn't parse", "tsconfigs that don't parse") : "",
1132
+ counts.fallbacks > 0 ? `${plural(counts.fallbacks, "file")} the lexer couldn't read` : "",
1133
+ counts.unknownNoTestReaches > 0 ? `${counts.unknownNoTestReaches} more unknown no test reaches` : ""
1134
+ ].filter((part) => part !== "");
1135
+ const lines = [];
1136
+ for (const part of parts) {
1137
+ const last = lines.at(-1);
1138
+ if (last !== undefined && textWidth(last) + SEPARATOR.length + textWidth(part) <= MEASURE) {
1139
+ lines[lines.length - 1] = `${last}${SEPARATOR}${part}`;
1140
+ } else
1141
+ lines.push(part);
1051
1142
  }
1143
+ return lines;
1144
+ }
1145
+ function failures(counts, max) {
1146
+ const parts = [
1147
+ [
1148
+ max !== undefined && counts.unknown > max ? counts.unknown : 0,
1149
+ `unknown, over --max-unknown ${max}`,
1150
+ `unknown, over --max-unknown ${max}`
1151
+ ],
1152
+ [counts.unlistedUnknowns, "unlisted unknown", "unlisted unknowns"],
1153
+ [counts.undeclaredPaths, "undeclared path", "undeclared paths"],
1154
+ [counts.deadGlobs, "dead glob", "dead globs"],
1155
+ [
1156
+ counts.staleKnownUnknowns + counts.staleDeadGlobs,
1157
+ "stale entry",
1158
+ "stale entries"
1159
+ ]
1160
+ ];
1161
+ return parts.flatMap(([count, one, many]) => count > 0 ? [plural(count, one, many)] : []);
1162
+ }
1163
+ function formatReport(report, max, view) {
1164
+ const { paint } = view;
1165
+ const counts = summarize(report);
1166
+ const lines = [
1167
+ verdict(paint, counts),
1168
+ ...context(counts, max).map((line) => paint.dim(line)),
1169
+ ""
1170
+ ];
1171
+ let cut = false;
1172
+ for (const section of [
1173
+ ...causeSections(widening(report)),
1174
+ ...otherSections(report)
1175
+ ]) {
1176
+ const rendered = renderSection(view, section);
1177
+ lines.push(...rendered.lines, "");
1178
+ cut ||= rendered.cut;
1179
+ }
1180
+ const detail = `checked in ${duration(view.elapsedMs)}${cut ? `${SEPARATOR}--all for every file` : ""}`;
1181
+ const failed = failures(counts, max);
1182
+ lines.push(failed.length > 0 ? failLine(paint, failed.join(SEPARATOR), detail) : closingLine(paint, "Check passes", detail));
1052
1183
  return lines.join(`
1053
- `).replace(BLANK_LINES, `
1184
+ `);
1185
+ }
1186
+
1187
+ // src/help.ts
1188
+ var row = (p, name, does, preset) => ` ${name.padEnd(21)}${does}${preset === undefined ? "" : p.dim(`${SEPARATOR}${preset}`)}`;
1189
+ var example = (p, intent, command) => ` ${p.dim(`# ${intent}`)}
1190
+ ${command}`;
1191
+ function usage(p) {
1192
+ return `${p.bold("bivium")} ${version}${p.dim(`${SEPARATOR}run only the tests your change can reach`)}
1193
+
1194
+ ${p.bold("Usage")}
1195
+ bivium <command> [arguments] [options]
1196
+
1197
+ ${p.bold("Commands")}
1198
+ ${row(p, "plan [base]", "the tests a change can affect, per suite")}
1199
+ ${row(p, "run [base]", "run a suite's selected tests")}
1200
+ ${row(p, "why <test> [file]", "the chain from a change, or a file, to a test")}
1201
+ ${row(p, "check", "what the graph can't read, and dead globs")}
1202
+ ${row(p, "graph", "each file's test fan-in, and the graph")}
1203
+
1204
+ base defaults to the config's base, else the upstream default branch.
1205
+ Options go before or after the command, as --flag value or --flag=value.
1206
+ A path is repo-relative, relative to the current directory, or absolute.
1207
+
1208
+ ${p.bold("Options")}
1209
+ ${row(p, "--config <file>", "the config file", "bivium.config.{ts,mts,mjs,js,json}")}
1210
+ ${row(p, "--cwd <dir>", "the repository", "the current directory")}
1211
+ ${row(p, "--no-cache", "read every file; skip the extraction cache")}
1212
+ ${row(p, "--json", "plan, why, check, graph: print JSON")}
1213
+ ${row(p, "--color, --no-color", "force color on or off", "on in a terminal")}
1214
+ ${row(p, "-h, --help", "this help")}
1215
+ ${row(p, "-v, --version", "the version")}
1216
+
1217
+ ${p.bold(" plan")}
1218
+ ${row(p, "--list", "the files, as when piped, on a terminal too")}
1219
+ ${row(p, "--github", "also write each suite's selection to $GITHUB_OUTPUT")}
1220
+ ${p.bold(" run")}
1221
+ ${row(p, "--suite <name>", "the suite to run", "the first")}
1222
+ ${p.bold(" why")}
1223
+ ${row(p, "--base <ref>", "the base ref", "as for plan")}
1224
+ ${row(p, "--format <f>", "tree, chain, source or json", "tree")}
1225
+ ${row(p, "--all", "every change's chain, not only the shortest")}
1226
+ ${p.bold(" check")}
1227
+ ${row(p, "--base <ref>", "the base ref", "HEAD")}
1228
+ ${row(p, "--all", "every file, and each fix whole")}
1229
+ ${row(p, "--max-unknown <n>", "fail past n unknown files that reach a test")}
1230
+ ${p.bold(" graph")}
1231
+ ${row(p, "--suite <name>", "only this suite", "every suite")}
1232
+ ${row(p, "--top <n>", "files to list per suite", "10")}
1233
+
1234
+ ${p.bold("Examples")}
1235
+ ${example(p, "the tests this branch needs, as data", "bivium plan origin/main --json")}
1236
+ ${example(p, "how a change to a file reaches a test", "bivium why tests/Button.test.ts src/Button.svelte --format chain")}
1237
+ ${example(p, "fail CI when a file bivium can't follow reaches a test", "bivium check --max-unknown 0")}
1054
1238
 
1055
- `).trimStart();
1239
+ ${p.bold("For agents")}
1240
+ Run with --json; read ok and summary. Exit 0 done, 1 check found
1241
+ problems, 2 a usage, config or git error; run exits with its command's.
1242
+ With --json, an error is JSON too: error.kind (usage, config, git or
1243
+ other), error.code and error.message.`;
1056
1244
  }
1057
1245
 
1058
1246
  // src/why.ts
@@ -1324,31 +1512,42 @@ var LIST = 3;
1324
1512
  function nameOf(node) {
1325
1513
  return node.slice(node.indexOf("#") + 1);
1326
1514
  }
1327
- function aligned(rows) {
1328
- const width = Math.max(0, ...rows.filter(([, at]) => at !== undefined).map(([text]) => text.length));
1329
- return rows.map(([text, at]) => at === undefined ? text : `${text.padEnd(width)} ${at}`);
1515
+ function aligned2(rows, paint) {
1516
+ const width = Math.max(0, ...rows.filter(([, , at]) => at !== undefined).map(([, t]) => t.length));
1517
+ return rows.map(([shown, plain, at]) => at === undefined ? shown : `${shown}${" ".repeat(width - plain.length)} ${paint.dim(at)}`);
1330
1518
  }
1331
- function tree(test, chain) {
1332
- const rows = [[test, undefined]];
1519
+ function tree(test, chain, paint) {
1520
+ const rows = [[paint.bold(test), test, undefined]];
1521
+ const row = (indent, glyph, shown, plain) => [
1522
+ `${indent}${paint.dim(glyph)}${shown}`,
1523
+ `${indent}${glyph}${plain}`
1524
+ ];
1333
1525
  const width = Math.max(0, ...chain.links.filter((link) => link.kind !== "unknown").map((link) => link.kind.length));
1334
1526
  let indent = "";
1335
1527
  for (const [i, link] of chain.links.entries()) {
1336
1528
  const next = chain.links[i + 1]?.node ?? chain.root;
1337
1529
  if (link.kind === "unknown") {
1338
- rows.push([`${indent}└─ depends on every change:`, undefined]);
1530
+ const every = "depends on every change:";
1531
+ rows.push([...row(indent, "└─ ", every, every), undefined]);
1339
1532
  for (const { cause, at } of chain.unknown) {
1340
- rows.push([`${indent} ✗ ${cause}`, at]);
1533
+ const plain = `${indent} ✗ ${cause}`;
1534
+ rows.push([`${indent} ${paint.bad("✗")} ${cause}`, plain, at]);
1341
1535
  }
1342
1536
  indent += " ";
1343
- rows.push([`${indent}└─ ${next}`, undefined]);
1537
+ rows.push([...row(indent, "└─ ", next, next), undefined]);
1344
1538
  indent += " ";
1345
1539
  break;
1346
1540
  }
1347
- rows.push([`${indent}└─ ${link.kind.padEnd(width)} ${next}`, link.at]);
1541
+ const kind = link.kind.padEnd(width);
1542
+ rows.push([
1543
+ ...row(indent, "└─ ", `${paint.faint(kind)} ${next}`, `${kind} ${next}`),
1544
+ link.at
1545
+ ]);
1348
1546
  indent += " ";
1349
1547
  }
1350
- rows.push([`${indent}● ${chain.cause}`, undefined]);
1351
- return aligned(rows);
1548
+ const end = `${indent}● ${chain.cause}`;
1549
+ rows.push([end, end, undefined]);
1550
+ return aligned2(rows, paint);
1352
1551
  }
1353
1552
  function verbOf(link) {
1354
1553
  return link.kind === "export" ? `exported as ${nameOf(link.node)}` : VERBS[link.kind];
@@ -1359,10 +1558,10 @@ function whereOf(link) {
1359
1558
  return `${link.node} (${configured})`;
1360
1559
  return link.at ?? link.node;
1361
1560
  }
1362
- function steps(links) {
1561
+ function steps(links, paint) {
1363
1562
  const rows = [...links].reverse().map((link) => [verbOf(link), whereOf(link)]);
1364
1563
  const width = Math.max(0, ...rows.map(([verb]) => verb.length));
1365
- return rows.map(([verb, where], i) => `${verb.padEnd(width)} ${where}${i === rows.length - 1 ? " ← selected" : ""}`);
1564
+ return rows.map(([verb, where], i) => i === rows.length - 1 ? `${paint.faint(verb.padEnd(width))} ${paint.bold(where)} ← selected` : `${paint.faint(verb.padEnd(width))} ${paint.dim(where)}`);
1366
1565
  }
1367
1566
  function header({ root, cause }) {
1368
1567
  if (cause === "changed")
@@ -1371,21 +1570,24 @@ function header({ root, cause }) {
1371
1570
  return `if ${root} changes`;
1372
1571
  return `${root}: ${cause}`;
1373
1572
  }
1374
- function chained(test, chain) {
1573
+ function chained(test, chain, paint) {
1375
1574
  const unknownAt = chain.links.findIndex((link) => link.kind === "unknown");
1376
1575
  const unknownLink = chain.links[unknownAt];
1377
1576
  if (unknownLink === undefined) {
1378
- return [header(chain), ...steps(chain.links).map((step) => ` ${step}`)];
1577
+ return [
1578
+ header(chain),
1579
+ ...steps(chain.links, paint).map((step) => ` ${step}`)
1580
+ ];
1379
1581
  }
1380
1582
  const node = unknownLink.node;
1381
1583
  const where = chain.unknown.map(({ at }) => at ?? node);
1382
1584
  const width = Math.max(0, ...where.map((at) => at.length));
1383
- const lines = [`${test} runs on every change`];
1585
+ const lines = [`${paint.bold(test)} runs on every change`];
1384
1586
  for (const { at, cause, fix } of chain.unknown) {
1385
- lines.push(` because ${(at ?? node).padEnd(width)} ${cause}`, ` fix: ${fix}`);
1587
+ lines.push(` because ${paint.dim((at ?? node).padEnd(width))} ${cause}`, ` ${paint.good("fix")}: ${fix}`);
1386
1588
  }
1387
1589
  if (unknownAt > 0) {
1388
- lines.push(` reached via ${node}`, ...steps(chain.links.slice(0, unknownAt)).map((step) => ` ${step}`));
1590
+ lines.push(` reached via ${node}`, ...steps(chain.links.slice(0, unknownAt), paint).map((step) => ` ${step}`));
1389
1591
  }
1390
1592
  return lines;
1391
1593
  }
@@ -1393,7 +1595,7 @@ var LINE_NUMBER = /:(\d+)$/;
1393
1595
  function lineNumber(at) {
1394
1596
  return at === undefined ? undefined : LINE_NUMBER.exec(at)?.[1];
1395
1597
  }
1396
- function sourced(test, chain) {
1598
+ function sourced(test, chain, paint) {
1397
1599
  const unknownAt = chain.links.findIndex((link) => link.kind === "unknown");
1398
1600
  const unknownLink = chain.links[unknownAt];
1399
1601
  const hops = unknownLink === undefined ? chain.links : chain.links.slice(0, unknownAt);
@@ -1402,20 +1604,20 @@ function sourced(test, chain) {
1402
1604
  const gutter = " ".repeat(width);
1403
1605
  const cited = (at, text) => {
1404
1606
  const n = lineNumber(at);
1405
- return n === undefined || text === undefined ? [] : [`${n.padStart(width)} | ${text}`];
1607
+ return n === undefined || text === undefined ? [] : [`${paint.dim(`${n.padStart(width)} |`)} ${text}`];
1406
1608
  };
1407
1609
  const count = plural(hops.length, "hop", "hops");
1408
1610
  const lines = unknownLink === undefined ? [
1409
- `selected: ${test} ← ${chain.root} (${count}${chain.cause === "changed" ? "" : `, ${chain.cause}`})`
1611
+ `selected: ${paint.bold(test)} ← ${chain.root} (${count}${chain.cause === "changed" ? "" : `, ${chain.cause}`})`
1410
1612
  ] : [
1411
- `selected: ${test} ← every change (${unknownAt === 0 ? "its dependencies can't be read" : `${count} to ${unknownLink.node}, whose dependencies can't be read`})`
1613
+ `selected: ${paint.bold(test)} ← every change (${unknownAt === 0 ? "its dependencies can't be read" : `${count} to ${unknownLink.node}, whose dependencies can't be read`})`
1412
1614
  ];
1413
1615
  lines.push("");
1414
1616
  for (const link of hops) {
1415
1617
  const configured = CONFIGURED[link.kind];
1416
1618
  const where = configured === undefined ? link.at ?? link.node : link.node;
1417
1619
  const kind = configured ?? link.kind;
1418
- lines.push(`${gutter}--> ${where} ${kind}`, ...cited(link.at, link.text));
1620
+ lines.push(`${gutter}${paint.dim("-->")} ${paint.dim(where)} ${paint.faint(kind)}`, ...cited(link.at, link.text));
1419
1621
  }
1420
1622
  if (unknownLink === undefined) {
1421
1623
  lines.push(`${gutter}● ${chain.root}: ${chain.cause}`);
@@ -1423,7 +1625,7 @@ function sourced(test, chain) {
1423
1625
  }
1424
1626
  const node = unknownLink.node;
1425
1627
  for (const { cause, at, text, fix } of chain.unknown) {
1426
- lines.push(`${gutter}✗ ${at ?? node} ${cause}`, ...cited(at, text), `${gutter} = fix: ${fix}`);
1628
+ lines.push(`${gutter}${paint.bad("✗")} ${paint.dim(at ?? node)} ${cause}`, ...cited(at, text), `${gutter} = ${paint.good("fix")}: ${fix}`);
1427
1629
  }
1428
1630
  return lines;
1429
1631
  }
@@ -1452,7 +1654,7 @@ function unselectedMessage(explanation) {
1452
1654
  ].join(`
1453
1655
  `);
1454
1656
  }
1455
- function formatExplanation(explanation, format = "tree") {
1657
+ function formatExplanation(explanation, format = "tree", paint = PLAIN) {
1456
1658
  if (explanation.kind === "full") {
1457
1659
  return [
1458
1660
  `The ${explanation.suite} suite runs in full:`,
@@ -1464,60 +1666,17 @@ function formatExplanation(explanation, format = "tree") {
1464
1666
  return unselectedMessage(explanation);
1465
1667
  const { test, more, others } = explanation;
1466
1668
  const render = RENDER[format];
1467
- const lines = render(test, explanation);
1468
- if (more.length > 0)
1469
- lines.push(moreLine(more, others.length > 0));
1669
+ const lines = render(test, explanation, paint);
1670
+ if (more.length > 0) {
1671
+ lines.push(paint.dim(moreLine(more, others.length > 0)));
1672
+ }
1470
1673
  for (const other of others)
1471
- lines.push("", ...render(test, other));
1674
+ lines.push("", ...render(test, other, paint));
1472
1675
  return lines.join(`
1473
1676
  `);
1474
1677
  }
1475
1678
 
1476
1679
  // src/main.ts
1477
- var USAGE = `Usage:
1478
- bivium plan [base] [--json] [--github] print the tests a change can affect
1479
- bivium run [base] [--suite <name>] run a suite's selected tests
1480
- bivium why <test> [file] [--base <ref>] the chain from a change (or file) to a test
1481
- [--format <f>] [--all] [--json]
1482
- bivium check [--max-unknown <n>] [--json]
1483
- what the graph can't read, and dead globs
1484
- bivium graph [--suite <name>] [--top <n>] [--json]
1485
- each file's test fan-in, and the graph
1486
- bivium --version print the version
1487
- bivium --help print this
1488
-
1489
- base defaults to the config's base, else the upstream default branch.
1490
- Options go before or after the command, as --flag value or --flag=value.
1491
- Paths may be repo-relative, relative to the current directory, or
1492
- absolute.
1493
-
1494
- Options:
1495
- --config <file> config file (default: bivium.config.{ts,mts,mjs,js,json})
1496
- --cwd <dir> repository (default: the current directory)
1497
- --no-cache read every file; don't read or write the extraction cache
1498
- --suite <name> for run: the suite (default: the first one); for graph:
1499
- only this suite (default: every one)
1500
- --json for plan, why, check and graph: print JSON
1501
- --github for plan: also write each suite's selection to
1502
- $GITHUB_OUTPUT as <output>=all|none|<files>
1503
- --base <ref> for why and check: the base ref
1504
- --format <f> for why: tree (default), chain (from the change to the
1505
- test), source (each hop's line of source) or json
1506
- --all for why: every change's chain to the test, not only the
1507
- shortest
1508
- --max-unknown <n> for check: fail when more unknown nodes than this reach
1509
- a test
1510
- --top <n> for graph: how many files to list per suite (default: 10)
1511
-
1512
- Exit status: 0 done; 1 check found problems; 2 a usage, configuration or
1513
- git error. run exits with its command's status. With --json, an error is
1514
- also printed to stdout as { "schemaVersion", "error": { "kind", "message" } },
1515
- kind one of usage, config, git or other.
1516
-
1517
- Examples:
1518
- bivium plan origin/main --json
1519
- bivium why tests/Button.test.ts src/Button.svelte --format chain
1520
- bivium check --json`;
1521
1680
  var WHITESPACE = /\s+/;
1522
1681
  var VALUED = new Set([
1523
1682
  "--config",
@@ -1528,12 +1687,12 @@ var VALUED = new Set([
1528
1687
  "--max-unknown",
1529
1688
  "--top"
1530
1689
  ]);
1531
- var COMMON = ["--config", "--cwd", "--no-cache"];
1690
+ var COMMON = ["--config", "--cwd", "--no-cache", "--color", "--no-color"];
1532
1691
  var FLAGS = {
1533
- plan: [...COMMON, "--json", "--github"],
1692
+ plan: [...COMMON, "--json", "--github", "--list"],
1534
1693
  run: [...COMMON, "--suite"],
1535
1694
  why: [...COMMON, "--base", "--json", "--format", "--all"],
1536
- check: [...COMMON, "--base", "--max-unknown", "--json"],
1695
+ check: [...COMMON, "--base", "--max-unknown", "--json", "--all"],
1537
1696
  graph: [...COMMON, "--suite", "--top", "--json"]
1538
1697
  };
1539
1698
  var POSITIONAL = {
@@ -1543,6 +1702,33 @@ var POSITIONAL = {
1543
1702
  check: 0,
1544
1703
  graph: 0
1545
1704
  };
1705
+ var PIPED = {
1706
+ stdout: false,
1707
+ stderr: false,
1708
+ env: {},
1709
+ writeError: () => {}
1710
+ };
1711
+ function colorAsked(argv) {
1712
+ let forced;
1713
+ for (const arg of argv) {
1714
+ if (arg === "--color" || arg === "--color=true")
1715
+ forced = true;
1716
+ if (arg === "--no-color" || arg === "--no-color=true")
1717
+ forced = false;
1718
+ }
1719
+ return forced;
1720
+ }
1721
+ function outFor(io, argv, startMs) {
1722
+ const agent = agentVariable(io.env) !== undefined;
1723
+ const forced = colorAsked(argv);
1724
+ return {
1725
+ io,
1726
+ paint: wantsColor(forced, io.stdout, io.env, agent) ? createPaint() : PLAIN,
1727
+ errorPaint: wantsColor(forced, io.stderr, io.env, agent) ? createPaint() : PLAIN,
1728
+ agent,
1729
+ startMs
1730
+ };
1731
+ }
1546
1732
  var SCHEMA_VERSION = 1;
1547
1733
  function usageError(code, message) {
1548
1734
  return new BiviumError2(code, message);
@@ -1550,7 +1736,7 @@ function usageError(code, message) {
1550
1736
  function unknownOption(command, flag) {
1551
1737
  const known = FLAGS[command] ?? [];
1552
1738
  const others = Object.keys(FLAGS).filter((other) => other !== command && FLAGS[other]?.includes(flag));
1553
- const hint = others.length > 0 ? ` (${others.join(" and ")} ${others.length === 1 ? "takes" : "take"} it)` : didYouMean(flag, known);
1739
+ const hint = others.length > 0 ? ` (${others.join(" and ")} ${others.length === 1 ? "takes" : "take"} it)` : didYouMean2(flag, known);
1554
1740
  return usageError("BV_UNKNOWN_OPTION", `bivium ${command}: unknown option ${flag}${hint}`);
1555
1741
  }
1556
1742
  function parseArgs(command, argv) {
@@ -1637,6 +1823,100 @@ function logPlan({ plan, narrowed }) {
1637
1823
  logSelection(`${name} tests`, selection, total, plan.full.includes(name));
1638
1824
  }
1639
1825
  }
1826
+ function verdictOf(name, selection, total, { plan, changed }, used, paint) {
1827
+ const suite = Object.keys(plan.suites).length > 1 ? ` (${name})` : "";
1828
+ if (selection.mode === "some") {
1829
+ return `${paint.bold(String(selection.files.length))} of ${plural(total, "test")} run for ${plural(changed.length, "changed file")}${suite}`;
1830
+ }
1831
+ if (selection.mode === "none") {
1832
+ const why = changed.length === 0 ? "nothing changed" : "no change reaches a test";
1833
+ return `no tests run${suite}: ${why}`;
1834
+ }
1835
+ const cause = plan.full.includes(name) ? plan.causes.find((candidate) => candidate.suites.includes(name)) : undefined;
1836
+ if (cause !== undefined)
1837
+ used.add(cause);
1838
+ const why = plan.full.includes(name) ? cause?.message ?? "a full run" : "each reaches a change";
1839
+ const every = total === 1 ? "the 1 test runs" : `all ${total} tests run`;
1840
+ return `${every}${suite}: ${why}`;
1841
+ }
1842
+ function commonDir(files) {
1843
+ const [first = ""] = files;
1844
+ let prefix = first.slice(0, first.lastIndexOf("/") + 1);
1845
+ for (const file of files) {
1846
+ while (!file.startsWith(prefix)) {
1847
+ prefix = prefix.slice(0, prefix.lastIndexOf("/", prefix.length - 2) + 1);
1848
+ }
1849
+ }
1850
+ return prefix;
1851
+ }
1852
+ function dirOf(file, prefix) {
1853
+ const slash = file.indexOf("/", prefix.length);
1854
+ return slash === -1 ? `${prefix}*` : file.slice(0, slash + 1);
1855
+ }
1856
+ function countTable(paint, { plan }) {
1857
+ const suites = Object.entries(plan.suites).flatMap(([name, selection]) => selection.mode === "some" ? [{ name, files: selection.files }] : []);
1858
+ const prefix = commonDir(suites.flatMap(({ files }) => files));
1859
+ const counts = new Map;
1860
+ for (const [i, { files }] of suites.entries()) {
1861
+ for (const file of files) {
1862
+ const dir = dirOf(file, prefix);
1863
+ const row = counts.get(dir) ?? suites.map(() => 0);
1864
+ row[i] = (row[i] ?? 0) + 1;
1865
+ counts.set(dir, row);
1866
+ }
1867
+ }
1868
+ if (counts.size < 2)
1869
+ return [];
1870
+ const sum = (row) => row.reduce((a, b) => a + b, 0);
1871
+ const rows = [...counts].sort(([a, x], [b, y]) => sum(y) - sum(x) || (a < b ? -1 : 1));
1872
+ const several = Object.keys(plan.suites).length > 1;
1873
+ const heads = several ? suites.map(({ name }) => name) : ["tests"];
1874
+ const right = heads.map((_, i) => i + 1);
1875
+ return aligned([
1876
+ headerRow(paint, ["directory", ...heads]),
1877
+ ...rows.map(([dir, row]) => [truncatePath(dir, 48), ...row.map(String)]),
1878
+ ["", ...heads.map(() => RULE)],
1879
+ [
1880
+ paint.dim(plural(rows.length, "directory", "directories")),
1881
+ ...suites.map(({ files }) => String(files.length))
1882
+ ]
1883
+ ], right, paint.dim);
1884
+ }
1885
+ async function showPlan(out, base, config, computed) {
1886
+ const { paint } = out;
1887
+ const { plan, narrowed } = computed;
1888
+ const used = new Set;
1889
+ const lines = [];
1890
+ let planned = 0;
1891
+ for (const [name, selection] of Object.entries(plan.suites)) {
1892
+ const total = plan.totals[name] ?? 0;
1893
+ lines.push(verdictOf(name, selection, total, computed, used, paint));
1894
+ if (selection.mode === "some")
1895
+ planned += selection.files.length;
1896
+ if (selection.mode === "all")
1897
+ planned += total;
1898
+ }
1899
+ const mergeBase = (await computed.mergeBase()).slice(0, 7);
1900
+ const notes = [
1901
+ [
1902
+ `since ${base} (merge base ${mergeBase})`,
1903
+ ...config.file ? [`config ${config.file}`] : []
1904
+ ].join(SEPARATOR),
1905
+ ...plan.causes.filter((cause) => !used.has(cause)).map((cause) => `full run: ${cause.message}`),
1906
+ ...plan.packages,
1907
+ ...plan.settings,
1908
+ ...narrowed.flatMap(({ narrower, result }) => ("note" in result) && result.note ? [`${narrower.name}: ${result.note}`] : [])
1909
+ ];
1910
+ lines.push(...notes.map((note) => paint.dim(truncateWords(note, MEASURE))));
1911
+ const table = countTable(paint, computed);
1912
+ if (table.length > 0)
1913
+ lines.push("", ...table);
1914
+ const some = Object.values(plan.suites).some(({ mode }) => mode === "some");
1915
+ const cost = duration(nowMs() - out.startMs);
1916
+ lines.push("", closingLine(paint, `Planned ${plural(planned, "test")}`, some ? `${cost}${SEPARATOR}--list for the files` : cost));
1917
+ console.log(lines.join(`
1918
+ `));
1919
+ }
1640
1920
  function githubOutput() {
1641
1921
  const output = githubOutputPath();
1642
1922
  if (!output) {
@@ -1665,7 +1945,7 @@ function findSuite(config, name) {
1665
1945
  if (suite)
1666
1946
  return suite;
1667
1947
  const names = config.suites.map((candidate) => candidate.name);
1668
- throw usageError("BV_UNKNOWN_SUITE", `bivium: no suite "${name}"${didYouMean(name, names)}; the config has ${names.join(", ")}`);
1948
+ throw usageError("BV_UNKNOWN_SUITE", `bivium: no suite "${name}"${didYouMean2(name, names)}; the config has ${names.join(", ")}`);
1669
1949
  }
1670
1950
  function real(path) {
1671
1951
  try {
@@ -1691,49 +1971,65 @@ function repoPath(root, arg, known) {
1691
1971
  return asWritten;
1692
1972
  return fromCwd !== undefined && known(fromCwd) ? fromCwd : asWritten;
1693
1973
  }
1694
- async function inspect(command, { flags, positional }) {
1974
+ async function inspect(command, { flags, positional }, out) {
1695
1975
  const format = flags.get("--format") ?? "tree";
1696
1976
  if (format !== "json" && !isFormat(format)) {
1697
- throw usageError("BV_BAD_OPTION_VALUE", `bivium why: --format takes tree, chain, source or json${didYouMean(format, ["tree", "chain", "source", "json"])}`);
1977
+ throw usageError("BV_BAD_OPTION_VALUE", `bivium why: --format takes tree, chain, source or json${didYouMean2(format, ["tree", "chain", "source", "json"])}`);
1698
1978
  }
1699
1979
  const maxFlag = flags.get("--max-unknown");
1700
1980
  const max = maxFlag === undefined ? undefined : Number(maxFlag);
1701
1981
  if (max !== undefined && !Number.isInteger(max)) {
1702
1982
  throw usageError("BV_BAD_OPTION_VALUE", "bivium check: --max-unknown takes a whole number");
1703
1983
  }
1704
- const [testArg, fileArg] = positional;
1984
+ const [testArg] = positional;
1705
1985
  if (command === "why" && testArg === undefined) {
1706
1986
  throw usageError("BV_MISSING_ARGUMENT", "bivium why: which test? bivium why <test> [file]");
1707
1987
  }
1708
- const { root, base, config } = await prepare({
1709
- cwd: flags.get("--cwd"),
1710
- base: flags.get("--base") ?? (command === "check" ? "HEAD" : undefined),
1711
- configFile: flags.get("--config")
1712
- });
1713
- const computed = await computePlan(root, base, config, {
1714
- ...flags.has("--no-cache") && { cache: false }
1715
- });
1716
- if (command === "check") {
1717
- const report = await check(root, config, computed);
1718
- const ok = !failed(report, max);
1719
- console.log(flags.has("--json") ? json({ ok, summary: summarize(report), ...report }) : formatReport(report, max));
1720
- return ok ? 0 : 1;
1988
+ const progress = command === "check" && out.io.stderr && !isDumb(out.io.env) && !out.agent && !flags.has("--json") ? createProgress(out.io.writeError, out.errorPaint, nowMs) : SILENT;
1989
+ progress.step("building the graph", 0);
1990
+ try {
1991
+ const { root, base, config } = await prepare2({
1992
+ cwd: flags.get("--cwd"),
1993
+ base: flags.get("--base") ?? (command === "check" ? "HEAD" : undefined),
1994
+ configFile: flags.get("--config")
1995
+ });
1996
+ const computed = await computePlan2(root, base, config, {
1997
+ ...flags.has("--no-cache") && { cache: false }
1998
+ });
1999
+ if (command === "check") {
2000
+ const report = await check(root, config, computed, (what, done) => progress.step(what, done));
2001
+ progress.clear();
2002
+ const ok = !failed(report, max);
2003
+ console.log(flags.has("--json") ? json({ ok, summary: summarize(report), ...report }) : formatReport(report, max, {
2004
+ paint: out.paint,
2005
+ all: flags.has("--all"),
2006
+ elapsedMs: nowMs() - out.startMs
2007
+ }));
2008
+ return ok ? 0 : 1;
2009
+ }
2010
+ return await whyCommand(root, config, computed, flags, positional, out);
2011
+ } catch (error) {
2012
+ progress.clear();
2013
+ throw error;
1721
2014
  }
2015
+ }
2016
+ async function whyCommand(root, config, computed, flags, [testArg, fileArg], out) {
2017
+ const format = flags.get("--format") ?? "tree";
1722
2018
  const inGraph = (path) => computed.graph.has(path);
1723
2019
  const isTest = (path) => config.suites.some((suite) => suite.isTest(path));
1724
2020
  const test = repoPath(root, testArg ?? "", (path) => inGraph(path) && isTest(path));
1725
2021
  const file = fileArg === undefined ? undefined : repoPath(root, fileArg, inGraph);
1726
2022
  if (!isTest(test) || !inGraph(test)) {
1727
2023
  const tests = [...computed.graph.keys()].filter(isTest);
1728
- throw usageError(inGraph(test) ? "BV_UNKNOWN_TEST" : "BV_UNKNOWN_FILE", inGraph(test) ? `bivium why: ${test} is no suite's test: name a test first, as in bivium why <test> ${test}` : `bivium why: no test ${test}${didYouMean(test, tests)}`);
2024
+ throw usageError(inGraph(test) ? "BV_UNKNOWN_TEST" : "BV_UNKNOWN_FILE", inGraph(test) ? `bivium why: ${test} is no suite's test: name a test first, as in bivium why <test> ${test}` : `bivium why: no test ${test}${didYouMean2(test, tests)}`);
1729
2025
  }
1730
2026
  if (file !== undefined && !inGraph(file)) {
1731
- throw usageError("BV_UNKNOWN_FILE", `bivium why: no file ${file}${didYouMean(file, computed.graph.keys())}`);
2027
+ throw usageError("BV_UNKNOWN_FILE", `bivium why: no file ${file}${didYouMean2(file, computed.graph.keys())}`);
1732
2028
  }
1733
2029
  const explanation = await explain(root, config, computed, test, file, {
1734
2030
  all: flags.has("--all")
1735
2031
  });
1736
- console.log(flags.has("--json") || format === "json" ? json(explanation) : formatExplanation(explanation, format));
2032
+ console.log(flags.has("--json") || format === "json" ? json(explanation) : formatExplanation(explanation, isFormat(format) ? format : "tree", out.paint));
1737
2033
  return 0;
1738
2034
  }
1739
2035
  async function graphCommand({ flags }) {
@@ -1741,23 +2037,23 @@ async function graphCommand({ flags }) {
1741
2037
  if (!Number.isInteger(top) || top < 0) {
1742
2038
  throw usageError("BV_BAD_OPTION_VALUE", "bivium graph: --top takes a whole number");
1743
2039
  }
1744
- const { root, base, config } = await prepare({
2040
+ const { root, base, config } = await prepare2({
1745
2041
  cwd: flags.get("--cwd"),
1746
2042
  base: "HEAD",
1747
2043
  configFile: flags.get("--config")
1748
2044
  });
1749
2045
  const one = findSuite(config, flags.get("--suite"));
1750
2046
  const suites = one ? [one] : config.suites;
1751
- const { graph } = await computePlan(root, base, config, {
2047
+ const { graph } = await computePlan2(root, base, config, {
1752
2048
  ...flags.has("--no-cache") && { cache: false }
1753
2049
  });
1754
2050
  const report = graphReport(graph, suites);
1755
2051
  console.log(flags.has("--json") ? json(report) : formatGraph(report, top));
1756
2052
  return 0;
1757
2053
  }
1758
- async function runCommand(command, { flags, positional }) {
2054
+ async function runCommand(command, { flags, positional }, out) {
1759
2055
  const output = flags.has("--github") ? githubOutput() : undefined;
1760
- const { root, base, config } = await prepare({
2056
+ const { root, base, config } = await prepare2({
1761
2057
  cwd: flags.get("--cwd"),
1762
2058
  base: positional[0],
1763
2059
  configFile: flags.get("--config")
@@ -1769,7 +2065,7 @@ async function runCommand(command, { flags, positional }) {
1769
2065
  if (command === "run" && !suite.run) {
1770
2066
  throw usageError("BV_NO_RUN_COMMAND", `bivium run: suite "${suite.name}" has no run command: add suites.${suite.name}.run to the config`);
1771
2067
  }
1772
- const computed = await computePlan(root, base, config, {
2068
+ const computed = await computePlan2(root, base, config, {
1773
2069
  ...flags.has("--no-cache") && { cache: false },
1774
2070
  ...command === "run" && { suites: [suite.name] },
1775
2071
  mergeBase: true
@@ -1793,6 +2089,8 @@ async function runCommand(command, { flags, positional }) {
1793
2089
  packages,
1794
2090
  narrowed
1795
2091
  }));
2092
+ } else if (out.io.stdout && !out.agent && !flags.has("--list")) {
2093
+ await showPlan(out, base, config, computed);
1796
2094
  } else {
1797
2095
  await logContext(base, config, computed);
1798
2096
  logPlan(computed);
@@ -1801,19 +2099,68 @@ async function runCommand(command, { flags, positional }) {
1801
2099
  writeOutputs(output, config, computed);
1802
2100
  return 0;
1803
2101
  }
1804
- await logContext(base, config, computed);
1805
- logPlan(computed);
2102
+ const human = out.io.stdout && !out.agent;
2103
+ const others = flags.has("--suite") ? [] : config.suites.slice(1).map((s) => `--suite=${s.name}`);
2104
+ if (human)
2105
+ await showRun(out, base, config, computed, suite.name, others);
2106
+ else {
2107
+ await logContext(base, config, computed);
2108
+ logPlan(computed);
2109
+ }
1806
2110
  const selection = computed.plan.suites[suite.name];
1807
2111
  if (selection === undefined || selection.mode === "none") {
1808
- console.log(`No ${suite.name} tests affected against ${base}; skipping.`);
2112
+ if (human) {
2113
+ console.log(closingLine(out.paint, `Nothing to run for ${suite.name}`));
2114
+ } else {
2115
+ console.log(`No ${suite.name} tests affected against ${base}; skipping.`);
2116
+ }
1809
2117
  return 0;
1810
2118
  }
1811
- const [program, ...args] = commandFor(suite.run ?? "", selection.mode === "some" ? selection.files : []);
2119
+ const [program, ...args] = selection.mode === "some" ? commandFor(suite.run ?? "", selection.files) : suite.runAll !== undefined ? commandFor(suite.runAll, []) : commandFor(suite.run ?? "", suite.roots.filter((root) => root !== "."));
1812
2120
  if (program === undefined) {
1813
2121
  throw usageError("BV_NO_RUN_COMMAND", `bivium run: suite "${suite.name}" has no run command: add suites.${suite.name}.run to the config`);
1814
2122
  }
2123
+ if (human) {
2124
+ const files = selection.mode === "some" ? selection.files.length : 0;
2125
+ const bare = commandFor(suite.run ?? "", []);
2126
+ console.log(`${out.paint.dim(shownCommand([program, ...args], bare, files))}
2127
+ `);
2128
+ }
2129
+ const started = nowMs();
1815
2130
  const result = spawnSync(program, args, { cwd: root, stdio: "inherit" });
1816
- return result.status ?? 1;
2131
+ const interrupted = result.signal === "SIGINT";
2132
+ const status = interrupted ? 130 : result.status ?? 1;
2133
+ if (human) {
2134
+ const took = duration(nowMs() - started);
2135
+ const name = suite.name;
2136
+ console.log(`
2137
+ ${interrupted ? failLine(out.paint, `${name} interrupted`, took) : status === 0 ? closingLine(out.paint, `${name} passed`, took) : failLine(out.paint, `${name} failed`, `${result.signal ?? `exit ${status}`}${SEPARATOR}${took}`)}`);
2138
+ }
2139
+ return status;
2140
+ }
2141
+ function shownCommand(whole, bare, files) {
2142
+ const line = `$ ${whole.join(" ")}`;
2143
+ if (textWidth(line) <= MEASURE)
2144
+ return line;
2145
+ return `$ ${bare.join(" ")} ${SEPARATOR.trim()} ${plural(files, "file")}, as bivium plan --list names them`;
2146
+ }
2147
+ async function showRun(out, base, config, computed, name, others) {
2148
+ const { paint } = out;
2149
+ const selection = computed.plan.suites[name];
2150
+ const total = computed.plan.totals[name] ?? 0;
2151
+ const used = new Set;
2152
+ const verdict = selection === undefined ? `no ${name} tests` : verdictOf(name, selection, total, computed, used, paint);
2153
+ const mergeBase = (await computed.mergeBase()).slice(0, 7);
2154
+ const context = [
2155
+ `since ${base} (merge base ${mergeBase})`,
2156
+ ...config.file ? [`config ${config.file}`] : []
2157
+ ].join(SEPARATOR);
2158
+ const lines = [verdict, paint.dim(context)];
2159
+ if (others.length > 0) {
2160
+ lines.push(paint.dim(`running ${name}${SEPARATOR}${plural(others.length, "more suite")}: ${others.join(", ")}`));
2161
+ }
2162
+ console.log(lines.join(`
2163
+ `));
1817
2164
  }
1818
2165
  function commandAt(argv) {
1819
2166
  for (let i = 0;i < argv.length; i++) {
@@ -1839,9 +2186,10 @@ function fail(argv, error) {
1839
2186
  }
1840
2187
  return 2;
1841
2188
  }
1842
- async function main(argv) {
2189
+ async function main(argv, io = PIPED) {
2190
+ const out = outFor(io, argv, nowMs());
1843
2191
  if (argv.includes("--help") || argv.includes("-h")) {
1844
- console.log(USAGE);
2192
+ console.log(usage(out.paint));
1845
2193
  return 0;
1846
2194
  }
1847
2195
  if (argv.includes("--version") || argv.includes("-v")) {
@@ -1851,23 +2199,23 @@ async function main(argv) {
1851
2199
  const at = commandAt(argv);
1852
2200
  const command = at === -1 ? undefined : argv[at];
1853
2201
  if (command === "help") {
1854
- console.log(USAGE);
2202
+ console.log(usage(out.paint));
1855
2203
  return 0;
1856
2204
  }
1857
2205
  if (command === undefined) {
1858
2206
  return fail(argv, usageError("BV_MISSING_ARGUMENT", `bivium: which command? ${COMMANDS.join(", ")} (bivium --help for usage)`));
1859
2207
  }
1860
2208
  if (!(command in FLAGS)) {
1861
- return fail(argv, usageError("BV_UNKNOWN_COMMAND", `bivium: unknown command "${command}"${didYouMean(command, COMMANDS)}; the commands are ${COMMANDS.join(", ")} (bivium --help for usage)`));
2209
+ return fail(argv, usageError("BV_UNKNOWN_COMMAND", `bivium: unknown command "${command}"${didYouMean2(command, COMMANDS)}; the commands are ${COMMANDS.join(", ")} (bivium --help for usage)`));
1862
2210
  }
1863
2211
  const rest = [...argv.slice(0, at), ...argv.slice(at + 1)];
1864
2212
  try {
1865
2213
  const args = parseArgs(command, rest);
1866
2214
  if (command === "why" || command === "check")
1867
- return await inspect(command, args);
2215
+ return await inspect(command, args, out);
1868
2216
  if (command === "graph")
1869
2217
  return await graphCommand(args);
1870
- return await runCommand(command, args);
2218
+ return await runCommand(command, args, out);
1871
2219
  } catch (error) {
1872
2220
  if (error instanceof BiviumError2)
1873
2221
  return fail(argv, error);
@@ -1877,4 +2225,10 @@ async function main(argv) {
1877
2225
  }
1878
2226
 
1879
2227
  // src/cli.ts
1880
- process.exitCode = await main(process.argv.slice(2));
2228
+ var io = {
2229
+ stdout: process.stdout.isTTY === true,
2230
+ stderr: process.stderr.isTTY === true,
2231
+ env: environment(),
2232
+ writeError: (text) => process.stderr.write(text)
2233
+ };
2234
+ process.exitCode = await main(process.argv.slice(2), io);