@trops/dash-check 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +309 -2
- package/cli/bin.js +12 -0
- package/cli/index.d.ts +7 -0
- package/cli/index.js +566 -0
- package/examples/changes-match-plan.bad.json +4 -0
- package/examples/changes-match-plan.check.js +10 -0
- package/examples/changes-match-plan.sample.json +4 -0
- package/examples/every-acceptance-has-a-test.bad.json +3 -0
- package/examples/every-acceptance-has-a-test.check.js +19 -0
- package/examples/every-acceptance-has-a-test.sample.json +3 -0
- package/examples/helpers/changelog.js +23 -0
- package/examples/jira-comment-from-job.bad.json +5 -0
- package/examples/jira-comment-from-job.check.js +10 -0
- package/examples/jira-comment-from-job.sample.json +5 -0
- package/examples/merge-outcome.bad.json +4 -0
- package/examples/merge-outcome.check.js +9 -0
- package/examples/merge-outcome.sample.json +4 -0
- package/examples/on-branch.bad.json +6 -0
- package/examples/on-branch.check.js +12 -0
- package/examples/on-branch.sample.json +6 -0
- package/examples/plan-complete.bad.json +5 -0
- package/examples/plan-complete.check.js +14 -0
- package/examples/plan-complete.sample.json +5 -0
- package/examples/pr-ci.bad.json +4 -0
- package/examples/pr-ci.check.js +12 -0
- package/examples/pr-ci.sample.json +4 -0
- package/examples/ready-for-review.bad.json +6 -0
- package/examples/ready-for-review.check.json +12 -0
- package/examples/ready-for-review.sample.json +6 -0
- package/examples/setup.bad.json +6 -0
- package/examples/setup.check.js +8 -0
- package/examples/setup.sample.json +6 -0
- package/examples/ticket-has-acceptance.bad.json +4 -0
- package/examples/ticket-has-acceptance.check.js +10 -0
- package/examples/ticket-has-acceptance.sample.json +4 -0
- package/examples/validate.bad.json +6 -0
- package/examples/validate.check.js +14 -0
- package/examples/validate.sample.json +6 -0
- package/examples/work-committed.bad.json +13 -0
- package/examples/work-committed.check.js +13 -0
- package/examples/work-committed.sample.json +5 -0
- package/examples/workspace-cleaned.bad.json +4 -0
- package/examples/workspace-cleaned.check.js +7 -0
- package/examples/workspace-cleaned.sample.json +4 -0
- package/helpers/commands.js +62 -0
- package/helpers/files.js +74 -0
- package/helpers/git.js +116 -0
- package/helpers/github.js +77 -0
- package/helpers/handoff.js +80 -0
- package/helpers/index.d.ts +15 -0
- package/helpers/index.js +36 -0
- package/helpers/node.js +106 -0
- package/helpers/plan.js +55 -0
- package/helpers/tracker.js +60 -0
- package/index.d.ts +325 -0
- package/index.js +86 -0
- package/lib/adapters/fs.js +85 -0
- package/lib/adapters/git.js +87 -0
- package/lib/adapters/github.js +151 -0
- package/lib/adapters/run.js +76 -0
- package/lib/adapters/tool.js +64 -0
- package/lib/context.js +102 -0
- package/lib/discover.js +102 -0
- package/lib/expect.js +238 -0
- package/lib/glob.js +89 -0
- package/lib/handoff.js +68 -0
- package/lib/helper.js +219 -0
- package/lib/register.js +35 -0
- package/lib/runner.js +214 -0
- package/lib/scope.js +107 -0
- package/lib/util.js +122 -0
- package/lib/values.js +138 -0
- package/package.json +59 -4
- package/recipe/index.d.ts +70 -0
- package/recipe/index.js +381 -0
- package/recipe/schema.json +55 -0
package/cli/index.js
ADDED
|
@@ -0,0 +1,566 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @trops/dash-check/cli: `dash-check`, run a repo's checks the way Dash
|
|
3
|
+
* runs them.
|
|
4
|
+
*
|
|
5
|
+
* dash-check every check in .dash/checks/
|
|
6
|
+
* dash-check <name> [--input f.json] one check (<name>.sample.json by default)
|
|
7
|
+
* dash-check --watch run again on every change
|
|
8
|
+
* dash-check --ci a Jest-like report, exit 1 on failure
|
|
9
|
+
* dash-check --list what's there
|
|
10
|
+
* dash-check --list-helpers [--json] [--input f.json]
|
|
11
|
+
* every helper and matcher (the composer's palette)
|
|
12
|
+
* dash-check --explain <file> a check as sentences
|
|
13
|
+
* dash-check new <name> [--recipe] a new check and its sample input
|
|
14
|
+
*
|
|
15
|
+
* A check gets Dash's contract: cwd is the repo, the input as JSON in
|
|
16
|
+
* $DASH_INPUT and on stdin, DASH_ITEM_*, DASH_WORKSPACE, DASH_BRANCH and
|
|
17
|
+
* DASH_STEP; exit 0 passes; a last line of {"reason", "details"} says why.
|
|
18
|
+
* `.check.js` files run in their own node, `.check.json` recipes run here,
|
|
19
|
+
* and any other file runs by its #! line, else its extension (.js node,
|
|
20
|
+
* .sh bash, .py python3, else sh).
|
|
21
|
+
*
|
|
22
|
+
* Exit codes: 0 passed, 1 a check failed, 2 bad arguments or no such check.
|
|
23
|
+
*/
|
|
24
|
+
"use strict";
|
|
25
|
+
|
|
26
|
+
const fs = require("fs");
|
|
27
|
+
const os = require("os");
|
|
28
|
+
const path = require("path");
|
|
29
|
+
const { spawn, execFileSync } = require("child_process");
|
|
30
|
+
|
|
31
|
+
const core = require("..");
|
|
32
|
+
const recipe = require("../recipe");
|
|
33
|
+
const { loadHelpers } = require("../lib/discover");
|
|
34
|
+
const { report, loadChecks } = require("../lib/runner");
|
|
35
|
+
|
|
36
|
+
const CHECKS_DIR = ".dash/checks";
|
|
37
|
+
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
|
|
38
|
+
const RUNNERS = { ".js": "node", ".cjs": "node", ".mjs": "node", ".sh": "bash", ".bash": "bash", ".py": "python3" };
|
|
39
|
+
const DEFAULT_TIMEOUT_SEC = 120;
|
|
40
|
+
const SAMPLE = { input: { answer: "" }, item: null, workspace: null };
|
|
41
|
+
const REGISTER = path.join(__dirname, "..", "lib", "register.js");
|
|
42
|
+
|
|
43
|
+
const USAGE = `Usage:
|
|
44
|
+
dash-check run every check in ${CHECKS_DIR}/
|
|
45
|
+
dash-check <name> [--input f.json] run one (default input: <name>.sample.json)
|
|
46
|
+
dash-check --watch run again on every change
|
|
47
|
+
dash-check --ci [a,b] a Jest-like report; exit 1 on failure
|
|
48
|
+
dash-check --list list the checks
|
|
49
|
+
dash-check --list-helpers [--json] [--input f.json]
|
|
50
|
+
every helper and matcher, with metadata
|
|
51
|
+
dash-check --explain <file> a check as sentences
|
|
52
|
+
dash-check new <name> [--recipe] scaffold a check and its sample input
|
|
53
|
+
Options: --cwd <dir>, --timeout <sec>, --json (results as JSON), --no-color`;
|
|
54
|
+
|
|
55
|
+
function parseArgs(argv) {
|
|
56
|
+
const a = { names: [], cwd: process.cwd(), input: null, timeout: null, color: null };
|
|
57
|
+
for (let i = 0; i < argv.length; i++) {
|
|
58
|
+
const v = argv[i];
|
|
59
|
+
const val = () => {
|
|
60
|
+
const x = argv[++i];
|
|
61
|
+
if (x === undefined) throw new Error(`${v} needs a value`);
|
|
62
|
+
return x;
|
|
63
|
+
};
|
|
64
|
+
try {
|
|
65
|
+
if (v === "--input" || v === "-i") a.input = val();
|
|
66
|
+
else if (v === "--cwd") a.cwd = path.resolve(val());
|
|
67
|
+
else if (v === "--timeout") a.timeout = Number(val());
|
|
68
|
+
else if (v === "--watch" || v === "-w") a.watch = true;
|
|
69
|
+
else if (v === "--ci") {
|
|
70
|
+
a.ci = true;
|
|
71
|
+
if (argv[i + 1] && !argv[i + 1].startsWith("-")) a.names.push(...argv[++i].split(",").filter(Boolean));
|
|
72
|
+
} else if (v === "--list") a.list = true;
|
|
73
|
+
else if (v === "--list-helpers") a.listHelpers = true;
|
|
74
|
+
else if (v === "--json") a.json = true;
|
|
75
|
+
else if (v === "--explain") a.explain = val();
|
|
76
|
+
else if (v === "--recipe") a.recipe = true;
|
|
77
|
+
else if (v === "--no-color") a.color = false;
|
|
78
|
+
else if (v === "--help" || v === "-h") a.help = true;
|
|
79
|
+
else if (v.startsWith("-")) return { error: `Unknown option ${v}` };
|
|
80
|
+
else a.names.push(v);
|
|
81
|
+
} catch (e) {
|
|
82
|
+
return { error: e.message };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (a.names[0] === "new" && !a.ci) {
|
|
86
|
+
a.create = a.names[1] || "";
|
|
87
|
+
a.names = [];
|
|
88
|
+
}
|
|
89
|
+
return a;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The checks in a repo: [{ name, file, type: "js" | "recipe" | "exec", sample? }]. */
|
|
93
|
+
function listChecks(cwd) {
|
|
94
|
+
const dir = path.join(cwd, CHECKS_DIR);
|
|
95
|
+
let entries = [];
|
|
96
|
+
try {
|
|
97
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
98
|
+
} catch (_e) {
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
const out = [];
|
|
102
|
+
for (const e of entries) {
|
|
103
|
+
const f = e.name;
|
|
104
|
+
if (f.startsWith(".")) continue;
|
|
105
|
+
if (e.isDirectory()) {
|
|
106
|
+
if (f === "helpers") continue;
|
|
107
|
+
try {
|
|
108
|
+
const m = JSON.parse(fs.readFileSync(path.join(dir, f, "check.json"), "utf8"));
|
|
109
|
+
if (m && typeof m.run === "string") out.push({ name: f, file: path.join(f, m.run), type: "exec", order: 2 });
|
|
110
|
+
} catch (_e) {
|
|
111
|
+
// A folder that isn't a check package.
|
|
112
|
+
}
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
let m;
|
|
116
|
+
if ((m = f.match(/^(.+)\.check\.c?js$/))) out.push({ name: m[1], file: f, type: "js", order: 0 });
|
|
117
|
+
else if ((m = f.match(/^(.+)\.check\.json$/))) out.push({ name: m[1], file: f, type: "recipe", order: 0 });
|
|
118
|
+
else if (/\.(md|json|txt|d\.ts)$/i.test(f)) continue;
|
|
119
|
+
else out.push({ name: f.replace(/\.[^.]+$/, ""), file: f, type: "exec", order: 1 });
|
|
120
|
+
}
|
|
121
|
+
out.sort((x, y) => x.name.localeCompare(y.name) || x.order - y.order || x.file.localeCompare(y.file));
|
|
122
|
+
const seen = new Set();
|
|
123
|
+
return out
|
|
124
|
+
.filter((c) => (seen.has(c.name) ? false : seen.add(c.name)))
|
|
125
|
+
.map((c) => {
|
|
126
|
+
const sample = path.join(dir, `${c.name}.sample.json`);
|
|
127
|
+
return { name: c.name, file: c.file, type: c.type, ...(fs.existsSync(sample) ? { sample } : {}) };
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function pick(checks, name) {
|
|
132
|
+
return checks.find((c) => c.file === name) || checks.find((c) => c.name === name) || null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function gitBranch(cwd) {
|
|
136
|
+
try {
|
|
137
|
+
return execFileSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
138
|
+
} catch (_e) {
|
|
139
|
+
return "";
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The environment Dash gives a check. */
|
|
144
|
+
function dashEnv(cwd, input, name, inputFile) {
|
|
145
|
+
const env = { ...process.env };
|
|
146
|
+
delete env.NODE_TEST_CONTEXT;
|
|
147
|
+
const item = (input && input.item) || {};
|
|
148
|
+
return {
|
|
149
|
+
...env,
|
|
150
|
+
DASH_INPUT: inputFile,
|
|
151
|
+
DASH_CHECK_QUIET: "1",
|
|
152
|
+
DASH_STEP: name,
|
|
153
|
+
DASH_WORKSPACE: cwd,
|
|
154
|
+
DASH_BRANCH: (input && input.workspace && input.workspace.branch) || gitBranch(cwd),
|
|
155
|
+
...(item.id ? { DASH_ITEM_ID: String(item.id) } : {}),
|
|
156
|
+
...(item.title ? { DASH_ITEM_TITLE: String(item.title) } : {}),
|
|
157
|
+
...(item.url ? { DASH_ITEM_URL: String(item.url) } : {}),
|
|
158
|
+
...(item.source ? { DASH_ITEM_SOURCE: String(item.source) } : {}),
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** The last {"reason", "details"} line of some output, or null. */
|
|
163
|
+
function lastProof(out) {
|
|
164
|
+
const lines = String(out || "").trim().split(/\r?\n/).filter(Boolean);
|
|
165
|
+
for (let i = lines.length - 1; i >= 0 && i >= lines.length - 3; i--) {
|
|
166
|
+
try {
|
|
167
|
+
const v = JSON.parse(lines[i]);
|
|
168
|
+
if (v && typeof v === "object" && ("reason" in v || "details" in v)) return { proof: v, index: i, lines };
|
|
169
|
+
} catch (_e) {
|
|
170
|
+
// Not JSON.
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function spawnP(cmd, args, { cwd, env, input, timeoutSec }) {
|
|
177
|
+
return new Promise((resolve) => {
|
|
178
|
+
let stdout = "";
|
|
179
|
+
let stderr = "";
|
|
180
|
+
let timedOut = false;
|
|
181
|
+
let child;
|
|
182
|
+
try {
|
|
183
|
+
child = spawn(cmd, args, { cwd, env, stdio: ["pipe", "pipe", "pipe"] });
|
|
184
|
+
} catch (e) {
|
|
185
|
+
resolve({ code: null, stdout: "", stderr: "", error: e });
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const timer = setTimeout(() => {
|
|
189
|
+
timedOut = true;
|
|
190
|
+
child.kill("SIGTERM");
|
|
191
|
+
setTimeout(() => child.kill("SIGKILL"), 2000).unref();
|
|
192
|
+
}, timeoutSec * 1000);
|
|
193
|
+
child.stdout.on("data", (d) => (stdout += d));
|
|
194
|
+
child.stderr.on("data", (d) => (stderr += d));
|
|
195
|
+
child.stdin.on("error", () => {});
|
|
196
|
+
child.stdin.end(input);
|
|
197
|
+
child.on("error", (e) => {
|
|
198
|
+
clearTimeout(timer);
|
|
199
|
+
resolve({ code: null, stdout, stderr, error: e });
|
|
200
|
+
});
|
|
201
|
+
child.on("close", (code) => {
|
|
202
|
+
clearTimeout(timer);
|
|
203
|
+
resolve({ code, stdout, stderr, timedOut });
|
|
204
|
+
});
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Run one check entry: { pass, reason, checks, steps?, output, file }.
|
|
210
|
+
* @param {{ name, file, type }} entry
|
|
211
|
+
* @param {{ cwd: string, input: object, timeoutSec?: number }} opts
|
|
212
|
+
*/
|
|
213
|
+
async function runEntry(entry, { cwd, input, timeoutSec }) {
|
|
214
|
+
const full = path.join(cwd, CHECKS_DIR, entry.file);
|
|
215
|
+
const shown = `${CHECKS_DIR}/${entry.file}`;
|
|
216
|
+
const limit = Number.isFinite(timeoutSec) && timeoutSec > 0 ? timeoutSec : DEFAULT_TIMEOUT_SEC;
|
|
217
|
+
if (entry.type === "recipe") {
|
|
218
|
+
let r;
|
|
219
|
+
try {
|
|
220
|
+
r = JSON.parse(fs.readFileSync(full, "utf8"));
|
|
221
|
+
} catch (e) {
|
|
222
|
+
return fromReason(entry, false, `${shown} isn't valid JSON (${e.message})`);
|
|
223
|
+
}
|
|
224
|
+
const res = await recipe.runRecipe(r, input, { cwd, env: dashEnv(cwd, input, entry.name, "") });
|
|
225
|
+
return { ...res, file: shown, output: "" };
|
|
226
|
+
}
|
|
227
|
+
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "dash-check-"));
|
|
228
|
+
try {
|
|
229
|
+
const inputFile = path.join(tmp, "input.json");
|
|
230
|
+
const json = JSON.stringify(input);
|
|
231
|
+
fs.writeFileSync(inputFile, json);
|
|
232
|
+
const env = dashEnv(cwd, input, entry.name, inputFile);
|
|
233
|
+
let cmd;
|
|
234
|
+
let args;
|
|
235
|
+
if (entry.type === "js") {
|
|
236
|
+
cmd = process.execPath;
|
|
237
|
+
args = ["-r", REGISTER, full];
|
|
238
|
+
} else {
|
|
239
|
+
let first = "";
|
|
240
|
+
try {
|
|
241
|
+
first = fs.readFileSync(full, "utf8").split(/\r?\n/, 1)[0] || "";
|
|
242
|
+
} catch (_e) {
|
|
243
|
+
first = "";
|
|
244
|
+
}
|
|
245
|
+
if (first.startsWith("#!")) {
|
|
246
|
+
try {
|
|
247
|
+
fs.chmodSync(full, 0o755);
|
|
248
|
+
} catch (_e) {
|
|
249
|
+
// Read-only: it'll fail to start and say so.
|
|
250
|
+
}
|
|
251
|
+
cmd = full;
|
|
252
|
+
args = [];
|
|
253
|
+
} else {
|
|
254
|
+
const runner = RUNNERS[path.extname(full).toLowerCase()] || "sh";
|
|
255
|
+
cmd = runner === "node" ? process.execPath : runner;
|
|
256
|
+
args = runner === "node" ? ["-r", REGISTER, full] : [full];
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
const r = await spawnP(cmd, args, { cwd, env, input: json, timeoutSec: limit });
|
|
260
|
+
const output = `${r.stdout || ""}${r.stderr ? `\n${r.stderr}` : ""}`.trim();
|
|
261
|
+
if (r.timedOut) return { ...fromReason(entry, false, `Stopped after ${limit} seconds`), file: shown, output };
|
|
262
|
+
if (r.error) return { ...fromReason(entry, false, `It couldn't start: ${r.error.message}`), file: shown, output };
|
|
263
|
+
const found = lastProof(r.stdout);
|
|
264
|
+
const pass = r.code === 0;
|
|
265
|
+
const reason = (found && typeof found.proof.reason === "string" && found.proof.reason) || (pass ? "Passed (exit 0)" : `Failed (exit ${r.code})`);
|
|
266
|
+
const shownOut = found ? [...found.lines.slice(0, found.index), ...found.lines.slice(found.index + 1)].join("\n") + (r.stderr ? `\n${r.stderr}` : "") : output;
|
|
267
|
+
const details = found && found.proof.details;
|
|
268
|
+
if (details && Array.isArray(details.checks)) {
|
|
269
|
+
const checks = details.checks.map((c) => ({ ...c, failures: c.failures || [] }));
|
|
270
|
+
return { pass, reason, checks, ...(details.steps ? { steps: details.steps } : {}), file: shown, output: shownOut.trim() };
|
|
271
|
+
}
|
|
272
|
+
return { ...fromReason(entry, pass, reason), file: shown, output: shownOut.trim() };
|
|
273
|
+
} finally {
|
|
274
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
function fromReason(entry, pass, reason) {
|
|
279
|
+
return { pass, reason, checks: [{ name: entry.name, pass, reason, failures: pass ? [] : [{ message: reason }] }] };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function readJsonFile(file) {
|
|
283
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Run checks and print. Gives the exit code. */
|
|
287
|
+
async function runAll(a, out) {
|
|
288
|
+
const checks = listChecks(a.cwd);
|
|
289
|
+
for (const n of a.names) {
|
|
290
|
+
if (!NAME_RE.test(n) || n.includes("..")) {
|
|
291
|
+
out.err(`"${n}" can't be a check's name`);
|
|
292
|
+
return 2;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
let given = null;
|
|
296
|
+
if (a.input) {
|
|
297
|
+
try {
|
|
298
|
+
given = readJsonFile(path.resolve(a.cwd, a.input));
|
|
299
|
+
} catch (e) {
|
|
300
|
+
out.err(`Can't read ${a.input}: ${e.message}`);
|
|
301
|
+
return 2;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
const wanted = a.names.length ? a.names : checks.map((c) => c.name);
|
|
305
|
+
if (!wanted.length) {
|
|
306
|
+
out.log(`No ${CHECKS_DIR} here: nothing to run. Start one with: dash-check new <name>`);
|
|
307
|
+
return 0;
|
|
308
|
+
}
|
|
309
|
+
loadHelpers({ cwd: a.cwd });
|
|
310
|
+
const color = a.color === null ? !a.ci && !a.json && !!process.stdout.isTTY : a.color;
|
|
311
|
+
const results = [];
|
|
312
|
+
let failed = 0;
|
|
313
|
+
for (const name of wanted) {
|
|
314
|
+
const entry = pick(checks, name);
|
|
315
|
+
if (!entry) {
|
|
316
|
+
const msg = `there's no ${CHECKS_DIR}/${name}`;
|
|
317
|
+
if (!a.ci && !a.json) {
|
|
318
|
+
out.err(`✗ ${name}: ${msg}`);
|
|
319
|
+
return 2;
|
|
320
|
+
}
|
|
321
|
+
failed++;
|
|
322
|
+
results.push({ name, pass: false, reason: msg, checks: [], file: `${CHECKS_DIR}/${name}` });
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
let input = given;
|
|
326
|
+
if (!input && entry.sample) {
|
|
327
|
+
try {
|
|
328
|
+
input = readJsonFile(entry.sample);
|
|
329
|
+
} catch (e) {
|
|
330
|
+
out.err(`Can't read ${entry.sample}: ${e.message}`);
|
|
331
|
+
return 2;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const res = await runEntry(entry, { cwd: a.cwd, input: input || SAMPLE, timeoutSec: a.timeout });
|
|
335
|
+
results.push({ name: entry.name, ...res });
|
|
336
|
+
if (!res.pass) failed++;
|
|
337
|
+
if (a.json) continue;
|
|
338
|
+
if (a.ci) {
|
|
339
|
+
out.log(report(res, { title: res.file, color }));
|
|
340
|
+
if (!res.pass && res.output) out.log(indent(res.output.split("\n").slice(-30).join("\n"), " "));
|
|
341
|
+
} else if (res.pass) {
|
|
342
|
+
const said = res.reason.startsWith(`${entry.name}: `) ? res.reason.slice(entry.name.length + 2) : res.reason;
|
|
343
|
+
out.log(`✓ ${entry.name}: ${said}`);
|
|
344
|
+
} else {
|
|
345
|
+
if (res.output) out.log(res.output.split("\n").slice(-30).join("\n"));
|
|
346
|
+
if (entry.type !== "exec") out.log(report(res, { color }));
|
|
347
|
+
out.log(`✗ ${entry.name}: ${res.reason}`);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
if (a.json) {
|
|
351
|
+
out.log(JSON.stringify({ pass: failed === 0, results }, null, 2));
|
|
352
|
+
} else if (a.ci) {
|
|
353
|
+
const all = results.flatMap((r) => r.checks || []);
|
|
354
|
+
const nFail = all.filter((c) => !c.pass).length;
|
|
355
|
+
const nSkip = all.filter((c) => c.skipped).length;
|
|
356
|
+
const nPass = all.length - nFail - nSkip;
|
|
357
|
+
const parts = [nFail ? `${nFail} failed` : null, nSkip ? `${nSkip} skipped` : null, `${nPass} passed`, `${all.length} total`].filter(Boolean);
|
|
358
|
+
const files = [failed ? `${failed} failed` : null, `${results.length - failed} passed`, `${results.length} total`].filter(Boolean);
|
|
359
|
+
out.log("");
|
|
360
|
+
out.log(`Files: ${files.join(", ")}`);
|
|
361
|
+
out.log(`Checks: ${parts.join(", ")}`);
|
|
362
|
+
}
|
|
363
|
+
return failed ? 1 : 0;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const indent = (s, pad) => s.split("\n").map((l) => pad + l).join("\n");
|
|
367
|
+
|
|
368
|
+
function listHelpersCmd(a, out) {
|
|
369
|
+
const found = loadHelpers({ cwd: a.cwd });
|
|
370
|
+
const helpers = core.listHelpers();
|
|
371
|
+
const matchers = core.expect.matchers();
|
|
372
|
+
let values;
|
|
373
|
+
if (a.input) {
|
|
374
|
+
try {
|
|
375
|
+
values = core.valuePaths(core.createContext(readJsonFile(path.resolve(a.cwd, a.input)), { cwd: a.cwd }));
|
|
376
|
+
} catch (e) {
|
|
377
|
+
out.err(`Can't read ${a.input}: ${e.message}`);
|
|
378
|
+
return 2;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
if (a.json) {
|
|
382
|
+
out.log(JSON.stringify({ helpers, matchers, errors: found.errors, ...(values ? { values } : {}) }, null, 2));
|
|
383
|
+
return 0;
|
|
384
|
+
}
|
|
385
|
+
const groups = {};
|
|
386
|
+
for (const h of helpers) (groups[h.group] = groups[h.group] || []).push(h);
|
|
387
|
+
for (const [g, list] of Object.entries(groups)) {
|
|
388
|
+
out.log(g);
|
|
389
|
+
for (const h of list) out.log(` ${h.id.padEnd(30)} ${h.label}${h.description ? ` (${h.description})` : ""}${h.source && h.source !== "@trops/dash-check" ? ` [${h.source}]` : ""}`);
|
|
390
|
+
}
|
|
391
|
+
out.log("Matchers");
|
|
392
|
+
for (const m of matchers) out.log(` ${m.id.padEnd(30)} ${m.sentence}`);
|
|
393
|
+
for (const e of found.errors) out.err(`✗ ${e.source} didn't load: ${e.error}`);
|
|
394
|
+
if (values) {
|
|
395
|
+
out.log("Values in the sample");
|
|
396
|
+
for (const v of values) out.log(` ${v.path}${"sample" in v ? ` = ${JSON.stringify(v.sample)}` : ` (${v.type})`}`);
|
|
397
|
+
}
|
|
398
|
+
return 0;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function explainCmd(a, out) {
|
|
402
|
+
const file = path.resolve(a.cwd, a.explain);
|
|
403
|
+
if (!fs.existsSync(file)) {
|
|
404
|
+
out.err(`There's no ${a.explain}`);
|
|
405
|
+
return 2;
|
|
406
|
+
}
|
|
407
|
+
loadHelpers({ cwd: a.cwd });
|
|
408
|
+
if (/\.json$/.test(file)) {
|
|
409
|
+
let r;
|
|
410
|
+
try {
|
|
411
|
+
r = readJsonFile(file);
|
|
412
|
+
} catch (e) {
|
|
413
|
+
out.err(`${a.explain} isn't valid JSON: ${e.message}`);
|
|
414
|
+
return 2;
|
|
415
|
+
}
|
|
416
|
+
const v = recipe.validateRecipe(r);
|
|
417
|
+
out.log(r.name || path.basename(file));
|
|
418
|
+
for (const line of recipe.explain(r)) out.log(` - ${line}`);
|
|
419
|
+
for (const e of v.errors) out.err(`✗ ${e.path ? `${e.path}: ` : ""}${e.message}`);
|
|
420
|
+
return v.valid ? 0 : 1;
|
|
421
|
+
}
|
|
422
|
+
if (/\.check\.c?js$/.test(file)) {
|
|
423
|
+
require("../lib/register");
|
|
424
|
+
let checks;
|
|
425
|
+
try {
|
|
426
|
+
checks = loadChecks(file);
|
|
427
|
+
} catch (e) {
|
|
428
|
+
out.err(`${a.explain} didn't load: ${e.message}`);
|
|
429
|
+
return 1;
|
|
430
|
+
}
|
|
431
|
+
out.log(`${path.basename(file)}: code, ${checks.length} check${checks.length === 1 ? "" : "s"}`);
|
|
432
|
+
for (const c of checks) out.log(` - ${c.name}${c.mode === "skip" ? " (skipped)" : c.mode === "only" ? " (only)" : ""}`);
|
|
433
|
+
out.log(" (Code reads as its check names. Write it as a .check.json recipe to read every step as a sentence.)");
|
|
434
|
+
return 0;
|
|
435
|
+
}
|
|
436
|
+
out.log(`${path.basename(file)}: a plain executable. Exit 0 passes; its last line {"reason"} says why.`);
|
|
437
|
+
return 0;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const SAMPLE_INPUT = {
|
|
441
|
+
input: { answer: 'Done.\n\n```json\n{ "status": "ok", "summary": "What the bot did", "files": ["src/index.js"] }\n```' },
|
|
442
|
+
item: { id: "DASH-1", title: "An example work item" },
|
|
443
|
+
workspace: { dir: ".", branch: "feat/DASH-1-example" },
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
function createCmd(a, out) {
|
|
447
|
+
const name = a.create;
|
|
448
|
+
if (!name || !NAME_RE.test(name) || name.includes("..") || name === "helpers") {
|
|
449
|
+
out.err(`Give the check a name made of letters, numbers, ".", "-" and "_": dash-check new <name>${name ? ` ("${name}" can't be one)` : ""}`);
|
|
450
|
+
return 2;
|
|
451
|
+
}
|
|
452
|
+
const dir = path.join(a.cwd, CHECKS_DIR);
|
|
453
|
+
const file = path.join(dir, a.recipe ? `${name}.check.json` : `${name}.check.js`);
|
|
454
|
+
const sample = path.join(dir, `${name}.sample.json`);
|
|
455
|
+
for (const f of [file, sample]) {
|
|
456
|
+
if (fs.existsSync(f)) {
|
|
457
|
+
out.err(`${path.relative(a.cwd, f)} is already there: pick another name, or edit it`);
|
|
458
|
+
return 2;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
462
|
+
const title = name.replace(/[-_.]+/g, " ");
|
|
463
|
+
if (a.recipe) {
|
|
464
|
+
const r = {
|
|
465
|
+
name: title,
|
|
466
|
+
steps: [
|
|
467
|
+
{ use: "handoff.has", with: { keys: ["summary"] } },
|
|
468
|
+
{ expect: "handoff.files", matcher: "toHaveLengthAtLeast", args: [1], message: "The handoff lists no changed files" },
|
|
469
|
+
],
|
|
470
|
+
};
|
|
471
|
+
fs.writeFileSync(file, `${JSON.stringify(r, null, 2)}\n`);
|
|
472
|
+
} else {
|
|
473
|
+
fs.writeFileSync(
|
|
474
|
+
file,
|
|
475
|
+
`// ${CHECKS_DIR}/${name}.check.js: run it with npx dash-check ${name}
|
|
476
|
+
const { check, expect } = require("@trops/dash-check");
|
|
477
|
+
const { handoff } = require("@trops/dash-check/helpers");
|
|
478
|
+
|
|
479
|
+
check(${JSON.stringify(title)}, async (ctx) => {
|
|
480
|
+
await handoff.has(ctx, { keys: ["summary"] });
|
|
481
|
+
expect(ctx.handoff.files, "handoff.files").toHaveLengthAtLeast(1, "The handoff lists no changed files");
|
|
482
|
+
});
|
|
483
|
+
`,
|
|
484
|
+
);
|
|
485
|
+
}
|
|
486
|
+
fs.writeFileSync(sample, `${JSON.stringify(SAMPLE_INPUT, null, 2)}\n`);
|
|
487
|
+
out.log(`Made ${path.relative(a.cwd, file)} and ${path.relative(a.cwd, sample)}.`);
|
|
488
|
+
out.log(`Try it: npx dash-check ${name} (then make the sample bad, and see it fail with a clear reason)`);
|
|
489
|
+
return 0;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
function listCmd(a, out) {
|
|
493
|
+
const checks = listChecks(a.cwd);
|
|
494
|
+
if (!checks.length) out.log(`No ${CHECKS_DIR} here.`);
|
|
495
|
+
for (const c of checks) out.log(`${c.name}\t${CHECKS_DIR}/${c.file}\t${c.type}${c.sample ? "\t(sample)" : ""}`);
|
|
496
|
+
return 0;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
function watch(a, out, signal) {
|
|
500
|
+
return new Promise((resolve) => {
|
|
501
|
+
let timer = null;
|
|
502
|
+
let running = false;
|
|
503
|
+
let again = false;
|
|
504
|
+
const go = async () => {
|
|
505
|
+
if (running) {
|
|
506
|
+
again = true;
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
running = true;
|
|
510
|
+
out.log(`\n— ${new Date().toLocaleTimeString()} —`);
|
|
511
|
+
await runAll(a, out);
|
|
512
|
+
out.log("Watching for changes (Ctrl-C to stop)…");
|
|
513
|
+
running = false;
|
|
514
|
+
if (again) {
|
|
515
|
+
again = false;
|
|
516
|
+
go();
|
|
517
|
+
}
|
|
518
|
+
};
|
|
519
|
+
let watcher;
|
|
520
|
+
const onChange = (_e, f) => {
|
|
521
|
+
const p = String(f || "");
|
|
522
|
+
if (/(^|[/\\])(\.git|node_modules)([/\\]|$)/.test(p)) return;
|
|
523
|
+
clearTimeout(timer);
|
|
524
|
+
timer = setTimeout(go, 200);
|
|
525
|
+
};
|
|
526
|
+
try {
|
|
527
|
+
watcher = fs.watch(a.cwd, { recursive: true }, onChange);
|
|
528
|
+
} catch (_e) {
|
|
529
|
+
watcher = fs.watch(path.join(a.cwd, CHECKS_DIR), onChange);
|
|
530
|
+
}
|
|
531
|
+
const stop = () => {
|
|
532
|
+
watcher.close();
|
|
533
|
+
clearTimeout(timer);
|
|
534
|
+
resolve(0);
|
|
535
|
+
};
|
|
536
|
+
if (signal) signal.addEventListener("abort", stop, { once: true });
|
|
537
|
+
else process.once("SIGINT", stop);
|
|
538
|
+
go();
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* The CLI. Gives the exit code.
|
|
544
|
+
* @param {string[]} argv
|
|
545
|
+
* @param {{ log?: Function, err?: Function, signal?: AbortSignal }} [io]
|
|
546
|
+
*/
|
|
547
|
+
async function main(argv, io = {}) {
|
|
548
|
+
const out = { log: io.log || ((s) => process.stdout.write(`${s}\n`)), err: io.err || ((s) => process.stderr.write(`${s}\n`)) };
|
|
549
|
+
const a = parseArgs(argv);
|
|
550
|
+
if (a.error) {
|
|
551
|
+
out.err(`${a.error}\n${USAGE}`);
|
|
552
|
+
return 2;
|
|
553
|
+
}
|
|
554
|
+
if (a.help) {
|
|
555
|
+
out.log(USAGE);
|
|
556
|
+
return 0;
|
|
557
|
+
}
|
|
558
|
+
if (a.create !== undefined) return createCmd(a, out);
|
|
559
|
+
if (a.listHelpers) return listHelpersCmd(a, out);
|
|
560
|
+
if (a.explain) return explainCmd(a, out);
|
|
561
|
+
if (a.list) return listCmd(a, out);
|
|
562
|
+
if (a.watch) return watch(a, out, io.signal);
|
|
563
|
+
return runAll(a, out);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
module.exports = { main, parseArgs, listChecks, runEntry, lastProof, CHECKS_DIR };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Walkthrough 8. Before the Reviewer: "Only the planned files changed".
|
|
2
|
+
// Lives in the shared package. Reads: git, handoff, row.
|
|
3
|
+
const { check, expect } = require("@trops/dash-check");
|
|
4
|
+
|
|
5
|
+
check("only the planned files changed", async ({ git, handoff, row }) => {
|
|
6
|
+
const changed = await git.changedFiles(`origin/${row.repo?.baseBranch || "main"}`);
|
|
7
|
+
const allowed = new Set([...(handoff.files ?? []), ...(handoff.newFiles ?? []), ...(handoff.tests ?? []).map((t) => t.file)]);
|
|
8
|
+
const extra = changed.filter((f) => !allowed.has(f) && !/package-lock\.json$/.test(f));
|
|
9
|
+
expect(extra, "files the plan didn't name").toBeEmpty(`Changed files the plan didn't name: ${extra.join(", ")}`);
|
|
10
|
+
});
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
{
|
|
2
|
+
"input": { "answer": "```json\n{ \"acceptance\": [\"Names are title case\", \"Dashes are kept\", \"Empty names stay empty\"], \"tests\": [{ \"acceptance\": \"Names are title case\", \"test\": \"titleCase('a b') is 'A B'\" }], \"files\": [\"src/invented.js\"] }\n```" }
|
|
3
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Walkthrough 5. Planner: "Every acceptance item has a test".
|
|
2
|
+
// Lives in the shared package. Reads: handoff, workspace.
|
|
3
|
+
// Every gap is listed, because each failing expect is collected.
|
|
4
|
+
const { check, expect } = require("@trops/dash-check");
|
|
5
|
+
|
|
6
|
+
check("every acceptance item has a test", ({ handoff }) => {
|
|
7
|
+
expect(handoff.acceptance, "handoff.acceptance").not.toBeEmpty("No acceptance items");
|
|
8
|
+
for (const a of handoff.acceptance ?? []) {
|
|
9
|
+
const t = handoff.tests?.find((x) => x.acceptance === a);
|
|
10
|
+
expect(t?.test, `the test for "${a}"`).toBeNonEmptyString(`No test for: ${a}`);
|
|
11
|
+
}
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
check("the plan only names files in the repo", async ({ handoff, workspace }) => {
|
|
15
|
+
for (const f of handoff.files ?? []) {
|
|
16
|
+
if (handoff.newFiles?.includes(f)) continue;
|
|
17
|
+
expect(await workspace.exists(f), f).toBe(true, `The plan names ${f}, which isn't in the repo (list new files in newFiles)`);
|
|
18
|
+
}
|
|
19
|
+
});
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
{
|
|
2
|
+
"input": { "answer": "```json\n{ \"acceptance\": [\"Names are title case\", \"Dashes are kept\"], \"tests\": [{ \"acceptance\": \"Names are title case\", \"test\": \"titleCase('a b') is 'A B'\", \"file\": \"test/title.test.js\" }, { \"acceptance\": \"Dashes are kept\", \"test\": \"titleCase('a-b') is 'A-B'\", \"file\": \"test/title.test.js\" }], \"files\": [\"package.json\"], \"newFiles\": [\"src/title.js\"] }\n```" }
|
|
3
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// A team's own helper: put it in <repo>/.dash/checks/helpers/changelog.js and
|
|
2
|
+
// it shows up in `dash-check --list-helpers` (the composer's "Your helpers").
|
|
3
|
+
// Built only from Layer 0: ctx.git, expect.
|
|
4
|
+
const { defineHelper, expect, note } = require("@trops/dash-check");
|
|
5
|
+
|
|
6
|
+
module.exports = defineHelper({
|
|
7
|
+
id: "team.changelogUpdated",
|
|
8
|
+
group: "Your helpers",
|
|
9
|
+
label: "Changelog updated",
|
|
10
|
+
description: "CHANGELOG.md changed on this branch",
|
|
11
|
+
sentence: "{file} changed since {base}",
|
|
12
|
+
params: {
|
|
13
|
+
file: { type: "path", label: "Changelog", default: "CHANGELOG.md" },
|
|
14
|
+
base: { type: "text", label: "Base branch", default: "{repo.baseBranch}" },
|
|
15
|
+
},
|
|
16
|
+
reads: ["git"],
|
|
17
|
+
async run(ctx, { file, base }) {
|
|
18
|
+
const ref = `origin/${base || (await ctx.git.defaultBranch()) || "main"}`;
|
|
19
|
+
const changed = await ctx.git.changedFiles(ref);
|
|
20
|
+
expect(changed, `files changed since ${ref}`).toContain(file, `${file} isn't updated: add a line for ${ctx.item.id || "this change"}`);
|
|
21
|
+
note(`${file} is updated`);
|
|
22
|
+
},
|
|
23
|
+
});
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Walkthrough 12. Reporter: "The ticket got its comment", checked in Jira itself.
|
|
2
|
+
// Lives in a tracker package (@dash-checks/jira). Reads: item, tool, job.
|
|
3
|
+
// ctx.tool only works when Dash runs the check (it supplies the provider).
|
|
4
|
+
const { check, expect } = require("@trops/dash-check");
|
|
5
|
+
|
|
6
|
+
check("the ticket has this job's comment", async ({ item, tool, job }) => {
|
|
7
|
+
const { comments } = await tool("jira", "listJiraIssueComments", { issueIdOrKey: item.id, orderBy: "-created", maxResults: 5 });
|
|
8
|
+
expect(comments.some((c) => new Date(c.created) >= new Date(job.startedAt)), "a comment since the job started")
|
|
9
|
+
.toBe(true, `No comment on ${item.id} since this job started`);
|
|
10
|
+
});
|