@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
package/index.d.ts ADDED
@@ -0,0 +1,347 @@
1
+ // Types for @trops/dash-check (Layer 0: the runner, expect, the context, defineHelper).
2
+
3
+ /** One thing that went wrong, said so it can be fixed. */
4
+ export interface Failure {
5
+ message: string;
6
+ /** Where (a file:line, a list of names), shown after the message. */
7
+ at?: string;
8
+ expected?: unknown;
9
+ received?: unknown;
10
+ matcher?: string;
11
+ label?: string;
12
+ /** It was a thrown error, not an expectation. */
13
+ error?: boolean;
14
+ /** The helper's own text, when a step's `message` replaced it. */
15
+ original?: string;
16
+ }
17
+
18
+ export interface CheckResult {
19
+ name: string;
20
+ pass: boolean;
21
+ skipped?: boolean;
22
+ reason: string;
23
+ failures: Failure[];
24
+ ms?: number;
25
+ }
26
+
27
+ export interface RunResult {
28
+ pass: boolean;
29
+ reason: string;
30
+ checks: CheckResult[];
31
+ }
32
+
33
+ // ---- the context ----------------------------------------------------------
34
+
35
+ export interface RunOutput {
36
+ code: number;
37
+ stdout: string;
38
+ stderr: string;
39
+ timedOut: boolean;
40
+ }
41
+
42
+ export interface Fs {
43
+ path(p: string): string;
44
+ exists(p: string): Promise<boolean>;
45
+ dirExists(p?: string): Promise<boolean>;
46
+ read(p: string): Promise<string>;
47
+ readJson<T = any>(p: string): Promise<T>;
48
+ /** Files matching a glob (or globs; "!glob" leaves out), relative and sorted. */
49
+ list(globs: string | string[]): Promise<string[]>;
50
+ }
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
+
70
+ export interface Git {
71
+ branch(): Promise<string>;
72
+ uncommitted(): Promise<string[]>;
73
+ isClean(): Promise<boolean>;
74
+ commitsSince(ref: string): Promise<number>;
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[]>;
80
+ lastCommitMessage(): Promise<string>;
81
+ remoteHas(branch: string, remote?: string): Promise<boolean>;
82
+ defaultBranch(): Promise<string | null>;
83
+ fileAt(ref: string, path: string): Promise<string | null>;
84
+ hasRef(ref: string): Promise<boolean>;
85
+ }
86
+
87
+ export interface CheckRun {
88
+ name: string;
89
+ status: string;
90
+ conclusion: string | null;
91
+ url: string | null;
92
+ }
93
+
94
+ export interface WaitResult {
95
+ runs: CheckRun[];
96
+ failed: CheckRun[];
97
+ pending: CheckRun[];
98
+ passed: CheckRun[];
99
+ noChecks: boolean;
100
+ timedOut: boolean;
101
+ waitedSec: number;
102
+ }
103
+
104
+ export interface GitHub {
105
+ pr(urlOrNumber: string | number, opts?: { repo?: string }): Promise<any & { slug: string }>;
106
+ checksFor(sha: string, opts?: { repo?: string }): Promise<{ runs: CheckRun[]; source: "check-runs" | "actions" }>;
107
+ waitForChecks(sha: string, opts?: { timeoutSec?: number; noChecksAfterSec?: number; pollSec?: number; repo?: string }): Promise<WaitResult>;
108
+ }
109
+
110
+ export interface Workspace {
111
+ dir: string;
112
+ branch?: string;
113
+ file(p: string): string;
114
+ exists(p: string): Promise<boolean>;
115
+ read(p: string): Promise<string>;
116
+ dirExists(): Promise<boolean>;
117
+ [key: string]: any;
118
+ }
119
+
120
+ export interface Context {
121
+ /** The raw check input (Dash's $DASH_INPUT). */
122
+ input: Record<string, any>;
123
+ /** The bot's whole answer. */
124
+ answer: string;
125
+ /** The answer's last json block, parsed; {} when there's none. */
126
+ handoff: Record<string, any>;
127
+ handoffInfo: { found: boolean; broken?: boolean; error?: string; list?: boolean; given?: boolean };
128
+ item: Record<string, any>;
129
+ picks: Record<string, any>;
130
+ row: Record<string, any>;
131
+ settings: Record<string, any>;
132
+ step: Record<string, any>;
133
+ job: Record<string, any>;
134
+ workspace: Workspace;
135
+ env: Record<string, string | undefined>;
136
+ /** Where fs, run and git work. */
137
+ cwd: string;
138
+ fs: Fs;
139
+ run(cmd: string, opts?: { timeoutSec?: number; env?: Record<string, string>; cwd?: string }): Promise<RunOutput>;
140
+ git: Git;
141
+ github: GitHub;
142
+ /** A read-only provider call; only Dash can answer it (DASH_TOOL_SOCKET). */
143
+ tool(provider: string, name: string, args?: Record<string, any>): Promise<any>;
144
+ /** A value by path: "handoff.files", "repo.baseBranch". */
145
+ get(path: string): any;
146
+ /** Fill "{placeholders}" from the context. */
147
+ fill<T = any>(value: T, opts?: FillOptions): any;
148
+ /** Is a `when` true? A path or a {placeholder}; "!" turns it around. */
149
+ when(expr: string | boolean | undefined): boolean;
150
+ /** Say how the running check passed. */
151
+ note(text: string): void;
152
+ }
153
+
154
+ export interface ContextOptions {
155
+ cwd?: string;
156
+ env?: Record<string, string | undefined>;
157
+ fetch?: (url: string, init?: any) => Promise<{ status: number; json(): Promise<any> }>;
158
+ tool?: (provider: string, name: string, args: Record<string, any>) => any;
159
+ now?: () => number;
160
+ sleep?: (ms: number) => Promise<void>;
161
+ }
162
+
163
+ export interface FillOptions {
164
+ /** What a placeholder with no value does: throw (default), become empty, or stay as is. */
165
+ missing?: "throw" | "empty" | "keep";
166
+ }
167
+
168
+ export function createContext(input?: Record<string, any>, opts?: ContextOptions): Context;
169
+
170
+ // ---- the runner -----------------------------------------------------------
171
+
172
+ export type CheckFn = (ctx: Context) => unknown | Promise<unknown>;
173
+
174
+ export interface CheckApi {
175
+ (name: string, fn: CheckFn): void;
176
+ skip(name: string, fn?: CheckFn): void;
177
+ only(name: string, fn: CheckFn): void;
178
+ }
179
+ export const check: CheckApi;
180
+ export function describe(name: string, fn: () => void): void;
181
+
182
+ export interface DefinedCheck {
183
+ name: string;
184
+ fn: CheckFn;
185
+ mode: null | "skip" | "only";
186
+ }
187
+
188
+ /** Run the checks defined so far. Default input: $DASH_INPUT. */
189
+ export function run(input?: Record<string, any>, opts?: ContextOptions & { ctx?: Context; filter?: (name: string) => boolean }): Promise<RunResult>;
190
+ export function runChecks(checks: DefinedCheck[], ctx: Context, opts?: { filter?: (name: string) => boolean }): Promise<RunResult>;
191
+ export function loadChecks(file: string): DefinedCheck[];
192
+ export function takeChecks(): DefinedCheck[];
193
+ /** Run a .check.js or .check.json file in this process. */
194
+ export function runFile(file: string, input?: Record<string, any>, opts?: ContextOptions & { ctx?: Context }): Promise<RunResult>;
195
+ /** {"reason", "details"}: Dash's check contract, one line. */
196
+ export function lastLine(result: RunResult): string;
197
+ export function report(result: RunResult, opts?: { title?: string; color?: boolean }): string;
198
+
199
+ // ---- expect ---------------------------------------------------------------
200
+
201
+ /** Each matcher returns whether it passed; its last argument is the failure's message. */
202
+ export interface Matchers<R = boolean> {
203
+ toBe(expected: unknown, message?: string): R;
204
+ toEqual(expected: unknown, message?: string): R;
205
+ toBeDefined(message?: string): R;
206
+ toBeTruthy(message?: string): R;
207
+ toBeArray(message?: string): R;
208
+ toBeString(message?: string): R;
209
+ toBeNonEmptyString(message?: string): R;
210
+ toBeNumber(message?: string): R;
211
+ toBeEmpty(message?: string): R;
212
+ toHaveLength(n: number, message?: string): R;
213
+ toHaveLengthAtLeast(n: number, message?: string): R;
214
+ toContain(item: unknown, message?: string): R;
215
+ toBeOneOf(options: unknown[], message?: string): R;
216
+ toHaveKeys(keys: string[], message?: string): R;
217
+ toMatch(pattern: RegExp | string, message?: string): R;
218
+ toBeGreaterThan(n: number, message?: string): R;
219
+ toBeLessThan(n: number, message?: string): R;
220
+ [custom: string]: any;
221
+ }
222
+
223
+ export interface Expectation extends Matchers<boolean> {
224
+ not: Matchers<boolean>;
225
+ resolves: Matchers<Promise<boolean>> & { not: Matchers<Promise<boolean>> };
226
+ rejects: Matchers<Promise<boolean>> & { not: Matchers<Promise<boolean>> };
227
+ }
228
+
229
+ export interface MatcherParam {
230
+ name: string;
231
+ type: string;
232
+ label: string;
233
+ }
234
+
235
+ export interface MatcherMeta {
236
+ id: string;
237
+ label: string;
238
+ sentence: string;
239
+ notSentence: string;
240
+ params: MatcherParam[];
241
+ description: string;
242
+ }
243
+
244
+ export interface MatcherDef {
245
+ id: string;
246
+ label?: string;
247
+ sentence: string;
248
+ notSentence?: string;
249
+ params?: Array<{ name: string; type?: string; label?: string }>;
250
+ description?: string;
251
+ test(received: any, ...args: any[]): boolean | { pass: boolean; got?: string };
252
+ }
253
+
254
+ export interface ExpectFn {
255
+ (value: unknown, label?: string): Expectation;
256
+ matchers(): MatcherMeta[];
257
+ extend(defs: MatcherDef | MatcherDef[]): MatcherMeta[];
258
+ has(id: string): boolean;
259
+ meta(id: string): MatcherMeta | null;
260
+ sentence(id: string, label: string, args?: unknown[], not?: boolean): string | null;
261
+ }
262
+ export const expect: ExpectFn;
263
+ export function defineMatcher(def: MatcherDef): MatcherMeta;
264
+
265
+ /** Fail the running check with a message (the fix), going on with the rest. */
266
+ export function fail(message: string, extra?: { at?: string; expected?: unknown; received?: unknown }): false;
267
+ /** Say how the running check passed. */
268
+ export function note(text: string): void;
269
+ /** Run fn with its own failure list. Never throws. */
270
+ export function collect(fn: () => unknown): Promise<{ failures: Failure[]; notes: string[] }>;
271
+
272
+ export class CheckFailure extends Error {
273
+ failures: Failure[];
274
+ }
275
+ export class DashCheckError extends Error {
276
+ fix?: string;
277
+ code?: number;
278
+ }
279
+
280
+ // ---- helpers --------------------------------------------------------------
281
+
282
+ export type ParamType = "text" | "number" | "boolean" | "select" | "path" | "glob" | "regex" | "list";
283
+
284
+ export interface ParamDef {
285
+ type?: ParamType;
286
+ label?: string;
287
+ description?: string;
288
+ default?: unknown;
289
+ required?: boolean;
290
+ options?: Array<string | number>;
291
+ placeholder?: string;
292
+ }
293
+
294
+ export interface HelperMeta {
295
+ id: string;
296
+ group: string;
297
+ label: string;
298
+ description: string;
299
+ sentence: string;
300
+ params: Record<string, ParamDef & { type: ParamType; label: string }>;
301
+ reads: string[];
302
+ source?: string;
303
+ }
304
+
305
+ export interface HelperDef<P = Record<string, any>> {
306
+ /** "group.name", e.g. "team.changelogUpdated". */
307
+ id: string;
308
+ group?: string;
309
+ label: string;
310
+ description?: string;
311
+ /** "at least {min} commit(s) past {base}" */
312
+ sentence?: string;
313
+ params?: Record<string, ParamDef>;
314
+ /** What it reads: git, fs, run, github, tool, handoff… */
315
+ reads?: string[];
316
+ run(ctx: Context, params: P): unknown | Promise<unknown>;
317
+ }
318
+
319
+ export interface Helper<P = Record<string, any>> {
320
+ (ctx: Context, params?: Partial<P> & { message?: string }): Promise<boolean>;
321
+ meta: HelperMeta;
322
+ isDashCheckHelper: true;
323
+ }
324
+
325
+ export function defineHelper<P = Record<string, any>>(def: HelperDef<P>): Helper<P>;
326
+ /** A registered helper by id, to call from code (a repo's own are found from ctx.cwd). */
327
+ export function helper(id: string): (ctx: Context, params?: Record<string, any>) => Promise<boolean>;
328
+ export function getHelper(id: string): Helper | null;
329
+ export function listHelpers(): HelperMeta[];
330
+ export function registerHelpers(helpers: Helper | Helper[], opts?: { source?: string; replace?: boolean }): Helper[];
331
+ /** Find a repo's own helpers: .dash/checks/helpers/*.js and packages with "dashCheck": { "helpers": [...] }. */
332
+ export function loadHelpers(opts?: { cwd?: string }): { helpers: Array<{ id: string; source: string }>; errors: Array<{ source: string; error: string }> };
333
+ export function sentenceOf(meta: HelperMeta, params?: Record<string, any>): string;
334
+ export function resolveParams(meta: HelperMeta, ctx: Context | null, params?: Record<string, any>): Record<string, any>;
335
+
336
+ // ---- small tools ----------------------------------------------------------
337
+
338
+ export function readHandoff(input: Record<string, any>): { handoff: Record<string, any>; info: Context["handoffInfo"] };
339
+ export function lastJsonBlock(text: string): { found: boolean; value?: any; fenced?: boolean; broken?: boolean; error?: string };
340
+ export function get(ctx: Context, path: string): any;
341
+ export function fill(ctx: Context, value: unknown, opts?: FillOptions): any;
342
+ export function when(ctx: Context, expr: string | boolean | undefined): boolean;
343
+ export function valuePaths(ctx: Context, opts?: { maxDepth?: number; max?: number }): Array<{ path: string; type: string; sample?: unknown }>;
344
+ export function matchGlob(globs: string | string[], path: string): boolean;
345
+ export function globToRegExp(glob: string): RegExp;
346
+ export function isEmpty(value: unknown): boolean;
347
+ export function deepEqual(a: unknown, b: unknown): boolean;
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,163 @@
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 fs = require("fs");
8
+ const path = require("path");
9
+ const { execArgs } = require("./run");
10
+ const { DashCheckError } = require("../util");
11
+
12
+ function makeGit({ cwd, env }) {
13
+ const g = (args) => execArgs("git", args, { cwd, env });
14
+ const must = async (args, what, fix) => {
15
+ const r = await g(args);
16
+ if (!r.ok) {
17
+ if (/not a git repository/i.test(r.err)) {
18
+ throw new DashCheckError(`${cwd} isn't a git repo`, { fix: "run the check in the repo's folder" });
19
+ }
20
+ throw new DashCheckError(`${what} (${r.err.split("\n")[0] || `git exit ${r.code}`})`, { fix });
21
+ }
22
+ return r.out;
23
+ };
24
+ const verify = async (ref) => (await g(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`])).ok;
25
+ const needRef = async (ref) => {
26
+ if (!ref || typeof ref !== "string") throw new DashCheckError("No git ref given", { fix: "name a branch, e.g. origin/main" });
27
+ if (!(await verify(ref))) {
28
+ const remote = ref.startsWith("origin/") ? ref.slice(7) : null;
29
+ throw new DashCheckError(`${ref} isn't there`, {
30
+ fix: remote ? `fetch it (git fetch origin ${remote}), or check the base branch's name` : "check the branch's name",
31
+ });
32
+ }
33
+ };
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/"];
42
+
43
+ const api = {
44
+ /** The current branch ("HEAD" when detached). */
45
+ branch: async () => (await must(["rev-parse", "--abbrev-ref", "HEAD"], "Can't read the branch")).trim(),
46
+ /** Uncommitted files (staged, unstaged and untracked). */
47
+ uncommitted: async () =>
48
+ (await must(["status", "--porcelain"], "Can't read git status"))
49
+ .split("\n")
50
+ .filter(Boolean)
51
+ .map((l) => l.slice(3).replace(/^"|"$/g, "")),
52
+ isClean: async () => (await api.uncommitted()).length === 0,
53
+ /** How many commits HEAD has past a ref (rev-list ref..HEAD). */
54
+ commitsSince: async (ref) => {
55
+ await needRef(ref);
56
+ return Number((await must(["rev-list", "--count", `${ref}..HEAD`], `Can't count commits past ${ref}`)).trim()) || 0;
57
+ },
58
+ /**
59
+ * Files changed since a ref: committed since where the branch left it,
60
+ * plus uncommitted and untracked ones. Sorted, relative.
61
+ */
62
+ changedFiles: async (ref) => {
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();
66
+ return [...new Set([...changed, ...untracked])].sort();
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
+ },
136
+ lastCommitMessage: async () => (await must(["log", "-1", "--format=%B"], "Can't read the last commit")).trim(),
137
+ /** Does the remote (origin) have this branch? */
138
+ remoteHas: async (branch, remote = "origin") => {
139
+ const r = await g(["ls-remote", "--exit-code", "--heads", remote, String(branch)]);
140
+ if (r.ok) return true;
141
+ if (r.code === 2) return false;
142
+ throw new DashCheckError(`Can't reach ${remote} (${r.err.split("\n")[0]})`, { fix: "check the remote and the sign-in" });
143
+ },
144
+ /** The default branch's name: origin/HEAD's, else main or master. null when none. */
145
+ defaultBranch: async () => {
146
+ const head = await g(["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"]);
147
+ if (head.ok && head.out.trim()) return head.out.trim().replace(/^refs\/remotes\/origin\//, "");
148
+ for (const b of ["main", "master"]) if (await verify(`origin/${b}`)) return b;
149
+ for (const b of ["main", "master"]) if (await verify(b)) return b;
150
+ return null;
151
+ },
152
+ /** A file's text at a ref, or null when it isn't there. */
153
+ fileAt: async (ref, p) => {
154
+ const r = await g(["show", `${ref}:${String(p).replace(/^\.\//, "")}`]);
155
+ return r.ok ? r.out : null;
156
+ },
157
+ /** Does a ref exist? */
158
+ hasRef: verify,
159
+ };
160
+ return api;
161
+ }
162
+
163
+ module.exports = { makeGit };