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.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            // A type checker and a coverage tool do not change what the code
168            // does when it runs, so neither is execution context, any more than
169            // a formatter is. pytest and tox decide what executes;
170            // `.python-version` decides which interpreter executes it.
171            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        // Symlinks are neither followed nor measured: a linked source tree is
188        // outside the project's own denominator.
189    }
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            assertion_sites: BTreeMap::new(),
336        },
337        manifest,
338        files,
339        unparseable,
340    })
341}
342
343/// Integrity inputs: sources and tests are hashed separately, dependency and
344/// configuration files identify the environment, and the test command
345/// identifies execution.
346///
347/// The ambient environment is deliberately absent. It is not a property of the
348/// project, it changes with every terminal, and folding it in made a run
349/// identity that no two machines could agree on. What a project actually needs
350/// from its environment is declared in the files above.
351pub fn python_integrity_inputs(files: &PythonFiles, command: &[String]) -> ExplicitIntegrityInputs {
352    let execution_configuration = command.join("\0").into_bytes();
353    ExplicitIntegrityInputs {
354        source_files: files.sources.iter().map(PathBuf::from).collect(),
355        test_files: files.tests.iter().map(PathBuf::from).collect(),
356        dependency_files: files.dependency_files.clone(),
357        configuration_files: files.configuration_files.clone(),
358        execution_configuration,
359    }
360}
361
362#[cfg(test)]
363mod tests {
364
365    #[test]
366    fn the_ambient_environment_is_not_part_of_run_identity() {
367        // Identity is what the project is, not which shell it was run from.
368        // Folding the environment in meant no two terminals, and no two
369        // machines, ever agreed on the same run. What a project genuinely needs
370        // from its environment it declares in the files that are hashed above.
371        let files = PythonFiles::default();
372        let command = ["pytest".to_owned(), "-q".to_owned()];
373        let inputs = python_integrity_inputs(&files, &command);
374        assert_eq!(inputs.execution_configuration, b"pytest\0-q");
375    }
376    use std::time::{SystemTime, UNIX_EPOCH};
377
378    use super::*;
379
380    fn fixture(name: &str) -> PathBuf {
381        let nonce = SystemTime::now()
382            .duration_since(UNIX_EPOCH)
383            .unwrap()
384            .as_nanos();
385        let root = std::env::temp_dir().join(format!(
386            "supercov-python-project-{}-{nonce}-{name}",
387            std::process::id()
388        ));
389        fs::create_dir_all(&root).unwrap();
390        root
391    }
392
393    fn write(root: &Path, relative: &str, contents: &str) {
394        let path = root.join(relative);
395        fs::create_dir_all(path.parent().unwrap()).unwrap();
396        fs::write(path, contents).unwrap();
397    }
398
399    #[test]
400    fn a_type_checker_and_a_coverage_tool_are_not_execution_context() {
401        // Neither changes what the code does when it runs, so neither should
402        // cost every flow in the map a re-reading. What decides execution does:
403        // pytest and tox choose what runs, `.python-version` chooses the
404        // interpreter that runs it.
405        let root = fixture("inert-tooling");
406        write(&root, "pyproject.toml", "[project]\nname='x'\n");
407        write(&root, "mypy.ini", "[mypy]\n");
408        write(&root, ".coveragerc", "[run]\n");
409        write(&root, "pytest.ini", "[pytest]\n");
410        write(&root, ".python-version", "3.13\n");
411        write(&root, "src/pkg/core.py", "def f(a):\n    return a\n");
412        let project = prepare_python_project(&root, None).unwrap();
413        assert_eq!(
414            project.files.configuration_files,
415            [
416                PathBuf::from(".python-version"),
417                PathBuf::from("pytest.ini")
418            ]
419        );
420        fs::remove_dir_all(root).unwrap();
421    }
422
423    fn scope_of(project: &PreparedPythonProject) -> crate::source_discovery::SourceScope {
424        serde_json::from_value(project.manifest.scope.clone().expect("a scope")).unwrap()
425    }
426
427    fn explicit(root: &Path, roots: &[&str]) -> crate::source_discovery::ExplicitSourceRoots {
428        let roots = roots
429            .iter()
430            .map(|root| (*root).to_owned())
431            .collect::<Vec<_>>();
432        crate::source_discovery::ExplicitSourceRoots::resolve(root, &roots).unwrap()
433    }
434
435    #[test]
436    fn explicit_roots_narrow_a_flat_layout_to_the_modules_it_names() {
437        // The reported project kept its own modules at the root with a vendored
438        // PySide6 tree beside them, and measured 660 files instead of about
439        // fifteen: nothing on the Python path read SUPERCOV_SOURCE_ROOTS. A flat
440        // layout has no directory to name, so a file has to be a root too, the
441        // way it already is for JavaScript.
442        let root = fixture("flat-roots");
443        write(&root, "a.py", "def f(x):\n    return x if x else 0\n");
444        write(&root, "vendor/pkg/b.py", "def g():\n    return 1\n");
445        write(&root, "test/test_a.py", "from a import f\n");
446
447        let project = prepare_python_project(&root, Some(&explicit(&root, &["a.py"]))).unwrap();
448        assert_eq!(project.files.sources, ["a.py"], "{:?}", project.files);
449        assert_eq!(
450            project.plan.files.keys().collect::<Vec<_>>(),
451            ["a.py"],
452            "the runtime is not handed a file the roots leave out, which is what \
453             keeps it from being instrumented at all"
454        );
455        assert!(
456            project
457                .files
458                .excluded
459                .contains(&("vendor/pkg/b.py".into(), "outside explicit source roots")),
460            "{:?}",
461            project.files.excluded
462        );
463        let scope = scope_of(&project);
464        assert_eq!(
465            scope.mode,
466            crate::source_discovery::SourceScopeMode::Explicit
467        );
468        assert_eq!(scope.roots, ["a.py"]);
469
470        // A directory is a root just as well, and narrows to what is under it.
471        let project = prepare_python_project(&root, Some(&explicit(&root, &["vendor"]))).unwrap();
472        assert_eq!(project.files.sources, ["vendor/pkg/b.py"]);
473
474        // Unset, discovery is what it always was.
475        let project = prepare_python_project(&root, None).unwrap();
476        assert_eq!(project.files.sources, ["a.py", "vendor/pkg/b.py"]);
477        assert_eq!(
478            scope_of(&project).mode,
479            crate::source_discovery::SourceScopeMode::Automatic
480        );
481        fs::remove_dir_all(root).ok();
482    }
483
484    #[test]
485    fn roots_that_name_nothing_are_refused_rather_than_measuring_nothing() {
486        // A typo in the variable must not become a green run over zero files,
487        // the failure mode most likely to pass unnoticed in an agent loop.
488        let root = fixture("roots-name-nothing");
489        write(&root, "a.py", "x = 1\n");
490        write(&root, "test/test_a.py", "import a\n");
491        let error = prepare_python_project(&root, Some(&explicit(&root, &["scr"]))).unwrap_err();
492        assert!(error.contains("SUPERCOV_SOURCE_ROOTS=scr"), "{error}");
493        assert!(
494            error.contains("scr does not exist"),
495            "the typo is what the person needs to see: {error}"
496        );
497        fs::remove_dir_all(root).ok();
498    }
499
500    #[test]
501    fn a_root_never_pulls_a_test_back_into_the_denominator() {
502        // Roots narrow what would be measured; they are not a second way to
503        // choose files. A root that happens to contain the test directory must
504        // still leave its tests out.
505        let root = fixture("roots-keep-tests-out");
506        write(&root, "a.py", "x = 1\n");
507        write(&root, "test/test_a.py", "import a\n");
508        let project = prepare_python_project(&root, Some(&explicit(&root, &["."]))).unwrap();
509        assert_eq!(project.files.sources, ["a.py"]);
510        assert!(project.files.tests.contains(&"test/test_a.py".to_owned()));
511        fs::remove_dir_all(root).ok();
512    }
513
514    #[test]
515    fn separates_sources_tests_environments_and_tooling() {
516        let root = fixture("discover");
517        write(&root, "pyproject.toml", "[project]\nname='x'\n");
518        write(&root, "pytest.ini", "[pytest]\n");
519        write(&root, "src/pkg/__init__.py", "");
520        write(&root, "src/pkg/core.py", "def f(a):\n    return a and 1\n");
521        write(&root, "tests/test_core.py", "def test():\n    pass\n");
522        write(&root, "conftest.py", "");
523        write(&root, "setup.py", "print(1)\n");
524        write(&root, ".venv/pyvenv.cfg", "home = /usr\n");
525        write(&root, ".venv/lib/site.py", "x = 1\n");
526        write(&root, "env2/pyvenv.cfg", "home = /usr\n");
527        write(&root, "env2/lib/thing.py", "y = 2\n");
528        write(&root, "broken/old.py", "print 'python 2'\n");
529        let project = prepare_python_project(&root, None).unwrap();
530        assert_eq!(
531            project.files.sources,
532            ["broken/old.py", "src/pkg/__init__.py", "src/pkg/core.py"]
533        );
534        assert_eq!(
535            project.files.tests,
536            ["conftest.py", "setup.py", "tests/test_core.py"]
537        );
538        assert_eq!(
539            project.files.dependency_files,
540            [PathBuf::from("pyproject.toml"), PathBuf::from("setup.py")]
541        );
542        assert_eq!(
543            project.files.configuration_files,
544            [PathBuf::from("pytest.ini")]
545        );
546        assert_eq!(project.unparseable.len(), 1);
547        assert!(project.plan.files.contains_key("src/pkg/core.py"));
548        assert!(!project.plan.files.contains_key("broken/old.py"));
549        let ids = project
550            .manifest
551            .limitations
552            .iter()
553            .map(|item| item["id"].as_str().unwrap().to_owned())
554            .collect::<BTreeSet<_>>();
555        assert_eq!(ids.len(), 1);
556        assert!(ids.contains(UNPARSEABLE_LIMITATION));
557        assert!(
558            project
559                .manifest
560                .points
561                .iter()
562                .all(|point| point.file.starts_with("src/"))
563        );
564        fs::remove_dir_all(root).unwrap();
565    }
566}