@maniumek/suwgate 0.3.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 (47) hide show
  1. package/README.md +92 -20
  2. package/dist/cli.js +38 -3
  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 +91 -19
  11. package/dist/gate/config.d.ts +12 -0
  12. package/dist/gate/config.js +87 -2
  13. package/dist/gate/contract.d.ts +6 -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 +89 -22
  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/repository/imagePins.js +1 -1
  26. package/dist/guards/repository/justModules.js +28 -10
  27. package/dist/guards/repository/noRawColors.js +1 -1
  28. package/dist/guards/repository/scriptsCalled.js +38 -11
  29. package/dist/profiles/contract.js +81 -38
  30. package/dist/profiles/criteriaRan.d.ts +1 -0
  31. package/dist/profiles/criteriaRan.js +44 -1
  32. package/dist/profiles/database.js +11 -4
  33. package/dist/profiles/dotnet.d.ts +1 -0
  34. package/dist/profiles/dotnet.js +28 -5
  35. package/dist/profiles/dotnetGuards.js +17 -1
  36. package/dist/profiles/library.js +4 -1
  37. package/dist/profiles/node.js +1 -0
  38. package/dist/profiles/presets/knip.d.ts +1 -0
  39. package/dist/profiles/presets/knip.js +4 -2
  40. package/dist/profiles/presets/playwright.d.ts +3 -1
  41. package/dist/profiles/presets/playwright.js +7 -1
  42. package/dist/profiles/shell.d.ts +3 -1
  43. package/dist/profiles/shell.js +22 -7
  44. package/dist/profiles/verdict.js +6 -2
  45. package/dist/profiles/web.js +24 -5
  46. package/package.json +1 -1
  47. package/schema/suwgate.schema.json +62 -3
@@ -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")));
@@ -70,6 +71,9 @@ function checkExceptions(raw, catalog, problem) {
70
71
  problem(where, `no guard "${exception.guard}": the guards are ${catalog.guards.map((guard) => guard.id).join(", ")} (and architecture/*, database/* of the .NET packages)`);
71
72
  }
72
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
+ }
73
77
  const prefix = Object.keys(DOTNET_GUARD_PREFIXES).find((candidate) => exception.guard.startsWith(candidate)) ?? "";
74
78
  const needed = DOTNET_GUARD_PREFIXES[prefix];
75
79
  if (needed !== undefined && !raw.profiles.includes(needed)) {
@@ -79,7 +83,7 @@ function checkExceptions(raw, catalog, problem) {
79
83
  else if (profiles !== "every" && !profiles.some((profile) => raw.profiles.includes(profile))) {
80
84
  problem(where, `"${exception.guard}" runs only for ${profiles.join(", ")}, which this repository does not have: delete the exception`);
81
85
  }
82
- const key = `${exception.guard}\u0000${exception.target}`;
86
+ const key = `${exception.guard}\u0000${exception.target}\u0000${exception.message ?? ""}`;
83
87
  if (seen.has(key))
84
88
  problem(where, `the same exception (${exception.guard}, ${exception.target}) is listed twice: keep one`);
85
89
  seen.add(key);
@@ -105,6 +109,70 @@ function checkSteps(raw, catalog, problem) {
105
109
  }
106
110
  });
107
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
+ }
108
176
  function profilesOf(id, catalog) {
109
177
  const dotnet = catalog.dotnetGuards.find((guard) => guard.id === id);
110
178
  if (dotnet !== undefined)
@@ -162,7 +230,13 @@ export function parseConfig(text, catalog) {
162
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+:?$/, "")}`),
163
231
  };
164
232
  }
165
- 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
+ }
166
240
  if (!validateFile(data)) {
167
241
  return {
168
242
  problems: relevant(validateFile.errors ?? []).map((error) => `${locate(document, lineCounter, segments(error.instancePath))}: ${describe(error)}`),
@@ -177,6 +251,12 @@ export function parseConfig(text, catalog) {
177
251
  checkSteps(data, catalog, problem);
178
252
  checkSkippedGuards(data, catalog, problem);
179
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
+ }
180
260
  if (problems.length > 0)
181
261
  return { problems };
182
262
  return {
@@ -185,6 +265,11 @@ export function parseConfig(text, catalog) {
185
265
  directories: data.directories ?? {},
186
266
  add: data.steps?.add ?? [],
187
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
+ },
188
273
  skippedGuards: data.guards?.skip ?? [],
189
274
  exceptions: data.exceptions ?? [],
190
275
  settings: data.settings ?? {},
@@ -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;
@@ -40,6 +42,7 @@ export interface StepContext {
40
42
  directories: Readonly<Partial<Record<Profile, string>>>;
41
43
  skippedSteps: readonly string[];
42
44
  skippedGuards: readonly string[];
45
+ settings: Readonly<Record<string, unknown>>;
43
46
  changed(): readonly string[];
44
47
  }
45
48
  export interface Skip {
@@ -54,5 +57,8 @@ export interface Step {
54
57
  profile?: Profile;
55
58
  needs?: readonly string[];
56
59
  after?: readonly string[];
60
+ orderAfter?: readonly string[];
57
61
  limitSeconds?: number;
62
+ settingsSchema?: object;
63
+ args?: string;
58
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,48 +34,97 @@ function chosenRun(step, quick) {
31
34
  return step.run;
32
35
  return step.quick;
33
36
  }
34
- function guardsStep(input) {
37
+ function activeGuards(input) {
35
38
  const skipped = input.config.skippedGuards.map((entry) => entry.guard);
36
- const active = input.catalog.guards.filter((guard) => (guard.profiles === "every" || guard.profiles.some((profile) => input.config.profiles.includes(profile))) &&
39
+ return input.catalog.guards.filter((guard) => (guard.profiles === "every" || guard.profiles.some((profile) => input.config.profiles.includes(profile))) &&
37
40
  (!input.quick || guard.quick !== false) &&
38
41
  !skipped.includes(guard.id));
42
+ }
43
+ function guardsTitle(input) {
44
+ const skipped = input.config.skippedGuards.map((entry) => entry.guard);
39
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
+ }
48
+ function guardsStep(input) {
49
+ const active = activeGuards(input);
40
50
  return {
41
51
  id: GUARDS_STEP,
42
- title: `repository guards (${active.length}${skippedHere === 0 ? "" : `, ${skippedHere} skipped in suwgate.yml`})`,
52
+ title: guardsTitle(input),
43
53
  after: [],
44
54
  limitSeconds: DEFAULT_LIMIT_SECONDS,
55
+ environment: [],
45
56
  inline: async () => {
46
- 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
+ });
47
64
  return { passed: summary.passed, log: summary.log };
48
65
  },
49
66
  };
50
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
+ }
51
104
  export function plan(input) {
52
- const steps = [...input.catalog.stepsFor(input.config.profiles), ...addedSteps(input.config)];
53
- const planned = [guardsStep(input)];
54
- 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;
55
110
  const run = chosenRun(step, input.quick);
56
111
  if (run === undefined)
57
112
  continue;
58
113
  const cwd = path.join(input.root, (step.profile === undefined ? undefined : input.config.directories[step.profile]) ?? "");
59
- 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
+ };
60
122
  const skippedByConfig = input.config.skip.find((skipped) => skipped.step === step.id);
61
- if (skippedByConfig !== undefined) {
123
+ if (skippedByConfig !== undefined && !asked) {
62
124
  planned.push({ ...base, skipped: { reason: skippedByConfig.reason, byConfig: true } });
63
125
  continue;
64
126
  }
65
- const context = {
66
- root: input.root,
67
- cwd,
68
- quick: input.quick,
69
- profiles: input.config.profiles,
70
- directories: input.config.directories,
71
- skippedSteps: input.config.skip.map((skipped) => skipped.step),
72
- skippedGuards: input.config.skippedGuards.map((skipped) => skipped.guard),
73
- changed: input.changed,
74
- };
75
- const line = typeof run === "string" ? run : run(context);
127
+ const line = typeof run === "string" ? run : run(stepContext(input, cwd));
76
128
  const missing = (step.needs ?? []).filter((tool) => !onPath(tool));
77
129
  if (line === null) {
78
130
  planned.push({ ...base, inline: () => Promise.resolve({ passed: true, log: "nothing to check" }) });
@@ -84,8 +136,23 @@ export function plan(input) {
84
136
  planned.push({ ...base, skipped: { reason: `${missing.join(", ")} not installed`, byConfig: false } });
85
137
  }
86
138
  else {
87
- planned.push({ ...base, command: { line, cwd } });
139
+ const args = asked ? (input.target?.args ?? []) : [];
140
+ planned.push({ ...base, command: { line, cwd, ...(args.length === 0 ? {} : { args }) } });
88
141
  }
89
142
  }
90
143
  return planned;
91
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,
@@ -7,7 +7,8 @@ const NGINX = new Set(["nginx.conf", "nginx.conf.template"]);
7
7
  const SHELLCHECK_DIRECTIVE = /^# shellcheck (disable|enable|source|shell|external-sources)=\S+$/;
8
8
  const DOCKERFILE_SYNTAX = /^# syntax=\S+$/;
9
9
  const EDITORCONFIG_CRITERION = new RegExp(`^# ${CRITERION_ID}$`);
10
- const RECIPE_OR_MODULE = /^(@?[A-Za-z_][\w-]*(\s+[^:=]*)?:(?!=)|mod\s+[\w-]+\s*$)/;
10
+ const RECIPE_OR_MODULE = /^(@?[A-Za-z_][\w-]*(\s+[^:]*)?:(?!=)|mod\??\s+[\w-]+(\s+(['"])[^'"]+\4)?\s*$)/;
11
+ const BLOCK_SCALAR = /^(\s*)((?:-\s+)*)(?:([^\s#][^#]*?):\s+)?[|>](?:[1-9][-+]?|[-+][1-9]?)?\s*(?:#.*)?$/;
11
12
  const isJust = (file) => ["justfile", ".justfile"].includes(fileName(file).toLowerCase()) || file.endsWith(".just");
12
13
  const isShell = (file) => file.endsWith(".sh") || file.endsWith(".bash") || file.startsWith(".githooks/");
13
14
  const isDockerfile = (file) => /^Dockerfile(\..+)?$/.test(fileName(file)) || file.endsWith(".Dockerfile");
@@ -56,9 +57,29 @@ function isAllowed(file, lines, index, comment) {
56
57
  (isEditorconfig(file) && EDITORCONFIG_CRITERION.test(comment)) ||
57
58
  (isJust(file) && describesTheRecipeBelow(lines, index)));
58
59
  }
60
+ const isYaml = (file) => file.endsWith(".yaml") || file.endsWith(".yml");
61
+ const indentOf = (line) => line.length - line.trimStart().length;
62
+ function blockScalarLines(lines) {
63
+ const inside = new Set();
64
+ let parent = null;
65
+ lines.forEach((line, index) => {
66
+ if (parent !== null && (line.trim() === "" || indentOf(line) > parent)) {
67
+ inside.add(index);
68
+ return;
69
+ }
70
+ parent = null;
71
+ const start = BLOCK_SCALAR.exec(line);
72
+ if (start !== null)
73
+ parent = (start[1] ?? "").length + (start[3] === undefined ? 0 : (start[2] ?? "").length);
74
+ });
75
+ return inside;
76
+ }
59
77
  export function hashCommentsIn(file, text) {
60
78
  const lines = text.split("\n");
79
+ const literal = isYaml(file) ? blockScalarLines(lines) : new Set();
61
80
  return lines.flatMap((line, index) => {
81
+ if (literal.has(index))
82
+ return [];
62
83
  const comment = commentOn(file, line);
63
84
  return comment !== null && !isAllowed(file, lines, index, comment) ? [{ line: index + 1, text: comment }] : [];
64
85
  });
@@ -3,6 +3,33 @@ const FRAMEWORK_SECTIONS = ["Logging", "AllowedHosts", "ConnectionStrings", "Kes
3
3
  const APPSETTINGS = /(^|\/)appsettings(\.[\w-]+)?\.json$/;
4
4
  const CSHARP = /\.cs$/;
5
5
  const SECTION_READ = /\b(?:BindConfiguration|GetSection|GetRequiredSection)\(\s*"([^":]+)/g;
6
+ const SECTION_READ_BY_NAME = /\b(?:BindConfiguration|GetSection|GetRequiredSection)\(\s*([A-Za-z_][\w.]*)\s*\)/g;
7
+ const TYPE_OR_CONSTANT = /\b(?:class|record|struct|interface)\s+(\w+)|\bconst\s+string\s+(\w+)\s*=\s*"([^":]+)"/g;
8
+ function constants(text) {
9
+ const found = new Map();
10
+ let type = "";
11
+ for (const match of text.matchAll(TYPE_OR_CONSTANT)) {
12
+ if (match[1] !== undefined) {
13
+ type = match[1];
14
+ }
15
+ else if (match[2] !== undefined && match[3] !== undefined) {
16
+ found.set(match[2], match[3]);
17
+ if (type !== "")
18
+ found.set(`${type}.${match[2]}`, match[3]);
19
+ }
20
+ }
21
+ return found;
22
+ }
23
+ function sectionsRead(texts) {
24
+ const named = new Map(texts.flatMap((text) => [...constants(text)]));
25
+ return new Set(texts.flatMap((text) => [
26
+ ...[...text.matchAll(SECTION_READ)].map((match) => match[1] ?? ""),
27
+ ...[...text.matchAll(SECTION_READ_BY_NAME)].flatMap((match) => {
28
+ const name = match[1] ?? "";
29
+ return named.get(name) ?? named.get(name.split(".").slice(-2).join(".")) ?? [];
30
+ }),
31
+ ]));
32
+ }
6
33
  function sectionsOf(file, text) {
7
34
  try {
8
35
  const parsed = JSON.parse(text);
@@ -17,10 +44,10 @@ function sectionsOf(file, text) {
17
44
  }
18
45
  export const appsettingsBound = {
19
46
  id: "appsettings-bound",
20
- description: "Every section of appsettings*.json is read by the code (an options class bound to it), so no setting is dead",
47
+ description: "Every section of appsettings*.json is read by the code (an options class bound to it, by a string or a const string), so no setting is dead",
21
48
  profiles: ["dotnet"],
22
49
  check(context) {
23
- const read = new Set(dotnetFiles(context, CSHARP).flatMap((file) => [...context.read(file).matchAll(SECTION_READ)].map((match) => match[1] ?? "")));
50
+ const read = sectionsRead(dotnetFiles(context, CSHARP).map((file) => context.read(file)));
24
51
  const problems = [];
25
52
  const unread = new Map();
26
53
  for (const file of dotnetFiles(context, APPSETTINGS)) {
@@ -44,7 +44,7 @@ export const imagePins = {
44
44
  check(context) {
45
45
  const found = context.files.flatMap((file) => isDockerfile(baseName(file)) || /\.(ya?ml|sh)$/.test(file) ? references(file, context.read(file)) : []);
46
46
  const unpinned = found
47
- .filter(({ image }) => !image.includes("$") && !isPinned(image))
47
+ .filter(({ image }) => !image.includes("$") && !image.includes("{{") && !isPinned(image))
48
48
  .map(({ file, line, image }) => ({
49
49
  target: file,
50
50
  line,