@maniumek/suwgate 0.14.0 → 0.15.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.
package/README.md CHANGED
@@ -94,7 +94,7 @@ suwgate dev tmux start # the whole local stack in one tmux sessi
94
94
  eval "$(suwgate dev checkout-env)" # in a linked worktree: its own test databases and e2e ports
95
95
  suwgate dev sibling suwagcms up # a sibling's images, rebuilt if its checkout moved on, then started
96
96
  suwgate dev api-types # the API contract and the web app's types, from the server
97
- suwgate dev slow-tests -n 20 # which .NET tests take the longest
97
+ suwgate dev slow-tests e2e -n 20 # which browser tests take the longest (dotnet, e2e, unit)
98
98
  ```
99
99
 
100
100
  Every subcommand answers `--help`. The `dev` section and what each command does: [docs/dev.md](docs/dev.md).
@@ -138,7 +138,7 @@ usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [--only] [--verb
138
138
  suwgate check every step of the repository's profiles (suwgate.yml) and the repository guards
139
139
  suwgate check --quick the guards, and the quick steps only for what changed since master; has a time budget
140
140
  (SUWGATE_QUICK_LIMIT seconds, default 20) because the Stop hook runs it after every turn
141
- --verbose list every step with its time, also when all pass, and the whole output of a failed step
141
+ --verbose list every step with its time, also when all pass, and the whole output of a failed step; suwgate step also of a passed one
142
142
  suwgate step the steps of this repository, with their titles and the tool that takes -- arguments
143
143
  suwgate step <id> one step and the steps it needs (after, transitively), with the same report; not a gate
144
144
  pass: the Stop hook does not count it. --only: that step alone. After --, arguments for the
package/dist/cli.js CHANGED
@@ -3,11 +3,14 @@ import { readFileSync } from "node:fs";
3
3
  import { parseArgs } from "node:util";
4
4
  import { check, step } from "./gate/check.js";
5
5
  import { dev, realEnvironment } from "./dev/index.js";
6
+ import { Failure } from "./dev/process.js";
6
7
  import { loadConfig } from "./gate/config.js";
8
+ import { allSteps } from "./gate/plan.js";
7
9
  import { PROFILES } from "./gate/contract.js";
8
10
  import { changedFiles, repositoryRoot } from "./gate/repository.js";
9
11
  import { guards, SHARED_RULES, writeSharedRules } from "./guards/index.js";
10
12
  import { discoverApiIn, dotnetGuards, stepsFor, verdict } from "./profiles/index.js";
13
+ import { readTimes, reportLocation } from "./profiles/reports.js";
11
14
  import { guardPr } from "./session/guardPr.js";
12
15
  import { guardEdit } from "./session/guardEdit.js";
13
16
  import { preCommit, runTool } from "./session/preCommit.js";
@@ -18,7 +21,7 @@ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [
18
21
  suwgate check every step of the repository's profiles (suwgate.yml) and the repository guards
19
22
  suwgate check --quick the guards, and the quick steps only for what changed since master; has a time budget
20
23
  (SUWGATE_QUICK_LIMIT seconds, default 20) because the Stop hook runs it after every turn
21
- --verbose list every step with its time, also when all pass, and the whole output of a failed step
24
+ --verbose list every step with its time, also when all pass, and the whole output of a failed step; suwgate step also of a passed one
22
25
  suwgate step the steps of this repository, with their titles and the tool that takes -- arguments
23
26
  suwgate step <id> one step and the steps it needs (after, transitively), with the same report; not a gate
24
27
  pass: the Stop hook does not count it. --only: that step alone. After --, arguments for the
@@ -37,7 +40,7 @@ const USAGE = `usage: suwgate check [--quick] [--verbose] | suwgate step [<id> [
37
40
  suwgate dev <db|logs|smoke|server|tmux|sibling|api-types|slow-tests|checkout-env>
38
41
  the local stack of the repository (the dev section of suwgate.yml), and the images of the
39
42
  sibling repositories it runs, rebuilt from their checkouts when stale, the API contract and types regenerated
40
- from the server, and a report of the slowest .NET tests; suwgate dev --help
43
+ from the server, and a report of the slowest tests; suwgate dev --help
41
44
  suwgate agents-shared writes AGENTS.shared.md, the rules every repository shares, as this suwgate ships it, into the
42
45
  repository root (the agents-shared guard fails until the copy is current)
43
46
  suwgate verdict <tests|guards|tsconfig|eslint> ...
@@ -66,6 +69,22 @@ function discoverApi(cwd) {
66
69
  const layout = discoverApiIn({ root, profiles, directories, contractSettings: configure["api-contract"]?.settings });
67
70
  return "problem" in layout ? layout : { root, layout };
68
71
  }
72
+ function slowTestsSteps(cwd) {
73
+ const root = repositoryRoot(cwd) ?? cwd;
74
+ const loaded = loadConfig(root, catalog);
75
+ if (!("config" in loaded))
76
+ throw new Failure(`suwgate dev slow-tests: suwgate.yml is not valid: ${loaded.problems.join("; ")}`, 2);
77
+ const { config } = loaded;
78
+ const skipped = config.skip.map((entry) => entry.step);
79
+ return {
80
+ root,
81
+ available: allSteps(config, catalog)
82
+ .map((found) => found.id)
83
+ .filter((id) => !skipped.includes(id)),
84
+ run: (id, runFolder) => step({ cwd: root, id, only: false, args: [], verbose: false, runFolder, env: process.env, catalog }),
85
+ times: (format, id, runFolder) => readTimes(format, reportLocation(runFolder, id, format)),
86
+ };
87
+ }
69
88
  function readInput() {
70
89
  try {
71
90
  return readFileSync(0, "utf8");
@@ -104,7 +123,7 @@ async function runStep(argv) {
104
123
  }
105
124
  async function main(argv) {
106
125
  if (argv[0] === "dev")
107
- return dev(argv.slice(1), realEnvironment(discoverApi));
126
+ return dev(argv.slice(1), realEnvironment(discoverApi, slowTestsSteps));
108
127
  if (argv[0] === "step")
109
128
  return runStep(argv.slice(1));
110
129
  if (argv[0] === "verdict") {
@@ -22,5 +22,4 @@ export interface GitCheckout {
22
22
  linked: boolean;
23
23
  }
24
24
  export declare function gitCheckout(root: string): GitCheckout;
25
- export declare function checkoutEnvOf(settings: DevSettings, env: Readonly<Record<string, string | undefined>>): CheckoutEnv;
26
25
  export declare function runCheckoutEnv(args: readonly string[], settings: DevSettings, env: Readonly<Record<string, string | undefined>>, io: Io): number;
@@ -69,7 +69,7 @@ export function gitCheckout(root) {
69
69
  }
70
70
  return { repository: commonDir, linked: gitDir !== commonDir };
71
71
  }
72
- export function checkoutEnvOf(settings, env) {
72
+ function checkoutEnvOf(settings, env) {
73
73
  const ci = (env["CI"] ?? "") !== "";
74
74
  const checkout = ci ? { repository: settings.root, linked: false } : gitCheckout(settings.root);
75
75
  return checkoutEnv({ checkoutName: path.basename(settings.root), ...checkout, ci, env, settings });
@@ -1,8 +1,9 @@
1
1
  import { type DiscoverApi } from "./apiTypes.ts";
2
2
  import { type Exec, type Io } from "./process.ts";
3
3
  import { type DevSettings } from "./settings.ts";
4
+ import { type SlowTestsSteps } from "./slowTests.ts";
4
5
  import { type Fetch, type SmokeCiEnvironment } from "./smoke.ts";
5
- export declare const DEV_USAGE = "usage: suwgate dev <db|logs|smoke|server|tmux|sibling|api-types|slow-tests|checkout-env> [arguments] (every one takes --help)\nThe dev scripts of the template as commands, configured by the dev section of suwgate.yml:\n db the local PostgreSQL of the compose file: up | down | reset | psql | logs | status\n logs why did it fail? the last warnings and errors of the server's JSON log\n smoke read-only requests against a running stack; --ci builds and starts its own stack first\n server the server under dotnet watch, restarted when it exits\n tmux the whole local stack in one tmux session: start [--restart] | stop\n sibling the images of a sibling repository, rebuilt from its checkout when stale: <name> image | up | rebuild | down | status\n api-types regenerate the API contract and the web app's types from the server, as the api-contract step generates them\n slow-tests a report of the slowest .NET tests: -n <count>, default 10\n checkout-env eval \"$(suwgate dev checkout-env)\": own test databases and e2e ports for a linked worktree";
6
+ export declare const DEV_USAGE = "usage: suwgate dev <db|logs|smoke|server|tmux|sibling|api-types|slow-tests|checkout-env> [arguments] (every one takes --help)\nThe dev scripts of the template as commands, configured by the dev section of suwgate.yml:\n db the local PostgreSQL of the compose file: up | down | reset | psql | logs | status\n logs why did it fail? the last warnings and errors of the server's JSON log\n smoke read-only requests against a running stack; --ci builds and starts its own stack first\n server the server under dotnet watch, restarted when it exits\n tmux the whole local stack in one tmux session: start [--restart] | stop\n sibling the images of a sibling repository, rebuilt from its checkout when stale: <name> image | up | rebuild | down | status\n api-types regenerate the API contract and the web app's types from the server, as the api-contract step generates them\n slow-tests a report of the slowest tests, by category: [dotnet|e2e|unit] [-n <count>], default 10\n checkout-env eval \"$(suwgate dev checkout-env)\": own test databases and e2e ports for a linked worktree";
6
7
  export interface DevEnvironment {
7
8
  cwd: string;
8
9
  env: Readonly<Record<string, string | undefined>>;
@@ -15,8 +16,9 @@ export interface DevEnvironment {
15
16
  ask: (question: string) => Promise<string>;
16
17
  loadSettings: (cwd: string) => DevSettings;
17
18
  discoverApi: DiscoverApi;
19
+ slowTestsSteps: (cwd: string) => SlowTestsSteps;
18
20
  temporaryFile: SmokeCiEnvironment["temporaryFile"];
19
21
  onInterrupt: SmokeCiEnvironment["onInterrupt"];
20
22
  }
21
- export declare function realEnvironment(discoverApi: DiscoverApi): DevEnvironment;
23
+ export declare function realEnvironment(discoverApi: DiscoverApi, slowTestsSteps: DevEnvironment["slowTestsSteps"]): DevEnvironment;
22
24
  export declare function dev(argv: readonly string[], environment: DevEnvironment): Promise<number>;
package/dist/dev/index.js CHANGED
@@ -23,7 +23,7 @@ The dev scripts of the template as commands, configured by the dev section of su
23
23
  tmux the whole local stack in one tmux session: start [--restart] | stop
24
24
  sibling the images of a sibling repository, rebuilt from its checkout when stale: <name> image | up | rebuild | down | status
25
25
  api-types regenerate the API contract and the web app's types from the server, as the api-contract step generates them
26
- slow-tests a report of the slowest .NET tests: -n <count>, default 10
26
+ slow-tests a report of the slowest tests, by category: [dotnet|e2e|unit] [-n <count>], default 10
27
27
  checkout-env eval "$(suwgate dev checkout-env)": own test databases and e2e ports for a linked worktree`;
28
28
  const USAGES = {
29
29
  db: DB_USAGE,
@@ -67,7 +67,7 @@ function onInterrupt(cleanup) {
67
67
  process.off("SIGTERM", stop);
68
68
  };
69
69
  }
70
- export function realEnvironment(discoverApi) {
70
+ export function realEnvironment(discoverApi, slowTestsSteps) {
71
71
  return {
72
72
  cwd: process.cwd(),
73
73
  env: process.env,
@@ -82,6 +82,7 @@ export function realEnvironment(discoverApi) {
82
82
  ask: askOnTerminal,
83
83
  loadSettings: (cwd) => loadSettings(repositoryRootOf(cwd)),
84
84
  discoverApi,
85
+ slowTestsSteps,
85
86
  temporaryFile,
86
87
  onInterrupt,
87
88
  };
@@ -143,7 +144,7 @@ async function dispatch(command, args, environment) {
143
144
  return runApiTypes({ root: found.root, layout: found.layout, exec: environment.exec, io });
144
145
  }
145
146
  case "slow-tests":
146
- return runSlowTests(parseSlowTests(args), { settings: settings(), env: environment.env, exec: environment.exec, io });
147
+ return runSlowTests(parseSlowTests(args), { io, steps: environment.slowTestsSteps(environment.cwd) });
147
148
  default:
148
149
  return runCheckoutEnv(args, settings(), environment.env, io);
149
150
  }
@@ -1,18 +1,29 @@
1
- import { type Exec, type Io } from "./process.ts";
2
- import type { DevSettings } from "./settings.ts";
3
- export declare const SLOW_TESTS_USAGE = "usage: suwgate dev slow-tests [-n <count>]\nWhich .NET tests take the longest? A report, not a check: it never fails for time, and suwgate check never runs it. A test far\nslower than its neighbours usually waits for something (a timeout, a server started per test) and passes anyway.\nSets the environment of suwgate dev checkout-env, starts the database like suwgate dev db up, builds the solution (the one\n*.slnx or *.sln in directories.dotnet, or in the root; none or several: exit 2), runs dotnet test --no-build with an xunit TRX\nreport in .artifacts/slow-tests (its output in run.log there), and lists the slowest tests with how long each took:\n suwgate dev slow-tests the 10 slowest\n suwgate dev slow-tests -n 25 the 25 slowest\nExit 1 when a test fails (the list still comes first), or the build or the database fails.";
1
+ import { type Io } from "./process.ts";
2
+ export declare const SLOW_TESTS_USAGE = "usage: suwgate dev slow-tests [dotnet|e2e|unit] [-n <count>]\nWhich tests take the longest? A report, not a check: it never fails for time, and suwgate check never runs it. A test far\nslower than its neighbours usually waits for something (a timeout, a server started per test) and passes anyway.\nIt runs the gate's own step of each category, with everything that step does first (a fresh database, the build, the servers),\nkeeps the reports of the tools in .artifacts/slow-tests/<category>, and lists the slowest tests with how long each took:\n dotnet the dotnet-test step (xUnit)\n e2e the e2e step (Playwright)\n unit the unit-tests step (Vitest)\n suwgate dev slow-tests every category this repository has (not skipped in suwgate.yml), each listed on its own\n suwgate dev slow-tests e2e only the browser tests\n suwgate dev slow-tests unit -n 25 the 25 slowest unit tests\nEach list starts with \"<category>: <n> tests, total <s> s, the <k> slowest:\" (-n sets k, default 10).\nExit 1 when a test or its step fails (the lists still come first), 2 on a usage error or a category this repository does not have.";
4
3
  export declare const RESULTS_FOLDER = ".artifacts/slow-tests";
5
- export interface SlowTestsEnvironment {
6
- settings: DevSettings;
7
- env: Readonly<Record<string, string | undefined>>;
8
- exec: Exec;
9
- io: Io;
10
- }
11
4
  export interface TestTime {
12
5
  seconds: number;
13
6
  name: string;
14
7
  }
15
- export declare function parseSlowTests(args: readonly string[]): number;
16
- export declare function parseTrx(text: string): TestTime[];
17
- export declare function slowest(times: readonly TestTime[], count: number): string[];
18
- export declare function runSlowTests(count: number, environment: SlowTestsEnvironment): Promise<number>;
8
+ type Format = "xunit" | "playwright" | "vitest";
9
+ export interface SlowTestsSteps {
10
+ root: string;
11
+ available: readonly string[];
12
+ run: (id: string, runFolder: string) => Promise<{
13
+ exitCode: number;
14
+ text: string;
15
+ }>;
16
+ times: (format: Format, step: string, runFolder: string) => TestTime[] | null;
17
+ }
18
+ export interface SlowTestsEnvironment {
19
+ io: Io;
20
+ steps: SlowTestsSteps;
21
+ }
22
+ export interface SlowTestsArguments {
23
+ category: string | null;
24
+ count: number;
25
+ }
26
+ export declare function parseSlowTests(args: readonly string[]): SlowTestsArguments;
27
+ export declare function slowest(category: string, times: readonly TestTime[], count: number): string[];
28
+ export declare function runSlowTests(parsed: SlowTestsArguments, environment: SlowTestsEnvironment): Promise<number>;
29
+ export {};
@@ -1,98 +1,90 @@
1
- import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1
+ import { mkdirSync, rmSync } from "node:fs";
2
2
  import path from "node:path";
3
- import { checkoutEnvOf } from "./checkoutEnv.js";
4
- import { runDb } from "./db.js";
5
3
  import { Failure, UsageError } from "./process.js";
6
- export const SLOW_TESTS_USAGE = `usage: suwgate dev slow-tests [-n <count>]
7
- Which .NET tests take the longest? A report, not a check: it never fails for time, and suwgate check never runs it. A test far
4
+ export const SLOW_TESTS_USAGE = `usage: suwgate dev slow-tests [dotnet|e2e|unit] [-n <count>]
5
+ Which tests take the longest? A report, not a check: it never fails for time, and suwgate check never runs it. A test far
8
6
  slower than its neighbours usually waits for something (a timeout, a server started per test) and passes anyway.
9
- Sets the environment of suwgate dev checkout-env, starts the database like suwgate dev db up, builds the solution (the one
10
- *.slnx or *.sln in directories.dotnet, or in the root; none or several: exit 2), runs dotnet test --no-build with an xunit TRX
11
- report in .artifacts/slow-tests (its output in run.log there), and lists the slowest tests with how long each took:
12
- suwgate dev slow-tests the 10 slowest
13
- suwgate dev slow-tests -n 25 the 25 slowest
14
- Exit 1 when a test fails (the list still comes first), or the build or the database fails.`;
7
+ It runs the gate's own step of each category, with everything that step does first (a fresh database, the build, the servers),
8
+ keeps the reports of the tools in .artifacts/slow-tests/<category>, and lists the slowest tests with how long each took:
9
+ dotnet the dotnet-test step (xUnit)
10
+ e2e the e2e step (Playwright)
11
+ unit the unit-tests step (Vitest)
12
+ suwgate dev slow-tests every category this repository has (not skipped in suwgate.yml), each listed on its own
13
+ suwgate dev slow-tests e2e only the browser tests
14
+ suwgate dev slow-tests unit -n 25 the 25 slowest unit tests
15
+ Each list starts with "<category>: <n> tests, total <s> s, the <k> slowest:" (-n sets k, default 10).
16
+ Exit 1 when a test or its step fails (the lists still come first), 2 on a usage error or a category this repository does not have.`;
15
17
  const DEFAULT_COUNT = 10;
16
18
  export const RESULTS_FOLDER = ".artifacts/slow-tests";
17
- const SECONDS_PER_MINUTE = 60;
18
- const SECONDS_PER_HOUR = 3600;
19
+ const CATEGORIES = {
20
+ dotnet: { step: "dotnet-test", format: "xunit" },
21
+ e2e: { step: "e2e", format: "playwright" },
22
+ unit: { step: "unit-tests", format: "vitest" },
23
+ };
19
24
  export function parseSlowTests(args) {
20
- if (args.length === 0)
21
- return DEFAULT_COUNT;
22
- const [flag, count, ...rest] = args;
23
- if (flag !== "-n" || count === undefined || rest.length > 0 || !/^[1-9]\d*$/.test(count))
24
- throw new UsageError(SLOW_TESTS_USAGE);
25
- return Number(count);
26
- }
27
- const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
28
- function unescaped(value) {
29
- return value.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|(\w+));/g, (entity, decimal, hex, named) => {
30
- if (decimal !== undefined)
31
- return String.fromCodePoint(Number(decimal));
32
- if (hex !== undefined)
33
- return String.fromCodePoint(parseInt(hex, 16));
34
- return ENTITIES[named ?? ""] ?? entity;
35
- });
36
- }
37
- function seconds(duration) {
38
- const [hours = "0", minutes = "0", rest = "0"] = duration.split(":");
39
- return Number(hours) * SECONDS_PER_HOUR + Number(minutes) * SECONDS_PER_MINUTE + Number(rest);
40
- }
41
- const RESULT_TAG = /<[\w.-]*:?[\w.-]*UnitTestResult((?:\s+[\w:.-]+="[^"]*")*)\s*\/?>/g;
42
- const ATTRIBUTE = /([\w:.-]+)="([^"]*)"/g;
43
- export function parseTrx(text) {
44
- return Array.from(text.matchAll(RESULT_TAG), (tag) => {
45
- const attributes = new Map(Array.from((tag[1] ?? "").matchAll(ATTRIBUTE), (attribute) => [attribute[1], attribute[2]]));
46
- return { duration: attributes.get("duration"), name: attributes.get("testName") };
47
- }).flatMap(({ duration, name }) => duration === undefined || duration === "" || name === undefined ? [] : [{ seconds: seconds(duration), name: unescaped(name) }]);
25
+ let category = null;
26
+ let count = DEFAULT_COUNT;
27
+ for (let index = 0; index < args.length; index++) {
28
+ const argument = args[index] ?? "";
29
+ if (argument === "-n") {
30
+ const value = args[++index];
31
+ if (value === undefined || !/^[1-9]\d*$/.test(value))
32
+ throw new UsageError(SLOW_TESTS_USAGE);
33
+ count = Number(value);
34
+ }
35
+ else if (category === null && Object.hasOwn(CATEGORIES, argument)) {
36
+ category = argument;
37
+ }
38
+ else {
39
+ throw new UsageError(SLOW_TESTS_USAGE);
40
+ }
41
+ }
42
+ return { category, count };
48
43
  }
49
- export function slowest(times, count) {
44
+ export function slowest(category, times, count) {
50
45
  const sorted = [...times].sort((first, second) => second.seconds - first.seconds);
46
+ const total = sorted.reduce((sum, time) => sum + time.seconds, 0);
51
47
  return [
52
- `${sorted.length} tests, the ${Math.min(count, sorted.length)} slowest:`,
48
+ `${category}: ${sorted.length} tests, total ${total.toFixed(1)} s, the ${Math.min(count, sorted.length)} slowest:`,
53
49
  ...sorted.slice(0, count).map((time) => `${time.seconds.toFixed(2).padStart(7)} s ${time.name}`),
54
50
  ];
55
51
  }
56
- function solutionOf(settings) {
57
- const directory = path.join(settings.root, settings.dotnetDirectory ?? "");
58
- const found = readdirSync(directory)
59
- .filter((file) => file.endsWith(".slnx") || file.endsWith(".sln"))
60
- .sort();
61
- const [solution] = found;
62
- if (solution !== undefined && found.length === 1)
63
- return path.join(directory, solution);
64
- throw new Failure(found.length === 0
65
- ? `suwgate dev slow-tests: no .slnx or .sln in ${directory}: set directories.dotnet in suwgate.yml to the folder of the solution`
66
- : `suwgate dev slow-tests: ${found.length} solutions in ${directory} (${found.join(", ")}): keep one, or point directories.dotnet at the folder of the one to run`, 2);
52
+ function chosenCategories(category, available) {
53
+ const present = Object.entries(CATEGORIES).filter(([, found]) => available.includes(found.step));
54
+ const names = present.map(([name]) => name);
55
+ const has = names.length === 0 ? "none of dotnet, e2e, unit" : names.join(", ");
56
+ if (category === null) {
57
+ if (present.length === 0)
58
+ throw new Failure(`suwgate dev slow-tests: this repository has no test steps to measure: ${has}`, 2);
59
+ return present;
60
+ }
61
+ if (!names.includes(category)) {
62
+ throw new Failure(`suwgate dev slow-tests: this repository has no ${category} tests (step ${CATEGORIES[category]?.step ?? ""}); it has: ${has}`, 2);
63
+ }
64
+ return present.filter(([name]) => name === category);
67
65
  }
68
- export async function runSlowTests(count, environment) {
69
- const { settings, io } = environment;
70
- const solution = solutionOf(settings);
71
- const checkout = checkoutEnvOf(settings, environment.env);
72
- if (checkout.notice !== null)
73
- io.err(checkout.notice);
74
- const variables = Object.fromEntries(checkout.variables);
75
- const exec = (argv, options) => environment.exec(argv, { ...options, env: { ...variables, ...options?.env } });
76
- const results = path.join(settings.root, RESULTS_FOLDER);
77
- rmSync(results, { recursive: true, force: true });
78
- mkdirSync(results, { recursive: true });
79
- const database = await runDb({ kind: "up" }, { settings, exec, io: { out: () => undefined, err: (text) => io.err(text) }, interactive: false, ask: () => Promise.resolve("") });
80
- if (database !== 0)
81
- throw new Failure(`suwgate dev slow-tests: the database did not start (exit ${database})`);
82
- const built = await exec(["dotnet", "build", solution, "--nologo", "-v", "q"], { capture: true });
83
- if (built.status !== 0) {
84
- io.err(built.stdout);
85
- throw new Failure(`suwgate dev slow-tests: dotnet build of ${solution} failed (exit ${built.status}), its output is above`);
66
+ export async function runSlowTests(parsed, environment) {
67
+ const { io, steps } = environment;
68
+ const failed = [];
69
+ for (const [name, found] of chosenCategories(parsed.category, steps.available)) {
70
+ const folder = path.join(steps.root, RESULTS_FOLDER, name);
71
+ rmSync(folder, { recursive: true, force: true });
72
+ mkdirSync(folder, { recursive: true });
73
+ io.err(`suwgate dev slow-tests: running the ${found.step} step for ${name}, its reports go to ${folder}`);
74
+ const ran = await steps.run(found.step, folder);
75
+ const times = steps.times(found.format, found.step, folder);
76
+ if (times !== null)
77
+ io.out(`${slowest(name, times, parsed.count).join("\n")}\n`);
78
+ if (ran.exitCode === 0 && times === null) {
79
+ io.err(ran.text);
80
+ io.err(`suwgate dev slow-tests: the ${found.step} step left no test report, so it ran no ${name} tests (its output is above)`);
81
+ }
82
+ else if (ran.exitCode !== 0) {
83
+ io.err(ran.text);
84
+ failed.push(name);
85
+ }
86
86
  }
87
- const log = path.join(results, "run.log");
88
- const tested = await exec(["dotnet", "test", "--solution", solution, "--no-build", "--no-progress", "--report-xunit-trx", "--results-directory", results], { capture: true, quiet: true });
89
- writeFileSync(log, tested.stdout);
90
- const times = readdirSync(results)
91
- .filter((file) => file.endsWith(".trx"))
92
- .flatMap((file) => parseTrx(readFileSync(path.join(results, file), "utf8")));
93
- for (const line of slowest(times, count))
94
- io.out(line);
95
- if (tested.status !== 0)
96
- throw new Failure(`suwgate dev slow-tests: a test failed; the run's output is in ${log}`);
87
+ if (failed.length > 0)
88
+ throw new Failure(`suwgate dev slow-tests: ${failed.join(", ")} failed, the output of the step is above`);
97
89
  return 0;
98
90
  }
@@ -12,6 +12,7 @@ export interface StepOptions {
12
12
  only: boolean;
13
13
  args: readonly string[];
14
14
  verbose: boolean;
15
+ runFolder?: string;
15
16
  env: NodeJS.ProcessEnv;
16
17
  catalog: Catalog;
17
18
  }
@@ -67,8 +67,12 @@ async function run(command, prepared, options) {
67
67
  ...(options.target === undefined ? {} : { target: options.target }),
68
68
  });
69
69
  const began = performance.now();
70
- const runFolder = mkdtempSync(path.join(tmpdir(), "suwgate-run-"));
71
- const results = await runSteps(steps, { ...options.env, SUWGATE_ROOT: root, SUWGATE_QUICK: options.quick ? "1" : "", SUWGATE_RUN: runFolder }, prepared.stepLimit).finally(() => rmSync(runFolder, { recursive: true, force: true }));
70
+ const keep = options.runFolder !== undefined;
71
+ const runFolder = options.runFolder ?? mkdtempSync(path.join(tmpdir(), "suwgate-run-"));
72
+ const results = await runSteps(steps, { ...options.env, SUWGATE_ROOT: root, SUWGATE_QUICK: options.quick ? "1" : "", SUWGATE_RUN: runFolder }, prepared.stepLimit).finally(() => {
73
+ if (!keep)
74
+ rmSync(runFolder, { recursive: true, force: true });
75
+ });
72
76
  const totalSeconds = Math.round((performance.now() - began) / 1000);
73
77
  const { text, passed } = report({
74
78
  results,
@@ -79,6 +83,7 @@ async function run(command, prepared, options) {
79
83
  exceptions: config.exceptions.length,
80
84
  mergedOnce: merged.length,
81
85
  verbose: options.verbose,
86
+ ...(options.verbose && options.target !== undefined ? { passedLogOf: options.target.id } : {}),
82
87
  });
83
88
  return { exitCode: passed ? 0 : 1, text };
84
89
  }
@@ -125,5 +130,6 @@ export async function step(options) {
125
130
  env: options.env,
126
131
  catalog: options.catalog,
127
132
  target: { id: options.id, only: options.only, args: options.args },
133
+ ...(options.runFolder === undefined ? {} : { runFolder: options.runFolder }),
128
134
  });
129
135
  }
package/dist/gate/plan.js CHANGED
@@ -127,7 +127,7 @@ export function plan(input) {
127
127
  const line = typeof run === "string" ? run : run(stepContext(input, cwd));
128
128
  const missing = (step.needs ?? []).filter((tool) => !onPath(tool));
129
129
  if (line === null) {
130
- planned.push({ ...base, inline: () => Promise.resolve({ passed: true, log: "nothing to check" }) });
130
+ planned.push({ ...base, inline: () => Promise.resolve({ passed: true, log: "" }) });
131
131
  }
132
132
  else if (typeof line !== "string") {
133
133
  planned.push({ ...base, skipped: { reason: line.skip, byConfig: false } });
@@ -8,6 +8,7 @@ export interface ReportInput {
8
8
  exceptions: number;
9
9
  mergedOnce?: number;
10
10
  verbose: boolean;
11
+ passedLogOf?: string;
11
12
  }
12
13
  export interface Report {
13
14
  text: string;
@@ -9,7 +9,7 @@ function shownLog(log, all) {
9
9
  return { text: lines.slice(-FAILURE_LINES).join("\n"), heading: `last ${FAILURE_LINES} of ${lines.length} lines, --verbose shows all` };
10
10
  }
11
11
  export function report(input) {
12
- const failures = [];
12
+ const logs = [];
13
13
  const rows = [];
14
14
  const notVerified = [];
15
15
  const skippedByConfig = [];
@@ -35,12 +35,17 @@ export function report(input) {
35
35
  failed = true;
36
36
  rows.push(row("FAIL", result.seconds, step.title));
37
37
  const shown = shownLog(result.log, input.verbose);
38
- failures.push(`==================== failed: ${step.title} (${shown.heading}) ====================\n${shown.text}`);
38
+ logs.push(`==================== failed: ${step.title} (${shown.heading}) ====================\n${shown.text}`);
39
39
  }
40
40
  else {
41
41
  passedCount++;
42
- if (input.verbose)
42
+ if (input.verbose) {
43
43
  rows.push(row("PASS", result.seconds, step.title));
44
+ if (input.passedLogOf === step.id && result.log.trim() !== "") {
45
+ const shown = shownLog(result.log, true);
46
+ logs.push(`==================== passed: ${step.title} (${shown.heading}) ====================\n${shown.text}`);
47
+ }
48
+ }
44
49
  }
45
50
  }
46
51
  if (input.quickLimit !== null && input.totalSeconds > input.quickLimit) {
@@ -57,8 +62,8 @@ export function report(input) {
57
62
  ...(skippedByConfig.length > 0 ? [`skipped in suwgate.yml: ${skippedByConfig.join(", ")}`] : []),
58
63
  ].join("; ");
59
64
  const lines = [];
60
- if (failures.length > 0)
61
- lines.push("", failures.join("\n\n"));
65
+ if (logs.length > 0)
66
+ lines.push("", logs.join("\n\n"));
62
67
  const clean = !failed && notVerified.length === 0 && skippedByConfig.length === 0;
63
68
  if (clean && !input.verbose) {
64
69
  lines.push(`PASS ${input.command}: all ${passedCount} steps in ${input.totalSeconds}s (${extras})`);
@@ -3,7 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { CRITERIA_FILE, criteriaConfig, criteriaExtras } from "./criteria.js";
5
5
  import { excludedTraits } from "./dotnet.js";
6
- import { readRun } from "./reports.js";
6
+ import { readRun, REPORT_FILE } from "./reports.js";
7
7
  import { quoted, read, settingsOf, tracked, verdictCommand } from "./shell.js";
8
8
  const CRITERIA_RAN_SETTINGS = {
9
9
  type: "object",
@@ -24,7 +24,6 @@ const REPORTED = {
24
24
  "visual test (playwright)": { step: "visual", format: "playwright" },
25
25
  "consumer test (playwright)": { step: "consumer-app", format: "playwright" },
26
26
  };
27
- const REPORT_FILE = { vitest: "vitest.json", playwright: "playwright.json", xunit: "results" };
28
27
  const ACCEPTANCE = /data-role="acceptance"[\s\S]*?(?=data-role="|$)/g;
29
28
  const CODE = /<code>([A-Za-z][\w.]*(?:-[\w.]+)*-\d+)<\/code>/g;
30
29
  export function criterionIds(spec) {
@@ -1,11 +1,18 @@
1
1
  export type ReportFormat = "vitest" | "playwright" | "xunit";
2
+ export declare const REPORT_FILE: Readonly<Record<ReportFormat, string>>;
3
+ export declare function reportLocation(run: string, step: string, format: ReportFormat): string;
2
4
  export interface TestRun {
3
5
  executed: number;
4
6
  passed: string[];
5
7
  }
8
+ export interface TestTime {
9
+ seconds: number;
10
+ name: string;
11
+ }
6
12
  interface VitestAssertion {
7
13
  fullName?: string;
8
14
  status?: string;
15
+ duration?: number | null;
9
16
  }
10
17
  interface VitestReport {
11
18
  testResults?: {
@@ -16,6 +23,9 @@ interface PlaywrightSpec {
16
23
  title?: string;
17
24
  tests?: {
18
25
  status?: string;
26
+ results?: {
27
+ duration?: number;
28
+ }[];
19
29
  }[];
20
30
  }
21
31
  interface PlaywrightSuite {
@@ -30,6 +40,10 @@ interface PlaywrightReport {
30
40
  export declare function vitestRun(report: VitestReport): TestRun;
31
41
  export declare function playwrightRun(report: PlaywrightReport): TestRun;
32
42
  export declare function xunitRun(xml: string): TestRun;
43
+ export declare function vitestTimes(report: VitestReport): TestTime[];
44
+ export declare function playwrightTimes(report: PlaywrightReport): TestTime[];
45
+ export declare function xunitTimes(xml: string): TestTime[];
33
46
  export declare function files(location: string, extension: string): string[];
34
47
  export declare function readRun(format: ReportFormat, location: string): TestRun | null;
48
+ export declare function readTimes(format: ReportFormat, location: string): TestTime[] | null;
35
49
  export {};
@@ -1,5 +1,13 @@
1
1
  import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
+ export const REPORT_FILE = {
4
+ vitest: "vitest.json",
5
+ playwright: "playwright.json",
6
+ xunit: "results",
7
+ };
8
+ export function reportLocation(run, step, format) {
9
+ return path.join(run, step, REPORT_FILE[format]);
10
+ }
3
11
  const XUNIT_TEST = /<test\b([^>]*?)(?:\/>|>([\s\S]*?)<\/test>)/g;
4
12
  const CRITERION_TRAIT = /<trait\s+name="criterion"\s+value="([^"]*)"/g;
5
13
  export function vitestRun(report) {
@@ -15,6 +23,7 @@ function specsOf(suite, titles) {
15
23
  ...(suite.specs ?? []).map((spec) => ({
16
24
  title: [...own, spec.title ?? ""].filter((title) => title !== "").join(" "),
17
25
  statuses: (spec.tests ?? []).map((test) => test.status ?? ""),
26
+ milliseconds: (spec.tests ?? []).flatMap((test) => test.results ?? []).reduce((sum, result) => sum + (result.duration ?? 0), 0),
18
27
  })),
19
28
  ...(suite.suites ?? []).flatMap((inner) => specsOf(inner, own)),
20
29
  ];
@@ -38,6 +47,37 @@ export function xunitRun(xml) {
38
47
  passed: tests.filter((test) => test.result === "Pass").flatMap((test) => test.criteria.map((id) => `${id}:`)),
39
48
  };
40
49
  }
50
+ const MILLISECONDS = 1000;
51
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
52
+ function unescaped(value) {
53
+ return value.replace(/&(?:#(\d+)|#x([0-9a-fA-F]+)|(\w+));/g, (entity, decimal, hex, named) => {
54
+ if (decimal !== undefined)
55
+ return String.fromCodePoint(Number(decimal));
56
+ if (hex !== undefined)
57
+ return String.fromCodePoint(parseInt(hex, 16));
58
+ return ENTITIES[named ?? ""] ?? entity;
59
+ });
60
+ }
61
+ export function vitestTimes(report) {
62
+ return (report.testResults ?? [])
63
+ .flatMap((file) => file.assertionResults ?? [])
64
+ .filter((assertion) => assertion.status === "passed" || assertion.status === "failed")
65
+ .map((assertion) => ({ seconds: (assertion.duration ?? 0) / MILLISECONDS, name: assertion.fullName ?? "" }));
66
+ }
67
+ export function playwrightTimes(report) {
68
+ return (report.suites ?? [])
69
+ .flatMap((suite) => specsOf(suite, []))
70
+ .filter((spec) => spec.statuses.some((status) => status !== "skipped"))
71
+ .map((spec) => ({ seconds: spec.milliseconds / MILLISECONDS, name: spec.title }));
72
+ }
73
+ export function xunitTimes(xml) {
74
+ return Array.from(xml.matchAll(XUNIT_TEST), (tag) => {
75
+ const attribute = (name) => new RegExp(`\\b${name}="([^"]*)"`).exec(tag[1] ?? "")?.[1];
76
+ return { name: attribute("name"), time: attribute("time"), result: attribute("result") };
77
+ }).flatMap(({ name, time, result }) => name === undefined || time === undefined || (result !== "Pass" && result !== "Fail")
78
+ ? []
79
+ : [{ seconds: Number(time), name: unescaped(name) }]);
80
+ }
41
81
  export function files(location, extension) {
42
82
  if (!existsSync(location))
43
83
  return [];
@@ -58,3 +98,13 @@ export function readRun(format, location) {
58
98
  const report = JSON.parse(readFileSync(location, "utf8"));
59
99
  return format === "vitest" ? vitestRun(report) : playwrightRun(report);
60
100
  }
101
+ export function readTimes(format, location) {
102
+ if (format === "xunit") {
103
+ const reports = files(location, ".xml");
104
+ return reports.length === 0 ? null : reports.flatMap((report) => xunitTimes(readFileSync(report, "utf8")));
105
+ }
106
+ if (!existsSync(location))
107
+ return null;
108
+ const report = JSON.parse(readFileSync(location, "utf8"));
109
+ return format === "vitest" ? vitestTimes(report) : playwrightTimes(report);
110
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maniumek/suwgate",
3
- "version": "0.14.0",
3
+ "version": "0.15.0",
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",