@trops/dash-check 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -7
- package/examples/changes-match-plan.check.js +12 -4
- package/examples/commits-scoped.bad.json +5 -0
- package/examples/commits-scoped.check.json +6 -0
- package/examples/commits-scoped.sample.json +5 -0
- package/examples/lockfile-explained.bad.json +11 -0
- package/examples/lockfile-explained.check.json +6 -0
- package/examples/lockfile-explained.sample.json +11 -0
- package/examples/max-growth.bad.json +8 -0
- package/examples/max-growth.check.json +6 -0
- package/examples/max-growth.sample.json +8 -0
- package/examples/new-tests-are-run.bad.json +4 -0
- package/examples/new-tests-are-run.check.json +7 -0
- package/examples/new-tests-are-run.sample.json +4 -0
- package/examples/no-new-debt.bad.json +8 -0
- package/examples/no-new-debt.check.json +14 -0
- package/examples/no-new-debt.sample.json +8 -0
- package/examples/plan-scope.bad.json +4 -0
- package/examples/plan-scope.check.json +6 -0
- package/examples/plan-scope.sample.json +4 -0
- package/examples/source-has-tests.bad.json +4 -0
- package/examples/source-has-tests.check.json +6 -0
- package/examples/source-has-tests.sample.json +4 -0
- package/examples/test-script-is-real.bad.json +6 -0
- package/examples/test-script-is-real.check.json +6 -0
- package/examples/test-script-is-real.sample.json +6 -0
- package/examples/validate-leaves-tree-clean.bad.json +6 -0
- package/examples/validate-leaves-tree-clean.check.json +7 -0
- package/examples/validate-leaves-tree-clean.sample.json +6 -0
- package/helpers/files.js +52 -2
- package/helpers/git.js +265 -2
- package/helpers/index.d.ts +91 -3
- package/helpers/node.js +192 -2
- package/index.d.ts +22 -0
- package/lib/adapters/git.js +80 -4
- package/lib/helper.js +18 -1
- 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
|
|
@@ -152,10 +154,10 @@ check("the work is ready for review", async (ctx) => {
|
|
|
152
154
|
|---|---|
|
|
153
155
|
| handoff | `has({ keys })`, `status({ is })`, `eachHas({ list, keys })` |
|
|
154
156
|
| 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 })` |
|
|
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,41 @@ 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
|
+
### Factory checks: did the bot do only what it planned?
|
|
173
|
+
|
|
174
|
+
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.
|
|
175
|
+
|
|
176
|
+
| Helper | Fails when | Params (defaults) |
|
|
177
|
+
|---|---|---|
|
|
178
|
+
| `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` |
|
|
179
|
+
| `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 |
|
|
180
|
+
| `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` |
|
|
181
|
+
| `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` |
|
|
182
|
+
| `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` |
|
|
183
|
+
| `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` |
|
|
184
|
+
| `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) |
|
|
185
|
+
| `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) |
|
|
186
|
+
| `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` |
|
|
187
|
+
|
|
188
|
+
A coding bot's step might run them in this order:
|
|
189
|
+
|
|
190
|
+
```json
|
|
191
|
+
{
|
|
192
|
+
"name": "The Coder did only what it planned",
|
|
193
|
+
"steps": [
|
|
194
|
+
{ "use": "git.validateLeavesTreeClean", "with": { "command": "npm run ci" } },
|
|
195
|
+
{ "use": "git.changesMatchPlan", "with": { "alsoAllow": "CHANGELOG.md" } },
|
|
196
|
+
{ "use": "git.commitsScoped" },
|
|
197
|
+
{ "use": "git.noChangesTo", "with": { "globs": ".github/workflows/**, .dash/checks/**" }, "label": "Gates unchanged" },
|
|
198
|
+
{ "use": "git.sourceHasTests", "with": { "exempt": "**/index.js" } },
|
|
199
|
+
{ "use": "node.newTestsAreRun", "with": { "runnerFiles": "package.json, scripts/ci.sh" } },
|
|
200
|
+
{ "use": "git.noNewMatches", "with": { "glob": "src/**, !**/*.test.*", "pattern": "console\\.log\\(|\\b(TODO|FIXME)\\b" },
|
|
201
|
+
"message": "Remove the console.log or TODO you added" },
|
|
202
|
+
{ "use": "files.maxGrowth" }
|
|
203
|
+
]
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
170
207
|
### Writing your own helper
|
|
171
208
|
|
|
172
209
|
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 +232,7 @@ module.exports = defineHelper({
|
|
|
195
232
|
});
|
|
196
233
|
```
|
|
197
234
|
|
|
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"]
|
|
235
|
+
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
236
|
|
|
200
237
|
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
238
|
|
|
@@ -286,7 +323,7 @@ A `.check.js` file also runs by itself, `node .dash/checks/validate.check.js`, t
|
|
|
286
323
|
|
|
287
324
|
## Examples
|
|
288
325
|
|
|
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:
|
|
326
|
+
[`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
327
|
|
|
291
328
|
| Example | Proves | Reads |
|
|
292
329
|
|---|---|---|
|
|
@@ -297,12 +334,21 @@ A `.check.js` file also runs by itself, `node .dash/checks/validate.check.js`, t
|
|
|
297
334
|
| `every-acceptance-has-a-test` | Every acceptance item has a test; the plan names real files | handoff, workspace |
|
|
298
335
|
| `validate` | Lint and tests pass, reported apart | run |
|
|
299
336
|
| `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 |
|
|
337
|
+
| `changes-match-plan` | Only the planned files changed; a lockfile only with `node.lockfileExplained` | git, fs, handoff, row |
|
|
301
338
|
| `pr-ci` | The PR's CI passed (no CI is a failure) | github |
|
|
302
339
|
| `merge-outcome` | The PR was merged only when allowed | github, settings |
|
|
303
340
|
| `workspace-cleaned` | The job's folder is gone | workspace |
|
|
304
341
|
| `jira-comment-from-job` | The ticket got this job's comment | tool, job |
|
|
305
342
|
| `ready-for-review.check.json` | The composer mockup's recipe | git, run, fs, handoff |
|
|
343
|
+
| `plan-scope.check.json` | `git.changesMatchPlan` | git, fs, handoff |
|
|
344
|
+
| `commits-scoped.check.json` | `git.commitsScoped` | git, handoff, item |
|
|
345
|
+
| `lockfile-explained.check.json` | `node.lockfileExplained` | git, fs |
|
|
346
|
+
| `source-has-tests.check.json` | `git.sourceHasTests`, its mode a team setting | git, fs, settings |
|
|
347
|
+
| `no-new-debt.check.json` | `git.noNewMatches`: no new console.log, TODO or eslint-disable | git |
|
|
348
|
+
| `max-growth.check.json` | `files.maxGrowth` | git, fs |
|
|
349
|
+
| `validate-leaves-tree-clean.check.json` | `git.validateLeavesTreeClean` | git, run |
|
|
350
|
+
| `test-script-is-real.check.json` | `node.testScriptIsReal` | fs, run |
|
|
351
|
+
| `new-tests-are-run.check.json` | `node.newTestsAreRun` | git, fs, settings |
|
|
306
352
|
| `helpers/changelog.js` | A team's own helper | git |
|
|
307
353
|
|
|
308
354
|
## 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 (
|
|
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)
|
|
9
|
-
|
|
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,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,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
|
+
}
|
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
|
-
|
|
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 };
|
package/helpers/git.js
CHANGED
|
@@ -4,7 +4,9 @@
|
|
|
4
4
|
*/
|
|
5
5
|
"use strict";
|
|
6
6
|
|
|
7
|
-
const { defineHelper, expect, fail, note, matchGlob, DashCheckError } = require("..");
|
|
7
|
+
const { defineHelper, expect, fail, note, matchGlob, globToRegExp, DashCheckError } = require("..");
|
|
8
|
+
const { needHandoff } = require("./handoff");
|
|
9
|
+
const { runOrFail } = require("./commands");
|
|
8
10
|
|
|
9
11
|
const listOf = (files, n = 10) => `${files.slice(0, n).join(", ")}${files.length > n ? `, and ${files.length - n} more` : ""}`;
|
|
10
12
|
|
|
@@ -113,4 +115,265 @@ const noChangesTo = defineHelper({
|
|
|
113
115
|
},
|
|
114
116
|
});
|
|
115
117
|
|
|
116
|
-
|
|
118
|
+
// ---- the plan: the files a handoff names ------------------------------------
|
|
119
|
+
|
|
120
|
+
const PLAN_KEYS = { type: "list", label: "Plan keys", default: ["files", "newFiles", "tests"], description: "Handoff keys that list files: a path, a list of paths, or a list of { file } (or { path })" };
|
|
121
|
+
const ALSO_ALLOW = { type: "list", label: "Also allowed", description: "Globs that may change without being in the plan, e.g. CHANGELOG.md" };
|
|
122
|
+
const LOCKFILES = {
|
|
123
|
+
type: "list",
|
|
124
|
+
label: "Lockfiles",
|
|
125
|
+
default: ["package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml"],
|
|
126
|
+
description: "Allowed outside the plan only when node.lockfileExplained passes for them",
|
|
127
|
+
};
|
|
128
|
+
const norm = (p) => String(p).trim().replace(/\\/g, "/").replace(/^\.\//, "");
|
|
129
|
+
|
|
130
|
+
/** The files the handoff's plan names (deduplicated, as written). */
|
|
131
|
+
function planFiles(ctx, keys) {
|
|
132
|
+
const out = new Set();
|
|
133
|
+
const add = (v) => {
|
|
134
|
+
if (typeof v === "string" && v.trim()) out.add(norm(v));
|
|
135
|
+
else if (v && typeof v === "object" && !Array.isArray(v)) add(v.file !== undefined ? v.file : v.path);
|
|
136
|
+
};
|
|
137
|
+
for (const k of keys) {
|
|
138
|
+
const v = ctx.get(`handoff.${k}`);
|
|
139
|
+
if (Array.isArray(v)) v.forEach(add);
|
|
140
|
+
else add(v);
|
|
141
|
+
}
|
|
142
|
+
return [...out];
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Is a file in the plan? A plan entry is a path, a folder ("src/x/") or a glob. */
|
|
146
|
+
const inPlan = (plan, f) =>
|
|
147
|
+
plan.some((p) => p === f || (p.endsWith("/") && f.startsWith(p)) || (/[*?{[]/.test(p) && matchGlob(p, f)));
|
|
148
|
+
|
|
149
|
+
const isLockfile = (lockfiles, f) => lockfiles.some((l) => l === f || l === f.split("/").pop() || (/[*?{[]/.test(l) && matchGlob(l, f)));
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* The changed files outside the plan, with lockfiles judged by
|
|
153
|
+
* node.lockfileExplained's rule: { extra, lockProblems: [{ file, reason, at }], lockOk: [file] }.
|
|
154
|
+
*/
|
|
155
|
+
async function outsidePlan(ctx, ref, files, { plan, alsoAllow, lockfiles, changed }) {
|
|
156
|
+
const { lockfileProblem } = require("./node");
|
|
157
|
+
const extra = [];
|
|
158
|
+
const lockProblems = [];
|
|
159
|
+
const lockOk = [];
|
|
160
|
+
const judged = new Map();
|
|
161
|
+
for (const f of files) {
|
|
162
|
+
if (inPlan(plan, f) || (alsoAllow.length && matchGlob(alsoAllow, f))) continue;
|
|
163
|
+
if (isLockfile(lockfiles, f)) {
|
|
164
|
+
if (!judged.has(f)) judged.set(f, await lockfileProblem(ctx, ref, f, { changed }));
|
|
165
|
+
const r = judged.get(f);
|
|
166
|
+
if (!r.changed || !r.reason) lockOk.push(f);
|
|
167
|
+
else lockProblems.push({ file: f, reason: r.reason, at: r.at });
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
extra.push(f);
|
|
171
|
+
}
|
|
172
|
+
return { extra, lockProblems, lockOk };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const changesMatchPlan = defineHelper({
|
|
176
|
+
id: "git.changesMatchPlan",
|
|
177
|
+
group: "Git",
|
|
178
|
+
label: "Only the planned files changed",
|
|
179
|
+
description: "Every changed file is named in the handoff's plan",
|
|
180
|
+
sentence: "every file changed since {base} is in handoff {planKeys}, or matches {alsoAllow}",
|
|
181
|
+
params: { base: BASE, planKeys: PLAN_KEYS, alsoAllow: ALSO_ALLOW, lockfiles: LOCKFILES },
|
|
182
|
+
reads: ["git", "fs", "handoff"],
|
|
183
|
+
async run(ctx, { base, planKeys, alsoAllow, lockfiles }) {
|
|
184
|
+
if (!needHandoff(ctx)) return;
|
|
185
|
+
const plan = planFiles(ctx, planKeys);
|
|
186
|
+
if (!plan.length) {
|
|
187
|
+
fail(`The handoff names no files in ${planKeys.join(", ")}: list the files the work changes`);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
const ref = await baseRef(ctx, base);
|
|
191
|
+
const changed = await ctx.git.changedFiles(ref);
|
|
192
|
+
const { extra, lockProblems } = await outsidePlan(ctx, ref, changed, { plan, alsoAllow, lockfiles, changed });
|
|
193
|
+
if (extra.length) fail("Files the plan didn't name changed: undo them, or add them to the plan", { at: listOf(extra), received: extra });
|
|
194
|
+
for (const p of lockProblems) fail(p.reason, p.at ? { at: p.at } : undefined);
|
|
195
|
+
if (!extra.length && !lockProblems.length) note(`${changed.length} changed file${changed.length === 1 ? "" : "s"}, all in the plan`);
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
const commitsScoped = defineHelper({
|
|
200
|
+
id: "git.commitsScoped",
|
|
201
|
+
group: "Git",
|
|
202
|
+
label: "Each commit is scoped",
|
|
203
|
+
description: "Every commit touches only planned files and names the item",
|
|
204
|
+
sentence: "each commit past {base} changes only files in handoff {planKeys} and mentions {mentions}",
|
|
205
|
+
params: {
|
|
206
|
+
base: BASE,
|
|
207
|
+
planKeys: { ...PLAN_KEYS, description: `${PLAN_KEYS.description}. Empty: don't check the files` },
|
|
208
|
+
alsoAllow: ALSO_ALLOW,
|
|
209
|
+
lockfiles: LOCKFILES,
|
|
210
|
+
mentions: { type: "text", label: "Message mentions", default: "{item.id}", description: "Text every commit message must have. Empty: don't check messages" },
|
|
211
|
+
},
|
|
212
|
+
reads: ["git", "fs", "handoff", "item"],
|
|
213
|
+
async run(ctx, { base, planKeys, alsoAllow, lockfiles, mentions }) {
|
|
214
|
+
let plan = null;
|
|
215
|
+
if (planKeys.length) {
|
|
216
|
+
if (!needHandoff(ctx)) return;
|
|
217
|
+
plan = planFiles(ctx, planKeys);
|
|
218
|
+
if (!plan.length) {
|
|
219
|
+
fail(`The handoff names no files in ${planKeys.join(", ")}: list the files the work changes`);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
const ref = await baseRef(ctx, base);
|
|
224
|
+
const commits = (await ctx.git.commits(ref)).filter((c) => c.parents.length < 2);
|
|
225
|
+
if (!commits.length) {
|
|
226
|
+
note(`No commits past ${ref}`);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const changed = plan ? await ctx.git.changedFiles(ref) : [];
|
|
230
|
+
let bad = 0;
|
|
231
|
+
for (const c of commits) {
|
|
232
|
+
const name = `${c.sha.slice(0, 7)} "${c.subject}"`;
|
|
233
|
+
if (plan) {
|
|
234
|
+
const { extra, lockProblems } = await outsidePlan(ctx, ref, c.files, { plan, alsoAllow, lockfiles, changed });
|
|
235
|
+
const out = [...extra, ...lockProblems.map((p) => p.file)];
|
|
236
|
+
if (out.length) {
|
|
237
|
+
bad++;
|
|
238
|
+
fail(`Commit ${name} changes files outside the plan: move them to their own branch, or add them to the plan`, { at: listOf(out), received: out });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (mentions && !c.message.includes(mentions)) {
|
|
242
|
+
bad++;
|
|
243
|
+
fail(`Commit ${name} doesn't mention ${mentions}: reword it (git commit --amend, or rebase -i before pushing)`);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (!bad) note(`${commits.length} commit${commits.length === 1 ? "" : "s"}, each scoped${mentions ? ` and mentioning ${mentions}` : ""}`);
|
|
247
|
+
},
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
// ---- tests next to the source ------------------------------------------------
|
|
251
|
+
|
|
252
|
+
const RE_ESC = /[.*+?^${}()|[\]\\]/g;
|
|
253
|
+
const SENT = { dir: "\u0001D\u0001", name: "\u0001N\u0001", ext: "\u0001E\u0001" };
|
|
254
|
+
|
|
255
|
+
/** A test pattern ("<dir>/<name>.test.*") for one source file, as a RegExp. */
|
|
256
|
+
function pairedTest(pattern, src) {
|
|
257
|
+
const slash = src.lastIndexOf("/");
|
|
258
|
+
const dir = slash < 0 ? "" : src.slice(0, slash);
|
|
259
|
+
const file = src.slice(slash + 1);
|
|
260
|
+
const dot = file.lastIndexOf(".");
|
|
261
|
+
const parts = { dir, name: dot > 0 ? file.slice(0, dot) : file, ext: dot > 0 ? file.slice(dot + 1) : "" };
|
|
262
|
+
let g = String(pattern).replace(/<(dir|name|ext)>/g, (_m, k) => SENT[k]);
|
|
263
|
+
if (!dir) g = g.replace(new RegExp(`^${SENT.dir}/`), "");
|
|
264
|
+
let src2 = globToRegExp(g).source;
|
|
265
|
+
for (const k of Object.keys(SENT)) src2 = src2.split(SENT[k]).join(parts[k].replace(RE_ESC, "\\$&"));
|
|
266
|
+
return new RegExp(src2);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const sourceHasTests = defineHelper({
|
|
270
|
+
id: "git.sourceHasTests",
|
|
271
|
+
group: "Git",
|
|
272
|
+
label: "Changed source has tests",
|
|
273
|
+
description: "Each changed source file has a changed test (paired by name, or any)",
|
|
274
|
+
sentence: "each changed {sources} file since {base} has a changed test ({mode})",
|
|
275
|
+
params: {
|
|
276
|
+
sources: {
|
|
277
|
+
type: "list",
|
|
278
|
+
label: "Source files",
|
|
279
|
+
default: ["src/**/*.{js,jsx,ts,tsx,mjs,cjs}", "lib/**/*.{js,jsx,ts,tsx,mjs,cjs}", "!**/*.{test,spec}.*", "!**/__tests__/**", "!**/*.stories.*", "!**/*.d.ts"],
|
|
280
|
+
},
|
|
281
|
+
tests: { type: "list", label: "Test files", default: ["**/*.{test,spec}.*", "**/__tests__/**", "test/**", "tests/**"], description: "What counts as a test in any mode" },
|
|
282
|
+
testPattern: {
|
|
283
|
+
type: "list",
|
|
284
|
+
label: "Paired test",
|
|
285
|
+
default: ["<dir>/<name>.{test,spec}.*", "<dir>/__tests__/<name>.*", "{test,tests}/**/<name>.{test,spec}.*", "{test,tests}/**/<name>.*"],
|
|
286
|
+
description: "Where a source's test is, in paired mode: <dir>, <name> and <ext> are the source's",
|
|
287
|
+
},
|
|
288
|
+
mode: { type: "select", label: "Mode", options: ["paired", "any"], default: "paired", description: "paired: each source has its own test; any: some test changed" },
|
|
289
|
+
exempt: { type: "list", label: "Exempt", description: "Sources that need no test, e.g. **/index.js" },
|
|
290
|
+
base: BASE,
|
|
291
|
+
},
|
|
292
|
+
reads: ["git", "fs"],
|
|
293
|
+
async run(ctx, { sources, tests, testPattern, mode, exempt, base }) {
|
|
294
|
+
const ref = await baseRef(ctx, base);
|
|
295
|
+
const changed = [];
|
|
296
|
+
for (const f of await ctx.git.changedFiles(ref)) if (await ctx.fs.exists(f)) changed.push(f);
|
|
297
|
+
const srcs = changed.filter((f) => matchGlob(sources, f) && !(exempt.length && matchGlob(exempt, f)));
|
|
298
|
+
if (!srcs.length) {
|
|
299
|
+
note(`No source file changed since ${ref}`);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const changedTests = changed.filter((f) => matchGlob(tests, f));
|
|
303
|
+
if (mode === "any") {
|
|
304
|
+
if (!changedTests.length) fail("Source changed but no test did: add or update a test", { at: listOf(srcs), received: srcs });
|
|
305
|
+
else note(`${srcs.length} source file${srcs.length === 1 ? "" : "s"} and ${changedTests.length} test${changedTests.length === 1 ? "" : "s"} changed`);
|
|
306
|
+
return;
|
|
307
|
+
}
|
|
308
|
+
const others = changed.filter((f) => !srcs.includes(f));
|
|
309
|
+
const missing = srcs.filter((s) => {
|
|
310
|
+
const res = testPattern.map((p) => pairedTest(p, s));
|
|
311
|
+
return !others.some((f) => res.some((re) => re.test(f)));
|
|
312
|
+
});
|
|
313
|
+
if (missing.length) {
|
|
314
|
+
fail(`Changed source with no changed test next to it: add or update ${missing.length === 1 ? "its test" : "their tests"} (${testPattern[0] || "a test"})`, { at: listOf(missing), received: missing });
|
|
315
|
+
} else note(`${srcs.length} source file${srcs.length === 1 ? "" : "s"}, each with its test`);
|
|
316
|
+
},
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
// ---- the lines the work added --------------------------------------------------
|
|
320
|
+
|
|
321
|
+
const noNewMatches = defineHelper({
|
|
322
|
+
id: "git.noNewMatches",
|
|
323
|
+
group: "Git",
|
|
324
|
+
label: "No added line matches a pattern",
|
|
325
|
+
description: "e.g. no new TODO or console.log; lines already there don't count",
|
|
326
|
+
sentence: "no line added since {base} in {glob} matches {pattern}",
|
|
327
|
+
params: {
|
|
328
|
+
glob: { type: "list", label: "Files", required: true, placeholder: "src/**/*.js, !**/*.test.js" },
|
|
329
|
+
pattern: { type: "regex", label: "Pattern", required: true, placeholder: "\\b(TODO|FIXME)\\b" },
|
|
330
|
+
base: BASE,
|
|
331
|
+
},
|
|
332
|
+
reads: ["git"],
|
|
333
|
+
async run(ctx, { glob, pattern, base }) {
|
|
334
|
+
const ref = await baseRef(ctx, base);
|
|
335
|
+
const added = (await ctx.git.addedLines(ref)).filter((l) => matchGlob(glob, l.file));
|
|
336
|
+
const hits = added.filter((l) => {
|
|
337
|
+
pattern.lastIndex = 0;
|
|
338
|
+
return pattern.test(l.text);
|
|
339
|
+
});
|
|
340
|
+
if (hits.length) {
|
|
341
|
+
const where = hits.map((h) => `${h.file}:${h.line}`);
|
|
342
|
+
fail(`${hits.length} added line${hits.length === 1 ? "" : "s"} match${hits.length === 1 ? "es" : ""} /${pattern.source}/: remove ${hits.length === 1 ? "it" : "them"}`, { at: listOf(where), received: where });
|
|
343
|
+
} else note(`No match in ${added.length} added line${added.length === 1 ? "" : "s"}`);
|
|
344
|
+
},
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
// ---- validation doesn't rewrite the tree ---------------------------------------
|
|
348
|
+
|
|
349
|
+
const validateLeavesTreeClean = defineHelper({
|
|
350
|
+
id: "git.validateLeavesTreeClean",
|
|
351
|
+
group: "Git",
|
|
352
|
+
label: "Validate doesn't rewrite files",
|
|
353
|
+
description: "Running the validate command leaves no file changed (no formatter --write, no npm install --save)",
|
|
354
|
+
sentence: "{command} passes and leaves nothing uncommitted",
|
|
355
|
+
params: {
|
|
356
|
+
command: { type: "text", label: "Command", default: "npm test" },
|
|
357
|
+
timeoutSec: { type: "number", label: "Time limit (s)", default: 1800 },
|
|
358
|
+
allowDirtyBefore: { type: "boolean", label: "Allow changes before", default: false, description: "Judge only files the command changes" },
|
|
359
|
+
},
|
|
360
|
+
reads: ["git", "run"],
|
|
361
|
+
async run(ctx, { command, timeoutSec, allowDirtyBefore }) {
|
|
362
|
+
const before = await ctx.git.uncommitted();
|
|
363
|
+
if (before.length && !allowDirtyBefore) {
|
|
364
|
+
fail(`There are uncommitted changes before ${command}: commit or discard them first`, { at: listOf(before, 5), received: before });
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const r = await runOrFail(ctx, command, timeoutSec);
|
|
368
|
+
const rewritten = (await ctx.git.uncommitted()).filter((f) => !before.includes(f));
|
|
369
|
+
if (rewritten.length) {
|
|
370
|
+
fail(`${command} changed files: make it check instead of rewrite (e.g. prettier --check, npm ci), and don't commit them`, { at: listOf(rewritten), received: rewritten });
|
|
371
|
+
} else if (r.code === 0 && !r.timedOut) note(`${command} passed and left the tree as it was`);
|
|
372
|
+
},
|
|
373
|
+
});
|
|
374
|
+
|
|
375
|
+
module.exports = {
|
|
376
|
+
onBranch, committedSince, clean, changedOnly, noChangesTo,
|
|
377
|
+
changesMatchPlan, commitsScoped, sourceHasTests, noNewMatches, validateLeavesTreeClean,
|
|
378
|
+
baseRef, planFiles, inPlan, pairedTest,
|
|
379
|
+
};
|
package/helpers/index.d.ts
CHANGED
|
@@ -2,13 +2,101 @@
|
|
|
2
2
|
import type { Helper } from "..";
|
|
3
3
|
|
|
4
4
|
type H = Helper<Record<string, any>>;
|
|
5
|
+
/** A list param: an array, or text split on commas ("a, b"; a glob's {a,b} stays whole). */
|
|
6
|
+
type List = string[] | string;
|
|
7
|
+
|
|
8
|
+
/** Shared by the git and node helpers: empty means the repo's default branch. Default "{repo.baseBranch}". */
|
|
9
|
+
interface Base {
|
|
10
|
+
base?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface ChangesMatchPlanParams extends Base {
|
|
14
|
+
/** Handoff keys listing files (a path, paths, or [{ file }] / [{ path }]). Default files, newFiles, tests. */
|
|
15
|
+
planKeys?: List;
|
|
16
|
+
/** Globs that may change outside the plan, e.g. CHANGELOG.md. */
|
|
17
|
+
alsoAllow?: List;
|
|
18
|
+
/** Allowed outside the plan only when node.lockfileExplained passes. Default package-lock.json, npm-shrinkwrap.json, yarn.lock, pnpm-lock.yaml. */
|
|
19
|
+
lockfiles?: List;
|
|
20
|
+
}
|
|
21
|
+
export interface CommitsScopedParams extends ChangesMatchPlanParams {
|
|
22
|
+
/** Text every commit message must have. Default "{item.id}"; empty skips it. planKeys "" skips the file check. */
|
|
23
|
+
mentions?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface SourceHasTestsParams extends Base {
|
|
26
|
+
sources?: List;
|
|
27
|
+
tests?: List;
|
|
28
|
+
/** Where a source's test is, with <dir>, <name> and <ext>. */
|
|
29
|
+
testPattern?: List;
|
|
30
|
+
mode?: "paired" | "any";
|
|
31
|
+
exempt?: List;
|
|
32
|
+
}
|
|
33
|
+
export interface NoNewMatchesParams extends Base {
|
|
34
|
+
glob: List;
|
|
35
|
+
pattern: string | RegExp;
|
|
36
|
+
}
|
|
37
|
+
export interface ValidateLeavesTreeCleanParams {
|
|
38
|
+
/** Default "npm test". */
|
|
39
|
+
command?: string;
|
|
40
|
+
/** Default 1800. */
|
|
41
|
+
timeoutSec?: number;
|
|
42
|
+
/** Judge only the files the command changes. Default false. */
|
|
43
|
+
allowDirtyBefore?: boolean;
|
|
44
|
+
}
|
|
45
|
+
export interface MaxGrowthParams extends Base {
|
|
46
|
+
glob?: List;
|
|
47
|
+
/** Default 800. */
|
|
48
|
+
maxLines?: number;
|
|
49
|
+
/** Default 50. */
|
|
50
|
+
maxAdded?: number;
|
|
51
|
+
exempt?: List;
|
|
52
|
+
}
|
|
53
|
+
export interface LockfileExplainedParams extends Base {
|
|
54
|
+
/** Default package-lock.json. */
|
|
55
|
+
lockfile?: string;
|
|
56
|
+
/** Default: package.json next to the lockfile, and any changed package.json below it. */
|
|
57
|
+
manifest?: string;
|
|
58
|
+
}
|
|
59
|
+
export interface TestScriptIsRealParams {
|
|
60
|
+
/** Default "test". */
|
|
61
|
+
script?: string;
|
|
62
|
+
/** Also run it and count the tests. Default false. */
|
|
63
|
+
run?: boolean;
|
|
64
|
+
/** Default 1; 0 skips the count. */
|
|
65
|
+
minTests?: number;
|
|
66
|
+
timeoutSec?: number;
|
|
67
|
+
}
|
|
68
|
+
export interface NewTestsAreRunParams extends Base {
|
|
69
|
+
tests?: List;
|
|
70
|
+
/** Default package.json. */
|
|
71
|
+
runnerFiles?: List;
|
|
72
|
+
/** Tests the runner finds by itself, e.g. src/**\/*.test.js. */
|
|
73
|
+
autoGlobs?: List;
|
|
74
|
+
}
|
|
5
75
|
|
|
6
76
|
export const handoff: { has: H; status: H; eachHas: H };
|
|
7
77
|
export const plan: { hasSections: H; acceptanceEachHasTest: H };
|
|
8
|
-
export const git: {
|
|
9
|
-
|
|
78
|
+
export const git: {
|
|
79
|
+
onBranch: H;
|
|
80
|
+
committedSince: H;
|
|
81
|
+
clean: H;
|
|
82
|
+
changedOnly: H;
|
|
83
|
+
noChangesTo: H;
|
|
84
|
+
changesMatchPlan: Helper<ChangesMatchPlanParams>;
|
|
85
|
+
commitsScoped: Helper<CommitsScopedParams>;
|
|
86
|
+
sourceHasTests: Helper<SourceHasTestsParams>;
|
|
87
|
+
noNewMatches: Helper<NoNewMatchesParams>;
|
|
88
|
+
validateLeavesTreeClean: Helper<ValidateLeavesTreeCleanParams>;
|
|
89
|
+
};
|
|
90
|
+
export const files: { exist: H; contain: H; noneMatch: H; maxGrowth: Helper<MaxGrowthParams> };
|
|
10
91
|
export const commands: { passes: H; outputMatches: H };
|
|
11
|
-
export const node: {
|
|
92
|
+
export const node: {
|
|
93
|
+
testsPass: H;
|
|
94
|
+
lintPasses: H;
|
|
95
|
+
noNewDependencies: H;
|
|
96
|
+
lockfileExplained: Helper<LockfileExplainedParams>;
|
|
97
|
+
testScriptIsReal: Helper<TestScriptIsRealParams>;
|
|
98
|
+
newTestsAreRun: Helper<NewTestsAreRunParams>;
|
|
99
|
+
};
|
|
12
100
|
export const github: { prOpen: H; ciPassed: H };
|
|
13
101
|
export const tracker: { ticketExists: H; ticketHasLabel: H };
|
|
14
102
|
/** Every starter helper. */
|
package/helpers/node.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
"use strict";
|
|
6
6
|
|
|
7
|
-
const { defineHelper, fail, note } = require("..");
|
|
7
|
+
const { defineHelper, fail, note, matchGlob, deepEqual } = require("..");
|
|
8
8
|
const { runOrFail } = require("./commands");
|
|
9
9
|
const { baseRef } = require("./git");
|
|
10
10
|
|
|
@@ -103,4 +103,194 @@ const noNewDependencies = defineHelper({
|
|
|
103
103
|
},
|
|
104
104
|
});
|
|
105
105
|
|
|
106
|
-
|
|
106
|
+
const listOf = (xs, n = 10) => `${xs.slice(0, n).join(", ")}${xs.length > n ? `, and ${xs.length - n} more` : ""}`;
|
|
107
|
+
const dirOf = (p) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
|
|
108
|
+
const parseJson = (text) => {
|
|
109
|
+
try {
|
|
110
|
+
return { ok: true, value: JSON.parse(text) };
|
|
111
|
+
} catch (_e) {
|
|
112
|
+
return { ok: false };
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
const depsOf = (pkg) => Object.fromEntries(DEP_KEYS.map((k) => [k, (pkg && pkg[k]) || {}]));
|
|
116
|
+
|
|
117
|
+
/** A JSON lockfile without its root version fields (a release bumps those). */
|
|
118
|
+
function lockBody(lock) {
|
|
119
|
+
const out = { ...lock };
|
|
120
|
+
delete out.version;
|
|
121
|
+
if (out.packages && out.packages[""]) {
|
|
122
|
+
out.packages = { ...out.packages, "": { ...out.packages[""] } };
|
|
123
|
+
delete out.packages[""].version;
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The entries of a JSON lockfile that differ: "node_modules/foo", … */
|
|
129
|
+
function lockDiff(a, b) {
|
|
130
|
+
const pa = (a && (a.packages || a.dependencies)) || {};
|
|
131
|
+
const pb = (b && (b.packages || b.dependencies)) || {};
|
|
132
|
+
const keys = [...new Set([...Object.keys(pa), ...Object.keys(pb)])].sort();
|
|
133
|
+
const diff = keys.filter((k) => !deepEqual(pa[k], pb[k])).map((k) => k || "(root)");
|
|
134
|
+
return diff.length ? diff : ["(the lockfile's other fields)"];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Why a changed lockfile isn't explained, or null when it is. It is
|
|
139
|
+
* explained when only its root version fields changed, or when a dependency
|
|
140
|
+
* section of a package.json in its folder (or below, for workspaces)
|
|
141
|
+
* changed. A lockfile git can't read as JSON (yarn.lock, pnpm-lock.yaml)
|
|
142
|
+
* needs a dependency change for any change.
|
|
143
|
+
* { changed, reason, at }
|
|
144
|
+
*/
|
|
145
|
+
async function lockfileProblem(ctx, ref, lockfile, { manifest, changed } = {}) {
|
|
146
|
+
const files = changed || (await ctx.git.changedFiles(ref));
|
|
147
|
+
if (!files.includes(lockfile)) return { changed: false };
|
|
148
|
+
const undo = `git checkout ${ref} -- ${lockfile}`;
|
|
149
|
+
const dir = dirOf(lockfile);
|
|
150
|
+
const manifests = manifest
|
|
151
|
+
? [manifest]
|
|
152
|
+
: [...new Set([dir ? `${dir}/package.json` : "package.json", ...files.filter((f) => /(^|\/)package\.json$/.test(f) && (!dir || f.startsWith(`${dir}/`)))])];
|
|
153
|
+
const depsChanged = [];
|
|
154
|
+
for (const m of manifests) {
|
|
155
|
+
const before = await ctx.git.fileAt(ref, m);
|
|
156
|
+
const nowThere = await ctx.fs.exists(m);
|
|
157
|
+
const old = before === null ? null : parseJson(before);
|
|
158
|
+
const now = nowThere ? parseJson(await ctx.fs.read(m)) : null;
|
|
159
|
+
if ((old && !old.ok) || (now && !now.ok) || (!old && !now)) continue;
|
|
160
|
+
if (!deepEqual(depsOf(old && old.value), depsOf(now && now.value))) depsChanged.push(m);
|
|
161
|
+
}
|
|
162
|
+
if (depsChanged.length) return { changed: true, reason: null, why: `dependencies changed in ${depsChanged.join(", ")}` };
|
|
163
|
+
if (!(await ctx.fs.exists(lockfile))) {
|
|
164
|
+
return { changed: true, reason: `${lockfile} was deleted, but no dependency changed: restore it (${undo})` };
|
|
165
|
+
}
|
|
166
|
+
const before = await ctx.git.fileAt(ref, lockfile);
|
|
167
|
+
if (before === null) {
|
|
168
|
+
return { changed: true, reason: `${lockfile} is new, but no dependency changed: remove it, or add it to the plan` };
|
|
169
|
+
}
|
|
170
|
+
const old = parseJson(before);
|
|
171
|
+
const now = parseJson(await ctx.fs.read(lockfile));
|
|
172
|
+
if (old.ok && now.ok) {
|
|
173
|
+
if (deepEqual(lockBody(old.value), lockBody(now.value))) return { changed: true, reason: null, why: "only its version changed" };
|
|
174
|
+
return {
|
|
175
|
+
changed: true,
|
|
176
|
+
reason: `${lockfile} changed, but no dependency in ${manifests.join(", ")} did: undo it (${undo})`,
|
|
177
|
+
at: listOf(lockDiff(lockBody(old.value), lockBody(now.value))),
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
return { changed: true, reason: `${lockfile} changed, but no dependency in ${manifests.join(", ")} did: undo it (${undo})` };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const lockfileExplained = defineHelper({
|
|
184
|
+
id: "node.lockfileExplained",
|
|
185
|
+
group: "Node",
|
|
186
|
+
label: "Lockfile change is explained",
|
|
187
|
+
description: "The lockfile changed only with a dependency (or only its version)",
|
|
188
|
+
sentence: "{lockfile} changed since {base} only with a dependency in package.json",
|
|
189
|
+
params: {
|
|
190
|
+
base: { type: "text", label: "Base branch", default: "{repo.baseBranch}", description: "Empty: the repo's default branch" },
|
|
191
|
+
lockfile: { type: "path", label: "Lockfile", default: "package-lock.json" },
|
|
192
|
+
manifest: { type: "path", label: "package.json", description: "Empty: package.json next to the lockfile, and any changed package.json below it" },
|
|
193
|
+
},
|
|
194
|
+
reads: ["git", "fs"],
|
|
195
|
+
async run(ctx, { base, lockfile, manifest }) {
|
|
196
|
+
const ref = await baseRef(ctx, base);
|
|
197
|
+
const r = await lockfileProblem(ctx, ref, lockfile, { manifest });
|
|
198
|
+
if (!r.changed) note(`${lockfile} didn't change`);
|
|
199
|
+
else if (r.reason) fail(r.reason, r.at ? { at: r.at } : undefined);
|
|
200
|
+
else note(`${lockfile} changed: ${r.why}`);
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
/** A script that runs nothing, or hides its failures; null when it looks real. */
|
|
205
|
+
function noOpScript(script) {
|
|
206
|
+
const s = String(script || "").trim();
|
|
207
|
+
if (!s) return "is empty";
|
|
208
|
+
if (/^(exit\s+0|true|:|echo\b[^&|;]*)\s*;?$/i.test(s)) return `does nothing ("${s}")`;
|
|
209
|
+
if (/no test specified/i.test(s)) return `is npm's placeholder ("${s}")`;
|
|
210
|
+
if (/(\|\|\s*(true|:|exit\s+0)|;\s*exit\s+0)\s*;?$/.test(s)) return `hides its failures ("${s}")`;
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const testScriptIsReal = defineHelper({
|
|
215
|
+
id: "node.testScriptIsReal",
|
|
216
|
+
group: "Node",
|
|
217
|
+
label: "The test script is real",
|
|
218
|
+
description: "package.json's test script isn't a no-op, and can run tests",
|
|
219
|
+
sentence: "the {script} script in package.json runs tests",
|
|
220
|
+
params: {
|
|
221
|
+
script: { type: "text", label: "Script", default: "test" },
|
|
222
|
+
run: { type: "boolean", label: "Run it", default: false, description: "Also run it and count the tests" },
|
|
223
|
+
minTests: { type: "number", label: "At least (tests)", default: 1, description: "When run; 0 skips the count" },
|
|
224
|
+
timeoutSec: { type: "number", label: "Time limit (s)", default: 900 },
|
|
225
|
+
},
|
|
226
|
+
reads: ["fs", "run"],
|
|
227
|
+
async run(ctx, { script, run, minTests, timeoutSec }) {
|
|
228
|
+
if (!(await ctx.fs.exists("package.json"))) {
|
|
229
|
+
fail("package.json isn't in the workspace");
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const pkg = await ctx.fs.readJson("package.json");
|
|
233
|
+
const body = pkg && pkg.scripts ? pkg.scripts[script] : undefined;
|
|
234
|
+
if (typeof body !== "string") {
|
|
235
|
+
fail(`package.json has no "${script}" script: add one that runs the tests`);
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const bad = noOpScript(body);
|
|
239
|
+
if (bad) {
|
|
240
|
+
fail(`The "${script}" script ${bad}: make it run the tests`);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (!run) {
|
|
244
|
+
note(`"${script}" is ${body}`);
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
const command = script === "test" ? "npm test" : `npm run ${script}`;
|
|
248
|
+
const r = await runOrFail(ctx, command, timeoutSec);
|
|
249
|
+
if (r.code !== 0 || r.timedOut) return;
|
|
250
|
+
const n = testCount(`${r.stdout}\n${r.stderr}`);
|
|
251
|
+
if (minTests > 0 && n === null) fail(`${command} passed, but its output doesn't say how many tests ran: use a runner that reports it, or set "At least" to 0`);
|
|
252
|
+
else if (minTests > 0 && n < minTests) fail(`${command} ran ${n} test${n === 1 ? "" : "s"}; it needs at least ${minTests}`, { received: n, expected: minTests });
|
|
253
|
+
else note(n === null ? `${command} passed` : `${n} test${n === 1 ? "" : "s"} passed`);
|
|
254
|
+
},
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
/** Glob-like words in a runner's text ("test/*.test.js", "src/**"): what it finds by itself. */
|
|
258
|
+
function globsIn(text) {
|
|
259
|
+
return [...new Set(String(text).split(/[\s"'`,=()[\]]+/).map((w) => w.replace(/^\.\//, "")).filter((w) => /[*?]/.test(w) && /[\w]/.test(w)))];
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const newTestsAreRun = defineHelper({
|
|
263
|
+
id: "node.newTestsAreRun",
|
|
264
|
+
group: "Node",
|
|
265
|
+
label: "New tests are run",
|
|
266
|
+
description: "Every new test file is picked up by a test runner",
|
|
267
|
+
sentence: "every new {tests} file since {base} is named or matched in {runnerFiles}, or matches {autoGlobs}",
|
|
268
|
+
params: {
|
|
269
|
+
base: { type: "text", label: "Base branch", default: "{repo.baseBranch}", description: "Empty: the repo's default branch" },
|
|
270
|
+
tests: { type: "list", label: "Test files", default: ["**/*.{test,spec}.{js,cjs,mjs,jsx,ts,tsx}"] },
|
|
271
|
+
runnerFiles: { type: "list", label: "Runner files", default: ["package.json"], description: "Files that name the tests to run, e.g. package.json, scripts/ci.sh" },
|
|
272
|
+
autoGlobs: { type: "list", label: "Found by the runner", description: "Tests the runner finds by itself, e.g. src/**/*.test.js for jest" },
|
|
273
|
+
},
|
|
274
|
+
reads: ["git", "fs"],
|
|
275
|
+
async run(ctx, { base, tests, runnerFiles, autoGlobs }) {
|
|
276
|
+
const ref = await baseRef(ctx, base);
|
|
277
|
+
const added = [];
|
|
278
|
+
for (const f of await ctx.git.changedFiles(ref)) {
|
|
279
|
+
if (!matchGlob(tests, f) || !(await ctx.fs.exists(f))) continue;
|
|
280
|
+
if ((await ctx.git.fileAt(ref, f)) === null) added.push(f);
|
|
281
|
+
}
|
|
282
|
+
if (!added.length) {
|
|
283
|
+
note(`No new test files since ${ref}`);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
const texts = [];
|
|
287
|
+
for (const r of runnerFiles) if (await ctx.fs.exists(r)) texts.push(await ctx.fs.read(r));
|
|
288
|
+
const found = [...autoGlobs, ...globsIn(texts.join("\n"))];
|
|
289
|
+
const missed = added.filter((f) => !(found.length && matchGlob(found, f)) && !texts.some((t) => t.includes(f)));
|
|
290
|
+
if (missed.length) {
|
|
291
|
+
fail(`New test files no runner runs: add them to ${runnerFiles.join(" or ")}, or say which globs the runner finds by itself`, { at: listOf(missed), received: missed });
|
|
292
|
+
} else note(`${added.length} new test file${added.length === 1 ? "" : "s"}, each run`);
|
|
293
|
+
},
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
module.exports = { testsPass, lintPasses, noNewDependencies, lockfileExplained, testScriptIsReal, newTestsAreRun, testCount, lockfileProblem, noOpScript };
|
package/index.d.ts
CHANGED
|
@@ -49,12 +49,34 @@ export interface Fs {
|
|
|
49
49
|
list(globs: string | string[]): Promise<string[]>;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
/** A line added since a ref (ctx.git.addedLines). */
|
|
53
|
+
export interface AddedLine {
|
|
54
|
+
file: string;
|
|
55
|
+
/** Its line number in the file as it is now (1-based). */
|
|
56
|
+
line: number;
|
|
57
|
+
text: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A commit past a ref (ctx.git.commits). */
|
|
61
|
+
export interface Commit {
|
|
62
|
+
sha: string;
|
|
63
|
+
subject: string;
|
|
64
|
+
message: string;
|
|
65
|
+
parents: string[];
|
|
66
|
+
/** The files it changed; empty for a merge commit. */
|
|
67
|
+
files: string[];
|
|
68
|
+
}
|
|
69
|
+
|
|
52
70
|
export interface Git {
|
|
53
71
|
branch(): Promise<string>;
|
|
54
72
|
uncommitted(): Promise<string[]>;
|
|
55
73
|
isClean(): Promise<boolean>;
|
|
56
74
|
commitsSince(ref: string): Promise<number>;
|
|
57
75
|
changedFiles(ref: string): Promise<string[]>;
|
|
76
|
+
/** Lines added since where HEAD left ref: committed, uncommitted, and untracked files whole. Binary files left out. */
|
|
77
|
+
addedLines(ref: string): Promise<AddedLine[]>;
|
|
78
|
+
/** The commits in ref..HEAD, oldest first. */
|
|
79
|
+
commits(ref: string): Promise<Commit[]>;
|
|
58
80
|
lastCommitMessage(): Promise<string>;
|
|
59
81
|
remoteHas(branch: string, remote?: string): Promise<boolean>;
|
|
60
82
|
defaultBranch(): Promise<string | null>;
|
package/lib/adapters/git.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
*/
|
|
5
5
|
"use strict";
|
|
6
6
|
|
|
7
|
+
const fs = require("fs");
|
|
8
|
+
const path = require("path");
|
|
7
9
|
const { execArgs } = require("./run");
|
|
8
10
|
const { DashCheckError } = require("../util");
|
|
9
11
|
|
|
@@ -30,6 +32,13 @@ function makeGit({ cwd, env }) {
|
|
|
30
32
|
}
|
|
31
33
|
};
|
|
32
34
|
const lines = (s) => s.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
35
|
+
const mergeBase = async (ref) => {
|
|
36
|
+
await needRef(ref);
|
|
37
|
+
return (await must(["merge-base", ref, "HEAD"], `Can't find where HEAD left ${ref}`)).trim();
|
|
38
|
+
};
|
|
39
|
+
const untrackedFiles = async () => lines(await must(["-c", "core.quotePath=false", "ls-files", "--others", "--exclude-standard"], "Can't list untracked files"));
|
|
40
|
+
// Plain diff output whatever the user's git config says.
|
|
41
|
+
const DIFF = ["-c", "core.quotePath=false", "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/"];
|
|
33
42
|
|
|
34
43
|
const api = {
|
|
35
44
|
/** The current branch ("HEAD" when detached). */
|
|
@@ -51,12 +60,79 @@ function makeGit({ cwd, env }) {
|
|
|
51
60
|
* plus uncommitted and untracked ones. Sorted, relative.
|
|
52
61
|
*/
|
|
53
62
|
changedFiles: async (ref) => {
|
|
54
|
-
await
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
const untracked = lines(await must(["ls-files", "--others", "--exclude-standard"], "Can't list untracked files"));
|
|
63
|
+
const base = await mergeBase(ref);
|
|
64
|
+
const changed = lines(await must(["-c", "core.quotePath=false", "diff", "--name-only", base], `Can't diff against ${ref}`));
|
|
65
|
+
const untracked = await untrackedFiles();
|
|
58
66
|
return [...new Set([...changed, ...untracked])].sort();
|
|
59
67
|
},
|
|
68
|
+
/**
|
|
69
|
+
* Lines added since a ref, the same files as changedFiles: committed
|
|
70
|
+
* since where the branch left it, uncommitted, and untracked files
|
|
71
|
+
* read whole. [{ file, line, text }], line numbers in the file as it is
|
|
72
|
+
* now. Binary files are left out.
|
|
73
|
+
*/
|
|
74
|
+
addedLines: async (ref) => {
|
|
75
|
+
const base = await mergeBase(ref);
|
|
76
|
+
const out = [];
|
|
77
|
+
let file = null;
|
|
78
|
+
let header = false;
|
|
79
|
+
let n = 0;
|
|
80
|
+
for (const l of (await must([...DIFF, "-U0", base], `Can't diff against ${ref}`)).split("\n")) {
|
|
81
|
+
if (l.startsWith("diff --git ")) {
|
|
82
|
+
file = null;
|
|
83
|
+
header = true;
|
|
84
|
+
} else if (header && l.startsWith("+++ ")) {
|
|
85
|
+
const p = l.slice(4);
|
|
86
|
+
file = p === "/dev/null" ? null : p.replace(/^"?b\//, "").replace(/"$/, "");
|
|
87
|
+
} else if (l.startsWith("@@")) {
|
|
88
|
+
header = false;
|
|
89
|
+
const m = l.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
|
90
|
+
n = m ? Number(m[1]) : 0;
|
|
91
|
+
} else if (!header && file && l.startsWith("+")) {
|
|
92
|
+
out.push({ file, line: n, text: l.slice(1) });
|
|
93
|
+
n++;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
for (const f of await untrackedFiles()) {
|
|
97
|
+
let buf;
|
|
98
|
+
try {
|
|
99
|
+
buf = fs.readFileSync(path.join(cwd, f));
|
|
100
|
+
} catch (_e) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (buf.includes(0)) continue;
|
|
104
|
+
const text = buf.toString("utf8").split(/\r?\n/);
|
|
105
|
+
if (text.length && text[text.length - 1] === "") text.pop();
|
|
106
|
+
text.forEach((t, i) => out.push({ file: f, line: i + 1, text: t }));
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
},
|
|
110
|
+
/**
|
|
111
|
+
* The commits HEAD has past a ref, oldest first:
|
|
112
|
+
* [{ sha, subject, message, parents, files }]. A merge commit's files
|
|
113
|
+
* are empty (git log names none for it).
|
|
114
|
+
*/
|
|
115
|
+
commits: async (ref) => {
|
|
116
|
+
await needRef(ref);
|
|
117
|
+
const raw = await must(
|
|
118
|
+
["-c", "core.quotePath=false", "log", "--reverse", "--name-only", "--no-renames", "--format=%x1e%H%x1f%P%x1f%B%x1f", `${ref}..HEAD`],
|
|
119
|
+
`Can't list the commits past ${ref}`,
|
|
120
|
+
);
|
|
121
|
+
return raw
|
|
122
|
+
.split("\x1e")
|
|
123
|
+
.filter((c) => c.trim())
|
|
124
|
+
.map((c) => {
|
|
125
|
+
const [sha, parents, message, names = ""] = c.split("\x1f");
|
|
126
|
+
const msg = message.trim();
|
|
127
|
+
return {
|
|
128
|
+
sha: sha.trim(),
|
|
129
|
+
subject: msg.split("\n")[0],
|
|
130
|
+
message: msg,
|
|
131
|
+
parents: parents.trim().split(/\s+/).filter(Boolean),
|
|
132
|
+
files: lines(names),
|
|
133
|
+
};
|
|
134
|
+
});
|
|
135
|
+
},
|
|
60
136
|
lastCommitMessage: async () => (await must(["log", "-1", "--format=%B"], "Can't read the last commit")).trim(),
|
|
61
137
|
/** Does the remote (origin) have this branch? */
|
|
62
138
|
remoteHas: async (branch, remote = "origin") => {
|
package/lib/helper.js
CHANGED
|
@@ -49,6 +49,23 @@ function normParams(id, params) {
|
|
|
49
49
|
return out;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
+
/** "a, b" → ["a", "b"], leaving commas in a glob's {a,b} alone. */
|
|
53
|
+
function splitList(s) {
|
|
54
|
+
const out = [];
|
|
55
|
+
let depth = 0;
|
|
56
|
+
let cur = "";
|
|
57
|
+
for (const c of s) {
|
|
58
|
+
if (c === "{") depth++;
|
|
59
|
+
else if (c === "}" && depth > 0) depth--;
|
|
60
|
+
if (c === "," && depth === 0) {
|
|
61
|
+
out.push(cur);
|
|
62
|
+
cur = "";
|
|
63
|
+
} else cur += c;
|
|
64
|
+
}
|
|
65
|
+
out.push(cur);
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
52
69
|
/** A param's value, converted to its type, or throws saying what's wrong. */
|
|
53
70
|
function coerce(id, name, p, v) {
|
|
54
71
|
const bad = (what) => new DashCheckError(`${id}: ${p.label} (${name}) ${what}`, { fix: `got ${fmt(v)}` });
|
|
@@ -71,7 +88,7 @@ function coerce(id, name, p, v) {
|
|
|
71
88
|
if (!p.options.map(String).includes(String(v))) throw bad(`must be one of ${p.options.join(", ")}`);
|
|
72
89
|
return p.options.find((o) => String(o) === String(v));
|
|
73
90
|
case "list": {
|
|
74
|
-
const list = Array.isArray(v) ? v : String(v)
|
|
91
|
+
const list = Array.isArray(v) ? v : splitList(String(v));
|
|
75
92
|
return list.map((x) => (typeof x === "string" ? x.trim() : x)).filter((x) => x !== "" && x !== undefined && x !== null);
|
|
76
93
|
}
|
|
77
94
|
case "regex":
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trops/dash-check",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Compose deterministic checks from small, described building blocks: Jest-style files, JSON recipes and helpers. Runs in Dash, in CI and on a laptop.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "trops",
|