@trops/dash-check 0.0.0-stage → 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.
Files changed (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +355 -2
  3. package/cli/bin.js +12 -0
  4. package/cli/index.d.ts +7 -0
  5. package/cli/index.js +566 -0
  6. package/examples/changes-match-plan.bad.json +4 -0
  7. package/examples/changes-match-plan.check.js +18 -0
  8. package/examples/changes-match-plan.sample.json +4 -0
  9. package/examples/commits-scoped.bad.json +5 -0
  10. package/examples/commits-scoped.check.json +6 -0
  11. package/examples/commits-scoped.sample.json +5 -0
  12. package/examples/every-acceptance-has-a-test.bad.json +3 -0
  13. package/examples/every-acceptance-has-a-test.check.js +19 -0
  14. package/examples/every-acceptance-has-a-test.sample.json +3 -0
  15. package/examples/helpers/changelog.js +23 -0
  16. package/examples/jira-comment-from-job.bad.json +5 -0
  17. package/examples/jira-comment-from-job.check.js +10 -0
  18. package/examples/jira-comment-from-job.sample.json +5 -0
  19. package/examples/lockfile-explained.bad.json +11 -0
  20. package/examples/lockfile-explained.check.json +6 -0
  21. package/examples/lockfile-explained.sample.json +11 -0
  22. package/examples/max-growth.bad.json +8 -0
  23. package/examples/max-growth.check.json +6 -0
  24. package/examples/max-growth.sample.json +8 -0
  25. package/examples/merge-outcome.bad.json +4 -0
  26. package/examples/merge-outcome.check.js +9 -0
  27. package/examples/merge-outcome.sample.json +4 -0
  28. package/examples/new-tests-are-run.bad.json +4 -0
  29. package/examples/new-tests-are-run.check.json +7 -0
  30. package/examples/new-tests-are-run.sample.json +4 -0
  31. package/examples/no-new-debt.bad.json +8 -0
  32. package/examples/no-new-debt.check.json +14 -0
  33. package/examples/no-new-debt.sample.json +8 -0
  34. package/examples/on-branch.bad.json +6 -0
  35. package/examples/on-branch.check.js +12 -0
  36. package/examples/on-branch.sample.json +6 -0
  37. package/examples/plan-complete.bad.json +5 -0
  38. package/examples/plan-complete.check.js +14 -0
  39. package/examples/plan-complete.sample.json +5 -0
  40. package/examples/plan-scope.bad.json +4 -0
  41. package/examples/plan-scope.check.json +6 -0
  42. package/examples/plan-scope.sample.json +4 -0
  43. package/examples/pr-ci.bad.json +4 -0
  44. package/examples/pr-ci.check.js +12 -0
  45. package/examples/pr-ci.sample.json +4 -0
  46. package/examples/ready-for-review.bad.json +6 -0
  47. package/examples/ready-for-review.check.json +12 -0
  48. package/examples/ready-for-review.sample.json +6 -0
  49. package/examples/setup.bad.json +6 -0
  50. package/examples/setup.check.js +8 -0
  51. package/examples/setup.sample.json +6 -0
  52. package/examples/source-has-tests.bad.json +4 -0
  53. package/examples/source-has-tests.check.json +6 -0
  54. package/examples/source-has-tests.sample.json +4 -0
  55. package/examples/test-script-is-real.bad.json +6 -0
  56. package/examples/test-script-is-real.check.json +6 -0
  57. package/examples/test-script-is-real.sample.json +6 -0
  58. package/examples/ticket-has-acceptance.bad.json +4 -0
  59. package/examples/ticket-has-acceptance.check.js +10 -0
  60. package/examples/ticket-has-acceptance.sample.json +4 -0
  61. package/examples/validate-leaves-tree-clean.bad.json +6 -0
  62. package/examples/validate-leaves-tree-clean.check.json +7 -0
  63. package/examples/validate-leaves-tree-clean.sample.json +6 -0
  64. package/examples/validate.bad.json +6 -0
  65. package/examples/validate.check.js +14 -0
  66. package/examples/validate.sample.json +6 -0
  67. package/examples/work-committed.bad.json +13 -0
  68. package/examples/work-committed.check.js +13 -0
  69. package/examples/work-committed.sample.json +5 -0
  70. package/examples/workspace-cleaned.bad.json +4 -0
  71. package/examples/workspace-cleaned.check.js +7 -0
  72. package/examples/workspace-cleaned.sample.json +4 -0
  73. package/helpers/commands.js +62 -0
  74. package/helpers/files.js +124 -0
  75. package/helpers/git.js +379 -0
  76. package/helpers/github.js +77 -0
  77. package/helpers/handoff.js +80 -0
  78. package/helpers/index.d.ts +103 -0
  79. package/helpers/index.js +36 -0
  80. package/helpers/node.js +296 -0
  81. package/helpers/plan.js +55 -0
  82. package/helpers/tracker.js +60 -0
  83. package/index.d.ts +347 -0
  84. package/index.js +86 -0
  85. package/lib/adapters/fs.js +85 -0
  86. package/lib/adapters/git.js +163 -0
  87. package/lib/adapters/github.js +151 -0
  88. package/lib/adapters/run.js +76 -0
  89. package/lib/adapters/tool.js +64 -0
  90. package/lib/context.js +102 -0
  91. package/lib/discover.js +102 -0
  92. package/lib/expect.js +238 -0
  93. package/lib/glob.js +89 -0
  94. package/lib/handoff.js +68 -0
  95. package/lib/helper.js +236 -0
  96. package/lib/register.js +35 -0
  97. package/lib/runner.js +214 -0
  98. package/lib/scope.js +107 -0
  99. package/lib/util.js +122 -0
  100. package/lib/values.js +138 -0
  101. package/package.json +59 -4
  102. package/recipe/index.d.ts +70 -0
  103. package/recipe/index.js +381 -0
  104. package/recipe/schema.json +55 -0
@@ -0,0 +1,103 @@
1
+ // Types for @trops/dash-check/helpers: the starter helpers.
2
+ import type { Helper } from "..";
3
+
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
+ }
75
+
76
+ export const handoff: { has: H; status: H; eachHas: H };
77
+ export const plan: { hasSections: H; acceptanceEachHasTest: H };
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> };
91
+ export const commands: { passes: H; outputMatches: H };
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
+ };
100
+ export const github: { prOpen: H; ciPassed: H };
101
+ export const tracker: { ticketExists: H; ticketHasLabel: H };
102
+ /** Every starter helper. */
103
+ export const all: H[];
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @trops/dash-check/helpers: the starter helpers, each a few lines of
3
+ * Layer 0. Call one with the check's ctx and its params:
4
+ *
5
+ * const { git, node, files } = require("@trops/dash-check/helpers");
6
+ * await git.committedSince(ctx, { base: "main" });
7
+ */
8
+ "use strict";
9
+
10
+ const { registerHelpers } = require("..");
11
+
12
+ const groups = {
13
+ handoff: require("./handoff"),
14
+ plan: require("./plan"),
15
+ git: require("./git"),
16
+ files: require("./files"),
17
+ commands: require("./commands"),
18
+ node: require("./node"),
19
+ github: require("./github"),
20
+ tracker: require("./tracker"),
21
+ };
22
+
23
+ const exported = {};
24
+ const all = [];
25
+ for (const [name, mod] of Object.entries(groups)) {
26
+ exported[name] = {};
27
+ for (const [k, v] of Object.entries(mod)) {
28
+ if (v && v.isDashCheckHelper) {
29
+ exported[name][k] = v;
30
+ all.push(v);
31
+ }
32
+ }
33
+ }
34
+ registerHelpers(all, { source: "@trops/dash-check" });
35
+
36
+ module.exports = { ...exported, all };
@@ -0,0 +1,296 @@
1
+ /**
2
+ * Node helpers: a Node repo's tests, lint and dependencies. Built only
3
+ * from Layer 0 (ctx.run, ctx.fs, ctx.git).
4
+ */
5
+ "use strict";
6
+
7
+ const { defineHelper, fail, note, matchGlob, deepEqual } = require("..");
8
+ const { runOrFail } = require("./commands");
9
+ const { baseRef } = require("./git");
10
+
11
+ /** How many tests passed, from common runners' summaries, or null. */
12
+ function testCount(out) {
13
+ const s = String(out || "");
14
+ const pats = [
15
+ /Tests:\s+(?:\d+ \w+, )*(\d+) passed/, // jest
16
+ /^# pass (\d+)/m, // node --test (TAP)
17
+ /ℹ pass (\d+)/, // node --test (spec)
18
+ /(\d+) passing/, // mocha
19
+ /Tests\s+(\d+) passed/, // vitest
20
+ ];
21
+ for (const p of pats) {
22
+ const m = s.match(p);
23
+ if (m) return Number(m[1]);
24
+ }
25
+ return null;
26
+ }
27
+
28
+ const testsPass = defineHelper({
29
+ id: "node.testsPass",
30
+ group: "Node",
31
+ label: "Tests pass",
32
+ description: "npm test, or a command",
33
+ sentence: "run {command}",
34
+ params: {
35
+ command: { type: "text", label: "Command", default: "npm test" },
36
+ timeoutSec: { type: "number", label: "Time limit (s)", default: 900 },
37
+ },
38
+ reads: ["run"],
39
+ async run(ctx, { command, timeoutSec }) {
40
+ const r = await runOrFail(ctx, command, timeoutSec, `${command}`);
41
+ if (r.code === 0 && !r.timedOut) {
42
+ const n = testCount(`${r.stdout}\n${r.stderr}`);
43
+ note(n === null ? `${command} passed` : `${n} test${n === 1 ? "" : "s"} passed`);
44
+ }
45
+ },
46
+ });
47
+
48
+ const lintPasses = defineHelper({
49
+ id: "node.lintPasses",
50
+ group: "Node",
51
+ label: "Lint passes",
52
+ description: "npm run lint, or a command",
53
+ sentence: "run {command}",
54
+ params: {
55
+ command: { type: "text", label: "Command", default: "npm run lint" },
56
+ timeoutSec: { type: "number", label: "Time limit (s)", default: 300 },
57
+ },
58
+ reads: ["run"],
59
+ async run(ctx, { command, timeoutSec }) {
60
+ const r = await runOrFail(ctx, command, timeoutSec);
61
+ if (r.code === 0 && !r.timedOut) note(`${command} passed`);
62
+ },
63
+ });
64
+
65
+ const DEP_KEYS = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"];
66
+
67
+ const noNewDependencies = defineHelper({
68
+ id: "node.noNewDependencies",
69
+ group: "Node",
70
+ label: "No new dependencies",
71
+ description: "package.json adds none since the base",
72
+ sentence: "package.json adds no dependencies since {base}",
73
+ params: {
74
+ base: { type: "text", label: "Base branch", default: "{repo.baseBranch}" },
75
+ allow: { type: "list", label: "Allowed", description: "Packages that may be added" },
76
+ },
77
+ reads: ["git", "fs"],
78
+ async run(ctx, { base, allow }) {
79
+ const ref = await baseRef(ctx, base);
80
+ const before = await ctx.git.fileAt(ref, "package.json");
81
+ if (before === null) {
82
+ fail(`package.json isn't on ${ref}, so there's nothing to compare with`);
83
+ return;
84
+ }
85
+ if (!(await ctx.fs.exists("package.json"))) {
86
+ fail("package.json isn't in the workspace");
87
+ return;
88
+ }
89
+ let old;
90
+ try {
91
+ old = JSON.parse(before);
92
+ } catch (e) {
93
+ fail(`package.json on ${ref} isn't valid JSON (${e.message})`);
94
+ return;
95
+ }
96
+ const now = await ctx.fs.readJson("package.json");
97
+ const names = (p) => new Set(DEP_KEYS.flatMap((k) => Object.keys((p && p[k]) || {})));
98
+ const had = names(old);
99
+ const added = [...names(now)].filter((n) => !had.has(n) && !allow.includes(n)).sort();
100
+ if (added.length) {
101
+ fail(`package.json adds ${added.length === 1 ? "a dependency" : "dependencies"}: remove ${added.length === 1 ? "it" : "them"}, or allow ${added.length === 1 ? "it" : "them"} on the check`, { at: added.join(", "), received: added });
102
+ } else note(`No new dependencies since ${ref}`);
103
+ },
104
+ });
105
+
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 };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Plan helpers: the plan a planning bot hands on. Built only from Layer 0.
3
+ */
4
+ "use strict";
5
+
6
+ const { defineHelper, expect, note } = require("..");
7
+ const { needHandoff } = require("./handoff");
8
+
9
+ const hasSections = defineHelper({
10
+ id: "plan.hasSections",
11
+ group: "Handoff",
12
+ label: "The plan has sections",
13
+ description: "The handoff's plan has each section, not empty",
14
+ sentence: "handoff.{key} has {sections}",
15
+ params: {
16
+ key: { type: "text", label: "Plan key", default: "plan" },
17
+ sections: { type: "list", label: "Sections", default: ["cause", "fix", "test"] },
18
+ },
19
+ reads: ["handoff"],
20
+ run(ctx, { key, sections }) {
21
+ if (!needHandoff(ctx)) return;
22
+ for (const s of sections) {
23
+ expect(ctx.get(`handoff.${key}.${s}`), `handoff.${key}.${s}`).not.toBeEmpty(`The ${key} has no ${s}`);
24
+ }
25
+ note(`The ${key} has ${sections.join(", ")}`);
26
+ },
27
+ });
28
+
29
+ const acceptanceEachHasTest = defineHelper({
30
+ id: "plan.acceptanceEachHasTest",
31
+ group: "Handoff",
32
+ label: "Each acceptance item has a test",
33
+ description: "Plan: every item is tested",
34
+ sentence: "every item in handoff.{acceptance} has a test in handoff.{tests}",
35
+ params: {
36
+ acceptance: { type: "text", label: "Acceptance key", default: "acceptance" },
37
+ tests: { type: "text", label: "Tests key", default: "tests" },
38
+ },
39
+ reads: ["handoff"],
40
+ run(ctx, { acceptance, tests }) {
41
+ if (!needHandoff(ctx)) return;
42
+ const items = ctx.get(`handoff.${acceptance}`);
43
+ if (!expect(items, `handoff.${acceptance}`).toBeArray(`The handoff has no ${acceptance} list`)) return;
44
+ if (!expect(items, `handoff.${acceptance}`).not.toBeEmpty(`The handoff's ${acceptance} is empty`)) return;
45
+ const list = ctx.get(`handoff.${tests}`);
46
+ const all = Array.isArray(list) ? list : [];
47
+ for (const a of items) {
48
+ const t = all.find((x) => x && typeof x === "object" && x.acceptance === a);
49
+ expect(t && t.test, `the test for "${a}"`).toBeNonEmptyString(`No test for: ${a}`);
50
+ }
51
+ note(`${items.length} acceptance item${items.length === 1 ? "" : "s"}, each with a test`);
52
+ },
53
+ });
54
+
55
+ module.exports = { hasSections, acceptanceEachHasTest };
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Tracker helpers: the work item in its tracker, through ctx.tool (so they
3
+ * run only in Dash, which supplies the provider). Built only from Layer 0.
4
+ * The defaults are Jira's; for another tracker set provider, tool and idArg.
5
+ */
6
+ "use strict";
7
+
8
+ const { defineHelper, expect, fail, note } = require("..");
9
+
10
+ const TRACKER = {
11
+ provider: { type: "text", label: "Provider", default: "jira" },
12
+ tool: { type: "text", label: "Tool", default: "getJiraIssue" },
13
+ idArg: { type: "text", label: "Id argument", default: "issueIdOrKey" },
14
+ id: { type: "text", label: "Item id", default: "{item.id}" },
15
+ };
16
+
17
+ async function fetchTicket(ctx, { provider, tool, idArg, id }) {
18
+ if (!id) {
19
+ fail("The job has no work item id: run it on a job with an item, or set the item id");
20
+ return null;
21
+ }
22
+ const t = await ctx.tool(provider, tool, { [idArg]: id });
23
+ if (!t || (typeof t === "object" && !Object.keys(t).length)) {
24
+ fail(`${id} isn't in ${provider}: check the id`);
25
+ return null;
26
+ }
27
+ return t;
28
+ }
29
+
30
+ const ticketExists = defineHelper({
31
+ id: "tracker.ticketExists",
32
+ group: "Tracker",
33
+ label: "The ticket exists",
34
+ description: "The work item is in the tracker",
35
+ sentence: "{id} exists in {provider}",
36
+ params: TRACKER,
37
+ reads: ["tool", "item"],
38
+ async run(ctx, p) {
39
+ if (await fetchTicket(ctx, p)) note(`${p.id} is in ${p.provider}`);
40
+ },
41
+ });
42
+
43
+ const ticketHasLabel = defineHelper({
44
+ id: "tracker.ticketHasLabel",
45
+ group: "Tracker",
46
+ label: "The ticket has a label",
47
+ description: "The work item carries a label",
48
+ sentence: "{id} has the label {label}",
49
+ params: { label: { type: "text", label: "Label", required: true }, ...TRACKER },
50
+ reads: ["tool", "item"],
51
+ async run(ctx, p) {
52
+ const t = await fetchTicket(ctx, p);
53
+ if (!t) return;
54
+ const raw = (t.fields && t.fields.labels) || t.labels || [];
55
+ const labels = raw.map((l) => (l && typeof l === "object" ? l.name : l));
56
+ expect(labels, `${p.id}'s labels`).toContain(p.label, `${p.id} has no label "${p.label}": add it`);
57
+ },
58
+ });
59
+
60
+ module.exports = { ticketExists, ticketHasLabel };