bivium 0.2.1 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +124 -0
- package/README.md +94 -22
- package/cli.js +32 -12
- package/index.d.ts +83 -10
- package/index.js +1 -1
- package/package.json +1 -1
- package/shared-rdy8fmax.js +10 -0
- package/shared-2e64e78s.js +0 -9
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,129 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.1 — 2026-11-03
|
|
4
|
+
|
|
5
|
+
**Features**
|
|
6
|
+
|
|
7
|
+
- `bivium check` lists the files under a suite's `root` that no test
|
|
8
|
+
reaches and the config doesn't exempt: a change to any of them runs
|
|
9
|
+
the whole suite by the orphan rule. Each comes with a fix by what it
|
|
10
|
+
looks like (`reads` for a test's snapshot, `wiring` for a runner's
|
|
11
|
+
config, `nonInputs` otherwise), and `check --json` has them as
|
|
12
|
+
`unreached`. It's reported, not a failure (#48).
|
|
13
|
+
- A `urls` value can be a list: the page first, then what else it loads
|
|
14
|
+
that no import says, such as a router's layouts (`/about` →
|
|
15
|
+
`app/(marketing)/about/page.tsx`, `app/(marketing)/layout.tsx`,
|
|
16
|
+
`app/layout.tsx`). The page must exist; the rest are edges where they
|
|
17
|
+
do (#26).
|
|
18
|
+
- A file's `@depends-on`, or an `edges` key that names it, now also
|
|
19
|
+
covers its `goto()` calls whose URL bivium can't read, such as a loop
|
|
20
|
+
over a list of routes: list the pages they open, and the file is no
|
|
21
|
+
longer unknown (#27).
|
|
22
|
+
|
|
23
|
+
## 0.3.0 — 2026-11-02
|
|
24
|
+
|
|
25
|
+
**Breaking changes**
|
|
26
|
+
|
|
27
|
+
- A changed `ignore`d file the graph reads selects only the tests that
|
|
28
|
+
reach it through an edge. It no longer trips the orphan rule (with
|
|
29
|
+
the default `root`, any ignored change ran the whole suite), and no
|
|
30
|
+
longer selects the tests whose dependencies are unknown, so a
|
|
31
|
+
docs-only change selects `none` (#31, #32).
|
|
32
|
+
- A suite's `root`, and `roots`, with a wildcard is an error. Both take
|
|
33
|
+
paths, so `root: "components/**"` matched nothing and the orphan rule
|
|
34
|
+
quietly stopped for it (#21).
|
|
35
|
+
- A usage or configuration error (no command, an unknown command,
|
|
36
|
+
option or suite) exits 2. It exited 1, as `check` does when it finds
|
|
37
|
+
problems (#40).
|
|
38
|
+
- `plan`'s and `check`'s text output changed (see CLI).
|
|
39
|
+
|
|
40
|
+
**Features**
|
|
41
|
+
|
|
42
|
+
- `suites.<name>.types: false` says a suite runs code: a change that
|
|
43
|
+
reaches its tests only through `import type`, `export type … from`,
|
|
44
|
+
JSDoc types or declaration files selects none of them. The default
|
|
45
|
+
keeps today's selection, which a type-checking suite needs. `why`
|
|
46
|
+
labels these edges `type` (#38).
|
|
47
|
+
- `suites.<name>.setup` names the files a runner loads before every
|
|
48
|
+
test (`setupFiles`, `--require`, `globalSetup`): every test of the
|
|
49
|
+
suite depends on them and on what they import (#35).
|
|
50
|
+
- `// @lists <glob>` selects a test when a match is added, deleted or
|
|
51
|
+
renamed, not when one is edited, for a test that lists files without
|
|
52
|
+
reading them (#25).
|
|
53
|
+
- An `edges` key can name generated files git doesn't list, such as
|
|
54
|
+
`.velite/*`: an import that resolves under it, with an extension or
|
|
55
|
+
as an index, lands there instead of being unresolved (#20).
|
|
56
|
+
- A root `pnpm-lock.yaml` (v6 or v9) is diffed like `bun.lock`. Its
|
|
57
|
+
settings, overrides, catalogs, patches and pnpm's own version still
|
|
58
|
+
run everything, as does one bivium can't read (#34).
|
|
59
|
+
- `loadedByName` lists the packages a test may load other than by an
|
|
60
|
+
import (`jsdom`, `ts-jest`). Set, any other package without a `bin`
|
|
61
|
+
is import-only, so a lockfile bump that reaches one no test imports
|
|
62
|
+
selects only its importers (#23).
|
|
63
|
+
- `knownUnknowns` lists the unknown nodes `check` allows, each with a
|
|
64
|
+
reason, and `check` fails on one it doesn't list or an entry that's
|
|
65
|
+
no longer unknown (#24).
|
|
66
|
+
- `bivium graph` ranks each suite's files by how many tests a change to
|
|
67
|
+
one selects; `--json` exports the graph with each node's fan-in
|
|
68
|
+
(#36).
|
|
69
|
+
|
|
70
|
+
**CLI**
|
|
71
|
+
|
|
72
|
+
- Options can come before the command, and `--help` or `-h` anywhere
|
|
73
|
+
prints usage and exits 0.
|
|
74
|
+
- `plan` prints each selection's scale (`unit tests: 3 of 822 files`)
|
|
75
|
+
and tells a full run (`all (full run)`) from every test reaching a
|
|
76
|
+
change. `plan --json` and `plan()` add `totals`, and `causes`, each
|
|
77
|
+
reason as data.
|
|
78
|
+
- `check` leads with counts by cause, and a fix for an unresolved
|
|
79
|
+
specifier names the file that's there: a sibling with another
|
|
80
|
+
extension, a file outside `roots`, or one git ignores.
|
|
81
|
+
- `why --format json` is `why --json` (#40).
|
|
82
|
+
|
|
83
|
+
**Performance**
|
|
84
|
+
|
|
85
|
+
- The walk tests each distinct pattern (`edges`, `@depends-on`,
|
|
86
|
+
`import.meta.glob`, `reads`) once per node it visits, however many
|
|
87
|
+
files declare it. With 4,000 tests and
|
|
88
|
+
`{ "tests/*.test.ts": "src/setup.ts" }`, a plan took 0.81 s, and now
|
|
89
|
+
0.08 s (#39).
|
|
90
|
+
- A plan that reads files holds only what it extracted from each, not
|
|
91
|
+
the file's text, and reads 64 at a time. A cold plan of 7,000 files
|
|
92
|
+
needs a 20 MB heap on Node instead of over 64 MB, and peaks at 124 MB
|
|
93
|
+
of RSS instead of 285 MB (Bun: 88 MB instead of 115 MB) (#42).
|
|
94
|
+
- The orphan rule's walk from each changed file stops at the first test
|
|
95
|
+
or page it reaches, as does the lockfile check for a package a test
|
|
96
|
+
imports: with 350 changes in 5,900 files, the selection step took
|
|
97
|
+
21.7 ms and now 8.1 ms.
|
|
98
|
+
|
|
99
|
+
**Fixes**
|
|
100
|
+
|
|
101
|
+
- An `alias` key that ends in `/` (`{ "@/": "src/" }`, as Vite
|
|
102
|
+
configs spell it) matches the specifiers that start with it. It
|
|
103
|
+
matched none (#29).
|
|
104
|
+
- A missing `x.js` resolves to `x.tsx` and `x.d.ts` as well as `x.ts`
|
|
105
|
+
(and the `.mjs` and `.cjs` variants), through `exports` and `imports`
|
|
106
|
+
targets too, so `@acme/ui/Button.js` reaches
|
|
107
|
+
`packages/ui/src/Button.ts`. A value import that finds only `x.d.ts`
|
|
108
|
+
is unknown: what runs isn't in the graph (#28).
|
|
109
|
+
- A doubled slash in a specifier resolves through `alias` and tsconfig
|
|
110
|
+
`paths` (#33).
|
|
111
|
+
- A specifier that starts with a dot but not `./` or `../` (`.velite`)
|
|
112
|
+
is bare, as TypeScript reads it (#20).
|
|
113
|
+
- An `edges` or `reads` key that names one file declares what it reads
|
|
114
|
+
from disk, as `@depends-on` and `@reads` do (#22).
|
|
115
|
+
- The lexer reads a JSX element with type arguments in `.tsx`
|
|
116
|
+
(`<List<string> />`) instead of falling back to the regex extractor
|
|
117
|
+
(#30).
|
|
118
|
+
- A type import from `fs` doesn't count as reading the disk, and
|
|
119
|
+
`check` lists an unresolved specifier once per file.
|
|
120
|
+
|
|
121
|
+
**Docs**
|
|
122
|
+
|
|
123
|
+
- The README has one table for what to do with a changed file no test
|
|
124
|
+
reaches, recipes for Vitest and Jest, pnpm workspaces, Playwright
|
|
125
|
+
and generated code, and what a plan costs in CI (#41).
|
|
126
|
+
|
|
3
127
|
## 0.2.1 — 2026-10-28
|
|
4
128
|
|
|
5
129
|
**Performance**
|
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ export default defineConfig({
|
|
|
31
31
|
|
|
32
32
|
```console
|
|
33
33
|
$ bunx bivium plan
|
|
34
|
-
unit tests: 3 files
|
|
34
|
+
unit tests: 3 of 12 files
|
|
35
35
|
tests/Button.test.ts
|
|
36
36
|
tests/Modal.test.ts
|
|
37
37
|
tests/css/unknown.test.ts
|
|
@@ -45,7 +45,7 @@ A one-pass lexer reads JavaScript and TypeScript (`.js`, `.ts`, `.jsx`, `.tsx`,
|
|
|
45
45
|
|
|
46
46
|
| It follows | As |
|
|
47
47
|
|:---|:---|
|
|
48
|
-
| Static, side-effect and dynamic imports, `export … from`, `require()` | Edges to every file the specifier can load: each extension that exists, each `exports` condition |
|
|
48
|
+
| Static, side-effect and dynamic imports, `export … from`, `require()` | Edges to every file the specifier can load: each extension that exists, each `exports` condition. A missing `x.js` (`.jsx`, `.mjs`, `.cjs`) is its TypeScript source, as TypeScript reads it: `x.ts`, `x.tsx` or `x.d.ts`, through any path, alias or `exports` target. A value import that finds only `x.d.ts` is unknown: what runs isn't in the graph |
|
|
49
49
|
| `vi.mock()`, `vi.importActual()` and the rest of the family | Edges |
|
|
50
50
|
| `import.meta.glob()` | Every matching file, now and later |
|
|
51
51
|
| JSDoc `@type {import("x")}` and `@import` | Edges (TypeScript reads them) |
|
|
@@ -57,7 +57,7 @@ A one-pass lexer reads JavaScript and TypeScript (`.js`, `.ts`, `.jsx`, `.tsx`,
|
|
|
57
57
|
| A file's own package and its ancestors' `package.json` dependencies, and builtins | `pkg:` nodes |
|
|
58
58
|
| Anything else | Unknown: the file depends on every change |
|
|
59
59
|
|
|
60
|
-
A root `bun.lock` or `
|
|
60
|
+
A root `bun.lock`, `package-lock.json` or `pnpm-lock.yaml` isn't a source file: a change to one seeds the packages it changed (see [Lockfiles](#lockfiles)).
|
|
61
61
|
|
|
62
62
|
A file it can't lex cleanly is read by a regex extractor instead, which over-approximates. CSS isn't scanned: generated stylesheets reach their inputs through `edges`, and a [narrower](#narrowers) can do better.
|
|
63
63
|
|
|
@@ -69,40 +69,101 @@ A file it can't lex cleanly is read by a regex extractor instead, which over-app
|
|
|
69
69
|
|:---|:---|
|
|
70
70
|
| `suites.<name>.tests` | The suite's test files |
|
|
71
71
|
| `suites.<name>.run` | The command `bivium run` runs. `{files}` is replaced by the selection (nothing for `all`); without it, the files are appended |
|
|
72
|
-
| `suites.<name>.root` | Where the orphan rule applies: a changed file here that no test of the suite reaches is wired some other way (a setup file, a runner config), so the whole suite runs. Default: the whole repository |
|
|
73
|
-
| `suites.<name>.urls` | URL pattern → file pattern, for `page.goto()` calls under `root` |
|
|
72
|
+
| `suites.<name>.root` | Where the orphan rule applies: a changed file here that no test of the suite reaches is wired some other way (a setup file, a runner config), so the whole suite runs. Paths, not globs (`e2e`, not `e2e/**`): a glob is an error. Default: the whole repository |
|
|
73
|
+
| `suites.<name>.urls` | URL pattern → file pattern, for `page.goto()` calls under `root`. A list names the page first, then what else it loads that no import says, such as a router's layouts: `{ "/*": ["app/(site)/*/page.tsx", "app/(site)/layout.tsx", "app/layout.tsx"] }`. The page must exist; the rest are edges where they do |
|
|
74
74
|
| `suites.<name>.pages` | Pages only a `goto()` opens; files only they load are wired to no test |
|
|
75
|
+
| `suites.<name>.setup` | Files the runner loads before every test (Vitest and Jest `setupFiles`, Mocha `--require`, Playwright `globalSetup`): every test of the suite depends on them and what they import. bivium doesn't read the runner's config, so name them here |
|
|
75
76
|
| `suites.<name>.wiring` | Files whose change runs the whole suite: another harness, a runner config |
|
|
76
77
|
| `suites.<name>.nonInputs` | Files under `root` the runner never reads, such as type-check inputs |
|
|
78
|
+
| `suites.<name>.types` | `false` when the suite runs code and can't observe types (Vitest, Jest, Playwright, `bun test`): a change that reaches its tests only through `import type`, `export type … from`, JSDoc types or a declaration file selects none of them. For the orphan rule a type-only reach counts only for a declaration file, since the runner may load any other file by name: list a types-only module under `root` in `nonInputs`. Default: `true`, which a type-checking suite (`tsc`, `vitest --typecheck`) needs. An inline `import { type A }` is always an edge: under `verbatimModuleSyntax` it still loads the module |
|
|
77
79
|
| `suites.<name>.output` | The step output `plan --github` writes. Default: `<name>-tests` |
|
|
78
|
-
| `roots` | Paths the graph reads. A changed file outside them that isn't ignored runs everything. Default: the whole repository |
|
|
79
|
-
| `ignore` | Files no test can observe. A
|
|
80
|
-
| `alias` | Specifier prefix → path, as the bundler aliases it. Tried before tsconfig `paths` and `package.json` `exports` |
|
|
81
|
-
| `edges` | Generated file glob → its inputs, which it depends on transitively, as with `@depends-on`: `{ "dist/*.css": "styles/**" }`. In a value, `$1`, `$2`… are what the key's wildcards matched, counted from the left: `{ "examples/*/package.json": "examples/$1/**" }` |
|
|
82
|
-
| `reads` | File glob → the files it reads as text, as with `@reads`: only a direct change to one counts, so their imports and unknowns don't spread to it. Values take `$1`… as in `edges`: `{ "tests/*.test.ts": "tests/__snapshots__/$1.test.ts.snap" }` |
|
|
80
|
+
| `roots` | Paths (not globs) the graph reads. A changed file outside them that isn't ignored runs everything. Default: the whole repository |
|
|
81
|
+
| `ignore` | Files no test can observe except through an edge (docs, stories). A change to one selects only the tests that reach it, never runs a suite by the orphan rule, and doesn't select the tests whose dependencies are unknown |
|
|
82
|
+
| `alias` | Specifier prefix → path, as the bundler aliases it. Tried before tsconfig `paths` and `package.json` `exports`. A key ending in `/` is the prefix, as Vite reads it: `{ "@/": "src/" }` maps `@/x` to `src/x` |
|
|
83
|
+
| `edges` | Generated file glob → its inputs, which it depends on transitively, as with `@depends-on`: `{ "dist/*.css": "styles/**" }`. A key may name files git doesn't list, such as a gitignored generator output (`{ ".velite/*": "content/**" }`): an import that resolves under it, by extension or as an index, lands on that file instead of being unresolved. In a value, `$1`, `$2`… are what the key's wildcards matched, counted from the left: `{ "examples/*/package.json": "examples/$1/**" }` |
|
|
84
|
+
| `reads` | File glob → the files it reads as text, as with `@reads`: only a direct change to one counts, so their imports and unknowns don't spread to it. An `edges` or `reads` key that names one file (no wildcard) declares what it reads, as its own `@depends-on` or `@reads` would, so its disk reads aren't unknown. Values take `$1`… as in `edges`: `{ "tests/*.test.ts": "tests/__snapshots__/$1.test.ts.snap" }` |
|
|
83
85
|
| `self` | The selector's own files: a change to one runs everything. The config file is always one |
|
|
84
86
|
| `importOnly` | Files only an import reaches: deleting one never orphans a suite |
|
|
85
87
|
| `hermetic` | Files whose disk reads and non-literal imports reach no file of the repository: a library's `fs` calls on its caller's paths, a test that reads only the temporary files it writes. They add no unknown |
|
|
86
88
|
| `barrels` | Modules that may bind named imports. Default: every module made only of re-exports |
|
|
87
89
|
| `external` | Packages a dependency installs that your code imports without declaring |
|
|
88
|
-
| `inert` | Packages no test uses except by importing them: linters, formatters, type packages (`["@biomejs/biome", "knip", "@types/*"]`). A [lockfile change](#lockfiles) that only they reach selects nothing |
|
|
90
|
+
| `inert` | Packages no test uses except by importing them: linters, formatters, type packages (`["@biomejs/biome", "knip", "@types/*"]`). A [lockfile change](#lockfiles) that only they reach selects nothing. With `loadedByName` set, only packages with a `bin` need listing |
|
|
91
|
+
| `loadedByName` | Packages a test may load other than by an import: a test environment or a plugin a config names by string (`["jsdom", "ts-jest"]`). Setting it, even to `[]`, says every other package without a `bin` is loaded only by imports, so a [lockfile change](#lockfiles) that reaches one no test imports selects only its importers. A package with a `bin` always counts as one a test may run |
|
|
89
92
|
| `extensions` | Suffixes tried after a specifier |
|
|
90
93
|
| `deadGlobs` | Dead globs `check` allows, each `{ file, glob, reason }`, the glob as `file` spells it |
|
|
94
|
+
| `knownUnknowns` | Nodes `check` allows to have unknown dependencies, each `{ file, reason }`. With it set, even to `[]` (which is `--max-unknown 0`), `check` fails on an unknown node some test reaches that it doesn't list, and on an entry that's no longer unknown, so a new unknown can't replace one that went away |
|
|
91
95
|
| `narrowers` | See [Narrowers](#narrowers) |
|
|
92
96
|
| `base` | The default base ref. Otherwise the upstream default branch (`origin/HEAD`, then `origin/main`, `origin/master`, `main`, `master`) |
|
|
93
97
|
| `cache` | The cache's directory, or `false`. Default: `node_modules/.cache/bivium`, or `.bivium/cache` |
|
|
94
98
|
|
|
99
|
+
## A change no test reaches
|
|
100
|
+
|
|
101
|
+
A changed file under a suite's `root` that no test of the suite reaches is wired some other way (a runner config, a setup file), so the whole suite runs: the orphan rule. With the default `root`, the whole repository, any file bivium can't trace to a test runs the suite, which is sound and coarse. Set `root` on every suite to the directories its tests and sources live in, and say what the rest is:
|
|
102
|
+
|
|
103
|
+
| You changed… | and want… | Use |
|
|
104
|
+
|:---|:---|:---|
|
|
105
|
+
| a file no test can observe: docs, stories, a changelog | nothing to run, unless some test imports it | `ignore` |
|
|
106
|
+
| a file under the suite's `root` only another tool reads: type-check inputs | nothing to run for this suite | the suite's `nonInputs` |
|
|
107
|
+
| a runner config or a second harness | the whole suite | the suite's `wiring` |
|
|
108
|
+
| a setup file the runner loads before every test, or what it imports | every test of the suite | the suite's `setup` |
|
|
109
|
+
| the selector's config, or its own code | everything | `self` (the config file always is) |
|
|
110
|
+
| a declaration file, in a suite that runs code | nothing | the suite's `types: false` |
|
|
111
|
+
| a types-only module only `import type` reaches, in a suite that runs code | nothing | the suite's `types: false`, and the module in its `nonInputs` |
|
|
112
|
+
| a file a test lists but doesn't read (a route, a story) | the test, when one is added or deleted | `// @lists <glob>` in the test |
|
|
113
|
+
| a file a build turns into what tests load | the tests that load the output | `edges` from the output to its inputs |
|
|
114
|
+
|
|
115
|
+
A file outside `roots` that isn't ignored runs everything: it's the backstop for wiring the graph can't see, such as a CI workflow.
|
|
116
|
+
|
|
117
|
+
`bivium check` lists every file under a suite's `root` that no test reaches and the config doesn't exempt, with a fix for each by what it looks like: a test's snapshot, a runner's config, or anything else. It's the list to work through when adopting bivium, and a new entry is a gap someone just added.
|
|
118
|
+
|
|
119
|
+
## Recipes
|
|
120
|
+
|
|
121
|
+
**Vitest or Jest.** Name the setup files the runner loads, mirror `resolve.alias` (a Vite key like `"@/"` works as written), give snapshots to their tests, and, for a suite that runs code, skip type-only edges:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
suites: {
|
|
125
|
+
unit: {
|
|
126
|
+
tests: "src/**/*.test.{ts,tsx}",
|
|
127
|
+
run: "vitest run {files}",
|
|
128
|
+
root: "src",
|
|
129
|
+
setup: ["src/setupTests.ts"], // vitest.config.ts `setupFiles`
|
|
130
|
+
wiring: ["vitest.config.ts"],
|
|
131
|
+
types: false,
|
|
132
|
+
nonInputs: ["src/**/types.ts"], // types only: nothing loads them at runtime
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
alias: { "@/": "src/" },
|
|
136
|
+
reads: { "src/**/*.test.{ts,tsx}": "src/$1__snapshots__/$2.test.$3.snap" },
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
tsconfig `paths` (what `vite-tsconfig-paths` reads) are read without an `alias`. An extensionless `vi.mock("@/x")` resolves as an import does. A test environment the runner loads by name (`jsdom`, `happy-dom`) goes in `loadedByName` if you set it.
|
|
140
|
+
|
|
141
|
+
**pnpm workspaces.** Workspace packages resolve through their `package.json` `exports`, and a `.js` specifier into one (`@acme/ui/Button.js`) reaches its `.ts` source. A `pnpm-lock.yaml` change selects through the packages it changed. Set `roots` to the packages and apps whose changes the suites should see, and a suite per test runner.
|
|
142
|
+
|
|
143
|
+
**Playwright.** Map `page.goto()` URLs to the pages they open with `urls`, list pages only a `goto()` opens in `pages`, and name `playwright.config.ts` in `wiring`:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
e2e: {
|
|
147
|
+
tests: "e2e/**/*.spec.ts",
|
|
148
|
+
root: "e2e",
|
|
149
|
+
urls: { "/*": "e2e/fixtures/*.html" },
|
|
150
|
+
wiring: ["playwright.config.ts"],
|
|
151
|
+
},
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
**Generated code.** A content or type generator that writes into a gitignored directory (`.velite`, `.contentlayer/generated`) is an `edges` entry from what it writes to what it reads: `{ ".velite/*": ["content/**", "velite.config.ts"] }`. An import of `#velite` or `../.velite` then reaches the content, and not every change.
|
|
155
|
+
|
|
95
156
|
## Lockfiles
|
|
96
157
|
|
|
97
|
-
A dependency bump changes a lockfile, which no file imports. When a root `bun.lock
|
|
158
|
+
A dependency bump changes a lockfile, which no file imports. When a root `bun.lock`, `package-lock.json` (v2 or v3) or `pnpm-lock.yaml` (v6 or v9) changes, bivium diffs it against the merge base and seeds the walk with the `pkg:` nodes of the packages whose entries changed, and of every package that depends on one, so a `svelte` bump selects what imports `svelte`, or a package built on it. A `package.json` whose only change is to dependencies the lockfile records the same way counts as those packages changing.
|
|
98
159
|
|
|
99
|
-
A changed package can also be used in ways the graph can't see: a CLI a test spawns, a runner, a type package. So when a change reaches a package that a `package.json` declares, or that some file imports, and that no test imports, everything runs, with the reason (`bun.lock: playwright 1.63.0 → 1.64.0, and no test imports it`), unless the package is `inert`. Everything also runs for a lockfile bivium can't parse, one whose settings other than its packages changed (`overrides`, patches), and a `package.json` change the lockfile doesn't record. Other lockfiles (`
|
|
160
|
+
A changed package can also be used in ways the graph can't see: a CLI a test spawns, a runner, a type package. So when a change reaches a package that a `package.json` declares, or that some file imports, and that no test imports, everything runs, with the reason (`bun.lock: playwright 1.63.0 → 1.64.0, and no test imports it`), unless the package is `inert`. With `loadedByName` set, only a package with a `bin` in the lockfile, or one it lists, counts as used that way: a bump that reaches a library only a CMS config imports selects nothing. Everything also runs for a lockfile bivium can't parse, one whose settings other than its packages changed (`overrides`, patches, pnpm's `settings`, `catalogs`, or the version of pnpm itself), and a `package.json` change the lockfile doesn't record. Other lockfiles (`yarn.lock`, `bun.lockb`) are files like any other: outside the roots, a change to one runs everything.
|
|
100
161
|
|
|
101
162
|
```console
|
|
102
163
|
$ bunx bivium plan
|
|
103
164
|
bun.lock: @biomejs/biome 2.5.14 → 2.6.3, inert
|
|
104
165
|
bun.lock: svelte 5.57.1 → 5.57.2
|
|
105
|
-
unit tests: 4 files
|
|
166
|
+
unit tests: 4 of 12 files
|
|
106
167
|
…
|
|
107
168
|
```
|
|
108
169
|
|
|
@@ -110,22 +171,24 @@ unit tests: 4 files
|
|
|
110
171
|
|
|
111
172
|
| Comment | Meaning |
|
|
112
173
|
|:---|:---|
|
|
113
|
-
| `// @depends-on <glob> [glob…]` | Inputs that aren't imports: files a script reads, a tool it spawns. Transitive. A file that reads the disk without one is unknown, unless it's `hermetic` |
|
|
174
|
+
| `// @depends-on <glob> [glob…]` | Inputs that aren't imports: files a script reads, a tool it spawns, the pages a `goto()` the graph can't read opens (a loop over a list of URLs). Transitive. A file that reads the disk without one (or `@reads`, or `@lists`), or calls `goto()` with a URL it can't read, is unknown, unless it's `hermetic` |
|
|
114
175
|
| `// @reads <glob> [glob…]` | Files read as text. Only a direct change to one counts, not a change to what it imports. The config's `reads` says the same for files that can't hold a comment |
|
|
176
|
+
| `// @lists <glob> [glob…]` | Files whose names it lists, not their contents: a convention test that checks every route has a handler. Only adding, deleting or renaming one counts; an edit doesn't select it, and doesn't run its suite by the orphan rule either |
|
|
115
177
|
| `// @glob-registry` | This file's `import.meta.glob` is a lookup table and adds no edges: whatever loads an entry names it itself |
|
|
116
178
|
|
|
117
179
|
## CLI
|
|
118
180
|
|
|
119
181
|
| Command | Does |
|
|
120
182
|
|:---|:---|
|
|
121
|
-
| `bivium plan [base] [--json] [--github]` | Prints each suite's selection
|
|
183
|
+
| `bivium plan [base] [--json] [--github]` | Prints each suite's selection (`none`, the files out of how many, `all` files when each reaches a change, or `all (full run)`) and why a suite runs in full. `--json` adds the base, merge base, changed files, narrower results, changed packages, each suite's test count (`totals`), and the reasons as data (`causes`, each a `FullRunCause`: `{ kind, suites, file?, package?, narrower?, message }`). `--github` also writes each suite's selection to `$GITHUB_OUTPUT` |
|
|
122
184
|
| `bivium run [base] [--suite <name>]` | Runs the suite's `run` command with its selection (default: the first suite), or skips it when nothing is affected |
|
|
123
|
-
| `bivium why <test> [file] [--format tree\|chain\|source] [--all]` | The shortest chain of edges from a changed file, or from `file`, to the test, with what spells each edge and the line it's on, and how many other changes reach the test. `--format tree` (the default) draws it from the test; `chain` reads from the change to the test; `source` prints each hop's line of source. `--all` shows every change's chain. For a test that isn't selected, it says what the file's chains reach instead |
|
|
124
|
-
| `bivium check [--max-unknown <n>]` |
|
|
185
|
+
| `bivium why <test> [file] [--format tree\|chain\|source\|json] [--all]` | The shortest chain of edges from a changed file, or from `file`, to the test, with what spells each edge and the line it's on, and how many other changes reach the test. `--format tree` (the default) draws it from the test; `chain` reads from the change to the test; `source` prints each hop's line of source; `json` (or `--json`) prints the chain as data. `--all` shows every change's chain. For a test that isn't selected, it says what the file's chains reach instead |
|
|
186
|
+
| `bivium check [--max-unknown <n>] [--json]` | Counts what it found by cause first, then lists every node with unknown dependencies, with where and how to fix each cause, and fails when more than `n` of them reach a test, or on one `knownUnknowns` doesn't list. A node no test depends on is listed apart and not counted: plans only run tests, so it widens nothing. Also lists the files under a suite's `root` that no test reaches, each with a fix (a change to one runs the whole suite; see [A change no test reaches](#a-change-no-test-reaches)), `tsconfig.json` files that don't parse, and [dead globs](#dead-globs), and fails on one `deadGlobs` doesn't allow or on an entry that matches none. `--json` prints the report as data |
|
|
187
|
+
| `bivium graph [--suite <name>] [--top <n>] [--json]` | How many of each suite's tests a change to each file selects through the graph (leaving out the tests that run on any change, which it counts apart): the `n` files that reach the most, and how files spread from none to every test. A few hub files that reach most tests are what make plans wide. `--json` prints each suite's `total` and `everyChange` tests, and every node with its `imports` and `importers` (file edges), `fanIn` per suite and whether it's `unknown` |
|
|
125
188
|
|
|
126
|
-
`--config`, `--cwd` and `--no-cache` work with every command, and `why` and `check` take `--base <ref>`. An unknown
|
|
189
|
+
`--config`, `--cwd` and `--no-cache` work with every command, before or after it, and `why` and `check` take `--base <ref>`. `--help` (or `-h`) prints usage. An unknown command, option or `--format` is an error. Exit status: 0 when done, 1 when `check` finds problems, 2 for a usage or configuration error; `run` exits with its command's status.
|
|
127
190
|
|
|
128
|
-
`why` names each edge by what spells it: `import`, `goto` (a page `page.goto()` opens), `html` (a module an HTML page loads: `script[src]`, `link[href]`, `iframe[src]` or an inline script's import), `name` (a named import bound to a barrel name) and `export` (the file that exports it), `glob` (`import.meta.glob`), `depends-on`, `edges` (the config's) and `
|
|
191
|
+
`why` names each edge by what spells it: `import`, `type` (an `import type`, `export type … from`, JSDoc type, or an edge to or from a declaration file), `setup` (a suite's setup file), `goto` (a page `page.goto()` opens), `html` (a module an HTML page loads: `script[src]`, `link[href]`, `iframe[src]` or an inline script's import), `name` (a named import bound to a barrel name) and `export` (the file that exports it), `glob` (`import.meta.glob`), `depends-on`, `edges` (the config's), `reads` and `lists`.
|
|
129
192
|
|
|
130
193
|
```console
|
|
131
194
|
$ bunx bivium why e2e/accordion.test.ts
|
|
@@ -178,7 +241,7 @@ tests/e2e.test.ts runs on every change
|
|
|
178
241
|
|
|
179
242
|
## Dead globs
|
|
180
243
|
|
|
181
|
-
A typo'd `@depends-on`, or one pointing only at files the planner skips, looks fine and never selects its file. `check` evaluates every `@depends-on`, `@reads` and `import.meta.glob` pattern,
|
|
244
|
+
A typo'd `@depends-on`, or one pointing only at files the planner skips, looks fine and never selects its file. `check` evaluates every `@depends-on`, `@reads`, `@lists` and `import.meta.glob` pattern, every `edges` and `reads` value, and every suite's `setup`, against every file git lists (tracked and untracked, inside the roots or not) and reports one that:
|
|
182
245
|
|
|
183
246
|
| Problem | Means |
|
|
184
247
|
|:---|:---|
|
|
@@ -233,6 +296,15 @@ jobs:
|
|
|
233
296
|
|
|
234
297
|
The cache holds what bivium extracted from each file, keyed by git blob, so a warm plan reads only the files a branch changed. Key it on the merge base: a pull request can restore caches from the default branch, whose run at that commit is the one to hit. Without `node_modules`, the cache lives in `.bivium/cache`; it writes a `.gitignore` so it never shows up as a change.
|
|
235
298
|
|
|
299
|
+
What a plan costs, measured on an Apple M-series laptop under load (median of five, wall time):
|
|
300
|
+
|
|
301
|
+
| Repository | Files | Bun, no cache | Bun, warm | Node 24, no cache | Node 24, warm | Cache |
|
|
302
|
+
|:---|---:|---:|---:|---:|---:|---:|
|
|
303
|
+
| carbon-components-svelte | 4,680 | 0.15 s | 0.09 s | 0.27 s | 0.13 s | 452 KB |
|
|
304
|
+
| generated TypeScript, 23 MB | 7,000 | 0.14 s | 0.08 s | 0.30 s | 0.12 s | 896 KB |
|
|
305
|
+
|
|
306
|
+
So the cache is optional at this size, `bunx --bun` is worth it, and planning inside a test job (no extra job, no install) costs well under a second. A cold plan of the generated repository peaks at 88 MB of RSS on Bun and 124 MB on Node.
|
|
307
|
+
|
|
236
308
|
## Narrowers
|
|
237
309
|
|
|
238
310
|
Some changes reach every test through a generated file: every page loads the compiled stylesheet, so any style edit selects every e2e test. A narrower replaces such a change's coarse seeds with finer ones from a semantic diff, such as the sources that render a changed CSS rule.
|
|
@@ -265,7 +337,7 @@ const result = await plan({ config, base: "origin/main" });
|
|
|
265
337
|
result.suites.unit; // { mode: "some", files: [...] }; result.suites.e2e is a type error
|
|
266
338
|
```
|
|
267
339
|
|
|
268
|
-
`plan(options?)` takes `cwd`, `base`, `config` (default: the config file in `cwd`) and `cache`, and returns each suite's selection, the reasons, the packages a lockfile change seeded or found inert, the base, merge base and changed files, and what each narrower returned. Given a config, the suite names carry through to the result's type. The package exports only `plan`, `defineConfig` and their types.
|
|
340
|
+
`plan(options?)` takes `cwd`, `base`, `config` (default: the config file in `cwd`) and `cache`, and returns each suite's selection, its test count, the reasons as sentences and as data, the packages a lockfile change seeded or found inert, the base, merge base and changed files, and what each narrower returned. Given a config, the suite names carry through to the result's type. The package exports only `plan`, `defineConfig` and their types.
|
|
269
341
|
|
|
270
342
|
## Compared with
|
|
271
343
|
|
package/cli.js
CHANGED
|
@@ -1,42 +1,62 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{version,globToRegExp,sorted,createResolver,SCANNED,formatOf,extract,finish,gotoPage,affectedBy,formatSelection,computePlan,prepare}from"./shared-
|
|
2
|
+
import{version,globToRegExp,sorted,QUERY,UNDECLARED_READS,RELATIVE,aliasPath,createResolver,SCANNED,formatOf,extract,finish,gotoPage,walksByTypes,importersOf,affectedBy,formatSelection,orphanOf,computePlan,prepare}from"./shared-rdy8fmax.js";import{spawnSync}from"node:child_process";import{appendFileSync}from"node:fs";import{statSync}from"node:fs";import{join as join2,posix}from"node:path";function plural(count,one,many=`${one}s`){return`${count} ${count===1?one:many}`}function fanIn(graph,suite){let ids=new Map,nodes=[...graph.keys()];for(let[i,node]of nodes.entries())ids.set(node,i);let matches=new Map,matching=(re)=>{let found=matches.get(re.source);if(!found){found=[];for(let[i,node]of nodes.entries())if(re.test(node))found.push(i);matches.set(re.source,found)}return found},forward=[],direct=[];for(let node of nodes){let deps=graph.get(node),out=[],read=[];if(deps){for(let file of deps.files){if(!suite.types&&deps.types?.has(file))continue;let id=ids.get(file);if(id!==void 0)out.push(id)}for(let re of deps.patterns)out.push(...matching(re));for(let re of[...deps.reads,...deps.lists??[]])read.push(...matching(re))}forward.push(out),direct.push(read)}let counts=new Uint32Array(nodes.length),stamp=new Int32Array(nodes.length).fill(-1),stack=[];for(let[t,test]of nodes.entries()){if(!suite.isTest(test))continue;let reached=[],visit=(id)=>{if(stamp[id]===t)return;stamp[id]=t,reached.push(id)};visit(t),stack.push(t);while(stack.length>0){let at=stack.pop()??0;for(let next of forward[at]){if(stamp[next]===t)continue;visit(next),stack.push(next)}}for(let id of[...reached])for(let read of direct[id])visit(read);for(let id of reached)counts[id]++}let result=new Map;for(let[i,node]of nodes.entries())result.set(node,counts[i]);return result}function graphReport(graph,suites){let counts=suites.map((suite)=>[suite.name,fanIn(graph,suite)]),unknown=[...graph].filter(([,deps])=>deps.unknown.length>0).map(([node])=>node),everyChange=walksByTypes(graph,unknown,{includeUnknown:!1,readers:!1});return{suites:Object.fromEntries(suites.map((suite)=>[suite.name,{total:[...graph.keys()].filter(suite.isTest).length,everyChange:sorted(everyChange(suite.types)).filter(suite.isTest)}])),nodes:[...graph].map(([node,deps])=>({node,imports:sorted(deps.files),importers:sorted(importersOf(graph,node)),fanIn:Object.fromEntries(counts.map(([name,count])=>[name,count.get(node)??0])),unknown:deps.unknown.length>0}))}}function buckets(total){let list=[[0,0],[1,1]];for(let low=2,high=10;low<total;low=high+1,high*=10)list.push([low,Math.min(high,total-1)]);if(total>1)list.push([total,total]);return list}function formatGraph(report,top){let lines=[],files=report.nodes.filter(({node})=>!node.startsWith("pkg:")&&!node.includes("#"));for(let[name,{total:tests,everyChange}]of Object.entries(report.suites)){let any=everyChange.length;lines.push(`${name}: ${plural(tests,"test")}${any>0?`; ${any} run on any change (\`bivium check\` says why)`:""}`);let 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)),width=Math.max(String(tests).length,5);if(ranked.length>0){lines.push(` ${"tests".padStart(width)} file`);for(let[id,count]of ranked.slice(0,top))lines.push(` ${String(count).padStart(width)} ${id}`);if(ranked.length>top)lines.push(` … ${ranked.length-top} more (--top <n> shows more)`)}lines.push(` files by how many ${name} tests a change to one selects:`);let rows=buckets(tests).map(([low,high])=>{let label=low===high?String(low):`${low}–${high}`,count=files.filter(({fanIn:reach})=>{let n=reach[name]??0;return n>=low&&n<=high}).length;return[label,count]}),labelWidth=Math.max(...rows.map(([label])=>label.length));for(let[label,count]of rows)lines.push(` ${label.padStart(labelWidth)} ${count}`)}return lines.join(`
|
|
3
|
+
`)}import{readFile}from"node:fs/promises";import{isAbsolute,join}from"node:path";var DISK_READ=/\bfrom\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\brequire\s*\(\s*["'](?:node:)?(?:fs|fs\/promises|child_process)["']|\bBun\.(?:file|Glob|spawn)/,NON_LITERAL_IMPORT=/\b(?:import|require|vi\.(?:mock|doMock|unmock|importActual|importMock))\s*(?:<[^>]*>)?\(\s*(?!["'][^"'`$]*["']\s*[,)])/,GLOB_CALL=/\bimport\.meta\.glob/,QUOTED_CAUSE=/"([^"]+)"/,LOADS=/\b(?:import|export|from|require|mock|doMock|unmock|importActual|importMock)\b|\b(?:src|href)\s*=/,GOTO_CALL=/\bgoto\s*\(/;function lineAt(source,index){let line=1;for(let i=source.indexOf(`
|
|
3
4
|
`);i!==-1&&i<index;i=source.indexOf(`
|
|
4
5
|
`,i+1))line++;return line}function lineOf(source,needle){let index=typeof needle==="string"?source.indexOf(needle):source.search(needle);return index===-1?void 0:lineAt(source,index)}function commentRanges(source){let ranges=[];for(let i=0;i<source.length;i++){let c=source[i];if(c==='"'||c==="'"){while(++i<source.length&&source[i]!==c&&source[i]!==`
|
|
5
6
|
`)if(source[i]==="\\")i++}else if(c==="`"){while(++i<source.length&&source[i]!=="`")if(source[i]==="\\")i++}else if(source.startsWith("//",i)){let end=source.indexOf(`
|
|
6
7
|
`,i);ranges.push([i,end===-1?source.length:end]),i=end===-1?source.length:end}else if(source.startsWith("/*",i)||source.startsWith("<!--",i)){let close=c==="/"?"*/":"-->",end=source.indexOf(close,i+2),stop=end===-1?source.length:end+close.length;ranges.push([i,stop]),i=stop-1}}return ranges}function lineTextAt(source,index){let start=source.lastIndexOf(`
|
|
7
8
|
`,index-1)+1,end=source.indexOf(`
|
|
8
|
-
`,index);return source.slice(start,end===-1?source.length:end)}function bestLine(source,needles,near){let comments,inComment=(index)=>(comments??=commentRanges(source),comments.some(([start,end])=>index>=start&&index<end)),code,any;for(let needle of needles)for(let index=source.indexOf(needle);index!==-1;index=source.indexOf(needle,index+1)){if(any??=index,inComment(index))continue;if(near===void 0||near.test(lineTextAt(source,index)))return lineAt(source,index);code??=index}let found=code??any;return found===void 0?void 0:lineAt(source,found)}function specifierLine(source,specifier){let quoted=['"',"'","`"].map((quote)=>`${quote}${specifier}${quote}`);return bestLine(source,quoted,LOADS)??bestLine(source,[specifier])}function gotoLine(source,argument,page){return(argument===void 0?void 0:bestLine(source,[argument],GOTO_CALL))??bestLine(source,[page.slice(page.lastIndexOf("/")+1)],GOTO_CALL)}function callLine(source,call){return bestLine(source,[call])}function causeLine(source,cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED_CAUSE.exec(cause)?.[1];return specifier===void 0?void 0:specifierLine(source,specifier)}if(cause==="non-literal dynamic import")return lineOf(source,NON_LITERAL_IMPORT);if(cause==="non-literal glob import")return lineOf(source,GLOB_CALL);if(cause===
|
|
9
|
+
`,index);return source.slice(start,end===-1?source.length:end)}function bestLine(source,needles,near){let comments,inComment=(index)=>(comments??=commentRanges(source),comments.some(([start,end])=>index>=start&&index<end)),code,any;for(let needle of needles)for(let index=source.indexOf(needle);index!==-1;index=source.indexOf(needle,index+1)){if(any??=index,inComment(index))continue;if(near===void 0||near.test(lineTextAt(source,index)))return lineAt(source,index);code??=index}let found=code??any;return found===void 0?void 0:lineAt(source,found)}function specifierLine(source,specifier){let quoted=['"',"'","`"].map((quote)=>`${quote}${specifier}${quote}`);return bestLine(source,quoted,LOADS)??bestLine(source,[specifier])}function gotoLine(source,argument,page){return(argument===void 0?void 0:bestLine(source,[argument],GOTO_CALL))??bestLine(source,[page.slice(page.lastIndexOf("/")+1)],GOTO_CALL)}function callLine(source,call){return bestLine(source,[call])}function causeLine(source,cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED_CAUSE.exec(cause)?.[1];return specifier===void 0?void 0:specifierLine(source,specifier)}if(cause==="non-literal dynamic import")return lineOf(source,NON_LITERAL_IMPORT);if(cause==="non-literal glob import")return lineOf(source,GLOB_CALL);if(cause===UNDECLARED_READS)return lineOf(source,DISK_READ);if(cause.startsWith("non-literal goto("))return lineOf(source,cause.slice(12,-1));let url=QUOTED_CAUSE.exec(cause)?.[1];return url===void 0?void 0:lineOf(source,url)}function textLine(source,text){return lineOf(source,text)}function annotationLine(source,tag,glob){let index=source.split(`
|
|
9
10
|
`).findIndex((line)=>line.includes(tag)&&line.includes(glob));return index===-1?void 0:index+1}function lineText(source,line){let start=0;for(let n=1;n<line;n++){let next=source.indexOf(`
|
|
10
11
|
`,start);if(next===-1)return"";start=next+1}let end=source.indexOf(`
|
|
11
|
-
`,start);return source.slice(start,end===-1?source.length:end).trim()}async function sourceOf(root,file){try{return await readFile(isAbsolute(file)?file:join(root,file),"utf-8")}catch{return}}function fileOf(node){let hash=node.indexOf("#");return hash===-1?node:node.slice(0,hash)}async function causesOf(root,computed,node){let file=fileOf(node),source=await sourceOf(root,file);return(computed.graph.get(node)?.unknown??[]).map((cause)=>{if(source===void 0)return{cause};let line=causeLine(source,cause);return line===void 0?{cause}:{cause,at:`${file}:${line}`,text:lineText(source,line)}})}var EXAMPLES=3,TAGS={"depends-on":"@depends-on",reads:"@reads",glob:"import.meta.glob",edges:"edges"},QUOTED=/"([^"]+)"/;function fixFor(cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED.exec(cause)?.[1]??"";if(specifier.startsWith("./%sveltekit.assets%/"))return"no file in the SvelteKit project's `static/` (a custom `kit.files.assets` isn't read): fix the path, or add an `edges` entry for it";if(specifier.startsWith("."))return"no file at that path: fix the import, or add an `edges` entry if a build generates it";if(specifier.startsWith("#"))return"map it in the `imports` of the file's package.json, or with `alias`";return"declare the package in a package.json, list it in `external` if a dependency installs it, or map it with `alias` or tsconfig `paths`"}if(cause==="non-literal dynamic import")return"spell the path as a string literal, load the files with `import.meta.glob` and literal patterns, or list the file in `hermetic` if it only imports paths its caller passes";if(cause==="non-literal glob import")return"pass `import.meta.glob` literal patterns";if(cause==="reads the disk without @depends-on")return"name what it reads: `// @depends-on <glob>`, or `// @reads <glob>` for files read as text; list the file in `hermetic` if it reads no file of the repository";if(cause.startsWith("non-literal goto("))return"pass `goto()` a literal URL, or a template whose path before `?` or `#` is literal";if(cause.startsWith("missing fixture "))return"no page at that URL: fix the URL, or the suite's `urls`";if(cause.startsWith("goto("))return"map the URL to a file with the suite's `urls`";return"see the cause"}function declaredGlobs(node,extraction){let relative=finish(node,extraction).globs;return[...extraction.dependsOn.map((glob)=>({kind:"depends-on",glob,pattern:globToRegExp(glob)})),...extraction.reads.map((glob)=>({kind:"reads",glob,pattern:globToRegExp(glob)})),...extraction.globs.map((glob,i)=>({kind:"glob",glob,pattern:globToRegExp(relative[i])}))]}function problemOf(matches,ignored){if(matches===0)return"matches nothing";if(ignored===0)return;return ignored===matches?"matches only ignored files":"partly ignored"}function deadOf(node,kind,glob,patterns,listed,skipped){let matches=listed.filter((file)=>patterns.some((re)=>re.test(file))),ignored=sorted(matches.filter(skipped)),problem=problemOf(matches.length,ignored.length);if(problem===void 0)return;return{node,kind,glob,problem,matches:matches.length,ignored:ignored.length,examples:ignored.slice(0,EXAMPLES),fix:problem==="matches nothing"?"fix the path":"point it at files the selector reads, or allowlist it in `deadGlobs` with a reason"}}function configDeadGlobs(config,{graph,listed},skipped){let file=config.file??"the config",found=[],entries=[...config.generated.map((map)=>["edges",map]),...config.reads.map((map)=>["reads",map])];for(let[kind,map]of entries){let patterns=map.values.map(()=>new Map),matched=!1;for(let node of graph.keys()){let targets=map.targets(node);if(!targets)continue;matched=!0;for(let[i,re]of targets.entries())patterns[i]?.set(re.source,re)}if(!matched){found.push({node:file,kind,glob:map.key,problem:"matches nothing",matches:0,ignored:0,examples:[],fix:"fix the path: no file the graph reads matches it"});continue}for(let[i,glob]of map.values.entries()){let expanded=[...patterns[i]?.values()??[]],dead=deadOf(file,kind,glob,expanded,listed,skipped);if(dead)found.push(dead)}}return found}async function findDeadGlobs(root,config,computed){let{graph,extractions,listed}=computed,skipped=(file)=>config.isIgnored(file)&&!graph.has(file),found=[];for(let node of graph.keys()){let extraction=extractions.get(node);if(!extraction)continue;for(let{kind,glob,pattern}of declaredGlobs(node,extraction)){let dead=deadOf(node,kind,glob,[pattern],listed,skipped);if(dead)found.push(dead)}}let configured=configDeadGlobs(config,computed,skipped),nodes=[...new Set([...found.map(({node})=>node),...configured.map(({node})=>node)])],texts=await Promise.all(nodes.map((node)=>sourceOf(root,node))),sources=new Map(nodes.map((node,i)=>[node,texts[i]])),locate=(dead,line)=>{let source=sources.get(dead.node),at=source===void 0?void 0:line(source);return at===void 0?dead:{...dead,at:`${dead.node}:${at}`}};return[...found.map((dead)=>locate(dead,(source)=>dead.kind==="glob"?specifierLine(source,dead.glob):annotationLine(source,TAGS[dead.kind],dead.glob))),...configured.map((dead)=>locate(dead,(source)=>specifierLine(source,dead.glob)))]}async function check(root,config,computed){let nodes=[...computed.graph].filter(([,deps])=>deps.unknown.length>0).map(([node])=>node),isTest=(node)=>config.suites.some((suite)=>suite.isTest(node)),unknown=await Promise.all(nodes.map(async(node)=>({node,causes:(await causesOf(root,computed,node)).map(({cause,at})=>at===void 0?{cause,fix:fixFor(cause)}:{cause,at,fix:fixFor(cause)}),tests:sorted([...affectedBy(computed.graph,[node],{includeUnknown:!1,readers:!1})].filter(isTest))}))),fallbacks=[...computed.fallbacks].map(([file,reason])=>({file,reason})),dead=await findDeadGlobs(root,config,computed),allows=(entry,found)=>entry.file===found.node&&entry.glob===found.glob;return{unknown,fallbacks,unparsedTsconfigs:computed.unparsedTsconfigs,deadGlobs:dead.filter((found)=>!config.deadGlobs.some((entry)=>allows(entry,found))),staleDeadGlobs:config.deadGlobs.filter((entry)=>!dead.some((found)=>allows(entry,found))).map((entry)=>({...entry,fix:"remove the entry: its glob is no longer dead"}))}}function summary({problem,matches,ignored,examples}){if(problem==="matches nothing")return problem;let shown=[...examples,...ignored>examples.length?["…"]:[]],count=problem==="partly ignored"?`${ignored} of ${matches}`:`${ignored}`;return`${problem} (${count}: ${shown.join(", ")})`}function widening(report){return report.unknown.filter((node)=>node.tests.length>0)}function pushUnknown(lines,{node,causes,tests}){lines.push(node);for(let{cause,at,fix}of causes)lines.push(` ✗ ${cause}${at?` ${at}`:""}`,` fix: ${fix}`);if(tests.length>0){let more=tests.length>3?`, and ${tests.length-3} more`:"";lines.push(` runs on any change: ${tests.slice(0,3).join(", ")}${more}`)}}function formatReport(report,max){let lines=[],widen=widening(report);for(let unknown of widen)pushUnknown(lines,unknown);let idle=report.unknown.filter((node)=>node.tests.length===0);if(idle.length>0){lines.push("","Unknown, but no test depends on them, so they widen nothing:");for(let unknown of idle)pushUnknown(lines,unknown)}if(report.fallbacks.length>0){lines.push("","Read by the regex extractor, which the lexer couldn't read:");for(let{file,reason}of report.fallbacks)lines.push(` ${file}: ${reason}`)}if(report.unparsedTsconfigs.length>0){lines.push("","tsconfig files that don't parse, whose `paths` are ignored:");for(let{file,reason}of report.unparsedTsconfigs)lines.push(` ${file}: ${reason}`)}if(report.deadGlobs.length>0){lines.push("","Dead globs: a change to what they match, or to some of it, selects nothing:");let node;for(let dead of report.deadGlobs){if(dead.node!==node)lines.push(` ${dead.node}`);node=dead.node,lines.push(` ✗ ${dead.kind} ${dead.glob}: ${summary(dead)}${dead.at?` ${dead.at}`:""}`,` fix: ${dead.fix}`)}}if(report.staleDeadGlobs.length>0){lines.push("","`deadGlobs` entries that match no dead glob:");for(let{file,glob,fix}of report.staleDeadGlobs)lines.push(` ${file}: ${glob}`,` fix: ${fix}`)}let count=widen.length,limit=max===void 0?"":` (at most ${max})`;if(lines.push("",`${count} ${count===1?"node":"nodes"} with unknown dependencies ${count===1?"reaches":"reach"} a test${limit}: each such test runs on any change.`),idle.length>0)lines.push(`${idle.length} more no test reaches.`);let dead=report.deadGlobs.length,stale=report.staleDeadGlobs.length;if(dead>0)lines.push(`${dead} dead ${dead===1?"glob":"globs"} not in \`deadGlobs\`.`);if(stale>0)lines.push(`${stale} stale \`deadGlobs\` ${stale===1?"entry":"entries"}.`);return lines.join(`
|
|
12
|
-
`).trimStart()}var CONFIG_EDGES="edges in the config",CONFIG_READS="reads in the config";async function edgeAt(context,node,via){if(via.kind==="edges")return{at:CONFIG_EDGES};if(via.kind==="unknown")return{};let file=fileOf(node),source=SCANNED.test(file)?await sourceOf(context.root,file):void 0,configured=(maps)=>maps.some((map)=>map.targets(node)?.some((re)=>re.test(via.from)));if(via.kind==="reads"&&configured(context.config.reads)){if(!(source!==void 0&&extract(formatOf(file),source).reads.some((glob)=>globToRegExp(glob).test(via.from))))return{at:CONFIG_READS}}if(source===void 0)return{};let line=edgeLine(context,node,via,source);return line===void 0?{}:{at:`${file}:${line}`,text:lineText(source,line)}}function edgeLine({config,resolve},node,via,source){let file=fileOf(node),extraction=extract(formatOf(file),source),matches=(glob)=>globToRegExp(glob).test(via.from);if(via.kind==="reads"||via.kind==="depends-on"){let tag=`@${via.kind}`,glob=(via.kind==="reads"?extraction.reads:extraction.dependsOn).find(matches);return(glob===void 0?void 0:annotationLine(source,tag,glob))??textLine(source,tag)}if(via.kind==="glob"){let relative=finish(file,extraction).globs,glob=extraction.globs.find((_,i)=>matches(relative[i]));return(glob===void 0?void 0:specifierLine(source,glob))??callLine(source,"import.meta.glob")}let target=fileOf(via.from);if(via.kind==="goto"){let argument=extraction.gotos.find((candidate)=>gotoPage(config,file,candidate)===target);return gotoLine(source,argument,target)}let loads=(specifier)=>{let resolved=resolve(file,specifier);return resolved!==void 0&&"files"in resolved&&resolved.files.includes(target)};if(via.kind==="export"){let barrel=extraction.barrel;if(!barrel)return;let own=barrel.names.get(node.slice(node.indexOf("#")+1)),specifier=[...own===void 0?[]:[own],...barrel.names.values(),...barrel.stars].find(loads);return specifier===void 0?void 0:specifierLine(source,specifier)}let imported=extraction.imports.find(({specifier})=>loads(specifier));return imported===void 0?void 0:specifierLine(source,imported.specifier)}function rootCause(computed,rootNode,from){if(from!==void 0)return"given";if(computed.changed.includes(rootNode))return"changed";let bumped=computed.plan.packageCauses.get(rootNode);if(bumped!==void 0)return bumped;if(computed.barrelNames.includes(rootNode))return"barrel name moved";for(let{narrower,result}of computed.narrowed)if("seeds"in result&&result.seeds.includes(rootNode))return`seeded by the ${narrower.name} narrower`;return"changed"}function walks(computed,suite,from){let{plan,graph}=computed;if(from!==void 0)return[{seeds:[from],opaque:void 0}];let narrowings=plan.narrowings.get(suite);if(!narrowings)return[{seeds:plan.seeds,opaque:void 0}];let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched));return[{seeds:plan.seeds.filter((seed)=>!matched.has(seed)),opaque:void 0},...narrowings.map((narrowing)=>({seeds:[...narrowing.matched,...narrowing.seeds].filter((seed)=>graph.has(seed)||computed.changed.includes(seed)),opaque:narrowing.narrower.opaque}))]}function shortestChain(computed,candidates,test){for(let walk of candidates){let parents=new Map;if(!affectedBy(computed.graph,walk.seeds,{opaque:walk.opaque,parents}).has(test))continue;let edges=[],node=test;for(let via=parents.get(node);via;via=parents.get(node))if(edges.push([node,via]),node=via.from,via.kind==="unknown")break;return{edges,root:node}}return}function reachers(computed,candidates,test,except){let found=new Set;for(let{seeds,opaque}of candidates)for(let seed of seeds){if(seed===except||found.has(seed))continue;if(affectedBy(computed.graph,[seed],{opaque}).has(test))found.add(seed)}return sorted(found)}async function chainOf(context,{edges,root},from){let last=edges.at(-1),[links,causes]=await Promise.all([Promise.all(edges.map(async([node,via])=>({node,kind:via.kind,...await edgeAt(context,node,via)}))),last?.[1].kind==="unknown"?causesOf(context.root,context.computed,last[0]):[]]);return{links,root,cause:rootCause(context.computed,root,from),unknown:causes.map((cause)=>({...cause,fix:fixFor(cause.cause)}))}}function unselected(config,computed,suite,from){let changed=computed.changed.length;if(from===void 0)return{kind:"unselected",suite,changed};let reached=sorted(affectedBy(computed.graph,[from],{includeUnknown:!1})),reaches={},example;for(let{name,isTest}of config.suites){let tests=reached.filter((node)=>isTest(node));if(tests.length===0)continue;if(reaches[name]=tests.length,name===suite||example===void 0)example=tests[0]}return{kind:"unselected",suite,from,changed,reaches,...example!==void 0&&{example}}}async function explain(root,config,computed,test,from,{all=!1}={}){let suite=config.suites.find((candidate)=>candidate.isTest(test));if(!suite)throw Error(`bivium why: ${test} is no suite's test`);if(!computed.graph.has(test))throw Error(`bivium why: no file ${test}`);if(from===void 0&&computed.plan.full.includes(suite.name))return{kind:"full",suite:suite.name,reasons:computed.plan.reasons};let candidates=walks(computed,suite.name,from),found=shortestChain(computed,candidates,test);if(!found)return unselected(config,computed,suite.name,from);let context={root,config,computed,resolve:createResolver({files:new Set(computed.graph.keys()),config,packages:computed.packages,tsconfigs:computed.tsconfigs})},everything=found.edges.at(-1)?.[1].kind==="unknown",more=from!==void 0||everything?[]:reachers(computed,candidates,test,found.root),[chain,others]=await Promise.all([chainOf(context,found,from),Promise.all((all?more:[]).map((seed)=>{let alone=candidates.map((walk)=>({...walk,seeds:walk.seeds.filter((candidate)=>candidate===seed)})),other=shortestChain(computed,alone,test);return other&&chainOf(context,other,void 0)}))]);return{kind:"chain",suite:suite.name,test,...chain,more,others:others.filter((other)=>other!==void 0)}}var FORMATS=["tree","chain","source"];function isFormat(value){return FORMATS.some((format)=>format===value)}var VERBS={import:"imported by",goto:"opened by",html:"loaded by page",name:"imported by",glob:"globbed by","depends-on":"depended on by",edges:"an input of",reads:"read as text by",unknown:"depends on every change"},LIST=3;function plural(count,one,many){return`${count} ${count===1?one:many}`}function nameOf(node){return node.slice(node.indexOf("#")+1)}function aligned(rows){let width=Math.max(0,...rows.filter(([,at])=>at!==void 0).map(([text])=>text.length));return rows.map(([text,at])=>at===void 0?text:`${text.padEnd(width)} ${at}`)}function tree(test,chain){let rows=[[test,void 0]],width=Math.max(0,...chain.links.filter((link)=>link.kind!=="unknown").map((link)=>link.kind.length)),indent="";for(let[i,link]of chain.links.entries()){let next=chain.links[i+1]?.node??chain.root;if(link.kind==="unknown"){rows.push([`${indent}└─ depends on every change:`,void 0]);for(let{cause,at}of chain.unknown)rows.push([`${indent} ✗ ${cause}`,at]);indent+=" ",rows.push([`${indent}└─ ${next}`,void 0]),indent+=" ";break}rows.push([`${indent}└─ ${link.kind.padEnd(width)} ${next}`,link.at]),indent+=" "}return rows.push([`${indent}● ${chain.cause}`,void 0]),aligned(rows)}function verbOf(link){return link.kind==="export"?`exported as ${nameOf(link.node)}`:VERBS[link.kind]}function whereOf(link){if(link.kind==="edges")return`${link.node} (${CONFIG_EDGES})`;return link.at??link.node}function steps(links){let rows=[...links].reverse().map((link)=>[verbOf(link),whereOf(link)]),width=Math.max(0,...rows.map(([verb])=>verb.length));return rows.map(([verb,where],i)=>`${verb.padEnd(width)} ${where}${i===rows.length-1?" ← selected":""}`)}function header({root,cause}){if(cause==="changed")return`${root} changed`;if(cause==="given")return`if ${root} changes`;return`${root}: ${cause}`}function chained(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown");if(unknownAt===-1)return[header(chain),...steps(chain.links).map((step)=>` ${step}`)];let node=chain.links[unknownAt].node,where=chain.unknown.map(({at})=>at??node),width=Math.max(0,...where.map((at)=>at.length)),lines=[`${test} runs on every change`];for(let[i,{cause,fix}]of chain.unknown.entries())lines.push(` because ${where[i].padEnd(width)} ${cause}`,` fix: ${fix}`);if(unknownAt>0)lines.push(` reached via ${node}`,...steps(chain.links.slice(0,unknownAt)).map((step)=>` ${step}`));return lines}var LINE_NUMBER=/:(\d+)$/;function lineNumber(at){return at===void 0?void 0:LINE_NUMBER.exec(at)?.[1]}function sourced(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown"),hops=unknownAt===-1?chain.links:chain.links.slice(0,unknownAt),numbers=[...chain.links,...chain.unknown].map(({at})=>lineNumber(at)),width=Math.max(0,...numbers.map((n)=>n?.length??0)),gutter=" ".repeat(width),cited=(at,text)=>{let n=lineNumber(at);return n===void 0||text===void 0?[]:[`${n.padStart(width)} | ${text}`]},count=plural(hops.length,"hop","hops"),lines=unknownAt===-1?[`selected: ${test} ← ${chain.root} (${count}${chain.cause==="changed"?"":`, ${chain.cause}`})`]:[`selected: ${test} ← every change (${unknownAt===0?"its dependencies can't be read":`${count} to ${chain.links[unknownAt].node}, whose dependencies can't be read`})`];lines.push("");for(let link of hops){let where=link.kind==="edges"?link.node:link.at??link.node,kind=link.kind==="edges"?CONFIG_EDGES:link.kind;lines.push(`${gutter}--> ${where} ${kind}`,...cited(link.at,link.text))}if(unknownAt===-1)return lines.push(`${gutter}● ${chain.root}: ${chain.cause}`),lines;let node=chain.links[unknownAt].node;for(let{cause,at,text,fix}of chain.unknown)lines.push(`${gutter}✗ ${at??node} ${cause}`,...cited(at,text),`${gutter} = fix: ${fix}`);return lines}var RENDER={tree,chain:chained,source:sourced};function moreLine(more,all){let shown=more.slice(0,LIST).join(", "),rest=more.length>LIST?", …":"";return`+ ${plural(more.length,"more change reaches","more changes reach")} this test: ${shown}${rest}${all?"":" (--all shows each chain)"}`}function unselectedMessage(explanation){let{from,changed,reaches,example}=explanation;if(from===void 0)return changed===0?"Not selected: nothing changed.":`Not selected: ${changed===1?"the changed file doesn't reach":`none of the ${changed} changed files reaches`} it.`;let counts=Object.entries(reaches??{}).map(([suite,count])=>`${count} ${suite}`),total=Object.values(reaches??{}).reduce((a,b)=>a+b,0);return[`Not selected by a change to ${from}: no chain reaches it.`,total===0?"Its chains reach no test.":`Its chains reach ${plural(total,"test","tests")} (${counts.join(", ")}), such as ${example}.`].join(`
|
|
12
|
+
`,start);return source.slice(start,end===-1?source.length:end).trim()}async function sourceOf(root,file){try{return await readFile(isAbsolute(file)?file:join(root,file),"utf-8")}catch{return}}function fileOf(node){let hash=node.indexOf("#");return hash===-1?node:node.slice(0,hash)}async function causesOf(root,computed,node){let file=fileOf(node),source=await sourceOf(root,file);return(computed.graph.get(node)?.unknown??[]).map((cause)=>{if(source===void 0)return{cause};let line=causeLine(source,cause);return line===void 0?{cause}:{cause,at:`${file}:${line}`,text:lineText(source,line)}})}var EXAMPLES=3,TAGS={"depends-on":"@depends-on",reads:"@reads",lists:"@lists",glob:"import.meta.glob",edges:"edges",setup:"setup"},QUOTED=/"([^"]+)"/;function fixFor(cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED.exec(cause)?.[1]??"";if(specifier.startsWith("./%sveltekit.assets%/"))return"no file in the SvelteKit project's `static/` (a custom `kit.files.assets` isn't read): fix the path, or add an `edges` entry for it";if(RELATIVE.test(specifier))return"no file at that path: fix the import, or add an `edges` entry if a build generates it";if(specifier.startsWith("#"))return"map it in the `imports` of the file's package.json, or with `alias`";return"declare the package in a package.json, list it in `external` if a dependency installs it, or map it with `alias` or tsconfig `paths`"}if(cause.startsWith("only declarations for "))return"only a declaration file is there, so what runs isn't in the graph: if a build writes it, name it in `edges` with its inputs, or import it with `import type` if only its types are used";if(cause==="non-literal dynamic import")return"spell the path as a string literal, load the files with `import.meta.glob` and literal patterns, or list the file in `hermetic` if it only imports paths its caller passes";if(cause==="non-literal glob import")return"pass `import.meta.glob` literal patterns";if(cause===UNDECLARED_READS)return"name what it reads: `// @depends-on <glob>`, or `// @reads <glob>` for files read as text, or an `edges` or `reads` entry for the file in the config; list the file in `hermetic` if it reads no file of the repository";if(cause.startsWith("non-literal goto("))return"pass `goto()` a literal URL, or a template whose path before `?` or `#` is literal; or name the pages it can open with `// @depends-on <glob>`";if(cause.startsWith("missing fixture "))return"no page at that URL: fix the URL, or the suite's `urls`";if(cause.startsWith("goto("))return"map the URL to a file with the suite's `urls`";return"see the cause"}function isFile(path){return statSync(path,{throwIfNoEntry:!1})?.isFile()??!1}function stemOf(path){let slash=path.lastIndexOf("/"),dot=path.indexOf(".",slash+2);return dot===-1?path:path.slice(0,dot)}function nearMisses(root,config,{graph,listed}){let stems,listedSet=new Set(listed),siblings=(path)=>{if(!stems){stems=new Map;for(let file of listed){let stem=stemOf(file),list=stems.get(stem);list?list.push(file):stems.set(stem,[file])}}return stems.get(stemOf(path))??[]},candidates=(base)=>[base,...config.extensions.map((ext)=>base+ext),...config.extensions.map((ext)=>`${base}/index${ext}`)];return(node,cause)=>{if(!cause.startsWith("unresolved "))return;let specifier=(QUOTED.exec(cause)?.[1]??"").replace(QUERY,""),base=RELATIVE.test(specifier)?posix.join(posix.dirname(fileOf(node)),specifier):config.alias.map((alias)=>aliasPath(alias,specifier)).find((path)=>path!==void 0);if(base===void 0||base.startsWith("../"))return;let tried=candidates(base),outside=tried.find((path)=>listedSet.has(path)&&!graph.has(path));if(outside!==void 0)return`${outside} exists, but outside \`roots\`: add it to \`roots\``;let unlisted=tried.find((path)=>isFile(join2(root,path)));if(unlisted!==void 0&&!listedSet.has(unlisted))return`${unlisted} exists, but git doesn't list it (ignored?): if a build writes it, name it in \`edges\` with its inputs`;let sibling=siblings(base).find((file)=>graph.has(file));if(sibling!==void 0)return`${sibling} exists: import it by that name, or add its extension to \`extensions\``;return}}function declaredGlobs(node,extraction){let relative=finish(node,extraction).globs;return[...extraction.dependsOn.map((glob)=>({kind:"depends-on",glob,pattern:globToRegExp(glob)})),...extraction.reads.map((glob)=>({kind:"reads",glob,pattern:globToRegExp(glob)})),...extraction.lists.map((glob)=>({kind:"lists",glob,pattern:globToRegExp(glob)})),...extraction.globs.map((glob,i)=>({kind:"glob",glob,pattern:globToRegExp(relative[i])}))]}function problemOf(matches,ignored){if(matches===0)return"matches nothing";if(ignored===0)return;return ignored===matches?"matches only ignored files":"partly ignored"}function deadOf(node,kind,glob,patterns,listed,skipped){let matches=listed.filter((file)=>patterns.some((re)=>re.test(file))),ignored=sorted(matches.filter(skipped)),problem=problemOf(matches.length,ignored.length);if(problem===void 0)return;return{node,kind,glob,problem,matches:matches.length,ignored:ignored.length,examples:ignored.slice(0,EXAMPLES),fix:problem==="matches nothing"?"fix the path":"point it at files the selector reads, or allowlist it in `deadGlobs` with a reason"}}function configDeadGlobs(config,{graph,listed},skipped){let file=config.file??"the config",found=[],entries=[...config.generated.map((map)=>["edges",map]),...config.reads.map((map)=>["reads",map])];for(let[kind,map]of entries){let patterns=map.values.map(()=>new Map),matched=!1;for(let node of graph.keys()){let targets=map.targets(node);if(!targets)continue;matched=!0;for(let[i,re]of targets.entries())patterns[i]?.set(re.source,re)}if(!matched){found.push({node:file,kind,glob:map.key,problem:"matches nothing",matches:0,ignored:0,examples:[],fix:"fix the path: no file the graph reads matches it"});continue}for(let[i,glob]of map.values.entries()){let expanded=[...patterns[i]?.values()??[]],dead=deadOf(file,kind,glob,expanded,listed,skipped);if(dead)found.push(dead)}}for(let suite of config.suites)for(let glob of suite.setup){let pattern=globToRegExp(glob),dead=deadOf(file,"setup",glob,[pattern],listed,skipped);if(dead)found.push(dead)}return found}async function findDeadGlobs(root,config,computed){let{graph,extractions,listed}=computed,skipped=(file)=>config.isIgnored(file)&&!graph.has(file),found=[];for(let node of graph.keys()){let extraction=extractions.get(node);if(!extraction)continue;for(let{kind,glob,pattern}of declaredGlobs(node,extraction)){let dead=deadOf(node,kind,glob,[pattern],listed,skipped);if(dead)found.push(dead)}}let configured=configDeadGlobs(config,computed,skipped),nodes=[...new Set([...found.map(({node})=>node),...configured.map(({node})=>node)])],texts=await Promise.all(nodes.map((node)=>sourceOf(root,node))),sources=new Map(nodes.map((node,i)=>[node,texts[i]])),locate=(dead,line)=>{let source=sources.get(dead.node),at=source===void 0?void 0:line(source);return at===void 0?dead:{...dead,at:`${dead.node}:${at}`}};return[...found.map((dead)=>locate(dead,(source)=>dead.kind==="glob"?specifierLine(source,dead.glob):annotationLine(source,TAGS[dead.kind],dead.glob))),...configured.map((dead)=>locate(dead,(source)=>specifierLine(source,dead.glob)))]}var CONFIG_FILE=/(?:^|[./_-])(?:config|setup|teardown|harness)(?:[./_-]|$)|^tsconfig[^/]*\.json$|^\.[^/]*rc(?:\.[^/]+)?$/;function unreachedFix(file,tests){let name=posix.basename(file),owner=tests.find((test)=>name.startsWith(`${posix.basename(test)}.`));if(owner!==void 0)return`if ${owner} reads it, add \`reads: { "${owner}": "${file}" }\` (or \`// @reads ${file}\` in the test)`;if(CONFIG_FILE.test(name))return"if the runner loads it, name it in the suite's `wiring` (or `setup`, if it runs before every test), which makes the full run deliberate";return"if a test reads or runs it, say so with `reads` or `@depends-on` in that test or what loads it; if none can observe it, list it in the suite's `nonInputs`, or delete it if it's dead"}function unreachedFiles(config,{graph}){let found=[],files=[...graph.keys()].filter((node)=>!node.startsWith("pkg:")&&!node.includes("#"));for(let suite of config.suites){let reached=fanIn(graph,suite),tests=files.filter(suite.isTest);for(let file of files){if((reached.get(file)??0)>0)continue;if(config.isIgnored(file)||config.isSelf(file))continue;if(suite.isWiring(file))continue;if(!orphanOf(graph,config,suite,file))continue;found.push({suite:suite.name,file,fix:unreachedFix(file,tests)})}}return found}async function check(root,config,computed){let nodes=[...computed.graph].filter(([,deps])=>deps.unknown.length>0).map(([node])=>node),testsOf=(node)=>{let reach=walksByTypes(computed.graph,[node],{includeUnknown:!1,readers:!1}),found=new Set;for(let suite of config.suites)for(let test of reach(suite.types))if(suite.isTest(test))found.add(test);return sorted(found)},nearMiss=nearMisses(root,config,computed),known=new Map((config.knownUnknowns??[]).map((entry)=>[entry.file,entry.reason])),unknown=await Promise.all(nodes.map(async(node)=>{let causes=(await causesOf(root,computed,node)).map(({cause,at})=>{let fix=nearMiss(node,cause)??fixFor(cause);return at===void 0?{cause,fix}:{cause,at,fix}}),reason=known.get(node),entry={node,causes,tests:testsOf(node)};if(reason!==void 0)entry.known=reason;return entry})),fallbacks=[...computed.fallbacks].map(([file,reason])=>({file,reason})),dead=await findDeadGlobs(root,config,computed),unreached=unreachedFiles(config,computed),allows=(entry,found)=>entry.file===found.node&&entry.glob===found.glob;return{unknown,fallbacks,unparsedTsconfigs:computed.unparsedTsconfigs,deadGlobs:dead.filter((found)=>!config.deadGlobs.some((entry)=>allows(entry,found))),unlistedUnknowns:config.knownUnknowns?unknown.filter((entry)=>entry.tests.length>0&&entry.known===void 0).map((entry)=>entry.node):[],staleKnownUnknowns:(config.knownUnknowns??[]).filter((entry)=>!nodes.includes(entry.file)).map((entry)=>({...entry,fix:"remove the entry: its dependencies are known now"})),unreached,staleDeadGlobs:config.deadGlobs.filter((entry)=>!dead.some((found)=>allows(entry,found))).map((entry)=>({...entry,fix:"remove the entry: its glob is no longer dead"}))}}function summary({problem,matches,ignored,examples}){if(problem==="matches nothing")return problem;let shown=[...examples,...ignored>examples.length?["…"]:[]],count=problem==="partly ignored"?`${ignored} of ${matches}`:`${ignored}`;return`${problem} (${count}: ${shown.join(", ")})`}function widening(report){return report.unknown.filter((node)=>node.tests.length>0)}function failed(report,max){return max!==void 0&&widening(report).length>max||report.unlistedUnknowns.length>0||report.staleKnownUnknowns.length>0||report.deadGlobs.length>0||report.staleDeadGlobs.length>0}function pushUnknown(lines,{node,causes,tests,known}){lines.push(known===void 0?node:`${node} (known: ${known})`);for(let{cause,at,fix}of causes)lines.push(` ✗ ${cause}${at?` ${at}`:""}`,` fix: ${fix}`);if(tests.length>0){let more=tests.length>3?`, and ${tests.length-3} more`:"";lines.push(` runs on any change: ${tests.slice(0,3).join(", ")}${more}`)}}function categoryOf(cause){if(cause.startsWith("unresolved ")){let specifier=QUOTED.exec(cause)?.[1]??"";if(RELATIVE.test(specifier))return"unresolved relative import";if(specifier.startsWith("#"))return"unresolved # import";return"unresolved bare import (a package, alias or path)"}if(cause.startsWith("only declarations for "))return"a .js import with only its declarations there";if(cause.startsWith("non-literal goto("))return"non-literal goto()";if(cause.startsWith("goto("))return"goto() URL no `urls` pattern maps";if(cause.startsWith("missing fixture "))return"goto() of a missing page";return cause}var POSITION=/(?: in <>)? at \d+.*$/,BLANK_LINES=/\n{3,}/g;function counted(counts){return[...counts].sort(([a,x],[b,y])=>y-x||(a<b?-1:1)).map(([what,count])=>`${count} ${what}`)}function summaryLines(report){let widen=widening(report),lines=[];if(widen.length>0){let tests=new Set(widen.flatMap((node)=>node.tests));lines.push(`${plural(widen.length,"node")} with unknown dependencies ${widen.length===1?"reaches":"reach"} ${plural(tests.size,"test")}, which ${tests.size===1?"runs":"run"} on any change:`);let causes=new Map;for(let node of widen)for(let category of new Set(node.causes.map(({cause})=>categoryOf(cause))))causes.set(category,(causes.get(category)??0)+1);lines.push(...counted(causes).map((line)=>` ${line}`))}let idle=report.unknown.length-widen.length;if(idle>0)lines.push(`${plural(idle,"more node")} with unknown dependencies no test reaches`);if(report.fallbacks.length>0){let reasons=new Map;for(let{reason}of report.fallbacks){let what=reason.replace(POSITION,"");reasons.set(what,(reasons.get(what)??0)+1)}lines.push(`${plural(report.fallbacks.length,"file")} read by the regex extractor: ${counted(reasons).join(", ")}`)}let problems=[[report.unparsedTsconfigs.length,"tsconfig file that doesn't parse","tsconfig files that don't parse"],[report.deadGlobs.length,"dead glob","dead globs"],[report.staleDeadGlobs.length,"stale `deadGlobs` entry","stale `deadGlobs` entries"],[report.unlistedUnknowns.length,"unknown not in `knownUnknowns`","unknowns not in `knownUnknowns`"],[report.staleKnownUnknowns.length,"stale `knownUnknowns` entry","stale `knownUnknowns` entries"],[report.unreached.length,"file under a suite's root that no test reaches","files under a suite's root that no test reaches"]];for(let[count,one,many]of problems)if(count>0)lines.push(plural(count,one,many));return lines.length===0?[]:["Summary:",...lines.map((line)=>` ${line}`),""]}var UNREACHED_SHOWN=10;function pushUnreached(lines,unreached){if(unreached.length===0)return;lines.push("","Files under a suite's root that no test reaches: a change to one runs the whole suite:");for(let suite of new Set(unreached.map((entry)=>entry.suite))){let entries=unreached.filter((entry)=>entry.suite===suite);lines.push(` ${suite} (${entries.length})`);for(let{file,fix}of entries.slice(0,UNREACHED_SHOWN))lines.push(` ${file}`,` fix: ${fix}`);let rest=entries.slice(UNREACHED_SHOWN);if(rest.length===0)continue;let dirs=new Map;for(let{file}of rest){let dir=posix.dirname(file);dirs.set(dir,(dirs.get(dir)??0)+1)}let counts=[...dirs].sort(([a,x],[b,y])=>y-x||(a<b?-1:1)).map(([dir,count])=>`${dir}/ (${count})`);lines.push(` … ${rest.length} more in ${counts.slice(0,5).join(", ")}${counts.length>5?", …":""} (--json lists each)`)}}function formatReport(report,max){let lines=summaryLines(report),widen=widening(report);for(let unknown of widen)pushUnknown(lines,unknown);let idle=report.unknown.filter((node)=>node.tests.length===0);if(idle.length>0){lines.push("","Unknown, but no test depends on them, so they widen nothing:");for(let unknown of idle)pushUnknown(lines,unknown)}if(report.fallbacks.length>0){lines.push("","Read by the regex extractor, which the lexer couldn't read:");for(let{file,reason}of report.fallbacks)lines.push(` ${file}: ${reason}`)}if(pushUnreached(lines,report.unreached),report.unparsedTsconfigs.length>0){lines.push("","tsconfig files that don't parse, whose `paths` are ignored:");for(let{file,reason}of report.unparsedTsconfigs)lines.push(` ${file}: ${reason}`)}if(report.deadGlobs.length>0){lines.push("","Dead globs: a change to what they match, or to some of it, selects nothing:");let node;for(let dead of report.deadGlobs){if(dead.node!==node)lines.push(` ${dead.node}`);node=dead.node,lines.push(` ✗ ${dead.kind} ${dead.glob}: ${summary(dead)}${dead.at?` ${dead.at}`:""}`,` fix: ${dead.fix}`)}}if(report.staleDeadGlobs.length>0){lines.push("","`deadGlobs` entries that match no dead glob:");for(let{file,glob,fix}of report.staleDeadGlobs)lines.push(` ${file}: ${glob}`,` fix: ${fix}`)}if(report.staleKnownUnknowns.length>0){lines.push("","`knownUnknowns` entries whose dependencies are known:");for(let{file,fix}of report.staleKnownUnknowns)lines.push(` ${file}`,` fix: ${fix}`)}let count=widen.length,limit=max===void 0?"":` (at most ${max})`;lines.push("",`${count} ${count===1?"node":"nodes"} with unknown dependencies ${count===1?"reaches":"reach"} a test${limit}: each such test runs on any change.`);let unlisted=report.unlistedUnknowns.length;if(unlisted>0)lines.push(`${unlisted} of them not in \`knownUnknowns\`: fix ${unlisted===1?"it":"them"}, or list ${unlisted===1?"it":"them"} with a reason.`);if(idle.length>0)lines.push(`${idle.length} more no test reaches.`);let staleKnown=report.staleKnownUnknowns.length;if(staleKnown>0)lines.push(`${plural(staleKnown,"stale `knownUnknowns` entry","stale `knownUnknowns` entries")}.`);let dead=report.deadGlobs.length,stale=report.staleDeadGlobs.length;if(dead>0)lines.push(`${plural(dead,"dead glob")} not in \`deadGlobs\`.`);if(stale>0)lines.push(`${plural(stale,"stale `deadGlobs` entry","stale `deadGlobs` entries")}.`);return lines.join(`
|
|
13
|
+
`).replace(BLANK_LINES,`
|
|
14
|
+
|
|
15
|
+
`).trimStart()}var CONFIG_EDGES="edges in the config",CONFIG_SETUP="setup in the config",CONFIGURED={edges:CONFIG_EDGES,setup:CONFIG_SETUP},CONFIG_READS="reads in the config";async function edgeAt(context,node,via){let spelled=CONFIGURED[via.kind];if(spelled!==void 0)return{at:spelled};if(via.kind==="unknown")return{};let file=fileOf(node),source=SCANNED.test(file)?await sourceOf(context.root,file):void 0,configured=(maps)=>maps.some((map)=>map.targets(node)?.some((re)=>re.test(via.from)));if(via.kind==="reads"&&configured(context.config.reads)){if(!(source!==void 0&&extract(formatOf(file),source).reads.some((glob)=>globToRegExp(glob).test(via.from))))return{at:CONFIG_READS}}if(source===void 0)return{};let line=edgeLine(context,node,via,source);return line===void 0?{}:{at:`${file}:${line}`,text:lineText(source,line)}}function edgeLine({config,resolve},node,via,source){let file=fileOf(node),extraction=extract(formatOf(file),source),matches=(glob)=>globToRegExp(glob).test(via.from);if(via.kind==="reads"||via.kind==="depends-on"||via.kind==="lists"){let tag=`@${via.kind}`,glob={reads:extraction.reads,"depends-on":extraction.dependsOn,lists:extraction.lists}[via.kind].find(matches);return(glob===void 0?void 0:annotationLine(source,tag,glob))??textLine(source,tag)}if(via.kind==="glob"){let relative=finish(file,extraction).globs,glob=extraction.globs.find((_,i)=>matches(relative[i]));return(glob===void 0?void 0:specifierLine(source,glob))??callLine(source,"import.meta.glob")}let target=fileOf(via.from);if(via.kind==="goto"){let argument=extraction.gotos.find((candidate)=>gotoPage(config,file,candidate)?.includes(target));return gotoLine(source,argument,target)}let loads=(specifier)=>{let resolved=resolve(file,specifier);return resolved!==void 0&&"files"in resolved&&resolved.files.includes(target)};if(via.kind==="export"){let barrel=extraction.barrel;if(!barrel)return;let own=barrel.names.get(node.slice(node.indexOf("#")+1)),specifier=[...own===void 0?[]:[own],...barrel.names.values(),...barrel.stars].find(loads);return specifier===void 0?void 0:specifierLine(source,specifier)}let imported=extraction.imports.find(({specifier})=>loads(specifier));return imported===void 0?void 0:specifierLine(source,imported.specifier)}function rootCause(computed,rootNode,from){if(from!==void 0)return"given";if(computed.changed.includes(rootNode))return"changed";let bumped=computed.plan.packageCauses.get(rootNode);if(bumped!==void 0)return bumped;if(computed.barrelNames.includes(rootNode))return"barrel name moved";for(let{narrower,result}of computed.narrowed)if("seeds"in result&&result.seeds.includes(rootNode))return`seeded by the ${narrower.name} narrower`;return"changed"}function walks(computed,{name,types},from){let{plan,graph}=computed;if(from!==void 0)return[{seeds:[from],opaque:void 0,types}];let{quiet,layout}=plan,narrowings=plan.narrowings.get(name);if(!narrowings)return[{seeds:plan.seeds,quiet,layout,opaque:void 0,types}];let matched=new Set(narrowings.flatMap((narrowing)=>narrowing.matched));return[{seeds:plan.seeds.filter((seed)=>!matched.has(seed)),quiet,layout,opaque:void 0,types},...narrowings.map((narrowing)=>({seeds:[...narrowing.matched,...narrowing.seeds].filter((seed)=>graph.has(seed)||computed.changed.includes(seed)),opaque:narrowing.narrower.opaque,layout,types}))]}function shortestChain(computed,candidates,test){for(let{seeds,...options}of candidates){let parents=new Map;if(!affectedBy(computed.graph,seeds,{...options,parents}).has(test))continue;let edges=[],node=test;for(let via=parents.get(node);via;via=parents.get(node))if(edges.push([node,via]),node=via.from,via.kind==="unknown")break;return{edges,root:node}}return}function reachers(computed,candidates,test,except){let found=new Set,unseen=(seed)=>seed!==except&&!found.has(seed);for(let{seeds,quiet=[],...options}of candidates){for(let seed of seeds.filter(unseen))if(affectedBy(computed.graph,[seed],options).has(test))found.add(seed);for(let seed of quiet.filter(unseen))if(affectedBy(computed.graph,[],{...options,quiet:[seed]}).has(test))found.add(seed)}return sorted(found)}async function chainOf(context,{edges,root},from){let last=edges.at(-1),[links,causes]=await Promise.all([Promise.all(edges.map(async([node,via])=>({node,kind:via.kind,...await edgeAt(context,node,via)}))),last?.[1].kind==="unknown"?causesOf(context.root,context.computed,last[0]):[]]);return{links,root,cause:rootCause(context.computed,root,from),unknown:causes.map((cause)=>({...cause,fix:fixFor(cause.cause)}))}}function unselected(config,computed,suite,from){let changed=computed.changed.length;if(from===void 0)return{kind:"unselected",suite,changed};let reachedBy=walksByTypes(computed.graph,[from],{includeUnknown:!1}),reaches={},example;for(let{name,isTest,types}of config.suites){let tests=sorted(reachedBy(types)).filter((node)=>isTest(node));if(tests.length===0)continue;if(reaches[name]=tests.length,name===suite||example===void 0)example=tests[0]}return{kind:"unselected",suite,from,changed,reaches,...example!==void 0&&{example}}}async function explain(root,config,computed,test,from,{all=!1}={}){let suite=config.suites.find((candidate)=>candidate.isTest(test));if(!suite)throw Error(`bivium why: ${test} is no suite's test`);if(!computed.graph.has(test))throw Error(`bivium why: no file ${test}`);if(from===void 0&&computed.plan.full.includes(suite.name))return{kind:"full",suite:suite.name,reasons:computed.plan.reasons};let candidates=walks(computed,suite,from),found=shortestChain(computed,candidates,test);if(!found)return unselected(config,computed,suite.name,from);let context={root,config,computed,resolve:createResolver({files:new Set(computed.graph.keys()),config,packages:computed.packages,tsconfigs:computed.tsconfigs})},everything=found.edges.at(-1)?.[1].kind==="unknown",more=from!==void 0||everything?[]:reachers(computed,candidates,test,found.root),[chain,others]=await Promise.all([chainOf(context,found,from),Promise.all((all?more:[]).map((seed)=>{let alone=candidates.map((walk)=>({...walk,seeds:walk.seeds.filter((candidate)=>candidate===seed),quiet:walk.quiet?.filter((candidate)=>candidate===seed)})),other=shortestChain(computed,alone,test);return other&&chainOf(context,other,void 0)}))]);return{kind:"chain",suite:suite.name,test,...chain,more,others:others.filter((other)=>other!==void 0)}}var FORMATS=["tree","chain","source"];function isFormat(value){return FORMATS.some((format)=>format===value)}var VERBS={import:"imported by",type:"type-imported by",setup:"a setup file of",goto:"opened by",html:"loaded by page",name:"imported by",glob:"globbed by","depends-on":"depended on by",edges:"an input of",reads:"read as text by",lists:"listed by",unknown:"depends on every change"},LIST=3;function nameOf(node){return node.slice(node.indexOf("#")+1)}function aligned(rows){let width=Math.max(0,...rows.filter(([,at])=>at!==void 0).map(([text])=>text.length));return rows.map(([text,at])=>at===void 0?text:`${text.padEnd(width)} ${at}`)}function tree(test,chain){let rows=[[test,void 0]],width=Math.max(0,...chain.links.filter((link)=>link.kind!=="unknown").map((link)=>link.kind.length)),indent="";for(let[i,link]of chain.links.entries()){let next=chain.links[i+1]?.node??chain.root;if(link.kind==="unknown"){rows.push([`${indent}└─ depends on every change:`,void 0]);for(let{cause,at}of chain.unknown)rows.push([`${indent} ✗ ${cause}`,at]);indent+=" ",rows.push([`${indent}└─ ${next}`,void 0]),indent+=" ";break}rows.push([`${indent}└─ ${link.kind.padEnd(width)} ${next}`,link.at]),indent+=" "}return rows.push([`${indent}● ${chain.cause}`,void 0]),aligned(rows)}function verbOf(link){return link.kind==="export"?`exported as ${nameOf(link.node)}`:VERBS[link.kind]}function whereOf(link){let configured=CONFIGURED[link.kind];if(configured!==void 0)return`${link.node} (${configured})`;return link.at??link.node}function steps(links){let rows=[...links].reverse().map((link)=>[verbOf(link),whereOf(link)]),width=Math.max(0,...rows.map(([verb])=>verb.length));return rows.map(([verb,where],i)=>`${verb.padEnd(width)} ${where}${i===rows.length-1?" ← selected":""}`)}function header({root,cause}){if(cause==="changed")return`${root} changed`;if(cause==="given")return`if ${root} changes`;return`${root}: ${cause}`}function chained(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown");if(unknownAt===-1)return[header(chain),...steps(chain.links).map((step)=>` ${step}`)];let node=chain.links[unknownAt].node,where=chain.unknown.map(({at})=>at??node),width=Math.max(0,...where.map((at)=>at.length)),lines=[`${test} runs on every change`];for(let[i,{cause,fix}]of chain.unknown.entries())lines.push(` because ${where[i].padEnd(width)} ${cause}`,` fix: ${fix}`);if(unknownAt>0)lines.push(` reached via ${node}`,...steps(chain.links.slice(0,unknownAt)).map((step)=>` ${step}`));return lines}var LINE_NUMBER=/:(\d+)$/;function lineNumber(at){return at===void 0?void 0:LINE_NUMBER.exec(at)?.[1]}function sourced(test,chain){let unknownAt=chain.links.findIndex((link)=>link.kind==="unknown"),hops=unknownAt===-1?chain.links:chain.links.slice(0,unknownAt),numbers=[...chain.links,...chain.unknown].map(({at})=>lineNumber(at)),width=Math.max(0,...numbers.map((n)=>n?.length??0)),gutter=" ".repeat(width),cited=(at,text)=>{let n=lineNumber(at);return n===void 0||text===void 0?[]:[`${n.padStart(width)} | ${text}`]},count=plural(hops.length,"hop","hops"),lines=unknownAt===-1?[`selected: ${test} ← ${chain.root} (${count}${chain.cause==="changed"?"":`, ${chain.cause}`})`]:[`selected: ${test} ← every change (${unknownAt===0?"its dependencies can't be read":`${count} to ${chain.links[unknownAt].node}, whose dependencies can't be read`})`];lines.push("");for(let link of hops){let configured=CONFIGURED[link.kind],where=configured===void 0?link.at??link.node:link.node,kind=configured??link.kind;lines.push(`${gutter}--> ${where} ${kind}`,...cited(link.at,link.text))}if(unknownAt===-1)return lines.push(`${gutter}● ${chain.root}: ${chain.cause}`),lines;let node=chain.links[unknownAt].node;for(let{cause,at,text,fix}of chain.unknown)lines.push(`${gutter}✗ ${at??node} ${cause}`,...cited(at,text),`${gutter} = fix: ${fix}`);return lines}var RENDER={tree,chain:chained,source:sourced};function moreLine(more,all){let shown=more.slice(0,LIST).join(", "),rest=more.length>LIST?", …":"";return`+ ${plural(more.length,"more change reaches","more changes reach")} this test: ${shown}${rest}${all?"":" (--all shows each chain)"}`}function unselectedMessage(explanation){let{from,changed,reaches,example}=explanation;if(from===void 0)return changed===0?"Not selected: nothing changed.":`Not selected: ${changed===1?"the changed file doesn't reach":`none of the ${changed} changed files reaches`} it.`;let counts=Object.entries(reaches??{}).map(([suite,count])=>`${count} ${suite}`),total=Object.values(reaches??{}).reduce((a,b)=>a+b,0);return[`Not selected by a change to ${from}: no chain reaches it.`,total===0?"Its chains reach no test.":`Its chains reach ${plural(total,"test","tests")} (${counts.join(", ")}), such as ${example}.`].join(`
|
|
13
16
|
`)}function formatExplanation(explanation,format="tree"){if(explanation.kind==="full")return[`The ${explanation.suite} suite runs in full:`,...explanation.reasons.map((reason)=>` ${reason}`)].join(`
|
|
14
17
|
`);if(explanation.kind==="unselected")return unselectedMessage(explanation);let{test,more,others}=explanation,render=RENDER[format],lines=render(test,explanation);if(more.length>0)lines.push(moreLine(more,others.length>0));for(let other of others)lines.push("",...render(test,other));return lines.join(`
|
|
15
18
|
`)}var USAGE=`Usage:
|
|
16
19
|
bivium plan [base] [--json] [--github] print the tests a change can affect
|
|
17
20
|
bivium run [base] [--suite <name>] run a suite's selected tests
|
|
18
21
|
bivium why <test> [file] [--base <ref>] the chain from a change (or file) to a test
|
|
19
|
-
[--format <f>] [--all]
|
|
20
|
-
bivium check [--max-unknown <n>]
|
|
22
|
+
[--format <f>] [--all] [--json]
|
|
23
|
+
bivium check [--max-unknown <n>] [--json]
|
|
24
|
+
what the graph can't read, and dead globs
|
|
25
|
+
bivium graph [--suite <name>] [--top <n>] [--json]
|
|
26
|
+
each file's test fan-in, and the graph
|
|
21
27
|
bivium --version print the version
|
|
28
|
+
bivium --help print this
|
|
22
29
|
|
|
23
30
|
base defaults to the config's base, else the upstream default branch.
|
|
31
|
+
Options go before or after the command.
|
|
24
32
|
|
|
25
33
|
Options:
|
|
26
34
|
--config <file> config file (default: bivium.config.{ts,mts,mjs,js,json})
|
|
27
35
|
--cwd <dir> repository (default: the current directory)
|
|
28
36
|
--no-cache read every file; don't read or write the extraction cache
|
|
29
|
-
--suite <name> for run: the suite (default: the first one)
|
|
30
|
-
|
|
37
|
+
--suite <name> for run: the suite (default: the first one); for graph:
|
|
38
|
+
only this suite (default: every one)
|
|
39
|
+
--json for plan, why, check and graph: print JSON
|
|
31
40
|
--github for plan: also write each suite's selection to
|
|
32
41
|
$GITHUB_OUTPUT as <output>=all|none|<files>
|
|
33
42
|
--base <ref> for why and check: the base ref
|
|
34
43
|
--format <f> for why: tree (default), chain (from the change to the
|
|
35
|
-
test)
|
|
44
|
+
test), source (each hop's line of source) or json
|
|
36
45
|
--all for why: every change's chain to the test, not only the
|
|
37
46
|
shortest
|
|
38
47
|
--max-unknown <n> for check: fail when more unknown nodes than this reach
|
|
39
|
-
a test
|
|
40
|
-
|
|
48
|
+
a test
|
|
49
|
+
--top <n> for graph: how many files to list per suite (default: 10)
|
|
50
|
+
|
|
51
|
+
Exit status: 0 done; 1 check found problems; 2 a usage or configuration
|
|
52
|
+
error. run exits with its command's status.
|
|
53
|
+
|
|
54
|
+
Examples:
|
|
55
|
+
bivium plan origin/main --json
|
|
56
|
+
bivium why tests/Button.test.ts src/Button.svelte --format chain
|
|
57
|
+
bivium check --json`,WHITESPACE=/\s+/,VALUED=new Set(["--config","--cwd","--suite","--base","--format","--max-unknown","--top"]),COMMON=["--config","--cwd","--no-cache"],FLAGS={plan:[...COMMON,"--json","--github"],run:[...COMMON,"--suite"],why:[...COMMON,"--base","--json","--format","--all"],check:[...COMMON,"--base","--max-unknown","--json"],graph:[...COMMON,"--suite","--top","--json"]},POSITIONAL={plan:1,run:1,why:2,check:0,graph:0};function parseArgs(command,argv){let known=FLAGS[command]??[],flags=new Map,positional=[];for(let i=0;i<argv.length;i++){let arg=argv[i];if(!arg.startsWith("--")){positional.push(arg);continue}if(!known.includes(arg))throw Error(`bivium ${command}: unknown option ${arg}`);if(!VALUED.has(arg)){flags.set(arg,"");continue}let value=argv[++i];if(value===void 0||value.startsWith("--"))throw Error(`bivium: ${arg} needs a value`);flags.set(arg,value)}if(positional.length>(POSITIONAL[command]??0))throw Error(`bivium ${command}: unexpected ${positional.at(-1)}`);return{flags,positional}}function commandFor(run,files){let words=run.split(WHITESPACE).filter(Boolean),at=words.indexOf("{files}");if(at===-1)return[...words,...files];return[...words.slice(0,at),...files,...words.slice(at+1)]}function logSelection(label,selection,total,forced){let files=total===1?"file":"files",count;if(selection.mode==="some")count=`${selection.files.length} of ${total} ${files}`;else if(selection.mode==="none")count="none";else if(forced)count="all (full run)";else count=`all ${total} ${files} (each reaches a change)`;if(console.log(`${label}: ${count}`),selection.mode==="some")for(let file of selection.files)console.log(` ${file}`)}function logPlan({plan,narrowed}){for(let reason of plan.reasons)console.log(`Full run: ${reason}`);for(let line of plan.packages)console.log(line);for(let{narrower,result}of narrowed)if("note"in result&&result.note)console.log(`${narrower.name}: ${result.note}`);for(let[name,selection]of Object.entries(plan.suites)){let total=plan.totals[name]??0;logSelection(`${name} tests`,selection,total,plan.full.includes(name))}}function writeOutputs(config,{plan}){let output=process.env.GITHUB_OUTPUT;if(!output)throw Error("bivium: GITHUB_OUTPUT is not set");let lines=config.suites.map((suite)=>`${suite.output}=${formatSelection(plan.suites[suite.name])}
|
|
58
|
+
`);appendFileSync(output,lines.join(""))}async function inspect(command,{flags,positional}){let format=flags.get("--format")??"tree";if(format!=="json"&&!isFormat(format))throw Error("bivium why: --format takes tree, chain, source or json");let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:flags.get("--base")??(command==="check"?"HEAD":void 0),configFile:flags.get("--config")}),computed=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1}});if(command==="check"){let maxFlag=flags.get("--max-unknown"),max=maxFlag===void 0?void 0:Number(maxFlag);if(max!==void 0&&!Number.isInteger(max))throw Error("bivium check: --max-unknown takes a whole number");let report=await check(root,config,computed);return console.log(flags.has("--json")?JSON.stringify(report,null,2):formatReport(report,max)),failed(report,max)?1:0}let[test,file]=positional;if(test===void 0)throw Error("bivium why: which test?");let explanation=await explain(root,config,computed,test,file,{all:flags.has("--all")});return console.log(flags.has("--json")||format==="json"?JSON.stringify(explanation,null,2):formatExplanation(explanation,format)),0}async function graphCommand({flags}){let top=Number(flags.get("--top")??"10");if(!Number.isInteger(top)||top<0)throw Error("bivium graph: --top takes a whole number");let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:"HEAD",configFile:flags.get("--config")}),name=flags.get("--suite"),suites=name===void 0?config.suites:config.suites.filter((suite)=>suite.name===name);if(suites.length===0)throw Error(`bivium: no suite "${name}"`);let{graph}=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1}}),report=graphReport(graph,suites);return console.log(flags.has("--json")?JSON.stringify(report,null,2):formatGraph(report,top)),0}async function runCommand(command,{flags,positional}){let{root,base,config}=await prepare({cwd:flags.get("--cwd"),base:positional[0],configFile:flags.get("--config")}),suiteName=flags.get("--suite"),suite=suiteName===void 0?config.suites[0]:config.suites.find((candidate)=>candidate.name===suiteName);if(!suite)throw Error(`bivium: no suite "${suiteName}"`);let computed=await computePlan(root,base,config,{...flags.has("--no-cache")&&{cache:!1},...command==="run"&&{suites:[suite.name]},mergeBase:command==="plan"&&flags.has("--json")});if(command==="plan"){if(flags.has("--json")){let{suites,reasons,causes,totals,packages}=computed.plan,narrowed=computed.narrowed.map((ran)=>({name:ran.narrower.name,result:ran.result}));console.log(JSON.stringify({base,mergeBase:await computed.mergeBase(),changed:computed.changed,suites,reasons,causes,totals,packages,narrowed},null,2))}else logPlan(computed);if(flags.has("--github"))writeOutputs(config,computed);return 0}if(logPlan(computed),!suite.run)throw Error(`bivium: suite "${suite.name}" has no run command`);let selection=computed.plan.suites[suite.name];if(selection.mode==="none")return console.log(`No ${suite.name} tests affected against ${base}; skipping.`),0;let[program,...args]=commandFor(suite.run,selection.mode==="some"?selection.files:[]);return spawnSync(program,args,{cwd:root,stdio:"inherit"}).status??1}function commandAt(argv){for(let i=0;i<argv.length;i++){let arg=argv[i];if(!arg.startsWith("-"))return i;if(VALUED.has(arg))i++}return-1}async function main(argv){if(argv.includes("--help")||argv.includes("-h"))return console.log(USAGE),0;if(argv.includes("--version")||argv.includes("-v"))return console.log(version),0;let at=commandAt(argv),command=at===-1?void 0:argv[at];if(command==="help")return console.log(USAGE),0;if(command===void 0){let first=argv[0],why=first===void 0?"":`unknown option ${first}
|
|
59
|
+
|
|
60
|
+
`;return console.error(`bivium: ${why}${USAGE}`),2}if(!(command in FLAGS))return console.error(`bivium: unknown command "${command}"
|
|
41
61
|
|
|
42
|
-
${USAGE}`),1;try{let args=parseArgs(command,rest);if(command==="why"||command==="check")return await inspect(command,args);return await runCommand(command,args)}catch(error){return console.error(error instanceof Error?error.message:String(error)),2}}process.exitCode=await main(process.argv.slice(2));
|
|
62
|
+
${USAGE}`),2;let rest=[...argv.slice(0,at),...argv.slice(at+1)];try{let args=parseArgs(command,rest);if(command==="why"||command==="check")return await inspect(command,args);if(command==="graph")return await graphCommand(args);return await runCommand(command,args)}catch(error){return console.error(error instanceof Error?error.message:String(error)),2}}process.exitCode=await main(process.argv.slice(2));
|