Skip to content
Merged
3 changes: 2 additions & 1 deletion crates/cli/HOW-TO.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ if !outcome.passed {
- `run_cli` returns exit code `0` on pass, `1` when any Budget, Ratchet, Regression, `state check` violation, `doctor` blocking error, or `plugin test` check fails, and `2` on operational errors.
- Library entry points in `src/lib.rs` (`check`, `diff`, `trend`, `impact`, `trace`, `init`, `guard`, `state_check`, `schema`, `resolved_config`, `doctor`, `agent_status`, `agent_install`, `churn`, `coupling`, `ratchet_update`, `baseline_update`, `rerender_report`, `plugin_test`) return `Result<_, CodeintError>` (except `schema`), where `CodeintError` pairs `message()` with an actionable `remedy()`.
- Gated operations (`check`, `diff`, `state_check`, `doctor`, and `plugin_test`) return `GatedOutcome<T>` (aliased as `CheckOutcome`, `DiffOutcome`, `StateCheckOutcome`, `DoctorOutcome`, and `PluginTestOutcome`), which pairs `passed`, `failures`, `report`, and `rendered` (`Option<String>`, populated when `DiffOptions.format` is set).
- `state_check` accepts `StateCheckOptions` (`head_ref`, `rename_threshold` defaulting to `50` with `0` disabling rename detection and values above `100` failing with `CodeintError`) and compares each revision's configured Ratchet file and `.codeint/baseline.json` against the merge-base without parsing source files or loading Plugins.
- `state_check` accepts `StateCheckOptions` (`head_ref`, `rename_threshold` defaulting to `50` with `0` disabling rename detection and values above `100` failing with `CodeintError`) and compares each revision's configured Ratchet file and `.codeint/baseline.json` against the merge-base.
It measures the base commit with built-in Language plugins only when validating a legacy Duplication Baseline upgrade.
- `diff` accepts `DiffOptions` (including `format: Option<ReportRenderFormat>` to populate `DiffOutcome.rendered` alongside the typed `DiffReport`, and `rename_threshold` defaulting to `50`, with `0` disabling rename detection and values above `100` failing with `CodeintError`).
- `init` takes `InitOptions` (`format`, `adopt`, `plugin_host`) and returns `InitOutcome` (`configuration` plus optional `AdoptedFiles` when `adopt` is `true`).
- `ratchet_update` and `baseline_update` accept `RatchetUpdateOptions` and `BaselineUpdateOptions` (both aliases of `StateUpdateOptions` with `reset`, `coverage_reports`, and `plugin_host`).
Expand Down
1 change: 1 addition & 0 deletions crates/cli/src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ pub(crate) fn built_in_languages() -> Vec<LanguageSchema> {
.collect()
}

#[derive(Default)]
pub(crate) struct LoadedPlugins {
external_languages: Vec<(String, WasmLanguagePlugin)>,
external_metrics: Vec<(String, WasmMetricPlugin)>,
Expand Down
2 changes: 1 addition & 1 deletion crates/cli/src/commit_measurement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use crate::check::{
use crate::describe;

const CODEINT_VERSION: &str = env!("CARGO_PKG_VERSION");
const MEASUREMENT_CACHE_VERSION: u32 = 10;
const MEASUREMENT_CACHE_VERSION: u32 = 11;

#[derive(Serialize)]
struct MeasurementSettings<'configuration> {
Expand Down
1 change: 1 addition & 0 deletions crates/cli/src/remedy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ fn state_check_remedy(error: &StateCheckError) -> Cow<'static, str> {
StateCheckError::Git(error) => Cow::Borrowed(git_remedy(error)),
StateCheckError::Configuration(error) => configuration_file_remedy(error),
StateCheckError::StateFile(error) => state_file_remedy(error),
StateCheckError::BaselineMeasurement(error) => check_remedy(error),
StateCheckError::InvalidRenameThreshold { .. } => {
Cow::Borrowed("Pass an integer from 0 to 100 for --rename-threshold.")
}
Expand Down
93 changes: 83 additions & 10 deletions crates/cli/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use codeint_config::{
Expand All @@ -7,9 +7,11 @@ use codeint_config::{
parse_configuration_files,
};
use codeint_git::{GitError, Repository, Snapshot, SnapshotFileLookup};
use codeint_model::RepoPath;
use codeint_model::{Metric, RepoPath, SourceSet};
use codeint_report::{BaseCommit, StateCheckReport};

use crate::check::{CheckError, LoadedPlugins};
use crate::commit_measurement::measure_all_languages_for_package;
use crate::diff::{Refs, Sides, sides};

#[derive(Debug, thiserror::Error)]
Expand All @@ -20,6 +22,8 @@ pub(crate) enum StateCheckError {
Configuration(#[from] ConfigurationFileError),
#[error(transparent)]
StateFile(#[from] StateFileError),
#[error("cannot verify the Duplication Baseline upgrade: {0}")]
BaselineMeasurement(#[source] Box<CheckError>),
#[error("rename threshold {threshold} is out of range (0..={MAX_RENAME_THRESHOLD})")]
InvalidRenameThreshold { threshold: u8 },
#[error("invalid {file} path {path:?}")]
Expand Down Expand Up @@ -54,30 +58,46 @@ pub(crate) fn check(
});
}
let repository = Repository::discover(folder)?;
let Sides {
merge_base,
head,
head_commit,
} = sides(
let revisions = sides(
&repository,
&Refs {
base: base_ref,
head: head_ref,
},
)?;

compare_revisions(&repository, base_ref, revisions, rename_threshold)
}

fn compare_revisions(
repository: &Repository,
base_ref: &str,
revisions: Sides,
rename_threshold: u8,
) -> Result<StateCheckReport, StateCheckError> {
let Sides {
merge_base,
head,
head_commit,
} = revisions;
let base_snapshot = repository.commit(merge_base)?;
let base_state = load_revision_state(RevisionSource::Commit(&base_snapshot), "base commit")?;
let head_state = load_head_state(&repository, head_commit)?;
let mut base_state =
load_revision_state(RevisionSource::Commit(&base_snapshot), "base commit")?;
let head_state = load_head_state(repository, head_commit)?;

let renames = detect_baseline_renames(
&repository,
repository,
&base_snapshot,
head_state.snapshot.as_ref(),
base_state.baseline.is_some() && head_state.baseline.is_some(),
rename_threshold,
)?;

verify_clone_anchor_upgrades(
&base_snapshot,
base_state.baseline.as_mut(),
head_state.baseline.as_ref(),
)?;
let comparison = compare_state(
&base_state.ratchet_path,
base_state.ratchet.as_ref(),
Expand All @@ -99,6 +119,59 @@ pub(crate) fn check(
))
}

fn verify_clone_anchor_upgrades(
base_snapshot: &Snapshot,
base: Option<&mut Baseline>,
head: Option<&Baseline>,
) -> Result<(), StateCheckError> {
let (Some(base), Some(head)) = (base, head) else {
return Ok(());
};
let metric = Metric::Duplication.key();
let upgraded_sets: Vec<SourceSet> = base
.source_sets
.iter()
.into_iter()
.filter_map(|(source_set, entries)| {
let before = entries.get(metric)?;
let after = head.entry(Some(source_set), metric)?;
if before.metric_version != after.metric_version {
return None;
}
let legacy_ids: BTreeSet<_> = before
.findings
.iter()
.filter(|finding| finding.clone_lines.is_empty())
.map(|finding| &finding.id)
.collect();
after
.findings
.iter()
.any(|finding| !finding.clone_lines.is_empty() && legacy_ids.contains(&finding.id))
.then_some(source_set)
})
.collect();
if upgraded_sets.is_empty() {
return Ok(());
}
let configuration =
load_revision_configuration(RevisionSource::Commit(base_snapshot), "base commit")?;
let (_, measurement) = measure_all_languages_for_package(
base_snapshot,
&LoadedPlugins::default(),
&configuration,
None,
None,
)
.map_err(|error| StateCheckError::BaselineMeasurement(Box::new(error)))?;
for source_set in upgraded_sets {
if let Some(entry) = base.source_sets.get_mut(source_set).get_mut(metric) {
entry.upgrade_clone_line_anchors(measurement.clone_group_anchors(source_set));
}
}
Ok(())
}

#[derive(Clone, Copy)]
enum RevisionSource<'a> {
Commit(&'a Snapshot),
Expand Down
20 changes: 20 additions & 0 deletions crates/cli/tests/fixtures/duplication-baseline/long.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export function first(item: Record<string, number>) {
let total = 0;
if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; }
if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; }
for (const n of [item.x, item.y, item.z]) total += n;
total += Math.sign(item.x) * (item.y - item.z);
total *= item.x > 0 ? item.y : item.z;
for (const n of [item.x, item.y, item.z]) total += n;
if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; }
total += Math.sign(item.x) * (item.y - item.z);
for (const n of [item.x, item.y, item.z]) total += n;
total *= item.x > 0 ? item.y : item.z;
switch (item.x) { case 3: total += item.y; break; default: total -= item.z; }
total *= item.x > 0 ? item.y : item.z;
total += Math.sign(item.x) * (item.y - item.z);
if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; }
total *= item.x > 0 ? item.y : item.z;
total += Math.sign(item.x) * (item.y - item.z);
return total;
}
17 changes: 17 additions & 0 deletions crates/cli/tests/fixtures/duplication-baseline/replacement.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export const third = {
currency: 'USD',
region: 'north',
notes: ['manual', 'reviewed'],
offset: null,
retries: 2,
enabled: true,
aliases: new Set(['short', 'long']),
limit: 300,
window: { starts: 12, ends: 42 },
owner: { active: false },
account: { kind: 'sample' },
count: 91,
empty: [],
route: '/test',
threshold: 0.25,
};
18 changes: 18 additions & 0 deletions crates/cli/tests/fixtures/duplication-baseline/short.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export function third(item: Record<string, number>) {
let total = 0;
if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; }
if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; }
for (const n of [item.x, item.y, item.z]) total += n;
total += Math.sign(item.x) * (item.y - item.z);
total *= item.x > 0 ? item.y : item.z;
for (const n of [item.x, item.y, item.z]) total += n;
if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; }
total += Math.sign(item.x) * (item.y - item.z);
for (const n of [item.x, item.y, item.z]) total += n;
total *= item.x > 0 ? item.y : item.z;
switch (item.x) { case 3: total += item.y; break; default: total -= item.z; }
total *= item.x > 0 ? item.y : item.z;
total += Math.sign(item.x) * (item.y - item.z);
if (item.x === 0) { total = total * 2 + item.y; } else { total += item.z; }
return total;
}
Loading