@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.
- package/README.md +68 -8
- 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 +114 -4
- package/helpers/node.js +192 -2
- package/helpers/plan.js +86 -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/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,123 @@
|
|
|
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
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface EvidenceForAcceptanceParams {
|
|
77
|
+
/** The evidence: { searchedDone, missing: [{ acceptance, read, why }] }. Default "notYetDone". */
|
|
78
|
+
key?: string;
|
|
79
|
+
/** Default "acceptance". */
|
|
80
|
+
acceptanceKey?: string;
|
|
81
|
+
/** Needs searchedDone. Default true. */
|
|
82
|
+
requireSearch?: boolean;
|
|
83
|
+
/** Judge only when the handoff's status is one of these; others pass. Default ["ok"]; empty judges every handoff. */
|
|
84
|
+
when?: List;
|
|
85
|
+
}
|
|
86
|
+
export interface NoOpenDecisionsParams {
|
|
87
|
+
/** Default "openDecisions". */
|
|
88
|
+
key?: string;
|
|
89
|
+
/** Judge only when the handoff's status is one of these; others pass. Default ["ok"]; empty judges every handoff. */
|
|
90
|
+
when?: List;
|
|
91
|
+
}
|
|
5
92
|
|
|
6
93
|
export const handoff: { has: H; status: H; eachHas: H };
|
|
7
|
-
export const plan: {
|
|
8
|
-
|
|
9
|
-
|
|
94
|
+
export const plan: {
|
|
95
|
+
hasSections: H;
|
|
96
|
+
acceptanceEachHasTest: H;
|
|
97
|
+
evidenceForAcceptance: Helper<EvidenceForAcceptanceParams>;
|
|
98
|
+
noOpenDecisions: Helper<NoOpenDecisionsParams>;
|
|
99
|
+
};
|
|
100
|
+
export const git: {
|
|
101
|
+
onBranch: H;
|
|
102
|
+
committedSince: H;
|
|
103
|
+
clean: H;
|
|
104
|
+
changedOnly: H;
|
|
105
|
+
noChangesTo: H;
|
|
106
|
+
changesMatchPlan: Helper<ChangesMatchPlanParams>;
|
|
107
|
+
commitsScoped: Helper<CommitsScopedParams>;
|
|
108
|
+
sourceHasTests: Helper<SourceHasTestsParams>;
|
|
109
|
+
noNewMatches: Helper<NoNewMatchesParams>;
|
|
110
|
+
validateLeavesTreeClean: Helper<ValidateLeavesTreeCleanParams>;
|
|
111
|
+
};
|
|
112
|
+
export const files: { exist: H; contain: H; noneMatch: H; maxGrowth: Helper<MaxGrowthParams> };
|
|
10
113
|
export const commands: { passes: H; outputMatches: H };
|
|
11
|
-
export const node: {
|
|
114
|
+
export const node: {
|
|
115
|
+
testsPass: H;
|
|
116
|
+
lintPasses: H;
|
|
117
|
+
noNewDependencies: H;
|
|
118
|
+
lockfileExplained: Helper<LockfileExplainedParams>;
|
|
119
|
+
testScriptIsReal: Helper<TestScriptIsRealParams>;
|
|
120
|
+
newTestsAreRun: Helper<NewTestsAreRunParams>;
|
|
121
|
+
};
|
|
12
122
|
export const github: { prOpen: H; ciPassed: H };
|
|
13
123
|
export const tracker: { ticketExists: H; ticketHasLabel: H };
|
|
14
124
|
/** 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 };
|