@trops/dash-check 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +68 -8
  2. package/examples/changes-match-plan.check.js +12 -4
  3. package/examples/commits-scoped.bad.json +5 -0
  4. package/examples/commits-scoped.check.json +6 -0
  5. package/examples/commits-scoped.sample.json +5 -0
  6. package/examples/lockfile-explained.bad.json +11 -0
  7. package/examples/lockfile-explained.check.json +6 -0
  8. package/examples/lockfile-explained.sample.json +11 -0
  9. package/examples/max-growth.bad.json +8 -0
  10. package/examples/max-growth.check.json +6 -0
  11. package/examples/max-growth.sample.json +8 -0
  12. package/examples/new-tests-are-run.bad.json +4 -0
  13. package/examples/new-tests-are-run.check.json +7 -0
  14. package/examples/new-tests-are-run.sample.json +4 -0
  15. package/examples/no-new-debt.bad.json +8 -0
  16. package/examples/no-new-debt.check.json +14 -0
  17. package/examples/no-new-debt.sample.json +8 -0
  18. package/examples/plan-scope.bad.json +4 -0
  19. package/examples/plan-scope.check.json +6 -0
  20. package/examples/plan-scope.sample.json +4 -0
  21. package/examples/source-has-tests.bad.json +4 -0
  22. package/examples/source-has-tests.check.json +6 -0
  23. package/examples/source-has-tests.sample.json +4 -0
  24. package/examples/test-script-is-real.bad.json +6 -0
  25. package/examples/test-script-is-real.check.json +6 -0
  26. package/examples/test-script-is-real.sample.json +6 -0
  27. package/examples/validate-leaves-tree-clean.bad.json +6 -0
  28. package/examples/validate-leaves-tree-clean.check.json +7 -0
  29. package/examples/validate-leaves-tree-clean.sample.json +6 -0
  30. package/helpers/files.js +52 -2
  31. package/helpers/git.js +265 -2
  32. package/helpers/index.d.ts +114 -4
  33. package/helpers/node.js +192 -2
  34. package/helpers/plan.js +86 -2
  35. package/index.d.ts +22 -0
  36. package/lib/adapters/git.js +80 -4
  37. package/lib/helper.js +18 -1
  38. package/package.json +1 -1
package/README.md CHANGED
@@ -121,11 +121,13 @@ You can also call `fail(message, { at })` to fail with a message and a location,
121
121
  | `ctx.env` | The environment, `DASH_*` included |
122
122
  | `ctx.fs` | `exists(p)`, `read(p)`, `readJson(p)`, `list(glob)`, `dirExists(p)`, relative to the workspace |
123
123
  | `ctx.run(cmd, { timeoutSec })` | Runs a command in the workspace: `{ code, stdout, stderr, timedOut }` |
124
- | `ctx.git` | `branch()`, `isClean()`, `uncommitted()`, `commitsSince(ref)`, `changedFiles(ref)`, `lastCommitMessage()`, `remoteHas(branch)`, `defaultBranch()`, `fileAt(ref, path)` |
124
+ | `ctx.git` | `branch()`, `isClean()`, `uncommitted()`, `commitsSince(ref)`, `changedFiles(ref)`, `addedLines(ref)`, `commits(ref)`, `lastCommitMessage()`, `remoteHas(branch)`, `defaultBranch()`, `fileAt(ref, path)` |
125
125
  | `ctx.github` | `pr(urlOrNumber)`, `checksFor(sha)`, `waitForChecks(sha, { timeoutSec, noChecksAfterSec })`, using `GH_TOKEN`. A failure says the HTTP code and what to do |
126
126
  | `ctx.tool(provider, name, args)` | A read-only call to one of the bot's providers (Jira, …). Only Dash can answer it, so outside Dash it fails and says so |
127
127
  | `ctx.get(path)`, `ctx.fill(text)`, `ctx.when(expr)` | Read a value by path (`"handoff.files"`), fill `"{placeholders}"`, test a `when` |
128
128
 
129
+ `changedFiles(ref)` and `addedLines(ref)` see the same work: what's committed since where the branch left `ref`, plus uncommitted and untracked files. `addedLines` gives `[{ file, line, text }]`, numbered as the file is now (an untracked file counts whole; binary files are left out), so a check can judge only what the work added. `commits(ref)` gives `[{ sha, subject, message, parents, files }]` for `ref..HEAD`, oldest first.
130
+
129
131
  In a test, give the context what it can't have outside Dash:
130
132
 
131
133
  ```js
@@ -151,11 +153,11 @@ check("the work is ready for review", async (ctx) => {
151
153
  | Group | Helpers |
152
154
  |---|---|
153
155
  | handoff | `has({ keys })`, `status({ is })`, `eachHas({ list, keys })` |
154
- | plan | `hasSections({ key, sections })`, `acceptanceEachHasTest({ acceptance, tests })` |
155
- | git | `onBranch({ branch })`, `committedSince({ base, min })`, `clean()`, `changedOnly({ globs, base })`, `noChangesTo({ globs, base })` |
156
- | files | `exist({ paths })`, `contain({ path, text })`, `noneMatch({ glob, pattern })` |
156
+ | plan | `hasSections({ key, sections })`, `acceptanceEachHasTest({ acceptance, tests })`, `evidenceForAcceptance({ key, acceptanceKey, requireSearch, when })`, `noOpenDecisions({ key, when })` (see below) |
157
+ | git | `onBranch({ branch })`, `committedSince({ base, min })`, `clean()`, `changedOnly({ globs, base })`, `noChangesTo({ globs, base })`, and the factory checks below |
158
+ | files | `exist({ paths })`, `contain({ path, text })`, `noneMatch({ glob, pattern })`, `maxGrowth(…)` |
157
159
  | commands | `passes({ command, timeoutSec })`, `outputMatches({ command, pattern })` |
158
- | node | `testsPass({ command })`, `lintPasses({ command })`, `noNewDependencies({ base, allow })` |
160
+ | node | `testsPass({ command })`, `lintPasses({ command })`, `noNewDependencies({ base, allow })`, `lockfileExplained(…)`, `testScriptIsReal(…)`, `newTestsAreRun(…)` |
159
161
  | github | `prOpen({ prKey })`, `ciPassed({ prKey, timeoutSec, noChecksAfterSec, ifNoChecks })` |
160
162
  | tracker | `ticketExists({ provider, tool, idArg, id })`, `ticketHasLabel({ label, … })` (these need Dash's `ctx.tool`) |
161
163
 
@@ -167,6 +169,55 @@ A few things every helper does for you:
167
169
  - **`message`.** Every helper takes `message`, which replaces its failure text. Where the failure was (`src/index.js:12`) is kept.
168
170
  - **Errors become failures.** If a helper throws (the folder isn't a git repo, GitHub says 404), the failure says why, and the check goes on to the next step.
169
171
 
172
+ ### Plan checks: is the plan ready to code?
173
+
174
+ Checks on a planning bot's handoff, before anyone writes code. They read only the handoff (no folder, no git), and judge it only when its `status` is one of `when` (default `ok`); any other status passes with "No plan (<status>)", so a bot that answers `none` or `ask` isn't failed for having no plan.
175
+
176
+ | Helper | Fails when | Params (defaults) |
177
+ |---|---|---|
178
+ | `plan.evidenceForAcceptance` | The plan has no `notYetDone`; its `searchedDone` (what it searched for done work, and found) is empty; an acceptance item has no `missing` entry `{ acceptance, read, why }` with the same text and a non-empty `read` and `why`; or it says some code was "not read" | `key` (`notYetDone`), `acceptanceKey` (`acceptance`), `requireSearch` (true), `when` (`ok`; empty judges every handoff) |
179
+ | `plan.noOpenDecisions` | The plan has no `openDecisions` list, or the list isn't empty (then the bot should ask, not plan) | `key` (`openDecisions`), `when` (`ok`) |
180
+
181
+ ```json
182
+ { "use": "plan.evidenceForAcceptance" }
183
+ { "use": "plan.noOpenDecisions", "with": { "when": "ok, split" } }
184
+ ```
185
+
186
+ ### Factory checks: did the bot do only what it planned?
187
+
188
+ Checks for a code factory, where a planning bot names the files and a coding bot changes them. Each works on any repo: all it needs is git and, for the plan checks, a handoff that lists files. Every one compares with `base` (default `{repo.baseBranch}`; empty means the repo's default branch, through `origin/` when the remote has it), and every one judges only **what the work changed**, so existing debt in the repo doesn't fail it.
189
+
190
+ | Helper | Fails when | Params (defaults) |
191
+ |---|---|---|
192
+ | `git.changesMatchPlan` | A changed file isn't in the plan. A lockfile outside the plan passes only when `node.lockfileExplained` would | `planKeys` (`files, newFiles, tests`), `alsoAllow`, `lockfiles` (`package-lock.json, npm-shrinkwrap.json, yarn.lock, pnpm-lock.yaml`), `base` |
193
+ | `git.commitsScoped` | A commit (not just the total diff) touches files outside the plan, or its message doesn't mention the item. Merge commits are skipped | the same, plus `mentions` (`{item.id}`). `planKeys: ""` or `mentions: ""` turns that half off |
194
+ | `node.lockfileExplained` | The lockfile changed, but no dependency section (`dependencies`, `devDependencies`, `optionalDependencies`, `peerDependencies`) of `package.json` did. Changing only the root `version` fields (a release) is fine. `yarn.lock` and `pnpm-lock.yaml` need a dependency change for any change | `lockfile` (`package-lock.json`), `manifest` (the `package.json` next to it, plus any changed `package.json` below it, for workspaces), `base` |
195
+ | `git.sourceHasTests` | A changed source file has no changed test: its own (`paired`), or any (`any`) | `sources` (`src/**` and `lib/**` JS/TS, not tests, stories or `.d.ts`), `tests`, `testPattern` (`<dir>/<name>.{test,spec}.*`, `<dir>/__tests__/<name>.*`, `{test,tests}/**/<name>.{test,spec}.*`, `{test,tests}/**/<name>.*`), `mode` (`paired`), `exempt` |
196
+ | `git.noNewMatches` | An **added** line matches a pattern. The diff-aware `files.noneMatch`: the 600 `console.log`s already there don't count, a new one does | `glob` (a list; `!glob` leaves out), `pattern`, `base` |
197
+ | `files.maxGrowth` | A changed file is new and over `maxLines`, crosses `maxLines`, or was already over it and grew by more than `maxAdded` | `glob` (JS/TS), `maxLines` (800), `maxAdded` (50), `exempt`, `base` |
198
+ | `git.validateLeavesTreeClean` | The tree isn't clean before validating, the command fails, or it leaves files changed (a formatter's `--write`, `npm install --save`) | `command` (`npm test`), `timeoutSec` (1800), `allowDirtyBefore` (false) |
199
+ | `node.testScriptIsReal` | The `test` script is missing, empty, a no-op (`exit 0`, `true`, `echo …`, npm's placeholder) or hides its failures (`… \|\| true`). With `run`, also when it reports fewer than `minTests` tests | `script` (`test`), `run` (false), `minTests` (1), `timeoutSec` (900) |
200
+ | `node.newTestsAreRun` | A **new** test file isn't named in a runner file, isn't matched by a glob written in one (`node --test 'test/*.test.js'`), and isn't in `autoGlobs` | `tests` (`**/*.{test,spec}.{js,cjs,mjs,jsx,ts,tsx}`), `runnerFiles` (`package.json`), `autoGlobs` (what the runner finds by itself, e.g. `src/**/*.test.js` for jest), `base` |
201
+
202
+ A coding bot's step might run them in this order:
203
+
204
+ ```json
205
+ {
206
+ "name": "The Coder did only what it planned",
207
+ "steps": [
208
+ { "use": "git.validateLeavesTreeClean", "with": { "command": "npm run ci" } },
209
+ { "use": "git.changesMatchPlan", "with": { "alsoAllow": "CHANGELOG.md" } },
210
+ { "use": "git.commitsScoped" },
211
+ { "use": "git.noChangesTo", "with": { "globs": ".github/workflows/**, .dash/checks/**" }, "label": "Gates unchanged" },
212
+ { "use": "git.sourceHasTests", "with": { "exempt": "**/index.js" } },
213
+ { "use": "node.newTestsAreRun", "with": { "runnerFiles": "package.json, scripts/ci.sh" } },
214
+ { "use": "git.noNewMatches", "with": { "glob": "src/**, !**/*.test.*", "pattern": "console\\.log\\(|\\b(TODO|FIXME)\\b" },
215
+ "message": "Remove the console.log or TODO you added" },
216
+ { "use": "files.maxGrowth" }
217
+ ]
218
+ }
219
+ ```
220
+
170
221
  ### Writing your own helper
171
222
 
172
223
  Put a file in `.dash/checks/helpers/` in your repo. Build it only from `ctx` and `expect`, never from `fs`, `child_process` or `fetch` directly:
@@ -195,7 +246,7 @@ module.exports = defineHelper({
195
246
  });
196
247
  ```
197
248
 
198
- Param types are `text`, `number`, `boolean`, `select` (with `options`), `path`, `glob`, `regex` and `list`. Values are converted to the type before `run` gets them: a `list` given as `"a, b"` arrives as `["a", "b"]`, and a `regex` arrives as a `RegExp`.
249
+ Param types are `text`, `number`, `boolean`, `select` (with `options`), `path`, `glob`, `regex` and `list`. Values are converted to the type before `run` gets them: a `list` given as `"a, b"` arrives as `["a", "b"]` (a glob's `{a,b}` stays whole: `"**/*.{js,ts}, !dist/**"` is two globs), and a `regex` arrives as a `RegExp`.
199
250
 
200
251
  Then use it from code with `helper("team.changelogUpdated")(ctx, { … })`, or from a recipe with `{ "use": "team.changelogUpdated" }`. It also shows in `dash-check --list-helpers`, and so in Dash's check composer.
201
252
 
@@ -286,7 +337,7 @@ A `.check.js` file also runs by itself, `node .dash/checks/validate.check.js`, t
286
337
 
287
338
  ## Examples
288
339
 
289
- [`examples/`](examples) holds the Code Factory's checks, written with dash-check. Each has a `.sample.json` that passes and a `.bad.json` that fails:
340
+ [`examples/`](examples) holds the Code Factory's checks, written with dash-check. Each has a `.sample.json` that passes and a `.bad.json` that fails. The ones that look at a repo say in `_about` what the repo looks like (the tests build it):
290
341
 
291
342
  | Example | Proves | Reads |
292
343
  |---|---|---|
@@ -297,12 +348,21 @@ A `.check.js` file also runs by itself, `node .dash/checks/validate.check.js`, t
297
348
  | `every-acceptance-has-a-test` | Every acceptance item has a test; the plan names real files | handoff, workspace |
298
349
  | `validate` | Lint and tests pass, reported apart | run |
299
350
  | `work-committed` | The work is committed, and the commit names the item | git, item |
300
- | `changes-match-plan` | Only the planned files changed | git, handoff, row |
351
+ | `changes-match-plan` | Only the planned files changed; a lockfile only with `node.lockfileExplained` | git, fs, handoff, row |
301
352
  | `pr-ci` | The PR's CI passed (no CI is a failure) | github |
302
353
  | `merge-outcome` | The PR was merged only when allowed | github, settings |
303
354
  | `workspace-cleaned` | The job's folder is gone | workspace |
304
355
  | `jira-comment-from-job` | The ticket got this job's comment | tool, job |
305
356
  | `ready-for-review.check.json` | The composer mockup's recipe | git, run, fs, handoff |
357
+ | `plan-scope.check.json` | `git.changesMatchPlan` | git, fs, handoff |
358
+ | `commits-scoped.check.json` | `git.commitsScoped` | git, handoff, item |
359
+ | `lockfile-explained.check.json` | `node.lockfileExplained` | git, fs |
360
+ | `source-has-tests.check.json` | `git.sourceHasTests`, its mode a team setting | git, fs, settings |
361
+ | `no-new-debt.check.json` | `git.noNewMatches`: no new console.log, TODO or eslint-disable | git |
362
+ | `max-growth.check.json` | `files.maxGrowth` | git, fs |
363
+ | `validate-leaves-tree-clean.check.json` | `git.validateLeavesTreeClean` | git, run |
364
+ | `test-script-is-real.check.json` | `node.testScriptIsReal` | fs, run |
365
+ | `new-tests-are-run.check.json` | `node.newTestsAreRun` | git, fs, settings |
306
366
  | `helpers/changelog.js` | A team's own helper | git |
307
367
 
308
368
  ## License
@@ -1,10 +1,18 @@
1
1
  // Walkthrough 8. Before the Reviewer: "Only the planned files changed".
2
- // Lives in the shared package. Reads: git, handoff, row.
2
+ // Lives in the shared package. Reads: git, fs, handoff, row.
3
+ // A lockfile the plan didn't name passes only when node.lockfileExplained
4
+ // does: a dependency changed, or only its version did. (git.changesMatchPlan
5
+ // does all of this in one step.)
3
6
  const { check, expect } = require("@trops/dash-check");
7
+ const { node } = require("@trops/dash-check/helpers");
4
8
 
5
- check("only the planned files changed", async ({ git, handoff, row }) => {
9
+ check("only the planned files changed", async (ctx) => {
10
+ const { git, handoff, row } = ctx;
6
11
  const changed = await git.changedFiles(`origin/${row.repo?.baseBranch || "main"}`);
7
12
  const allowed = new Set([...(handoff.files ?? []), ...(handoff.newFiles ?? []), ...(handoff.tests ?? []).map((t) => t.file)]);
8
- const extra = changed.filter((f) => !allowed.has(f) && !/package-lock\.json$/.test(f));
9
- expect(extra, "files the plan didn't name").toBeEmpty(`Changed files the plan didn't name: ${extra.join(", ")}`);
13
+ const extra = changed.filter((f) => !allowed.has(f));
14
+ const lockfiles = extra.filter((f) => /(^|\/)package-lock\.json$/.test(f));
15
+ for (const lockfile of lockfiles) await node.lockfileExplained(ctx, { lockfile });
16
+ const rest = extra.filter((f) => !lockfiles.includes(f));
17
+ expect(rest, "files the plan didn't name").toBeEmpty(`Changed files the plan didn't name: ${rest.join(", ")}`);
10
18
  });
@@ -0,0 +1,5 @@
1
+ {
2
+ "input": { "answer": "```json\n{ \"files\": [\"src/a.js\", \"src/a.test.js\"] }\n```" },
3
+ "item": { "id": "DASH-98" },
4
+ "row": { "repo": { "baseBranch": "main" } }
5
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "Each commit is scoped",
3
+ "steps": [
4
+ { "use": "git.commitsScoped", "with": { "base": "{repo.baseBranch}", "mentions": "{item.id}" } }
5
+ ]
6
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "input": { "answer": "```json\n{ \"files\": [\"src/a.js\", \"src/a.test.js\"] }\n```" },
3
+ "item": { "id": "DASH-97" },
4
+ "row": { "repo": { "baseBranch": "main" } }
5
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "_about": "Run on a branch whose package-lock.json changed (node_modules/foo) while package.json's dependencies didn't.",
3
+ "row": {
4
+ "repo": {
5
+ "baseBranch": "main"
6
+ }
7
+ },
8
+ "workspace": {
9
+ "dir": "."
10
+ }
11
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "The lockfile changed only with a dependency",
3
+ "steps": [
4
+ { "use": "node.lockfileExplained", "with": { "base": "{repo.baseBranch}" } }
5
+ ]
6
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "_about": "Run on a branch whose package-lock.json changed along with a dependency in package.json (or only in its version).",
3
+ "row": {
4
+ "repo": {
5
+ "baseBranch": "main"
6
+ }
7
+ },
8
+ "workspace": {
9
+ "dir": "."
10
+ }
11
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "_about": "Run on a branch that added 60 lines to a file already past 800.",
3
+ "row": {
4
+ "repo": {
5
+ "baseBranch": "main"
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "No file grows too big",
3
+ "steps": [
4
+ { "use": "files.maxGrowth", "with": { "base": "{repo.baseBranch}", "maxLines": 800, "maxAdded": 50 } }
5
+ ]
6
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "_about": "Run on a branch whose changed files stay under 800 lines.",
3
+ "row": {
4
+ "repo": {
5
+ "baseBranch": "main"
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "row": { "repo": { "baseBranch": "main" } },
3
+ "settings": { "autoGlobs": "" }
4
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "New tests are run",
3
+ "steps": [
4
+ { "use": "node.newTestsAreRun",
5
+ "with": { "base": "{repo.baseBranch}", "runnerFiles": "package.json, scripts/ci.sh", "autoGlobs": "{autoGlobs}" } }
6
+ ]
7
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "row": { "repo": { "baseBranch": "main" } },
3
+ "settings": { "autoGlobs": "src/**/*.test.js" }
4
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "_about": "Run on a branch that added a console.log and a TODO.",
3
+ "row": {
4
+ "repo": {
5
+ "baseBranch": "main"
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "name": "No new TODO, console.log or disables",
3
+ "steps": [
4
+ { "use": "git.noNewMatches",
5
+ "with": { "glob": "src/**/*.js, !**/*.test.js", "pattern": "console\\.log\\(", "base": "{repo.baseBranch}" },
6
+ "message": "Remove the console.log you added" },
7
+ { "use": "git.noNewMatches",
8
+ "with": { "glob": "**/*.{js,jsx,ts,tsx}", "pattern": "\\b(TODO|FIXME|HACK|XXX)\\b", "base": "{repo.baseBranch}" },
9
+ "message": "Do the TODO or file a ticket; don't commit it" },
10
+ { "use": "git.noNewMatches",
11
+ "with": { "glob": "**/*.{js,jsx,ts,tsx}", "pattern": "eslint-disable|@ts-ignore|\\.only\\(|debugger;", "base": "{repo.baseBranch}" },
12
+ "message": "Fix the code instead of turning the check off" }
13
+ ]
14
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "_about": "Run on a branch that added no TODO, console.log or eslint-disable (old ones are fine).",
3
+ "row": {
4
+ "repo": {
5
+ "baseBranch": "main"
6
+ }
7
+ }
8
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "input": { "answer": "```json\n{ \"files\": [\"src/a.js\"] }\n```" },
3
+ "row": { "repo": { "baseBranch": "main" } }
4
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "Only the planned files changed",
3
+ "steps": [
4
+ { "use": "git.changesMatchPlan", "with": { "base": "{repo.baseBranch}", "alsoAllow": "CHANGELOG.md" } }
5
+ ]
6
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "input": { "answer": "```json\n{ \"files\": [\"src/a.js\"], \"tests\": [{ \"acceptance\": \"A works\", \"file\": \"src/a.test.js\" }] }\n```" },
3
+ "row": { "repo": { "baseBranch": "main" } }
4
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "row": { "repo": { "baseBranch": "main" } },
3
+ "settings": { "testsMode": "paired" }
4
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "Changed source has tests",
3
+ "steps": [
4
+ { "use": "git.sourceHasTests", "with": { "base": "{repo.baseBranch}", "mode": "{testsMode}", "exempt": "**/index.js" } }
5
+ ]
6
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "row": { "repo": { "baseBranch": "main" } },
3
+ "settings": { "testsMode": "any" }
4
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "_about": "Run in a repo whose test script is \"exit 0\".",
3
+ "workspace": {
4
+ "dir": "."
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "npm test runs tests",
3
+ "steps": [
4
+ { "use": "node.testScriptIsReal", "with": { "script": "test", "run": true, "minTests": 1 } }
5
+ ]
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "_about": "Run in a repo whose npm test runs and reports its tests.",
3
+ "workspace": {
4
+ "dir": "."
5
+ }
6
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "_about": "Run in a repo whose npm run ci runs a formatter that rewrites a tracked file.",
3
+ "workspace": {
4
+ "dir": "."
5
+ }
6
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "Validate doesn't rewrite files",
3
+ "steps": [
4
+ { "use": "git.validateLeavesTreeClean", "with": { "command": "npm run ci", "timeoutSec": 1800 },
5
+ "message": "Validation rewrote tracked files (a formatter's --write, or npm install --save): fix the script, and don't commit them" }
6
+ ]
7
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "_about": "Run in a repo whose npm run ci only checks.",
3
+ "workspace": {
4
+ "dir": "."
5
+ }
6
+ }
package/helpers/files.js CHANGED
@@ -3,7 +3,8 @@
3
3
  */
4
4
  "use strict";
5
5
 
6
- const { defineHelper, expect, fail, note } = require("..");
6
+ const { defineHelper, expect, fail, note, matchGlob } = require("..");
7
+ const { baseRef } = require("./git");
7
8
 
8
9
  const exist = defineHelper({
9
10
  id: "files.exist",
@@ -71,4 +72,53 @@ const noneMatch = defineHelper({
71
72
  },
72
73
  });
73
74
 
74
- module.exports = { exist, contain, noneMatch };
75
+ /** Lines in a text ("a\nb\n" is 2), or null for binary. */
76
+ const lineCount = (text) => {
77
+ if (text === null || text === undefined) return null;
78
+ const t = String(text);
79
+ if (t.includes("\0")) return null;
80
+ if (!t) return 0;
81
+ return t.split(/\r?\n/).length - (/\r?\n$/.test(t) ? 1 : 0);
82
+ };
83
+
84
+ const maxGrowth = defineHelper({
85
+ id: "files.maxGrowth",
86
+ group: "Files",
87
+ label: "No file grows too big",
88
+ description: "A changed file stays under a size, and a big file doesn't grow much",
89
+ sentence: "no changed {glob} file since {base} grows past {maxLines} lines, or by more than {maxAdded} when already past",
90
+ params: {
91
+ glob: { type: "list", label: "Files", default: ["**/*.{js,jsx,ts,tsx,mjs,cjs}"] },
92
+ maxLines: { type: "number", label: "Most lines", default: 800 },
93
+ maxAdded: { type: "number", label: "Most added to a big file", default: 50 },
94
+ exempt: { type: "list", label: "Exempt", description: "Files that may grow, e.g. generated ones" },
95
+ base: { type: "text", label: "Base branch", default: "{repo.baseBranch}", description: "Empty: the repo's default branch" },
96
+ },
97
+ reads: ["git", "fs"],
98
+ async run(ctx, { glob, maxLines, maxAdded, exempt, base }) {
99
+ const ref = await baseRef(ctx, base);
100
+ const files = (await ctx.git.changedFiles(ref)).filter((f) => matchGlob(glob, f) && !(exempt.length && matchGlob(exempt, f)));
101
+ let seen = 0;
102
+ let big = 0;
103
+ for (const f of files) {
104
+ if (!(await ctx.fs.exists(f))) continue;
105
+ const now = lineCount(await ctx.fs.read(f));
106
+ if (now === null) continue;
107
+ seen++;
108
+ if (now <= maxLines) continue;
109
+ big++;
110
+ const before = lineCount(await ctx.git.fileAt(ref, f));
111
+ if (before === null) {
112
+ fail(`${f} is new and has ${now} lines (most: ${maxLines}): split it into smaller modules`, { received: now, expected: maxLines });
113
+ } else if (before <= maxLines) {
114
+ fail(`${f} grew past ${maxLines} lines (${before} → ${now}): put the new code in its own module`, { received: now, expected: maxLines });
115
+ } else if (now - before > maxAdded) {
116
+ fail(`${f} already has ${before} lines and grew by ${now - before} (most: ${maxAdded}): put the new code in its own module`, { received: now - before, expected: maxAdded });
117
+ }
118
+ }
119
+ if (!big) note(`${seen} changed file${seen === 1 ? "" : "s"} checked, none past ${maxLines} lines`);
120
+ else note(`${seen} changed file${seen === 1 ? "" : "s"} checked; ${big} past ${maxLines} lines grew ${maxAdded} or fewer`);
121
+ },
122
+ });
123
+
124
+ module.exports = { exist, contain, noneMatch, maxGrowth, lineCount };