@diffci.com/diffci 0.3.54 → 0.3.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist-client/src/client/agent-selection.d.ts +9 -2
  2. package/dist-client/src/client/agent-selection.js +20 -8
  3. package/dist-client/src/client/agent-setup.js +1 -1
  4. package/dist-client/src/client/cli.js +19 -7
  5. package/dist-client/src/client/command-batches.js +3 -2
  6. package/dist-client/src/client/context.d.ts +2 -0
  7. package/dist-client/src/client/context.js +51 -2
  8. package/dist-client/src/client/coverage-map.js +6 -1
  9. package/dist-client/src/client/full-command.js +22 -14
  10. package/dist-client/src/client/gate.js +24 -10
  11. package/dist-client/src/client/hook.d.ts +17 -0
  12. package/dist-client/src/client/hook.js +53 -1
  13. package/dist-client/src/client/install.d.ts +6 -0
  14. package/dist-client/src/client/install.js +29 -1
  15. package/dist-client/src/client/job-summary.d.ts +1 -1
  16. package/dist-client/src/client/job-summary.js +2 -1
  17. package/dist-client/src/client/mcp.js +4 -0
  18. package/dist-client/src/client/observe.js +4 -3
  19. package/dist-client/src/client/report.d.ts +8 -1
  20. package/dist-client/src/client/report.js +11 -0
  21. package/dist-client/src/client/shared-graph-cache.js +4 -2
  22. package/dist-client/src/client/telemetry.js +2 -1
  23. package/dist-client/src/client/usage-signal.d.ts +1 -1
  24. package/dist-client/src/client/verify-savings.d.ts +6 -0
  25. package/dist-client/src/client/verify-savings.js +15 -3
  26. package/dist-client/src/client/verify.js +124 -22
  27. package/dist-client/src/client/workflow-guard.js +27 -6
  28. package/dist-client/src/client/workflow-templates.d.ts +11 -1
  29. package/dist-client/src/client/workflow-templates.js +43 -2
  30. package/node_modules/@diffci.com/core/README.md +17 -10
  31. package/node_modules/@diffci.com/core/dist/ci-inference/expression.d.ts +5 -0
  32. package/node_modules/@diffci.com/core/dist/ci-inference/expression.js +38 -5
  33. package/node_modules/@diffci.com/core/dist/ci-inference/expression.js.map +1 -1
  34. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js +26 -6
  35. package/node_modules/@diffci.com/core/dist/ci-inference/infer.js.map +1 -1
  36. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.d.ts +2 -1
  37. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js +7 -2
  38. package/node_modules/@diffci.com/core/dist/ci-inference/jobs.js.map +1 -1
  39. package/node_modules/@diffci.com/core/dist/ci-inference/matrix.js +15 -8
  40. package/node_modules/@diffci.com/core/dist/ci-inference/matrix.js.map +1 -1
  41. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js +6 -2
  42. package/node_modules/@diffci.com/core/dist/ci-inference/purpose.js.map +1 -1
  43. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js +38 -5
  44. package/node_modules/@diffci.com/core/dist/ci-inference/resolve.js.map +1 -1
  45. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js +13 -1
  46. package/node_modules/@diffci.com/core/dist/git/ci-config-paths.js.map +1 -1
  47. package/node_modules/@diffci.com/core/dist/git/git-diff.d.ts +5 -0
  48. package/node_modules/@diffci.com/core/dist/git/git-diff.js +64 -31
  49. package/node_modules/@diffci.com/core/dist/git/git-diff.js.map +1 -1
  50. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js +22 -1
  51. package/node_modules/@diffci.com/core/dist/planner/check-narrowing.js.map +1 -1
  52. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.d.ts +6 -0
  53. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js +14 -2
  54. package/node_modules/@diffci.com/core/dist/planner/pipeline-steps.js.map +1 -1
  55. package/node_modules/@diffci.com/core/dist/planner/planner.js +65 -14
  56. package/node_modules/@diffci.com/core/dist/planner/planner.js.map +1 -1
  57. package/node_modules/@diffci.com/core/dist/planner/rust-command.js +43 -1
  58. package/node_modules/@diffci.com/core/dist/planner/rust-command.js.map +1 -1
  59. package/node_modules/@diffci.com/core/dist/planner/script-reads.js +5 -2
  60. package/node_modules/@diffci.com/core/dist/planner/script-reads.js.map +1 -1
  61. package/node_modules/@diffci.com/core/dist/planner/test-command.js +17 -2
  62. package/node_modules/@diffci.com/core/dist/planner/test-command.js.map +1 -1
  63. package/node_modules/@diffci.com/core/dist/planner/type-program.js +27 -1
  64. package/node_modules/@diffci.com/core/dist/planner/type-program.js.map +1 -1
  65. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js +5 -1
  66. package/node_modules/@diffci.com/core/dist/repo/adapters/go.js.map +1 -1
  67. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js +71 -9
  68. package/node_modules/@diffci.com/core/dist/repo/adapters/maven.js.map +1 -1
  69. package/node_modules/@diffci.com/core/dist/repo/adapters/python.d.ts +9 -1
  70. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js +259 -18
  71. package/node_modules/@diffci.com/core/dist/repo/adapters/python.js.map +1 -1
  72. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.d.ts +3 -1
  73. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.js +44 -6
  74. package/node_modules/@diffci.com/core/dist/repo/adapters/rust-invocation.js.map +1 -1
  75. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.d.ts +1 -0
  76. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js +338 -24
  77. package/node_modules/@diffci.com/core/dist/repo/adapters/rust.js.map +1 -1
  78. package/node_modules/@diffci.com/core/dist/repo/adapters/types.d.ts +10 -0
  79. package/node_modules/@diffci.com/core/dist/repo/adapters/types.js.map +1 -1
  80. package/node_modules/@diffci.com/core/dist/repo/file-references.d.ts +16 -0
  81. package/node_modules/@diffci.com/core/dist/repo/file-references.js +76 -5
  82. package/node_modules/@diffci.com/core/dist/repo/file-references.js.map +1 -1
  83. package/node_modules/@diffci.com/core/dist/repo/graph.js +101 -30
  84. package/node_modules/@diffci.com/core/dist/repo/graph.js.map +1 -1
  85. package/node_modules/@diffci.com/core/dist/repo/impact.d.ts +7 -0
  86. package/node_modules/@diffci.com/core/dist/repo/impact.js +56 -9
  87. package/node_modules/@diffci.com/core/dist/repo/impact.js.map +1 -1
  88. package/node_modules/@diffci.com/core/dist/repo/layout.js +4 -1
  89. package/node_modules/@diffci.com/core/dist/repo/layout.js.map +1 -1
  90. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js +10 -1
  91. package/node_modules/@diffci.com/core/dist/repo/runner-universe.js.map +1 -1
  92. package/node_modules/@diffci.com/core/dist/repo/script-universe.js +1 -1
  93. package/node_modules/@diffci.com/core/dist/repo/script-universe.js.map +1 -1
  94. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js +5 -1
  95. package/node_modules/@diffci.com/core/dist/repo/test-discovery.js.map +1 -1
  96. package/node_modules/@diffci.com/core/dist/repo/types.d.ts +3 -0
  97. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js +3 -3
  98. package/node_modules/@diffci.com/core/dist/repo/workflow-test-steps.js.map +1 -1
  99. package/node_modules/@diffci.com/core/dist/repo/yarn-berry-lockfile.d.ts +11 -0
  100. package/node_modules/@diffci.com/core/dist/repo/yarn-berry-lockfile.js +208 -0
  101. package/node_modules/@diffci.com/core/dist/repo/yarn-berry-lockfile.js.map +1 -0
  102. package/node_modules/@diffci.com/core/dist/repo/yarn-lockfile.d.ts +3 -0
  103. package/node_modules/@diffci.com/core/dist/repo/yarn-lockfile.js +2 -2
  104. package/node_modules/@diffci.com/core/dist/repo/yarn-lockfile.js.map +1 -1
  105. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js +65 -13
  106. package/node_modules/@diffci.com/core/dist/research/baseline/matcher.js.map +1 -1
  107. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js +47 -2
  108. package/node_modules/@diffci.com/core/dist/research/baseline/workflow-parser.js.map +1 -1
  109. package/node_modules/@diffci.com/core/package.json +1 -0
  110. package/node_modules/@diffci.com/core/src/ci-inference/expression.ts +38 -5
  111. package/node_modules/@diffci.com/core/src/ci-inference/infer.ts +21 -6
  112. package/node_modules/@diffci.com/core/src/ci-inference/jobs.ts +7 -2
  113. package/node_modules/@diffci.com/core/src/ci-inference/matrix.ts +15 -8
  114. package/node_modules/@diffci.com/core/src/ci-inference/purpose.ts +6 -2
  115. package/node_modules/@diffci.com/core/src/ci-inference/resolve.ts +37 -5
  116. package/node_modules/@diffci.com/core/src/git/ci-config-paths.ts +8 -1
  117. package/node_modules/@diffci.com/core/src/git/git-diff.ts +57 -32
  118. package/node_modules/@diffci.com/core/src/planner/check-narrowing.ts +22 -1
  119. package/node_modules/@diffci.com/core/src/planner/pipeline-steps.ts +13 -2
  120. package/node_modules/@diffci.com/core/src/planner/planner.ts +42 -14
  121. package/node_modules/@diffci.com/core/src/planner/rust-command.ts +37 -1
  122. package/node_modules/@diffci.com/core/src/planner/script-reads.ts +5 -1
  123. package/node_modules/@diffci.com/core/src/planner/test-command.ts +17 -2
  124. package/node_modules/@diffci.com/core/src/planner/type-program.ts +25 -1
  125. package/node_modules/@diffci.com/core/src/repo/adapters/go.ts +5 -1
  126. package/node_modules/@diffci.com/core/src/repo/adapters/maven.ts +74 -9
  127. package/node_modules/@diffci.com/core/src/repo/adapters/python.ts +209 -18
  128. package/node_modules/@diffci.com/core/src/repo/adapters/rust-invocation.ts +44 -6
  129. package/node_modules/@diffci.com/core/src/repo/adapters/rust.ts +264 -24
  130. package/node_modules/@diffci.com/core/src/repo/adapters/types.ts +10 -1
  131. package/node_modules/@diffci.com/core/src/repo/file-references.ts +70 -5
  132. package/node_modules/@diffci.com/core/src/repo/graph.ts +82 -21
  133. package/node_modules/@diffci.com/core/src/repo/impact.ts +57 -8
  134. package/node_modules/@diffci.com/core/src/repo/layout.ts +5 -1
  135. package/node_modules/@diffci.com/core/src/repo/runner-universe.ts +11 -1
  136. package/node_modules/@diffci.com/core/src/repo/script-universe.ts +1 -1
  137. package/node_modules/@diffci.com/core/src/repo/test-discovery.ts +4 -1
  138. package/node_modules/@diffci.com/core/src/repo/types.ts +3 -1
  139. package/node_modules/@diffci.com/core/src/repo/workflow-test-steps.ts +3 -3
  140. package/node_modules/@diffci.com/core/src/repo/yarn-berry-lockfile.ts +178 -0
  141. package/node_modules/@diffci.com/core/src/repo/yarn-lockfile.ts +2 -2
  142. package/node_modules/@diffci.com/core/src/research/baseline/matcher.ts +43 -13
  143. package/node_modules/@diffci.com/core/src/research/baseline/workflow-parser.ts +44 -2
  144. package/package.json +2 -2
@@ -13,10 +13,11 @@ import { contribution, type AdapterContext, type AdapterContribution, type Repos
13
13
  * WHAT. The import graph comes from Python's own `ast` module, run once over every `.py` file (a short
14
14
  * script on stdin; no repository code is imported or executed, unlike `pytest --collect-only`, which runs
15
15
  * conftest.py). DiffCI resolves each import against the repository root, `src/`, pytest's `pythonpath`
16
- * and, for a file in a directory without `__init__.py`, that directory (pytest's default `prepend`
17
- * import mode puts it on sys.path). Importing `a.b.c` also reaches `a/__init__.py` and `a/b/__init__.py`,
16
+ * and each file's basedir: its own directory when that has no `__init__.py`, otherwise the first
17
+ * directory above its package (pytest's default `prepend` import mode puts the basedir on sys.path). Importing `a.b.c` also reaches `a/__init__.py` and `a/b/__init__.py`,
18
18
  * which run on import. Tests follow pytest's `python_files` and `testpaths`; each test also depends on
19
- * every `conftest.py` from its directory up to the root, which pytest loads before it.
19
+ * every `conftest.py` from its directory up to the root, which pytest loads before it, and on every
20
+ * plugin module that `addopts` loads with `-p`.
20
21
  *
21
22
  * Full validation instead, as global blockers: no Python interpreter, a file that does not parse, an
22
23
  * `importlib.import_module` / `__import__` / `pytest_plugins` entry whose name is computed, a first-party
@@ -64,15 +65,23 @@ export type PythonImport = [module: string, level: number, names: string[]];
64
65
  export interface PythonFileImports { imports?: PythonImport[]; dynamic?: boolean; error?: string }
65
66
 
66
67
  const EXCLUDED_DIRS = new Set([".venv", "venv", "env", ".env", ".tox", ".nox", "site-packages", "__pycache__", ".eggs", ".mypy_cache", ".pytest_cache", ".ruff_cache"]);
67
- const PROJECT_FILES = ["pyproject.toml", "setup.py", "setup.cfg", "pytest.ini", "tox.ini", "conftest.py"];
68
+ const PROJECT_FILES = ["pyproject.toml", "setup.py", "setup.cfg", "pytest.toml", ".pytest.toml", "pytest.ini", ".pytest.ini", "tox.ini", "conftest.py"];
68
69
 
69
70
  export function isPythonSource(path: string): boolean {
70
71
  return path.endsWith(".py") && !path.split("/").some((part) => EXCLUDED_DIRS.has(part) || part.endsWith(".egg-info"));
71
72
  }
72
73
 
73
- /** The first interpreter that runs: `python3`, `python`, then the Windows launcher `py -3`. */
74
+ /** The interpreters `pythonInterpreter()` tries, in order: `python3`, `python`, then the Windows launcher `py -3`. */
75
+ export const PYTHON_INTERPRETER_CANDIDATES: readonly (readonly string[])[] = [["python3"], ["python"], ["py", "-3"]];
76
+
77
+ /**
78
+ * The first of `PYTHON_INTERPRETER_CANDIDATES` that runs Python 3. Each call probes again, so two calls
79
+ * can disagree when a launcher is slow or flaky (a Windows `python3` alias stub); use the interpreter
80
+ * the analysis recorded (`profile.pythonInterpreter`) rather than a second probe (#304).
81
+ */
74
82
  export function pythonInterpreter(cwd: string): string[] | undefined {
75
- for (const candidate of [["python3"], ["python"], ["py", "-3"]]) {
83
+ for (const entry of PYTHON_INTERPRETER_CANDIDATES) {
84
+ const candidate = [...entry];
76
85
  const result = spawnSync(candidate[0]!, [...candidate.slice(1), "-c", "import sys; print(sys.version_info[0])"], { cwd, encoding: "utf8", timeout: 10_000, windowsHide: true });
77
86
  if (result.status === 0 && result.stdout.trim() === "3") return candidate;
78
87
  }
@@ -83,6 +92,8 @@ export interface PytestSettings {
83
92
  pythonFiles: string[];
84
93
  testpaths: string[];
85
94
  pythonpath: string[];
95
+ /** Plugin modules `addopts` loads with `-p`; every test depends on them. */
96
+ plugins?: string[];
86
97
  /** A key that is present but could not be read; its file makes the analysis fall back. */
87
98
  unreadable?: string;
88
99
  }
@@ -91,27 +102,168 @@ function splitList(value: string): string[] {
91
102
  return value.split(/[\s,]+/).map((entry) => entry.replace(/^["']|["']$/g, "")).filter(Boolean);
92
103
  }
93
104
 
105
+ /**
106
+ * The strings of a TOML array of strings that starts with `[` at `start`. Comments, commas and line breaks
107
+ * between the strings are skipped, and a `]`, `,` or `#` inside a quoted string stays part of the value.
108
+ * Anything else (a nested array, a number, a multi-line string, an escape it cannot read, no closing `]`)
109
+ * returns undefined, so the caller can fall back instead of guessing.
110
+ */
111
+ function readTomlStringArray(text: string, start: number): string[] | undefined {
112
+ const values: string[] = [];
113
+ const escapes: Record<string, string> = { "\\": "\\", '"': '"', b: "\b", t: "\t", n: "\n", f: "\f", r: "\r" };
114
+ let index = start + 1;
115
+ let expectValue = true;
116
+ while (index < text.length) {
117
+ const char = text[index]!;
118
+ if (char === " " || char === "\t" || char === "\r" || char === "\n") index += 1;
119
+ else if (char === "#") {
120
+ const end = text.indexOf("\n", index);
121
+ index = end === -1 ? text.length : end;
122
+ } else if (char === "]") return values;
123
+ else if (char === ",") {
124
+ if (expectValue) return undefined;
125
+ expectValue = true;
126
+ index += 1;
127
+ } else if ((char === '"' || char === "'") && expectValue) {
128
+ if (text.startsWith(char.repeat(3), index)) return undefined;
129
+ let value = "";
130
+ index += 1;
131
+ for (;;) {
132
+ const next = text[index];
133
+ if (next === undefined || next === "\n") return undefined;
134
+ if (next === char) break;
135
+ if (next === "\\" && char === '"') {
136
+ const escaped = escapes[text[index + 1] ?? ""];
137
+ if (escaped === undefined) return undefined;
138
+ value += escaped;
139
+ index += 2;
140
+ } else {
141
+ value += next;
142
+ index += 1;
143
+ }
144
+ }
145
+ index += 1;
146
+ values.push(value);
147
+ expectValue = false;
148
+ } else return undefined;
149
+ }
150
+ return undefined;
151
+ }
152
+
94
153
  /** pytest's own configuration, from the first file pytest would use. Only the keys selection depends on. */
95
154
  export function readPytestSettings(read: (path: string) => string | undefined): PytestSettings {
96
155
  const settings: PytestSettings = { pythonFiles: ["test_*.py", "*_test.py"], testpaths: [], pythonpath: [] };
97
- const keys = ["python_files", "testpaths", "pythonpath"] as const;
156
+ const keys = ["python_files", "testpaths", "pythonpath", "addopts"] as const;
98
157
  const apply = (key: (typeof keys)[number], values: string[]) => {
99
158
  if (key === "python_files") settings.pythonFiles = values;
100
- else settings[key] = values;
159
+ else if (key === "addopts") {
160
+ // `-p name` and `-pname` import a plugin module before collection; `-p no:name` disables one.
161
+ const plugins = values.flatMap((value, index) => value === "-p" ? [values[index + 1] ?? ""] : value.startsWith("-p") && !value.startsWith("--") ? [value.slice(2)] : [])
162
+ .filter((name) => !name.startsWith("no:"));
163
+ if (plugins.length) settings.plugins = plugins;
164
+ } else settings[key] = values;
165
+ };
166
+ const escape = (text: string) => text.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
167
+ const isToml = (file: string) => file.endsWith(".toml");
168
+ // A table header may be indented and followed by a comment (`[pytest] # selection`). TOML also allows
169
+ // spaces inside the brackets and quoted keys (`[ pytest ]`, `[tool."pytest"]`), which this reader doesn't
170
+ // match: a header that only matches with spaces and quotes removed makes the file unreadable instead.
171
+ const section = (file: string, text: string, header: string): string | undefined => {
172
+ const comment = isToml(file) ? "#" : "#;";
173
+ return new RegExp(`^[ \\t]*\\[${escape(header)}\\][ \\t]*(?:[${comment}].*)?$([\\s\\S]*?)(?=^[ \\t]*\\[|(?![\\s\\S]))`, "m").exec(text)?.[1];
174
+ };
175
+ const looseHeader = (file: string, text: string, header: string): boolean =>
176
+ isToml(file) && [...text.matchAll(/^[ \t]*\[([^\]\n]*)\]/gm)].some((match) =>
177
+ match[1]!.replace(/[\s"']/g, "") === header && section(file, match[0]!.trim(), header) === undefined);
178
+ const hasEntries = (body: string) => /^[ \t]*[^\s#]/m.test(body);
179
+ const keyAt = (key: string) => `^[ \\t]*${key}[ \\t]*=`;
180
+ // A quoted or dotted key (`"testpaths" = …`, `ini_options.testpaths = …`) can't be told apart from the
181
+ // keys selection reads, so a TOML table with one is unreadable.
182
+ const unclassified = (body: string) => /^[ \t]*(?:"[^"\n]*"|'[^'\n]*'|[A-Za-z0-9_-]+)[ \t]*\./m.test(body) ||
183
+ /^[ \t]*(?:"[^"\n]*"|'[^'\n]*')[ \t]*=/m.test(body);
184
+ // pytest 9's native TOML mode (`pytest.toml`, `[tool.pytest]`): every key selection reads is a list of
185
+ // strings, and each `addopts` item is one argument. Any other type is an error in pytest, so it can't be read.
186
+ const readNative = (file: string, body: string) => {
187
+ if (unclassified(body)) { settings.unreadable = `${file} key DiffCI can't classify`; return settings; }
188
+ for (const key of keys) {
189
+ const array = new RegExp(`${keyAt(key)}[ \\t]*(?=\\[)`, "m").exec(body);
190
+ if (array) {
191
+ const values = readTomlStringArray(body, array.index + array[0].length);
192
+ if (values) apply(key, values);
193
+ else settings.unreadable = `${file} ${key}`;
194
+ } else if (new RegExp(keyAt(key), "m").test(body)) settings.unreadable = `${file} ${key}`;
195
+ }
196
+ return settings;
101
197
  };
102
- for (const [file, header] of [["pytest.ini", "pytest"], ["pyproject.toml", "tool.pytest.ini_options"], ["tox.ini", "pytest"], ["setup.cfg", "tool:pytest"]] as const) {
198
+ const order = [["pytest.toml", "pytest"], [".pytest.toml", "pytest"], ["pytest.ini", "pytest"], [".pytest.ini", "pytest"], ["pyproject.toml", "tool.pytest.ini_options"], ["tox.ini", "pytest"], ["setup.cfg", "tool:pytest"]] as const;
199
+ // pytest before 9 ignores `pytest.toml`, `.pytest.toml` and `[tool.pytest]`, and uses the first of the
200
+ // other files that matches. When a native config wins and such a file also exists, the answer depends on
201
+ // the installed pytest, so it can't be read.
202
+ const olderPytestFile = (from: number): string | undefined => {
203
+ for (const [file, header] of order.slice(from)) {
204
+ const text = read(file);
205
+ if (text === undefined || file === ".pytest.toml") continue;
206
+ if (file === "pytest.ini" || file === ".pytest.ini" || section(file, text, header) !== undefined) return file;
207
+ }
208
+ return undefined;
209
+ };
210
+ const native = (file: string, body: string | undefined, index: number) => {
211
+ const older = olderPytestFile(index);
212
+ if (older) { settings.unreadable = `${file} is ignored before pytest 9, which reads ${older}`; return settings; }
213
+ return body === undefined ? settings : readNative(file, body);
214
+ };
215
+ // pytest's search order. `pytest.toml`, `.pytest.toml`, `pytest.ini` and `.pytest.ini` match even when
216
+ // empty or without their `[pytest]` table, and then pytest uses its defaults; the other files only match
217
+ // with their section. The first match wins and options are never merged.
218
+ for (const [index, [file, header]] of order.entries()) {
103
219
  const text = read(file);
104
220
  if (text === undefined) continue;
105
- const section = new RegExp(`^\\[${header.replace(/[.:]/g, "\\$&")}\\]\\s*$([\\s\\S]*?)(?=^\\[|(?![\\s\\S]))`, "m").exec(text);
106
- if (!section) continue;
107
- const body = section[1]!;
221
+ if (looseHeader(file, text, "pytest") || looseHeader(file, text, "tool.pytest") || looseHeader(file, text, "tool.pytest.ini_options")) {
222
+ settings.unreadable = `${file} pytest table header DiffCI can't read`;
223
+ return settings;
224
+ }
225
+ if (file === "pytest.toml" || file === ".pytest.toml") {
226
+ const body = section(file, text, "pytest");
227
+ // pytest rejects options written above any table.
228
+ if (body === undefined && hasEntries(text.split(/^[ \t]*\[/m, 1)[0]!)) { settings.unreadable = `${file} options outside [pytest]`; return settings; }
229
+ return native(file, body, index + 1);
230
+ }
231
+ if (file === "pyproject.toml") {
232
+ // `[tool.pytest]` holds native TOML values, `[tool.pytest.ini_options]` INI-style ones. pytest refuses a
233
+ // file that sets both, and an `ini_options` key inside `[tool.pytest]` is a form this reader doesn't parse.
234
+ const nativeBody = section(file, text, "tool.pytest");
235
+ const ini = section(file, text, header);
236
+ if (nativeBody !== undefined && new RegExp(`^[ \\t]*ini_options[ \\t]*[.=]`, "m").test(nativeBody)) { settings.unreadable = `${file} [tool.pytest] ini_options`; return settings; }
237
+ if (nativeBody !== undefined && hasEntries(nativeBody)) {
238
+ if (ini !== undefined && hasEntries(ini)) { settings.unreadable = `${file} [tool.pytest] and [tool.pytest.ini_options]`; return settings; }
239
+ // An empty [tool.pytest.ini_options] beside it is what pytest 8 reads.
240
+ if (ini !== undefined) { settings.unreadable = `${file} [tool.pytest] is ignored before pytest 9, which reads [tool.pytest.ini_options]`; return settings; }
241
+ return native(file, nativeBody, index + 1);
242
+ }
243
+ }
244
+ const body = section(file, text, header);
245
+ if (body === undefined) {
246
+ if (file === "pytest.ini" || file === ".pytest.ini") return settings;
247
+ continue;
248
+ }
249
+ if (file === "pyproject.toml" && unclassified(body)) { settings.unreadable = `${file} key DiffCI can't classify`; return settings; }
108
250
  for (const key of keys) {
109
251
  if (file === "pyproject.toml") {
110
- const match = new RegExp(`^${key}\\s*=\\s*(\\[[\\s\\S]*?\\]|"[^"]*"|'[^']*')`, "m").exec(body);
111
- if (match) apply(key, splitList(match[1]!.replace(/^\[|\]$/g, "")));
112
- else if (new RegExp(`^${key}\\s*=`, "m").test(body)) settings.unreadable = `${file} ${key}`;
252
+ const match = new RegExp(`${keyAt(key)}[ \\t]*("[^"]*"|'[^']*')`, "m").exec(body);
253
+ const array = new RegExp(`${keyAt(key)}[ \\t]*(?=\\[)`, "m").exec(body);
254
+ // A multi-line string would otherwise match as an empty one. Its contents are read as one string;
255
+ // a basic string's line-ending backslash only joins lines. An unterminated one cannot be read.
256
+ const multiline = new RegExp(`${keyAt(key)}[ \\t]*("""|'{3})([\\s\\S]*?)\\1`, "m").exec(body);
257
+ if (multiline) apply(key, splitList(multiline[1] === '"""' ? multiline[2]!.replace(/\\\r?\n/g, " ") : multiline[2]!));
258
+ else if (new RegExp(`${keyAt(key)}[ \\t]*(?:"""|'{3})`, "m").test(body)) settings.unreadable = `${file} ${key}`;
259
+ else if (array) {
260
+ const values = readTomlStringArray(body, array.index + array[0].length);
261
+ if (values) apply(key, key === "addopts" ? values.flatMap(splitList) : values);
262
+ else settings.unreadable = `${file} ${key}`;
263
+ } else if (match) apply(key, splitList(match[1]!));
264
+ else if (new RegExp(keyAt(key), "m").test(body)) settings.unreadable = `${file} ${key}`;
113
265
  } else {
114
- // INI values continue on indented lines.
266
+ // INI values continue on indented lines, so a key starts at the beginning of a line.
115
267
  const match = new RegExp(`^${key}\\s*=\\s*(.*(?:\\r?\\n[ \\t]+.*)*)`, "m").exec(body);
116
268
  if (match) apply(key, splitList(match[1]!));
117
269
  }
@@ -125,13 +277,30 @@ function globToRegExp(glob: string): RegExp {
125
277
  return new RegExp(`^${glob.replace(/[.+^${}()|\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]")}$`);
126
278
  }
127
279
 
280
+ /** One path segment against one shell-style glob segment, as Python's `fnmatch` reads it. */
281
+ function segmentMatches(glob: string, segment: string): boolean {
282
+ const source = glob.replace(/\[!/g, "[^").replace(/[.+${}()|\\]/g, "\\$&").replace(/\*/g, "[^/]*").replace(/\?/g, "[^/]");
283
+ try { return new RegExp(`^${source}$`).test(segment); } catch { return glob === segment; }
284
+ }
285
+
286
+ /** Whether `segments` starts with directories (or is a file) that `glob` names; `**` spans any depth. */
287
+ function globPrefixMatches(glob: readonly string[], segments: readonly string[]): boolean {
288
+ if (!glob.length) return true;
289
+ const [head, ...rest] = glob;
290
+ if (head === "**") return segments.some((_, index) => globPrefixMatches(rest, segments.slice(index))) || globPrefixMatches(rest, []);
291
+ return segments.length > 0 && segmentMatches(head!, segments[0]!) && globPrefixMatches(rest, segments.slice(1));
292
+ }
293
+
128
294
  export function isPytestFile(path: string, settings: PytestSettings): boolean {
129
295
  const base = posix.basename(path);
130
296
  if (!settings.pythonFiles.some((glob) => globToRegExp(glob).test(base))) return false;
131
297
  if (!settings.testpaths.length) return true;
132
298
  return settings.testpaths.some((root) => {
133
299
  const clean = root.replace(/^\.\//, "").replace(/\/$/, "");
134
- return clean === "." || clean === "" || path === clean || path.startsWith(`${clean}/`);
300
+ if (clean === "." || clean === "") return true;
301
+ // pytest expands each testpaths entry with glob.iglob(entry, recursive=True).
302
+ if (/[*?[]/.test(clean)) return globPrefixMatches(clean.split("/"), path.split("/"));
303
+ return path === clean || path.startsWith(`${clean}/`);
135
304
  });
136
305
  }
137
306
 
@@ -172,12 +341,24 @@ export function resolvePythonGraph(files: readonly string[], parsed: Record<stri
172
341
  return [candidate, ...inits];
173
342
  };
174
343
  const isPackageDir = (dir: string) => known.has(dir ? `${dir}/__init__.py` : "__init__.py");
344
+ // pytest's default `prepend` import mode puts the basedir on sys.path: the file's own directory when
345
+ // it is not in a package, otherwise the first directory above its package (the nearest ancestor
346
+ // without `__init__.py`). Undefined when the package reaches the repository root.
347
+ const basedirOf = (dir: string): string | undefined => {
348
+ let base = dir;
349
+ while (isPackageDir(base)) {
350
+ if (!base) return undefined;
351
+ base = posix.dirname(base) === "." ? "" : posix.dirname(base);
352
+ }
353
+ return base;
354
+ };
175
355
  for (const file of files) {
176
356
  const entry = parsed[file];
177
357
  if (!entry || entry.error) { blockers.push(`Python file could not be parsed (${entry?.error ?? "no result"}): ${file}`); continue; }
178
358
  if (entry.dynamic) blockers.push(`Python computed import in ${file}; full validation required`);
179
359
  const dir = posix.dirname(file) === "." ? "" : posix.dirname(file);
180
- const fileRoots = isPackageDir(dir) ? roots : [...roots, dir];
360
+ const basedir = basedirOf(dir);
361
+ const fileRoots = basedir === undefined || roots.includes(basedir) ? roots : [...roots, basedir];
181
362
  const add = (targets: string[] | undefined) => { for (const to of targets ?? []) edge(file, to); };
182
363
  for (const [module, level, names] of entry.imports ?? []) {
183
364
  if (level > 0) {
@@ -203,6 +384,16 @@ export function resolvePythonGraph(files: readonly string[], parsed: Record<stri
203
384
  }
204
385
  // pytest loads every conftest.py from the rootdir down to the test's directory first.
205
386
  if (tests.has(file)) {
387
+ // Plugins named by `-p` in addopts are imported before any test is collected.
388
+ for (const plugin of settings.plugins ?? []) {
389
+ const parts = plugin.split(".");
390
+ const target = roots.map((root) => moduleFiles(root, parts)).find(Boolean);
391
+ if (target) add(target);
392
+ else if (!plugin || firstParty.has(parts[0]!)) {
393
+ const blocker = `Unresolved pytest plugin in addopts: -p ${plugin}`;
394
+ if (!blockers.includes(blocker)) blockers.push(blocker);
395
+ }
396
+ }
206
397
  const segments = dir ? dir.split("/") : [];
207
398
  for (let depth = 0; depth <= segments.length; depth += 1) {
208
399
  const conftest = [...segments.slice(0, depth), "conftest.py"].join("/");
@@ -8,6 +8,11 @@ function record(value: unknown): value is Record<string, unknown> {
8
8
 
9
9
  const plain = (value: unknown): boolean => typeof value === "string" && value.trim() === "cargo test";
10
10
 
11
+ /** `--workspace` (or its old name `--all`) tests every member. That is plain `cargo test` exactly when
12
+ * plain `cargo test` already covers every member: a single crate, or a virtual workspace without
13
+ * `default-members`. The adapter says which. */
14
+ const wholeWorkspace = (value: unknown): boolean => typeof value === "string" && /^cargo test --(?:workspace|all)$/.test(value.trim());
15
+
11
16
  /** Steps that install a toolchain, restore caches or check out the code. They choose which compiler
12
17
  * runs, the same for the selected and the full command, but not which tests run or with what flags. */
13
18
  const SETUP_ACTION = /^(?:actions\/checkout|actions\/cache(?:\/restore)?|actions\/upload-artifact|Swatinem\/rust-cache|dtolnay\/rust-toolchain|actions-rust-lang\/setup-rust-toolchain|actions-rs\/toolchain)@[A-Za-z0-9._/-]+$/;
@@ -16,12 +21,44 @@ const SETUP_ACTION = /^(?:actions\/checkout|actions\/cache(?:\/restore)?|actions
16
21
  * per step: chaining, substitution or redirection could hide another invocation. */
17
22
  const NON_TEST_COMMAND = /^(?:cargo (?:build|check|clippy|fmt|doc)|rustup (?:component|target|toolchain|default|show|update))(?: [A-Za-z0-9_.,:=@+/-]+)*$/;
18
23
 
24
+ /** rustup commands chained with `&&` (`rustup default stable && rustup update --no-self-update`),
25
+ * where an argument may be a matrix value. Only rustup, so the chain cannot hide a test run. */
26
+ const RUSTUP_ARGUMENT = String.raw`(?:[A-Za-z0-9_.,:=@+/-]+|\$\{\{ ?matrix\.([A-Za-z0-9_-]+) ?\}\})`;
27
+ const RUSTUP_COMMAND = new RegExp(String.raw`^rustup (?:component|target|toolchain|default|show|update)(?: ${RUSTUP_ARGUMENT})*$`);
28
+
29
+ /** A matrix value is pasted into the script as text, so each one a rustup step uses must be a plain
30
+ * toolchain-like word, in the matrix and in every `include` entry. */
31
+ function plainMatrixValues(strategy: unknown, key: string): boolean {
32
+ if (!record(strategy) || !record(strategy.matrix)) return false;
33
+ const word = (value: unknown) => (typeof value === "string" || typeof value === "number") && /^[A-Za-z0-9_.-]+$/.test(String(value));
34
+ const values = strategy.matrix[key];
35
+ const include = strategy.matrix.include;
36
+ if (include !== undefined && (!Array.isArray(include) || include.some(entry => !record(entry) || (key in entry && !word(entry[key]))))) return false;
37
+ if (values === undefined) return Array.isArray(include) && include.some(entry => record(entry) && key in entry);
38
+ return Array.isArray(values) && values.length > 0 && values.every(word);
39
+ }
40
+
41
+ function setupCommand(run: string, strategy: unknown): boolean {
42
+ if (NON_TEST_COMMAND.test(run)) return true;
43
+ const parts = run.split(" && ");
44
+ return parts.every(part => {
45
+ if (!RUSTUP_COMMAND.test(part)) return false;
46
+ return [...part.matchAll(/\$\{\{ ?matrix\.([A-Za-z0-9_-]+) ?\}\}/g)].every(match => plainMatrixValues(strategy, match[1]!));
47
+ });
48
+ }
49
+
19
50
  /** Environment that changes output or retries, never what is compiled or tested. */
20
- const NEUTRAL_ENV = new Set(["CARGO_TERM_COLOR", "CARGO_INCREMENTAL", "CARGO_NET_RETRY", "CARGO_NET_GIT_FETCH_WITH_CLI",
51
+ const NEUTRAL_ENV = new Set(["CARGO_TERM_COLOR", "CARGO_TERM_VERBOSE", "CARGO_INCREMENTAL", "CARGO_NET_RETRY", "CARGO_NET_GIT_FETCH_WITH_CLI",
21
52
  "CARGO_REGISTRIES_CRATES_IO_PROTOCOL", "RUST_BACKTRACE", "RUSTUP_MAX_RETRIES", "CI"]);
22
53
 
54
+ /** `RUSTFLAGS: -Dwarnings` (and the same for rustdoc) turns warnings into errors. It changes neither
55
+ * what is compiled nor which tests run, and applies equally to the selected and the full command.
56
+ * Any other flag (cfg, codegen, target features, sanitizers) still makes the evidence advisory. */
57
+ const DENY_WARNINGS = /^\s*(?:(?:-D ?warnings|--deny[= ]warnings)\s*)+$/;
58
+
23
59
  const neutralEnv = (value: unknown): boolean => value === undefined || record(value)
24
- && Object.entries(value).every(([key, setting]) => NEUTRAL_ENV.has(key) && ["string", "number", "boolean"].includes(typeof setting) && !String(setting).includes("${{"));
60
+ && Object.entries(value).every(([key, setting]) => ["string", "number", "boolean"].includes(typeof setting) && !String(setting).includes("${{")
61
+ && (NEUTRAL_ENV.has(key) || ["RUSTFLAGS", "RUSTDOCFLAGS"].includes(key) && DENY_WARNINGS.test(String(setting))));
25
62
 
26
63
  /** Workflow and job keys with no effect on how a step's command runs. */
27
64
  const WORKFLOW_KEYS = new Set(["name", "run-name", "on", "true", "permissions", "concurrency", "env", "jobs"]);
@@ -31,8 +68,9 @@ const TEST_STEP_KEYS = new Set(["name", "id", "run", "env", "timeout-minutes"]);
31
68
 
32
69
  /** Evidence for the one invocation whose flags and execution context we can reproduce.
33
70
  * Do not turn a Cargo manifest, a wrapper or a feature-specific CI run into plain cargo test. */
34
- export function rustTestInvocation(repoPath: string, files: readonly string[]): "cargo test" | undefined {
71
+ export function rustTestInvocation(repoPath: string, files: readonly string[], options: { allMembersTested?: boolean } = {}): "cargo test" | undefined {
35
72
  let found = false;
73
+ const testCommand = (value: unknown) => plain(value) || options.allMembersTested === true && wholeWorkspace(value);
36
74
  if (files.includes("package.json")) {
37
75
  try {
38
76
  const manifest: unknown = JSON.parse(readFileSync(join(repoPath, "package.json"), "utf8"));
@@ -41,7 +79,7 @@ export function rustTestInvocation(repoPath: string, files: readonly string[]):
41
79
  if (!record(manifest.scripts)) return undefined;
42
80
  // A plain command under an unrelated script name is not evidence that the actual
43
81
  // test entrypoint has the same semantics. Unknown scripts may wrap additional suites.
44
- if (!plain(manifest.scripts.test) || Object.values(manifest.scripts).some(script => !plain(script))) return undefined;
82
+ if (!testCommand(manifest.scripts.test) || Object.values(manifest.scripts).some(script => !testCommand(script))) return undefined;
45
83
  if (Object.keys(manifest.scripts).some(name => /^(?:pre|post)/.test(name))) return undefined;
46
84
  found = true;
47
85
  }
@@ -61,11 +99,11 @@ export function rustTestInvocation(repoPath: string, files: readonly string[]):
61
99
  for (const step of job.steps) {
62
100
  if (!record(step)) return undefined;
63
101
  if ("run" in step) {
64
- if (plain(step.run)) {
102
+ if (testCommand(step.run)) {
65
103
  // The test step itself runs unconditionally, in the checkout root, with the default shell.
66
104
  if (Object.keys(step).some(key => !TEST_STEP_KEYS.has(key)) || !neutralEnv(step.env)) return undefined;
67
105
  found = true;
68
- } else if (typeof step.run !== "string" || !NON_TEST_COMMAND.test(step.run.trim())
106
+ } else if (typeof step.run !== "string" || !setupCommand(step.run.trim(), job.strategy)
69
107
  || Object.keys(step).some(key => !["name", "id", "run", "env", "if", "timeout-minutes", "continue-on-error"].includes(key)) || !neutralEnv(step.env)) {
70
108
  // Wrappers, nextest, cargo make, just, other `cargo test` flags and unknown scripts are
71
109
  // not reproduced, before or after the test and in any job.