@trops/dash-check 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +68 -8
  2. package/examples/changes-match-plan.check.js +12 -4
  3. package/examples/commits-scoped.bad.json +5 -0
  4. package/examples/commits-scoped.check.json +6 -0
  5. package/examples/commits-scoped.sample.json +5 -0
  6. package/examples/lockfile-explained.bad.json +11 -0
  7. package/examples/lockfile-explained.check.json +6 -0
  8. package/examples/lockfile-explained.sample.json +11 -0
  9. package/examples/max-growth.bad.json +8 -0
  10. package/examples/max-growth.check.json +6 -0
  11. package/examples/max-growth.sample.json +8 -0
  12. package/examples/new-tests-are-run.bad.json +4 -0
  13. package/examples/new-tests-are-run.check.json +7 -0
  14. package/examples/new-tests-are-run.sample.json +4 -0
  15. package/examples/no-new-debt.bad.json +8 -0
  16. package/examples/no-new-debt.check.json +14 -0
  17. package/examples/no-new-debt.sample.json +8 -0
  18. package/examples/plan-scope.bad.json +4 -0
  19. package/examples/plan-scope.check.json +6 -0
  20. package/examples/plan-scope.sample.json +4 -0
  21. package/examples/source-has-tests.bad.json +4 -0
  22. package/examples/source-has-tests.check.json +6 -0
  23. package/examples/source-has-tests.sample.json +4 -0
  24. package/examples/test-script-is-real.bad.json +6 -0
  25. package/examples/test-script-is-real.check.json +6 -0
  26. package/examples/test-script-is-real.sample.json +6 -0
  27. package/examples/validate-leaves-tree-clean.bad.json +6 -0
  28. package/examples/validate-leaves-tree-clean.check.json +7 -0
  29. package/examples/validate-leaves-tree-clean.sample.json +6 -0
  30. package/helpers/files.js +52 -2
  31. package/helpers/git.js +265 -2
  32. package/helpers/index.d.ts +114 -4
  33. package/helpers/node.js +192 -2
  34. package/helpers/plan.js +86 -2
  35. package/index.d.ts +22 -0
  36. package/lib/adapters/git.js +80 -4
  37. package/lib/helper.js +18 -1
  38. package/package.json +1 -1
package/helpers/plan.js CHANGED
@@ -3,7 +3,7 @@
3
3
  */
4
4
  "use strict";
5
5
 
6
- const { defineHelper, expect, note } = require("..");
6
+ const { defineHelper, expect, fail, note } = require("..");
7
7
  const { needHandoff } = require("./handoff");
8
8
 
9
9
  const hasSections = defineHelper({
@@ -52,4 +52,88 @@ const acceptanceEachHasTest = defineHelper({
52
52
  },
53
53
  });
54
54
 
55
- module.exports = { hasSections, acceptanceEachHasTest };
55
+ /**
56
+ * Whether to judge this handoff: only when its status is one of `when`
57
+ * (empty: always). Otherwise it notes "No plan (<status>)" and passes.
58
+ */
59
+ function judges(ctx, when) {
60
+ if (!when.length) return true;
61
+ const s = ctx.handoff && ctx.handoff.status;
62
+ if (when.includes(s)) return true;
63
+ note(`No plan (${s === undefined ? "no status" : s})`);
64
+ return false;
65
+ }
66
+
67
+ const NOT_READ = /not read|didn.t read|wasn.t read|unread/i;
68
+
69
+ const evidenceForAcceptance = defineHelper({
70
+ id: "plan.evidenceForAcceptance",
71
+ group: "Handoff",
72
+ label: "It checked the work isn't already done",
73
+ description: "Plan: it searched for finished work, and for each acceptance item says what it read and why it's still missing",
74
+ sentence: "handoff.{key} has a search and, for every item in handoff.{acceptanceKey}, what was read and why it's missing",
75
+ params: {
76
+ key: { type: "text", label: "Evidence key", default: "notYetDone", description: "Holds searchedDone and missing: [{ acceptance, read, why }]" },
77
+ acceptanceKey: { type: "text", label: "Acceptance key", default: "acceptance" },
78
+ requireSearch: { type: "boolean", label: "Needs a search", default: true, description: "The evidence must say what it searched for done work (searchedDone)" },
79
+ when: { type: "list", label: "Only when status is", default: ["ok"], description: "Other statuses pass; empty judges every handoff" },
80
+ },
81
+ reads: ["handoff"],
82
+ run(ctx, { key, acceptanceKey, requireSearch, when }) {
83
+ if (!needHandoff(ctx)) return;
84
+ if (!judges(ctx, when)) return;
85
+ const nd = ctx.get(`handoff.${key}`);
86
+ if (!nd || typeof nd !== "object" || Array.isArray(nd)) {
87
+ fail(
88
+ `No ${key}: before planning, ${requireSearch ? "search for done work like this (searchedDone) and, " : ""}for each ${acceptanceKey} item, read the code that would do it and say why it is still missing (missing)`
89
+ );
90
+ return;
91
+ }
92
+ if (requireSearch && !String(nd.searchedDone || "").trim()) {
93
+ fail(`${key}.searchedDone is empty: search for done tickets like this one and say what you searched and found`);
94
+ }
95
+ const acc = ctx.get(`handoff.${acceptanceKey}`);
96
+ const items = Array.isArray(acc) ? acc : [];
97
+ const miss = Array.isArray(nd.missing) ? nd.missing : [];
98
+ const lacking = items.filter(
99
+ (a) => !miss.some((m) => m && m.acceptance === a && String(m.read || "").trim() && String(m.why || "").trim())
100
+ );
101
+ if (lacking.length) {
102
+ fail(
103
+ `No evidence it is still missing for: ${lacking.join("; ")}. For each, name the file and function you read (read) and why it does not already do it (why).`
104
+ );
105
+ }
106
+ if (NOT_READ.test(JSON.stringify(nd))) fail(`${key} says some code was not read: read it before planning`);
107
+ note(`${requireSearch ? "Searched for done work, and evidence" : "Evidence"} for ${items.length} ${acceptanceKey} item${items.length === 1 ? "" : "s"}`);
108
+ },
109
+ });
110
+
111
+ const noOpenDecisions = defineHelper({
112
+ id: "plan.noOpenDecisions",
113
+ group: "Handoff",
114
+ label: "Nothing is left for the user to decide",
115
+ description: "Plan: it lists the decisions still open, and there are none",
116
+ sentence: "handoff.{key} is an empty list",
117
+ params: {
118
+ key: { type: "text", label: "Decisions key", default: "openDecisions" },
119
+ when: { type: "list", label: "Only when status is", default: ["ok"], description: "Other statuses pass; empty judges every handoff" },
120
+ },
121
+ reads: ["handoff"],
122
+ run(ctx, { key, when }) {
123
+ if (!needHandoff(ctx)) return;
124
+ if (!judges(ctx, when)) return;
125
+ const list = ctx.get(`handoff.${key}`);
126
+ if (!Array.isArray(list)) {
127
+ fail(`No ${key}: list every choice the ticket or your plan leaves open (approach, design, scope, work outside the repos), or [] if there are none`);
128
+ return;
129
+ }
130
+ if (list.length) {
131
+ const text = list.map((d) => (typeof d === "string" ? d : JSON.stringify(d))).join("; ");
132
+ fail(`The plan leaves decisions open: ${text}. Don't plan: answer status ask with the question for the user.`);
133
+ return;
134
+ }
135
+ note("No open decisions");
136
+ },
137
+ });
138
+
139
+ module.exports = { hasSections, acceptanceEachHasTest, evidenceForAcceptance, noOpenDecisions };
package/index.d.ts CHANGED
@@ -49,12 +49,34 @@ export interface Fs {
49
49
  list(globs: string | string[]): Promise<string[]>;
50
50
  }
51
51
 
52
+ /** A line added since a ref (ctx.git.addedLines). */
53
+ export interface AddedLine {
54
+ file: string;
55
+ /** Its line number in the file as it is now (1-based). */
56
+ line: number;
57
+ text: string;
58
+ }
59
+
60
+ /** A commit past a ref (ctx.git.commits). */
61
+ export interface Commit {
62
+ sha: string;
63
+ subject: string;
64
+ message: string;
65
+ parents: string[];
66
+ /** The files it changed; empty for a merge commit. */
67
+ files: string[];
68
+ }
69
+
52
70
  export interface Git {
53
71
  branch(): Promise<string>;
54
72
  uncommitted(): Promise<string[]>;
55
73
  isClean(): Promise<boolean>;
56
74
  commitsSince(ref: string): Promise<number>;
57
75
  changedFiles(ref: string): Promise<string[]>;
76
+ /** Lines added since where HEAD left ref: committed, uncommitted, and untracked files whole. Binary files left out. */
77
+ addedLines(ref: string): Promise<AddedLine[]>;
78
+ /** The commits in ref..HEAD, oldest first. */
79
+ commits(ref: string): Promise<Commit[]>;
58
80
  lastCommitMessage(): Promise<string>;
59
81
  remoteHas(branch: string, remote?: string): Promise<boolean>;
60
82
  defaultBranch(): Promise<string | null>;
@@ -4,6 +4,8 @@
4
4
  */
5
5
  "use strict";
6
6
 
7
+ const fs = require("fs");
8
+ const path = require("path");
7
9
  const { execArgs } = require("./run");
8
10
  const { DashCheckError } = require("../util");
9
11
 
@@ -30,6 +32,13 @@ function makeGit({ cwd, env }) {
30
32
  }
31
33
  };
32
34
  const lines = (s) => s.split("\n").map((l) => l.trim()).filter(Boolean);
35
+ const mergeBase = async (ref) => {
36
+ await needRef(ref);
37
+ return (await must(["merge-base", ref, "HEAD"], `Can't find where HEAD left ${ref}`)).trim();
38
+ };
39
+ const untrackedFiles = async () => lines(await must(["-c", "core.quotePath=false", "ls-files", "--others", "--exclude-standard"], "Can't list untracked files"));
40
+ // Plain diff output whatever the user's git config says.
41
+ const DIFF = ["-c", "core.quotePath=false", "diff", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/"];
33
42
 
34
43
  const api = {
35
44
  /** The current branch ("HEAD" when detached). */
@@ -51,12 +60,79 @@ function makeGit({ cwd, env }) {
51
60
  * plus uncommitted and untracked ones. Sorted, relative.
52
61
  */
53
62
  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"));
63
+ const base = await mergeBase(ref);
64
+ const changed = lines(await must(["-c", "core.quotePath=false", "diff", "--name-only", base], `Can't diff against ${ref}`));
65
+ const untracked = await untrackedFiles();
58
66
  return [...new Set([...changed, ...untracked])].sort();
59
67
  },
68
+ /**
69
+ * Lines added since a ref, the same files as changedFiles: committed
70
+ * since where the branch left it, uncommitted, and untracked files
71
+ * read whole. [{ file, line, text }], line numbers in the file as it is
72
+ * now. Binary files are left out.
73
+ */
74
+ addedLines: async (ref) => {
75
+ const base = await mergeBase(ref);
76
+ const out = [];
77
+ let file = null;
78
+ let header = false;
79
+ let n = 0;
80
+ for (const l of (await must([...DIFF, "-U0", base], `Can't diff against ${ref}`)).split("\n")) {
81
+ if (l.startsWith("diff --git ")) {
82
+ file = null;
83
+ header = true;
84
+ } else if (header && l.startsWith("+++ ")) {
85
+ const p = l.slice(4);
86
+ file = p === "/dev/null" ? null : p.replace(/^"?b\//, "").replace(/"$/, "");
87
+ } else if (l.startsWith("@@")) {
88
+ header = false;
89
+ const m = l.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
90
+ n = m ? Number(m[1]) : 0;
91
+ } else if (!header && file && l.startsWith("+")) {
92
+ out.push({ file, line: n, text: l.slice(1) });
93
+ n++;
94
+ }
95
+ }
96
+ for (const f of await untrackedFiles()) {
97
+ let buf;
98
+ try {
99
+ buf = fs.readFileSync(path.join(cwd, f));
100
+ } catch (_e) {
101
+ continue;
102
+ }
103
+ if (buf.includes(0)) continue;
104
+ const text = buf.toString("utf8").split(/\r?\n/);
105
+ if (text.length && text[text.length - 1] === "") text.pop();
106
+ text.forEach((t, i) => out.push({ file: f, line: i + 1, text: t }));
107
+ }
108
+ return out;
109
+ },
110
+ /**
111
+ * The commits HEAD has past a ref, oldest first:
112
+ * [{ sha, subject, message, parents, files }]. A merge commit's files
113
+ * are empty (git log names none for it).
114
+ */
115
+ commits: async (ref) => {
116
+ await needRef(ref);
117
+ const raw = await must(
118
+ ["-c", "core.quotePath=false", "log", "--reverse", "--name-only", "--no-renames", "--format=%x1e%H%x1f%P%x1f%B%x1f", `${ref}..HEAD`],
119
+ `Can't list the commits past ${ref}`,
120
+ );
121
+ return raw
122
+ .split("\x1e")
123
+ .filter((c) => c.trim())
124
+ .map((c) => {
125
+ const [sha, parents, message, names = ""] = c.split("\x1f");
126
+ const msg = message.trim();
127
+ return {
128
+ sha: sha.trim(),
129
+ subject: msg.split("\n")[0],
130
+ message: msg,
131
+ parents: parents.trim().split(/\s+/).filter(Boolean),
132
+ files: lines(names),
133
+ };
134
+ });
135
+ },
60
136
  lastCommitMessage: async () => (await must(["log", "-1", "--format=%B"], "Can't read the last commit")).trim(),
61
137
  /** Does the remote (origin) have this branch? */
62
138
  remoteHas: async (branch, remote = "origin") => {
package/lib/helper.js CHANGED
@@ -49,6 +49,23 @@ function normParams(id, params) {
49
49
  return out;
50
50
  }
51
51
 
52
+ /** "a, b" → ["a", "b"], leaving commas in a glob's {a,b} alone. */
53
+ function splitList(s) {
54
+ const out = [];
55
+ let depth = 0;
56
+ let cur = "";
57
+ for (const c of s) {
58
+ if (c === "{") depth++;
59
+ else if (c === "}" && depth > 0) depth--;
60
+ if (c === "," && depth === 0) {
61
+ out.push(cur);
62
+ cur = "";
63
+ } else cur += c;
64
+ }
65
+ out.push(cur);
66
+ return out;
67
+ }
68
+
52
69
  /** A param's value, converted to its type, or throws saying what's wrong. */
53
70
  function coerce(id, name, p, v) {
54
71
  const bad = (what) => new DashCheckError(`${id}: ${p.label} (${name}) ${what}`, { fix: `got ${fmt(v)}` });
@@ -71,7 +88,7 @@ function coerce(id, name, p, v) {
71
88
  if (!p.options.map(String).includes(String(v))) throw bad(`must be one of ${p.options.join(", ")}`);
72
89
  return p.options.find((o) => String(o) === String(v));
73
90
  case "list": {
74
- const list = Array.isArray(v) ? v : String(v).split(",");
91
+ const list = Array.isArray(v) ? v : splitList(String(v));
75
92
  return list.map((x) => (typeof x === "string" ? x.trim() : x)).filter((x) => x !== "" && x !== undefined && x !== null);
76
93
  }
77
94
  case "regex":
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trops/dash-check",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Compose deterministic checks from small, described building blocks: Jest-style files, JSON recipes and helpers. Runs in Dash, in CI and on a laptop.",
5
5
  "license": "MIT",
6
6
  "author": "trops",