@maniumek/suwgate 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,6 +12,10 @@ pnpm exec suwgate step # the steps of this repository, with their ti
12
12
  pnpm exec suwgate step e2e -- --headed -g notes # one step and what it needs; after --, arguments for its tool
13
13
  ```
14
14
 
15
+ pnpm installs a version only once it is a day old (`minimumReleaseAge`). To take a new suwgate the day it is published, exclude
16
+ the package by name in `pnpm-workspace.yaml`, `minimumReleaseAgeExclude: ["@maniumek/suwgate"]`: an entry with a version
17
+ (`@maniumek/suwgate@0.5.0`) has to be edited on every version bump, the name does not.
18
+
15
19
  `suwgate.yml` in the repository root says what the repository is and where it departs from the defaults:
16
20
 
17
21
  ```yaml
@@ -117,7 +121,9 @@ build come with it) and prints the report `suwgate check` prints, with the same
117
121
  server): `suwgate step e2e` does not run them.
118
122
  - It is not a gate pass: the Stop hook does not count it, and the next turn still runs the quick gate.
119
123
  - The evidence still applies where it makes sense for one step: a test step that ran 0 tests fails (a filter that matches
120
- nothing is a mistake); `dotnet-test` asks the .NET guards' evidence only when it gets no arguments, because a filtered run
124
+ nothing is a mistake). With arguments, `dotnet-test` counts the tests of the whole run, not of each test project
125
+ (`--ignore-exit-code 8` for each test project, then xUnit's reports of all of them), so `--filter-class "*Notes*"` passes in a
126
+ repository with more than one test project and fails only when no test anywhere matched; `dotnet-test` asks the .NET guards' evidence only when it gets no arguments, because a filtered run
121
127
  leaves guards out on purpose; `criteria-ran` reads the reports of the same run, so `suwgate step criteria-ran` runs every
122
128
  test step first, and with `--only` it has no reports and fails.
123
129
 
@@ -254,11 +260,14 @@ the solution, `layers.json`, the sources and the migrations itself, and takes fr
254
260
  `GetElapsedTime`, `TickCount`, `DateTime.Now`, `UtcNow` and `Today`, `Thread.Sleep`, `Task.Delay`, `Timeout =` in an attribute),
255
261
  and the `*.test`, `*.spec`, `*.e2e`, `*.visual`
256
262
  and `*.stories` files and the helpers of an `e2e/` folder (`performance.now`, `Date.now()` in a subtraction, `setTimeout`,
257
- `sleep(<n>)`, `waitForTimeout`, `interruptAfterTimeLimit`, and `timeout: <n>` in a Vitest file). It lets through a call that is
263
+ `sleep(<n>)`, `waitForTimeout`, `interruptAfterTimeLimit`, and `timeout: <n>` in a Vitest file, such as the options of `it`, `test`
264
+ or `describe`). It lets through a call that is
258
265
  handed a `TimeProvider` (a `FakeTimeProvider` in the tests), `Task.Delay` inside a `while`, `for`, `foreach` or `do` loop (a poll)
259
266
  or with `Timeout.Infinite`, the timers and the clock of a file that calls `vi.useFakeTimers()`, Playwright's auto-waiting
260
267
  `expect` with its own `timeout`, a ceiling against a hang (`CancelAfter`, `new CancellationTokenSource(<delay>)`,
261
- `WaitAsync(<TimeSpan>)`: the test waits for an event and fails fast, with its name, if it never comes), and the tools' configs
268
+ `WaitAsync(<TimeSpan>)`, and the `timeout` option of a Vitest wait for an event: `vi.waitFor`, `vi.waitUntil`, `expect.poll`,
269
+ Testing Library's `waitFor`, `findBy*` and `findAllBy*`; the test waits for the event and fails fast, with its name, if it never
270
+ comes: a ceiling, not a speed promise), and the tools' configs
262
271
  (`playwright.config.ts`), whose ceilings stop a hang.
263
272
  - `human-docs` (every profile): `README.md`, `docs/development.md` and the README of a profile's directory never tell a person to
264
273
  run a script meant for agents, one in `scripts/.internal/` or `<name>.Gate/scripts/`; people run `just` recipes. A command is a
@@ -274,8 +283,8 @@ A check counts only when the tool shows it ran, not because a file or a line of
274
283
  `VerifyAll` or `Guards.Verify`) writes its id and outcome there. The step fails unless every guard of the profiles that
275
284
  `guards.skip` does not name is in it, so a deleted guard test, a `[Fact(Skip = …)]` or a filtered-out one fails the gate.
276
285
  - Zero tests fail: `unit-tests`, `stories` (Vitest, its JSON report), `e2e` (Playwright, its JSON report) and `dotnet-test`
277
- (`--zero-tests-policy strict` of Microsoft.Testing.Platform, and xUnit's XML report) fail when the tool ran no test, also when
278
- every test was skipped. A repository with truly no tests for a profile skips the step in `suwgate.yml` with a reason.
286
+ (`--zero-tests-policy strict` of Microsoft.Testing.Platform for each test project, and xUnit's XML reports for the whole run)
287
+ fail when the tool ran no test, also when every test was skipped. A repository with truly no tests for a profile skips the step in `suwgate.yml` with a reason.
279
288
  - `typecheck` reads `tsc --showConfig` of every tsconfig it checks: the strict options of the suwgate preset must be in effect, so
280
289
  an override that turns one off fails, naming the option.
281
290
  - `lint` reads `eslint --print-config` of a source file of `src/`: `suwgate/no-comments` and `boundaries/dependencies` must be
@@ -290,7 +299,10 @@ A check counts only when the tool shows it ran, not because a file or a line of
290
299
  stylesheet that module imports. Both read the sources: the evidence (a run hitting `/health`, a built stylesheet with the
291
300
  kit's tokens) needs a running server or a production build, which the gate does not have in every repository.
292
301
  - The reports live in a temporary folder of the run (`SUWGATE_RUN`), deleted when `suwgate check` ends. `dotnet-test` asks xUnit
293
- for its XML report (`--report-xunit-xml`), so every .NET test project tests with xUnit v3.
302
+ for its XML report (`--report-xunit-xml`), so every .NET test project tests with xUnit v3. Each test project writes its own
303
+ report, `<project>.<target framework>.xunit.xml` (`--report-xunit-xml-filename` through `TestingPlatformCommandLineArguments`,
304
+ from a targets file the step passes as `-p:CustomAfterMicrosoftCommonTargets`): xUnit's own name is the moment the project
305
+ started, which two projects that start together share, and one report would overwrite the other.
294
306
 
295
307
  `suwgate dev db|logs|smoke|server|tmux|checkout-env` runs the local stack of the template (database, logs, smoke test, server, tmux
296
308
  session, worktree databases) from a `dev` section of `suwgate.yml`: [docs/dev.md](docs/dev.md).
@@ -1,10 +1,11 @@
1
1
  import { type Io } from "./process.ts";
2
2
  import type { DevSettings } from "./settings.ts";
3
- export declare const CHECKOUT_ENV_USAGE = "usage: eval \"$(suwgate dev checkout-env)\"\nPrints shell `export` lines, so the shell that evals them has the variables of this checkout: the builds leave no worker\nprocesses behind (MSBUILDDISABLENODEREUSE, DOTNET_CLI_USE_MSBUILD_SERVER), and a linked git worktree gets its own test and\ne2e databases and its own e2e ports, so checkouts that run the gate or the browser tests at the same time do not collide.\nThe main checkout and CI keep the plain names and ports (<database>_e2e, ports dev.ports.e2eServer and e2eWeb). A linked\nworktree takes a suffix from its directory name (lower-case [a-z0-9_], at most 30 chars, and a hash of the name) for the\ndatabase names and a port pair (20000-29999) from the same hash. Nothing is cleaned up afterwards: a worktree's databases\nstay until you drop them. A value already in the environment wins. What it chose goes to stderr.";
4
- export declare function cksum(text: string): number;
5
- export declare function suffixOf(name: string): string;
3
+ export declare const CHECKOUT_ENV_USAGE = "usage: eval \"$(suwgate dev checkout-env)\"\nPrints shell `export` lines, so the shell that evals them has the variables of this checkout: the builds leave no worker\nprocesses behind (MSBUILDDISABLENODEREUSE, DOTNET_CLI_USE_MSBUILD_SERVER), and a linked git worktree gets its own test and\ne2e databases and its own e2e ports, so checkouts that run the gate or the browser tests at the same time do not collide.\nThe main checkout and CI keep the plain names and ports (<database>_e2e, ports dev.ports.e2eServer and e2eWeb). A linked\nworktree takes a suffix from its directory name (lower-case [a-z0-9_], at most 30 chars, and a hash of the repository's git\ndirectory and that name, so same-named worktrees of two repositories differ) for the database names and a port pair\n(20000-29999) from the same hash. Nothing is cleaned up afterwards: a worktree's databases\nstay until you drop them. A value already in the environment wins. What it chose goes to stderr.";
4
+ export declare function checkoutHash(repository: string, checkoutName: string): number;
5
+ export declare function suffixOf(name: string, hash: number): string;
6
6
  export interface CheckoutInputs {
7
7
  checkoutName: string;
8
+ repository: string;
8
9
  linked: boolean;
9
10
  ci: boolean;
10
11
  env: Readonly<Record<string, string | undefined>>;
@@ -16,5 +17,9 @@ export interface CheckoutEnv {
16
17
  }
17
18
  export declare function checkoutEnv(inputs: CheckoutInputs): CheckoutEnv;
18
19
  export declare function exportLines(variables: readonly (readonly [string, string])[]): string;
19
- export declare function isLinkedWorktree(root: string): boolean;
20
+ export interface GitCheckout {
21
+ repository: string;
22
+ linked: boolean;
23
+ }
24
+ export declare function gitCheckout(root: string): GitCheckout;
20
25
  export declare function runCheckoutEnv(args: readonly string[], settings: DevSettings, env: Readonly<Record<string, string | undefined>>, io: Io): number;
@@ -1,4 +1,5 @@
1
1
  import { execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
2
3
  import path from "node:path";
3
4
  import { Failure, quoted } from "./process.js";
4
5
  export const CHECKOUT_ENV_USAGE = `usage: eval "$(suwgate dev checkout-env)"
@@ -6,33 +7,19 @@ Prints shell \`export\` lines, so the shell that evals them has the variables of
6
7
  processes behind (MSBUILDDISABLENODEREUSE, DOTNET_CLI_USE_MSBUILD_SERVER), and a linked git worktree gets its own test and
7
8
  e2e databases and its own e2e ports, so checkouts that run the gate or the browser tests at the same time do not collide.
8
9
  The main checkout and CI keep the plain names and ports (<database>_e2e, ports dev.ports.e2eServer and e2eWeb). A linked
9
- worktree takes a suffix from its directory name (lower-case [a-z0-9_], at most 30 chars, and a hash of the name) for the
10
- database names and a port pair (20000-29999) from the same hash. Nothing is cleaned up afterwards: a worktree's databases
10
+ worktree takes a suffix from its directory name (lower-case [a-z0-9_], at most 30 chars, and a hash of the repository's git
11
+ directory and that name, so same-named worktrees of two repositories differ) for the database names and a port pair
12
+ (20000-29999) from the same hash. Nothing is cleaned up afterwards: a worktree's databases
11
13
  stay until you drop them. A value already in the environment wins. What it chose goes to stderr.`;
12
- const CRC_TABLE = Array.from({ length: 256 }, (_, index) => {
13
- let value = index << 24;
14
- for (let bit = 0; bit < 8; bit++)
15
- value = value & 0x80000000 ? (value << 1) ^ 0x04c11db7 : value << 1;
16
- return value >>> 0;
17
- });
18
14
  const SUFFIX_NAME_LENGTH = 30;
19
15
  const PORT_BASE = 20000;
20
16
  const PORT_PAIRS = 5000;
21
- function step(crc, byte) {
22
- return ((crc << 8) ^ (CRC_TABLE[((crc >>> 24) ^ byte) & 0xff] ?? 0)) >>> 0;
17
+ export function checkoutHash(repository, checkoutName) {
18
+ return createHash("sha256").update(`${repository}\n${checkoutName}`).digest().readUInt32BE(0);
23
19
  }
24
- export function cksum(text) {
25
- const bytes = Buffer.from(text, "utf8");
26
- let crc = 0;
27
- for (const byte of bytes)
28
- crc = step(crc, byte);
29
- for (let length = bytes.length; length > 0; length = Math.floor(length / 256))
30
- crc = step(crc, length % 256);
31
- return ~crc >>> 0;
32
- }
33
- export function suffixOf(name) {
20
+ export function suffixOf(name, hash) {
34
21
  const safe = Array.from(Buffer.from(name.toLowerCase(), "utf8"), (byte) => /[a-z0-9_]/.test(String.fromCharCode(byte)) ? String.fromCharCode(byte) : "_").join("");
35
- return `${safe.slice(0, SUFFIX_NAME_LENGTH)}_${cksum(name)}`;
22
+ return `${safe.slice(0, SUFFIX_NAME_LENGTH)}_${hash}`;
36
23
  }
37
24
  export function checkoutEnv(inputs) {
38
25
  const { settings, env } = inputs;
@@ -42,8 +29,9 @@ export function checkoutEnv(inputs) {
42
29
  };
43
30
  const { database } = settings;
44
31
  const isolated = !inputs.ci && inputs.linked;
45
- const suffix = suffixOf(inputs.checkoutName);
46
- const base = PORT_BASE + (cksum(inputs.checkoutName) % PORT_PAIRS) * 2;
32
+ const hash = checkoutHash(inputs.repository, inputs.checkoutName);
33
+ const suffix = suffixOf(inputs.checkoutName, hash);
34
+ const base = PORT_BASE + (hash % PORT_PAIRS) * 2;
47
35
  const variables = [
48
36
  ["MSBUILDDISABLENODEREUSE", "1"],
49
37
  ["DOTNET_CLI_USE_MSBUILD_SERVER", "0"],
@@ -73,13 +61,13 @@ function gitPath(root, args) {
73
61
  return null;
74
62
  }
75
63
  }
76
- export function isLinkedWorktree(root) {
64
+ export function gitCheckout(root) {
77
65
  const gitDir = gitPath(root, ["rev-parse", "--absolute-git-dir"]);
78
66
  const commonDir = gitPath(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
79
67
  if (gitDir === null || commonDir === null) {
80
68
  throw new Failure(`suwgate dev checkout-env: ${root} is not a git checkout, so a linked worktree cannot be told from the main one: run it in a cloned repository or worktree`);
81
69
  }
82
- return gitDir !== commonDir;
70
+ return { repository: commonDir, linked: gitDir !== commonDir };
83
71
  }
84
72
  export function runCheckoutEnv(args, settings, env, io) {
85
73
  if (args.length > 0) {
@@ -87,9 +75,10 @@ export function runCheckoutEnv(args, settings, env, io) {
87
75
  return 2;
88
76
  }
89
77
  const ci = (env["CI"] ?? "") !== "";
78
+ const checkout = ci ? { repository: settings.root, linked: false } : gitCheckout(settings.root);
90
79
  const result = checkoutEnv({
91
80
  checkoutName: path.basename(settings.root),
92
- linked: ci ? false : isLinkedWorktree(settings.root),
81
+ ...checkout,
93
82
  ci,
94
83
  env,
95
84
  settings,
@@ -6,6 +6,7 @@ const E2E_HELPER = /(^|\/)e2e\/.+\.[cm]?[jt]sx?$/;
6
6
  const TOOL_CONFIG = /\.config\.[cm]?[jt]s$/;
7
7
  const VITEST_TEST = /\.test\.[cm]?[jt]sx?$/;
8
8
  const FAKE_TIMERS = /\buseFakeTimers\s*\(/;
9
+ const WAITS_FOR_AN_EVENT = /(^|\.)(waitFor|find(All)?By\w+)$|^vi\.waitUntil$|^expect\.poll$/;
9
10
  const MEASURES = "measures real time";
10
11
  const READS_CLOCK = "reads the real clock";
11
12
  const WAITS = "waits on real time";
@@ -31,8 +32,27 @@ const WEB_RULES = [
31
32
  { name: "sleep or delay", pattern: /\b(sleep|delay)\(\s*\d/, verb: WAITS, faked: true },
32
33
  { name: "waitForTimeout", pattern: /\bwaitForTimeout\b/, verb: WAITS },
33
34
  { name: "interruptAfterTimeLimit", pattern: /\binterruptAfterTimeLimit\b/, verb: LIMITS },
34
- { name: "timeout:", pattern: /\btimeout\s*:\s*[1-9]/, verb: LIMITS, vitestOnly: true },
35
+ {
36
+ name: "timeout:",
37
+ pattern: /\btimeout\s*:\s*[1-9]/,
38
+ verb: LIMITS,
39
+ vitestOnly: true,
40
+ allowed: (source, at) => WAITS_FOR_AN_EVENT.test(enclosingCall(source, at)),
41
+ },
35
42
  ];
43
+ function enclosingCall(source, at) {
44
+ let depth = 0;
45
+ for (let position = at - 1; position >= 0; position--) {
46
+ const sign = source.charAt(position);
47
+ if (")]}".includes(sign))
48
+ depth++;
49
+ else if ("([{".includes(sign) && depth > 0)
50
+ depth--;
51
+ else if (sign === "(")
52
+ return /[\w$.]*$/.exec(source.slice(0, position).trimEnd())?.[0] ?? "";
53
+ }
54
+ return "";
55
+ }
36
56
  function blank(text) {
37
57
  return text.replace(/[^\n]/g, " ");
38
58
  }
@@ -176,10 +196,16 @@ function csharpFindings(file, source) {
176
196
  function webFindings(file, source) {
177
197
  const faked = FAKE_TIMERS.test(source);
178
198
  const rules = WEB_RULES.filter((rule) => !(faked && rule.faked) && (VITEST_TEST.test(file) || rule.vitestOnly !== true));
179
- return numberedLines(source).flatMap(({ line, text }) => rules.flatMap((rule) => {
180
- const match = rule.pattern.exec(text);
181
- return match === null ? [] : [finding(file, line, rule.name, rule.verb)];
182
- }));
199
+ let start = 0;
200
+ return numberedLines(source).flatMap(({ line, text }) => {
201
+ const lineStart = start;
202
+ start = source.indexOf("\n", start) + 1;
203
+ return rules.flatMap((rule) => {
204
+ const matches = [...text.matchAll(new RegExp(rule.pattern, "g"))];
205
+ const found = matches.some((match) => rule.allowed?.(source, lineStart + match.index) !== true);
206
+ return found ? [finding(file, line, rule.name, rule.verb)] : [];
207
+ });
208
+ });
183
209
  }
184
210
  function isWebTest(file) {
185
211
  return !file.includes("node_modules/") && !TOOL_CONFIG.test(file) && (WEB_TEST.test(file) || E2E_HELPER.test(file));
@@ -6,7 +6,10 @@ const GUARD_PACKAGE = /<(PackageReference|ProjectReference)\b[^>]*(?:Include|Upd
6
6
  const TEST_PROJECT = /<PackageReference\b[^>]*Include="xunit\.v3"|<IsTestProject>true<\/IsTestProject>/;
7
7
  export const NO_IDLE_BUILD_PROCESSES = "export MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0";
8
8
  const BUILD = `${NO_IDLE_BUILD_PROCESSES} && dotnet build --nologo -v quiet`;
9
- const TEST_OPTIONS = '--no-build --no-progress --zero-tests-policy strict --report-xunit-xml --results-directory "$run/results"';
9
+ const REPORT_NAMES = "$run/report-names.targets";
10
+ const REPORT_NAMES_TARGETS = "<Project><PropertyGroup><TestingPlatformCommandLineArguments>$(TestingPlatformCommandLineArguments) --report-xunit-xml-filename &quot;$(MSBuildProjectName).$(TargetFramework).xunit.xml&quot;</TestingPlatformCommandLineArguments></PropertyGroup></Project>";
11
+ const TEST_OPTIONS = `-p:CustomAfterMicrosoftCommonTargets="${REPORT_NAMES}" --no-build --no-progress --zero-tests-policy strict --report-xunit-xml --results-directory "$run/results"`;
12
+ const ONLY_AN_EMPTY_RUN_FAILS = "${1:+--ignore-exit-code 8}";
10
13
  const FORMAT = `${NO_IDLE_BUILD_PROCESSES} && dotnet tool restore >/dev/null`;
11
14
  export const DOTNET_BUILD = "dotnet-build";
12
15
  export const DOTNET_TEST = "dotnet-test";
@@ -54,6 +57,7 @@ export function witnessed(context, tests) {
54
57
  return [
55
58
  runDirectory(DOTNET_TEST),
56
59
  'export SUWGATE_EVIDENCE="$run/evidence"',
60
+ `printf '%s' ${quoted(REPORT_NAMES_TARGETS)} >"${REPORT_NAMES}"`,
57
61
  tests,
58
62
  verdictCommand(`tests xunit "$run/results" ${quoted("dotnet test")}`),
59
63
  `{ [ $# -gt 0 ] || ${verdictCommand(`guards "$run/evidence" ${requiredGuards(context).map(quoted).join(" ")}`)}; }`,
@@ -87,7 +91,7 @@ export const dotnetSteps = [
87
91
  profile: "dotnet",
88
92
  needs: ["dotnet"],
89
93
  after: [DOTNET_BUILD, DATABASE_UP],
90
- run: (context) => inCheckoutEnv(context, witnessed(context, `dotnet test ${testOptions(context)} "$@"`)),
94
+ run: (context) => inCheckoutEnv(context, witnessed(context, `dotnet test ${testOptions(context)} ${ONLY_AN_EMPTY_RUN_FAILS} "$@"`)),
91
95
  quick: (context) => {
92
96
  const command = guardTests(context);
93
97
  return command === null ? null : inCheckoutEnv(context, witnessed(context, command));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maniumek/suwgate",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "One quality gate for every repository: suwgate check runs the steps of the repository's profiles and its guards, configured in suwgate.yml",
5
5
  "license": "MIT",
6
6
  "author": "Manomenu",