@invariantly/cli 0.0.0-stage → 0.0.3

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/dist/check.js ADDED
@@ -0,0 +1,1247 @@
1
+ import { readdir, readFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { parse } from "yaml";
4
+ import { validateText } from "./validate.js";
5
+ const TEST_FILE = /\.(test|spec)\.(ts|tsx|mts|cts|js|jsx|mjs|cjs)$/;
6
+ const SKIP_DIRS = new Set(["node_modules", "dist", "build", "coverage"]);
7
+ /** Path segments that exclude Python files only (JS discovery is unchanged). */
8
+ const PY_SKIP_DIRS = new Set(["venv", "site-packages"]);
9
+ const MARKER = /\[(INV-[0-9]{2,})\]/g;
10
+ /**
11
+ * Validates the registry, then links every test file under the registry's directory to its rules.
12
+ * Throws only when the registry, a directory or a test file cannot be read (the CLI turns that into exit 2).
13
+ */
14
+ export async function checkFile(file, schema, options = {}) {
15
+ const warnings = [];
16
+ const warn = (warning) => {
17
+ warnings.push(warning);
18
+ options.warn?.(warning.message);
19
+ };
20
+ const text = await readFile(file, "utf8");
21
+ const registry = validateText(text, schema, file);
22
+ const empty = { testFileCount: 0, untested: [], unknownMarkers: [], links: [], warnings };
23
+ if (!registry.ok)
24
+ return { ...registry, ...empty };
25
+ const rules = parse(text).rules;
26
+ const ids = new Set(rules.map((r) => r.id));
27
+ const root = dirname(file);
28
+ const found = await findTestFiles(root);
29
+ let pytest;
30
+ try {
31
+ pytest = await readPytestConfig(root, found.rootFiles);
32
+ }
33
+ catch (error) {
34
+ if (!(error instanceof ConfigError))
35
+ throw error;
36
+ warn({ code: "pytest-config-invalid", message: `${error.message}; Python tests supply no coverage`, path: error.file });
37
+ }
38
+ if (pytest && pytest.ignored.length > 0) {
39
+ warn({
40
+ code: "pytest-option-ignored",
41
+ message: `${pytest.file}: ${pytest.ignored.join(", ")} not evaluated; Python coverage may include tests pytest does not select`,
42
+ path: pytest.file,
43
+ });
44
+ }
45
+ const pyFiles = pytest ? selectPythonFiles(found, pytest) : [];
46
+ const links = [];
47
+ const unknownMarkers = [];
48
+ for (const rel of found.js) {
49
+ const source = await readFile(join(root, rel), "utf8");
50
+ for (const t of findTests(source)) {
51
+ if (t.kind === "test") {
52
+ for (const id of t.markers)
53
+ links.push({ id, file: rel, line: t.line, test: t.name, active: t.active });
54
+ }
55
+ for (const id of t.ownMarkers) {
56
+ if (!ids.has(id))
57
+ unknownMarkers.push({ id, file: rel, line: t.line, test: t.name, active: t.active });
58
+ }
59
+ }
60
+ }
61
+ for (const rel of pyFiles) {
62
+ const scan = scanPytest(await readFile(join(root, rel), "utf8"));
63
+ for (const site of scan.sites) {
64
+ for (const id of site.ids) {
65
+ if (!ids.has(id))
66
+ unknownMarkers.push({ id, file: rel, line: site.line, test: site.name, active: site.active });
67
+ }
68
+ }
69
+ if (scan.fault) {
70
+ const { line, column, message } = scan.fault;
71
+ warn({ code: "lexical-fault", message: `${rel}:${line}:${column}: ${message}; this file supplies no coverage`, path: rel, line });
72
+ continue;
73
+ }
74
+ for (const t of scan.tests) {
75
+ if (t.kind !== "test" || t.markers.length === 0)
76
+ continue;
77
+ if (pytest.deselect !== undefined && t.marks.includes(pytest.deselect))
78
+ continue;
79
+ if (t.conditional) {
80
+ warn({
81
+ code: "skipif-runtime-condition",
82
+ message: `${rel}:${t.line}: ${t.name}: coverage depends on a runtime condition (skipif)`,
83
+ path: rel,
84
+ line: t.line,
85
+ });
86
+ }
87
+ for (const id of t.markers)
88
+ links.push({ id, file: rel, line: t.line, test: t.name, active: t.active });
89
+ }
90
+ }
91
+ unknownMarkers.sort((a, b) => (a.file < b.file ? -1 : a.file > b.file ? 1 : a.line - b.line));
92
+ const untested = [];
93
+ rules.forEach((rule, index) => {
94
+ const mine = links.filter((l) => l.id === rule.id);
95
+ if (!mine.some((l) => l.active)) {
96
+ untested.push({ id: rule.id, path: `/rules/${index}`, skipped: mine.length });
97
+ }
98
+ });
99
+ return {
100
+ ...registry,
101
+ ok: untested.length === 0 && unknownMarkers.length === 0,
102
+ testFileCount: found.js.length + pyFiles.length,
103
+ untested,
104
+ unknownMarkers,
105
+ links: links.filter((l) => ids.has(l.id)),
106
+ warnings,
107
+ };
108
+ }
109
+ /** Whether discovery descends into a directory named `name`. */
110
+ export function isTestDiscoveryDirectory(name) {
111
+ return !name.startsWith(".") && !SKIP_DIRS.has(name);
112
+ }
113
+ /** Whether discovery considers this regular file as a Python test candidate. */
114
+ export function isPythonTestCandidate(rel) {
115
+ const segments = rel.split("/");
116
+ const name = segments.pop();
117
+ return name.endsWith(".py") && name !== "conftest.py" &&
118
+ segments.every((part) => isTestDiscoveryDirectory(part) && !PY_SKIP_DIRS.has(part));
119
+ }
120
+ /** True when `rel` (relative, `/` separators) is a vitest/jest test file that discovery would scan. */
121
+ export function isJsTestPath(rel) {
122
+ const parts = rel.split("/");
123
+ const dirs = parts.slice(0, -1);
124
+ return TEST_FILE.test(parts[parts.length - 1]) && dirs.every(isTestDiscoveryDirectory);
125
+ }
126
+ /** Lists test files below `root`, skipping dependencies, build output, dot-directories and symlinks. */
127
+ async function findTestFiles(root) {
128
+ const found = { js: [], py: [], seen: new Set(), rootFiles: new Set() };
129
+ const walk = async (dir, segments) => {
130
+ const entries = await readdir(dir, { withFileTypes: true });
131
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
132
+ for (const entry of entries) {
133
+ const rel = [...segments, entry.name].join("/");
134
+ if (entry.isDirectory()) {
135
+ if (isTestDiscoveryDirectory(entry.name)) {
136
+ found.seen.add(rel);
137
+ await walk(join(dir, entry.name), [...segments, entry.name]);
138
+ }
139
+ }
140
+ else if (entry.isFile()) {
141
+ found.seen.add(rel);
142
+ if (segments.length === 0)
143
+ found.rootFiles.add(entry.name);
144
+ if (TEST_FILE.test(entry.name))
145
+ found.js.push(rel);
146
+ else if (isPythonTestCandidate(rel)) {
147
+ found.py.push(rel);
148
+ }
149
+ }
150
+ }
151
+ };
152
+ await walk(root, []);
153
+ return found;
154
+ }
155
+ /** Applies `testpaths`, `norecursedirs` and `python_files` to the Python candidates. */
156
+ export function selectPythonFiles(found, config) {
157
+ const split = (path) => path.split(/[\\/]+/).filter((s) => s !== "" && s !== ".");
158
+ const roots = config.testpaths
159
+ .map(split)
160
+ .filter((p) => p.length > 0 && !p.includes("..") && !/^[A-Za-z]:$/.test(p[0]))
161
+ .filter((p) => [...found.seen].some((s) => matchesPrefix(p, split(s)) && split(s).length === p.length));
162
+ // pytest falls back to the root directory when no testpath exists.
163
+ const starts = roots.length > 0 ? roots : [[]];
164
+ return found.py.filter((rel) => {
165
+ const parts = split(rel);
166
+ const name = parts[parts.length - 1];
167
+ if (!config.pythonFiles.some((g) => globMatch(g, name)))
168
+ return false;
169
+ return starts.some((start) => {
170
+ if (!matchesPrefix(start, parts))
171
+ return false;
172
+ // Directories below the testpath are pruned by norecursedirs; the testpath itself is not.
173
+ const dirs = parts.slice(start.length, -1);
174
+ return !dirs.some((d) => config.norecursedirs.some((g) => globMatch(g, d)));
175
+ });
176
+ });
177
+ }
178
+ /** True when each glob segment of `prefix` matches the corresponding segment of `parts`. */
179
+ function matchesPrefix(prefix, parts) {
180
+ return prefix.length <= parts.length && prefix.every((g, k) => globMatch(g, parts[k]));
181
+ }
182
+ const SUITES = new Set(["describe", "suite", "fdescribe"]);
183
+ const TESTS = new Set(["it", "test", "fit"]);
184
+ const ALWAYS_SKIPPED = new Set(["xdescribe", "xit", "xtest"]);
185
+ const INACTIVE_MODIFIERS = new Set(["skip", "todo"]);
186
+ const REGEX_AFTER = new Set(["return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw", "instanceof", "yield", "await"]);
187
+ const CLOSE = { "(": ")", "[": "]", "{": "}" };
188
+ /** Finds every test and suite call in a test file. Never evaluates the source. */
189
+ export function findTests(source) {
190
+ const tokens = tokenize(source);
191
+ const found = [];
192
+ const stack = [{ close: "", active: true, markers: [] }];
193
+ const pending = new Map();
194
+ for (let k = 0; k < tokens.length; k++) {
195
+ const tok = tokens[k];
196
+ const top = stack[stack.length - 1];
197
+ if (tok.type === "punct") {
198
+ const close = CLOSE[tok.value];
199
+ if (close) {
200
+ stack.push({ close, ...(pending.get(k) ?? { active: top.active, markers: top.markers }) });
201
+ }
202
+ else if (stack.length > 1 && tok.value === top.close) {
203
+ stack.pop();
204
+ }
205
+ continue;
206
+ }
207
+ const base = tok.value;
208
+ if (tok.type !== "id" || !(SUITES.has(base) || TESTS.has(base) || ALWAYS_SKIPPED.has(base)))
209
+ continue;
210
+ if (tokens[k - 1]?.value === ".")
211
+ continue; // obj.it(…) is not a test call
212
+ // Follow the call chain: it.skip(…), test.each([…])(…), describe.skipIf(x)(…).
213
+ const modifiers = [];
214
+ let j = k + 1;
215
+ let call = -1;
216
+ while (j < tokens.length) {
217
+ const t = tokens[j];
218
+ const next = tokens[j + 1];
219
+ if (t.type === "punct" && t.value === "." && next?.type === "id") {
220
+ modifiers.push(next.value);
221
+ j += 2;
222
+ }
223
+ else if (t.type === "punct" && t.value === "(") {
224
+ const end = matchingParen(tokens, j);
225
+ const after = tokens[end + 1];
226
+ if (end > 0 && after?.type === "punct" && (after.value === "(" || after.value === ".")) {
227
+ j = end + 1; // arguments of a modifier such as .each([...]) — the test call follows
228
+ continue;
229
+ }
230
+ call = j;
231
+ break;
232
+ }
233
+ else {
234
+ break;
235
+ }
236
+ }
237
+ if (call < 0)
238
+ continue;
239
+ const nameTok = tokens[call + 1];
240
+ const name = nameTok?.type === "str" ? nameTok.value : "";
241
+ const ownMarkers = [...name.matchAll(MARKER)].map((m) => m[1]);
242
+ const markers = [...new Set([...top.markers, ...ownMarkers])];
243
+ const isSuite = SUITES.has(base) || base === "xdescribe";
244
+ // A test given only its name (no function) is a todo.
245
+ const noBody = !isSuite && nameTok?.type === "str" && tokens[call + 2]?.value === ")";
246
+ const active = top.active && !ALWAYS_SKIPPED.has(base) && !modifiers.some((m) => INACTIVE_MODIFIERS.has(m)) && !noBody;
247
+ found.push({ kind: isSuite ? "suite" : "test", name, line: tok.line, active, ownMarkers, markers });
248
+ pending.set(call, { active, markers });
249
+ }
250
+ return found;
251
+ }
252
+ function matchingParen(tokens, open) {
253
+ let depth = 0;
254
+ for (let i = open; i < tokens.length; i++) {
255
+ const v = tokens[i];
256
+ if (v.type !== "punct")
257
+ continue;
258
+ if (v.value === "(")
259
+ depth++;
260
+ else if (v.value === ")" && --depth === 0)
261
+ return i;
262
+ }
263
+ return -1;
264
+ }
265
+ /** Splits source into identifiers, string literals and punctuation; drops comments and whitespace. */
266
+ function tokenize(src) {
267
+ const tokens = [];
268
+ const braces = [];
269
+ const templates = [];
270
+ let i = 0;
271
+ let line = 1;
272
+ const n = src.length;
273
+ const regexAllowed = () => {
274
+ const prev = tokens[tokens.length - 1];
275
+ if (!prev)
276
+ return true;
277
+ if (prev.type === "str")
278
+ return false;
279
+ if (prev.type === "id")
280
+ return REGEX_AFTER.has(prev.value);
281
+ return prev.value !== ")" && prev.value !== "]" && prev.value !== "}";
282
+ };
283
+ // Reads template text into `tok` until the closing backtick or a `${`.
284
+ const scanTemplate = (tok) => {
285
+ while (i < n) {
286
+ const c = src[i];
287
+ if (c === "\\") {
288
+ tok.value += src[i + 1] ?? "";
289
+ if (src[i + 1] === "\n")
290
+ line++;
291
+ i += 2;
292
+ }
293
+ else if (c === "`") {
294
+ i++;
295
+ templates.pop();
296
+ return;
297
+ }
298
+ else if (c === "$" && src[i + 1] === "{") {
299
+ tok.value += "${…}";
300
+ braces.push("${");
301
+ i += 2;
302
+ return;
303
+ }
304
+ else {
305
+ if (c === "\n")
306
+ line++;
307
+ tok.value += c;
308
+ i++;
309
+ }
310
+ }
311
+ templates.pop();
312
+ };
313
+ while (i < n) {
314
+ const c = src[i];
315
+ if (c === "\n") {
316
+ line++;
317
+ i++;
318
+ }
319
+ else if (c === " " || c === "\t" || c === "\r" || c === "\f" || c === "\v" || c === "") {
320
+ i++;
321
+ }
322
+ else if (c === "/" && src[i + 1] === "/") {
323
+ while (i < n && src[i] !== "\n")
324
+ i++;
325
+ }
326
+ else if (c === "/" && src[i + 1] === "*") {
327
+ const end = src.indexOf("*/", i + 2);
328
+ const stop = end < 0 ? n : end + 2;
329
+ for (let k = i; k < stop; k++)
330
+ if (src[k] === "\n")
331
+ line++;
332
+ i = stop;
333
+ }
334
+ else if (c === '"' || c === "'") {
335
+ const tok = { type: "str", value: "", line };
336
+ i++;
337
+ while (i < n && src[i] !== c && src[i] !== "\n") {
338
+ if (src[i] === "\\") {
339
+ tok.value += src[i + 1] ?? "";
340
+ if (src[i + 1] === "\n")
341
+ line++;
342
+ i += 2;
343
+ }
344
+ else {
345
+ tok.value += src[i];
346
+ i++;
347
+ }
348
+ }
349
+ i++;
350
+ tokens.push(tok);
351
+ }
352
+ else if (c === "`") {
353
+ const tok = { type: "str", value: "", line };
354
+ tokens.push(tok);
355
+ templates.push(tok);
356
+ i++;
357
+ scanTemplate(tok);
358
+ }
359
+ else if (c === "}" && braces[braces.length - 1] === "${") {
360
+ braces.pop();
361
+ i++;
362
+ const tok = templates[templates.length - 1];
363
+ if (tok)
364
+ scanTemplate(tok);
365
+ }
366
+ else if (c === "/" && regexAllowed()) {
367
+ let inClass = false;
368
+ i++;
369
+ while (i < n && src[i] !== "\n") {
370
+ const r = src[i];
371
+ if (r === "\\")
372
+ i++;
373
+ else if (r === "[")
374
+ inClass = true;
375
+ else if (r === "]")
376
+ inClass = false;
377
+ else if (r === "/" && !inClass)
378
+ break;
379
+ i++;
380
+ }
381
+ i++;
382
+ while (i < n && /[a-z]/i.test(src[i]))
383
+ i++;
384
+ tokens.push({ type: "str", value: "", line });
385
+ }
386
+ else if (/[A-Za-z_$0-9]/.test(c)) {
387
+ const start = i;
388
+ while (i < n && /[\w$.]/.test(src[i]) && !(src[i] === "." && !/[0-9]/.test(c)))
389
+ i++;
390
+ tokens.push({ type: "id", value: src.slice(start, i), line });
391
+ }
392
+ else {
393
+ if (c === "{")
394
+ braces.push("{");
395
+ else if (c === "}")
396
+ braces.pop();
397
+ tokens.push({ type: "punct", value: c, line });
398
+ i++;
399
+ }
400
+ }
401
+ return tokens;
402
+ }
403
+ /** Last dotted names that make a test, class or module inactive, whatever the prefix. */
404
+ const INACTIVATING = new Set(["skip", "xfail", "skipIf", "skipUnless", "expectedFailure"]);
405
+ const PY_CLOSE = { "(": ")", "[": "]", "{": "}" };
406
+ const PY_NAME_START = /[\p{L}_]/u;
407
+ const PY_NAME = /[\p{L}\p{N}_]/u;
408
+ const STRING_PREFIX = /^(?:[rRbBuUfFtT]|[rR][bBfFtT]|[bBfFtT][rR])$/;
409
+ const PY_OPS = ["**=", "//=", ">>=", "<<=", "...", "->", ":=", "==", "!=", "<=", ">=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "@=", "**", "//", "<<", ">>"];
410
+ /** Finds every collected pytest test and test class in a Python file. Never evaluates the source. */
411
+ export function findPytestTests(source) {
412
+ return scanPytest(source).tests;
413
+ }
414
+ class Fault {
415
+ fault;
416
+ constructor(fault) {
417
+ this.fault = fault;
418
+ }
419
+ }
420
+ /**
421
+ * Splits Python source into logical lines of tokens (names, strings, numbers, operators).
422
+ * Comments are dropped; bracket depth and `\` continuations join physical lines.
423
+ * Stops at the first unterminated string or unbalanced bracket; the logical line in
424
+ * progress at that point is dropped.
425
+ */
426
+ function tokenizePython(src) {
427
+ const lines = [];
428
+ let current = [];
429
+ let indent = 0;
430
+ const brackets = [];
431
+ const n = src.length;
432
+ let i = 0;
433
+ let line = 1;
434
+ let lineStart = 0;
435
+ const newline = (at) => {
436
+ line++;
437
+ lineStart = at + 1;
438
+ };
439
+ const push = (tok, start) => {
440
+ if (current.length === 0 && carryIndent !== undefined) {
441
+ indent = carryIndent;
442
+ carryIndent = undefined;
443
+ }
444
+ else if (current.length === 0) {
445
+ indent = 0;
446
+ for (let k = lineStart; k < start; k++)
447
+ indent = src[k] === "\t" ? indent + 8 - (indent % 8) : indent + 1;
448
+ }
449
+ current.push(tok);
450
+ };
451
+ let carryIndent;
452
+ const flush = () => {
453
+ if (current.length > 0)
454
+ lines.push({ indent, tokens: current });
455
+ current = [];
456
+ carryIndent = undefined;
457
+ };
458
+ // Reads a string literal starting at the quote at `i`; returns its value (escapes approximated).
459
+ const scanString = (prefix, startLine, startColumn) => {
460
+ const q = src[i];
461
+ const triple = src.startsWith(q + q + q, i);
462
+ const raw = /r/i.test(prefix);
463
+ const formatted = /[ft]/i.test(prefix);
464
+ const unterminated = () => new Fault({ line: startLine, column: startColumn, message: "unterminated string" });
465
+ i += triple ? 3 : 1;
466
+ let value = "";
467
+ for (;;) {
468
+ if (i >= n)
469
+ throw unterminated();
470
+ const c = src[i];
471
+ if (c === "\\") {
472
+ const next = src[i + 1] ?? "";
473
+ if (next === "\r" && src[i + 2] === "\n") {
474
+ newline(i + 2);
475
+ i += 3;
476
+ continue;
477
+ }
478
+ if ((raw && next !== q && next !== "\\" && next !== "\n") || (formatted && next === "{")) {
479
+ // A raw backslash escapes only a quote, a backslash or a newline; `{` still opens a field.
480
+ value += c;
481
+ i++;
482
+ continue;
483
+ }
484
+ if (next === "\n")
485
+ newline(i + 1);
486
+ value += raw ? c + next : next;
487
+ i += 2;
488
+ }
489
+ else if (triple ? src.startsWith(q + q + q, i) : c === q) {
490
+ i += triple ? 3 : 1;
491
+ return value;
492
+ }
493
+ else if (c === "\n") {
494
+ if (!triple)
495
+ throw unterminated();
496
+ newline(i);
497
+ value += c;
498
+ i++;
499
+ }
500
+ else if (formatted && c === "{") {
501
+ if (src[i + 1] === "{") {
502
+ value += "{";
503
+ i += 2;
504
+ }
505
+ else {
506
+ i++;
507
+ if (!scanField())
508
+ throw unterminated();
509
+ value += "{…}";
510
+ }
511
+ }
512
+ else {
513
+ value += c;
514
+ i++;
515
+ }
516
+ }
517
+ };
518
+ // Skips an f-string replacement field after its `{`; false when the source ends first.
519
+ const scanField = () => {
520
+ let depth = 0;
521
+ while (i < n) {
522
+ const c = src[i];
523
+ if (c === "\n") {
524
+ newline(i);
525
+ i++;
526
+ }
527
+ else if (c === "'" || c === '"') {
528
+ scanString("", line, i - lineStart + 1);
529
+ }
530
+ else if (PY_NAME_START.test(c)) {
531
+ const start = i;
532
+ while (i < n && PY_NAME.test(src[i]))
533
+ i++;
534
+ const word = src.slice(start, i);
535
+ if ((src[i] === "'" || src[i] === '"') && STRING_PREFIX.test(word))
536
+ scanString(word, line, start - lineStart + 1);
537
+ }
538
+ else if (c === "(" || c === "[" || c === "{") {
539
+ depth++;
540
+ i++;
541
+ }
542
+ else if (c === ")" || c === "]" || (c === "}" && depth > 0)) {
543
+ depth--;
544
+ i++;
545
+ }
546
+ else if (c === "}") {
547
+ i++;
548
+ return true;
549
+ }
550
+ else if (c === ":" && depth === 0) {
551
+ // Format spec: literal text up to the closing brace, with nested fields.
552
+ i++;
553
+ while (i < n && src[i] !== "}") {
554
+ if (src[i] === "{") {
555
+ i++;
556
+ if (!scanField())
557
+ return false;
558
+ }
559
+ else {
560
+ if (src[i] === "\n")
561
+ newline(i);
562
+ i++;
563
+ }
564
+ }
565
+ if (i >= n)
566
+ return false;
567
+ i++;
568
+ return true;
569
+ }
570
+ else {
571
+ i++;
572
+ }
573
+ }
574
+ return false;
575
+ };
576
+ try {
577
+ while (i < n) {
578
+ const c = src[i];
579
+ const column = i - lineStart + 1;
580
+ if (c === "\n") {
581
+ newline(i);
582
+ i++;
583
+ if (brackets.length === 0)
584
+ flush();
585
+ }
586
+ else if (c === " " || c === "\t" || c === "\r" || c === "\f" || c === "\v" || c === "") {
587
+ i++;
588
+ }
589
+ else if (c === "#") {
590
+ while (i < n && src[i] !== "\n")
591
+ i++;
592
+ }
593
+ else if (c === "\\" && (src[i + 1] === "\n" || (src[i + 1] === "\r" && src[i + 2] === "\n"))) {
594
+ i += src[i + 1] === "\n" ? 1 : 2;
595
+ newline(i);
596
+ i++;
597
+ }
598
+ else if (c === "'" || c === '"') {
599
+ const start = i;
600
+ const startLine = line;
601
+ const value = scanString("", line, column);
602
+ push({ type: "str", value, line: startLine, column, prefix: "" }, start);
603
+ }
604
+ else if (PY_NAME_START.test(c)) {
605
+ const start = i;
606
+ while (i < n && PY_NAME.test(src[i]))
607
+ i++;
608
+ const word = src.slice(start, i);
609
+ if ((src[i] === "'" || src[i] === '"') && STRING_PREFIX.test(word)) {
610
+ const startLine = line;
611
+ const value = scanString(word, line, column);
612
+ push({ type: "str", value, line: startLine, column, prefix: word.toLowerCase() }, start);
613
+ }
614
+ else {
615
+ push({ type: "name", value: word, line, column, prefix: "" }, start);
616
+ }
617
+ }
618
+ else if (/[0-9]/.test(c) || (c === "." && /[0-9]/.test(src[i + 1] ?? ""))) {
619
+ const start = i;
620
+ while (i < n && /[\w.]/.test(src[i]))
621
+ i++;
622
+ push({ type: "num", value: src.slice(start, i), line, column, prefix: "" }, start);
623
+ }
624
+ else {
625
+ const op = PY_OPS.find((o) => src.startsWith(o, i)) ?? c;
626
+ if (op === ";" && brackets.length === 0) {
627
+ // `a; b` is two statements at the same indentation.
628
+ const statementIndent = indent;
629
+ flush();
630
+ carryIndent = statementIndent;
631
+ i++;
632
+ continue;
633
+ }
634
+ const tok = { type: "op", value: op, line, column, prefix: "" };
635
+ if (PY_CLOSE[op]) {
636
+ brackets.push(tok);
637
+ }
638
+ else if (op === ")" || op === "]" || op === "}") {
639
+ const open = brackets.pop();
640
+ if (!open || PY_CLOSE[open.value] !== op)
641
+ throw new Fault({ line, column, message: `unmatched '${op}'` });
642
+ }
643
+ push(tok, i);
644
+ i += op.length;
645
+ }
646
+ }
647
+ const open = brackets[0];
648
+ if (open)
649
+ return { lines, fault: { line: open.line, column: open.column, message: `'${open.value}' was never closed` } };
650
+ flush();
651
+ return { lines };
652
+ }
653
+ catch (error) {
654
+ if (error instanceof Fault)
655
+ return { lines, fault: error.fault };
656
+ throw error;
657
+ }
658
+ }
659
+ /** Index of the bracket closing the one at `open`, or -1. */
660
+ function closing(tokens, open, end = tokens.length) {
661
+ let depth = 0;
662
+ for (let k = open; k < end; k++) {
663
+ const t = tokens[k];
664
+ if (t.type !== "op")
665
+ continue;
666
+ if (PY_CLOSE[t.value])
667
+ depth++;
668
+ else if ((t.value === ")" || t.value === "]" || t.value === "}") && --depth === 0)
669
+ return k;
670
+ }
671
+ return -1;
672
+ }
673
+ /** Splits `tokens[start, end)` at top-level commas. */
674
+ function splitArgs(tokens, start, end) {
675
+ const parts = [];
676
+ let depth = 0;
677
+ let from = start;
678
+ for (let k = start; k < end; k++) {
679
+ const v = tokens[k];
680
+ if (v.type === "op" && PY_CLOSE[v.value])
681
+ depth++;
682
+ else if (v.type === "op" && (v.value === ")" || v.value === "]" || v.value === "}"))
683
+ depth--;
684
+ else if (v.type === "op" && v.value === "," && depth === 0) {
685
+ if (k > from)
686
+ parts.push([from, k]);
687
+ from = k + 1;
688
+ }
689
+ }
690
+ if (end > from)
691
+ parts.push([from, end]);
692
+ return parts;
693
+ }
694
+ /** Reads a dotted name at `start`; returns its parts and the index after it. */
695
+ function dottedName(tokens, start, end) {
696
+ const parts = [];
697
+ let k = start;
698
+ if (tokens[k]?.type !== "name" || k >= end)
699
+ return { parts, next: k };
700
+ parts.push(tokens[k].value);
701
+ k++;
702
+ while (k + 1 < end && tokens[k].value === "." && tokens[k + 1].type === "name") {
703
+ parts.push(tokens[k + 1].value);
704
+ k += 2;
705
+ }
706
+ return { parts, next: k };
707
+ }
708
+ function readMark(tokens, start, end, line) {
709
+ const { parts, next } = dottedName(tokens, start, end);
710
+ if (parts.length === 0)
711
+ return undefined;
712
+ const literal = parts.length === 3 && parts[0] === "pytest" && parts[1] === "mark" ? parts[2] : undefined;
713
+ const ids = [];
714
+ if (literal === "invariant" && tokens[next]?.value === "(") {
715
+ const close = closing(tokens, next, end);
716
+ if (close > 0) {
717
+ for (const [a, b] of splitArgs(tokens, next + 1, close)) {
718
+ const arg = tokens.slice(a, b);
719
+ // Positional string literals, implicitly concatenated; f-strings and bytes are not ids.
720
+ if (arg.every((t) => t.type === "str" && !/[bft]/.test(t.prefix)))
721
+ ids.push(arg.map((t) => t.value).join(""));
722
+ }
723
+ }
724
+ }
725
+ return { last: parts[parts.length - 1], literal, ids, line };
726
+ }
727
+ /**
728
+ * Marks named anywhere in a statement on `pytestmark`: `= mark`, `= [mark, …]`, `+= […]`,
729
+ * `.append(mark)`, `= […] + […]`. Reading every mark in the statement errs toward inactive.
730
+ */
731
+ function readPytestmark(tokens) {
732
+ const head = tokens[0];
733
+ if (head?.type !== "name" || head.value !== "pytestmark")
734
+ return undefined;
735
+ const marks = [];
736
+ for (let k = 1; k < tokens.length; k++) {
737
+ if (tokens[k].type !== "name" || tokens[k - 1].value === ".")
738
+ continue;
739
+ const mark = readMark(tokens, k, tokens.length, head.line);
740
+ if (mark)
741
+ marks.push(mark);
742
+ }
743
+ return marks;
744
+ }
745
+ /** True for a module-level `pytest.skip(…, allow_module_level=True)` (any prefix) or `raise …SkipTest`. */
746
+ function skipsModule(tokens) {
747
+ for (let k = 0; k < tokens.length; k++) {
748
+ const t = tokens[k];
749
+ if (t.type !== "name" || tokens[k - 1]?.value === ".")
750
+ continue;
751
+ if (t.value === "raise") {
752
+ const { parts } = dottedName(tokens, k + 1, tokens.length);
753
+ if (parts[parts.length - 1] === "SkipTest")
754
+ return true;
755
+ continue;
756
+ }
757
+ const { parts, next } = dottedName(tokens, k, tokens.length);
758
+ if (parts[parts.length - 1] === "skip" && tokens[next]?.value === "(") {
759
+ const close = closing(tokens, next);
760
+ for (let a = next + 1; a < (close < 0 ? tokens.length : close) - 2; a++) {
761
+ if (tokens[a].value === "allow_module_level" && tokens[a + 1].value === "=" && tokens[a + 2].value === "True")
762
+ return true;
763
+ }
764
+ }
765
+ }
766
+ return false;
767
+ }
768
+ export function scanPytest(source) {
769
+ const { lines, fault } = tokenizePython(source);
770
+ const scope = (kind, name, line, indent, parent) => ({
771
+ kind, name, line, indent, parent, children: [], decorators: [], pytestmark: [], hasInit: false, testCaseBase: false, bases: [],
772
+ });
773
+ const module = scope("module", "", 0, -1);
774
+ const stack = [module];
775
+ let pending = [];
776
+ let moduleSkipped = false;
777
+ for (const { indent, tokens } of lines) {
778
+ while (stack.length > 1 && indent <= stack[stack.length - 1].indent)
779
+ stack.pop();
780
+ const owner = stack[stack.length - 1];
781
+ const head = tokens[0];
782
+ if (head.value === "@") {
783
+ const wrapped = tokens[1]?.value === "(" && closing(tokens, 1) === tokens.length - 1;
784
+ const mark = readMark(tokens, wrapped ? 2 : 1, wrapped ? tokens.length - 1 : tokens.length, head.line);
785
+ if (mark)
786
+ pending.push(mark);
787
+ continue;
788
+ }
789
+ const at = head.value === "async" && tokens[1]?.value === "def" ? 1 : 0;
790
+ const keyword = tokens[at].value;
791
+ if ((keyword === "def" || keyword === "class") && tokens[at + 1]?.type === "name") {
792
+ const name = tokens[at + 1].value;
793
+ const s = scope(keyword, name, head.line, indent, owner);
794
+ s.decorators = pending;
795
+ if (keyword === "class" && tokens[at + 2]?.value === "(") {
796
+ const close = closing(tokens, at + 2);
797
+ for (const [a, b] of splitArgs(tokens, at + 3, close < 0 ? tokens.length : close)) {
798
+ const { parts, next } = dottedName(tokens, a, b);
799
+ if (next !== b)
800
+ continue;
801
+ if (parts[parts.length - 1].endsWith("TestCase"))
802
+ s.testCaseBase = true;
803
+ if (parts.length === 1)
804
+ s.bases.push(parts[0]);
805
+ }
806
+ }
807
+ if (keyword === "def" && (name === "__init__" || name === "__new__") && owner.kind === "class")
808
+ owner.hasInit = true;
809
+ owner.children.push(s);
810
+ stack.push(s);
811
+ pending = [];
812
+ continue;
813
+ }
814
+ pending = [];
815
+ if (owner.kind !== "def") {
816
+ const marks = readPytestmark(tokens);
817
+ if (marks)
818
+ owner.pytestmark.push(...marks);
819
+ const last = tokens[tokens.length - 1].value;
820
+ if (head.value === "__test__" && (tokens[1]?.value === "=" || tokens[1]?.value === ":") && tokens[tokens.length - 2]?.value === "=" && (last === "False" || last === "True")) {
821
+ owner.testFlag = last === "True";
822
+ }
823
+ }
824
+ if (owner === module && skipsModule(tokens))
825
+ moduleSkipped = true;
826
+ }
827
+ const tests = [];
828
+ const sites = [];
829
+ const isInactive = (marks) => moduleSkipped || marks.some((m) => INACTIVATING.has(m.last));
830
+ const ids = (marks) => [...new Set(marks.flatMap((m) => m.ids))];
831
+ // A class with the classes it inherits from in this file (same-named classes defined earlier), nearest first.
832
+ const lineage = (s, seen = new Set()) => {
833
+ if (seen.has(s))
834
+ return [];
835
+ seen.add(s);
836
+ return [
837
+ s,
838
+ ...s.bases.flatMap((base) => {
839
+ for (let p = s.parent; p; p = p.parent) {
840
+ const found = p.children.filter((c) => c.kind === "class" && c.name === base && c.line < s.line).pop();
841
+ if (found)
842
+ return lineage(found, seen);
843
+ }
844
+ return [];
845
+ }),
846
+ ];
847
+ };
848
+ const visit = (s, inherited, path, collected) => {
849
+ // Marks, __test__, __init__ and TestCase bases follow inheritance, as they do at runtime.
850
+ const line = s.kind === "class" ? lineage(s) : [s];
851
+ const own = line.flatMap((c) => [...c.decorators, ...c.pytestmark]);
852
+ const marks = [...inherited, ...own];
853
+ const name = s.kind === "module" ? "" : [...path, s.name].join("::");
854
+ const active = !isInactive(marks);
855
+ if (s.kind !== "module" && ids(s.decorators).length > 0) {
856
+ sites.push({ ids: ids(s.decorators), line: s.line, name, active });
857
+ }
858
+ for (const m of s.pytestmark) {
859
+ if (m.ids.length > 0)
860
+ sites.push({ ids: m.ids, line: m.line, name: [...path, ...(name ? [s.name] : []), "pytestmark"].join("::"), active });
861
+ }
862
+ let eligible = false;
863
+ if (s.kind === "class") {
864
+ const testFlag = line.find((c) => c.testFlag !== undefined)?.testFlag;
865
+ const isTestCase = line.some((c) => c.testCaseBase);
866
+ eligible = collected && testFlag !== false && ((s.name.startsWith("Test") && !line.some((c) => c.hasInit)) || isTestCase);
867
+ }
868
+ else if (s.kind === "def") {
869
+ eligible = collected && s.name.startsWith("test");
870
+ }
871
+ if (eligible) {
872
+ tests.push({
873
+ kind: s.kind === "class" ? "suite" : "test",
874
+ name,
875
+ line: s.line,
876
+ active,
877
+ ownMarkers: ids(own),
878
+ markers: ids(marks),
879
+ conditional: active && marks.some((m) => m.last === "skipif"),
880
+ marks: [...new Set(marks.flatMap((m) => (m.literal ? [m.literal] : [])))],
881
+ });
882
+ }
883
+ const childCollected = s.kind === "module" ? s.testFlag !== false : s.kind === "class" && eligible;
884
+ // A later definition with the same name replaces an earlier one, as it does at runtime.
885
+ const lastIndex = new Map(s.children.map((c, k) => [c.name, k]));
886
+ s.children.forEach((child, k) => visit(child, marks, s.kind === "module" ? [] : [...path, s.name], childCollected && lastIndex.get(child.name) === k));
887
+ };
888
+ visit(module, [], [], true);
889
+ return { tests, sites, fault };
890
+ }
891
+ const PYTEST_DEFAULTS = {
892
+ testpaths: [],
893
+ pythonFiles: ["test_*.py", "*_test.py"],
894
+ norecursedirs: ["*.egg", ".*", "_darcs", "build", "CVS", "dist", "node_modules", "venv", "{arch}"],
895
+ ignored: [],
896
+ };
897
+ class ConfigError extends Error {
898
+ /** The configuration file, relative to the registry's directory; set once the file is known. */
899
+ file = "";
900
+ }
901
+ /** Reads the pytest configuration that applies in `root`; throws when it cannot be used. */
902
+ export async function readRootPytestConfig(root) {
903
+ const entries = await readdir(root, { withFileTypes: true });
904
+ return readPytestConfig(root, new Set(entries.filter((e) => e.isFile()).map((e) => e.name)));
905
+ }
906
+ /** Reads the first applicable pytest configuration in `root`; throws ConfigError when it cannot be used. */
907
+ async function readPytestConfig(root, present) {
908
+ const candidates = [
909
+ // pytest's own precedence; pytest.toml, .pytest.toml, pytest.ini and .pytest.ini apply even when empty.
910
+ ["pytest.toml", (t) => parseToml(t).get("pytest") ?? new Map()],
911
+ [".pytest.toml", (t) => parseToml(t).get("pytest") ?? new Map()],
912
+ ["pytest.ini", (t) => parseIni(t).get("pytest") ?? new Map()],
913
+ [".pytest.ini", (t) => parseIni(t).get("pytest") ?? new Map()],
914
+ ["pyproject.toml", (t) => {
915
+ const tables = parseToml(t);
916
+ return tables.get("tool.pytest") ?? tables.get("tool.pytest.ini_options");
917
+ }],
918
+ ["tox.ini", (t) => parseIni(t).get("pytest")],
919
+ ["setup.cfg", (t) => parseIni(t).get("tool:pytest")],
920
+ ];
921
+ for (const [file, read] of candidates) {
922
+ if (!present.has(file))
923
+ continue;
924
+ const text = await readFile(join(root, file), "utf8");
925
+ let settings;
926
+ try {
927
+ settings = read(text);
928
+ }
929
+ catch (error) {
930
+ if (error instanceof ConfigError)
931
+ throw Object.assign(new ConfigError(`${file}: ${error.message}`), { file });
932
+ throw error;
933
+ }
934
+ if (!settings)
935
+ continue;
936
+ try {
937
+ return { file, ...settingsToConfig(settings) };
938
+ }
939
+ catch (error) {
940
+ if (error instanceof ConfigError)
941
+ throw Object.assign(new ConfigError(`${file}: ${error.message}`), { file });
942
+ throw error;
943
+ }
944
+ }
945
+ return PYTEST_DEFAULTS;
946
+ }
947
+ function settingsToConfig(settings) {
948
+ const list = (key) => {
949
+ const value = settings.get(key);
950
+ return value === undefined ? undefined : typeof value === "string" ? shellSplit(value) : value;
951
+ };
952
+ const config = {
953
+ testpaths: list("testpaths") ?? [],
954
+ pythonFiles: list("python_files") ?? PYTEST_DEFAULTS.pythonFiles,
955
+ norecursedirs: list("norecursedirs") ?? PYTEST_DEFAULTS.norecursedirs,
956
+ ignored: ["python_functions", "python_classes"].filter((key) => settings.has(key)),
957
+ };
958
+ const args = list("addopts") ?? [];
959
+ let expression;
960
+ for (let k = 0; k < args.length; k++) {
961
+ const arg = args[k];
962
+ if (arg === "-m") {
963
+ if (k + 1 >= args.length)
964
+ throw new ConfigError("addopts: -m needs an expression");
965
+ expression = args[++k];
966
+ }
967
+ else if (arg.startsWith("-m")) {
968
+ expression = arg.slice(2);
969
+ }
970
+ else if (/^(-k|--ignore|--ignore-glob|--deselect)(=|$)/.test(arg) || (arg.startsWith("-k") && arg.length > 2)) {
971
+ config.ignored.push(`addopts ${arg.replace(/=.*/, "")}`);
972
+ }
973
+ }
974
+ if (expression !== undefined) {
975
+ const match = /^\s*not\s+([A-Za-z_][A-Za-z0-9_]*)\s*$/.exec(expression);
976
+ if (!match)
977
+ throw new ConfigError(`addopts: unsupported -m expression "${expression}" (only "not NAME" is supported)`);
978
+ config.deselect = match[1];
979
+ }
980
+ return config;
981
+ }
982
+ /** Splits a command line like Python's shlex.split: whitespace, quotes and backslashes. */
983
+ function shellSplit(text) {
984
+ const words = [];
985
+ let word;
986
+ for (let i = 0; i < text.length; i++) {
987
+ const c = text[i];
988
+ if (/\s/.test(c)) {
989
+ if (word !== undefined)
990
+ words.push(word);
991
+ word = undefined;
992
+ }
993
+ else if (c === "'" || c === '"') {
994
+ let end = i + 1;
995
+ while (end < text.length && text[end] !== c)
996
+ end += c === '"' && text[end] === "\\" ? 2 : 1;
997
+ if (end >= text.length)
998
+ end = -1;
999
+ if (end < 0)
1000
+ throw new ConfigError(`unterminated quote in "${text.trim()}"`);
1001
+ word = (word ?? "") + text.slice(i + 1, end).replace(c === '"' ? /\\(["\\$`])/g : /$^/, "$1");
1002
+ i = end;
1003
+ }
1004
+ else if (c === "\\" && i + 1 < text.length) {
1005
+ word = (word ?? "") + text[++i];
1006
+ }
1007
+ else {
1008
+ word = (word ?? "") + c;
1009
+ }
1010
+ }
1011
+ if (word !== undefined)
1012
+ words.push(word);
1013
+ return words;
1014
+ }
1015
+ /** Parses an ini file the way pytest's iniconfig does: sections, `key = value`, indented continuations. */
1016
+ function parseIni(text) {
1017
+ const sections = new Map();
1018
+ let section;
1019
+ let key;
1020
+ text.split(/\r?\n/).forEach((raw, index) => {
1021
+ const line = raw.replace(/^\uFEFF/, "");
1022
+ const trimmed = line.trim();
1023
+ if (trimmed === "" || trimmed.startsWith("#") || trimmed.startsWith(";"))
1024
+ return;
1025
+ if (/^\s/.test(line)) {
1026
+ if (!section || key === undefined)
1027
+ throw new ConfigError(`line ${index + 1}: unexpected continuation line`);
1028
+ section.set(key, `${section.get(key)}\n${stripIniComment(trimmed)}`);
1029
+ return;
1030
+ }
1031
+ const header = /^\[([^\]]+)\]\s*(?:[#;].*)?$/.exec(trimmed);
1032
+ if (header) {
1033
+ section = sections.get(header[1].trim()) ?? new Map();
1034
+ sections.set(header[1].trim(), section);
1035
+ key = undefined;
1036
+ return;
1037
+ }
1038
+ const sep = /[=:]/.exec(line);
1039
+ if (!section || !sep)
1040
+ throw new ConfigError(`line ${index + 1}: expected "[section]" or "key = value"`);
1041
+ key = line.slice(0, sep.index).trim();
1042
+ section.set(key, stripIniComment(line.slice(sep.index + 1).trim()));
1043
+ });
1044
+ return sections;
1045
+ }
1046
+ function stripIniComment(value) {
1047
+ const at = value.search(/\s[#;]/);
1048
+ return (at < 0 ? value : value.slice(0, at)).trim();
1049
+ }
1050
+ /**
1051
+ * Parses the TOML needed to read pytest settings: tables, keys, strings, arrays.
1052
+ * Other values (numbers, booleans, dates, inline tables) are skipped. Throws ConfigError on malformed input.
1053
+ */
1054
+ function parseToml(text) {
1055
+ const tables = new Map();
1056
+ let table = new Map();
1057
+ let tableName = "";
1058
+ tables.set("", table);
1059
+ const n = text.length;
1060
+ let i = 0;
1061
+ let line = 1;
1062
+ const error = (message) => new ConfigError(`line ${line}: ${message}`);
1063
+ const skipSpace = (newlines) => {
1064
+ while (i < n) {
1065
+ const c = text[i];
1066
+ if (c === " " || c === "\t" || c === "\r" || c === "\uFEFF")
1067
+ i++;
1068
+ else if (c === "#")
1069
+ while (i < n && text[i] !== "\n")
1070
+ i++;
1071
+ else if (c === "\n" && newlines) {
1072
+ line++;
1073
+ i++;
1074
+ }
1075
+ else
1076
+ break;
1077
+ }
1078
+ };
1079
+ const readString = () => {
1080
+ const q = text[i];
1081
+ const triple = text.startsWith(q + q + q, i);
1082
+ i += triple ? 3 : 1;
1083
+ if (triple && text[i] === "\n") {
1084
+ line++;
1085
+ i++;
1086
+ }
1087
+ let value = "";
1088
+ for (;;) {
1089
+ if (i >= n)
1090
+ throw error("unterminated string");
1091
+ const c = text[i];
1092
+ if (triple ? text.startsWith(q + q + q, i) : c === q) {
1093
+ // Up to two quotes may end a multi-line string's content right before its closing delimiter.
1094
+ let extra = 0;
1095
+ while (triple && extra < 2 && text[i + 3 + extra] === q)
1096
+ extra++;
1097
+ i += (triple ? 3 : 1) + extra;
1098
+ return value + q.repeat(extra);
1099
+ }
1100
+ if (c === "\n") {
1101
+ if (!triple)
1102
+ throw error("unterminated string");
1103
+ line++;
1104
+ }
1105
+ if (c === "\\" && q === '"') {
1106
+ const next = text[i + 1] ?? "";
1107
+ value += next === "n" ? "\n" : next === "t" ? "\t" : next;
1108
+ i += 2;
1109
+ continue;
1110
+ }
1111
+ value += c;
1112
+ i++;
1113
+ }
1114
+ };
1115
+ // Returns a string, an array of strings, or undefined for any other value.
1116
+ const readValue = () => {
1117
+ const c = text[i];
1118
+ if (c === '"' || c === "'")
1119
+ return readString();
1120
+ if (c === "[") {
1121
+ i++;
1122
+ const items = [];
1123
+ for (;;) {
1124
+ skipSpace(true);
1125
+ if (i >= n)
1126
+ throw error("unterminated array");
1127
+ if (text[i] === "]") {
1128
+ i++;
1129
+ break;
1130
+ }
1131
+ items.push(readValue());
1132
+ skipSpace(true);
1133
+ if (text[i] === ",")
1134
+ i++;
1135
+ else if (text[i] !== "]")
1136
+ throw error("expected ',' or ']' in array");
1137
+ }
1138
+ return items.every((v) => typeof v === "string") ? items : undefined;
1139
+ }
1140
+ if (c === "{") {
1141
+ let depth = 0;
1142
+ while (i < n) {
1143
+ const d = text[i];
1144
+ if (d === '"' || d === "'") {
1145
+ readString();
1146
+ continue;
1147
+ }
1148
+ if (d === "\n")
1149
+ line++;
1150
+ if (d === "{")
1151
+ depth++;
1152
+ if (d === "}" && --depth === 0) {
1153
+ i++;
1154
+ return undefined;
1155
+ }
1156
+ i++;
1157
+ }
1158
+ throw error("unterminated inline table");
1159
+ }
1160
+ const start = i;
1161
+ while (i < n && !/[,\]}\n#]/.test(text[i]))
1162
+ i++;
1163
+ if (text.slice(start, i).trim() === "")
1164
+ throw error("missing value");
1165
+ return undefined;
1166
+ };
1167
+ const readKey = (stop) => {
1168
+ const parts = [];
1169
+ for (;;) {
1170
+ skipSpace(false);
1171
+ if (text[i] === '"' || text[i] === "'")
1172
+ parts.push(readString());
1173
+ else {
1174
+ const start = i;
1175
+ while (i < n && /[A-Za-z0-9_-]/.test(text[i]))
1176
+ i++;
1177
+ if (i === start)
1178
+ throw error("expected a key");
1179
+ parts.push(text.slice(start, i));
1180
+ }
1181
+ skipSpace(false);
1182
+ if (text[i] === ".")
1183
+ i++;
1184
+ else if (i < n && stop.test(text[i]))
1185
+ return parts.join(".");
1186
+ else
1187
+ throw error("malformed key");
1188
+ }
1189
+ };
1190
+ for (;;) {
1191
+ skipSpace(true);
1192
+ if (i >= n)
1193
+ break;
1194
+ if (text[i] === "[") {
1195
+ const array = text[i + 1] === "[";
1196
+ i += array ? 2 : 1;
1197
+ const name = readKey(/\]/);
1198
+ i += array ? 2 : 1;
1199
+ table = array ? new Map() : (tables.get(name) ?? new Map());
1200
+ tableName = array ? `[[${name}]]` : name;
1201
+ if (!array)
1202
+ tables.set(name, table);
1203
+ }
1204
+ else {
1205
+ const key = readKey(/=/);
1206
+ i++;
1207
+ skipSpace(false);
1208
+ const value = readValue();
1209
+ if (value !== undefined && !key.includes("."))
1210
+ table.set(key, value);
1211
+ else if (value !== undefined) {
1212
+ // A dotted key such as `pytest.ini_options.addopts` under `[tool]` sets a key in a sub-table.
1213
+ const parts = key.split(".");
1214
+ const target = [tableName, ...parts.slice(0, -1)].filter((p) => p !== "").join(".");
1215
+ const sub = tables.get(target) ?? new Map();
1216
+ tables.set(target, sub);
1217
+ sub.set(parts[parts.length - 1], value);
1218
+ }
1219
+ }
1220
+ skipSpace(false);
1221
+ if (i < n && text[i] !== "\n")
1222
+ throw error("expected end of line");
1223
+ }
1224
+ return tables;
1225
+ }
1226
+ /** Matches a name against a glob with `*`, `?` and `[...]` / `[!...]`, like Python's fnmatch. */
1227
+ function globMatch(pattern, name) {
1228
+ let source = "";
1229
+ for (let k = 0; k < pattern.length; k++) {
1230
+ const c = pattern[k];
1231
+ if (c === "*")
1232
+ source += ".*";
1233
+ else if (c === "?")
1234
+ source += ".";
1235
+ else if (c === "[" && pattern.indexOf("]", k + 2) > 0) {
1236
+ const end = pattern.indexOf("]", k + 2);
1237
+ let body = pattern.slice(k + 1, end);
1238
+ if (body.startsWith("!"))
1239
+ body = `^${body.slice(1)}`;
1240
+ source += `[${body.replace(/\\/g, "\\\\")}]`;
1241
+ k = end;
1242
+ }
1243
+ else
1244
+ source += c.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&");
1245
+ }
1246
+ return new RegExp(`^${source}$`, "s").test(name);
1247
+ }