@trops/dash-check 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +355 -2
  3. package/cli/bin.js +12 -0
  4. package/cli/index.d.ts +7 -0
  5. package/cli/index.js +566 -0
  6. package/examples/changes-match-plan.bad.json +4 -0
  7. package/examples/changes-match-plan.check.js +18 -0
  8. package/examples/changes-match-plan.sample.json +4 -0
  9. package/examples/commits-scoped.bad.json +5 -0
  10. package/examples/commits-scoped.check.json +6 -0
  11. package/examples/commits-scoped.sample.json +5 -0
  12. package/examples/every-acceptance-has-a-test.bad.json +3 -0
  13. package/examples/every-acceptance-has-a-test.check.js +19 -0
  14. package/examples/every-acceptance-has-a-test.sample.json +3 -0
  15. package/examples/helpers/changelog.js +23 -0
  16. package/examples/jira-comment-from-job.bad.json +5 -0
  17. package/examples/jira-comment-from-job.check.js +10 -0
  18. package/examples/jira-comment-from-job.sample.json +5 -0
  19. package/examples/lockfile-explained.bad.json +11 -0
  20. package/examples/lockfile-explained.check.json +6 -0
  21. package/examples/lockfile-explained.sample.json +11 -0
  22. package/examples/max-growth.bad.json +8 -0
  23. package/examples/max-growth.check.json +6 -0
  24. package/examples/max-growth.sample.json +8 -0
  25. package/examples/merge-outcome.bad.json +4 -0
  26. package/examples/merge-outcome.check.js +9 -0
  27. package/examples/merge-outcome.sample.json +4 -0
  28. package/examples/new-tests-are-run.bad.json +4 -0
  29. package/examples/new-tests-are-run.check.json +7 -0
  30. package/examples/new-tests-are-run.sample.json +4 -0
  31. package/examples/no-new-debt.bad.json +8 -0
  32. package/examples/no-new-debt.check.json +14 -0
  33. package/examples/no-new-debt.sample.json +8 -0
  34. package/examples/on-branch.bad.json +6 -0
  35. package/examples/on-branch.check.js +12 -0
  36. package/examples/on-branch.sample.json +6 -0
  37. package/examples/plan-complete.bad.json +5 -0
  38. package/examples/plan-complete.check.js +14 -0
  39. package/examples/plan-complete.sample.json +5 -0
  40. package/examples/plan-scope.bad.json +4 -0
  41. package/examples/plan-scope.check.json +6 -0
  42. package/examples/plan-scope.sample.json +4 -0
  43. package/examples/pr-ci.bad.json +4 -0
  44. package/examples/pr-ci.check.js +12 -0
  45. package/examples/pr-ci.sample.json +4 -0
  46. package/examples/ready-for-review.bad.json +6 -0
  47. package/examples/ready-for-review.check.json +12 -0
  48. package/examples/ready-for-review.sample.json +6 -0
  49. package/examples/setup.bad.json +6 -0
  50. package/examples/setup.check.js +8 -0
  51. package/examples/setup.sample.json +6 -0
  52. package/examples/source-has-tests.bad.json +4 -0
  53. package/examples/source-has-tests.check.json +6 -0
  54. package/examples/source-has-tests.sample.json +4 -0
  55. package/examples/test-script-is-real.bad.json +6 -0
  56. package/examples/test-script-is-real.check.json +6 -0
  57. package/examples/test-script-is-real.sample.json +6 -0
  58. package/examples/ticket-has-acceptance.bad.json +4 -0
  59. package/examples/ticket-has-acceptance.check.js +10 -0
  60. package/examples/ticket-has-acceptance.sample.json +4 -0
  61. package/examples/validate-leaves-tree-clean.bad.json +6 -0
  62. package/examples/validate-leaves-tree-clean.check.json +7 -0
  63. package/examples/validate-leaves-tree-clean.sample.json +6 -0
  64. package/examples/validate.bad.json +6 -0
  65. package/examples/validate.check.js +14 -0
  66. package/examples/validate.sample.json +6 -0
  67. package/examples/work-committed.bad.json +13 -0
  68. package/examples/work-committed.check.js +13 -0
  69. package/examples/work-committed.sample.json +5 -0
  70. package/examples/workspace-cleaned.bad.json +4 -0
  71. package/examples/workspace-cleaned.check.js +7 -0
  72. package/examples/workspace-cleaned.sample.json +4 -0
  73. package/helpers/commands.js +62 -0
  74. package/helpers/files.js +124 -0
  75. package/helpers/git.js +379 -0
  76. package/helpers/github.js +77 -0
  77. package/helpers/handoff.js +80 -0
  78. package/helpers/index.d.ts +103 -0
  79. package/helpers/index.js +36 -0
  80. package/helpers/node.js +296 -0
  81. package/helpers/plan.js +55 -0
  82. package/helpers/tracker.js +60 -0
  83. package/index.d.ts +347 -0
  84. package/index.js +86 -0
  85. package/lib/adapters/fs.js +85 -0
  86. package/lib/adapters/git.js +163 -0
  87. package/lib/adapters/github.js +151 -0
  88. package/lib/adapters/run.js +76 -0
  89. package/lib/adapters/tool.js +64 -0
  90. package/lib/context.js +102 -0
  91. package/lib/discover.js +102 -0
  92. package/lib/expect.js +238 -0
  93. package/lib/glob.js +89 -0
  94. package/lib/handoff.js +68 -0
  95. package/lib/helper.js +236 -0
  96. package/lib/register.js +35 -0
  97. package/lib/runner.js +214 -0
  98. package/lib/scope.js +107 -0
  99. package/lib/util.js +122 -0
  100. package/lib/values.js +138 -0
  101. package/package.json +59 -4
  102. package/recipe/index.d.ts +70 -0
  103. package/recipe/index.js +381 -0
  104. package/recipe/schema.json +55 -0
@@ -0,0 +1,151 @@
1
+ /**
2
+ * github.js: ctx.github, read-only GitHub with GH_TOKEN (the bot's GitHub
3
+ * provider in Dash; a token in CI). `fetch` can be passed in for tests.
4
+ *
5
+ * pr(urlOrNumber) the PR, as GitHub gives it (plus `slug`)
6
+ * checksFor(sha, { repo }) { runs: [{ name, status, conclusion, url }], source }
7
+ * waitForChecks(sha, { timeoutSec, noChecksAfterSec, pollSec, repo })
8
+ * { runs, failed, pending, passed, noChecks, timedOut, waitedSec }
9
+ *
10
+ * Each call fails with GitHub's HTTP code and what to do about it.
11
+ */
12
+ "use strict";
13
+
14
+ const { DashCheckError } = require("../util");
15
+
16
+ const PR_URL_RE = /^https:\/\/github\.com\/([^/\s]+)\/([^/\s]+)\/pull\/(\d+)\/?(?:[#?].*)?$/;
17
+ const REPO_RE = /(?:github\.com[/:])?([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/;
18
+ const OK_CONCLUSIONS = ["success", "skipped", "neutral"];
19
+
20
+ function fixFor(code, slug, hasToken) {
21
+ if (code === 401) return hasToken ? "GH_TOKEN is wrong or expired: sign in to GitHub again" : "set GH_TOKEN (sign the bot's GitHub provider in)";
22
+ if (code === 403) return `GH_TOKEN can't read ${slug}, or GitHub's rate limit was hit: give the token read access, or wait`;
23
+ if (code === 404) return `${slug} or the PR isn't there, or GH_TOKEN can't see it: check the link and the token's repo access`;
24
+ if (code >= 500) return "GitHub is having trouble: try again";
25
+ return "check the link and GH_TOKEN";
26
+ }
27
+
28
+ function slugOf(text) {
29
+ const m = String(text || "").trim().match(REPO_RE);
30
+ return m ? `${m[1]}/${m[2]}` : null;
31
+ }
32
+
33
+ /**
34
+ * @param {{ env: object, fetch?: Function, now?: () => number,
35
+ * sleep?: (ms: number) => Promise<void>, repo?: () => Promise<string|null> }} opts
36
+ */
37
+ function makeGithub(opts) {
38
+ const env = opts.env || {};
39
+ const token = String(env.GH_TOKEN || env.GITHUB_TOKEN || "").trim();
40
+ const doFetch = opts.fetch || (typeof fetch === "function" ? fetch : null);
41
+ const now = opts.now || Date.now;
42
+ const sleep = opts.sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
43
+ const base = String(env.GITHUB_API_URL || "https://api.github.com").replace(/\/$/, "");
44
+ let lastSlug = null;
45
+
46
+ async function api(p, what) {
47
+ if (!doFetch) throw new DashCheckError("This Node has no fetch", { fix: "use Node 18 or later" });
48
+ let res;
49
+ try {
50
+ res = await doFetch(`${base}/${p}`, {
51
+ headers: {
52
+ Accept: "application/vnd.github+json",
53
+ "User-Agent": "dash-check",
54
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
55
+ },
56
+ });
57
+ } catch (e) {
58
+ throw new DashCheckError(`Can't reach GitHub for ${what} (${e && e.message ? e.message : e})`, { fix: "check the network" });
59
+ }
60
+ let body = null;
61
+ try {
62
+ body = await res.json();
63
+ } catch (_e) {
64
+ body = null;
65
+ }
66
+ return { code: res.status, body };
67
+ }
68
+
69
+ async function need(p, what, slug) {
70
+ const r = await api(p, what);
71
+ if (r.code !== 200) {
72
+ throw new DashCheckError(`GitHub said HTTP ${r.code} for ${what}`, { fix: fixFor(r.code, slug, !!token), code: r.code });
73
+ }
74
+ return r.body;
75
+ }
76
+
77
+ async function repoSlug(given) {
78
+ const s = slugOf(given) || lastSlug || slugOf(env.GITHUB_REPOSITORY) || (opts.repo ? slugOf(await opts.repo()) : null);
79
+ if (!s) {
80
+ throw new DashCheckError("Don't know which GitHub repo", {
81
+ fix: "give a full PR link (https://github.com/owner/repo/pull/1), or set GITHUB_REPOSITORY=owner/repo",
82
+ });
83
+ }
84
+ return s;
85
+ }
86
+
87
+ const gh = {
88
+ async pr(urlOrNumber, { repo } = {}) {
89
+ let slug;
90
+ let number;
91
+ const m = String(urlOrNumber == null ? "" : urlOrNumber).trim().match(PR_URL_RE);
92
+ if (m) {
93
+ slug = `${m[1]}/${m[2]}`;
94
+ number = Number(m[3]);
95
+ } else if (/^#?\d+$/.test(String(urlOrNumber == null ? "" : urlOrNumber).trim())) {
96
+ number = Number(String(urlOrNumber).replace("#", ""));
97
+ slug = await repoSlug(repo);
98
+ } else {
99
+ throw new DashCheckError(
100
+ urlOrNumber ? `${String(urlOrNumber).slice(0, 200)} isn't a GitHub PR link` : "No PR given",
101
+ { fix: "use a link like https://github.com/owner/repo/pull/12, or a PR number" },
102
+ );
103
+ }
104
+ lastSlug = slug;
105
+ const body = await need(`repos/${slug}/pulls/${number}`, `PR #${number} on ${slug}`, slug);
106
+ return { ...body, slug };
107
+ },
108
+
109
+ async checksFor(sha, { repo } = {}) {
110
+ if (!sha) throw new DashCheckError("No commit given", { fix: "pass the PR's head sha (pr.head.sha)" });
111
+ const slug = await repoSlug(repo);
112
+ const c = await api(`repos/${slug}/commits/${sha}/check-runs?per_page=100`, `check runs on ${slug}`);
113
+ if (c.code === 200) {
114
+ const runs = ((c.body && c.body.check_runs) || []).map((r) => ({
115
+ name: r.name, status: r.status, conclusion: r.conclusion || null, url: r.html_url || null,
116
+ }));
117
+ return { runs, source: "check-runs" };
118
+ }
119
+ const a = await api(`repos/${slug}/actions/runs?head_sha=${sha}&per_page=100`, `Actions runs on ${slug}`);
120
+ if (a.code !== 200) {
121
+ throw new DashCheckError(
122
+ `GitHub said HTTP ${c.code} for check runs and HTTP ${a.code} for Actions runs on ${slug}`,
123
+ { fix: `give GH_TOKEN read access to Checks or Actions on ${slug}`, code: a.code },
124
+ );
125
+ }
126
+ const runs = ((a.body && a.body.workflow_runs) || []).map((r) => ({
127
+ name: r.name, status: r.status, conclusion: r.conclusion || null, url: r.html_url || null,
128
+ }));
129
+ return { runs, source: "actions" };
130
+ },
131
+
132
+ async waitForChecks(sha, { timeoutSec = 1200, noChecksAfterSec = 180, pollSec = 15, repo } = {}) {
133
+ const started = now();
134
+ for (;;) {
135
+ const { runs } = await gh.checksFor(sha, { repo });
136
+ const waitedSec = Math.round((now() - started) / 1000);
137
+ const pending = runs.filter((r) => r.status !== "completed");
138
+ const failed = runs.filter((r) => r.status === "completed" && !OK_CONCLUSIONS.includes(r.conclusion));
139
+ const passed = runs.filter((r) => r.status === "completed" && OK_CONCLUSIONS.includes(r.conclusion));
140
+ const done = runs.length > 0 && pending.length === 0;
141
+ const noChecks = runs.length === 0 && waitedSec >= noChecksAfterSec;
142
+ const timedOut = !done && !noChecks && waitedSec >= timeoutSec;
143
+ if (done || noChecks || timedOut) return { runs, failed, pending, passed, noChecks, timedOut, waitedSec };
144
+ await sleep(Math.max(0, pollSec) * 1000);
145
+ }
146
+ },
147
+ };
148
+ return gh;
149
+ }
150
+
151
+ module.exports = { makeGithub, slugOf, PR_URL_RE };
@@ -0,0 +1,76 @@
1
+ /**
2
+ * run.js: ctx.run(cmd, { timeoutSec }) runs a shell command in the
3
+ * workspace and gives { code, stdout, stderr, timedOut }. It never throws
4
+ * for a failing command: the exit code says.
5
+ */
6
+ "use strict";
7
+
8
+ const { spawn, execFile } = require("child_process");
9
+
10
+ const DEFAULT_TIMEOUT_SEC = 120;
11
+ const MAX_OUTPUT = 4 * 1024 * 1024;
12
+
13
+ function makeRun({ cwd, env }) {
14
+ return function run(cmd, opts = {}) {
15
+ const timeoutSec = Number(opts.timeoutSec) > 0 ? Number(opts.timeoutSec) : DEFAULT_TIMEOUT_SEC;
16
+ return new Promise((resolve) => {
17
+ let stdout = "";
18
+ let stderr = "";
19
+ let timedOut = false;
20
+ let child;
21
+ try {
22
+ child = spawn(String(cmd), {
23
+ cwd: opts.cwd || cwd,
24
+ env: { ...env, ...(opts.env || {}) },
25
+ shell: true,
26
+ detached: process.platform !== "win32",
27
+ stdio: ["ignore", "pipe", "pipe"],
28
+ });
29
+ } catch (e) {
30
+ resolve({ code: 127, stdout: "", stderr: e.message, timedOut: false });
31
+ return;
32
+ }
33
+ const cap = (s, d) => (s.length > MAX_OUTPUT ? s : s + d);
34
+ child.stdout.on("data", (d) => (stdout = cap(stdout, d.toString())));
35
+ child.stderr.on("data", (d) => (stderr = cap(stderr, d.toString())));
36
+ const kill = (sig) => {
37
+ try {
38
+ if (process.platform !== "win32") process.kill(-child.pid, sig);
39
+ else child.kill(sig);
40
+ } catch (_e) {
41
+ // Already gone.
42
+ }
43
+ };
44
+ const timer = setTimeout(() => {
45
+ timedOut = true;
46
+ kill("SIGTERM");
47
+ setTimeout(() => kill("SIGKILL"), 2000).unref();
48
+ }, timeoutSec * 1000);
49
+ child.on("error", (e) => {
50
+ clearTimeout(timer);
51
+ resolve({ code: 127, stdout, stderr: stderr || e.message, timedOut });
52
+ });
53
+ child.on("close", (code, signal) => {
54
+ clearTimeout(timer);
55
+ if (timedOut) stderr += `${stderr ? "\n" : ""}Stopped after ${timeoutSec} seconds`;
56
+ resolve({ code: code === null ? (signal ? 128 : 1) : code, stdout, stderr, timedOut });
57
+ });
58
+ });
59
+ };
60
+ }
61
+
62
+ /** Run a program with arguments (no shell): { ok, code, out, err }. */
63
+ function execArgs(file, args, { cwd, env, maxBuffer = MAX_OUTPUT } = {}) {
64
+ return new Promise((resolve) => {
65
+ execFile(file, args, { cwd, env, maxBuffer, encoding: "utf8" }, (err, stdout, stderr) => {
66
+ resolve({
67
+ ok: !err,
68
+ code: err ? (typeof err.code === "number" ? err.code : 1) : 0,
69
+ out: String(stdout || ""),
70
+ err: String(stderr || (err && err.message) || "").trim(),
71
+ });
72
+ });
73
+ });
74
+ }
75
+
76
+ module.exports = { makeRun, execArgs, DEFAULT_TIMEOUT_SEC };
@@ -0,0 +1,64 @@
1
+ /**
2
+ * tool.js: ctx.tool(provider, name, args), a read-only call to one of the
3
+ * bot's providers. Only Dash can answer it: it runs the check with
4
+ * DASH_TOOL_SOCKET, a local socket that takes one JSON line
5
+ * { "id": 1, "provider": "jira", "tool": "getJiraIssue", "args": { … } }
6
+ * and answers one JSON line { "id": 1, "result": … } or { "id": 1, "error": "…" }.
7
+ * Outside Dash it fails, saying so. Tests pass `tool` to createContext.
8
+ */
9
+ "use strict";
10
+
11
+ const net = require("net");
12
+ const { DashCheckError } = require("../util");
13
+
14
+ const TIMEOUT_MS = 60 * 1000;
15
+
16
+ function makeTool({ env, tool }) {
17
+ if (typeof tool === "function") {
18
+ return async (provider, name, args = {}) => tool(provider, name, args);
19
+ }
20
+ const socket = env && env.DASH_TOOL_SOCKET;
21
+ if (!socket) {
22
+ return async (provider, name) => {
23
+ throw new DashCheckError(`ctx.tool("${provider}", "${name}") only works when Dash runs the check`, {
24
+ fix: "run it from a bot step in Dash, or pass { tool } to createContext in a test",
25
+ });
26
+ };
27
+ }
28
+ let nextId = 1;
29
+ return (provider, name, args = {}) =>
30
+ new Promise((resolve, reject) => {
31
+ const id = nextId++;
32
+ const conn = net.createConnection(socket);
33
+ let buf = "";
34
+ const done = (fn, v) => {
35
+ clearTimeout(timer);
36
+ conn.destroy();
37
+ fn(v);
38
+ };
39
+ const timer = setTimeout(
40
+ () => done(reject, new DashCheckError(`Dash didn't answer ${provider}.${name} in time`, { fix: "check that the provider is connected" })),
41
+ TIMEOUT_MS,
42
+ );
43
+ conn.on("connect", () => conn.write(`${JSON.stringify({ id, provider, tool: name, args })}\n`));
44
+ conn.on("data", (d) => {
45
+ buf += d.toString();
46
+ const nl = buf.indexOf("\n");
47
+ if (nl < 0) return;
48
+ let msg;
49
+ try {
50
+ msg = JSON.parse(buf.slice(0, nl));
51
+ } catch (e) {
52
+ done(reject, new DashCheckError(`Dash's answer to ${provider}.${name} isn't JSON`, { fix: e.message }));
53
+ return;
54
+ }
55
+ if (msg.error) done(reject, new DashCheckError(`${provider}.${name} failed (${msg.error})`, { fix: "check the tool's name, its arguments and the provider's sign-in" }));
56
+ else done(resolve, msg.result);
57
+ });
58
+ conn.on("error", (e) =>
59
+ done(reject, new DashCheckError(`Can't reach Dash for ${provider}.${name} (${e.message})`, { fix: "run the check from Dash" })),
60
+ );
61
+ });
62
+ }
63
+
64
+ module.exports = { makeTool };
package/lib/context.js ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * context.js: createContext(input, opts) builds the `ctx` every check gets.
3
+ *
4
+ * Plain data (each `{}` when Dash didn't give it):
5
+ * input the raw check input (Dash's $DASH_INPUT), always there
6
+ * answer the bot's whole answer (text)
7
+ * handoff the answer's last json block, parsed (`{}` when there's none)
8
+ * item, picks, row, settings, step, job
9
+ * workspace { dir, branch, exists(p), read(p), file(p), dirExists() }
10
+ * env the environment, DASH_* included
11
+ * Read-only adapters, all in the workspace (`cwd`):
12
+ * fs, run, git, github, tool
13
+ * And small tools:
14
+ * get(path), fill(text), when(expr), note(text)
15
+ *
16
+ * Nothing here imports Dash: Dash's inputs are just data.
17
+ */
18
+ "use strict";
19
+
20
+ const fs = require("fs");
21
+ const path = require("path");
22
+ const { isObj } = require("./util");
23
+ const { readHandoff, answerOf } = require("./handoff");
24
+ const values = require("./values");
25
+ const { note } = require("./scope");
26
+ const { makeFs, expand } = require("./adapters/fs");
27
+ const { makeRun, execArgs } = require("./adapters/run");
28
+ const { makeGit } = require("./adapters/git");
29
+ const { makeGithub } = require("./adapters/github");
30
+ const { makeTool } = require("./adapters/tool");
31
+
32
+ const obj = (v) => (isObj(v) ? v : {});
33
+
34
+ /**
35
+ * @param {object} [input] the check input (Dash's standard input)
36
+ * @param {{ cwd?: string, env?: object, fetch?: Function, tool?: Function,
37
+ * now?: () => number, sleep?: (ms: number) => Promise<void> }} [opts]
38
+ */
39
+ function createContext(input, opts = {}) {
40
+ const raw = isObj(input) ? input : {};
41
+ const env = { ...(opts.env || process.env) };
42
+ const cwd = path.resolve(opts.cwd || process.cwd());
43
+ const { handoff, info } = readHandoff(raw);
44
+ const files = makeFs(cwd);
45
+ const git = makeGit({ cwd, env });
46
+ const w = obj(raw.workspace);
47
+ const wsDir = typeof w.dir === "string" && w.dir ? path.resolve(cwd, expand(w.dir)) : cwd;
48
+ const stepName = env.DASH_STEP;
49
+
50
+ const ctx = {
51
+ input: raw,
52
+ answer: answerOf(raw),
53
+ handoff,
54
+ handoffInfo: info,
55
+ item: obj(raw.item),
56
+ picks: obj(raw.picks),
57
+ row: obj(raw.row || raw.rows),
58
+ settings: obj(raw.settings),
59
+ step: isObj(raw.step) ? raw.step : stepName ? { name: stepName, inputs: obj(raw.check && raw.check.inputs) } : {},
60
+ job: obj(raw.job),
61
+ workspace: {
62
+ ...w,
63
+ dir: wsDir,
64
+ branch: typeof w.branch === "string" ? w.branch : env.DASH_BRANCH || undefined,
65
+ file: (p) => files.path(p),
66
+ exists: (p) => files.exists(p),
67
+ read: (p) => files.read(p),
68
+ dirExists: async () => {
69
+ try {
70
+ return fs.statSync(wsDir).isDirectory();
71
+ } catch (_e) {
72
+ return false;
73
+ }
74
+ },
75
+ },
76
+ env,
77
+ cwd,
78
+ fs: files,
79
+ run: makeRun({ cwd, env }),
80
+ git,
81
+ github: makeGithub({
82
+ env,
83
+ fetch: opts.fetch,
84
+ now: opts.now,
85
+ sleep: opts.sleep,
86
+ repo: async () => {
87
+ const r = obj(raw.row && raw.row.repo);
88
+ if (r.url) return r.url;
89
+ const remote = await execArgs("git", ["remote", "get-url", "origin"], { cwd, env });
90
+ return remote.ok ? remote.out.trim() : null;
91
+ },
92
+ }),
93
+ tool: makeTool({ env, tool: opts.tool }),
94
+ };
95
+ ctx.get = (p) => values.get(ctx, p);
96
+ ctx.fill = (text, o) => values.fill(ctx, text, o);
97
+ ctx.when = (expr) => values.when(ctx, expr);
98
+ ctx.note = note;
99
+ return ctx;
100
+ }
101
+
102
+ module.exports = { createContext };
@@ -0,0 +1,102 @@
1
+ /**
2
+ * discover.js: finding a team's own helpers.
3
+ *
4
+ * - every .js file in the repo's .dash/checks/helpers/;
5
+ * - every installed package (dependencies and devDependencies) whose
6
+ * package.json says "dashCheck": { "helpers": ["./a.js", …] }.
7
+ *
8
+ * A file exports one helper, a list of them, or an object of them. A file
9
+ * that won't load is reported with its error; the others still load.
10
+ */
11
+ "use strict";
12
+
13
+ const fs = require("fs");
14
+ const path = require("path");
15
+ const { register, unregister } = require("./helper");
16
+
17
+ const HELPERS_DIR = ".dash/checks/helpers";
18
+
19
+ function helpersIn(exported) {
20
+ if (!exported) return [];
21
+ if (exported.isDashCheckHelper) return [exported];
22
+ if (Array.isArray(exported)) return exported.filter((h) => h && h.isDashCheckHelper);
23
+ if (typeof exported === "object") return Object.values(exported).filter((h) => h && h.isDashCheckHelper);
24
+ return [];
25
+ }
26
+
27
+ function loadFile(file, source, out, loaded) {
28
+ const shown = source;
29
+ try {
30
+ const full = path.resolve(file);
31
+ // A helper file asks for the same copy of dash-check as this one, so
32
+ // its defineHelper and expect are ours.
33
+ require("./register");
34
+ const prev = loaded.get(full);
35
+ if (prev) prev.forEach((id) => unregister(id));
36
+ delete require.cache[full];
37
+ const list = helpersIn(require(full));
38
+ if (!list.length) throw new Error("it exports no helper: module.exports = defineHelper({ … })");
39
+ register(list, { source: shown, replace: !!prev });
40
+ loaded.set(full, list.map((h) => h.meta.id));
41
+ for (const h of list) out.helpers.push({ id: h.meta.id, source: shown });
42
+ } catch (e) {
43
+ out.errors.push({ source: shown, error: e && e.message ? e.message.split("\n")[0] : String(e) });
44
+ }
45
+ }
46
+
47
+ const LOADED = new Map();
48
+
49
+ /**
50
+ * Load a repo's helpers into the registry.
51
+ * @param {{ cwd?: string }} [opts]
52
+ * @returns {{ helpers: Array<{ id, source }>, errors: Array<{ source, error }> }}
53
+ */
54
+ function loadHelpers({ cwd = process.cwd() } = {}) {
55
+ const out = { helpers: [], errors: [] };
56
+ const dir = path.join(cwd, HELPERS_DIR);
57
+ let files = [];
58
+ try {
59
+ files = fs.readdirSync(dir).filter((f) => /\.c?js$/.test(f)).sort();
60
+ } catch (_e) {
61
+ files = [];
62
+ }
63
+ for (const f of files) loadFile(path.join(dir, f), `${HELPERS_DIR}/${f}`, out, LOADED);
64
+
65
+ let pkg = null;
66
+ try {
67
+ pkg = JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8"));
68
+ } catch (_e) {
69
+ pkg = null;
70
+ }
71
+ const deps = pkg ? Object.keys({ ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) }).sort() : [];
72
+ const self = pkg && pkg.dashCheck ? [[".", pkg]] : [];
73
+ const found = [...self];
74
+ for (const name of deps) {
75
+ const at = path.join(cwd, "node_modules", name);
76
+ try {
77
+ const dp = JSON.parse(fs.readFileSync(path.join(at, "package.json"), "utf8"));
78
+ if (dp.dashCheck) found.push([name, dp]);
79
+ } catch (_e) {
80
+ // Not installed, or no package.json: nothing to load.
81
+ }
82
+ }
83
+ for (const [name, dp] of found) {
84
+ const root = name === "." ? cwd : path.join(cwd, "node_modules", name);
85
+ const list = dp.dashCheck && Array.isArray(dp.dashCheck.helpers) ? dp.dashCheck.helpers : null;
86
+ if (!list) {
87
+ out.errors.push({ source: `${name}/package.json`, error: 'its "dashCheck" needs "helpers": ["./file.js", …]' });
88
+ continue;
89
+ }
90
+ for (const rel of list) {
91
+ const full = path.resolve(root, String(rel));
92
+ if (path.relative(root, full).startsWith("..")) {
93
+ out.errors.push({ source: `${name}: ${rel}`, error: "a helper must be inside its package" });
94
+ continue;
95
+ }
96
+ loadFile(full, name === "." ? String(rel) : `${name}/${String(rel).replace(/^\.\//, "")}`, out, LOADED);
97
+ }
98
+ }
99
+ return out;
100
+ }
101
+
102
+ module.exports = { loadHelpers, HELPERS_DIR };