Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Five core Metrics are calibrated against stratified panels of current public rep
Additional independent Metrics and structural checks run in the same pass:

- **Test gap**: share of total Production Function mass not executed by tests, read from user-named LCOV or Cobertura XML Coverage reports without running your test suite, listing the heaviest untested functions first ([Test gap guide](./docs/guide/test-gap.md), [ADR 0017](./docs/adr/0017-test-gap-from-coverage-reports.md)).
Set `new_file_budgets.production.test_gap` to enforce the ratio on newly added Production files in `codeint diff`.
- **Orphan files**: Production files unreachable from manifest-declared, program-start, and configured `entry_points`, classified as `unreferenced` or `test-only`.
- **File size** (opt-in): the share of Production source lines beyond the File size limit set in `file_size.max_source_lines`, with one Oversized file Finding per file over the limit.
- **Dependency hygiene**: three independent Metrics (`unused_dependencies`, `unlisted_dependencies`, and `dev_in_production_dependencies`) comparing `package.json`, `Cargo.toml`, `pyproject.toml`, `composer.json`, `pubspec.yaml`, and `go.mod` against imported external packages while excluding standard-library built-ins.
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use codeint_report::{
};

mod control_characters;
mod coverage;
pub(crate) mod coverage;
mod errors;
mod frameworks;
mod lowering;
Expand Down
90 changes: 80 additions & 10 deletions crates/cli/src/check/coverage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::collections::BTreeMap;
use std::io::Read;
use std::path::{Path, PathBuf};

use codeint_git::{CommitId, GitError, Repository, SnapshotFileLookup};
use codeint_metrics::{
CoverageApplyOutcome, CoverageParseError, MAX_COVERAGE_REPORT_BYTES, NamedCoverageReport,
apply_coverage_reports, parse_coverage_report,
Expand Down Expand Up @@ -60,20 +61,89 @@ pub(crate) fn load_coverage_reports(
.iter()
.map(|target| {
let bytes = read_bounded_coverage_file(repository_root, &target.display, &target.full)?;
let report = parse_coverage_report(&bytes).map_err(|source| {
CheckError::InvalidCoverageReport {
path: target.display.clone(),
source,
}
})?;
Ok(NamedCoverageReport {
path: target.display.clone(),
report,
})
parse_named_coverage_report(&target.display, &bytes)
})
.collect()
}

#[derive(Clone, Copy)]
pub(crate) enum NewFileCoverageSource<'a> {
WorkingTree(&'a Path),
Head(&'a Repository, CommitId),
}

impl NewFileCoverageSource<'_> {
pub(crate) fn load(self, paths: &[String]) -> Result<Vec<NamedCoverageReport>, CheckError> {
match self {
Self::WorkingTree(root) => {
let paths = select_coverage_report_paths(root, root, paths, None);
load_coverage_reports(root, &paths)
}
Self::Head(repository, commit) => paths
.iter()
.map(|path| load_head_coverage_report(repository, commit, path))
.collect(),
}
}
}

fn load_head_coverage_report(
repository: &Repository,
commit: CommitId,
path: &str,
) -> Result<NamedCoverageReport, CheckError> {
let missing = || CheckError::MissingHeadCoverageReport {
path: path.to_owned(),
};
let normalized = Path::new(path)
.components()
.filter(|part| !matches!(part, std::path::Component::CurDir))
.map(|part| part.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
let repo_path = RepoPath::new(normalized).map_err(|_| missing())?;
match repository.read_commit_file_following_symlinks_bounded(
commit,
&repo_path,
MAX_COVERAGE_REPORT_BYTES as u64,
) {
Err(GitError::FileTooLarge { size_bytes, .. }) => Err(CheckError::InvalidCoverageReport {
path: path.to_owned(),
source: CoverageParseError::ReportTooLarge {
size_bytes: usize::try_from(size_bytes).unwrap_or(usize::MAX),
max_bytes: MAX_COVERAGE_REPORT_BYTES,
},
}),
Err(error) => Err(error.into()),
Ok(SnapshotFileLookup::File(bytes)) => parse_named_coverage_report(path, &bytes),
Ok(SnapshotFileLookup::OutsideRepository) => {
Err(CheckError::CoverageReportOutsideRepository {
path: path.to_owned(),
})
}
Ok(
SnapshotFileLookup::Missing
| SnapshotFileLookup::BrokenSymlink
| SnapshotFileLookup::NotAFile,
) => Err(missing()),
}
}

fn parse_named_coverage_report(
path: &str,
bytes: &[u8],
) -> Result<NamedCoverageReport, CheckError> {
let report =
parse_coverage_report(bytes).map_err(|source| CheckError::InvalidCoverageReport {
path: path.to_owned(),
source,
})?;
Ok(NamedCoverageReport {
path: path.to_owned(),
report,
})
}

pub(crate) fn apply_loaded_coverage_reports(
reports: &[NamedCoverageReport],
languages: &mut [MeasuredLanguage],
Expand Down
6 changes: 6 additions & 0 deletions crates/cli/src/check/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ pub(crate) enum CheckError {
},
#[error("Coverage report {path:?} does not exist")]
MissingCoverageReport { path: String },
#[error("Coverage report {path:?} does not exist at the selected --head ref")]
MissingHeadCoverageReport { path: String },
#[error("Coverage report {path:?} is outside the Git repository")]
CoverageReportOutsideRepository { path: String },
#[error("cannot read Coverage report {path:?}")]
Expand All @@ -93,6 +95,10 @@ pub(crate) enum CheckError {
"budgets.production.test_gap ({budget}) is set, but Test gap is absent; the Test gap Budget needs a Coverage report"
)]
TestGapBudgetWithoutCoverage { budget: f64 },
#[error(
"new_file_budgets.production.test_gap is set, but no Coverage report applies to the languages of newly added Production files"
)]
NewFileTestGapBudgetWithoutCoverage,
#[error("{config_file}: dialects.{} conflict: {conflict}", conflict.language)]
DialectConflict {
config_file: ConfigFileKind,
Expand Down
70 changes: 68 additions & 2 deletions crates/cli/src/commit_measurement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ use std::collections::{BTreeMap, HashSet};

use codeint_config::Configuration;
use codeint_git::{CommitId, Repository, ResultCache, Snapshot};
use codeint_metrics::DependencyHygiene;
use codeint_model::{CodeModel, Metric, RepoPath};
use codeint_metrics::{DependencyHygiene, TestGap, apply_coverage_reports};
use codeint_model::{CodeModel, Metric, RepoPath, SourceSet};
use codeint_plugin_host::{PLUGIN_INTERFACE_VERSION, built_in_language_names};
use codeint_report::{CommitMeasurement, CommitMeasurementOptions};
use serde::Serialize;

use crate::check::coverage::NewFileCoverageSource;
use crate::check::{
CheckError, LoadedPlugins, LoweringCache, MeasuredSnapshot, SelectedPackage,
compute_dependency_hygiene, compute_orphan_files, compute_orphan_files_for_subset,
Expand Down Expand Up @@ -179,6 +180,7 @@ pub(crate) fn measure_all_languages_with_new_files(
configuration: &Configuration,
package: Option<&str>,
lowering_cache: Option<&LoweringCache>,
coverage_source: NewFileCoverageSource<'_>,
) -> Result<
(
Option<SelectedPackage>,
Expand All @@ -196,6 +198,7 @@ pub(crate) fn measure_all_languages_with_new_files(
plugins,
configuration,
selected.as_ref(),
coverage_source,
)?;
let measurement =
measure_snapshot_to_commit(snapshot, plugins, configuration, selected.as_ref())?;
Expand All @@ -219,6 +222,7 @@ fn measure_new_files_subset(
plugins: &LoadedPlugins,
configuration: &Configuration,
selected: Option<&SelectedPackage>,
coverage_source: NewFileCoverageSource<'_>,
) -> Result<Option<CommitMeasurement>, CheckError> {
let orphan_files = compute_orphan_files_for_subset(snapshot, selected, new_files);
let models: Vec<CodeModel> = snapshot
Expand All @@ -230,6 +234,23 @@ fn measure_new_files_subset(
if models.is_empty() {
return Ok(None);
}
let test_gap = if configuration
.new_file_budgets
.production_test_gap()
.is_some()
&& models.iter().flat_map(|model| &model.files).any(|file| {
file.model.source_set == SourceSet::Production && !file.model.functions.is_empty()
}) {
Some(measure_new_file_test_gap(
snapshot,
new_files,
selected,
coverage_source,
&configuration.coverage_reports,
)?)
} else {
None
};
let metric_plugins = plugins.metric_plugins();
let disabled_hazard_rules = configuration.hazards.disabled_rules_set();
let empty_hygiene = DependencyHygiene::default();
Expand All @@ -247,9 +268,54 @@ fn measure_new_files_subset(
},
)
.map_err(|error| CheckError::metric_plugin(configuration.config_file(), error))?;
let measurement = match test_gap {
Some((ratio, unmatched_paths)) => {
measurement.with_new_file_test_gap(ratio, unmatched_paths)
}
None => measurement,
};
Ok(Some(measurement))
}

fn measure_new_file_test_gap(
snapshot: &MeasuredSnapshot,
new_files: &HashSet<RepoPath>,
selected: Option<&SelectedPackage>,
coverage_source: NewFileCoverageSource<'_>,
coverage_paths: &[String],
) -> Result<(f64, Vec<String>), CheckError> {
let coverage = coverage_source.load(coverage_paths)?;
let mut models: Vec<_> = snapshot
.languages
.iter()
.map(|language| CodeModel {
files: language.model.files.clone(),
languages: language.model.languages.clone(),
..CodeModel::default()
})
.collect();
let outcome = apply_coverage_reports(&coverage, &mut models, &snapshot.file_line_counts)?;
for (model, measured) in models.iter_mut().zip(&snapshot.languages) {
model.files.retain(|file| {
file.model.source_set == SourceSet::Production
&& new_files.contains(&file.path)
&& selected
.is_none_or(|pkg| pkg.matches(measured.model.workspace.package_of(&file.path)))
});
}
let covered = CodeModel::merge(models.into_iter().filter(|model| {
model
.files
.iter()
.any(|file| !file.model.functions.is_empty())
&& model.languages.iter().any(|facts| facts.has_coverage)
}))
.into_source_sets();
TestGap::measure(covered.get(SourceSet::Production))
.map(|test_gap| (test_gap.ratio(), outcome.unmatched_paths))
.ok_or(CheckError::NewFileTestGapBudgetWithoutCoverage)
}

fn filter_model_to_new_files(
model: &CodeModel,
new_files: &HashSet<RepoPath>,
Expand Down
20 changes: 11 additions & 9 deletions crates/cli/src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use codeint_report::{
BaseCommit, CommitMeasurement, DiffReport, DiffReportOptions, Head, HeadCommit,
};

use crate::check::coverage::NewFileCoverageSource;
use crate::check::{
CheckError, LoweringCache, PreparedOwnership, SelectedPackage, WorkspaceContext, WorkspaceRef,
};
Expand Down Expand Up @@ -262,9 +263,7 @@ fn measure_head_with_snapshots(
&base_snapshot,
&head_snapshot,
&rename_map,
request.package,
request.lowering_cache,
request.check_new_file_budgets,
&request,
)? {
return Ok(MeasuredHead {
selected: measured.selected,
Expand Down Expand Up @@ -313,24 +312,27 @@ fn measure_head_if_new_files(
base_snapshot: &Snapshot,
head_snapshot: &Snapshot,
renames: &RenameMap,
package: Option<&str>,
lowering_cache: &LoweringCache,
enabled: bool,
request: &MeasureHeadRequest<'_>,
) -> Result<Option<NewFilesHeadMeasurement>, CheckError> {
if !enabled {
if !request.check_new_file_budgets {
return Ok(None);
}
let new_files = newly_added_files(base_snapshot, head_snapshot, renames);
if new_files.is_empty() {
return Ok(None);
}
let coverage_source = match request.head_commit {
Some(commit) => NewFileCoverageSource::Head(context.repository, commit),
None => NewFileCoverageSource::WorkingTree(context.repository.root()),
};
let (selected, measurement, new_files) = measure_all_languages_with_new_files(
head_snapshot,
&new_files,
context.plugins,
context.configuration,
package,
Some(lowering_cache),
request.package,
Some(request.lowering_cache),
coverage_source,
)?;
Ok(Some(NewFilesHeadMeasurement {
selected,
Expand Down
12 changes: 10 additions & 2 deletions crates/cli/src/remedy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,9 @@ fn coverage_check_remedy(error: &CheckError) -> Option<&'static str> {
CheckError::MissingCoverageReport { .. } => {
"Check that the Coverage report path exists and generate it with your test runner before running codeint check."
}
CheckError::MissingHeadCoverageReport { .. } => {
"Commit the Coverage report at the configured path in the selected head ref."
}
CheckError::CoverageReportOutsideRepository { .. } => {
"Pass a Coverage report file inside the Git repository; codeint refuses paths and symbolic links outside the repository."
}
Expand All @@ -277,6 +280,9 @@ fn coverage_check_remedy(error: &CheckError) -> Option<&'static str> {
CheckError::TestGapBudgetWithoutCoverage { .. } => {
"Name at least one LCOV or Cobertura XML Coverage report in coverage_reports or pass --coverage-report <PATH>, or remove budgets.production.test_gap."
}
CheckError::NewFileTestGapBudgetWithoutCoverage => {
"Name an LCOV or Cobertura XML report for the measured head in coverage_reports, or remove new_file_budgets.production.test_gap."
}
_ => return None,
})
}
Expand All @@ -297,11 +303,13 @@ fn check_plugin_remedy(error: &CheckError) -> Cow<'static, str> {
CheckError::ExtensionConflict { .. }
| CheckError::UnknownWorkspacePackage { .. }
| CheckError::MissingCoverageReport { .. }
| CheckError::MissingHeadCoverageReport { .. }
| CheckError::CoverageReportOutsideRepository { .. }
| CheckError::UnreadableCoverageReport { .. }
| CheckError::InvalidCoverageReport { .. }
| CheckError::CoverageApply(_)
| CheckError::TestGapBudgetWithoutCoverage { .. }
| CheckError::NewFileTestGapBudgetWithoutCoverage
| CheckError::DialectConflict { .. }
| CheckError::UnknownHazardRule { .. }
| CheckError::StateFile(_)
Expand Down Expand Up @@ -490,8 +498,8 @@ pub(crate) fn git_remedy(error: &GitError) -> &'static str {
GitError::NonUtf8Path { .. } | GitError::InvalidPath(_) => {
"Rename the file so that its path is valid UTF-8 with no backslash, then run codeint again."
}
GitError::Read { .. } => {
"Check that you have permission to read the file, then run codeint again."
GitError::Read { .. } | GitError::FileTooLarge { .. } => {
"Check that the file is readable and within any stated size limit, then run codeint again."
}
GitError::UnknownRef { .. } => {
"Pass a branch, tag, or commit that exists in this repository; fetch it first when it lives on a remote: git fetch origin main"
Expand Down
Loading