@maniumek/suwgate 0.5.2 → 0.7.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
@@ -47,7 +47,7 @@ exceptions:
47
47
  across the board overrides it with `SUWGATE_QUICK_LIMIT=<seconds>`.
48
48
  - `exceptions` let one target through one guard, always with a `reason`; `suwgate check` counts them in its report, and an
49
49
  exception that no longer matches anything fails the gate until it is deleted. Two optional fields, for the repository guards
50
- (the .NET packages match by target only):
50
+ and the .NET guards alike:
51
51
  - `message` narrows it to the target's findings whose message contains that text, so a second finding in the same file still
52
52
  fails: `{ guard: no-raw-colors, target: Myapp.Web/src/mail.tsx, message: "#1e66f5", reason: … }`.
53
53
  - `once: true` makes it a one-time exception, for a finding that goes away once the change is on master, such as an
@@ -257,15 +257,16 @@ the solution, `layers.json`, the sources and the migrations itself, and takes fr
257
257
  - `test-timing` (`dotnet`, `web`, `library`): no test measures, sleeps on, waits for or limits real time, because a test that
258
258
  waits on the clock flakes on a slow machine and a speed promise, in milliseconds or in steps counted instead of them, does not
259
259
  belong on the gate. It reads the `.cs` files of the `*.Tests` and `*.Testing` projects (`Stopwatch`, `GetTimestamp`,
260
- `GetElapsedTime`, `TickCount`, `DateTime.Now`, `UtcNow` and `Today`, `Thread.Sleep`, `Task.Delay`, `Timeout =` in an attribute),
260
+ `GetElapsedTime`, `TickCount`, `DateTime.Now`, `UtcNow` and `Today`, `TimeProvider.System`, `Thread.Sleep`, `Task.Delay`, `Timeout =` in an attribute,
261
+ a `TimeSpan.From…` or `new TimeSpan(…)` handed to a constructor that gets no `TimeProvider`),
261
262
  and the `*.test`, `*.spec`, `*.e2e`, `*.visual`
262
263
  and `*.stories` files and the helpers of an `e2e/` folder (`performance.now`, `Date.now()` in a subtraction, `setTimeout`,
263
264
  `sleep(<n>)`, `waitForTimeout`, `interruptAfterTimeLimit`, and `timeout: <n>` in a Vitest file, such as the options of `it`, `test`
264
265
  or `describe`). It lets through a call that is
265
- handed a `TimeProvider` (a `FakeTimeProvider` in the tests), `Task.Delay` inside a `while`, `for`, `foreach` or `do` loop (a poll)
266
+ handed a `TimeProvider` (a `FakeTimeProvider` in the tests; `TimeProvider.System` is the real clock and fails), `Task.Delay` inside a `while`, `for`, `foreach` or `do` loop (a poll)
266
267
  or with `Timeout.Infinite`, the timers and the clock of a file that calls `vi.useFakeTimers()`, Playwright's auto-waiting
267
268
  `expect` with its own `timeout`, a ceiling against a hang (`CancelAfter`, `new CancellationTokenSource(<delay>)`,
268
- `WaitAsync(<TimeSpan>)`, and the `timeout` option of a Vitest wait for an event: `vi.waitFor`, `vi.waitUntil`, `expect.poll`,
269
+ `WaitAsync(<TimeSpan>)`, an `HttpClient`'s `Timeout`, and the `timeout` option of a Vitest wait for an event: `vi.waitFor`, `vi.waitUntil`, `expect.poll`,
269
270
  Testing Library's `waitFor`, `findBy*` and `findAllBy*`; the test waits for the event and fails fast, with its name, if it never
270
271
  comes: a ceiling, not a speed promise), and the tools' configs
271
272
  (`playwright.config.ts`), whose ceilings stop a hang.
package/dist/dev/logs.js CHANGED
@@ -1,4 +1,4 @@
1
- import { readdirSync, readFileSync, statSync } from "node:fs";
1
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parseArgs } from "node:util";
4
4
  import { composeBase } from "./db.js";
@@ -106,6 +106,42 @@ export function newestLog(directory) {
106
106
  const files = names.map((name) => ({ file: path.join(directory, name), time: statSync(path.join(directory, name)).mtimeMs }));
107
107
  return files.sort((left, right) => right.time - left.time)[0]?.file ?? null;
108
108
  }
109
+ const RECIPE = /^@?([A-Za-z_][\w-]*)(?:\s[^:]*)?:(?!=)/;
110
+ function justFiles(root) {
111
+ const entries = (() => {
112
+ try {
113
+ return readdirSync(root, { withFileTypes: true });
114
+ }
115
+ catch {
116
+ return [];
117
+ }
118
+ })();
119
+ return entries.flatMap((entry) => {
120
+ if (entry.isFile() && entry.name === "justfile")
121
+ return [{ file: path.join(root, entry.name), module: "" }];
122
+ if (entry.isFile() && entry.name.endsWith(".just"))
123
+ return [{ file: path.join(root, entry.name), module: entry.name.replace(/\.just$/, "") }];
124
+ const nested = path.join(root, entry.name, "mod.just");
125
+ return entry.isDirectory() && existsSync(nested) ? [{ file: nested, module: entry.name }] : [];
126
+ });
127
+ }
128
+ function recipeRunning(root, command) {
129
+ for (const { file, module } of justFiles(root)) {
130
+ let recipe;
131
+ for (const text of readFileSync(file, "utf8").split("\n")) {
132
+ if (!/^\s/.test(text))
133
+ recipe = text.trim() === "" ? recipe : RECIPE.exec(text)?.[1];
134
+ else if (recipe !== undefined && command.test(text))
135
+ return `just ${module === "" ? "" : `${module} `}${recipe}`;
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+ function startHint(root) {
141
+ const stack = recipeRunning(root, /\bdev\s+tmux\s+start\b/) ?? "suwgate dev tmux start";
142
+ const server = recipeRunning(root, /\bdev\s+server\b/) ?? "suwgate dev server";
143
+ return `Start the server with \`${stack}\` (or \`${server}\`)`;
144
+ }
109
145
  export async function runLogs(command, settings, exec, io, cwd) {
110
146
  let sourceName;
111
147
  let content;
@@ -118,7 +154,7 @@ export async function runLogs(command, settings, exec, io, cwd) {
118
154
  else {
119
155
  const file = command.file === "" ? newestLog(path.dirname(path.join(settings.root, settings.logFile))) : path.resolve(cwd, command.file);
120
156
  if (file === null) {
121
- throw new Failure("suwgate dev logs: no log file yet. Start the server with `suwgate dev tmux start` (or `suwgate dev server`), or run the browser tests (they write the logs), or read the container stack with --compose.");
157
+ throw new Failure(`suwgate dev logs: no log file yet. ${startHint(settings.root)}, or run the browser tests (they write the logs), or read the container stack with --compose.`);
122
158
  }
123
159
  try {
124
160
  content = readFileSync(file, "utf8");
@@ -29,6 +29,7 @@ export interface DevSettings {
29
29
  psql: string | null;
30
30
  };
31
31
  serverProject: string | null;
32
+ dotnetDirectory: string | null;
32
33
  webDirectory: string | null;
33
34
  logFile: string;
34
35
  smokeChecks: SmokeCheck[];
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync } from "node:fs";
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { parse } from "yaml";
4
4
  import { Failure } from "./process.js";
@@ -128,7 +128,8 @@ export function resolveSettings(raw, directories, root) {
128
128
  up: databaseRaw["up"] === undefined ? null : text(databaseRaw, "up", "dev.database", "", problems),
129
129
  psql: databaseRaw["psql"] === undefined ? null : text(databaseRaw, "psql", "dev.database", "", problems),
130
130
  },
131
- serverProject: typeof serverRaw["project"] === "string" ? serverRaw["project"] : stringOrNull(directories["dotnet"]),
131
+ serverProject: serverRaw["project"] === undefined ? null : text(serverRaw, "project", "dev.server", "", problems),
132
+ dotnetDirectory: stringOrNull(directories["dotnet"]),
132
133
  webDirectory: stringOrNull(directories["web"]),
133
134
  logFile: text(serverRaw, "logFile", "dev.server", ".artifacts/logs/server.jsonl", problems),
134
135
  smokeChecks: smokeChecks(top["smoke"], problems),
@@ -149,11 +150,35 @@ export function loadSettings(root) {
149
150
  const directories = typeof data["directories"] === "object" && data["directories"] !== null ? data["directories"] : {};
150
151
  return resolveSettings(data["dev"], directories, root);
151
152
  }
152
- export function needServerProject(settings) {
153
- if (settings.serverProject === null) {
154
- throw new Failure("no server project: set directories.dotnet (or dev.server.project) in suwgate.yml to the folder of the server's .csproj", 2);
153
+ const WEB_SDK = /\bSdk\s*=\s*"Microsoft\.NET\.Sdk\.Web[/"]|<Sdk\s+Name\s*=\s*"Microsoft\.NET\.Sdk\.Web"/;
154
+ const NOT_SOURCES = new Set(["node_modules", "bin", "obj"]);
155
+ function webProjects(root, folder) {
156
+ let entries;
157
+ try {
158
+ entries = readdirSync(path.join(root, folder), { withFileTypes: true });
159
+ }
160
+ catch {
161
+ return [];
155
162
  }
156
- return settings.serverProject;
163
+ return entries.flatMap((entry) => {
164
+ const relative = folder === "" ? entry.name : `${folder}/${entry.name}`;
165
+ if (entry.isDirectory())
166
+ return entry.name.startsWith(".") || NOT_SOURCES.has(entry.name) ? [] : webProjects(root, relative);
167
+ return entry.name.endsWith(".csproj") && WEB_SDK.test(readFileSync(path.join(root, relative), "utf8")) ? [relative] : [];
168
+ });
169
+ }
170
+ export function needServerProject(settings) {
171
+ if (settings.serverProject !== null)
172
+ return settings.serverProject;
173
+ const under = settings.dotnetDirectory ?? "";
174
+ const found = webProjects(settings.root, under.replace(/^\.\/?|\/+$/g, "")).sort();
175
+ const [project] = found;
176
+ if (project !== undefined && found.length === 1)
177
+ return path.posix.dirname(project);
178
+ const where = under === "" ? "the repository" : under;
179
+ throw new Failure(found.length === 0
180
+ ? `no server project: no .csproj in ${where} uses Sdk="Microsoft.NET.Sdk.Web"; set dev.server.project in suwgate.yml to the folder of the server's .csproj`
181
+ : `${found.length} server projects use Sdk="Microsoft.NET.Sdk.Web" (${found.join(", ")}): set dev.server.project in suwgate.yml to the folder of the one suwgate dev server runs`, 2);
157
182
  }
158
183
  export function needWebDirectory(settings) {
159
184
  if (settings.webDirectory === null) {
@@ -1,5 +1,5 @@
1
1
  import { resolveSettings } from "./settings.js";
2
- export function settingsOf(raw = { name: "myapp" }, directories = { dotnet: "Myapp.Server", web: "Myapp.Web" }) {
2
+ export function settingsOf(raw = { name: "myapp", server: { project: "Myapp.Server" } }, directories = { web: "Myapp.Web" }) {
3
3
  return resolveSettings(raw, directories, "/repo");
4
4
  }
5
5
  export function fakeExec(answer = () => ({})) {
@@ -71,9 +71,6 @@ function checkExceptions(raw, catalog, problem) {
71
71
  problem(where, `no guard "${exception.guard}": the guards are ${catalog.guards.map((guard) => guard.id).join(", ")} (and architecture/*, database/* of the .NET packages)`);
72
72
  }
73
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
- }
77
74
  const prefix = Object.keys(DOTNET_GUARD_PREFIXES).find((candidate) => exception.guard.startsWith(candidate)) ?? "";
78
75
  const needed = DOTNET_GUARD_PREFIXES[prefix];
79
76
  if (needed !== undefined && !raw.profiles.includes(needed)) {
@@ -59,6 +59,9 @@ export async function runGuards(input) {
59
59
  lines.push(`${guard.id}: ${done.target}: the one-time exception is on master now and excepts nothing: delete it from ${CONFIG_FILE}`);
60
60
  }
61
61
  }
62
+ for (const done of (input.merged ?? []).filter((exception) => !input.guards.some((guard) => guard.id === exception.guard))) {
63
+ lines.push(`${done.guard}: ${done.target}: the one-time exception is on master now and excepts nothing: delete it from ${CONFIG_FILE}`);
64
+ }
62
65
  const header = `${input.guards.length} guard${input.guards.length === 1 ? "" : "s"}, ${excepted} findings excepted in ${CONFIG_FILE}`;
63
66
  return { passed: !failed, log: [header, ...lines].join("\n") };
64
67
  }
@@ -11,13 +11,20 @@ const MEASURES = "measures real time";
11
11
  const READS_CLOCK = "reads the real clock";
12
12
  const WAITS = "waits on real time";
13
13
  const LIMITS = "limits the test in real time";
14
+ const REAL_CLOCK_FIX = "a test runs on a FakeTimeProvider (Microsoft.Extensions.Time.Testing), never on the real clock: hand the code a new FakeTimeProvider() and move time with its Advance or SetUtcNow";
14
15
  const CSHARP_RULES = [
15
16
  { pattern: /\b(?<found>Stopwatch|GetElapsedTime|GetTimestamp|TickCount64|TickCount)\b/dg, verb: MEASURES },
16
17
  { pattern: /\b(?<found>(DateTime|DateTimeOffset)\.(Now|UtcNow|Today))\b/dg, verb: READS_CLOCK },
17
18
  { pattern: /\b(?<found>Thread\.Sleep)\b/dg, verb: "sleeps on real time" },
18
19
  { pattern: /\[[^[\]]*?\b(?<found>Timeout\s*=)(?!=)/dg, verb: LIMITS },
20
+ { pattern: /\b(?<found>TimeProvider\.System)\b/dg, verb: "is the real clock, not a FakeTimeProvider", fix: REAL_CLOCK_FIX },
19
21
  ];
20
- const onFakeClock = (call) => call.args.slice(1).some((arg) => /provider|clock/i.test(arg));
22
+ const FAKE_CLOCK = /provider|clock/i;
23
+ const onFakeClock = (call) => call.args.slice(1).some((arg) => FAKE_CLOCK.test(arg));
24
+ const CONSTRUCTED = /\bnew\s+(?<type>[A-Za-z_][\w.]*)\s*(?:<[^<>()]*>)?\s*\(|\bnew\s*\(/g;
25
+ const INTERVAL = /^(?:\w+\s*:\s*)?(?:TimeSpan\.From\w+\s*\(|new\s+TimeSpan\s*\()/;
26
+ const NOT_A_WAIT = new Set(["CancellationTokenSource", "DateTimeOffset", "TimeSpan"]);
27
+ const DECLARED_TYPE = /\b(?<type>[A-Za-z_]\w*)\s*(?:<[^<>()]*>)?\s+[A-Za-z_]\w*\s*=\s*$/;
21
28
  const CSHARP_CALLS = [
22
29
  {
23
30
  pattern: /\bTask\.Delay\s*\(/g,
@@ -179,19 +186,39 @@ function argumentsOf(text, open) {
179
186
  }
180
187
  return args.filter((arg) => arg !== "");
181
188
  }
182
- function finding(file, line, found, verb) {
183
- return { target: file, line, message: `${found.replace(/\s+/g, " ")} ${verb}: ${FIX}` };
189
+ function finding(file, line, found, verb, fix = FIX) {
190
+ return { target: file, line, message: `${found.replace(/\s+/g, " ")} ${verb}: ${fix}` };
191
+ }
192
+ function constructedType(text, match) {
193
+ const named = match.groups?.["type"];
194
+ if (named !== undefined)
195
+ return named.split(".").at(-1) ?? named;
196
+ return DECLARED_TYPE.exec(text.slice(0, match.index))?.groups?.["type"] ?? "";
197
+ }
198
+ function constructorFindings(file, text) {
199
+ return [...text.matchAll(CONSTRUCTED)].flatMap((match) => {
200
+ const type = constructedType(text, match);
201
+ if (NOT_A_WAIT.has(type))
202
+ return [];
203
+ const args = argumentsOf(text, match.index + match[0].length - 1);
204
+ const interval = args.find((arg) => INTERVAL.test(arg));
205
+ if (interval === undefined || args.some((arg) => FAKE_CLOCK.test(arg)))
206
+ return [];
207
+ return [
208
+ finding(file, lineAt(text, match.index), `${interval.replace(/^\w+\s*:\s*/, "")} handed to new ${type}(…)`, "gives the code a real-time interval without a TimeProvider", `${FIX}; a ceiling against a hang stays allowed (new CancellationTokenSource(<delay>), CancelAfter, WaitAsync(<TimeSpan>), an HttpClient's Timeout)`),
209
+ ];
210
+ });
184
211
  }
185
212
  function csharpFindings(file, source) {
186
213
  const text = codeOnly(source);
187
214
  const plain = CSHARP_RULES.flatMap((rule) => [...text.matchAll(rule.pattern)].flatMap((match) => {
188
215
  const found = match.indices?.groups?.["found"];
189
- return found === undefined ? [] : [finding(file, lineAt(text, found[0]), text.slice(found[0], found[1]), rule.verb)];
216
+ return found === undefined ? [] : [finding(file, lineAt(text, found[0]), text.slice(found[0], found[1]), rule.verb, rule.fix)];
190
217
  }));
191
218
  const calls = CSHARP_CALLS.flatMap((rule) => [...text.matchAll(rule.pattern)]
192
219
  .filter((match) => !rule.allowed({ text, at: match.index, args: argumentsOf(text, match.index + match[0].length - 1) }))
193
220
  .map((match) => finding(file, lineAt(text, match.index), match[0].replace(/^\.|\s*\($/g, ""), rule.verb)));
194
- return [...plain, ...calls].sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
221
+ return [...plain, ...calls, ...constructorFindings(file, text)].sort((a, b) => (a.line ?? 0) - (b.line ?? 0));
195
222
  }
196
223
  function webFindings(file, source) {
197
224
  const faked = FAKE_TIMERS.test(source);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maniumek/suwgate",
3
- "version": "0.5.2",
3
+ "version": "0.7.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",
@@ -137,11 +137,11 @@
137
137
  "message": {
138
138
  "type": "string",
139
139
  "minLength": 1,
140
- "description": "Narrows the exception to the target's findings whose message contains this text; without it, every finding of the target is excepted. Repository guards only."
140
+ "description": "Narrows the exception to the target's findings whose message contains this text; without it, every finding of the target is excepted."
141
141
  },
142
142
  "once": {
143
143
  "type": "boolean",
144
- "description": "A one-time exception: it holds only while master's suwgate.yml does not have it yet (on the branch that adds it). After the merge it excepts nothing and is never stale; the report asks to delete it. Repository guards only."
144
+ "description": "A one-time exception: it holds only while master's suwgate.yml does not have it yet (on the branch that adds it). After the merge it excepts nothing and is never stale; the report asks to delete it."
145
145
  }
146
146
  }
147
147
  }
@@ -224,7 +224,7 @@
224
224
  "properties": {
225
225
  "project": {
226
226
  "$ref": "#/$defs/relativePath",
227
- "description": "The folder of the server's .csproj (default directories.dotnet)."
227
+ "description": "The folder of the server's .csproj (default: the folder of the one .csproj on Sdk=\"Microsoft.NET.Sdk.Web\" in directories.dotnet, or in the repository)."
228
228
  },
229
229
  "logFile": {
230
230
  "$ref": "#/$defs/relativePath",