1use std::{
9 collections::{BTreeMap, BTreeSet},
10 fs,
11 path::{Path, PathBuf},
12};
13
14use serde_json::json;
15
16use crate::{
17 coverage_report::CoverageManifest,
18 integrity::ExplicitIntegrityInputs,
19 python_instrumenter::{
20 PYTHON_PROBE_PLAN_VERSION, PythonFilePlan, PythonProbePlan, build_python_obligations,
21 },
22 source_discovery::{SourceScope, SourceScopeEntry, SourceScopeMode, SourceScopeStatus},
23};
24
25pub const UNPARSEABLE_LIMITATION: &str = "python-source-unparseable";
26
27const EXCLUDED_DIRECTORIES: &[&str] = &[
29 ".git",
30 ".hg",
31 ".svn",
32 ".supercov",
33 ".mcdc-pool",
34 ".cache",
35 "node_modules",
36 "__pycache__",
37 ".venv",
38 "venv",
39 ".env",
40 "env",
41 ".tox",
42 ".nox",
43 ".mypy_cache",
44 ".pytest_cache",
45 ".ruff_cache",
46 ".hypothesis",
47 ".eggs",
48 "build",
49 "dist",
50 "target",
51 "site-packages",
52 "htmlcov",
53];
54
55const DEPENDENCY_FILES: &[&str] = &[
56 "pyproject.toml",
57 "setup.cfg",
58 "setup.py",
59 "requirements.txt",
60 "requirements-dev.txt",
61 "Pipfile",
62 "Pipfile.lock",
63 "poetry.lock",
64 "uv.lock",
65 "pdm.lock",
66];
67
68#[derive(Debug, Clone, PartialEq, Eq, Default)]
69pub struct PythonFiles {
70 pub sources: Vec<String>,
72 pub tests: Vec<String>,
74 pub dependency_files: Vec<PathBuf>,
75 pub configuration_files: Vec<PathBuf>,
76 pub excluded: Vec<(String, &'static str)>,
77}
78
79#[derive(Debug, Clone, PartialEq)]
80pub struct PreparedPythonProject {
81 pub root: PathBuf,
82 pub files: PythonFiles,
83 pub manifest: CoverageManifest,
84 pub plan: PythonProbePlan,
85 pub unparseable: Vec<(String, String)>,
86}
87
88fn is_venv(directory: &Path) -> bool {
89 fs::symlink_metadata(directory.join("pyvenv.cfg")).is_ok()
90}
91
92fn is_test_path(relative: &str) -> Option<&'static str> {
93 let mut components = relative.split('/').peekable();
94 let mut file_name = "";
95 while let Some(component) = components.next() {
96 if components.peek().is_none() {
97 file_name = component;
98 break;
99 }
100 if matches!(component, "tests" | "test" | "testing" | "__tests__") {
101 return Some("inside a test directory");
102 }
103 }
104 if file_name == "conftest.py" {
105 return Some("pytest conftest");
106 }
107 if file_name.starts_with("test_") && file_name.ends_with(".py") {
108 return Some("test module by name");
109 }
110 if file_name.ends_with("_test.py") || file_name.ends_with("_tests.py") {
111 return Some("test module by name");
112 }
113 if matches!(
114 file_name,
115 "setup.py" | "noxfile.py" | "tasks.py" | "fabfile.py"
116 ) {
117 return Some("build/test tooling script");
118 }
119 None
120}
121
122fn walk(
123 root: &Path,
124 directory: &Path,
125 files: &mut PythonFiles,
126 all_python: &mut Vec<String>,
127) -> Result<(), String> {
128 let mut entries = fs::read_dir(directory)
129 .map_err(|error| format!("{}: {error}", directory.display()))?
130 .collect::<Result<Vec<_>, _>>()
131 .map_err(|error| error.to_string())?;
132 entries.sort_by_key(fs::DirEntry::file_name);
133 for entry in entries {
134 let path = entry.path();
135 let name = entry.file_name().into_string().map_err(|_| {
136 format!(
137 "Python project contains a non-UTF-8 path: {}",
138 path.display()
139 )
140 })?;
141 let file_type = entry.file_type().map_err(|error| error.to_string())?;
142 let relative = path
143 .strip_prefix(root)
144 .map_err(|_| format!("path escaped root: {}", path.display()))?
145 .to_string_lossy()
146 .replace('\\', "/");
147 if file_type.is_dir() {
148 if EXCLUDED_DIRECTORIES.contains(&name.as_str())
149 || name.ends_with(".egg-info")
150 || is_venv(&path)
151 {
152 files
153 .excluded
154 .push((relative, "tooling or environment directory"));
155 continue;
156 }
157 walk(root, &path, files, all_python)?;
158 } else if file_type.is_file() {
159 if DEPENDENCY_FILES.contains(&name.as_str())
160 || (name.starts_with("requirements") && name.ends_with(".txt"))
161 {
162 files.dependency_files.push(PathBuf::from(&relative));
163 if name != "setup.py" {
164 continue;
165 }
166 }
167 if matches!(name.as_str(), "pytest.ini" | "tox.ini" | ".python-version") {
172 files.configuration_files.push(PathBuf::from(&relative));
173 continue;
174 }
175 if !name.ends_with(".py") {
176 continue;
177 }
178 all_python.push(relative.clone());
179 match is_test_path(&relative) {
180 Some(reason) => {
181 files.tests.push(relative.clone());
182 files.excluded.push((relative, reason));
183 }
184 None => files.sources.push(relative),
185 }
186 }
187 }
190 Ok(())
191}
192
193pub fn discover_python_files(root: &Path) -> Result<PythonFiles, String> {
194 let mut files = PythonFiles::default();
195 let mut all_python = Vec::new();
196 walk(root, root, &mut files, &mut all_python)?;
197 files.sources.sort();
198 files.tests.sort();
199 files.dependency_files.sort();
200 files.configuration_files.sort();
201 Ok(files)
202}
203
204fn limitation(id: &str, kind: &str, file: &str, reason: &str) -> serde_json::Value {
205 json!({
206 "id": id,
207 "kind": kind,
208 "file": file,
209 "line": 1,
210 "column": 0,
211 "source": "",
212 "reason": reason
213 })
214}
215
216pub fn prepare_python_project(
217 root: &Path,
218 roots: Option<&crate::source_discovery::ExplicitSourceRoots>,
219) -> Result<PreparedPythonProject, String> {
220 let mut files = discover_python_files(root)?;
221 if let Some(roots) = roots {
222 roots.narrow(&mut files.sources, &mut files.excluded, String::as_str);
223 roots.refuse_if_empty(files.sources.len(), "Python")?;
224 }
225 if files.sources.is_empty() && files.tests.is_empty() {
226 return Err(
227 "no Python source files were found under the project root; Supercov measures .py files outside virtual environments, build output and test directories".into(),
228 );
229 }
230 let mut manifest = CoverageManifest {
231 unmeasured: Vec::new(),
232 decisions: Vec::new(),
233 points: Vec::new(),
234 branches: Vec::new(),
235 limitations: Vec::new(),
236 scope: None,
237 };
238 let mut plan_files = BTreeMap::<String, PythonFilePlan>::new();
239 let mut limitation_ids = BTreeSet::new();
240 let mut unparseable = Vec::new();
241 for relative in &files.sources {
242 let path = root.join(relative);
243 let source = fs::read(&path).map_err(|error| format!("{}: {error}", path.display()))?;
244 let Ok(source) = String::from_utf8(source) else {
245 unparseable.push((relative.clone(), "source is not valid UTF-8".to_owned()));
246 continue;
247 };
248 match build_python_obligations(relative, &source) {
249 Ok(obligations) => {
250 manifest.points.extend(obligations.manifest.points);
251 manifest.decisions.extend(obligations.manifest.decisions);
252 manifest.branches.extend(obligations.manifest.branches);
253 manifest.unmeasured.extend(obligations.manifest.unmeasured);
254 for item in obligations.manifest.limitations {
255 let id = item
256 .get("id")
257 .and_then(serde_json::Value::as_str)
258 .unwrap_or_default()
259 .to_owned();
260 if limitation_ids.insert(id) {
261 manifest.limitations.push(item);
262 }
263 }
264 plan_files.insert(relative.clone(), obligations.plan);
265 }
266 Err(error) => unparseable.push((relative.clone(), error.to_string())),
267 }
268 }
269 if let Some((file, reason)) = unparseable.first()
270 && limitation_ids.insert(UNPARSEABLE_LIMITATION.into())
271 {
272 manifest.limitations.push(limitation(
273 UNPARSEABLE_LIMITATION,
274 "source-scope",
275 file,
276 &format!(
277 "{} source file(s) could not be parsed and carry no obligations; first: {file}: {reason}",
278 unparseable.len()
279 ),
280 ));
281 }
282 manifest.unmeasured.sort();
283 manifest.unmeasured.dedup();
284 let mut entries = Vec::new();
285 for file in &files.sources {
286 let unparseable_file = unparseable.iter().any(|(path, _)| path == file);
287 entries.push(SourceScopeEntry {
288 file: file.clone(),
289 status: if unparseable_file {
290 SourceScopeStatus::Excluded
291 } else {
292 SourceScopeStatus::Included
293 },
294 reason: if unparseable_file {
295 "could not be parsed".into()
296 } else {
297 "Python application source".into()
298 },
299 package_root: None,
300 });
301 }
302 for (file, reason) in &files.excluded {
303 if file.ends_with(".py") {
304 entries.push(SourceScopeEntry {
305 file: file.clone(),
306 status: SourceScopeStatus::Excluded,
307 reason: (*reason).into(),
308 package_root: None,
309 });
310 }
311 }
312 entries.sort_by(|left, right| left.file.cmp(&right.file));
313 manifest.scope = Some(
314 serde_json::to_value(SourceScope {
315 version: 1,
316 mode: if roots.is_some() {
317 SourceScopeMode::Explicit
318 } else {
319 SourceScopeMode::Automatic
320 },
321 roots: match roots {
322 Some(roots) => roots.local_roots().map_err(|error| error.to_string())?,
323 None => vec![".".into()],
324 },
325 entries,
326 })
327 .map_err(|error| error.to_string())?,
328 );
329 Ok(PreparedPythonProject {
330 root: root.to_owned(),
331 plan: PythonProbePlan {
332 version: PYTHON_PROBE_PLAN_VERSION,
333 root: root.display().to_string(),
334 files: plan_files,
335 },
336 manifest,
337 files,
338 unparseable,
339 })
340}
341
342pub fn python_integrity_inputs(files: &PythonFiles, command: &[String]) -> ExplicitIntegrityInputs {
351 let execution_configuration = command.join("\0").into_bytes();
352 ExplicitIntegrityInputs {
353 source_files: files.sources.iter().map(PathBuf::from).collect(),
354 test_files: files.tests.iter().map(PathBuf::from).collect(),
355 dependency_files: files.dependency_files.clone(),
356 configuration_files: files.configuration_files.clone(),
357 execution_configuration,
358 }
359}
360
361#[cfg(test)]
362mod tests {
363
364 #[test]
365 fn the_ambient_environment_is_not_part_of_run_identity() {
366 let files = PythonFiles::default();
371 let command = ["pytest".to_owned(), "-q".to_owned()];
372 let inputs = python_integrity_inputs(&files, &command);
373 assert_eq!(inputs.execution_configuration, b"pytest\0-q");
374 }
375 use std::time::{SystemTime, UNIX_EPOCH};
376
377 use super::*;
378
379 fn fixture(name: &str) -> PathBuf {
380 let nonce = SystemTime::now()
381 .duration_since(UNIX_EPOCH)
382 .unwrap()
383 .as_nanos();
384 let root = std::env::temp_dir().join(format!(
385 "supercov-python-project-{}-{nonce}-{name}",
386 std::process::id()
387 ));
388 fs::create_dir_all(&root).unwrap();
389 root
390 }
391
392 fn write(root: &Path, relative: &str, contents: &str) {
393 let path = root.join(relative);
394 fs::create_dir_all(path.parent().unwrap()).unwrap();
395 fs::write(path, contents).unwrap();
396 }
397
398 #[test]
399 fn a_type_checker_and_a_coverage_tool_are_not_execution_context() {
400 let root = fixture("inert-tooling");
405 write(&root, "pyproject.toml", "[project]\nname='x'\n");
406 write(&root, "mypy.ini", "[mypy]\n");
407 write(&root, ".coveragerc", "[run]\n");
408 write(&root, "pytest.ini", "[pytest]\n");
409 write(&root, ".python-version", "3.13\n");
410 write(&root, "src/pkg/core.py", "def f(a):\n return a\n");
411 let project = prepare_python_project(&root, None).unwrap();
412 assert_eq!(
413 project.files.configuration_files,
414 [
415 PathBuf::from(".python-version"),
416 PathBuf::from("pytest.ini")
417 ]
418 );
419 fs::remove_dir_all(root).unwrap();
420 }
421
422 fn scope_of(project: &PreparedPythonProject) -> crate::source_discovery::SourceScope {
423 serde_json::from_value(project.manifest.scope.clone().expect("a scope")).unwrap()
424 }
425
426 fn explicit(root: &Path, roots: &[&str]) -> crate::source_discovery::ExplicitSourceRoots {
427 let roots = roots
428 .iter()
429 .map(|root| (*root).to_owned())
430 .collect::<Vec<_>>();
431 crate::source_discovery::ExplicitSourceRoots::resolve(root, &roots).unwrap()
432 }
433
434 #[test]
435 fn explicit_roots_narrow_a_flat_layout_to_the_modules_it_names() {
436 let root = fixture("flat-roots");
442 write(&root, "a.py", "def f(x):\n return x if x else 0\n");
443 write(&root, "vendor/pkg/b.py", "def g():\n return 1\n");
444 write(&root, "test/test_a.py", "from a import f\n");
445
446 let project = prepare_python_project(&root, Some(&explicit(&root, &["a.py"]))).unwrap();
447 assert_eq!(project.files.sources, ["a.py"], "{:?}", project.files);
448 assert_eq!(
449 project.plan.files.keys().collect::<Vec<_>>(),
450 ["a.py"],
451 "the runtime is not handed a file the roots leave out, which is what \
452 keeps it from being instrumented at all"
453 );
454 assert!(
455 project
456 .files
457 .excluded
458 .contains(&("vendor/pkg/b.py".into(), "outside explicit source roots")),
459 "{:?}",
460 project.files.excluded
461 );
462 let scope = scope_of(&project);
463 assert_eq!(
464 scope.mode,
465 crate::source_discovery::SourceScopeMode::Explicit
466 );
467 assert_eq!(scope.roots, ["a.py"]);
468
469 let project = prepare_python_project(&root, Some(&explicit(&root, &["vendor"]))).unwrap();
471 assert_eq!(project.files.sources, ["vendor/pkg/b.py"]);
472
473 let project = prepare_python_project(&root, None).unwrap();
475 assert_eq!(project.files.sources, ["a.py", "vendor/pkg/b.py"]);
476 assert_eq!(
477 scope_of(&project).mode,
478 crate::source_discovery::SourceScopeMode::Automatic
479 );
480 fs::remove_dir_all(root).ok();
481 }
482
483 #[test]
484 fn roots_that_name_nothing_are_refused_rather_than_measuring_nothing() {
485 let root = fixture("roots-name-nothing");
488 write(&root, "a.py", "x = 1\n");
489 write(&root, "test/test_a.py", "import a\n");
490 let error = prepare_python_project(&root, Some(&explicit(&root, &["scr"]))).unwrap_err();
491 assert!(error.contains("SUPERCOV_SOURCE_ROOTS=scr"), "{error}");
492 assert!(
493 error.contains("scr does not exist"),
494 "the typo is what the person needs to see: {error}"
495 );
496 fs::remove_dir_all(root).ok();
497 }
498
499 #[test]
500 fn a_root_never_pulls_a_test_back_into_the_denominator() {
501 let root = fixture("roots-keep-tests-out");
505 write(&root, "a.py", "x = 1\n");
506 write(&root, "test/test_a.py", "import a\n");
507 let project = prepare_python_project(&root, Some(&explicit(&root, &["."]))).unwrap();
508 assert_eq!(project.files.sources, ["a.py"]);
509 assert!(project.files.tests.contains(&"test/test_a.py".to_owned()));
510 fs::remove_dir_all(root).ok();
511 }
512
513 #[test]
514 fn separates_sources_tests_environments_and_tooling() {
515 let root = fixture("discover");
516 write(&root, "pyproject.toml", "[project]\nname='x'\n");
517 write(&root, "pytest.ini", "[pytest]\n");
518 write(&root, "src/pkg/__init__.py", "");
519 write(&root, "src/pkg/core.py", "def f(a):\n return a and 1\n");
520 write(&root, "tests/test_core.py", "def test():\n pass\n");
521 write(&root, "conftest.py", "");
522 write(&root, "setup.py", "print(1)\n");
523 write(&root, ".venv/pyvenv.cfg", "home = /usr\n");
524 write(&root, ".venv/lib/site.py", "x = 1\n");
525 write(&root, "env2/pyvenv.cfg", "home = /usr\n");
526 write(&root, "env2/lib/thing.py", "y = 2\n");
527 write(&root, "broken/old.py", "print 'python 2'\n");
528 let project = prepare_python_project(&root, None).unwrap();
529 assert_eq!(
530 project.files.sources,
531 ["broken/old.py", "src/pkg/__init__.py", "src/pkg/core.py"]
532 );
533 assert_eq!(
534 project.files.tests,
535 ["conftest.py", "setup.py", "tests/test_core.py"]
536 );
537 assert_eq!(
538 project.files.dependency_files,
539 [PathBuf::from("pyproject.toml"), PathBuf::from("setup.py")]
540 );
541 assert_eq!(
542 project.files.configuration_files,
543 [PathBuf::from("pytest.ini")]
544 );
545 assert_eq!(project.unparseable.len(), 1);
546 assert!(project.plan.files.contains_key("src/pkg/core.py"));
547 assert!(!project.plan.files.contains_key("broken/old.py"));
548 let ids = project
549 .manifest
550 .limitations
551 .iter()
552 .map(|item| item["id"].as_str().unwrap().to_owned())
553 .collect::<BTreeSet<_>>();
554 assert_eq!(ids.len(), 1);
555 assert!(ids.contains(UNPARSEABLE_LIMITATION));
556 assert!(
557 project
558 .manifest
559 .points
560 .iter()
561 .all(|point| point.file.starts_with("src/"))
562 );
563 fs::remove_dir_all(root).unwrap();
564 }
565}