@maniumek/suwgate 0.2.0 → 0.4.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 (62) hide show
  1. package/README.md +132 -24
  2. package/dist/cli.js +49 -5
  3. package/dist/dev/db.d.ts +1 -1
  4. package/dist/dev/db.js +25 -0
  5. package/dist/dev/logs.js +9 -1
  6. package/dist/dev/settings.d.ts +2 -0
  7. package/dist/dev/settings.js +5 -2
  8. package/dist/eslint/index.js +4 -1
  9. package/dist/gate/check.d.ts +10 -0
  10. package/dist/gate/check.js +94 -18
  11. package/dist/gate/config.d.ts +19 -1
  12. package/dist/gate/config.js +119 -4
  13. package/dist/gate/contract.d.ts +13 -0
  14. package/dist/gate/guardsStep.d.ts +3 -1
  15. package/dist/gate/guardsStep.js +14 -3
  16. package/dist/gate/plan.d.ts +20 -1
  17. package/dist/gate/plan.js +92 -20
  18. package/dist/gate/report.d.ts +1 -0
  19. package/dist/gate/report.js +12 -3
  20. package/dist/gate/repository.d.ts +1 -0
  21. package/dist/gate/repository.js +8 -0
  22. package/dist/gate/runner.js +18 -3
  23. package/dist/guards/comments/hash.js +22 -1
  24. package/dist/guards/dotnet/appsettingsBound.js +29 -2
  25. package/dist/guards/dotnet/index.js +2 -1
  26. package/dist/guards/dotnet/suwbackkitWiring.d.ts +2 -0
  27. package/dist/guards/dotnet/suwbackkitWiring.js +31 -0
  28. package/dist/guards/repository/imagePins.js +1 -1
  29. package/dist/guards/repository/index.js +2 -0
  30. package/dist/guards/repository/justModules.js +28 -10
  31. package/dist/guards/repository/noRawColors.js +1 -1
  32. package/dist/guards/repository/scriptsCalled.js +38 -11
  33. package/dist/guards/repository/suwfrontkitWiring.d.ts +2 -0
  34. package/dist/guards/repository/suwfrontkitWiring.js +52 -0
  35. package/dist/profiles/contract.js +81 -38
  36. package/dist/profiles/criteria.d.ts +1 -0
  37. package/dist/profiles/criteria.js +1 -1
  38. package/dist/profiles/criteriaRan.d.ts +22 -0
  39. package/dist/profiles/criteriaRan.js +152 -0
  40. package/dist/profiles/database.js +11 -4
  41. package/dist/profiles/dotnet.d.ts +2 -0
  42. package/dist/profiles/dotnet.js +39 -6
  43. package/dist/profiles/dotnetGuards.d.ts +3 -0
  44. package/dist/profiles/dotnetGuards.js +54 -0
  45. package/dist/profiles/everyRepository.js +2 -0
  46. package/dist/profiles/index.d.ts +2 -0
  47. package/dist/profiles/index.js +2 -0
  48. package/dist/profiles/library.js +12 -7
  49. package/dist/profiles/node.js +21 -7
  50. package/dist/profiles/presets/knip.d.ts +1 -0
  51. package/dist/profiles/presets/knip.js +4 -2
  52. package/dist/profiles/presets/playwright.d.ts +3 -1
  53. package/dist/profiles/presets/playwright.js +7 -1
  54. package/dist/profiles/reports.d.ts +35 -0
  55. package/dist/profiles/reports.js +60 -0
  56. package/dist/profiles/shell.d.ts +6 -0
  57. package/dist/profiles/shell.js +39 -4
  58. package/dist/profiles/verdict.d.ts +9 -0
  59. package/dist/profiles/verdict.js +124 -0
  60. package/dist/profiles/web.js +25 -6
  61. package/package.json +2 -2
  62. package/schema/suwgate.schema.json +82 -4
@@ -1,5 +1,6 @@
1
- import { type Guard, type GuardException, type Profile, type Step } from "./contract.ts";
1
+ import { type DotnetGuard, type Guard, type GuardException, type Profile, type Step } from "./contract.ts";
2
2
  export declare const CONFIG_FILE = "suwgate.yml";
3
+ export declare const MAX_ALIASES = 10000;
3
4
  interface AddedStep {
4
5
  name: string;
5
6
  run: string;
@@ -12,17 +13,34 @@ interface SkippedStep {
12
13
  step: string;
13
14
  reason: string;
14
15
  }
16
+ interface SkippedGuard {
17
+ guard: string;
18
+ reason: string;
19
+ }
20
+ export interface Environment {
21
+ env?: Record<string, string>;
22
+ unset?: string[];
23
+ }
24
+ interface ConfiguredStep extends Environment {
25
+ limitSeconds?: number;
26
+ after?: string[];
27
+ settings?: unknown;
28
+ }
15
29
  export interface Config {
16
30
  profiles: Profile[];
17
31
  directories: Partial<Record<Profile, string>>;
18
32
  add: AddedStep[];
19
33
  skip: SkippedStep[];
34
+ configure: Record<string, ConfiguredStep>;
35
+ environment: Environment;
36
+ skippedGuards: SkippedGuard[];
20
37
  exceptions: GuardException[];
21
38
  settings: Record<string, unknown>;
22
39
  quickLimitSeconds?: number;
23
40
  }
24
41
  export interface Catalog {
25
42
  guards: readonly Guard[];
43
+ dotnetGuards: readonly DotnetGuard[];
26
44
  stepsFor(profiles: readonly Profile[]): readonly Step[];
27
45
  }
28
46
  export type Loaded = {
@@ -5,6 +5,7 @@ import { isNode, LineCounter, parseDocument } from "yaml";
5
5
  import { PROFILES } from "./contract.js";
6
6
  export const CONFIG_FILE = "suwgate.yml";
7
7
  const SCHEMA_FILE = new URL("../../schema/suwgate.schema.json", import.meta.url);
8
+ export const MAX_ALIASES = 10_000;
8
9
  const DOTNET_GUARD_PREFIXES = { "architecture/": "dotnet", "database/": "database" };
9
10
  const ajv = new Ajv2020({ allErrors: true, strict: true });
10
11
  const validateFile = ajv.compile(JSON.parse(readFileSync(SCHEMA_FILE, "utf8")));
@@ -35,7 +36,8 @@ function describe(error) {
35
36
  switch (error.keyword) {
36
37
  case "required": {
37
38
  const missing = String(params["missingProperty"]);
38
- const fix = missing === "reason" ? `: every ${parts[0] === "exceptions" ? "exception" : "skipped step"} says why (reason: <why>)` : "";
39
+ const what = parts[0] === "exceptions" ? "exception" : parts[0] === "guards" ? "skipped guard" : "skipped step";
40
+ const fix = missing === "reason" ? `: every ${what} says why (reason: <why>)` : "";
39
41
  return `${where} has no "${missing}"${fix}`;
40
42
  }
41
43
  case "additionalProperties":
@@ -69,6 +71,9 @@ function checkExceptions(raw, catalog, problem) {
69
71
  problem(where, `no guard "${exception.guard}": the guards are ${catalog.guards.map((guard) => guard.id).join(", ")} (and architecture/*, database/* of the .NET packages)`);
70
72
  }
71
73
  else if (profiles === "dotnet-guard") {
74
+ if (exception.message !== undefined || exception.once !== undefined) {
75
+ problem(where, `"${exception.guard}" is a .NET guard, and the .NET packages match an exception by its target only: delete message and once`);
76
+ }
72
77
  const prefix = Object.keys(DOTNET_GUARD_PREFIXES).find((candidate) => exception.guard.startsWith(candidate)) ?? "";
73
78
  const needed = DOTNET_GUARD_PREFIXES[prefix];
74
79
  if (needed !== undefined && !raw.profiles.includes(needed)) {
@@ -78,7 +83,7 @@ function checkExceptions(raw, catalog, problem) {
78
83
  else if (profiles !== "every" && !profiles.some((profile) => raw.profiles.includes(profile))) {
79
84
  problem(where, `"${exception.guard}" runs only for ${profiles.join(", ")}, which this repository does not have: delete the exception`);
80
85
  }
81
- const key = `${exception.guard}\u0000${exception.target}`;
86
+ const key = `${exception.guard}\u0000${exception.target}\u0000${exception.message ?? ""}`;
82
87
  if (seen.has(key))
83
88
  problem(where, `the same exception (${exception.guard}, ${exception.target}) is listed twice: keep one`);
84
89
  seen.add(key);
@@ -104,9 +109,100 @@ function checkSteps(raw, catalog, problem) {
104
109
  }
105
110
  });
106
111
  }
112
+ function checkConfigure(raw, catalog, problem) {
113
+ const steps = catalog.stepsFor(raw.profiles);
114
+ const known = steps.map((step) => step.id);
115
+ const added = (raw.steps?.add ?? []).map((step) => step.name);
116
+ const skipped = (raw.steps?.skip ?? []).map((entry) => entry.step);
117
+ for (const [id, configured] of Object.entries(raw.steps?.configure ?? {})) {
118
+ const where = ["steps", "configure", id];
119
+ const step = steps.find((candidate) => candidate.id === id);
120
+ if (step === undefined) {
121
+ problem(where, added.includes(id)
122
+ ? `"${id}" is added in steps.add, which takes its limitSeconds and after itself; steps.configure is for the steps of the profiles`
123
+ : `the profiles ${raw.profiles.join(", ")} have no step "${id}": their steps are ${known.join(", ")}`);
124
+ continue;
125
+ }
126
+ if (skipped.includes(id))
127
+ problem(where, `"${id}" is skipped in steps.skip, so this configuration is never used: delete it, or the skip`);
128
+ (configured.after ?? []).forEach((after, at) => {
129
+ if (after === id)
130
+ problem([...where, "after", at], `"${id}" cannot wait for itself`);
131
+ else if (!known.includes(after) && !added.includes(after))
132
+ problem([...where, "after", at], `no step "${after}": the steps are ${[...known, ...added].join(", ")}`);
133
+ });
134
+ if (configured.settings === undefined)
135
+ continue;
136
+ if (step.settingsSchema === undefined) {
137
+ problem([...where, "settings"], `the step "${id}" takes no settings`);
138
+ continue;
139
+ }
140
+ const validate = ajv.compile(step.settingsSchema);
141
+ if (!validate(configured.settings)) {
142
+ for (const error of relevant(validate.errors ?? [])) {
143
+ problem([...where, "settings", ...segments(error.instancePath)], describe({ ...error, instancePath: `/steps/configure/${id}/settings${error.instancePath}` }));
144
+ }
145
+ }
146
+ }
147
+ }
148
+ function circle(raw, catalog) {
149
+ const waits = new Map();
150
+ for (const step of catalog.stepsFor(raw.profiles)) {
151
+ waits.set(step.id, [...(step.after ?? []), ...(step.orderAfter ?? []), ...(raw.steps?.configure?.[step.id]?.after ?? [])]);
152
+ }
153
+ for (const step of raw.steps?.add ?? [])
154
+ waits.set(step.name, step.after ?? []);
155
+ const done = new Set();
156
+ const visit = (id, path) => {
157
+ if (path.includes(id))
158
+ return [...path.slice(path.indexOf(id)), id];
159
+ if (done.has(id))
160
+ return null;
161
+ for (const next of waits.get(id) ?? []) {
162
+ const found = visit(next, [...path, id]);
163
+ if (found !== null)
164
+ return found;
165
+ }
166
+ done.add(id);
167
+ return null;
168
+ };
169
+ for (const id of waits.keys()) {
170
+ const found = visit(id, []);
171
+ if (found !== null)
172
+ return found;
173
+ }
174
+ return null;
175
+ }
176
+ function profilesOf(id, catalog) {
177
+ const dotnet = catalog.dotnetGuards.find((guard) => guard.id === id);
178
+ if (dotnet !== undefined)
179
+ return [dotnet.profile];
180
+ return catalog.guards.find((guard) => guard.id === id)?.profiles ?? null;
181
+ }
182
+ function checkSkippedGuards(raw, catalog, problem) {
183
+ const skipped = (raw.guards?.skip ?? []).map((entry) => entry.guard);
184
+ (raw.guards?.skip ?? []).forEach((entry, index) => {
185
+ const where = ["guards", "skip", index, "guard"];
186
+ const profiles = profilesOf(entry.guard, catalog);
187
+ if (profiles === null) {
188
+ const known = [...catalog.guards.map((guard) => guard.id), ...catalog.dotnetGuards.map((guard) => guard.id)];
189
+ problem(where, `no guard "${entry.guard}": the guards are ${known.join(", ")}`);
190
+ }
191
+ else if (profiles !== "every" && !profiles.some((profile) => raw.profiles.includes(profile))) {
192
+ problem(where, `"${entry.guard}" runs only for ${profiles.join(", ")}, which this repository does not have: delete the entry`);
193
+ }
194
+ if (skipped.indexOf(entry.guard) !== index)
195
+ problem(where, `"${entry.guard}" is skipped twice: keep one entry`);
196
+ });
197
+ (raw.exceptions ?? []).forEach((exception, index) => {
198
+ if (skipped.includes(exception.guard)) {
199
+ problem(["exceptions", index], `"${exception.guard}" is skipped in guards.skip, so this exception is never checked: delete it, or the skip`);
200
+ }
201
+ });
202
+ }
107
203
  function checkSettings(raw, catalog, problem) {
108
204
  for (const [id, value] of Object.entries(raw.settings ?? {})) {
109
- const guard = catalog.guards.find((candidate) => candidate.id === id);
205
+ const guard = catalog.guards.find((candidate) => candidate.id === id) ?? catalog.dotnetGuards.find((candidate) => candidate.id === id);
110
206
  if (guard?.settingsSchema === undefined) {
111
207
  problem(["settings", id], guard === undefined ? `no guard "${id}"` : `the guard "${id}" takes no settings`);
112
208
  continue;
@@ -134,7 +230,13 @@ export function parseConfig(text, catalog) {
134
230
  problems: document.errors.map((error) => `${CONFIG_FILE}:${error.linePos?.[0].line ?? 1}:${error.linePos?.[0].col ?? 1}: ${(error.message.split("\n")[0] ?? "").replace(/ at line \d+, column \d+:?$/, "")}`),
135
231
  };
136
232
  }
137
- const data = document.toJS();
233
+ let data;
234
+ try {
235
+ data = document.toJS({ maxAliasCount: MAX_ALIASES });
236
+ }
237
+ catch (error) {
238
+ return { problems: [`${CONFIG_FILE}: ${error instanceof Error ? error.message : String(error)}`] };
239
+ }
138
240
  if (!validateFile(data)) {
139
241
  return {
140
242
  problems: relevant(validateFile.errors ?? []).map((error) => `${locate(document, lineCounter, segments(error.instancePath))}: ${describe(error)}`),
@@ -147,7 +249,14 @@ export function parseConfig(text, catalog) {
147
249
  checkDirectories(data, problem);
148
250
  checkExceptions(data, catalog, problem);
149
251
  checkSteps(data, catalog, problem);
252
+ checkSkippedGuards(data, catalog, problem);
150
253
  checkSettings(data, catalog, problem);
254
+ checkConfigure(data, catalog, problem);
255
+ if (problems.length === 0) {
256
+ const found = circle(data, catalog);
257
+ if (found !== null)
258
+ problem(["steps"], `steps wait for each other in a circle: ${found.join(" -> ")}: drop one of these after entries`);
259
+ }
151
260
  if (problems.length > 0)
152
261
  return { problems };
153
262
  return {
@@ -156,6 +265,12 @@ export function parseConfig(text, catalog) {
156
265
  directories: data.directories ?? {},
157
266
  add: data.steps?.add ?? [],
158
267
  skip: data.steps?.skip ?? [],
268
+ configure: data.steps?.configure ?? {},
269
+ environment: {
270
+ ...(data.env === undefined ? {} : { env: data.env }),
271
+ ...(data.unset === undefined ? {} : { unset: data.unset }),
272
+ },
273
+ skippedGuards: data.guards?.skip ?? [],
159
274
  exceptions: data.exceptions ?? [],
160
275
  settings: data.settings ?? {},
161
276
  ...(data.quick?.limitSeconds === undefined ? {} : { quickLimitSeconds: data.quick.limitSeconds }),
@@ -9,6 +9,8 @@ export interface GuardException {
9
9
  guard: string;
10
10
  target: string;
11
11
  reason: string;
12
+ message?: string;
13
+ once?: boolean;
12
14
  }
13
15
  export interface GuardContext {
14
16
  root: string;
@@ -19,6 +21,11 @@ export interface GuardContext {
19
21
  settings: unknown;
20
22
  read(file: string): string;
21
23
  }
24
+ export interface DotnetGuard {
25
+ id: string;
26
+ profile: Profile;
27
+ settingsSchema?: object;
28
+ }
22
29
  export interface Guard {
23
30
  id: string;
24
31
  description: string;
@@ -33,6 +40,9 @@ export interface StepContext {
33
40
  quick: boolean;
34
41
  profiles: readonly Profile[];
35
42
  directories: Readonly<Partial<Record<Profile, string>>>;
43
+ skippedSteps: readonly string[];
44
+ skippedGuards: readonly string[];
45
+ settings: Readonly<Record<string, unknown>>;
36
46
  changed(): readonly string[];
37
47
  }
38
48
  export interface Skip {
@@ -47,5 +57,8 @@ export interface Step {
47
57
  profile?: Profile;
48
58
  needs?: readonly string[];
49
59
  after?: readonly string[];
60
+ orderAfter?: readonly string[];
50
61
  limitSeconds?: number;
62
+ settingsSchema?: object;
63
+ args?: string;
51
64
  }
@@ -1,5 +1,5 @@
1
1
  import { type Config } from "./config.ts";
2
- import type { Guard } from "./contract.ts";
2
+ import type { Guard, GuardException } from "./contract.ts";
3
3
  interface GuardsSummary {
4
4
  passed: boolean;
5
5
  log: string;
@@ -9,6 +9,8 @@ interface GuardsInput {
9
9
  guards: readonly Guard[];
10
10
  files: readonly string[];
11
11
  config: Config;
12
+ merged?: readonly GuardException[];
12
13
  }
14
+ export declare function sameException(a: GuardException, b: GuardException): boolean;
13
15
  export declare function runGuards(input: GuardsInput): Promise<GuardsSummary>;
14
16
  export {};
@@ -1,6 +1,12 @@
1
1
  import { readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { CONFIG_FILE } from "./config.js";
4
+ export function sameException(a, b) {
5
+ return a.guard === b.guard && a.target === b.target && a.message === b.message;
6
+ }
7
+ function matches(exception, finding) {
8
+ return exception.target === finding.target && (exception.message === undefined || finding.message.includes(exception.message));
9
+ }
4
10
  function shown(guard, finding) {
5
11
  return `${guard.id}: ${finding.target}${finding.line === undefined ? "" : `:${finding.line}`}: ${finding.message}`;
6
12
  }
@@ -30,10 +36,12 @@ export async function runGuards(input) {
30
36
  let excepted = 0;
31
37
  let failed = false;
32
38
  for (const guard of input.guards) {
33
- const exceptions = input.config.exceptions.filter((exception) => exception.guard === guard.id);
39
+ const own = input.config.exceptions.filter((exception) => exception.guard === guard.id);
40
+ const merged = own.filter((exception) => (input.merged ?? []).some((done) => sameException(done, exception)));
41
+ const exceptions = own.filter((exception) => !merged.includes(exception));
34
42
  const used = new Set();
35
43
  for (const finding of await findingsOf(guard, input, exceptions)) {
36
- const exception = exceptions.find((candidate) => candidate.target === finding.target);
44
+ const exception = exceptions.find((candidate) => matches(candidate, finding));
37
45
  if (exception === undefined) {
38
46
  lines.push(shown(guard, finding));
39
47
  failed = true;
@@ -44,9 +52,12 @@ export async function runGuards(input) {
44
52
  }
45
53
  excepted += used.size;
46
54
  for (const stale of exceptions.filter((exception) => !used.has(exception))) {
47
- lines.push(`${guard.id}: ${stale.target}: the exception in ${CONFIG_FILE} matches nothing any more: delete it`);
55
+ lines.push(`${guard.id}: ${stale.target}: the exception in ${CONFIG_FILE}${stale.message === undefined ? "" : ` (message: ${stale.message})`} matches nothing any more: delete it`);
48
56
  failed = true;
49
57
  }
58
+ for (const done of merged) {
59
+ lines.push(`${guard.id}: ${done.target}: the one-time exception is on master now and excepts nothing: delete it from ${CONFIG_FILE}`);
60
+ }
50
61
  }
51
62
  const header = `${input.guards.length} guard${input.guards.length === 1 ? "" : "s"}, ${excepted} findings excepted in ${CONFIG_FILE}`;
52
63
  return { passed: !failed, log: [header, ...lines].join("\n") };
@@ -1,4 +1,6 @@
1
- import type { Catalog, Config } from "./config.ts";
1
+ import type { Catalog, Config, Environment } from "./config.ts";
2
+ import type { GuardException, Step } from "./contract.ts";
3
+ export declare const GUARDS_STEP = "guards";
2
4
  export interface Outcome {
3
5
  passed: boolean;
4
6
  log: string;
@@ -8,6 +10,7 @@ export interface PlannedStep {
8
10
  title: string;
9
11
  after: readonly string[];
10
12
  limitSeconds: number;
13
+ environment: readonly Environment[];
11
14
  skipped?: {
12
15
  reason: string;
13
16
  byConfig: boolean;
@@ -15,9 +18,15 @@ export interface PlannedStep {
15
18
  command?: {
16
19
  line: string;
17
20
  cwd: string;
21
+ args?: readonly string[];
18
22
  };
19
23
  inline?: () => Promise<Outcome>;
20
24
  }
25
+ export interface Target {
26
+ id: string;
27
+ only: boolean;
28
+ args: readonly string[];
29
+ }
21
30
  export interface PlanInput {
22
31
  root: string;
23
32
  quick: boolean;
@@ -25,5 +34,15 @@ export interface PlanInput {
25
34
  catalog: Catalog;
26
35
  files: readonly string[];
27
36
  changed: () => readonly string[];
37
+ merged?: readonly GuardException[];
38
+ target?: Target;
39
+ }
40
+ export interface ListedStep {
41
+ id: string;
42
+ title: string;
43
+ args?: string;
44
+ skipped?: string;
28
45
  }
46
+ export declare function allSteps(config: Config, catalog: Catalog): Step[];
29
47
  export declare function plan(input: PlanInput): PlannedStep[];
48
+ export declare function listSteps(input: Omit<PlanInput, "target">): ListedStep[];
package/dist/gate/plan.js CHANGED
@@ -2,7 +2,7 @@ import { accessSync, constants } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { runGuards } from "./guardsStep.js";
4
4
  const DEFAULT_LIMIT_SECONDS = 300;
5
- const GUARDS_STEP = "guards";
5
+ export const GUARDS_STEP = "guards";
6
6
  function onPath(tool) {
7
7
  return (process.env["PATH"] ?? "").split(path.delimiter).some((folder) => {
8
8
  try {
@@ -24,6 +24,9 @@ function addedSteps(config) {
24
24
  ...(added.limitSeconds === undefined ? {} : { limitSeconds: added.limitSeconds }),
25
25
  }));
26
26
  }
27
+ export function allSteps(config, catalog) {
28
+ return [...catalog.stepsFor(config.profiles), ...addedSteps(config)];
29
+ }
27
30
  function chosenRun(step, quick) {
28
31
  if (!quick)
29
32
  return step.run;
@@ -31,43 +34,97 @@ function chosenRun(step, quick) {
31
34
  return step.run;
32
35
  return step.quick;
33
36
  }
37
+ function activeGuards(input) {
38
+ const skipped = input.config.skippedGuards.map((entry) => entry.guard);
39
+ return input.catalog.guards.filter((guard) => (guard.profiles === "every" || guard.profiles.some((profile) => input.config.profiles.includes(profile))) &&
40
+ (!input.quick || guard.quick !== false) &&
41
+ !skipped.includes(guard.id));
42
+ }
43
+ function guardsTitle(input) {
44
+ const skipped = input.config.skippedGuards.map((entry) => entry.guard);
45
+ const skippedHere = input.catalog.guards.filter((guard) => skipped.includes(guard.id)).length;
46
+ return `repository guards (${activeGuards(input).length}${skippedHere === 0 ? "" : `, ${skippedHere} skipped in suwgate.yml`})`;
47
+ }
34
48
  function guardsStep(input) {
35
- const active = input.catalog.guards.filter((guard) => (guard.profiles === "every" || guard.profiles.some((profile) => input.config.profiles.includes(profile))) &&
36
- (!input.quick || guard.quick !== false));
49
+ const active = activeGuards(input);
37
50
  return {
38
51
  id: GUARDS_STEP,
39
- title: `repository guards (${active.length})`,
52
+ title: guardsTitle(input),
40
53
  after: [],
41
54
  limitSeconds: DEFAULT_LIMIT_SECONDS,
55
+ environment: [],
42
56
  inline: async () => {
43
- const summary = await runGuards({ root: input.root, guards: active, files: input.files, config: input.config });
57
+ const summary = await runGuards({
58
+ root: input.root,
59
+ guards: active,
60
+ files: input.files,
61
+ config: input.config,
62
+ merged: input.merged ?? [],
63
+ });
44
64
  return { passed: summary.passed, log: summary.log };
45
65
  },
46
66
  };
47
67
  }
68
+ function needed(step, config) {
69
+ return [...(step.after ?? []), ...(config.configure[step.id]?.after ?? [])];
70
+ }
71
+ function selected(steps, input) {
72
+ const { target } = input;
73
+ if (target === undefined)
74
+ return new Set([GUARDS_STEP, ...steps.map((step) => step.id)]);
75
+ const chosen = new Set();
76
+ const visit = (id) => {
77
+ if (chosen.has(id))
78
+ return;
79
+ chosen.add(id);
80
+ const step = steps.find((candidate) => candidate.id === id);
81
+ if (step !== undefined && !target.only)
82
+ needed(step, input.config).forEach(visit);
83
+ };
84
+ visit(target.id);
85
+ return chosen;
86
+ }
87
+ function environmentOf(step, config) {
88
+ const own = config.configure[step.id];
89
+ return [config.environment, ...(own === undefined ? [] : [{ ...own }])].filter((layer) => layer.env !== undefined || layer.unset !== undefined);
90
+ }
91
+ function stepContext(input, cwd) {
92
+ return {
93
+ root: input.root,
94
+ cwd,
95
+ quick: input.quick,
96
+ profiles: input.config.profiles,
97
+ directories: input.config.directories,
98
+ skippedSteps: input.config.skip.map((skipped) => skipped.step),
99
+ skippedGuards: input.config.skippedGuards.map((skipped) => skipped.guard),
100
+ settings: Object.fromEntries(Object.entries(input.config.configure).flatMap(([id, configured]) => configured.settings === undefined ? [] : [[id, configured.settings]])),
101
+ changed: input.changed,
102
+ };
103
+ }
48
104
  export function plan(input) {
49
- const steps = [...input.catalog.stepsFor(input.config.profiles), ...addedSteps(input.config)];
50
- const planned = [guardsStep(input)];
51
- for (const step of steps) {
105
+ const steps = allSteps(input.config, input.catalog);
106
+ const chosen = selected(steps, input);
107
+ const planned = chosen.has(GUARDS_STEP) ? [guardsStep(input)] : [];
108
+ for (const step of steps.filter((candidate) => chosen.has(candidate.id))) {
109
+ const asked = input.target?.id === step.id;
52
110
  const run = chosenRun(step, input.quick);
53
111
  if (run === undefined)
54
112
  continue;
55
113
  const cwd = path.join(input.root, (step.profile === undefined ? undefined : input.config.directories[step.profile]) ?? "");
56
- const base = { id: step.id, title: step.title, after: step.after ?? [], limitSeconds: step.limitSeconds ?? DEFAULT_LIMIT_SECONDS };
114
+ const configured = input.config.configure[step.id];
115
+ const base = {
116
+ id: step.id,
117
+ title: step.title,
118
+ after: [...needed(step, input.config), ...(step.orderAfter ?? [])],
119
+ limitSeconds: configured?.limitSeconds ?? step.limitSeconds ?? DEFAULT_LIMIT_SECONDS,
120
+ environment: environmentOf(step, input.config),
121
+ };
57
122
  const skippedByConfig = input.config.skip.find((skipped) => skipped.step === step.id);
58
- if (skippedByConfig !== undefined) {
123
+ if (skippedByConfig !== undefined && !asked) {
59
124
  planned.push({ ...base, skipped: { reason: skippedByConfig.reason, byConfig: true } });
60
125
  continue;
61
126
  }
62
- const context = {
63
- root: input.root,
64
- cwd,
65
- quick: input.quick,
66
- profiles: input.config.profiles,
67
- directories: input.config.directories,
68
- changed: input.changed,
69
- };
70
- const line = typeof run === "string" ? run : run(context);
127
+ const line = typeof run === "string" ? run : run(stepContext(input, cwd));
71
128
  const missing = (step.needs ?? []).filter((tool) => !onPath(tool));
72
129
  if (line === null) {
73
130
  planned.push({ ...base, inline: () => Promise.resolve({ passed: true, log: "nothing to check" }) });
@@ -79,8 +136,23 @@ export function plan(input) {
79
136
  planned.push({ ...base, skipped: { reason: `${missing.join(", ")} not installed`, byConfig: false } });
80
137
  }
81
138
  else {
82
- planned.push({ ...base, command: { line, cwd } });
139
+ const args = asked ? (input.target?.args ?? []) : [];
140
+ planned.push({ ...base, command: { line, cwd, ...(args.length === 0 ? {} : { args }) } });
83
141
  }
84
142
  }
85
143
  return planned;
86
144
  }
145
+ export function listSteps(input) {
146
+ return [
147
+ { id: GUARDS_STEP, title: guardsTitle(input) },
148
+ ...allSteps(input.config, input.catalog).map((step) => {
149
+ const skipped = input.config.skip.find((entry) => entry.step === step.id)?.reason;
150
+ return {
151
+ id: step.id,
152
+ title: step.title,
153
+ ...(step.args === undefined ? {} : { args: step.args }),
154
+ ...(skipped === undefined ? {} : { skipped }),
155
+ };
156
+ }),
157
+ ];
158
+ }
@@ -6,6 +6,7 @@ export interface ReportInput {
6
6
  quickLimit: number | null;
7
7
  ci: boolean;
8
8
  exceptions: number;
9
+ mergedOnce?: number;
9
10
  verbose: boolean;
10
11
  }
11
12
  export interface Report {
@@ -2,8 +2,11 @@ const FAILURE_LINES = 25;
2
2
  function row(status, seconds, title, note = "") {
3
3
  return ` ${status.padEnd(4)} ${seconds === null ? " " : `${String(seconds).padStart(4)}s`} ${title}${note === "" ? "" : ` — ${note}`}`;
4
4
  }
5
- function tail(log) {
6
- return log.trimEnd().split("\n").slice(-FAILURE_LINES).join("\n");
5
+ function shownLog(log, all) {
6
+ const lines = log.trimEnd().split("\n");
7
+ if (all || lines.length <= FAILURE_LINES)
8
+ return { text: lines.join("\n"), heading: `all ${lines.length} lines` };
9
+ return { text: lines.slice(-FAILURE_LINES).join("\n"), heading: `last ${FAILURE_LINES} of ${lines.length} lines, --verbose shows all` };
7
10
  }
8
11
  export function report(input) {
9
12
  const failures = [];
@@ -31,7 +34,8 @@ export function report(input) {
31
34
  else if (result.status === "fail") {
32
35
  failed = true;
33
36
  rows.push(row("FAIL", result.seconds, step.title));
34
- failures.push(`==================== failed: ${step.title} (last ${FAILURE_LINES} lines) ====================\n${tail(result.log)}`);
37
+ const shown = shownLog(result.log, input.verbose);
38
+ failures.push(`==================== failed: ${step.title} (${shown.heading}) ====================\n${shown.text}`);
35
39
  }
36
40
  else {
37
41
  passedCount++;
@@ -45,6 +49,11 @@ export function report(input) {
45
49
  }
46
50
  const extras = [
47
51
  `${input.exceptions} exception${input.exceptions === 1 ? "" : "s"} in suwgate.yml`,
52
+ ...((input.mergedOnce ?? 0) > 0
53
+ ? [
54
+ `${input.mergedOnce} one-time exception${input.mergedOnce === 1 ? " is" : "s are"} on master now: delete ${input.mergedOnce === 1 ? "it" : "them"}`,
55
+ ]
56
+ : []),
48
57
  ...(skippedByConfig.length > 0 ? [`skipped in suwgate.yml: ${skippedByConfig.join(", ")}`] : []),
49
58
  ].join("; ");
50
59
  const lines = [];
@@ -1,3 +1,4 @@
1
1
  export declare function repositoryRoot(cwd: string): string | null;
2
2
  export declare function repositoryFiles(root: string): string[];
3
3
  export declare function changedFiles(root: string): string[];
4
+ export declare function fileOnMaster(root: string, file: string): string | null;
@@ -35,3 +35,11 @@ export function changedFiles(root) {
35
35
  const untracked = git(root, ["ls-files", "--others", "--exclude-standard"]);
36
36
  return [...new Set([...lines(committedOrStaged), ...lines(untracked)])].sort();
37
37
  }
38
+ export function fileOnMaster(root, file) {
39
+ for (const branch of ["master", "origin/master"]) {
40
+ const base = git(root, ["merge-base", "HEAD", branch])?.trim();
41
+ if (base !== undefined && base.length > 0)
42
+ return git(root, ["show", `${base}:${file}`]);
43
+ }
44
+ return null;
45
+ }
@@ -10,10 +10,25 @@ function killGroup(pid, signal) {
10
10
  return;
11
11
  }
12
12
  }
13
- function runCommand(line, cwd, limitSeconds, env) {
13
+ function matcher(pattern) {
14
+ return new RegExp(`^${pattern.replaceAll("*", ".*").replaceAll("?", ".")}$`, "i");
15
+ }
16
+ function stepEnv(env, layers) {
17
+ return layers.reduce((current, layer) => {
18
+ const cleared = (layer.unset ?? []).map(matcher);
19
+ const kept = Object.entries(current).filter(([name]) => !cleared.some((pattern) => pattern.test(name)));
20
+ return { ...Object.fromEntries(kept), ...layer.env };
21
+ }, env);
22
+ }
23
+ function runCommand(command, limitSeconds, env) {
14
24
  return new Promise((resolve) => {
15
25
  const chunks = [];
16
- const child = spawn("bash", ["-c", line], { cwd, env, detached: true, stdio: ["ignore", "pipe", "pipe"] });
26
+ const child = spawn("bash", ["-c", command.line, "suwgate", ...(command.args ?? [])], {
27
+ cwd: command.cwd,
28
+ env,
29
+ detached: true,
30
+ stdio: ["ignore", "pipe", "pipe"],
31
+ });
17
32
  child.stdout.on("data", (chunk) => chunks.push(chunk));
18
33
  child.stderr.on("data", (chunk) => chunks.push(chunk));
19
34
  let timedOut = false;
@@ -59,7 +74,7 @@ export async function runSteps(steps, env, stepLimit) {
59
74
  const began = performance.now();
60
75
  const limit = stepLimit ?? step.limitSeconds;
61
76
  const outcome = step.command !== undefined
62
- ? await runCommand(step.command.line, step.command.cwd, limit, env)
77
+ ? await runCommand(step.command, limit, stepEnv(env, step.environment))
63
78
  : await (step.inline ?? (() => Promise.resolve({ passed: true, log: "" })))();
64
79
  return {
65
80
  step,