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(root: &Path) -> Result<PreparedPythonProject, String> {
217    let files = discover_python_files(root)?;
218    if files.sources.is_empty() && files.tests.is_empty() {
219        return Err(
220            "no Python source files were found under the project root; Supercov measures .py files outside virtual environments, build output and test directories".into(),
221        );
222    }
223    let mut manifest = CoverageManifest {
224        unmeasured: Vec::new(),
225        decisions: Vec::new(),
226        points: Vec::new(),
227        branches: Vec::new(),
228        limitations: Vec::new(),
229        scope: None,
230    };
231    let mut plan_files = BTreeMap::<String, PythonFilePlan>::new();
232    let mut limitation_ids = BTreeSet::new();
233    let mut unparseable = Vec::new();
234    for relative in &files.sources {
235        let path = root.join(relative);
236        let source = fs::read(&path).map_err(|error| format!("{}: {error}", path.display()))?;
237        let Ok(source) = String::from_utf8(source) else {
238            unparseable.push((relative.clone(), "source is not valid UTF-8".to_owned()));
239            continue;
240        };
241        match build_python_obligations(relative, &source) {
242            Ok(obligations) => {
243                manifest.points.extend(obligations.manifest.points);
244                manifest.decisions.extend(obligations.manifest.decisions);
245                manifest.branches.extend(obligations.manifest.branches);
246                manifest.unmeasured.extend(obligations.manifest.unmeasured);
247                for item in obligations.manifest.limitations {
248                    let id = item
249                        .get("id")
250                        .and_then(serde_json::Value::as_str)
251                        .unwrap_or_default()
252                        .to_owned();
253                    if limitation_ids.insert(id) {
254                        manifest.limitations.push(item);
255                    }
256                }
257                plan_files.insert(relative.clone(), obligations.plan);
258            }
259            Err(error) => unparseable.push((relative.clone(), error.to_string())),
260        }
261    }
262    if let Some((file, reason)) = unparseable.first()
263        && limitation_ids.insert(UNPARSEABLE_LIMITATION.into())
264    {
265        manifest.limitations.push(limitation(
266            UNPARSEABLE_LIMITATION,
267            "source-scope",
268            file,
269            &format!(
270                "{} source file(s) could not be parsed and carry no obligations; first: {file}: {reason}",
271                unparseable.len()
272            ),
273        ));
274    }
275    manifest.unmeasured.sort();
276    manifest.unmeasured.dedup();
277    let mut entries = Vec::new();
278    for file in &files.sources {
279        let unparseable_file = unparseable.iter().any(|(path, _)| path == file);
280        entries.push(SourceScopeEntry {
281            file: file.clone(),
282            status: if unparseable_file {
283                SourceScopeStatus::Excluded
284            } else {
285                SourceScopeStatus::Included
286            },
287            reason: if unparseable_file {
288                "could not be parsed".into()
289            } else {
290                "Python application source".into()
291            },
292            package_root: None,
293        });
294    }
295    for (file, reason) in &files.excluded {
296        if file.ends_with(".py") {
297            entries.push(SourceScopeEntry {
298                file: file.clone(),
299                status: SourceScopeStatus::Excluded,
300                reason: (*reason).into(),
301                package_root: None,
302            });
303        }
304    }
305    entries.sort_by(|left, right| left.file.cmp(&right.file));
306    manifest.scope = Some(
307        serde_json::to_value(SourceScope {
308            version: 1,
309            mode: SourceScopeMode::Automatic,
310            roots: vec![".".into()],
311            entries,
312        })
313        .map_err(|error| error.to_string())?,
314    );
315    Ok(PreparedPythonProject {
316        root: root.to_owned(),
317        plan: PythonProbePlan {
318            version: PYTHON_PROBE_PLAN_VERSION,
319            root: root.display().to_string(),
320            files: plan_files,
321        },
322        manifest,
323        files,
324        unparseable,
325    })
326}
327
328/// Integrity inputs: sources and tests are hashed separately, dependency and
329/// configuration files identify the environment, and the test command
330/// identifies execution.
331///
332/// The ambient environment is deliberately absent. It is not a property of the
333/// project, it changes with every terminal, and folding it in made a run
334/// identity that no two machines could agree on. What a project actually needs
335/// from its environment is declared in the files above.
336pub fn python_integrity_inputs(files: &PythonFiles, command: &[String]) -> ExplicitIntegrityInputs {
337    let execution_configuration = command.join("\0").into_bytes();
338    ExplicitIntegrityInputs {
339        source_files: files.sources.iter().map(PathBuf::from).collect(),
340        test_files: files.tests.iter().map(PathBuf::from).collect(),
341        dependency_files: files.dependency_files.clone(),
342        configuration_files: files.configuration_files.clone(),
343        execution_configuration,
344    }
345}
346
347#[cfg(test)]
348mod tests {
349
350    #[test]
351    fn the_ambient_environment_is_not_part_of_run_identity() {
352        // Identity is what the project is, not which shell it was run from.
353        // Folding the environment in meant no two terminals, and no two
354        // machines, ever agreed on the same run. What a project genuinely needs
355        // from its environment it declares in the files that are hashed above.
356        let files = PythonFiles::default();
357        let command = ["pytest".to_owned(), "-q".to_owned()];
358        let inputs = python_integrity_inputs(&files, &command);
359        assert_eq!(inputs.execution_configuration, b"pytest\0-q");
360    }
361    use std::time::{SystemTime, UNIX_EPOCH};
362
363    use super::*;
364
365    fn fixture(name: &str) -> PathBuf {
366        let nonce = SystemTime::now()
367            .duration_since(UNIX_EPOCH)
368            .unwrap()
369            .as_nanos();
370        let root = std::env::temp_dir().join(format!(
371            "supercov-python-project-{}-{nonce}-{name}",
372            std::process::id()
373        ));
374        fs::create_dir_all(&root).unwrap();
375        root
376    }
377
378    fn write(root: &Path, relative: &str, contents: &str) {
379        let path = root.join(relative);
380        fs::create_dir_all(path.parent().unwrap()).unwrap();
381        fs::write(path, contents).unwrap();
382    }
383
384    #[test]
385    fn a_type_checker_and_a_coverage_tool_are_not_execution_context() {
386        // Neither changes what the code does when it runs, so neither should
387        // cost every flow in the map a re-reading. What decides execution does:
388        // pytest and tox choose what runs, `.python-version` chooses the
389        // interpreter that runs it.
390        let root = fixture("inert-tooling");
391        write(&root, "pyproject.toml", "[project]\nname='x'\n");
392        write(&root, "mypy.ini", "[mypy]\n");
393        write(&root, ".coveragerc", "[run]\n");
394        write(&root, "pytest.ini", "[pytest]\n");
395        write(&root, ".python-version", "3.13\n");
396        write(&root, "src/pkg/core.py", "def f(a):\n    return a\n");
397        let project = prepare_python_project(&root).unwrap();
398        assert_eq!(
399            project.files.configuration_files,
400            [
401                PathBuf::from(".python-version"),
402                PathBuf::from("pytest.ini")
403            ]
404        );
405        fs::remove_dir_all(root).unwrap();
406    }
407
408    #[test]
409    fn separates_sources_tests_environments_and_tooling() {
410        let root = fixture("discover");
411        write(&root, "pyproject.toml", "[project]\nname='x'\n");
412        write(&root, "pytest.ini", "[pytest]\n");
413        write(&root, "src/pkg/__init__.py", "");
414        write(&root, "src/pkg/core.py", "def f(a):\n    return a and 1\n");
415        write(&root, "tests/test_core.py", "def test():\n    pass\n");
416        write(&root, "conftest.py", "");
417        write(&root, "setup.py", "print(1)\n");
418        write(&root, ".venv/pyvenv.cfg", "home = /usr\n");
419        write(&root, ".venv/lib/site.py", "x = 1\n");
420        write(&root, "env2/pyvenv.cfg", "home = /usr\n");
421        write(&root, "env2/lib/thing.py", "y = 2\n");
422        write(&root, "broken/old.py", "print 'python 2'\n");
423        let project = prepare_python_project(&root).unwrap();
424        assert_eq!(
425            project.files.sources,
426            ["broken/old.py", "src/pkg/__init__.py", "src/pkg/core.py"]
427        );
428        assert_eq!(
429            project.files.tests,
430            ["conftest.py", "setup.py", "tests/test_core.py"]
431        );
432        assert_eq!(
433            project.files.dependency_files,
434            [PathBuf::from("pyproject.toml"), PathBuf::from("setup.py")]
435        );
436        assert_eq!(
437            project.files.configuration_files,
438            [PathBuf::from("pytest.ini")]
439        );
440        assert_eq!(project.unparseable.len(), 1);
441        assert!(project.plan.files.contains_key("src/pkg/core.py"));
442        assert!(!project.plan.files.contains_key("broken/old.py"));
443        let ids = project
444            .manifest
445            .limitations
446            .iter()
447            .map(|item| item["id"].as_str().unwrap().to_owned())
448            .collect::<BTreeSet<_>>();
449        assert_eq!(ids.len(), 1);
450        assert!(ids.contains(UNPARSEABLE_LIMITATION));
451        assert!(
452            project
453                .manifest
454                .points
455                .iter()
456                .all(|point| point.file.starts_with("src/"))
457        );
458        fs::remove_dir_all(root).unwrap();
459    }
460}