@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.
- package/LICENSE +21 -0
- package/README.md +355 -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 +18 -0
- package/examples/changes-match-plan.sample.json +4 -0
- 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/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/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/merge-outcome.bad.json +4 -0
- package/examples/merge-outcome.check.js +9 -0
- package/examples/merge-outcome.sample.json +4 -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/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/plan-scope.bad.json +4 -0
- package/examples/plan-scope.check.json +6 -0
- package/examples/plan-scope.sample.json +4 -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/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/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-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/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 +124 -0
- package/helpers/git.js +379 -0
- package/helpers/github.js +77 -0
- package/helpers/handoff.js +80 -0
- package/helpers/index.d.ts +103 -0
- package/helpers/index.js +36 -0
- package/helpers/node.js +296 -0
- package/helpers/plan.js +55 -0
- package/helpers/tracker.js +60 -0
- package/index.d.ts +347 -0
- package/index.js +86 -0
- package/lib/adapters/fs.js +85 -0
- package/lib/adapters/git.js +163 -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 +236 -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
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Types for @trops/dash-check/recipe: checks as data.
|
|
2
|
+
import type { Context, ContextOptions, Failure, RunResult, Helper } from "..";
|
|
3
|
+
|
|
4
|
+
export interface UseStep {
|
|
5
|
+
use: string;
|
|
6
|
+
with?: Record<string, unknown>;
|
|
7
|
+
when?: string | boolean;
|
|
8
|
+
message?: string;
|
|
9
|
+
label?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ExpectStep {
|
|
13
|
+
expect: string;
|
|
14
|
+
matcher: string;
|
|
15
|
+
args?: unknown[];
|
|
16
|
+
not?: boolean;
|
|
17
|
+
when?: string | boolean;
|
|
18
|
+
message?: string;
|
|
19
|
+
label?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type Step = UseStep | ExpectStep;
|
|
23
|
+
|
|
24
|
+
export interface Recipe {
|
|
25
|
+
$schema?: string;
|
|
26
|
+
name: string;
|
|
27
|
+
description?: string;
|
|
28
|
+
version?: 1;
|
|
29
|
+
steps: Step[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface StepResult {
|
|
33
|
+
index: number;
|
|
34
|
+
label: string;
|
|
35
|
+
sentence: string;
|
|
36
|
+
pass: boolean;
|
|
37
|
+
skipped?: boolean;
|
|
38
|
+
reason: string;
|
|
39
|
+
failures: Failure[];
|
|
40
|
+
ms?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface RecipeResult extends RunResult {
|
|
44
|
+
steps: StepResult[];
|
|
45
|
+
errors?: Array<{ path: string; message: string }>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface RecipeOptions extends ContextOptions {
|
|
49
|
+
getHelper?: (id: string) => Helper | null;
|
|
50
|
+
/** Run only these steps (by index). */
|
|
51
|
+
only?: number[];
|
|
52
|
+
ctx?: Context;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const schema: Record<string, any>;
|
|
56
|
+
export function validateRecipe(recipe: unknown, opts?: { getHelper?: (id: string) => Helper | null }): { valid: boolean; errors: Array<{ path: string; message: string }> };
|
|
57
|
+
export function compileRecipe(recipe: Recipe, opts?: { getHelper?: (id: string) => Helper | null }): {
|
|
58
|
+
name: string;
|
|
59
|
+
steps: Array<{ index: number; label: string; when?: string | boolean; run(ctx: Context): Promise<unknown>; step: Step }>;
|
|
60
|
+
check(ctx: Context): Promise<void>;
|
|
61
|
+
};
|
|
62
|
+
export function runRecipe(recipe: Recipe, input?: Record<string, any>, opts?: RecipeOptions): Promise<RecipeResult>;
|
|
63
|
+
/** The recipe as a .check.js file that gives the same result. */
|
|
64
|
+
export function recipeToCode(recipe: Recipe, opts?: { getHelper?: (id: string) => Helper | null; file?: string }): string;
|
|
65
|
+
export const toCode: typeof recipeToCode;
|
|
66
|
+
/** One sentence per step. */
|
|
67
|
+
export function explain(recipe: Recipe, opts?: { getHelper?: (id: string) => Helper | null }): string[];
|
|
68
|
+
export function valuePaths(ctx: Context): Array<{ path: string; type: string; sample?: unknown }>;
|
|
69
|
+
export function slug(name: string): string;
|
|
70
|
+
export function pathCode(path: string): string;
|
package/recipe/index.js
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @trops/dash-check/recipe: checks as data.
|
|
3
|
+
*
|
|
4
|
+
* { "name": "the work is ready for review",
|
|
5
|
+
* "steps": [
|
|
6
|
+
* { "use": "git.committedSince", "with": { "base": "{repo.baseBranch}" } },
|
|
7
|
+
* { "expect": "handoff.files", "matcher": "toHaveLengthAtLeast", "args": [1],
|
|
8
|
+
* "message": "The handoff lists no changed files" } ] }
|
|
9
|
+
*
|
|
10
|
+
* validateRecipe, compileRecipe, runRecipe (a result per step),
|
|
11
|
+
* recipeToCode (the same check as a .check.js file) and explain (sentences).
|
|
12
|
+
* A recipe makes the same calls a file makes: helpers and expect.
|
|
13
|
+
*/
|
|
14
|
+
"use strict";
|
|
15
|
+
|
|
16
|
+
const core = require("..");
|
|
17
|
+
require("../helpers");
|
|
18
|
+
const schema = require("./schema.json");
|
|
19
|
+
|
|
20
|
+
const { expect, getHelper, sentenceOf, createContext, collect, fill, when, get, valuePaths } = core;
|
|
21
|
+
const { summarize } = require("../lib/runner");
|
|
22
|
+
const { coerce } = require("../lib/helper");
|
|
23
|
+
const { display } = require("../lib/scope");
|
|
24
|
+
const { isObj, fmt } = require("../lib/util");
|
|
25
|
+
const { hasPlaceholder } = require("../lib/values");
|
|
26
|
+
|
|
27
|
+
const PATH_RE = /^[A-Za-z_$][\w$-]*(\.[\w$-]+)*$/;
|
|
28
|
+
const HELPER_ID_RE = /^[a-z][A-Za-z0-9]*(\.[a-z][A-Za-z0-9]*)+$/;
|
|
29
|
+
const USE_KEYS = ["use", "with", "when", "message", "label"];
|
|
30
|
+
const EXPECT_KEYS = ["expect", "matcher", "args", "not", "when", "message", "label"];
|
|
31
|
+
const TOP_KEYS = ["$schema", "name", "description", "version", "steps"];
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* What's wrong with a recipe.
|
|
35
|
+
* @param {object} recipe
|
|
36
|
+
* @param {{ getHelper?: (id: string) => any }} [opts] where helpers are found
|
|
37
|
+
* @returns {{ valid: boolean, errors: Array<{ path: string, message: string }> }}
|
|
38
|
+
*/
|
|
39
|
+
function validateRecipe(recipe, opts = {}) {
|
|
40
|
+
const find = opts.getHelper || getHelper;
|
|
41
|
+
const errors = [];
|
|
42
|
+
const err = (path, message) => errors.push({ path, message });
|
|
43
|
+
if (!isObj(recipe)) {
|
|
44
|
+
err("", "A recipe is a JSON object: { \"name\": …, \"steps\": [ … ] }");
|
|
45
|
+
return { valid: false, errors };
|
|
46
|
+
}
|
|
47
|
+
for (const k of Object.keys(recipe)) if (!TOP_KEYS.includes(k)) err(k, `"${k}" isn't part of a recipe (use ${TOP_KEYS.slice(1).join(", ")})`);
|
|
48
|
+
if (typeof recipe.name !== "string" || !recipe.name.trim()) err("name", "Give the recipe a name: what it proves");
|
|
49
|
+
if (recipe.description !== undefined && typeof recipe.description !== "string") err("description", "description must be text");
|
|
50
|
+
if (recipe.version !== undefined && recipe.version !== 1) err("version", "This dash-check reads recipe version 1");
|
|
51
|
+
if (!Array.isArray(recipe.steps) || !recipe.steps.length) {
|
|
52
|
+
err("steps", "Add at least one step: { \"use\": \"helper.id\" } or { \"expect\": \"handoff.key\", \"matcher\": \"toBeDefined\" }");
|
|
53
|
+
return { valid: false, errors };
|
|
54
|
+
}
|
|
55
|
+
recipe.steps.forEach((s, i) => {
|
|
56
|
+
const at = `steps[${i}]`;
|
|
57
|
+
if (!isObj(s)) return err(at, "A step is an object");
|
|
58
|
+
const isUse = s.use !== undefined;
|
|
59
|
+
const isExpect = s.expect !== undefined;
|
|
60
|
+
if (isUse === isExpect) return err(at, 'A step has either "use" (a helper) or "expect" (a value), not both or neither');
|
|
61
|
+
const keys = isUse ? USE_KEYS : EXPECT_KEYS;
|
|
62
|
+
for (const k of Object.keys(s)) if (!keys.includes(k)) err(`${at}.${k}`, `"${k}" isn't part of a${isUse ? " use" : "n expect"} step`);
|
|
63
|
+
if (s.message !== undefined && typeof s.message !== "string") err(`${at}.message`, "message must be text");
|
|
64
|
+
if (s.label !== undefined && typeof s.label !== "string") err(`${at}.label`, "label must be text");
|
|
65
|
+
if (s.when !== undefined && typeof s.when !== "string" && typeof s.when !== "boolean") err(`${at}.when`, "when is a value path or a {placeholder}");
|
|
66
|
+
if (isUse) {
|
|
67
|
+
if (typeof s.use !== "string" || !HELPER_ID_RE.test(s.use)) return err(`${at}.use`, `"${s.use}" isn't a helper id (e.g. git.committedSince)`);
|
|
68
|
+
const h = find(s.use);
|
|
69
|
+
if (!h) return err(`${at}.use`, `There's no helper ${s.use}`);
|
|
70
|
+
if (s.with !== undefined && !isObj(s.with)) return err(`${at}.with`, "with is an object of the helper's params");
|
|
71
|
+
const given = s.with || {};
|
|
72
|
+
const params = h.meta.params;
|
|
73
|
+
for (const k of Object.keys(given)) {
|
|
74
|
+
if (k === "message") err(`${at}.with.message`, 'Put message on the step, next to "use"');
|
|
75
|
+
else if (!params[k]) err(`${at}.with.${k}`, `${s.use} has no param "${k}" (it has ${Object.keys(params).join(", ") || "none"})`);
|
|
76
|
+
}
|
|
77
|
+
for (const [k, p] of Object.entries(params)) {
|
|
78
|
+
const v = given[k];
|
|
79
|
+
if (v === undefined) {
|
|
80
|
+
if (p.required && p.default === undefined) err(`${at}.with.${k}`, `${s.use} needs ${p.label} (${k})`);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (typeof v === "string" && hasPlaceholder(v)) continue;
|
|
84
|
+
if (p.type === "list" && Array.isArray(v) && v.some((x) => typeof x === "string" && hasPlaceholder(x))) continue;
|
|
85
|
+
try {
|
|
86
|
+
coerce(s.use, k, p, v);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
err(`${at}.with.${k}`, e.message);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
} else {
|
|
92
|
+
if (typeof s.expect !== "string" || !PATH_RE.test(s.expect)) err(`${at}.expect`, `"${s.expect}" isn't a value path (e.g. handoff.files)`);
|
|
93
|
+
const m = typeof s.matcher === "string" ? expect.meta(s.matcher) : null;
|
|
94
|
+
if (!m) {
|
|
95
|
+
err(`${at}.matcher`, `There's no matcher ${fmt(s.matcher)} (use one of ${expect.matchers().map((x) => x.id).join(", ")})`);
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (s.args !== undefined && !Array.isArray(s.args)) return err(`${at}.args`, "args is a list of the matcher's params");
|
|
99
|
+
const n = (s.args || []).length;
|
|
100
|
+
if (n !== m.params.length) {
|
|
101
|
+
err(`${at}.args`, `${s.matcher} takes ${m.params.length} arg${m.params.length === 1 ? "" : "s"}${m.params.length ? ` (${m.params.map((p) => p.name).join(", ")})` : ""}, not ${n}`);
|
|
102
|
+
}
|
|
103
|
+
(s.args || []).forEach((a, j) => {
|
|
104
|
+
const p = m.params[j];
|
|
105
|
+
if (!p) return;
|
|
106
|
+
if (p.type === "number" && typeof a !== "number" && !(typeof a === "string" && hasPlaceholder(a))) err(`${at}.args[${j}]`, `${p.label} must be a number`);
|
|
107
|
+
if (p.type === "list" && !Array.isArray(a) && !(typeof a === "string" && hasPlaceholder(a))) err(`${at}.args[${j}]`, `${p.label} must be a list`);
|
|
108
|
+
if (p.type === "regex" && typeof a === "string" && !hasPlaceholder(a)) {
|
|
109
|
+
try {
|
|
110
|
+
new RegExp(a);
|
|
111
|
+
} catch (e) {
|
|
112
|
+
err(`${at}.args[${j}]`, `${p.label} isn't a valid pattern (${e.message})`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
if (s.not !== undefined && typeof s.not !== "boolean") err(`${at}.not`, "not is true or false");
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
return { valid: errors.length === 0, errors };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A step's row label ("Work is committed", "Expect handoff.files"). */
|
|
123
|
+
function stepLabel(step, find = getHelper) {
|
|
124
|
+
if (step.label) return step.label;
|
|
125
|
+
if (step.use) {
|
|
126
|
+
const h = find(step.use);
|
|
127
|
+
return h ? h.meta.label : step.use;
|
|
128
|
+
}
|
|
129
|
+
return `Expect ${step.expect}`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function matcherArgs(ctx, step) {
|
|
133
|
+
const args = (step.args || []).map((a) => fill(ctx, a));
|
|
134
|
+
const meta = expect.meta(step.matcher);
|
|
135
|
+
return args.map((a, i) => (meta.params[i] && meta.params[i].type === "regex" && typeof a === "string" ? new RegExp(a) : a));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* A recipe as functions: { name, steps: [{ index, label, when, run(ctx) }], check(ctx) }.
|
|
140
|
+
* `check(ctx)` runs every step the way a .check.js file would.
|
|
141
|
+
* Throws when the recipe isn't valid, listing every problem.
|
|
142
|
+
*/
|
|
143
|
+
function compileRecipe(recipe, opts = {}) {
|
|
144
|
+
const v = validateRecipe(recipe, opts);
|
|
145
|
+
if (!v.valid) {
|
|
146
|
+
const e = new Error(`The recipe isn't valid: ${v.errors.map((x) => `${x.path ? `${x.path}: ` : ""}${x.message}`).join("; ")}`);
|
|
147
|
+
e.errors = v.errors;
|
|
148
|
+
throw e;
|
|
149
|
+
}
|
|
150
|
+
const find = opts.getHelper || getHelper;
|
|
151
|
+
const steps = recipe.steps.map((step, index) => {
|
|
152
|
+
let run;
|
|
153
|
+
if (step.use) {
|
|
154
|
+
const h = find(step.use);
|
|
155
|
+
run = (ctx) => h(ctx, { ...(step.with || {}), ...(step.message ? { message: step.message } : {}) });
|
|
156
|
+
} else {
|
|
157
|
+
run = (ctx) => {
|
|
158
|
+
const args = matcherArgs(ctx, step);
|
|
159
|
+
const e = expect(get(ctx, step.expect), step.expect);
|
|
160
|
+
const m = step.not ? e.not : e;
|
|
161
|
+
return m[step.matcher](...args, ...(step.message ? [fill(ctx, step.message, { missing: "keep" })] : []));
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
return { index, label: stepLabel(step, find), when: step.when, run, step };
|
|
165
|
+
});
|
|
166
|
+
async function check(ctx) {
|
|
167
|
+
for (const s of steps) {
|
|
168
|
+
if (s.when !== undefined && !when(ctx, s.when)) continue;
|
|
169
|
+
await s.run(ctx);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return { name: recipe.name.trim(), steps, check };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Run a recipe: a result per step, and the check's result.
|
|
177
|
+
* @param {object} recipe
|
|
178
|
+
* @param {object} [input] the check input (a sample, or Dash's)
|
|
179
|
+
* @param {{ only?: number[], ctx?: object, getHelper?: Function } & object} [opts]
|
|
180
|
+
* only: run just these steps (by index); others createContext options
|
|
181
|
+
* @returns {Promise<{ pass, reason, checks, steps: Array<{ index, label, sentence, pass, skipped?, reason, failures, ms }> }>}
|
|
182
|
+
*/
|
|
183
|
+
async function runRecipe(recipe, input, opts = {}) {
|
|
184
|
+
let compiled;
|
|
185
|
+
try {
|
|
186
|
+
compiled = compileRecipe(recipe, opts);
|
|
187
|
+
} catch (e) {
|
|
188
|
+
const name = (isObj(recipe) && typeof recipe.name === "string" && recipe.name) || "recipe";
|
|
189
|
+
return {
|
|
190
|
+
pass: false,
|
|
191
|
+
reason: e.message,
|
|
192
|
+
errors: e.errors || [],
|
|
193
|
+
checks: [{ name, pass: false, reason: e.message, failures: [{ message: e.message }] }],
|
|
194
|
+
steps: [],
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
const ctx = opts.ctx || createContext(input || {}, opts);
|
|
198
|
+
const only = Array.isArray(opts.only) ? opts.only : null;
|
|
199
|
+
const lines = explain(recipe, opts);
|
|
200
|
+
const steps = [];
|
|
201
|
+
const failures = [];
|
|
202
|
+
const notes = [];
|
|
203
|
+
let broken = null;
|
|
204
|
+
const t0 = Date.now();
|
|
205
|
+
for (const s of compiled.steps) {
|
|
206
|
+
const base = { index: s.index, label: s.label, sentence: lines[s.index] };
|
|
207
|
+
if (only && !only.includes(s.index)) {
|
|
208
|
+
steps.push({ ...base, pass: true, skipped: true, reason: "Not run (only other steps were asked for)", failures: [] });
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (broken !== null) {
|
|
212
|
+
steps.push({ ...base, pass: false, skipped: true, reason: `Not run: step ${broken + 1} broke`, failures: [] });
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
if (s.when !== undefined && !when(ctx, s.when)) {
|
|
216
|
+
steps.push({ ...base, pass: true, skipped: true, reason: `Skipped: ${s.when} is false`, failures: [] });
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const t = Date.now();
|
|
220
|
+
const r = await collect(() => s.run(ctx));
|
|
221
|
+
if (r.failures.some((f) => f.error) && !s.step.use) broken = s.index;
|
|
222
|
+
const pass = r.failures.length === 0;
|
|
223
|
+
failures.push(...r.failures);
|
|
224
|
+
notes.push(...r.notes);
|
|
225
|
+
steps.push({
|
|
226
|
+
...base,
|
|
227
|
+
pass,
|
|
228
|
+
reason: pass ? r.notes.join("; ") || "Passed" : r.failures.map(display).join("; "),
|
|
229
|
+
failures: r.failures,
|
|
230
|
+
ms: Date.now() - t,
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
const pass = failures.length === 0;
|
|
234
|
+
const checkRec = {
|
|
235
|
+
name: compiled.name,
|
|
236
|
+
pass,
|
|
237
|
+
reason: pass ? notes.join("; ") || "Passed" : failures.map(display).join("; "),
|
|
238
|
+
failures,
|
|
239
|
+
ms: Date.now() - t0,
|
|
240
|
+
};
|
|
241
|
+
return { ...summarize([checkRec]), steps };
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
// ---- recipe → code ------------------------------------------------------
|
|
245
|
+
|
|
246
|
+
const IDENT = /^[A-Za-z_$][\w$]*$/;
|
|
247
|
+
|
|
248
|
+
function jsValue(v, indent) {
|
|
249
|
+
if (Array.isArray(v)) {
|
|
250
|
+
const inner = v.map((x) => jsValue(x, indent));
|
|
251
|
+
const one = `[${inner.join(", ")}]`;
|
|
252
|
+
return one.length <= 70 ? one : `[\n${inner.map((x) => `${indent} ${x}`).join(",\n")},\n${indent}]`;
|
|
253
|
+
}
|
|
254
|
+
if (isObj(v)) return jsObject(v, indent);
|
|
255
|
+
return JSON.stringify(v);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function jsObject(o, indent) {
|
|
259
|
+
const entries = Object.entries(o).map(([k, v]) => `${IDENT.test(k) ? k : JSON.stringify(k)}: ${jsValue(v, `${indent} `)}`);
|
|
260
|
+
if (!entries.length) return "{}";
|
|
261
|
+
const one = `{ ${entries.join(", ")} }`;
|
|
262
|
+
if (one.length <= 72 && !one.includes("\n")) return one;
|
|
263
|
+
return `{\n${entries.map((e) => `${indent} ${e}`).join(",\n")},\n${indent}}`;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** A value path as JS on ctx: handoff.plan.cause → ctx.handoff.plan?.cause. */
|
|
267
|
+
function pathCode(p) {
|
|
268
|
+
const parts = p.split(".");
|
|
269
|
+
const { ROOTS } = require("../lib/values");
|
|
270
|
+
if (!ROOTS.includes(parts[0]) || parts.length === 1 || !parts.every((x) => IDENT.test(x) || /^\d+$/.test(x))) {
|
|
271
|
+
return `ctx.get(${JSON.stringify(p)})`;
|
|
272
|
+
}
|
|
273
|
+
let out = `ctx.${parts[0]}`;
|
|
274
|
+
parts.slice(1).forEach((k, i) => {
|
|
275
|
+
const acc = /^\d+$/.test(k) ? `[${k}]` : `.${k}`;
|
|
276
|
+
out += i === 0 ? acc : `?.${acc.replace(/^\./, "")}`;
|
|
277
|
+
});
|
|
278
|
+
return out;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function argCode(a, type) {
|
|
282
|
+
if (typeof a === "string" && hasPlaceholder(a)) return `ctx.fill(${JSON.stringify(a)})`;
|
|
283
|
+
if (type === "regex" && typeof a === "string") {
|
|
284
|
+
try {
|
|
285
|
+
return String(new RegExp(a));
|
|
286
|
+
} catch (_e) {
|
|
287
|
+
return JSON.stringify(a);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
return jsValue(a, " ");
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* The recipe as a .check.js file that gives the same result.
|
|
295
|
+
* @param {object} recipe
|
|
296
|
+
* @param {{ getHelper?: Function, file?: string }} [opts]
|
|
297
|
+
*/
|
|
298
|
+
function recipeToCode(recipe, opts = {}) {
|
|
299
|
+
const compiled = compileRecipe(recipe, opts);
|
|
300
|
+
const find = opts.getHelper || getHelper;
|
|
301
|
+
const groups = new Set();
|
|
302
|
+
let usesHelperById = false;
|
|
303
|
+
let usesExpect = false;
|
|
304
|
+
const body = [];
|
|
305
|
+
for (const s of compiled.steps) {
|
|
306
|
+
const step = s.step;
|
|
307
|
+
const pad = step.when !== undefined ? " " : " ";
|
|
308
|
+
const lines = [];
|
|
309
|
+
if (step.use) {
|
|
310
|
+
const h = find(step.use);
|
|
311
|
+
const builtin = require("../helpers").all.includes(h);
|
|
312
|
+
const params = { ...(step.with || {}), ...(step.message ? { message: step.message } : {}) };
|
|
313
|
+
const arg = Object.keys(params).length ? `, ${jsObject(params, pad)}` : "";
|
|
314
|
+
if (builtin) {
|
|
315
|
+
const [g, ...rest] = step.use.split(".");
|
|
316
|
+
groups.add(g);
|
|
317
|
+
lines.push(`${pad}await ${g}.${rest.join(".")}(ctx${arg});`);
|
|
318
|
+
} else {
|
|
319
|
+
usesHelperById = true;
|
|
320
|
+
lines.push(`${pad}await helper(${JSON.stringify(step.use)})(ctx${arg});`);
|
|
321
|
+
}
|
|
322
|
+
} else {
|
|
323
|
+
usesExpect = true;
|
|
324
|
+
const meta = expect.meta(step.matcher);
|
|
325
|
+
const args = (step.args || []).map((a, i) => argCode(a, meta.params[i] && meta.params[i].type));
|
|
326
|
+
if (step.message) args.push(hasPlaceholder(step.message) ? `ctx.fill(${JSON.stringify(step.message)}, { missing: "keep" })` : JSON.stringify(step.message));
|
|
327
|
+
const head = `${pad}expect(${pathCode(step.expect)}, ${JSON.stringify(step.expect)})`;
|
|
328
|
+
const call = `${step.not ? ".not" : ""}.${step.matcher}(${args.join(", ")});`;
|
|
329
|
+
if (head.length + call.length <= 90) lines.push(head + call);
|
|
330
|
+
else lines.push(head, `${pad} ${call}`);
|
|
331
|
+
}
|
|
332
|
+
if (step.when !== undefined) {
|
|
333
|
+
body.push(` if (ctx.when(${JSON.stringify(step.when)})) {`, ...lines, " }");
|
|
334
|
+
} else body.push(...lines);
|
|
335
|
+
}
|
|
336
|
+
const coreNames = ["check", ...(usesExpect ? ["expect"] : []), ...(usesHelperById ? ["helper"] : [])];
|
|
337
|
+
const file = opts.file || `.dash/checks/${slug(recipe.name)}.check.js`;
|
|
338
|
+
const head = [
|
|
339
|
+
`// ${file} (generated by recipeToCode)`,
|
|
340
|
+
`const { ${coreNames.join(", ")} } = require("@trops/dash-check");`,
|
|
341
|
+
];
|
|
342
|
+
if (groups.size) head.push(`const { ${[...groups].join(", ")} } = require("@trops/dash-check/helpers");`);
|
|
343
|
+
return `${head.join("\n")}\n\ncheck(${JSON.stringify(compiled.name)}, async (ctx) => {\n${body.join("\n")}\n});\n`;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** A name as a file name: "The work is ready" → "the-work-is-ready". */
|
|
347
|
+
function slug(name) {
|
|
348
|
+
return String(name || "check").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60) || "check";
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ---- explain --------------------------------------------------------------
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* The recipe as sentences, one per step:
|
|
355
|
+
* "Work is committed: at least 1 commit(s) past {repo.baseBranch}, and nothing uncommitted"
|
|
356
|
+
* @returns {string[]}
|
|
357
|
+
*/
|
|
358
|
+
function explain(recipe, opts = {}) {
|
|
359
|
+
const find = opts.getHelper || getHelper;
|
|
360
|
+
if (!isObj(recipe) || !Array.isArray(recipe.steps)) return [];
|
|
361
|
+
return recipe.steps.map((s) => {
|
|
362
|
+
if (!isObj(s)) return "(not a step)";
|
|
363
|
+
let text;
|
|
364
|
+
if (s.use) {
|
|
365
|
+
const h = find(s.use);
|
|
366
|
+
if (!h) text = `${s.use} (no such helper)`;
|
|
367
|
+
else {
|
|
368
|
+
const said = sentenceOf(h.meta, s.with || {});
|
|
369
|
+
text = `${s.label || h.meta.label}${said ? `: ${said}` : ""}`;
|
|
370
|
+
}
|
|
371
|
+
} else {
|
|
372
|
+
const said = expect.has(s.matcher) ? expect.sentence(s.matcher, s.expect, s.args || [], !!s.not) : `${s.expect} ${s.matcher}`;
|
|
373
|
+
text = `${s.label ? `${s.label}: ` : ""}Expect ${said}`;
|
|
374
|
+
}
|
|
375
|
+
if (s.when !== undefined) text = `Only when ${s.when}: ${text}`;
|
|
376
|
+
if (s.message) text += `. If it fails, say: "${s.message}"`;
|
|
377
|
+
return text;
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
module.exports = { schema, validateRecipe, compileRecipe, runRecipe, recipeToCode, toCode: recipeToCode, explain, valuePaths, slug, pathCode };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
3
|
+
"$id": "https://github.com/trops/dash-check/recipe/schema.json",
|
|
4
|
+
"title": "dash-check recipe",
|
|
5
|
+
"description": "A check made of steps: helpers (use) and value expectations (expect). It holds no code, so it is safe to store on a bot, share and edit in a UI.",
|
|
6
|
+
"type": "object",
|
|
7
|
+
"required": ["name", "steps"],
|
|
8
|
+
"additionalProperties": false,
|
|
9
|
+
"properties": {
|
|
10
|
+
"$schema": { "type": "string" },
|
|
11
|
+
"name": { "type": "string", "minLength": 1, "maxLength": 200, "description": "What the check proves" },
|
|
12
|
+
"description": { "type": "string", "maxLength": 2000 },
|
|
13
|
+
"version": { "type": "integer", "minimum": 1, "description": "The recipe format's version (1)" },
|
|
14
|
+
"steps": {
|
|
15
|
+
"type": "array",
|
|
16
|
+
"minItems": 1,
|
|
17
|
+
"maxItems": 100,
|
|
18
|
+
"items": { "oneOf": [{ "$ref": "#/definitions/useStep" }, { "$ref": "#/definitions/expectStep" }] }
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"definitions": {
|
|
22
|
+
"when": {
|
|
23
|
+
"type": ["string", "boolean"],
|
|
24
|
+
"description": "Run the step only when this is truthy: a value path (handoff.prUrl) or a placeholder ({mergeWhenGreen}); a leading ! turns it around"
|
|
25
|
+
},
|
|
26
|
+
"message": { "type": "string", "maxLength": 2000, "description": "What a failure says instead (the fix)" },
|
|
27
|
+
"label": { "type": "string", "maxLength": 200, "description": "The row's own name (default: the helper's label)" },
|
|
28
|
+
"useStep": {
|
|
29
|
+
"type": "object",
|
|
30
|
+
"required": ["use"],
|
|
31
|
+
"additionalProperties": false,
|
|
32
|
+
"properties": {
|
|
33
|
+
"use": { "type": "string", "pattern": "^[a-z][A-Za-z0-9]*(\\.[a-z][A-Za-z0-9]*)+$", "description": "A helper's id, e.g. git.committedSince" },
|
|
34
|
+
"with": { "type": "object", "description": "The helper's params; strings can hold {placeholders} from settings, item and row" },
|
|
35
|
+
"when": { "$ref": "#/definitions/when" },
|
|
36
|
+
"message": { "$ref": "#/definitions/message" },
|
|
37
|
+
"label": { "$ref": "#/definitions/label" }
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"expectStep": {
|
|
41
|
+
"type": "object",
|
|
42
|
+
"required": ["expect", "matcher"],
|
|
43
|
+
"additionalProperties": false,
|
|
44
|
+
"properties": {
|
|
45
|
+
"expect": { "type": "string", "pattern": "^[A-Za-z_$][\\w$-]*(\\.[\\w$-]+)*$", "description": "A value by path: handoff.files, item.id, env.DASH_BRANCH, repo.baseBranch" },
|
|
46
|
+
"matcher": { "type": "string", "pattern": "^to[A-Z][A-Za-z0-9]*$", "description": "A matcher's id, e.g. toHaveLengthAtLeast" },
|
|
47
|
+
"args": { "type": "array", "description": "The matcher's params, in order; strings can hold {placeholders}" },
|
|
48
|
+
"not": { "type": "boolean", "description": "Expect the opposite" },
|
|
49
|
+
"when": { "$ref": "#/definitions/when" },
|
|
50
|
+
"message": { "$ref": "#/definitions/message" },
|
|
51
|
+
"label": { "$ref": "#/definitions/label" }
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|