Skip to main content

supercov_engine/
python_project.rs

1//! Python project discovery and ahead-of-run obligation preparation.
2//!
3//! The project runs in place: nothing here copies or rewrites sources. Rust
4//! reads every in-scope `.py` file once, builds the complete manifest and the
5//! runtime probe plan, and records which files were included, excluded or
6//! unparseable so the run can say exactly what its denominator covers.
7
8use 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
27/// Directories that never hold the project's own measured source.
28const 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    /// Relative, `/`-separated paths of measured application sources.
71    pub sources: Vec<String>,
72    /// Relative paths of test modules, conftests and other excluded `.py`.
73    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 != "target" || crate::source_discovery::target_is_build_output(&path)))
150                || name.ends_with(".egg-info")
151                || is_venv(&path)
152            {
153                files
154                    .excluded
155                    .push((relative, "tooling or environment directory"));
156                continue;
157            }
158            walk(root, &path, files, all_python)?;
159        } else if file_type.is_file() {
160            if DEPENDENCY_FILES.contains(&name.as_str())
161                || (name.starts_with("requirements") && name.ends_with(".txt"))
162            {
163                files.dependency_files.push(PathBuf::from(&relative));
164                if name != "setup.py" {
165                    continue;
166                }
167            }
168            // A type checker and a coverage tool do not change what the code
169            // does when it runs, so neither is execution context, any more than
170            // a formatter is. pytest and tox decide what executes;
171            // `.python-version` decides which interpreter executes it.
172            if matches!(name.as_str(), "pytest.ini" | "tox.ini" | ".python-version") {
173                files.configuration_files.push(PathBuf::from(&relative));
174                continue;
175            }
176            if !name.ends_with(".py") {
177                continue;
178            }
179            all_python.push(relative.clone());
180            match is_test_path(&relative) {
181                Some(reason) => {
182                    files.tests.push(relative.clone());
183                    files.excluded.push((relative, reason));
184                }
185                None => files.sources.push(relative),
186            }
187        }
188        // Symlinks are neither followed nor measured: a linked source tree is
189        // outside the project's own denominator.
190    }
191    Ok(())
192}
193
194pub fn discover_python_files(root: &Path) -> Result<PythonFiles, String> {
195    let mut files = PythonFiles::default();
196    let mut all_python = Vec::new();
197    walk(root, root, &mut files, &mut all_python)?;
198    files.sources.sort();
199    files.tests.sort();
200    files.dependency_files.sort();
201    files.configuration_files.sort();
202    Ok(files)
203}
204
205fn limitation(id: &str, kind: &str, file: &str, reason: &str) -> serde_json::Value {
206    json!({
207        "id": id,
208        "kind": kind,
209        "file": file,
210        "line": 1,
211        "column": 0,
212        "source": "",
213        "reason": reason
214    })
215}
216
217pub fn prepare_python_project(
218    root: &Path,
219    roots: Option<&crate::source_discovery::ExplicitSourceRoots>,
220) -> Result<PreparedPythonProject, String> {
221    let mut files = discover_python_files(root)?;
222    if let Some(roots) = roots {
223        roots.narrow(&mut files.sources, &mut files.excluded, String::as_str);
224        roots.refuse_if_empty(files.sources.len(), "Python")?;
225    }
226    if files.sources.is_empty() && files.tests.is_empty() {
227        return Err(
228            "no Python source files were found under the project root; Supercov measures .py files outside virtual environments, build output and test directories".into(),
229        );
230    }
231    let mut manifest = CoverageManifest {
232        unmeasured: Vec::new(),
233        decisions: Vec::new(),
234        points: Vec::new(),
235        branches: Vec::new(),
236        limitations: Vec::new(),
237        scope: None,
238        assertion_sites: Vec::new(),
239    };
240    let mut plan_files = BTreeMap::<String, PythonFilePlan>::new();
241    let mut limitation_ids = BTreeSet::new();
242    let mut unparseable = Vec::new();
243    for relative in &files.sources {
244        let path = root.join(relative);
245        let source = fs::read(&path).map_err(|error| format!("{}: {error}", path.display()))?;
246        let Ok(source) = String::from_utf8(source) else {
247            unparseable.push((relative.clone(), "source is not valid UTF-8".to_owned()));
248            continue;
249        };
250        match build_python_obligations(relative, &source) {
251            Ok(obligations) => {
252                manifest.points.extend(obligations.manifest.points);
253                manifest.decisions.extend(obligations.manifest.decisions);
254                manifest.branches.extend(obligations.manifest.branches);
255                manifest.unmeasured.extend(obligations.manifest.unmeasured);
256                for item in obligations.manifest.limitations {
257                    let id = item
258                        .get("id")
259                        .and_then(serde_json::Value::as_str)
260                        .unwrap_or_default()
261                        .to_owned();
262                    if limitation_ids.insert(id) {
263                        manifest.limitations.push(item);
264                    }
265                }
266                plan_files.insert(relative.clone(), obligations.plan);
267            }
268            Err(error) => unparseable.push((relative.clone(), error.to_string())),
269        }
270    }
271    if let Some((file, reason)) = unparseable.first()
272        && limitation_ids.insert(UNPARSEABLE_LIMITATION.into())
273    {
274        manifest.limitations.push(limitation(
275            UNPARSEABLE_LIMITATION,
276            "source-scope",
277            file,
278            &format!(
279                "{} source file(s) could not be parsed and carry no obligations; first: {file}: {reason}",
280                unparseable.len()
281            ),
282        ));
283    }
284    manifest.unmeasured.sort();
285    manifest.unmeasured.dedup();
286    let mut entries = Vec::new();
287    for file in &files.sources {
288        let unparseable_file = unparseable.iter().any(|(path, _)| path == file);
289        entries.push(SourceScopeEntry {
290            file: file.clone(),
291            status: if unparseable_file {
292                SourceScopeStatus::Excluded
293            } else {
294                SourceScopeStatus::Included
295            },
296            reason: if unparseable_file {
297                "could not be parsed".into()
298            } else {
299                "Python application source".into()
300            },
301            package_root: None,
302        });
303    }
304    for (file, reason) in &files.excluded {
305        if file.ends_with(".py") {
306            entries.push(SourceScopeEntry {
307                file: file.clone(),
308                status: SourceScopeStatus::Excluded,
309                reason: (*reason).into(),
310                package_root: None,
311            });
312        }
313    }
314    entries.sort_by(|left, right| left.file.cmp(&right.file));
315    manifest.scope = Some(
316        serde_json::to_value(SourceScope {
317            version: 1,
318            mode: if roots.is_some() {
319                SourceScopeMode::Explicit
320            } else {
321                SourceScopeMode::Automatic
322            },
323            roots: match roots {
324                Some(roots) => roots.local_roots().map_err(|error| error.to_string())?,
325                None => vec![".".into()],
326            },
327            entries,
328        })
329        .map_err(|error| error.to_string())?,
330    );
331    Ok(PreparedPythonProject {
332        root: root.to_owned(),
333        plan: PythonProbePlan {
334            version: PYTHON_PROBE_PLAN_VERSION,
335            root: root.display().to_string(),
336            files: plan_files,
337            assertion_sites: BTreeMap::new(),
338        },
339        manifest,
340        files,
341        unparseable,
342    })
343}
344
345/// Integrity inputs: sources and tests are hashed separately, dependency and
346/// configuration files identify the environment, and the test command
347/// identifies execution.
348///
349/// The ambient environment is deliberately absent. It is not a property of the
350/// project, it changes with every terminal, and folding it in made a run
351/// identity that no two machines could agree on. What a project actually needs
352/// from its environment is declared in the files above.
353pub fn python_integrity_inputs(files: &PythonFiles, command: &[String]) -> ExplicitIntegrityInputs {
354    let execution_configuration = command.join("\0").into_bytes();
355    ExplicitIntegrityInputs {
356        source_files: files.sources.iter().map(PathBuf::from).collect(),
357        test_files: files.tests.iter().map(PathBuf::from).collect(),
358        dependency_files: files.dependency_files.clone(),
359        configuration_files: files.configuration_files.clone(),
360        execution_configuration,
361    }
362}
363
364#[cfg(test)]
365mod tests {
366
367    #[test]
368    fn the_ambient_environment_is_not_part_of_run_identity() {
369        // Identity is what the project is, not which shell it was run from.
370        // Folding the environment in meant no two terminals, and no two
371        // machines, ever agreed on the same run. What a project genuinely needs
372        // from its environment it declares in the files that are hashed above.
373        let files = PythonFiles::default();
374        let command = ["pytest".to_owned(), "-q".to_owned()];
375        let inputs = python_integrity_inputs(&files, &command);
376        assert_eq!(inputs.execution_configuration, b"pytest\0-q");
377    }
378    use std::time::{SystemTime, UNIX_EPOCH};
379
380    use super::*;
381
382    fn fixture(name: &str) -> PathBuf {
383        let nonce = SystemTime::now()
384            .duration_since(UNIX_EPOCH)
385            .unwrap()
386            .as_nanos();
387        let root = std::env::temp_dir().join(format!(
388            "supercov-python-project-{}-{nonce}-{name}",
389            std::process::id()
390        ));
391        fs::create_dir_all(&root).unwrap();
392        root
393    }
394
395    fn write(root: &Path, relative: &str, contents: &str) {
396        let path = root.join(relative);
397        fs::create_dir_all(path.parent().unwrap()).unwrap();
398        fs::write(path, contents).unwrap();
399    }
400
401    #[test]
402    fn a_type_checker_and_a_coverage_tool_are_not_execution_context() {
403        // Neither changes what the code does when it runs, so neither should
404        // cost every flow in the map a re-reading. What decides execution does:
405        // pytest and tox choose what runs, `.python-version` chooses the
406        // interpreter that runs it.
407        let root = fixture("inert-tooling");
408        write(&root, "pyproject.toml", "[project]\nname='x'\n");
409        write(&root, "mypy.ini", "[mypy]\n");
410        write(&root, ".coveragerc", "[run]\n");
411        write(&root, "pytest.ini", "[pytest]\n");
412        write(&root, ".python-version", "3.13\n");
413        write(&root, "src/pkg/core.py", "def f(a):\n    return a\n");
414        let project = prepare_python_project(&root, None).unwrap();
415        assert_eq!(
416            project.files.configuration_files,
417            [
418                PathBuf::from(".python-version"),
419                PathBuf::from("pytest.ini")
420            ]
421        );
422        fs::remove_dir_all(root).unwrap();
423    }
424
425    fn scope_of(project: &PreparedPythonProject) -> crate::source_discovery::SourceScope {
426        serde_json::from_value(project.manifest.scope.clone().expect("a scope")).unwrap()
427    }
428
429    fn explicit(root: &Path, roots: &[&str]) -> crate::source_discovery::ExplicitSourceRoots {
430        let roots = roots
431            .iter()
432            .map(|root| (*root).to_owned())
433            .collect::<Vec<_>>();
434        crate::source_discovery::ExplicitSourceRoots::resolve(root, &roots).unwrap()
435    }
436
437    #[test]
438    fn explicit_roots_narrow_a_flat_layout_to_the_modules_it_names() {
439        // The reported project kept its own modules at the root with a vendored
440        // PySide6 tree beside them, and measured 660 files instead of about
441        // fifteen: nothing on the Python path read SUPERCOV_SOURCE_ROOTS. A flat
442        // layout has no directory to name, so a file has to be a root too, the
443        // way it already is for JavaScript.
444        let root = fixture("flat-roots");
445        write(&root, "a.py", "def f(x):\n    return x if x else 0\n");
446        write(&root, "vendor/pkg/b.py", "def g():\n    return 1\n");
447        write(&root, "test/test_a.py", "from a import f\n");
448
449        let project = prepare_python_project(&root, Some(&explicit(&root, &["a.py"]))).unwrap();
450        assert_eq!(project.files.sources, ["a.py"], "{:?}", project.files);
451        assert_eq!(
452            project.plan.files.keys().collect::<Vec<_>>(),
453            ["a.py"],
454            "the runtime is not handed a file the roots leave out, which is what \
455             keeps it from being instrumented at all"
456        );
457        assert!(
458            project
459                .files
460                .excluded
461                .contains(&("vendor/pkg/b.py".into(), "outside explicit source roots")),
462            "{:?}",
463            project.files.excluded
464        );
465        let scope = scope_of(&project);
466        assert_eq!(
467            scope.mode,
468            crate::source_discovery::SourceScopeMode::Explicit
469        );
470        assert_eq!(scope.roots, ["a.py"]);
471
472        // A directory is a root just as well, and narrows to what is under it.
473        let project = prepare_python_project(&root, Some(&explicit(&root, &["vendor"]))).unwrap();
474        assert_eq!(project.files.sources, ["vendor/pkg/b.py"]);
475
476        // Unset, discovery is what it always was.
477        let project = prepare_python_project(&root, None).unwrap();
478        assert_eq!(project.files.sources, ["a.py", "vendor/pkg/b.py"]);
479        assert_eq!(
480            scope_of(&project).mode,
481            crate::source_discovery::SourceScopeMode::Automatic
482        );
483        fs::remove_dir_all(root).ok();
484    }
485
486    #[test]
487    fn roots_that_name_nothing_are_refused_rather_than_measuring_nothing() {
488        // A typo in the variable must not become a green run over zero files,
489        // the failure mode most likely to pass unnoticed in an agent loop.
490        let root = fixture("roots-name-nothing");
491        write(&root, "a.py", "x = 1\n");
492        write(&root, "test/test_a.py", "import a\n");
493        let error = prepare_python_project(&root, Some(&explicit(&root, &["scr"]))).unwrap_err();
494        assert!(error.contains("SUPERCOV_SOURCE_ROOTS=scr"), "{error}");
495        assert!(
496            error.contains("scr does not exist"),
497            "the typo is what the person needs to see: {error}"
498        );
499        fs::remove_dir_all(root).ok();
500    }
501
502    #[test]
503    fn a_root_never_pulls_a_test_back_into_the_denominator() {
504        // Roots narrow what would be measured; they are not a second way to
505        // choose files. A root that happens to contain the test directory must
506        // still leave its tests out.
507        let root = fixture("roots-keep-tests-out");
508        write(&root, "a.py", "x = 1\n");
509        write(&root, "test/test_a.py", "import a\n");
510        let project = prepare_python_project(&root, Some(&explicit(&root, &["."]))).unwrap();
511        assert_eq!(project.files.sources, ["a.py"]);
512        assert!(project.files.tests.contains(&"test/test_a.py".to_owned()));
513        fs::remove_dir_all(root).ok();
514    }
515
516    #[test]
517    fn separates_sources_tests_environments_and_tooling() {
518        let root = fixture("discover");
519        write(&root, "pyproject.toml", "[project]\nname='x'\n");
520        write(&root, "pytest.ini", "[pytest]\n");
521        write(&root, "src/pkg/__init__.py", "");
522        write(&root, "src/pkg/core.py", "def f(a):\n    return a and 1\n");
523        write(&root, "tests/test_core.py", "def test():\n    pass\n");
524        write(&root, "conftest.py", "");
525        write(&root, "setup.py", "print(1)\n");
526        write(&root, ".venv/pyvenv.cfg", "home = /usr\n");
527        write(&root, ".venv/lib/site.py", "x = 1\n");
528        write(&root, "env2/pyvenv.cfg", "home = /usr\n");
529        write(&root, "env2/lib/thing.py", "y = 2\n");
530        write(&root, "broken/old.py", "print 'python 2'\n");
531        let project = prepare_python_project(&root, None).unwrap();
532        assert_eq!(
533            project.files.sources,
534            ["broken/old.py", "src/pkg/__init__.py", "src/pkg/core.py"]
535        );
536        assert_eq!(
537            project.files.tests,
538            ["conftest.py", "setup.py", "tests/test_core.py"]
539        );
540        assert_eq!(
541            project.files.dependency_files,
542            [PathBuf::from("pyproject.toml"), PathBuf::from("setup.py")]
543        );
544        assert_eq!(
545            project.files.configuration_files,
546            [PathBuf::from("pytest.ini")]
547        );
548        assert_eq!(project.unparseable.len(), 1);
549        assert!(project.plan.files.contains_key("src/pkg/core.py"));
550        assert!(!project.plan.files.contains_key("broken/old.py"));
551        let ids = project
552            .manifest
553            .limitations
554            .iter()
555            .map(|item| item["id"].as_str().unwrap().to_owned())
556            .collect::<BTreeSet<_>>();
557        assert_eq!(ids.len(), 1);
558        assert!(ids.contains(UNPARSEABLE_LIMITATION));
559        assert!(
560            project
561                .manifest
562                .points
563                .iter()
564                .all(|point| point.file.starts_with("src/"))
565        );
566        fs::remove_dir_all(root).unwrap();
567    }
568}