diff --git a/crates/ide-coverage/Cargo.toml b/crates/ide-coverage/Cargo.toml index 7fa20b8f6..be3d3c64c 100644 --- a/crates/ide-coverage/Cargo.toml +++ b/crates/ide-coverage/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "ide-coverage" -description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov)" +description = "Run with Coverage: coverage-tool launch plans (cargo-llvm-cov, vitest / jest / c8, coverage.py, go test, JaCoCo) and report parsers (lcov, Go cover profiles, JaCoCo and Cobertura XML, SimpleCov, coverage.py data)" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/ide-coverage/src/coveragepy.rs b/crates/ide-coverage/src/coveragepy.rs new file mode 100644 index 000000000..96d2d1080 --- /dev/null +++ b/crates/ide-coverage/src/coveragepy.rs @@ -0,0 +1,180 @@ +//! coverage.py data files (`.coverage`, and `.coverage.*` of parallel runs): SQLite databases of +//! executed lines and arcs. Which lines are statements, excluded or branches only comes from +//! analysing the source, so coverage.py in the project's interpreter combines the data into a +//! scratch file (`[paths]` of the project's configuration applies) and writes Cobertura XML. + +use crate::{CoverageSuite, cobertura}; +use ide_core::{IdeError, IdeResult}; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// Whether `path` is an SQLite database (coverage.py 5+ data). +pub fn is_data_file(path: &Path) -> bool { + let mut head = [0u8; 16]; + std::fs::File::open(path).and_then(|mut f| f.read_exact(&mut head)).is_ok() && &head == b"SQLite format 3\0" +} + +/// `path`, or every `.coverage.*` file next to it when it is one of a parallel run's. +fn inputs(path: &Path) -> Vec { + let parallel = path.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")); + let mut files: Vec = match (parallel, path.parent()) { + (true, Some(dir)) => std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| { + p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(".coverage.")) && is_data_file(p) + }) + .collect(), + _ => Vec::new(), + }; + if files.is_empty() { + files.push(path.to_path_buf()); + } + files.sort(); + files +} + +/// The files a `coverage xml -i` run skipped: `… No source for code: ''. …`. +fn missing_sources(stderr: &str) -> Vec { + stderr + .lines() + .filter_map(|l| l.split_once("No source for code: '")?.1.split_once("'.").map(|(p, _)| PathBuf::from(p))) + .collect() +} + +fn coverage(python: &Path, root: &Path, args: &[&std::ffi::OsStr]) -> IdeResult { + let out = ide_core::process::prepare(Command::new(python).current_dir(root)) + .args(["-m", "coverage"]) + .args(args) + .output() + .map_err(|e| IdeError::unavailable(format!("cannot run {}: {e}", python.display())))?; + let stderr = ide_core::output_encoding::decode_tool_output(&out.stderr); + if out.status.success() { + return Ok(stderr); + } + if stderr.contains("No module named coverage") { + return Err(IdeError::unavailable(format!( + "Reading a .coverage data file needs coverage.py in the project's interpreter ({}). Install it, or import the output of `coverage xml`.", + python.display() + ))); + } + let text = + if stderr.trim().is_empty() { ide_core::output_encoding::decode_tool_output(&out.stdout) } else { stderr }; + Err(IdeError::invalid(format!("coverage.py could not read the data: {}", text.trim()))) +} + +/// Reads the data file at `path` with `python`'s coverage.py, run in `root`; `out` holds the +/// scratch files. Blocking. +pub(crate) fn import(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult { + let data = out.join(".coverage"); + let xml = out.join("coverage.xml"); + let inputs = inputs(path); + let mut args: Vec<&std::ffi::OsStr> = + vec!["combine".as_ref(), "--keep".as_ref(), "--data-file".as_ref(), data.as_ref()]; + args.extend(inputs.iter().map(|p| p.as_os_str())); + coverage(python, root, &args)?; + // `-i`: report what has source here instead of failing on the first file that has none. + let stderr = coverage( + python, + root, + &["xml".as_ref(), "-i".as_ref(), "--data-file".as_ref(), data.as_ref(), "-o".as_ref(), xml.as_ref()], + )?; + let text = std::fs::read_to_string(&xml)?; + let mut acc = cobertura::parse(&text, root).map_err(|e| IdeError::invalid(format!("{}: {e}", xml.display())))?; + for file in missing_sources(&stderr) { + acc.file(&file); + } + Ok(acc.finish("coverage.py")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_the_files_of_a_parallel_run() { + let tmp = tempfile::tempdir().unwrap(); + let db = |name: &str| { + let p = tmp.path().join(name); + std::fs::write(&p, b"SQLite format 3\0rest").unwrap(); + p + }; + let a = db(".coverage.host.1.x"); + let b = db(".coverage.host.2.y"); + let single = db(".coverage"); + std::fs::write(tmp.path().join(".coverage.notes"), "text").unwrap(); + std::fs::write(tmp.path().join(".coveragerc"), "[run]\n").unwrap(); + assert!(is_data_file(&a) && !is_data_file(&tmp.path().join(".coveragerc"))); + assert_eq!(inputs(&a), [a.clone(), b]); + assert_eq!(inputs(&single), [single]); + } + + /// Two parallel runs recorded on another machine (`…/ci/app`), mapped by the project's `[paths]`. + /// Needs coverage.py in `python3`; skipped without it. + #[test] + fn combines_parallel_data_with_the_projects_paths() { + let has_coverage = Command::new("python3").args(["-m", "coverage", "--version"]).output(); + if !has_coverage.is_ok_and(|o| o.status.success()) { + eprintln!("skipped: no coverage.py in python3"); + return; + } + let tmp = tempfile::tempdir().unwrap(); + // coverage.py reports real paths (`/private/var/…` for macOS's `/var/…`). + let base = tmp.path().canonicalize().unwrap(); + let ci = base.join("ci/app"); + let root = base.join("project"); + let calc = "def sign(n):\n if n < 0:\n return -1\n return 1\n"; + for dir in [&ci, &root] { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("calc.py"), calc).unwrap(); + } + std::fs::write(ci.join("gone.py"), "x = 1\n").unwrap(); + std::fs::write(ci.join("neg.py"), "import calc, gone\ncalc.sign(-1)\n").unwrap(); + std::fs::write(ci.join("pos.py"), "import calc\ncalc.sign(1)\n").unwrap(); + for script in ["neg.py", "pos.py"] { + let ok = Command::new("python3") + .current_dir(&ci) + .args(["-m", "coverage", "run", "--branch", "--parallel-mode", script]) + .status() + .unwrap(); + assert!(ok.success()); + } + let data = root.join("data"); + std::fs::create_dir_all(&data).unwrap(); + for e in std::fs::read_dir(&ci).unwrap().flatten() { + if e.file_name().to_string_lossy().starts_with(".coverage.") { + std::fs::rename(e.path(), data.join(e.file_name())).unwrap(); + } + } + std::fs::remove_dir_all(&ci).unwrap(); + std::fs::write(root.join(".coveragerc"), "[paths]\nsource =\n ./\n */ci/app/\n").unwrap(); + let first = std::fs::read_dir(&data).unwrap().flatten().next().unwrap().path(); + let out = base.join("out"); + std::fs::create_dir_all(&out).unwrap(); + let suite = import(&first, &root, Path::new("python3"), &out).unwrap(); + + let calc = suite.files.iter().find(|f| f.path.as_ref() as &Path == root.join("calc.py")).unwrap(); + // Both runs together take both branches of line 2. + assert_eq!((calc.lines_total, calc.lines_covered, calc.branches_total, calc.branches_covered), (4, 4, 2, 2)); + // The scripts and `gone.py` have no source in the project: listed without lines. + let empty: Vec<&str> = suite + .files + .iter() + .filter(|f| f.lines.is_empty()) + .filter_map(|f| (f.path.as_ref() as &Path).file_name()?.to_str()) + .collect(); + assert_eq!(empty, ["gone.py", "neg.py", "pos.py"]); + // They keep the recorded path, so the import notification counts them as not in the project. + assert!(suite.files.iter().filter(|f| f.lines.is_empty()).all(|f| (f.path.as_ref() as &Path).starts_with(&ci))); + assert_eq!(std::fs::read_dir(&data).unwrap().count(), 2, "the user's data files are kept"); + } + + #[test] + fn reads_files_without_source_from_warnings() { + let stderr = "/v/lib/coverage/report_core.py:122: CoverageWarning: Couldn't parse '/ci/app/a.py': No source for code: '/ci/app/a.py'. (couldnt-parse); see https://coverage.readthedocs.io\n coverage._warn(msg, slug=\"couldnt-parse\")\n"; + assert_eq!(missing_sources(stderr), [PathBuf::from("/ci/app/a.py")]); + } +} diff --git a/crates/ide-coverage/src/import.rs b/crates/ide-coverage/src/import.rs index b60176286..8a642f6b6 100644 --- a/crates/ide-coverage/src/import.rs +++ b/crates/ide-coverage/src/import.rs @@ -82,6 +82,12 @@ pub fn import(path: &Path, root: &Path) -> IdeResult { Ok(suite) } +/// Reads a coverage.py data file (see [`crate::is_data_file`]) with the coverage.py of `python`, +/// run in `root`; `out` is an empty scratch directory. Blocking. +pub fn import_data(path: &Path, root: &Path, python: &Path, out: &Path) -> IdeResult { + crate::coveragepy::import(path, root, python, out) +} + /// Whether `dir` exists, without asking again below a directory known to be missing: every /// lookup under macOS's `/home` (autofs) takes tens of milliseconds, and CI reports /// (`/home/runner/work/…`) name thousands of files there. diff --git a/crates/ide-coverage/src/lib.rs b/crates/ide-coverage/src/lib.rs index 7ed5f755d..c89001414 100644 --- a/crates/ide-coverage/src/lib.rs +++ b/crates/ide-coverage/src/lib.rs @@ -17,6 +17,7 @@ //! Lines in the model are 0-based, like every IPC coordinate. mod cobertura; +mod coveragepy; mod goprofile; mod import; mod jacoco; @@ -24,7 +25,8 @@ mod lcov; mod plan; mod simplecov; -pub use import::import; +pub use coveragepy::is_data_file; +pub use import::{import, import_data}; pub use plan::prepare; use ide_core::{IdeError, IdeResult, IpcPath}; diff --git a/crates/ide-host/src/ops/coverage.rs b/crates/ide-host/src/ops/coverage.rs index 3c50df085..f2c046cc2 100644 --- a/crates/ide-host/src/ops/coverage.rs +++ b/crates/ide-host/src/ops/coverage.rs @@ -3,7 +3,7 @@ use crate::Host; use ide_command::command; use super::blocking; -use ide_core::{IdeResult, IpcPath}; +use ide_core::{IdeError, IdeResult, IpcPath}; use ide_coverage::{CoveragePrepared, CoverageReportSpec, CoverageSuite}; use ide_run::RunConfig; @@ -35,9 +35,30 @@ pub async fn coverage_collect(host: &Host, window: &str, report: CoverageReportS /// with paths mapped into this project. #[command(trust = always)] pub async fn coverage_import(host: &Host, window: &str, path: IpcPath) -> IdeResult { - // Also reads Cobertura XML and a SimpleCov resultset. - let root = host.project(window)?.root.clone(); - blocking(move || ide_coverage::import(&path, &root)).await + // Also reads Cobertura XML, a SimpleCov resultset and coverage.py data files. + let project = host.project(window)?; + let (root, cache, config_dir) = + (project.root.clone(), project.cache_dir.join("coverage-import"), host.config_dir.clone()); + let trusted = project.require_trust(); + blocking(move || { + if !ide_coverage::is_data_file(&path) { + return ide_coverage::import(&path, &root); + } + // coverage.py analyses the sources with the project's interpreter: that runs project code. + trusted.map_err(|_| { + IdeError::unavailable( + "Reading a .coverage data file runs the project's Python. Trust the project, or import the output of `coverage xml`.", + ) + })?; + let python = super::sdk::effective_python(&config_dir, &project, path.parent()).ok_or_else(|| { + IdeError::unavailable( + "Reading a .coverage data file needs the project's Python interpreter. Choose one, or import the output of `coverage xml`.", + ) + })?; + let out = ide_run::wrap::new_output_dir(&cache, KEEP_RUNS)?; + ide_coverage::import_data(&path, &root, &python, &out) + }) + .await } ide_command::domain!(coverage: coverage_collect, coverage_import, coverage_prepare); diff --git a/docs/en/guide/coverage.mdx b/docs/en/guide/coverage.mdx index b5de4cc36..63c207559 100644 --- a/docs/en/guide/coverage.mdx +++ b/docs/en/guide/coverage.mdx @@ -62,6 +62,7 @@ Not supported: - JaCoCo XML report - Cobertura XML report (`coverage xml` of coverage.py, and other tools); relative file names resolve against its `` - SimpleCov `.resultset.json` +- coverage.py data file (`.coverage`); choosing one `.coverage.*` file of a parallel run imports all of them. It is read by coverage.py in the project's interpreter, run in the project directory, so the project must be trusted and the project's coverage configuration applies (`[paths]`, excluded lines). Your data files are not changed. In the macOS file chooser, press `⌘⇧.` to show these hidden files. File paths recorded on another machine are mapped into the project by their longest matching suffix. The import notification says how many files of the report are not in the project. diff --git a/docs/zh/guide/coverage.mdx b/docs/zh/guide/coverage.mdx index 0f0f10963..36dd1491c 100644 --- a/docs/zh/guide/coverage.mdx +++ b/docs/zh/guide/coverage.mdx @@ -57,6 +57,7 @@ description: "使用覆盖率运行配置,在编辑器、项目视图和覆盖 - JaCoCo XML 报告 - Cobertura XML 报告(coverage.py 的 `coverage xml` 及其他工具生成);相对文件名按报告的 `` 解析 - SimpleCov `.resultset.json` +- coverage.py 数据文件(`.coverage`);选择并行运行中的任意一个 `.coverage.*` 文件,会把它们一起导入。数据文件由项目解释器里的 coverage.py 在项目目录中读取,因此项目需要受信任,并且会应用项目的 coverage 配置(`[paths]`、排除的行)。不会修改你的数据文件。在 macOS 的文件选择窗口中按 `⌘⇧.` 可以显示这类隐藏文件。 报告中记录的其他机器上的路径,会按最长匹配后缀映射到当前项目中。导入通知会说明报告中有多少个文件不在此项目中。 diff --git a/src/features/coverage/projectScope.test.ts b/src/features/coverage/projectScope.test.ts index 1bde6c2fc..1730f4f3a 100644 --- a/src/features/coverage/projectScope.test.ts +++ b/src/features/coverage/projectScope.test.ts @@ -114,6 +114,13 @@ it("says how many imported files are not in the project", async () => { expect(backend.notify).toHaveBeenLastCalledWith( expect.objectContaining({ level: "warning", body: "2 files of the report are not in this project." }), ); + backend.coverageImport.mockResolvedValue(ok({ ...data, runner: "coverage.py", files: [file, foreign("/ci/a.py")] })); + await importReport(report); + expect(backend.notify).toHaveBeenLastCalledWith( + expect.objectContaining({ + body: "1 file of the data has no source in this project. Map it with [paths] in the coverage.py configuration.", + }), + ); backend.coverageImport.mockResolvedValue(ok(data)); await importReport(report); expect(backend.notify).toHaveBeenLastCalledWith(expect.objectContaining({ level: "info", body: undefined })); diff --git a/src/features/coverage/reports.tsx b/src/features/coverage/reports.tsx index e9ff77e29..ebe34706b 100644 --- a/src/features/coverage/reports.tsx +++ b/src/features/coverage/reports.tsx @@ -1,6 +1,6 @@ /** * Coverage reports collected elsewhere: "Import a report collected in CI from - * disk" (lcov, JaCoCo or Cobertura XML, Go cover profile, SimpleCov) and "Manage Coverage Reports" + * disk" (lcov, JaCoCo or Cobertura XML, Go cover profile, SimpleCov, coverage.py data) and "Manage Coverage Reports" * (choose the shown suite, delete suites and remembered imports). */ import { useMemo, useState } from "react"; @@ -43,6 +43,18 @@ async function pickReport(): Promise { }); } +/** Says how many files of an import are not in the project; coverage.py data maps them with `[paths]`. */ +function outsideText(outside: number, runner: string): string | undefined { + if (!outside) return undefined; + if (runner === "coverage.py") + return outside === 1 + ? "1 file of the data has no source in this project. Map it with [paths] in the coverage.py configuration." + : tx`${outside} files of the data have no source in this project. Map them with [paths] in the coverage.py configuration.`; + return outside === 1 + ? "1 file of the report is not in this project." + : tx`${outside} files of the report are not in this project.`; +} + /** Imports `path` (asks for a file without one) and shows it like a run's suite. */ export async function importReport(path?: string): Promise { if (!isTauri()) { @@ -73,13 +85,7 @@ export async function importReport(path?: string): Promise { level: outside ? "warning" : "info", key: "coverage-import", title: `Imported coverage '${suite.name}': ${formatPercent(covered!, total!)} lines`, - body: !data.files.length - ? "The report covers no files of this project." - : outside === 1 - ? "1 file of the report is not in this project." - : outside - ? tx`${outside} files of the report are not in this project.` - : undefined, + body: !data.files.length ? "The report covers no files of this project." : outsideText(outside, data.runner), }); return suite; } catch (e) { diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 6e0903035..6c09eb3e9 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4296,5 +4296,7 @@ "1 file of the report is not in this project.": "1 file of the report is not in this project.", "{count} files of the report are not in this project.": "{count} files of the report are not in this project.", "Waiting for process connection on {address}…": "Waiting for process connection on {address}…", - "Add to the program: {line}": "Add to the program: {line}" + "Add to the program: {line}": "Add to the program: {line}", + "1 file of the data has no source in this project. Map it with [paths] in the coverage.py configuration.": "1 file of the data has no source in this project. Map it with [paths] in the coverage.py configuration.", + "{count} files of the data have no source in this project. Map them with [paths] in the coverage.py configuration.": "{count} files of the data have no source in this project. Map them with [paths] in the coverage.py configuration." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index bc2f22a03..0402ddcec 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -10794,5 +10794,7 @@ "Failed to deactivate {failed} of {total} data sources": "{total} 个数据源中有 {failed} 个停用失败", "Refresh {count} Data Sources": "刷新 {count} 个数据源", "Deactivate {count} Data Sources": "停用 {count} 个数据源", - "Remove {count} Data Sources…": "移除 {count} 个数据源…" + "Remove {count} Data Sources…": "移除 {count} 个数据源…", + "1 file of the data has no source in this project. Map it with [paths] in the coverage.py configuration.": "数据中有 1 个文件在此项目中找不到源码。请在 coverage.py 配置的 [paths] 中映射它。", + "{count} files of the data have no source in this project. Map them with [paths] in the coverage.py configuration.": "数据中有 {count} 个文件在此项目中找不到源码。请在 coverage.py 配置的 [paths] 中映射它们。" }