@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/index.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @trops/dash-check: compose deterministic checks from small, described
|
|
3
|
+
* building blocks.
|
|
4
|
+
*
|
|
5
|
+
* const { check, expect } = require("@trops/dash-check");
|
|
6
|
+
* check("the ticket has acceptance items", ({ handoff }) => {
|
|
7
|
+
* expect(handoff.acceptance, "handoff.acceptance").not.toBeEmpty("Add acceptance items to the ticket");
|
|
8
|
+
* });
|
|
9
|
+
*
|
|
10
|
+
* Layer 0 (this module): the runner, expect, the context, defineHelper.
|
|
11
|
+
* Layer 1: require("@trops/dash-check/helpers").
|
|
12
|
+
* Layer 2: require("@trops/dash-check/recipe").
|
|
13
|
+
*/
|
|
14
|
+
"use strict";
|
|
15
|
+
|
|
16
|
+
const runner = require("./lib/runner");
|
|
17
|
+
const { expect, defineMatcher } = require("./lib/expect");
|
|
18
|
+
const { createContext } = require("./lib/context");
|
|
19
|
+
const { defineHelper, helper, getHelper, listHelpers, register, sentenceOf, resolveParams } = require("./lib/helper");
|
|
20
|
+
const { fail, note, collect, CheckFailure } = require("./lib/scope");
|
|
21
|
+
const { lastJsonBlock, readHandoff } = require("./lib/handoff");
|
|
22
|
+
const { matchGlob, globToRegExp } = require("./lib/glob");
|
|
23
|
+
const values = require("./lib/values");
|
|
24
|
+
const { DashCheckError, isEmpty, deepEqual } = require("./lib/util");
|
|
25
|
+
const { loadHelpers } = require("./lib/discover");
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Run a check file in this process: a .check.js file's checks, or a
|
|
29
|
+
* .check.json recipe. The file's require("@trops/dash-check") must give this
|
|
30
|
+
* copy (lib/register.js makes sure of it).
|
|
31
|
+
* @param {string} file
|
|
32
|
+
* @param {object} [input] the check input
|
|
33
|
+
* @param {object} [opts] createContext options (cwd, env, fetch, tool, …)
|
|
34
|
+
*/
|
|
35
|
+
async function runFile(file, input = {}, opts = {}) {
|
|
36
|
+
require("./lib/register");
|
|
37
|
+
if (/\.json$/i.test(file)) {
|
|
38
|
+
const r = JSON.parse(require("fs").readFileSync(file, "utf8"));
|
|
39
|
+
return require("./recipe").runRecipe(r, input, opts);
|
|
40
|
+
}
|
|
41
|
+
const checks = runner.loadChecks(file);
|
|
42
|
+
return runner.runChecks(checks, opts.ctx || createContext(input, opts), opts);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
module.exports = {
|
|
46
|
+
runFile,
|
|
47
|
+
// the runner
|
|
48
|
+
check: runner.check,
|
|
49
|
+
describe: runner.describe,
|
|
50
|
+
run: runner.run,
|
|
51
|
+
runChecks: runner.runChecks,
|
|
52
|
+
loadChecks: runner.loadChecks,
|
|
53
|
+
takeChecks: runner.takeChecks,
|
|
54
|
+
lastLine: runner.lastLine,
|
|
55
|
+
report: runner.report,
|
|
56
|
+
// expect
|
|
57
|
+
expect,
|
|
58
|
+
defineMatcher,
|
|
59
|
+
fail,
|
|
60
|
+
note,
|
|
61
|
+
collect,
|
|
62
|
+
// the context
|
|
63
|
+
createContext,
|
|
64
|
+
readHandoff,
|
|
65
|
+
lastJsonBlock,
|
|
66
|
+
get: values.get,
|
|
67
|
+
fill: values.fill,
|
|
68
|
+
when: values.when,
|
|
69
|
+
valuePaths: values.valuePaths,
|
|
70
|
+
// helpers
|
|
71
|
+
defineHelper,
|
|
72
|
+
helper,
|
|
73
|
+
getHelper,
|
|
74
|
+
listHelpers,
|
|
75
|
+
registerHelpers: register,
|
|
76
|
+
loadHelpers,
|
|
77
|
+
sentenceOf,
|
|
78
|
+
resolveParams,
|
|
79
|
+
// small tools
|
|
80
|
+
matchGlob,
|
|
81
|
+
globToRegExp,
|
|
82
|
+
isEmpty,
|
|
83
|
+
deepEqual,
|
|
84
|
+
CheckFailure,
|
|
85
|
+
DashCheckError,
|
|
86
|
+
};
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* fs.js: ctx.fs, read-only and relative to the workspace.
|
|
3
|
+
* exists(p), dirExists(p), read(p), readJson(p), list(glob)
|
|
4
|
+
*/
|
|
5
|
+
"use strict";
|
|
6
|
+
|
|
7
|
+
const fs = require("fs");
|
|
8
|
+
const path = require("path");
|
|
9
|
+
const os = require("os");
|
|
10
|
+
const { matchGlob, globBase } = require("../glob");
|
|
11
|
+
const { DashCheckError } = require("../util");
|
|
12
|
+
|
|
13
|
+
const SKIP_DIRS = new Set([".git", "node_modules"]);
|
|
14
|
+
const MAX_FILES = 20000;
|
|
15
|
+
|
|
16
|
+
const expand = (p) => (p === "~" || String(p).startsWith("~/") ? path.join(os.homedir(), String(p).slice(1)) : String(p));
|
|
17
|
+
|
|
18
|
+
function makeFs(cwd) {
|
|
19
|
+
const at = (p) => path.resolve(cwd, expand(p));
|
|
20
|
+
const api = {
|
|
21
|
+
/** The full path of a workspace path. */
|
|
22
|
+
path: (p) => at(p),
|
|
23
|
+
exists: async (p) => fs.existsSync(at(p)),
|
|
24
|
+
dirExists: async (p = ".") => {
|
|
25
|
+
try {
|
|
26
|
+
return fs.statSync(at(p)).isDirectory();
|
|
27
|
+
} catch (_e) {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
read: async (p) => {
|
|
32
|
+
try {
|
|
33
|
+
return fs.readFileSync(at(p), "utf8");
|
|
34
|
+
} catch (e) {
|
|
35
|
+
throw new DashCheckError(`Can't read ${p}`, {
|
|
36
|
+
fix: e.code === "ENOENT" ? "the file isn't there" : e.message,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
readJson: async (p) => {
|
|
41
|
+
const text = await api.read(p);
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(text);
|
|
44
|
+
} catch (e) {
|
|
45
|
+
throw new DashCheckError(`${p} isn't valid JSON`, { fix: e.message });
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
/**
|
|
49
|
+
* Files matching a glob (or globs, with "!glob" to leave out), relative
|
|
50
|
+
* and sorted. Skips .git and node_modules unless the glob names them.
|
|
51
|
+
*/
|
|
52
|
+
list: async (globs) => {
|
|
53
|
+
const list = (Array.isArray(globs) ? globs : [globs]).map(String).filter(Boolean);
|
|
54
|
+
const wanted = list.filter((g) => !g.startsWith("!"));
|
|
55
|
+
const names = new Set(list.join(" ").split(/[/\s]/));
|
|
56
|
+
const bases = [...new Set(wanted.map(globBase))];
|
|
57
|
+
const out = new Set();
|
|
58
|
+
let count = 0;
|
|
59
|
+
const walk = (rel) => {
|
|
60
|
+
let entries;
|
|
61
|
+
try {
|
|
62
|
+
entries = fs.readdirSync(path.join(cwd, rel), { withFileTypes: true });
|
|
63
|
+
} catch (_e) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
for (const e of entries) {
|
|
67
|
+
if (count > MAX_FILES) return;
|
|
68
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
69
|
+
if (e.isDirectory()) {
|
|
70
|
+
if (SKIP_DIRS.has(e.name) && !names.has(e.name)) continue;
|
|
71
|
+
walk(r);
|
|
72
|
+
} else {
|
|
73
|
+
count++;
|
|
74
|
+
if (matchGlob(list, r)) out.add(r);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
for (const b of bases) walk(b);
|
|
79
|
+
return [...out].sort();
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
return api;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
module.exports = { makeFs, expand };
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* git.js: ctx.git, read-only git in the workspace. Each method fails with
|
|
3
|
+
* what went wrong and what to do about it.
|
|
4
|
+
*/
|
|
5
|
+
"use strict";
|
|
6
|
+
|
|
7
|
+
const { execArgs } = require("./run");
|
|
8
|
+
const { DashCheckError } = require("../util");
|
|
9
|
+
|
|
10
|
+
function makeGit({ cwd, env }) {
|
|
11
|
+
const g = (args) => execArgs("git", args, { cwd, env });
|
|
12
|
+
const must = async (args, what, fix) => {
|
|
13
|
+
const r = await g(args);
|
|
14
|
+
if (!r.ok) {
|
|
15
|
+
if (/not a git repository/i.test(r.err)) {
|
|
16
|
+
throw new DashCheckError(`${cwd} isn't a git repo`, { fix: "run the check in the repo's folder" });
|
|
17
|
+
}
|
|
18
|
+
throw new DashCheckError(`${what} (${r.err.split("\n")[0] || `git exit ${r.code}`})`, { fix });
|
|
19
|
+
}
|
|
20
|
+
return r.out;
|
|
21
|
+
};
|
|
22
|
+
const verify = async (ref) => (await g(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`])).ok;
|
|
23
|
+
const needRef = async (ref) => {
|
|
24
|
+
if (!ref || typeof ref !== "string") throw new DashCheckError("No git ref given", { fix: "name a branch, e.g. origin/main" });
|
|
25
|
+
if (!(await verify(ref))) {
|
|
26
|
+
const remote = ref.startsWith("origin/") ? ref.slice(7) : null;
|
|
27
|
+
throw new DashCheckError(`${ref} isn't there`, {
|
|
28
|
+
fix: remote ? `fetch it (git fetch origin ${remote}), or check the base branch's name` : "check the branch's name",
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
const lines = (s) => s.split("\n").map((l) => l.trim()).filter(Boolean);
|
|
33
|
+
|
|
34
|
+
const api = {
|
|
35
|
+
/** The current branch ("HEAD" when detached). */
|
|
36
|
+
branch: async () => (await must(["rev-parse", "--abbrev-ref", "HEAD"], "Can't read the branch")).trim(),
|
|
37
|
+
/** Uncommitted files (staged, unstaged and untracked). */
|
|
38
|
+
uncommitted: async () =>
|
|
39
|
+
(await must(["status", "--porcelain"], "Can't read git status"))
|
|
40
|
+
.split("\n")
|
|
41
|
+
.filter(Boolean)
|
|
42
|
+
.map((l) => l.slice(3).replace(/^"|"$/g, "")),
|
|
43
|
+
isClean: async () => (await api.uncommitted()).length === 0,
|
|
44
|
+
/** How many commits HEAD has past a ref (rev-list ref..HEAD). */
|
|
45
|
+
commitsSince: async (ref) => {
|
|
46
|
+
await needRef(ref);
|
|
47
|
+
return Number((await must(["rev-list", "--count", `${ref}..HEAD`], `Can't count commits past ${ref}`)).trim()) || 0;
|
|
48
|
+
},
|
|
49
|
+
/**
|
|
50
|
+
* Files changed since a ref: committed since where the branch left it,
|
|
51
|
+
* plus uncommitted and untracked ones. Sorted, relative.
|
|
52
|
+
*/
|
|
53
|
+
changedFiles: async (ref) => {
|
|
54
|
+
await needRef(ref);
|
|
55
|
+
const base = (await must(["merge-base", ref, "HEAD"], `Can't find where HEAD left ${ref}`)).trim();
|
|
56
|
+
const changed = lines(await must(["diff", "--name-only", base], `Can't diff against ${ref}`));
|
|
57
|
+
const untracked = lines(await must(["ls-files", "--others", "--exclude-standard"], "Can't list untracked files"));
|
|
58
|
+
return [...new Set([...changed, ...untracked])].sort();
|
|
59
|
+
},
|
|
60
|
+
lastCommitMessage: async () => (await must(["log", "-1", "--format=%B"], "Can't read the last commit")).trim(),
|
|
61
|
+
/** Does the remote (origin) have this branch? */
|
|
62
|
+
remoteHas: async (branch, remote = "origin") => {
|
|
63
|
+
const r = await g(["ls-remote", "--exit-code", "--heads", remote, String(branch)]);
|
|
64
|
+
if (r.ok) return true;
|
|
65
|
+
if (r.code === 2) return false;
|
|
66
|
+
throw new DashCheckError(`Can't reach ${remote} (${r.err.split("\n")[0]})`, { fix: "check the remote and the sign-in" });
|
|
67
|
+
},
|
|
68
|
+
/** The default branch's name: origin/HEAD's, else main or master. null when none. */
|
|
69
|
+
defaultBranch: async () => {
|
|
70
|
+
const head = await g(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]);
|
|
71
|
+
if (head.ok && head.out.trim()) return head.out.trim().replace(/^refs\/remotes\/origin\//, "");
|
|
72
|
+
for (const b of ["main", "master"]) if (await verify(`origin/${b}`)) return b;
|
|
73
|
+
for (const b of ["main", "master"]) if (await verify(b)) return b;
|
|
74
|
+
return null;
|
|
75
|
+
},
|
|
76
|
+
/** A file's text at a ref, or null when it isn't there. */
|
|
77
|
+
fileAt: async (ref, p) => {
|
|
78
|
+
const r = await g(["show", `${ref}:${String(p).replace(/^\.\//, "")}`]);
|
|
79
|
+
return r.ok ? r.out : null;
|
|
80
|
+
},
|
|
81
|
+
/** Does a ref exist? */
|
|
82
|
+
hasRef: verify,
|
|
83
|
+
};
|
|
84
|
+
return api;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = { makeGit };
|
|
@@ -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 };
|