From d5c09ac0f34750c128101eb58e198be334eebf70 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:21:26 +0800 Subject: [PATCH 1/4] feat(cli): add native gix file churn and churn-prioritized findings Extend crates/git with native gix first-parent tree-diff churn analysis over configurable --since (days or UTC date) and --commits windows, with clean shallow-clone and non-Git diagnostics. Surface churn-prioritized Erosion and Duplication Findings independently per Metric (preserving ADR 0003 with no blended score) via codeint churn (text, TOON, JSON, Markdown) and the read-only churn tool in codeint mcp. Closes #182 --- crates/cli/src/check.rs | 14 +- crates/cli/src/churn.rs | 37 ++++ crates/cli/src/lib.rs | 62 +++++- crates/cli/src/mcp.rs | 65 +++++- crates/cli/tests/churn.rs | 329 ++++++++++++++++++++++++++++ crates/cli/tests/mcp.rs | 48 +++- crates/config/src/churn.rs | 83 +++++++ crates/config/src/lib.rs | 76 ++++++- crates/git/src/churn.rs | 287 ++++++++++++++++++++++++ crates/git/src/lib.rs | 2 + crates/report/src/churn.rs | 280 +++++++++++++++++++++++ crates/report/src/churn/markdown.rs | 103 +++++++++ crates/report/src/churn/text.rs | 69 ++++++ crates/report/src/lib.rs | 2 + docs/reference.md | 27 ++- 15 files changed, 1471 insertions(+), 13 deletions(-) create mode 100644 crates/cli/src/churn.rs create mode 100644 crates/cli/tests/churn.rs create mode 100644 crates/config/src/churn.rs create mode 100644 crates/git/src/churn.rs create mode 100644 crates/report/src/churn.rs create mode 100644 crates/report/src/churn/markdown.rs create mode 100644 crates/report/src/churn/text.rs diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index f678623..82b8604 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -162,14 +162,22 @@ impl LoadedPlugins { } } -pub(crate) fn check( +pub(crate) fn load_workspace( folder: &Path, - findings: FindingsShown, plugin_host: &PluginHostConfig, -) -> Result { +) -> Result<(Repository, Configuration, LoadedPlugins), CheckError> { let repository = Repository::discover(folder)?; let configuration = read_configuration(repository.root())?; let loaded = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; + Ok((repository, configuration, loaded)) +} + +pub(crate) fn check( + folder: &Path, + findings: FindingsShown, + plugin_host: &PluginHostConfig, +) -> Result { + let (repository, configuration, loaded) = load_workspace(folder, plugin_host)?; let plugins = loaded.as_named(); let metric_plugins = loaded.metric_plugins(); check_loaded( diff --git a/crates/cli/src/churn.rs b/crates/cli/src/churn.rs new file mode 100644 index 0000000..299ebe6 --- /dev/null +++ b/crates/cli/src/churn.rs @@ -0,0 +1,37 @@ +use std::path::Path; + +use codeint_config::{ChurnWindow, FindingsShown, PluginHostConfig}; +use codeint_git::ChurnRange; +use codeint_report::{ChurnHistoryInput, ChurnReport}; + +use crate::check::{CheckError, load_workspace, measure_with}; + +pub(crate) fn churn( + folder: &Path, + window: ChurnWindow, + findings: FindingsShown, + plugin_host: &PluginHostConfig, +) -> Result { + let (repository, configuration, loaded) = load_workspace(folder, plugin_host)?; + let plugins = loaded.as_named(); + let history = repository.file_churn(churn_range(window))?; + let tree = repository.working_tree()?; + let languages = measure_with(&tree, &plugins, &configuration)?; + let input = ChurnHistoryInput { + window, + commits_analyzed: history.commits_analyzed, + shallow: history.shallow, + touches_by_file: history.touches_by_file, + }; + Ok(ChurnReport::summarize(languages, &input, findings)) +} + +fn churn_range(window: ChurnWindow) -> ChurnRange { + match window { + ChurnWindow::Days(days) => ChurnRange::Days(days), + ChurnWindow::Since(day) => ChurnRange::Since { + unix_seconds: day.start_unix_seconds(), + }, + ChurnWindow::Commits(count) => ChurnRange::Commits(count), + } +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c3c9d6d..38958b4 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -1,6 +1,7 @@ #![forbid(unsafe_code)] mod check; +mod churn; mod commit_measurement; mod diff; mod guard; @@ -21,10 +22,10 @@ use codeint_git::ResultCache; use codeint_report::ReportError; pub use codeint_config::{ - CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, - TrendRange, + CalendarDay, ChurnFormat, ChurnSince, ChurnWindow, FindingsShown, GuardFormat, + PluginHostConfig, ReportFormat, TrendFormat, TrendRange, }; -pub use codeint_report::{DiffReport, GuardReport, Report, TrendReport}; +pub use codeint_report::{ChurnReport, DiffReport, GuardReport, Report, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -80,6 +81,23 @@ impl Default for TrendOptions { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChurnOptions { + pub window: ChurnWindow, + pub findings: FindingsShown, + pub plugin_host: PluginHostConfig, +} + +impl Default for ChurnOptions { + fn default() -> ChurnOptions { + ChurnOptions { + window: ChurnWindow::default(), + findings: FindingsShown::WorstPerMetric(DEFAULT_WORST_FINDINGS), + plugin_host: PluginHostConfig::default(), + } + } +} + pub struct CheckOutcome { pub passed: bool, pub failures: Vec, @@ -188,6 +206,16 @@ pub fn guard(folder: &Path, target: &Path) -> Result guard::guard(folder, target).map_err(|err| CodeintError::from_cli_error(CliError::Guard(err))) } +pub fn churn(folder: &Path, options: &ChurnOptions) -> Result { + churn::churn( + folder, + options.window, + options.findings, + &options.plugin_host, + ) + .map_err(|err| CodeintError::from_cli_error(CliError::Check(err))) +} + #[derive(Debug, thiserror::Error)] enum CliError { #[error(transparent)] @@ -304,9 +332,37 @@ fn run() -> Result { target, format, } => run_guard(&folder, &target, format), + Command::Churn { + folder, + window, + destination, + findings, + format, + plugin_host, + } => run_churn( + &folder, + window, + &destination, + findings, + format, + &plugin_host, + ), } } +fn run_churn( + folder: &Path, + window: ChurnWindow, + destination: &ReportDestination, + findings: FindingsShown, + format: ChurnFormat, + plugin_host: &PluginHostConfig, +) -> Result { + let report = churn::churn(folder, window, findings, plugin_host)?; + write_report(&report.render(format)?, destination)?; + Ok(Outcome::Passed) +} + fn run_guard(folder: &Path, target: &Path, format: GuardFormat) -> Result { let report = guard::guard(folder, target)?; print_report(&format!("{}\n", report.render(format)?))?; diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 55e02b3..6394dd3 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -3,12 +3,14 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use codeint_config::{ - CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, - TrendRange, + CalendarDay, ChurnFormat, ChurnSince, ChurnWindow, FindingsShown, GuardFormat, + PluginHostConfig, ReportFormat, TrendFormat, TrendRange, }; use serde_json::{Value, json}; -use crate::{CheckOptions, DiffOptions, TrendOptions, check, diff, guard, trend}; +use crate::{ + CheckOptions, ChurnOptions, DiffOptions, TrendOptions, check, churn, diff, guard, trend, +}; const DEFAULT_PROTOCOL_VERSION: &str = "2024-11-05"; @@ -170,6 +172,19 @@ fn handle_tools_list() -> Value { "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." } } } + }, + { + "name": "churn", + "description": "Rank eroded and duplicated files alongside their Git commit churn independently per Metric over a configurable lookback window.", + "inputSchema": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "since": { "type": "string", "description": "Lookback window in days (such as 90d) or UTC date (YYYY-MM-DD); mutually exclusive with commits." }, + "commits": { "type": "integer", "minimum": 1, "description": "Walk at most this many main-line commits from HEAD; mutually exclusive with since." }, + "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } + } + } } ] }) @@ -189,6 +204,7 @@ fn handle_tools_call( "diff" => Ok(call_diff(args, ctx)), "trend" => Ok(call_trend(args, ctx)), "guard" => Ok(call_guard(args, ctx)), + "churn" => Ok(call_churn(args, ctx)), other => Err((-32602, format!("Unknown tool: {other}"))), } } @@ -304,6 +320,49 @@ fn call_guard(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { }) } +fn call_churn(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { + let window = match parse_churn_window(args) { + Ok(window) => window, + Err(err) => return err, + }; + let folder = resolve_folder(args, ctx.default_folder); + let options = ChurnOptions { + window, + findings: parse_findings(args), + plugin_host: ctx.plugin_host.clone(), + }; + render_json_tool(churn(&folder, &options), |report| { + report.render(ChurnFormat::Json) + }) +} + +fn parse_churn_window(args: Option<&Value>) -> Result { + let since_val = args.and_then(|a| a.get("since")).filter(|v| !v.is_null()); + let commits_val = args.and_then(|a| a.get("commits")).filter(|v| !v.is_null()); + if since_val.is_some() && commits_val.is_some() { + return Err(tool_err( + "Arguments since and commits are mutually exclusive", + )); + } + if let Some(value) = since_val { + let text = value + .as_str() + .ok_or_else(|| tool_err("Argument since must be a string"))?; + return ChurnSince::from_str(text) + .map(ChurnWindow::from) + .map_err(|err| tool_err(&format!("Invalid since window {text:?}: {err}"))); + } + if let Some(value) = commits_val { + let count = value + .as_u64() + .and_then(|n| usize::try_from(n).ok()) + .filter(|&n| n > 0) + .ok_or_else(|| tool_err("Argument commits must be a positive integer"))?; + return Ok(ChurnWindow::Commits(count)); + } + Ok(ChurnWindow::default()) +} + fn resolve_folder(args: Option<&Value>, default_folder: &Path) -> PathBuf { match args.and_then(|a| a.get("path")).and_then(Value::as_str) { Some(p) if !p.is_empty() => { diff --git a/crates/cli/tests/churn.rs b/crates/cli/tests/churn.rs new file mode 100644 index 0000000..5fd252f --- /dev/null +++ b/crates/cli/tests/churn.rs @@ -0,0 +1,329 @@ +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +use serde_json::Value; +use tempfile::TempDir; + +struct ChurnFixture(TempDir); + +impl ChurnFixture { + fn init() -> ChurnFixture { + let dir = tempfile::tempdir().expect("tempdir"); + run_git( + dir.path(), + &["init", "-q", "-b", "main"], + "2026-05-01T10:00:00Z", + ); + ChurnFixture(dir) + } + + fn root(&self) -> &Path { + self.0.path() + } + + fn save_and_commit(&self, files: &[(&str, String)], msg: &str, when: &str) { + for (rel, content) in files { + let dest = self.root().join(rel); + fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir"); + fs::write(dest, content).expect("write"); + } + run_git(self.root(), &["add", "-A"], when); + run_git(self.root(), &["commit", "-q", "-m", msg], when); + } + + fn churn(&self, extra: &[&str]) -> Output { + exec_churn(self.root(), extra) + } + + fn churn_json(&self, extra: &[&str]) -> Value { + let args: Vec<&str> = extra.iter().copied().chain(["--format", "json"]).collect(); + let out = self.churn(&args); + assert_eq!( + out.status.code(), + Some(0), + "churn stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + serde_json::from_slice(&out.stdout).expect("valid churn JSON") + } +} + +fn run_git(cwd: &Path, args: &[&str], when: &str) { + let vars = [ + ("GIT_CONFIG_GLOBAL", "/dev/null"), + ("GIT_CONFIG_NOSYSTEM", "1"), + ("GIT_AUTHOR_NAME", "Churn"), + ("GIT_AUTHOR_EMAIL", "churn@example.invalid"), + ("GIT_COMMITTER_NAME", "Churn"), + ("GIT_COMMITTER_EMAIL", "churn@example.invalid"), + ("GIT_AUTHOR_DATE", when), + ("GIT_COMMITTER_DATE", when), + ]; + let out = Command::new("git") + .args(args) + .current_dir(cwd) + .envs(vars) + .output() + .expect("git"); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); +} + +fn exec_churn(cwd: &Path, extra: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .arg("churn") + .args(extra) + .current_dir(cwd) + .output() + .expect("run codeint churn") +} + +fn eroded_ts(name: &str, salt: usize) -> String { + let checks: String = (1..=12) + .map(|i| format!(" if (v === {i}) return {};\n", i + salt)) + .collect(); + format!("export function {name}(v: number): number {{\n{checks} return {salt};\n}}\n") +} + +fn duplicated_ts(prefix: &str, extra: &str) -> String { + format!( + "export function {prefix}Calc(items: number[], fee: number): number {{\n\ + \x20 let acc = 0;\n\ + \x20 for (const item of items) {{\n\ + \x20 if (item > 0) {{\n\ + \x20 acc += item * 2;\n\ + \x20 }} else {{\n\ + \x20 acc -= item;\n\ + \x20 }}\n\ + \x20 }}\n\ + \x20 const net = acc - fee;\n\ + \x20 const rounded = Math.round(net * 100) / 100;\n\ + \x20 const floored = Math.max(rounded, 0);\n\ + \x20 const finalValue = floored + 1;\n\ + \x20 return finalValue;\n\ + }}\n\ + {extra}\n" + ) +} + +fn assert_no_blended_score_keys(value: &Value) { + let forbidden = ["score", "index", "grade", "rating", "hotspot_score"]; + match value { + Value::Object(map) => { + for (k, v) in map { + let lower = k.to_ascii_lowercase(); + for word in forbidden { + assert!( + !lower.contains(word), + "ADR 0003 violation: unexpected blended key {k:?}" + ); + } + assert_no_blended_score_keys(v); + } + } + Value::Array(items) => items.iter().for_each(assert_no_blended_score_keys), + _ => {} + } +} + +fn assert_format_contains(repo: &ChurnFixture, format: &str, needles: &[&str]) { + let out = repo.churn(&["--format", format]); + assert_eq!( + out.status.code(), + Some(0), + "{format} stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8_lossy(&out.stdout); + for needle in needles { + assert!( + stdout.contains(needle), + "{format} missing {needle:?}: {stdout}" + ); + } +} + +#[test] +fn churn_ranks_eroded_and_duplicated_files_independently_by_commit_count_with_no_score() { + let repo = ChurnFixture::init(); + repo.save_and_commit( + &[ + ("src/cold_eroded.ts", eroded_ts("coldEroded", 0)), + ("src/hot_eroded.ts", eroded_ts("hotEroded", 1)), + ("src/cold_dup.ts", duplicated_ts("cold", "")), + ( + "src/hot_dup.ts", + duplicated_ts("hot", "export const v1 = 1;"), + ), + ("src/clean.ts", "export const clean = 1;\n".to_owned()), + ], + "initial", + "2026-05-01T10:00:00Z", + ); + repo.save_and_commit( + &[ + ("src/hot_eroded.ts", eroded_ts("hotEroded", 2)), + ( + "src/hot_dup.ts", + duplicated_ts("hot", "export const v1 = 2;"), + ), + ("src/clean.ts", "export const clean = 2;\n".to_owned()), + ], + "touch hot files 2", + "2026-05-02T10:00:00Z", + ); + repo.save_and_commit( + &[ + ("src/hot_eroded.ts", eroded_ts("hotEroded", 3)), + ( + "src/hot_dup.ts", + duplicated_ts("hot", "export const v1 = 3;"), + ), + ("src/clean.ts", "export const clean = 3;\n".to_owned()), + ], + "touch hot files 3", + "2026-05-03T10:00:00Z", + ); + repo.save_and_commit( + &[ + ("src/hot_eroded.ts", eroded_ts("hotEroded", 4)), + ("src/clean.ts", "export const clean = 4;\n".to_owned()), + ], + "touch hot eroded 4", + "2026-05-04T10:00:00Z", + ); + + let report = repo.churn_json(&[]); + assert_no_blended_score_keys(&report); + assert_eq!(report["commits_analyzed"], 4); + assert_eq!(report["shallow"], false); + assert!(report.get("warning").is_none()); + + let eroded = report["source_sets"]["production"]["erosion"]["findings"] + .as_array() + .expect("eroded findings"); + assert_eq!(eroded.len(), 2); + assert_eq!(eroded[0]["path"], "src/hot_eroded.ts"); + assert_eq!(eroded[0]["commits"], 4); + assert_eq!(eroded[0]["eroded_functions"], 1); + assert!(eroded[0]["eroded_function_mass"].as_f64().expect("mass") > 0.0); + assert_eq!(eroded[1]["path"], "src/cold_eroded.ts"); + assert_eq!(eroded[1]["commits"], 1); + + let duplicated = report["source_sets"]["production"]["duplication"]["findings"] + .as_array() + .expect("duplication findings"); + assert_eq!(duplicated.len(), 2); + assert_eq!(duplicated[0]["path"], "src/hot_dup.ts"); + assert_eq!(duplicated[0]["commits"], 3); + assert!(duplicated[0]["clone_lines"].as_u64().expect("clone_lines") > 0); + assert_eq!(duplicated[0]["clone_groups"], 1); + assert_eq!(duplicated[1]["path"], "src/cold_dup.ts"); + assert_eq!(duplicated[1]["commits"], 1); +} + +#[test] +fn churn_respects_since_days_since_date_and_commits_window() { + let repo = ChurnFixture::init(); + for (label, salt, when) in [ + ("old", 1, "2026-01-01T10:00:00Z"), + ("mid", 2, "2026-05-01T10:00:00Z"), + ("recent", 3, "2026-05-10T10:00:00Z"), + ("head", 4, "2026-05-15T10:00:00Z"), + ] { + repo.save_and_commit(&[("src/eroded.ts", eroded_ts(label, salt))], label, when); + } + + let by_days = repo.churn_json(&["--since", "30d"]); + assert_eq!(by_days["commits_analyzed"], 3); + assert_eq!( + by_days["source_sets"]["production"]["erosion"]["findings"][0]["commits"], + 3 + ); + + let by_date = repo.churn_json(&["--since", "2026-05-05"]); + assert_eq!(by_date["commits_analyzed"], 2); + assert_eq!( + by_date["source_sets"]["production"]["erosion"]["findings"][0]["commits"], + 2 + ); + + let by_commits = repo.churn_json(&["--commits", "2"]); + assert_eq!(by_commits["commits_analyzed"], 2); + assert_eq!( + by_commits["source_sets"]["production"]["erosion"]["findings"][0]["commits"], + 2 + ); + + assert_eq!( + repo.churn(&["--since", "30d", "--commits", "5"]) + .status + .code(), + Some(2) + ); + assert_eq!(repo.churn(&["--since", "0d"]).status.code(), Some(2)); +} + +#[test] +fn churn_renders_text_toon_json_and_markdown_formats() { + let repo = ChurnFixture::init(); + repo.save_and_commit( + &[("src/eroded.ts", eroded_ts("hot", 1))], + "c1", + "2026-05-01T10:00:00Z", + ); + repo.save_and_commit( + &[("src/eroded.ts", eroded_ts("hot", 2))], + "c2", + "2026-05-02T10:00:00Z", + ); + + assert_format_contains(&repo, "text", &["src/eroded.ts", "Erosion"]); + assert_format_contains(&repo, "toon", &["commits_analyzed: 2", "src/eroded.ts"]); + assert_format_contains(&repo, "markdown", &["# codeint churn", "`src/eroded.ts`"]); +} + +#[test] +fn churn_handles_shallow_clones_and_non_git_directories_gracefully() { + let origin = ChurnFixture::init(); + for i in 1..=4 { + origin.save_and_commit( + &[("src/eroded.ts", eroded_ts("hot", i))], + &format!("c{i}"), + &format!("2026-05-0{i}T10:00:00Z"), + ); + } + + let shallow = ChurnFixture::init(); + let url = format!("file://{}", origin.root().display()); + run_git( + shallow.root(), + &["fetch", "-q", "--depth", "2", &url, "main"], + "2026-05-05T10:00:00Z", + ); + run_git( + shallow.root(), + &["reset", "-q", "--hard", "FETCH_HEAD"], + "2026-05-05T10:00:00Z", + ); + + let report = shallow.churn_json(&[]); + assert_eq!(report["shallow"], true); + assert_eq!(report["commits_analyzed"], 2); + let warning = report["warning"].as_str().expect("shallow clone warning"); + assert!(warning.contains("shallow"), "warning: {warning}"); + assert!(warning.contains("--unshallow"), "warning: {warning}"); + + let non_git = tempfile::tempdir().expect("non-git tempdir"); + let out = exec_churn(non_git.path(), &[]); + assert_eq!(out.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("not inside a Git repository"), + "stderr: {stderr}" + ); +} diff --git a/crates/cli/tests/mcp.rs b/crates/cli/tests/mcp.rs index d6156b3..09a0f69 100644 --- a/crates/cli/tests/mcp.rs +++ b/crates/cli/tests/mcp.rs @@ -77,7 +77,7 @@ fn mcp_initialize_list_and_call_tools() { assert_eq!(responses[0]["result"]["serverInfo"]["name"], "codeint"); let tools = responses[1]["result"]["tools"].as_array().unwrap(); let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["check", "diff", "trend", "guard"]); + assert_eq!(names, ["check", "diff", "trend", "guard", "churn"]); assert_eq!(responses[2]["result"]["isError"], false); let check_payload: Value = serde_json::from_str( @@ -205,3 +205,49 @@ fn mcp_guard_tool_reports_existing_planned_unzoned_and_unconfigured_paths() { assert_eq!(unzoned["configured"], true); assert!(unzoned.get("zone").is_none()); } + +fn tool_call(id: u64, name: &str, arguments: Value) -> Value { + json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { "name": name, "arguments": arguments } + }) +} + +#[test] +fn mcp_churn_tool_reports_file_churn_and_handles_non_git_directory() { + let repo = init_sample_repo(); + let non_git = TempDir::new().unwrap(); + let responses = send_mcp_requests( + repo.path(), + &[ + tool_call(1, "churn", json!({"commits": 10})), + tool_call( + 2, + "churn", + json!({"path": non_git.path().to_string_lossy()}), + ), + ], + ); + assert_eq!(responses.len(), 2); + assert_eq!(responses[0]["result"]["isError"], false); + let payload: Value = serde_json::from_str( + responses[0]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(payload["commits_analyzed"], 1); + assert_eq!(payload["shallow"], false); + assert!(payload.get("score").is_none()); + + assert_eq!(responses[1]["result"]["isError"], true); + let err_text = responses[1]["result"]["content"][0]["text"] + .as_str() + .unwrap(); + assert!( + err_text.contains("not inside a Git repository"), + "err: {err_text}" + ); +} diff --git a/crates/config/src/churn.rs b/crates/config/src/churn.rs new file mode 100644 index 0000000..61251b4 --- /dev/null +++ b/crates/config/src/churn.rs @@ -0,0 +1,83 @@ +use std::fmt; +use std::str::FromStr; + +use crate::CalendarDay; + +pub const DEFAULT_CHURN_DAYS: u32 = 90; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum ChurnFormat { + Text, + Toon, + Json, + Markdown, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChurnSince { + Days(u32), + Day(CalendarDay), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChurnWindow { + Days(u32), + Since(CalendarDay), + Commits(usize), +} + +impl Default for ChurnWindow { + fn default() -> ChurnWindow { + ChurnWindow::Days(DEFAULT_CHURN_DAYS) + } +} + +impl From for ChurnWindow { + fn from(since: ChurnSince) -> ChurnWindow { + match since { + ChurnSince::Days(days) => ChurnWindow::Days(days), + ChurnSince::Day(day) => ChurnWindow::Since(day), + } + } +} + +impl fmt::Display for ChurnWindow { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ChurnWindow::Days(days) => write!(formatter, "{days}d"), + ChurnWindow::Since(day) => write!(formatter, "{day}"), + ChurnWindow::Commits(1) => write!(formatter, "1 commit"), + ChurnWindow::Commits(count) => write!(formatter, "{count} commits"), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error( + "{text:?} is not a positive day count such as 90d or a real UTC date written as YYYY-MM-DD" +)] +pub struct ChurnSinceError { + text: String, +} + +impl FromStr for ChurnSince { + type Err = ChurnSinceError; + + fn from_str(text: &str) -> Result { + if let Some(prefix) = text.strip_suffix('d').or_else(|| text.strip_suffix('D')) { + if let Ok(days) = prefix.parse::() + && days > 0 + { + return Ok(ChurnSince::Days(days)); + } + return Err(ChurnSinceError { + text: text.to_owned(), + }); + } + CalendarDay::from_str(text) + .map(ChurnSince::Day) + .map_err(|_| ChurnSinceError { + text: text.to_owned(), + }) + } +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 642a0b3..3b7b662 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -6,6 +6,7 @@ use clap::{Parser, Subcommand}; mod boundaries; mod calendar_day; +mod churn; mod codeint_json; mod config_error; mod regression_limits; @@ -15,6 +16,7 @@ pub use boundaries::{ Boundaries, BoundaryDirective, BoundaryPreset, BoundaryRuleDecision, BoundarySourceSet, }; pub use calendar_day::{CalendarDay, CalendarDayError}; +pub use churn::{ChurnFormat, ChurnSince, ChurnSinceError, ChurnWindow, DEFAULT_CHURN_DAYS}; pub use codeint_json::{ Budget, Budgets, Configuration, DetectedLanguage, LanguageCoverage, Languages, PluginDeclaration, PluginKind, PluginLimits, PluginSource, Sha256Digest, SourceSetOverrides, @@ -158,6 +160,14 @@ pub enum Command { target: PathBuf, format: GuardFormat, }, + Churn { + folder: PathBuf, + window: ChurnWindow, + destination: ReportDestination, + findings: FindingsShown, + format: ChurnFormat, + plugin_host: PluginHostConfig, + }, } #[derive(Debug)] @@ -248,7 +258,7 @@ enum CommandArguments { version: Option, }, #[command( - about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, trend, and guard tools" + about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, trend, guard, and churn tools" )] Mcp, #[command( @@ -268,6 +278,40 @@ enum CommandArguments { )] format: GuardFormat, }, + #[command( + about = "Rank eroded and duplicated files alongside their Git commit churn independently per Metric" + )] + Churn { + #[arg( + long, + value_name = "WINDOW", + conflicts_with = "commits", + help = "Lookback window in days (such as 90d) or a UTC date (YYYY-MM-DD); defaults to 90d" + )] + since: Option, + #[arg( + long, + value_name = "COUNT", + conflicts_with = "since", + help = "Walk at most this many main-line commits from HEAD" + )] + commits: Option, + #[arg( + long, + value_name = "FILE", + help = "Write the report to this file instead of standard output" + )] + output: Option, + #[arg(long, help = "List every Finding instead of the 20 worst per Metric")] + all: bool, + #[arg( + long, + value_enum, + default_value_t = ChurnFormat::Toon, + help = "The format of the report" + )] + format: ChurnFormat, + }, } #[derive(Debug, clap::Args)] @@ -328,9 +372,39 @@ fn build_command( target: path, format, }), + CommandArguments::Churn { + since, + commits, + output, + all, + format, + } => build_churn_command(current_folder, since, commits, output, all, format), } } +fn build_churn_command( + current_folder: &Path, + since: Option, + commits: Option, + output: Option, + all: bool, + format: ChurnFormat, +) -> Result { + let window = match (since, commits) { + (Some(since), None) => ChurnWindow::from(since), + (None, Some(count)) => ChurnWindow::Commits(count.get()), + _ => ChurnWindow::default(), + }; + Ok(Command::Churn { + folder: current_folder.to_path_buf(), + window, + destination: report_destination(current_folder, output)?, + findings: findings_shown(all), + format, + plugin_host: plugin_host_config_of_this_process(current_folder), + }) +} + fn build_trend_command( current_folder: &Path, since: Option, diff --git a/crates/git/src/churn.rs b/crates/git/src/churn.rs new file mode 100644 index 0000000..d4c8566 --- /dev/null +++ b/crates/git/src/churn.rs @@ -0,0 +1,287 @@ +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use codeint_model::RepoPath; +use gix::ObjectId; +use gix::objs::tree::EntryMode; + +use crate::{CommitId, GitError, Repository}; + +const SECONDS_PER_DAY: i64 = 86_400; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChurnRange { + Days(u32), + Since { unix_seconds: i64 }, + Commits(usize), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileChurnSummary { + pub commits_analyzed: usize, + pub shallow: bool, + pub truncated_by_shallow_boundary: bool, + pub touches_by_file: BTreeMap, +} + +enum EffectiveRange { + Commits(usize), + Since(i64), +} + +impl EffectiveRange { + fn from_head(range: ChurnRange, head_unix_seconds: i64) -> EffectiveRange { + match range { + ChurnRange::Days(days) => EffectiveRange::Since( + head_unix_seconds.saturating_sub(i64::from(days) * SECONDS_PER_DAY), + ), + ChurnRange::Since { unix_seconds } => EffectiveRange::Since(unix_seconds), + ChurnRange::Commits(count) => EffectiveRange::Commits(count), + } + } + + fn admits(&self, analyzed: usize, committed_at_unix_seconds: i64) -> bool { + match self { + EffectiveRange::Commits(limit) => analyzed < *limit, + EffectiveRange::Since(cutoff) => committed_at_unix_seconds >= *cutoff, + } + } +} + +impl Repository { + pub fn file_churn(&self, range: ChurnRange) -> Result { + let head = self.repository.head_id().map_err(GitError::NoHistory)?; + let shallow_boundary = self + .repository + .shallow_commits() + .map_err(GitError::NoHistory)?; + let shallow = shallow_boundary + .as_ref() + .is_some_and(|boundary| !boundary.is_empty()); + let head_id = head.detach(); + let head_commit = + self.repository + .find_commit(head_id) + .map_err(|source| GitError::History { + commit: CommitId(head_id), + source, + })?; + let head_time = head_commit + .time() + .map_err(|source| GitError::History { + commit: CommitId(head_id), + source, + })? + .seconds; + let effective = EffectiveRange::from_head(range, head_time); + self.walk_churn(head_id, &effective, shallow, shallow_boundary.as_ref()) + } + + fn walk_churn( + &self, + start: ObjectId, + effective: &EffectiveRange, + shallow: bool, + shallow_boundary: Option<&gix::shallow::Commits>, + ) -> Result { + let mut commits_analyzed = 0usize; + let mut truncated_by_shallow_boundary = false; + let mut touches_by_file: BTreeMap = BTreeMap::new(); + let mut next = Some(start); + while let Some(id) = next { + let commit = CommitId(id); + let found = self + .repository + .find_commit(id) + .map_err(|source| GitError::History { commit, source })?; + let committed_at = found + .time() + .map_err(|source| GitError::History { commit, source })? + .seconds; + if !effective.admits(commits_analyzed, committed_at) { + break; + } + commits_analyzed += 1; + let at_boundary = shallow_boundary.is_some_and(|boundary| boundary.contains(&id)); + let parent_id = if at_boundary { + truncated_by_shallow_boundary = true; + None + } else { + found.parent_ids().next().map(|parent| parent.detach()) + }; + let touched = self.touched_files_in_commit(commit, &found, parent_id)?; + for path in touched { + *touches_by_file.entry(path).or_insert(0) += 1; + } + next = parent_id; + } + Ok(FileChurnSummary { + commits_analyzed, + shallow, + truncated_by_shallow_boundary, + touches_by_file, + }) + } + + fn touched_files_in_commit( + &self, + commit: CommitId, + found: &gix::Commit<'_>, + parent_id: Option, + ) -> Result, GitError> { + let new_tree = found + .tree() + .map_err(|source| GitError::CommitTree { commit, source })?; + let mut touched = BTreeSet::new(); + let mut diff = TreeDiffer { + repository: &self.repository, + commit, + touched: &mut touched, + }; + match parent_id { + Some(pid) => { + let parent_commit = CommitId(pid); + let old_tree = self + .repository + .find_commit(pid) + .and_then(|parent| parent.tree()) + .map_err(|source| GitError::CommitTree { + commit: parent_commit, + source, + })?; + diff.trees("", &old_tree, &new_tree)?; + } + None => { + diff.collect_blobs("", &new_tree)?; + } + } + Ok(touched) + } +} + +struct TreeDiffer<'a> { + repository: &'a gix::Repository, + commit: CommitId, + touched: &'a mut BTreeSet, +} + +impl TreeDiffer<'_> { + fn trees( + &mut self, + prefix: &str, + old_tree: &gix::Tree<'_>, + new_tree: &gix::Tree<'_>, + ) -> Result<(), GitError> { + if old_tree.id == new_tree.id { + return Ok(()); + } + let old_entries = tree_entries(self.commit, old_tree)?; + let new_entries = tree_entries(self.commit, new_tree)?; + self.visit_present(prefix, &old_entries, &new_entries)?; + self.visit_removed(prefix, &old_entries, &new_entries) + } + + fn visit_present( + &mut self, + prefix: &str, + old_entries: &HashMap, + new_entries: &HashMap, + ) -> Result<(), GitError> { + for (name, &(new_mode, new_oid)) in new_entries { + let path = join_prefix(prefix, name); + match old_entries.get(name) { + None => self.record_entry(&path, new_mode, new_oid)?, + Some(&(old_mode, old_oid)) if old_oid == new_oid && old_mode == new_mode => {} + Some(&(old_mode, old_oid)) => { + self.visit_changed(&path, (old_mode, old_oid), (new_mode, new_oid))?; + } + } + } + Ok(()) + } + + fn visit_removed( + &mut self, + prefix: &str, + old_entries: &HashMap, + new_entries: &HashMap, + ) -> Result<(), GitError> { + for (name, &(old_mode, old_oid)) in old_entries { + if !new_entries.contains_key(name) { + let path = join_prefix(prefix, name); + self.record_entry(&path, old_mode, old_oid)?; + } + } + Ok(()) + } + + fn visit_changed( + &mut self, + path: &str, + (old_mode, old_oid): (EntryMode, ObjectId), + (new_mode, new_oid): (EntryMode, ObjectId), + ) -> Result<(), GitError> { + if old_mode.is_tree() && new_mode.is_tree() { + let old_sub = find_tree(self.repository, self.commit, old_oid)?; + let new_sub = find_tree(self.repository, self.commit, new_oid)?; + return self.trees(path, &old_sub, &new_sub); + } + self.record_entry(path, old_mode, old_oid)?; + self.record_entry(path, new_mode, new_oid) + } + + fn record_entry(&mut self, path: &str, mode: EntryMode, oid: ObjectId) -> Result<(), GitError> { + if mode.is_blob() { + if let Ok(repo_path) = RepoPath::new(path) { + self.touched.insert(repo_path); + } + } else if mode.is_tree() { + let subtree = find_tree(self.repository, self.commit, oid)?; + self.collect_blobs(path, &subtree)?; + } + Ok(()) + } + + fn collect_blobs(&mut self, prefix: &str, tree: &gix::Tree<'_>) -> Result<(), GitError> { + for (name, (mode, oid)) in tree_entries(self.commit, tree)? { + let path = join_prefix(prefix, &name); + self.record_entry(&path, mode, oid)?; + } + Ok(()) + } +} + +fn find_tree( + repository: &gix::Repository, + commit: CommitId, + oid: ObjectId, +) -> Result, GitError> { + repository + .find_tree(oid) + .map_err(|source| GitError::CommitTree { commit, source }) +} + +fn tree_entries( + commit: CommitId, + tree: &gix::Tree<'_>, +) -> Result, GitError> { + let mut map = HashMap::new(); + for entry in tree.iter() { + let entry = entry.map_err(|source| GitError::CommitTree { commit, source })?; + let Ok(name) = std::str::from_utf8(entry.inner.filename) else { + continue; + }; + map.insert( + name.to_owned(), + (entry.inner.mode, entry.inner.oid.to_owned()), + ); + } + Ok(map) +} + +fn join_prefix(prefix: &str, name: &str) -> String { + if prefix.is_empty() { + name.to_owned() + } else { + format!("{prefix}/{name}") + } +} diff --git a/crates/git/src/lib.rs b/crates/git/src/lib.rs index 54c7c7c..5c2b739 100644 --- a/crates/git/src/lib.rs +++ b/crates/git/src/lib.rs @@ -9,9 +9,11 @@ use gix::dir::entry::{Kind, Status}; use gix::dir::walk::EmissionMode; use gix::dir::walk::delegate::Collect; +mod churn; mod history; mod result_cache; +pub use churn::{ChurnRange, FileChurnSummary}; pub use history::{CommitRange, HistoryCommit}; pub use result_cache::{ResultCache, ResultCacheError}; diff --git a/crates/report/src/churn.rs b/crates/report/src/churn.rs new file mode 100644 index 0000000..58437a3 --- /dev/null +++ b/crates/report/src/churn.rs @@ -0,0 +1,280 @@ +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet}; + +use codeint_config::{ChurnFormat, ChurnWindow, FindingsShown}; +use codeint_metrics::{Duplication, Erosion, MinimumCloneTokens, MinimumDistinctTokens}; +use codeint_model::{CodeModel, RepoPath, SourceSet}; +use serde::Serialize; + +use crate::{Decimal, FindingKind, Findings, MeasuredLanguage, ReportError}; + +mod markdown; +mod text; + +const SHALLOW_WARNING: &str = "Repository is a shallow clone; commit churn counts stop at the shallow boundary and may be incomplete. Fetch full history with `git fetch --unshallow`."; + +pub struct ChurnHistoryInput { + pub window: ChurnWindow, + pub commits_analyzed: usize, + pub shallow: bool, + pub touches_by_file: BTreeMap, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)] +#[serde(rename_all = "snake_case")] +enum SourceSetKey { + Production, + Test, + Generated, + Vendored, +} + +impl SourceSetKey { + fn from_source_set(source_set: SourceSet) -> SourceSetKey { + match source_set { + SourceSet::Production => SourceSetKey::Production, + SourceSet::Test => SourceSetKey::Test, + SourceSet::Generated => SourceSetKey::Generated, + SourceSet::Vendored => SourceSetKey::Vendored, + } + } + + fn heading(self) -> &'static str { + match self { + SourceSetKey::Production => "Production", + SourceSetKey::Test => "Test", + SourceSetKey::Generated => "Generated", + SourceSetKey::Vendored => "Vendored", + } + } +} + +#[derive(Debug, Serialize)] +pub struct ChurnReport { + window: String, + commits_analyzed: usize, + shallow: bool, + #[serde(skip_serializing_if = "Option::is_none")] + warning: Option, + source_sets: BTreeMap, +} + +#[derive(Debug, Serialize)] +struct SourceSetChurnSection { + files: usize, + erosion: ErosionChurnSection, + duplication: DuplicationChurnSection, +} + +#[derive(Debug, Serialize)] +struct ErosionChurnSection { + ratio: Decimal, + eroded_function_mass: Decimal, + total_function_mass: Decimal, + #[serde(flatten)] + findings: Findings, +} + +#[derive(Debug, Serialize)] +struct ErodedChurnFile { + path: String, + commits: usize, + eroded_functions: usize, + eroded_function_mass: Decimal, + max_cyclomatic_complexity: u32, +} + +#[derive(Debug, Serialize)] +struct DuplicationChurnSection { + ratio: Decimal, + clone_lines: u64, + #[serde(flatten)] + findings: Findings, +} + +#[derive(Debug, Serialize)] +struct DuplicatedChurnFile { + path: String, + commits: usize, + clone_lines: u64, + clone_groups: usize, +} + +impl FindingKind for ErodedChurnFile { + const LIST_KEY: &'static str = "findings"; +} + +impl FindingKind for DuplicatedChurnFile { + const LIST_KEY: &'static str = "findings"; +} + +impl ChurnReport { + pub fn summarize( + languages: Vec, + history: &ChurnHistoryInput, + findings: FindingsShown, + ) -> ChurnReport { + let model = CodeModel::merge(languages.into_iter().map(|lang| lang.model)); + let mut source_sets = BTreeMap::new(); + for (source_set, part) in model.into_source_sets().iter() { + if !part.files.is_empty() { + source_sets.insert( + SourceSetKey::from_source_set(source_set), + SourceSetChurnSection::new(part, &history.touches_by_file, findings), + ); + } + } + let warning = history.shallow.then(|| SHALLOW_WARNING.to_owned()); + ChurnReport { + window: history.window.to_string(), + commits_analyzed: history.commits_analyzed, + shallow: history.shallow, + warning, + source_sets, + } + } + + pub fn render(&self, format: ChurnFormat) -> Result { + match format { + ChurnFormat::Text => Ok(text::render(self)), + ChurnFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), + ChurnFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), + ChurnFormat::Markdown => Ok(markdown::render(self)), + } + } + + fn named_source_sets(&self) -> impl Iterator { + self.source_sets + .iter() + .map(|(key, section)| (key.heading(), section)) + } +} + +impl SourceSetChurnSection { + fn new( + model: &CodeModel, + touches_by_file: &BTreeMap, + shown: FindingsShown, + ) -> SourceSetChurnSection { + let erosion = Erosion::measure(model); + let duplication = Duplication::measure( + model, + MinimumCloneTokens::DEFAULT, + MinimumDistinctTokens::DEFAULT, + ); + SourceSetChurnSection { + files: model.files.len(), + erosion: ErosionChurnSection::new(&erosion, touches_by_file, shown), + duplication: DuplicationChurnSection::new(&duplication, touches_by_file, shown), + } + } +} + +struct ErosionAccumulator { + eroded_functions: usize, + eroded_function_mass: f64, + max_cyclomatic_complexity: u32, +} + +impl ErosionChurnSection { + fn new( + erosion: &Erosion, + touches_by_file: &BTreeMap, + shown: FindingsShown, + ) -> ErosionChurnSection { + let mut by_file: BTreeMap<&RepoPath, ErosionAccumulator> = BTreeMap::new(); + for func in erosion.eroded_functions() { + let entry = by_file.entry(&func.path).or_insert(ErosionAccumulator { + eroded_functions: 0, + eroded_function_mass: 0.0, + max_cyclomatic_complexity: 0, + }); + entry.eroded_functions += 1; + entry.eroded_function_mass += func.function_mass; + entry.max_cyclomatic_complexity = entry + .max_cyclomatic_complexity + .max(func.cyclomatic_complexity); + } + let mut rows: Vec = by_file + .into_iter() + .map(|(path, acc)| ErodedChurnFile { + path: path.to_string(), + commits: touches_by_file.get(path).copied().unwrap_or(0), + eroded_functions: acc.eroded_functions, + eroded_function_mass: Decimal::rounded(acc.eroded_function_mass), + max_cyclomatic_complexity: acc.max_cyclomatic_complexity, + }) + .collect(); + rows.sort_by(compare_eroded_rows); + ErosionChurnSection { + ratio: Decimal::rounded(erosion.ratio()), + eroded_function_mass: Decimal::rounded(erosion.eroded_function_mass()), + total_function_mass: Decimal::rounded(erosion.total_function_mass()), + findings: Findings::worst_first(rows.into_iter(), shown), + } + } +} + +fn compare_eroded_rows(left: &ErodedChurnFile, right: &ErodedChurnFile) -> Ordering { + right + .commits + .cmp(&left.commits) + .then_with(|| { + right + .eroded_function_mass + .0 + .total_cmp(&left.eroded_function_mass.0) + }) + .then_with(|| left.path.cmp(&right.path)) +} + +struct DuplicationAccumulator { + lines: BTreeSet, + groups: BTreeSet, +} + +impl DuplicationChurnSection { + fn new( + duplication: &Duplication, + touches_by_file: &BTreeMap, + shown: FindingsShown, + ) -> DuplicationChurnSection { + let mut by_file: BTreeMap<&RepoPath, DuplicationAccumulator> = BTreeMap::new(); + for (group_index, group) in duplication.clone_groups.iter().enumerate() { + for fragment in &group.fragments { + let entry = + by_file + .entry(&fragment.path) + .or_insert_with(|| DuplicationAccumulator { + lines: BTreeSet::new(), + groups: BTreeSet::new(), + }); + entry.lines.extend(fragment.start_line..=fragment.end_line); + entry.groups.insert(group_index); + } + } + let mut rows: Vec = by_file + .into_iter() + .map(|(path, acc)| DuplicatedChurnFile { + path: path.to_string(), + commits: touches_by_file.get(path).copied().unwrap_or(0), + clone_lines: acc.lines.len() as u64, + clone_groups: acc.groups.len(), + }) + .collect(); + rows.sort_by(compare_duplicated_rows); + DuplicationChurnSection { + ratio: Decimal::rounded(duplication.ratio()), + clone_lines: duplication.clone_lines.count(), + findings: Findings::worst_first(rows.into_iter(), shown), + } + } +} + +fn compare_duplicated_rows(left: &DuplicatedChurnFile, right: &DuplicatedChurnFile) -> Ordering { + right + .commits + .cmp(&left.commits) + .then_with(|| right.clone_lines.cmp(&left.clone_lines)) + .then_with(|| left.path.cmp(&right.path)) +} diff --git a/crates/report/src/churn/markdown.rs b/crates/report/src/churn/markdown.rs new file mode 100644 index 0000000..29d1d9f --- /dev/null +++ b/crates/report/src/churn/markdown.rs @@ -0,0 +1,103 @@ +use super::{ChurnReport, DuplicationChurnSection, ErosionChurnSection}; +use crate::markdown::{code, table}; + +const TITLE: &str = "# codeint churn"; + +pub(super) fn render(report: &ChurnReport) -> String { + let mut blocks = vec![TITLE.to_owned(), summary_line(report)]; + if let Some(warning) = &report.warning { + blocks.push(format!("> Warning: {warning}")); + } + for (name, section) in report.named_source_sets() { + blocks.push(format!("## {name}")); + push_erosion_blocks(&mut blocks, §ion.erosion); + push_duplication_blocks(&mut blocks, §ion.duplication); + } + blocks.join("\n\n") +} + +fn summary_line(report: &ChurnReport) -> String { + let noun = if report.commits_analyzed == 1 { + "commit" + } else { + "commits" + }; + format!( + "codeint analyzed {} {noun} (window: `{}`).", + report.commits_analyzed, report.window + ) +} + +fn push_table_section( + blocks: &mut Vec, + heading: String, + empty_note: &str, + headers: &[&str], + rows: Vec>, +) { + blocks.push(heading); + if rows.is_empty() { + blocks.push(empty_note.to_owned()); + } else { + blocks.push(table(headers, rows)); + } +} + +fn push_erosion_blocks(blocks: &mut Vec, section: &ErosionChurnSection) { + let rows = section + .findings + .listed + .iter() + .map(|row| { + vec![ + code(&row.path), + row.commits.to_string(), + row.eroded_functions.to_string(), + row.eroded_function_mass.0.to_string(), + row.max_cyclomatic_complexity.to_string(), + ] + }) + .collect(); + push_table_section( + blocks, + format!( + "### Erosion (ratio {}, mass {}/{})", + section.ratio.0, section.eroded_function_mass.0, section.total_function_mass.0 + ), + "No eroded files.", + &[ + "File", + "Commits", + "Eroded functions", + "Eroded Function mass", + "Max CC", + ], + rows, + ); +} + +fn push_duplication_blocks(blocks: &mut Vec, section: &DuplicationChurnSection) { + let rows = section + .findings + .listed + .iter() + .map(|row| { + vec![ + code(&row.path), + row.commits.to_string(), + row.clone_lines.to_string(), + row.clone_groups.to_string(), + ] + }) + .collect(); + push_table_section( + blocks, + format!( + "### Duplication (ratio {}, {} clone lines)", + section.ratio.0, section.clone_lines + ), + "No duplicated files.", + &["File", "Commits", "Clone lines", "Clone groups"], + rows, + ); +} diff --git a/crates/report/src/churn/text.rs b/crates/report/src/churn/text.rs new file mode 100644 index 0000000..233a5ab --- /dev/null +++ b/crates/report/src/churn/text.rs @@ -0,0 +1,69 @@ +use std::fmt::Write as _; + +use super::{ChurnReport, DuplicationChurnSection, ErosionChurnSection}; + +pub(super) fn render(report: &ChurnReport) -> String { + let mut out = String::new(); + let _ = writeln!( + out, + "codeint churn (window: {}, commits analyzed: {})", + report.window, report.commits_analyzed + ); + if let Some(warning) = &report.warning { + let _ = writeln!(out, "warning: {warning}"); + } + for (name, section) in report.named_source_sets() { + let _ = writeln!(out, "\n{name} ({} files)", section.files); + write_erosion(&mut out, §ion.erosion); + write_duplication(&mut out, §ion.duplication); + } + out.trim_end_matches('\n').to_owned() +} + +fn write_erosion(out: &mut String, section: &ErosionChurnSection) { + let _ = writeln!( + out, + " Erosion (ratio {}, mass {}/{}):", + section.ratio.0, section.eroded_function_mass.0, section.total_function_mass.0 + ); + if section.findings.listed.is_empty() { + let _ = writeln!(out, " none"); + return; + } + for row in §ion.findings.listed { + let _ = writeln!( + out, + " {} commits={} eroded_functions={} mass={} max_cc={}", + row.path, + row.commits, + row.eroded_functions, + row.eroded_function_mass.0, + row.max_cyclomatic_complexity + ); + } + if section.findings.left_out > 0 { + let _ = writeln!(out, " ... {} more", section.findings.left_out); + } +} + +fn write_duplication(out: &mut String, section: &DuplicationChurnSection) { + let _ = writeln!( + out, + " Duplication (ratio {}, clone_lines {}):", + section.ratio.0, section.clone_lines + ); + if section.findings.listed.is_empty() { + let _ = writeln!(out, " none"); + return; + } + for row in §ion.findings.listed { + let _ = writeln!( + out, + " {} commits={} clone_lines={} clone_groups={}", + row.path, row.commits, row.clone_lines, row.clone_groups + ); + } + if section.findings.left_out > 0 { + let _ = writeln!(out, " ... {} more", section.findings.left_out); + } +} diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index ec6083c..71a95f4 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -18,6 +18,7 @@ use codeint_model::{ use serde::ser::SerializeMap; use serde::{Deserialize, Serialize, Serializer}; +mod churn; mod diff; mod guard; mod markdown; @@ -27,6 +28,7 @@ mod sarif; mod tests; mod trend; +pub use churn::{ChurnHistoryInput, ChurnReport}; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use measurement::CommitMeasurement; diff --git a/docs/reference.md b/docs/reference.md index 92e93a0..ce89aa8 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -28,8 +28,9 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `trend` | Measure each commit of the main line and print each Metric over time; see [`codeint trend`](#codeint-trend) | | `init` | Write a starter `codeint.json`; see [`codeint init`](#codeint-init) | | `update` | Update a standalone codeint binary in place from GitHub Releases; see [`codeint update`](#codeint-update) | -| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, and `guard` tools; see [`codeint mcp`](#codeint-mcp) | +| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, `guard`, and `churn` tools; see [`codeint mcp`](#codeint-mcp) | | `guard` | Show the architectural boundary zone, allowed and denied target zones, `public_files` constraints, and allowed importers for a file path; see [`codeint guard`](#codeint-guard) | +| `churn` | Rank eroded and duplicated files alongside their Git commit churn independently per Metric; see [`codeint churn`](#codeint-churn) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -487,7 +488,7 @@ codeint 0.5.0 is already up to date (v0.5.0) | `-h, --help` | Print the help of `codeint mcp` | `codeint mcp` runs a local Model Context Protocol (MCP) server over standard input and standard output with no open network port. -It exposes four read-only tools (`check`, `diff`, `trend`, and `guard`) so coding agents can measure Software entropy, inspect architectural boundaries, and fix Regressions before opening a pull request. +It exposes five read-only tools (`check`, `diff`, `trend`, `guard`, and `churn`) so coding agents can measure Software entropy, inspect architectural boundaries, rank high-churn eroded or duplicated files, and fix Regressions before opening a pull request. When standard input closes, the server exits with code 0: ```sh exit=0 @@ -514,6 +515,28 @@ codeint guard src/route.ts --format toon codeint guard src/route.ts --format json ``` +### `codeint churn` + +| Option | Meaning | +| ------ | ------- | +| `--since ` | Lookback window in days (such as `90d`) or a UTC date (`YYYY-MM-DD`); defaults to `90d` | +| `--commits ` | Walk at most this many main-line commits from HEAD | +| `--output ` | Write the report to this file instead of standard output | +| `--all` | List every Finding instead of the 20 worst per Metric | +| `--format ` | The format of the report: `toon`, the default, `text`, `json`, or `markdown` | +| `-h, --help` | Print the help of `codeint churn` | + +`codeint churn` walks main-line Git history natively via `gix` to count per-file commit touches over the configured window, then ranks eroded and duplicated files independently per Metric without any blended score. +In a shallow clone, `codeint churn` stops at the shallow boundary and includes a structured warning in the report. + +```sh exit=0 +codeint churn +codeint churn --since 90d --format text +codeint churn --commits 10 --all --format toon +codeint churn --format json --output churn.json +codeint churn --format markdown +``` + ## Exit codes | Exit code | Meaning | From 36b449d585d2261dab925ea9a5931b6482c839ad Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:29:16 +0800 Subject: [PATCH 2/4] feat(report): add CODEOWNERS parsing, owner attribution, and --owner filtering Parse standard CODEOWNERS files (.github/CODEOWNERS, CODEOWNERS, docs/CODEOWNERS) with last-match-wins semantics, attach matched owners to report Findings when present while remaining silent when absent, and support --owner filtering in codeint check and codeint diff. Closes #184 --- crates/cli/src/check.rs | 71 +++++-- crates/cli/src/diff.rs | 37 ++-- crates/cli/src/lib.rs | 29 ++- crates/cli/src/mcp.rs | 2 + crates/cli/src/remedy.rs | 10 +- crates/cli/tests/codeowners.rs | 213 +++++++++++++++++++ crates/config/src/codeowners.rs | 190 +++++++++++++++++ crates/config/src/codeowners/tests.rs | 153 ++++++++++++++ crates/config/src/lib.rs | 12 ++ crates/report/src/diff.rs | 65 ++++-- crates/report/src/diff/markdown.rs | 28 +-- crates/report/src/lib.rs | 283 +++++++++++++++++--------- crates/report/src/markdown.rs | 87 +++++--- crates/report/src/ownership.rs | 26 +++ crates/report/src/sarif/tests.rs | 4 + docs/reference.md | 9 + 16 files changed, 1025 insertions(+), 194 deletions(-) create mode 100644 crates/cli/tests/codeowners.rs create mode 100644 crates/config/src/codeowners.rs create mode 100644 crates/config/src/codeowners/tests.rs create mode 100644 crates/report/src/ownership.rs diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index f678623..67f067a 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -3,8 +3,8 @@ use std::path::Path; use std::string::FromUtf8Error; use codeint_config::{ - Configuration, ConfigurationFileError, FindingsShown, LanguageCoverage, PluginHostConfig, - SourceSetOverrides, read_configuration, + Codeowners, CodeownersError, Configuration, ConfigurationFileError, FindingsShown, + LanguageCoverage, OwnerFilter, PluginHostConfig, SourceSetOverrides, read_configuration, }; use codeint_git::{GitError, Repository, Snapshot}; use codeint_lang_dart::Dart; @@ -21,7 +21,7 @@ use codeint_plugin_host::{ PluginHostError, WasmLanguagePlugin, WasmMetricPlugin, load_language_plugins_with_limits, load_metric_plugins_with_limits, }; -use codeint_report::{MeasuredLanguage, Report}; +use codeint_report::{MeasuredLanguage, OwnershipOptions, Report}; use rayon::prelude::{IntoParallelIterator, IntoParallelRefIterator, ParallelIterator}; #[cfg(test)] @@ -33,6 +33,8 @@ pub(crate) enum CheckError { Git(#[from] GitError), #[error(transparent)] Configuration(#[from] ConfigurationFileError), + #[error(transparent)] + Codeowners(#[from] CodeownersError), #[error("cannot resolve runtime imports")] Resolve(#[source] ResolveError), #[error("a Language plugin supplies an invalid Reference range")] @@ -162,22 +164,58 @@ impl LoadedPlugins { } } +pub(crate) struct PreparedRun { + pub(crate) repository: Repository, + pub(crate) configuration: Configuration, + pub(crate) loaded: LoadedPlugins, + pub(crate) codeowners: Option, + pub(crate) owner_filter: Option, +} + +impl PreparedRun { + pub(crate) fn load( + folder: &Path, + owner_pattern: Option<&str>, + plugin_host: &PluginHostConfig, + ) -> Result { + let repository = Repository::discover(folder)?; + let configuration = read_configuration(repository.root())?; + let codeowners = Codeowners::load(repository.root())?; + let owner_filter = owner_pattern.map(OwnerFilter::new).transpose()?; + let loaded = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; + Ok(PreparedRun { + repository, + configuration, + loaded, + codeowners, + owner_filter, + }) + } + + pub(crate) fn ownership(&self) -> OwnershipOptions<'_> { + OwnershipOptions { + codeowners: self.codeowners.as_ref(), + owner_filter: self.owner_filter.as_ref(), + } + } +} + pub(crate) fn check( folder: &Path, findings: FindingsShown, + owner: Option<&str>, plugin_host: &PluginHostConfig, ) -> Result { - let repository = Repository::discover(folder)?; - let configuration = read_configuration(repository.root())?; - let loaded = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; - let plugins = loaded.as_named(); - let metric_plugins = loaded.metric_plugins(); + let run = PreparedRun::load(folder, owner, plugin_host)?; + let plugins = run.loaded.as_named(); + let metric_plugins = run.loaded.metric_plugins(); check_loaded( - &repository, - &configuration, + &run.repository, + &run.configuration, &plugins, &metric_plugins, findings, + run.ownership(), ) } @@ -190,7 +228,14 @@ fn check_with( let repository = Repository::discover(folder)?; let configuration = read_configuration(repository.root())?; configuration.validate_metrics(&[])?; - check_loaded(&repository, &configuration, plugins, &[], findings) + check_loaded( + &repository, + &configuration, + plugins, + &[], + findings, + OwnershipOptions::default(), + ) } fn check_loaded( @@ -199,16 +244,18 @@ fn check_loaded( plugins: &[NamedLanguagePlugin<'_>], metric_plugins: &[&dyn MetricPlugin], findings: FindingsShown, + ownership: OwnershipOptions<'_>, ) -> Result { let tree = repository.working_tree()?; let languages = measure_with(&tree, plugins, configuration)?; - Ok(Report::summarize_with_metrics_and_boundaries( + Ok(Report::summarize_with_ownership( languages, tree.submodules().to_vec(), findings, &configuration.budgets, metric_plugins, configuration.boundaries.as_ref(), + ownership, )?) } diff --git a/crates/cli/src/diff.rs b/crates/cli/src/diff.rs index 7edaca9..626c91b 100644 --- a/crates/cli/src/diff.rs +++ b/crates/cli/src/diff.rs @@ -1,10 +1,10 @@ use std::path::Path; -use codeint_config::{FindingsShown, PluginHostConfig, read_configuration}; +use codeint_config::{FindingsShown, PluginHostConfig}; use codeint_git::{CommitId, GitError, Repository, ResultCache}; -use codeint_report::{BaseCommit, DiffReport, Head, HeadCommit}; +use codeint_report::{BaseCommit, DiffReport, DiffReportOptions, Head, HeadCommit}; -use crate::check::{CheckError, LoadedPlugins}; +use crate::check::{CheckError, PreparedRun}; use crate::commit_measurement::{CommitMeasurer, measure_all_languages}; pub(crate) struct Refs<'a> { @@ -22,24 +22,32 @@ pub(crate) fn diff( folder: &Path, refs: Refs<'_>, findings: FindingsShown, + owner: Option<&str>, result_cache: Option<&ResultCache>, plugin_host: &PluginHostConfig, ) -> Result { - let repository = Repository::discover(folder)?; - let configuration = read_configuration(repository.root())?; - let plugins = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; + let run = PreparedRun::load(folder, owner, plugin_host)?; let Sides { merge_base, head, head_commit, - } = sides(&repository, &refs)?; - let measurer = CommitMeasurer::new(&repository, &configuration, &plugins, result_cache); + } = sides(&run.repository, &refs)?; + let measurer = CommitMeasurer::new( + &run.repository, + &run.configuration, + &run.loaded, + result_cache, + ); let base_measurement = measurer.measure(merge_base)?; let head_measurement = match head_commit { Some(commit) => measurer.measure(commit)?, - None => measure_all_languages(&repository.working_tree()?, &plugins, &configuration)?, + None => measure_all_languages( + &run.repository.working_tree()?, + &run.loaded, + &run.configuration, + )?, }; - Ok(DiffReport::compare( + Ok(DiffReport::compare_with_options( BaseCommit { git_ref: refs.base.to_owned(), merge_base: merge_base.to_string(), @@ -47,9 +55,12 @@ pub(crate) fn diff( head, base_measurement, head_measurement, - findings, - &configuration.budgets, - &configuration.regression_limits, + DiffReportOptions { + findings, + budgets: &run.configuration.budgets, + limits: &run.configuration.regression_limits, + ownership: run.ownership(), + }, )) } diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index c3c9d6d..6c93aa4 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -32,12 +32,14 @@ const DEFAULT_TREND_COMMITS: usize = 20; #[derive(Debug, Clone, PartialEq, Eq)] pub struct CheckOptions { pub findings: FindingsShown, + pub owner: Option, pub plugin_host: PluginHostConfig, } impl Default for CheckOptions { fn default() -> CheckOptions { CheckOptions { + owner: None, findings: FindingsShown::WorstPerMetric(DEFAULT_WORST_FINDINGS), plugin_host: PluginHostConfig::default(), } @@ -48,6 +50,7 @@ impl Default for CheckOptions { pub struct DiffOptions { pub head_ref: Option, pub findings: FindingsShown, + pub owner: Option, pub result_cache: Option, pub plugin_host: PluginHostConfig, } @@ -57,6 +60,7 @@ impl Default for DiffOptions { DiffOptions { head_ref: None, findings: FindingsShown::WorstPerMetric(DEFAULT_WORST_FINDINGS), + owner: None, result_cache: None, plugin_host: PluginHostConfig::default(), } @@ -124,8 +128,13 @@ impl fmt::Display for CodeintError { impl Error for CodeintError {} pub fn check(folder: &Path, options: &CheckOptions) -> Result { - let report = check::check(folder, options.findings, &options.plugin_host) - .map_err(|err| CodeintError::from_cli_error(CliError::Check(err)))?; + let report = check::check( + folder, + options.findings, + options.owner.as_deref(), + &options.plugin_host, + ) + .map_err(|err| CodeintError::from_cli_error(CliError::Check(err)))?; let failures: Vec = report .over_budget() .iter() @@ -169,6 +178,7 @@ fn measure_diff( folder, refs, options.findings, + options.owner.as_deref(), cache.as_ref(), &options.plugin_host, ) @@ -253,8 +263,16 @@ fn run() -> Result { destination, findings, format, + owner, plugin_host, - } => run_check(&folder, &destination, findings, format, &plugin_host), + } => run_check( + &folder, + &destination, + findings, + format, + owner.as_deref(), + &plugin_host, + ), Command::Diff { folder, base_ref, @@ -262,12 +280,14 @@ fn run() -> Result { destination, findings, format, + owner, result_cache, plugin_host, } => { let options = DiffOptions { head_ref, findings, + owner, result_cache, plugin_host, }; @@ -343,9 +363,10 @@ fn run_check( destination: &ReportDestination, findings: FindingsShown, format: ReportFormat, + owner: Option<&str>, plugin_host: &PluginHostConfig, ) -> Result { - let report = check::check(folder, findings, plugin_host)?; + let report = check::check(folder, findings, owner, plugin_host)?; write_report(&report.render(format)?, destination)?; Ok(Outcome::from_failures( report diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 55e02b3..6b385d0 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -197,6 +197,7 @@ fn call_check(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { let folder = resolve_folder(args, ctx.default_folder); let options = CheckOptions { findings: parse_findings(args), + owner: None, plugin_host: ctx.plugin_host.clone(), }; match check(&folder, &options) { @@ -221,6 +222,7 @@ fn call_diff(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { .and_then(Value::as_str) .map(str::to_owned), findings: parse_findings(args), + owner: None, result_cache: ctx.result_cache.clone(), plugin_host: ctx.plugin_host.clone(), }; diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 9747e89..caccec6 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -1,4 +1,6 @@ -use codeint_config::{ConfigError, ConfigurationFileError, StarterConfigurationError}; +use codeint_config::{ + CodeownersError, ConfigError, ConfigurationFileError, StarterConfigurationError, +}; use codeint_git::GitError; use codeint_model::{MetricPluginError, WorkspaceError}; use codeint_plugin_host::PluginHostError; @@ -30,6 +32,12 @@ fn check_remedy(error: &CheckError) -> &'static str { match error { CheckError::Git(error) => git_remedy(error), CheckError::Configuration(error) => configuration_file_remedy(error), + CheckError::Codeowners(CodeownersError::Read { .. }) => { + "Check that the CODEOWNERS file is readable UTF-8, then run codeint again." + } + CheckError::Codeowners(CodeownersError::InvalidOwnerPattern { .. }) => { + "Pass a valid glob pattern to --owner, such as @org/team or @org/*." + } CheckError::Workspace(error) => workspace_remedy(error), CheckError::Resolve(_) => { "This is a defect in the Language plugin; report it to the author of the Language plugin." diff --git a/crates/cli/tests/codeowners.rs b/crates/cli/tests/codeowners.rs new file mode 100644 index 0000000..4e68552 --- /dev/null +++ b/crates/cli/tests/codeowners.rs @@ -0,0 +1,213 @@ +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +use serde_json::Value; +use tempfile::TempDir; + +fn init_fixture(files: &[(&str, &str)]) -> TempDir { + let dir = tempfile::tempdir().expect("create temporary folder"); + run_git(dir.path(), &["init", "--quiet", "--initial-branch", "main"]); + for (relative, text) in files { + write_fixture(dir.path(), relative, text); + } + dir +} + +fn write_fixture(root: &Path, relative: &str, text: &str) { + let full = root.join(relative); + if let Some(parent) = full.parent() { + fs::create_dir_all(parent).expect("create parent folder"); + } + fs::write(full, text).expect("write file"); +} + +fn run_git(root: &Path, args: &[&str]) { + let status = Command::new("git") + .args(args) + .current_dir(root) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_AUTHOR_NAME", "Fixture") + .env("GIT_AUTHOR_EMAIL", "fixture@example.invalid") + .env("GIT_COMMITTER_NAME", "Fixture") + .env("GIT_COMMITTER_EMAIL", "fixture@example.invalid") + .status() + .expect("run git"); + assert!(status.success(), "git {args:?} exited with {status}"); +} + +fn run_cli(root: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .args(args) + .current_dir(root) + .env("RUST_BACKTRACE", "1") + .output() + .expect("run codeint") +} + +fn eroded_ts(name: &str) -> String { + let branches: String = (1..=12) + .map(|value| format!(" if (value === {value}) return {value};\n")) + .collect(); + format!("export function {name}(value: number): number {{\n{branches} return 0;\n}}\n") +} + +fn run_json(root: &Path, args: &[&str], expected_exit: i32) -> Value { + let output = run_cli(root, args); + assert_eq!( + output.status.code(), + Some(expected_exit), + "codeint {args:?} stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("parse JSON stdout") +} + +fn erosion_paths(value: &Value, key: &str) -> Vec { + value["source_sets"]["production"]["erosion"][key] + .as_array() + .expect("erosion findings array") + .iter() + .map(|item| item["path"].as_str().expect("path string").to_owned()) + .collect() +} + +#[test] +fn check_is_silent_when_no_codeowners_file_exists() { + let dir = init_fixture(&[("src/backend.ts", &eroded_ts("compute"))]); + for (format, forbidden) in [ + ("json", "\"owners\""), + ("toon", "owners"), + ("markdown", "Owners"), + ] { + let output = run_cli(dir.path(), &["check", "--format", format]); + assert_eq!(output.status.code(), Some(0)); + let text = String::from_utf8(output.stdout).expect("UTF-8 stdout"); + assert!( + !text.contains(forbidden), + "unexpected {forbidden} in {format}: {text}" + ); + } +} + +#[test] +fn check_attaches_owners_in_json_toon_and_markdown_with_precedence() { + let dir = init_fixture(&[ + ("src/backend.ts", &eroded_ts("computeBackend")), + ("src/frontend.ts", &eroded_ts("renderFrontend")), + ("CODEOWNERS", "* @fallback-team\n"), + ( + ".github/CODEOWNERS", + "* @org/platform\nsrc/backend.ts @org/backend @alice\nsrc/frontend.ts @org/frontend\n", + ), + ]); + + let value = run_json(dir.path(), &["check", "--format", "json"], 0); + let findings = value["source_sets"]["production"]["erosion"]["findings"] + .as_array() + .expect("erosion findings array"); + assert_eq!(findings.len(), 2); + let backend = findings + .iter() + .find(|f| f["path"] == "src/backend.ts") + .expect("backend finding"); + assert_eq!( + backend["owners"], + serde_json::json!(["@org/backend", "@alice"]) + ); + let frontend = findings + .iter() + .find(|f| f["path"] == "src/frontend.ts") + .expect("frontend finding"); + assert_eq!(frontend["owners"], serde_json::json!(["@org/frontend"])); + + for (format, required) in [ + ("toon", &["@org/backend", "@org/frontend"][..]), + ( + "markdown", + &["| Owners |", "@org/backend", "@org/frontend"][..], + ), + ] { + let output = run_cli(dir.path(), &["check", "--format", format]); + assert_eq!(output.status.code(), Some(0)); + let text = String::from_utf8(output.stdout).expect("UTF-8 stdout"); + for needle in required { + assert!(text.contains(needle), "{format} missing {needle}: {text}"); + } + } +} + +#[test] +fn check_owner_flag_filters_findings() { + let dir = init_fixture(&[ + ("src/backend.ts", &eroded_ts("computeBackend")), + ("src/frontend.ts", &eroded_ts("renderFrontend")), + ( + ".github/CODEOWNERS", + "src/backend.ts @org/backend\nsrc/frontend.ts @org/frontend\n", + ), + ]); + + let exact = run_json( + dir.path(), + &["check", "--format", "json", "--owner", "@org/backend"], + 0, + ); + assert_eq!(erosion_paths(&exact, "findings"), vec!["src/backend.ts"]); + + let wildcard = run_json( + dir.path(), + &["check", "--format", "json", "--owner", "@org/front*"], + 0, + ); + assert_eq!( + erosion_paths(&wildcard, "findings"), + vec!["src/frontend.ts"] + ); +} + +#[test] +fn diff_attaches_owners_and_filters_with_owner_flag() { + let dir = init_fixture(&[ + ( + "src/clean.ts", + "export function ok(): number { return 1; }\n", + ), + ( + "CODEOWNERS", + "src/backend.ts @org/backend\nsrc/frontend.ts @org/frontend\n", + ), + ]); + run_git(dir.path(), &["add", "--all"]); + run_git(dir.path(), &["commit", "--quiet", "--message", "base"]); + + write_fixture(dir.path(), "src/backend.ts", &eroded_ts("computeBackend")); + write_fixture(dir.path(), "src/frontend.ts", &eroded_ts("renderFrontend")); + + let diff_all = run_json(dir.path(), &["diff", "main", "--format", "json"], 1); + let new_all = diff_all["source_sets"]["production"]["erosion"]["new"] + .as_array() + .expect("new findings array"); + assert_eq!(new_all.len(), 2); + assert!(new_all.iter().any(|f| { + f["path"] == "src/backend.ts" && f["owners"] == serde_json::json!(["@org/backend"]) + })); + assert!(new_all.iter().any(|f| { + f["path"] == "src/frontend.ts" && f["owners"] == serde_json::json!(["@org/frontend"]) + })); + + let diff_filtered = run_json( + dir.path(), + &[ + "diff", + "main", + "--format", + "json", + "--owner", + "@org/backend", + ], + 1, + ); + assert_eq!(erosion_paths(&diff_filtered, "new"), vec!["src/backend.ts"]); +} diff --git a/crates/config/src/codeowners.rs b/crates/config/src/codeowners.rs new file mode 100644 index 0000000..f2fa622 --- /dev/null +++ b/crates/config/src/codeowners.rs @@ -0,0 +1,190 @@ +use std::path::{Path, PathBuf}; + +use globset::{GlobBuilder, GlobMatcher}; + +#[cfg(test)] +mod tests; + +#[derive(Debug, thiserror::Error)] +pub enum CodeownersError { + #[error("cannot read {}", path.display())] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("invalid owner filter pattern {pattern:?}")] + InvalidOwnerPattern { + pattern: String, + #[source] + source: globset::Error, + }, +} + +#[derive(Debug, Clone, Default)] +pub struct Codeowners { + rules: Vec, +} + +#[derive(Debug, Clone)] +struct Rule { + matchers: Vec, + owners: Vec, +} + +impl Codeowners { + pub const STANDARD_PATHS: [&'static str; 3] = + [".github/CODEOWNERS", "CODEOWNERS", "docs/CODEOWNERS"]; + + pub fn load(repository_root: &Path) -> Result, CodeownersError> { + for relative in Self::STANDARD_PATHS { + let path = repository_root.join(relative); + if path.is_file() { + let text = std::fs::read_to_string(&path) + .map_err(|source| CodeownersError::Read { path, source })?; + return Ok(Some(Codeowners::parse(&text))); + } + } + Ok(None) + } + + pub fn parse(text: &str) -> Codeowners { + let rules = text.lines().filter_map(parse_rule).collect(); + Codeowners { rules } + } + + pub fn owners_for(&self, path: &str) -> Vec { + let normalized = path.trim_start_matches('/'); + self.rules + .iter() + .rev() + .find(|rule| rule.matches(normalized)) + .map(|rule| rule.owners.clone()) + .unwrap_or_default() + } + + pub fn owners_for_many<'a>(&self, paths: impl IntoIterator) -> Vec { + let mut combined = Vec::new(); + for path in paths { + for owner in self.owners_for(path) { + if !combined.contains(&owner) { + combined.push(owner); + } + } + } + combined + } +} + +impl Rule { + fn matches(&self, path: &str) -> bool { + self.matchers.iter().any(|matcher| matcher.is_match(path)) + } +} + +#[derive(Debug, Clone)] +pub struct OwnerFilter { + matcher: GlobMatcher, +} + +impl OwnerFilter { + pub fn new(pattern: &str) -> Result { + let matcher = GlobBuilder::new(pattern) + .case_insensitive(true) + .build() + .map_err(|source| CodeownersError::InvalidOwnerPattern { + pattern: pattern.to_owned(), + source, + })? + .compile_matcher(); + Ok(OwnerFilter { matcher }) + } + + pub fn matches(&self, owner: &str) -> bool { + self.matcher.is_match(owner) + } + + pub fn matches_any(&self, owners: &[String]) -> bool { + owners.iter().any(|owner| self.matches(owner)) + } +} + +fn parse_rule(line: &str) -> Option { + let trimmed = line.trim(); + if trimmed.is_empty() || trimmed.starts_with('#') { + return None; + } + let (pattern, rest) = take_pattern(trimmed); + if pattern.is_empty() { + return None; + } + let matchers = compile_pattern(&pattern)?; + let owners = parse_owners(rest); + Some(Rule { matchers, owners }) +} + +fn take_pattern(line: &str) -> (String, &str) { + let mut pattern = String::new(); + let mut chars = line.char_indices().peekable(); + while let Some((index, ch)) = chars.next() { + if ch == '\\' { + if let Some(&(_, next)) = chars.peek() { + pattern.push(next); + chars.next(); + } + continue; + } + if ch.is_whitespace() { + return (pattern, &line[index..]); + } + pattern.push(ch); + } + (pattern, "") +} + +fn parse_owners(rest: &str) -> Vec { + rest.split_whitespace() + .take_while(|token| !token.starts_with('#')) + .map(str::to_owned) + .collect() +} + +fn compile_pattern(pattern: &str) -> Option> { + let (has_leading_slash, without_leading) = match pattern.strip_prefix('/') { + Some(rest) => (true, rest), + None => (false, pattern), + }; + let (has_trailing_slash, core) = match without_leading.strip_suffix('/') { + Some(rest) => (true, rest), + None => (false, without_leading), + }; + if core.is_empty() { + return None; + } + let anchored = has_leading_slash || core.contains('/'); + let prefix = if anchored { "" } else { "**/" }; + let mut patterns = Vec::new(); + if has_trailing_slash { + patterns.push(format!("{prefix}{core}/**")); + } else { + patterns.push(format!("{prefix}{core}")); + if !last_segment_has_wildcard(core) { + patterns.push(format!("{prefix}{core}/**")); + } + } + let mut matchers = Vec::with_capacity(patterns.len()); + for glob in patterns { + let matcher = GlobBuilder::new(&glob) + .literal_separator(true) + .build() + .ok()? + .compile_matcher(); + matchers.push(matcher); + } + Some(matchers) +} + +fn last_segment_has_wildcard(pattern: &str) -> bool { + let last = pattern.rsplit('/').next().unwrap_or(pattern); + last.contains('*') || last.contains('?') || last.contains('[') +} diff --git a/crates/config/src/codeowners/tests.rs b/crates/config/src/codeowners/tests.rs new file mode 100644 index 0000000..7a60a60 --- /dev/null +++ b/crates/config/src/codeowners/tests.rs @@ -0,0 +1,153 @@ +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use super::{Codeowners, OwnerFilter}; + +struct TempFolder(PathBuf); + +impl TempFolder { + fn new(name: &str) -> TempFolder { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let id = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "codeint-codeowners-{name}-{}-{id}", + std::process::id() + )); + let _ = fs::remove_dir_all(&path); + fs::create_dir_all(&path).expect("create temp folder"); + TempFolder(path) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn assert_owners_table(rules: &str, cases: &[(&str, &[&str])]) { + let codeowners = Codeowners::parse(rules); + for (path, expected) in cases { + let expected: Vec = expected.iter().map(|s| (*s).to_owned()).collect(); + assert_eq!(codeowners.owners_for(path), expected, "path: {path}"); + } +} + +#[test] +fn load_returns_none_when_no_codeowners_file_exists() { + let dir = TempFolder::new("none"); + let loaded = Codeowners::load(dir.path()).expect("load succeeds"); + assert!(loaded.is_none()); +} + +#[test] +fn load_prefers_github_over_root_over_docs() { + let dir = TempFolder::new("precedence"); + fs::create_dir_all(dir.path().join("docs")).expect("create docs"); + fs::create_dir_all(dir.path().join(".github")).expect("create .github"); + for (file, team) in [ + ("docs/CODEOWNERS", "@docs-team"), + ("CODEOWNERS", "@root-team"), + (".github/CODEOWNERS", "@github-team"), + ] { + fs::write(dir.path().join(file), format!("* {team}\n")).expect("write CODEOWNERS"); + let loaded = Codeowners::load(dir.path()) + .expect("load codeowners") + .expect("found codeowners"); + assert_eq!(loaded.owners_for("src/a.ts"), vec![team]); + } +} + +#[test] +fn last_matching_pattern_wins_and_empty_owners_clears_ownership() { + assert_owners_table( + "\ +# Global default +* @global-owner1 @global-owner2 +*.js @js-owner +src/special.js @special-owner +src/unowned.js +", + &[ + ("README.md", &["@global-owner1", "@global-owner2"]), + ("src/app.js", &["@js-owner"]), + ("src/special.js", &["@special-owner"]), + ("src/unowned.js", &[]), + ], + ); +} + +#[test] +fn anchored_paths_match_only_from_repository_root() { + assert_owners_table( + "\ +/build/logs/ @logs-team +/root-only.ts @root-owner +docs/guide.md @docs-owner +", + &[ + ("build/logs/app.log", &["@logs-team"]), + ("build/logs/nested/app.log", &["@logs-team"]), + ("sub/build/logs/app.log", &[]), + ("root-only.ts", &["@root-owner"]), + ("src/root-only.ts", &[]), + ("docs/guide.md", &["@docs-owner"]), + ("pkg/docs/guide.md", &[]), + ], + ); +} + +#[test] +fn directory_and_wildcard_patterns_follow_codeowners_rules() { + assert_owners_table( + "\ +docs/* @docs-shallow +apps/ @apps-team +**/logs/** @logs-deep +src/**/test/*.ts @test-team +", + &[ + ("docs/a.md", &["@docs-shallow"]), + ("docs/sub/b.md", &[]), + ("apps/web/a.ts", &["@apps-team"]), + ("pkg/apps/web/a.ts", &["@apps-team"]), + ("logs/a.txt", &["@logs-deep"]), + ("a/b/logs/c/d.txt", &["@logs-deep"]), + ("src/test/a.ts", &["@test-team"]), + ("src/pkg/mod/test/a.ts", &["@test-team"]), + ], + ); +} + +#[test] +fn inline_comments_and_escaped_spaces_are_parsed() { + assert_owners_table( + "\ +src/my\\ file.ts @space-owner # trailing comment +*.ts @ts-owner # another comment +", + &[("src/my file.ts", &["@ts-owner"])], + ); + assert_owners_table( + "src/my\\ file.ts @space-owner # trailing comment\n", + &[("src/my file.ts", &["@space-owner"])], + ); +} + +#[test] +fn owner_filter_matches_case_insensitively_and_supports_wildcards() { + let exact = OwnerFilter::new("@Org/Backend").expect("exact filter"); + assert!(exact.matches("@org/backend")); + assert!(exact.matches("@ORG/BACKEND")); + assert!(!exact.matches("@org/frontend")); + + let glob = OwnerFilter::new("@org/*-core").expect("glob filter"); + assert!(glob.matches("@org/api-core")); + assert!(glob.matches("@ORG/UI-CORE")); + assert!(!glob.matches("@other/api-core")); +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 642a0b3..4091208 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -7,6 +7,7 @@ use clap::{Parser, Subcommand}; mod boundaries; mod calendar_day; mod codeint_json; +mod codeowners; mod config_error; mod regression_limits; mod result_cache_folder; @@ -21,6 +22,7 @@ pub use codeint_json::{ StarterConfigurationError, configuration_schema, published_schema_address, read_configuration, write_starter_configuration, }; +pub use codeowners::{Codeowners, CodeownersError, OwnerFilter}; pub use config_error::{ConfigurationFileError, JsonType, KeyPath, KeySegment}; pub use regression_limits::{NewFindingsRule, RatioRise, RegressionLimit, RegressionLimits}; @@ -120,6 +122,7 @@ pub enum Command { destination: ReportDestination, findings: FindingsShown, format: ReportFormat, + owner: Option, plugin_host: PluginHostConfig, }, Diff { @@ -129,6 +132,7 @@ pub enum Command { destination: ReportDestination, findings: FindingsShown, format: ReportFormat, + owner: Option, result_cache: Option, plugin_host: PluginHostConfig, }, @@ -287,6 +291,12 @@ struct ReportArguments { help = "The format of the report" )] format: ReportFormat, + #[arg( + long, + value_name = "OWNER", + help = "Include only Findings whose CODEOWNERS owner matches this pattern" + )] + owner: Option, } pub fn read_invocation() -> Result { @@ -360,6 +370,7 @@ fn build_check_command( destination: report_destination(current_folder, report.output)?, findings: findings_shown(report.all), format: report.format, + owner: report.owner, plugin_host: plugin_host_config_of_this_process(current_folder), }) } @@ -377,6 +388,7 @@ fn build_diff_command( destination: report_destination(current_folder, report.output)?, findings: findings_shown(report.all), format: report.format, + owner: report.owner, result_cache: result_cache_folder_of_this_process(current_folder), plugin_host: plugin_host_config_of_this_process(current_folder), }) diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index cf82cf1..95a13ab 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -9,6 +9,7 @@ use serde::ser::SerializeMap; use serde::{Serialize, Serializer}; use crate::measurement::{CommitMeasurement, MetricMeasurement, SourceSetMeasurement}; +use crate::ownership::{OwnedFinding, OwnershipOptions}; use crate::sarif::{ListedExternalMetric, ListedFindings, SarifLog}; use crate::{ BoundaryFindingRow, BudgetFailure, CloneGroupFinding, Decimal, ErodedFunctionFinding, @@ -135,6 +136,13 @@ trait Identified { fn id(&self) -> &str; } +pub struct DiffReportOptions<'a> { + pub findings: FindingsShown, + pub budgets: &'a Budgets, + pub limits: &'a RegressionLimits, + pub ownership: OwnershipOptions<'a>, +} + impl DiffReport { pub fn compare( base: BaseCommit, @@ -144,13 +152,39 @@ impl DiffReport { findings: FindingsShown, budgets: &Budgets, limits: &RegressionLimits, + ) -> DiffReport { + DiffReport::compare_with_options( + base, + head, + base_measurement, + head_measurement, + DiffReportOptions { + findings, + budgets, + limits, + ownership: OwnershipOptions::default(), + }, + ) + } + + pub fn compare_with_options( + base: BaseCommit, + head: Head, + base_measurement: CommitMeasurement, + head_measurement: CommitMeasurement, + options: DiffReportOptions<'_>, ) -> DiffReport { let mut source_sets = SourceSetChangesSections::default(); let base_sets = base_measurement.into_source_sets(); let head_sets = head_measurement.into_source_sets(); for ((source_set, base), (_, head)) in base_sets.into_iter().zip(head_sets) { if base.files > 0 || head.files > 0 { - *source_sets.slot(source_set) = Some(source_set_changes(base, head, findings)); + *source_sets.slot(source_set) = Some(source_set_changes( + base, + head, + options.findings, + options.ownership, + )); } } DiffReport { @@ -159,8 +193,8 @@ impl DiffReport { merge_base: base.merge_base, }, head: head_entry(head), - over_budget: over_budget(&source_sets, budgets), - regressions: regressions(&source_sets, limits), + over_budget: over_budget(&source_sets, options.budgets), + regressions: regressions(&source_sets, options.limits), source_sets, } } @@ -239,21 +273,24 @@ impl Serialize for MetricChanges { } } -fn classify( +fn classify( base: MetricMeasurement, head: MetricMeasurement, shown: FindingsShown, + ownership: OwnershipOptions<'_>, ) -> MetricChanges { - let base_ids = ids(&base.findings_worst_first); - let head_ids = ids(&head.findings_worst_first); + let base_findings = ownership.apply(base.findings_worst_first); + let head_findings = ownership.apply(head.findings_worst_first); + let base_ids = ids(&base_findings); + let head_ids = ids(&head_findings); MetricChanges { base_ratio: Decimal::rounded(base.ratio), head_ratio: Decimal::rounded(head.ratio), base_numerator: Decimal::rounded(base.numerator), head_numerator: Decimal::rounded(head.numerator), unchanged: head_ids.intersection(&base_ids).count(), - new: missing_from(head.findings_worst_first, &base_ids, shown), - resolved: missing_from(base.findings_worst_first, &head_ids, shown), + new: missing_from(head_findings, &base_ids, shown), + resolved: missing_from(base_findings, &head_ids, shown), } } @@ -494,6 +531,7 @@ fn source_set_changes( mut base: SourceSetMeasurement, mut head: SourceSetMeasurement, shown: FindingsShown, + ownership: OwnershipOptions<'_>, ) -> SourceSetChanges { let keys: BTreeSet = base .external_metrics @@ -520,7 +558,7 @@ fn source_set_changes( ExternalMetricChanges { name, description, - changes: classify(base_measurement, head_measurement, shown), + changes: classify(base_measurement, head_measurement, shown, ownership), }, ); } @@ -530,13 +568,14 @@ fn source_set_changes( base_boundaries.unwrap_or_default(), head_boundaries.unwrap_or_default(), shown, + ownership, )), }; SourceSetChanges { - erosion: classify(base.erosion, head.erosion, shown), - duplication: classify(base.duplication, head.duplication, shown), - verbosity: classify(base.verbosity, head.verbosity, shown), - import_cycles: classify(base.import_cycles, head.import_cycles, shown), + erosion: classify(base.erosion, head.erosion, shown, ownership), + duplication: classify(base.duplication, head.duplication, shown, ownership), + verbosity: classify(base.verbosity, head.verbosity, shown, ownership), + import_cycles: classify(base.import_cycles, head.import_cycles, shown, ownership), boundaries, external_metrics, } diff --git a/crates/report/src/diff/markdown.rs b/crates/report/src/diff/markdown.rs index 4d75479..b7204f3 100644 --- a/crates/report/src/diff/markdown.rs +++ b/crates/report/src/diff/markdown.rs @@ -4,7 +4,7 @@ use crate::markdown::{ BOUNDARY_FINDING_COLUMNS, CLONE_GROUP, ERODED_FUNCTION, ERODED_FUNCTION_COLUMNS, EXTERNAL_FINDING_COLUMNS, FINDING, FLAGGED_LINE, FLAGGED_LINE_COLUMNS, IMPORT_CYCLE, Noun, boundary_finding_row, clone_group_item, code, eroded_function_row, external_finding_row, - flagged_line_row, import_cycle_item, list, push_findings, sentence_item, table, + findings_table, flagged_line_row, import_cycle_item, list, push_findings, sentence_item, table, }; const TITLE: &str = "# codeint diff"; @@ -104,12 +104,7 @@ fn findings_blocks(changes: &SourceSetChanges) -> Vec { "Erosion", &changes.erosion, &ERODED_FUNCTION, - |listed| { - table( - &ERODED_FUNCTION_COLUMNS, - listed.iter().map(eroded_function_row).collect(), - ) - }, + |listed| findings_table(&ERODED_FUNCTION_COLUMNS, listed, eroded_function_row), ); push_changes( &mut blocks, @@ -123,12 +118,7 @@ fn findings_blocks(changes: &SourceSetChanges) -> Vec { "Verbosity", &changes.verbosity, &FLAGGED_LINE, - |listed| { - table( - &FLAGGED_LINE_COLUMNS, - listed.iter().map(flagged_line_row).collect(), - ) - }, + |listed| findings_table(&FLAGGED_LINE_COLUMNS, listed, flagged_line_row), ); push_changes( &mut blocks, @@ -139,10 +129,7 @@ fn findings_blocks(changes: &SourceSetChanges) -> Vec { ); if let Some(boundaries) = &changes.boundaries { push_changes(&mut blocks, "Boundaries", boundaries, &FINDING, |listed| { - table( - &BOUNDARY_FINDING_COLUMNS, - listed.iter().map(boundary_finding_row).collect(), - ) + findings_table(&BOUNDARY_FINDING_COLUMNS, listed, boundary_finding_row) }); } for external in changes.external_metrics.values() { @@ -151,12 +138,7 @@ fn findings_blocks(changes: &SourceSetChanges) -> Vec { &external.name, &external.changes, &FINDING, - |listed| { - table( - &EXTERNAL_FINDING_COLUMNS, - listed.iter().map(external_finding_row).collect(), - ) - }, + |listed| findings_table(&EXTERNAL_FINDING_COLUMNS, listed, external_finding_row), ); } blocks diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index ec6083c..9dbabf1 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use codeint_config::{ - Boundaries as BoundariesConfig, BoundaryDirective, BoundaryRuleDecision, Budgets, + Boundaries as BoundariesConfig, BoundaryDirective, BoundaryRuleDecision, Budgets, Codeowners, FindingsShown, ReportFormat, }; use codeint_metrics::{ @@ -22,16 +22,20 @@ mod diff; mod guard; mod markdown; mod measurement; +mod ownership; mod sarif; #[cfg(test)] mod tests; mod trend; -pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; +pub use diff::{BaseCommit, DiffReport, DiffReportOptions, Head, HeadCommit}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use measurement::CommitMeasurement; +pub use ownership::OwnershipOptions; pub use trend::{TrendPoint, TrendReport}; +use ownership::OwnedFinding; + const DECIMAL_SCALE: f64 = 10_000.0; const NOT_PUBLISHED_FOR_THIS_LANGUAGE: &str = "no published Reference range for this language"; const NOT_SHOWN_FOR_SEVERAL_LANGUAGES: &str = @@ -152,6 +156,8 @@ struct BoundaryFindingRow { #[serde(skip_serializing_if = "Option::is_none")] reason: Option, message: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, } #[derive(Debug, Serialize)] @@ -176,6 +182,8 @@ struct ExternalMetricFinding { #[serde(skip_serializing_if = "Option::is_none")] end_line: Option, message: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, } #[derive(Debug, Serialize)] @@ -243,6 +251,8 @@ struct ErodedFunctionFinding { cyclomatic_complexity: u32, source_lines: u32, function_mass: Decimal, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, } #[derive(Debug, Serialize)] @@ -259,6 +269,8 @@ struct CloneGroupFinding { id: String, tokens: usize, locations: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, } #[derive(Debug, Serialize, Deserialize)] @@ -285,6 +297,8 @@ struct FlaggedLineRow { path: String, line: u32, rule: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, } #[derive(Debug, Serialize)] @@ -310,12 +324,16 @@ struct UnresolvedImportRow { importer: String, specifier: String, reason: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, } #[derive(Debug, Serialize, Deserialize)] struct ImportCycleFinding { id: String, modules: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, } #[derive(Debug, Serialize, Deserialize)] @@ -402,6 +420,18 @@ impl Findings { listed, } } + + fn worst_first_owned( + items: impl Iterator, + ownership: OwnershipOptions<'_>, + shown: FindingsShown, + ) -> Findings + where + T: OwnedFinding, + { + let filtered = ownership.apply(items.collect()); + Findings::worst_first(filtered.into_iter(), shown) + } } impl Serialize for Findings { @@ -440,6 +470,47 @@ impl FindingKind for ExternalMetricFinding { const LIST_KEY: &'static str = "findings"; } +macro_rules! impl_single_path_owner { + ($ty:ty, $field:ident) => { + impl OwnedFinding for $ty { + fn assign_owners(&mut self, codeowners: &Codeowners) { + self.owners = codeowners.owners_for(&self.$field); + } + + fn owners(&self) -> &[String] { + &self.owners + } + } + }; +} + +impl_single_path_owner!(ErodedFunctionFinding, path); +impl_single_path_owner!(FlaggedLineRow, path); +impl_single_path_owner!(UnresolvedImportRow, importer); +impl_single_path_owner!(ExternalMetricFinding, path); +impl_single_path_owner!(BoundaryFindingRow, importer); + +impl OwnedFinding for CloneGroupFinding { + fn assign_owners(&mut self, codeowners: &Codeowners) { + self.owners = + codeowners.owners_for_many(self.locations.iter().map(|loc| loc.path.as_str())); + } + + fn owners(&self) -> &[String] { + &self.owners + } +} + +impl OwnedFinding for ImportCycleFinding { + fn assign_owners(&mut self, codeowners: &Codeowners) { + self.owners = codeowners.owners_for_many(self.modules.iter().map(String::as_str)); + } + + fn owners(&self) -> &[String] { + &self.owners + } +} + impl FindingKind for BoundaryFindingRow { const LIST_KEY: &'static str = "findings"; } @@ -478,16 +549,28 @@ impl BoundaryPolicy for ConfigBoundaryPolicy<'_> { } } -fn mapped_findings<'a, T: 'a, R: From<&'a T>>(items: &'a [T], shown: FindingsShown) -> Findings { - Findings::worst_first(items.iter().map(R::from), shown) +#[derive(Clone, Copy)] +struct FindingsView<'a> { + shown: FindingsShown, + ownership: OwnershipOptions<'a>, +} + +impl FindingsView<'_> { + fn select(self, items: impl Iterator) -> Findings { + Findings::worst_first_owned(items, self.ownership, self.shown) + } + + fn map<'a, T: 'a, R: From<&'a T> + OwnedFinding>(self, items: &'a [T]) -> Findings { + self.select(items.iter().map(R::from)) + } } impl BoundariesSection { - fn new(boundaries: &Boundaries, shown: FindingsShown) -> BoundariesSection { + fn new(boundaries: &Boundaries, view: FindingsView<'_>) -> BoundariesSection { BoundariesSection { ratio: Decimal::rounded(boundaries.ratio()), resolved_imports: boundaries.resolved_imports(), - findings: mapped_findings(boundaries.findings(), shown), + findings: view.map(boundaries.findings()), } } } @@ -504,6 +587,7 @@ impl From<&BoundaryFinding> for BoundaryFindingRow { target_zone: finding.target_zone.clone(), reason: finding.reason.clone(), message: finding.message.clone(), + owners: Vec::new(), } } } @@ -516,6 +600,7 @@ impl ExternalMetricFinding { line: finding.line, end_line: finding.end_line, message: finding.message.clone(), + owners: Vec::new(), } } } @@ -527,6 +612,7 @@ impl SourceSetSections { findings: FindingsShown, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + ownership: OwnershipOptions<'_>, ) -> Result { let mut sections = SourceSetSections::default(); for (source_set, model) in source_sets.iter() { @@ -539,6 +625,7 @@ impl SourceSetSections { findings, metric_plugins, source_set_boundaries, + ownership, )?); } } @@ -612,11 +699,16 @@ impl SourceSetSection { findings: FindingsShown, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + ownership: OwnershipOptions<'_>, ) -> Result { + let view = FindingsView { + shown: findings, + ownership, + }; let measured = Measured::new(model); let boundaries = boundaries.map(|config| { let evaluated = Boundaries::measure(model, &ConfigBoundaryPolicy(config)); - BoundariesSection::new(&evaluated, findings) + BoundariesSection::new(&evaluated, view) }); let mut external_metrics = BTreeMap::new(); for plugin in metric_plugins { @@ -630,12 +722,11 @@ impl SourceSetSection { reference_range: ranges.entry(plugin.key()), numerator: Decimal::rounded(result.numerator), denominator: Decimal::rounded(result.denominator), - findings: Findings::worst_first( + findings: view.select( result .findings .iter() .map(ExternalMetricFinding::from_model), - findings, ), }, ); @@ -643,10 +734,53 @@ impl SourceSetSection { Ok(SourceSetSection { files: model.files.len(), source_lines: source_lines(model), - erosion: ErosionSection::new(&measured.erosion, ranges, findings), - duplication: DuplicationSection::new(&measured.duplication, ranges, findings), - verbosity: VerbositySection::new(&measured.verbosity, ranges, findings), - import_cycles: ImportCyclesSection::new(&measured.import_cycles, ranges, findings), + erosion: ErosionSection { + ratio: Decimal::rounded(measured.erosion.ratio()), + reference_range: ranges.entry(Metric::Erosion.key()), + eroded_function_mass: Decimal::rounded(measured.erosion.eroded_function_mass()), + total_function_mass: Decimal::rounded(measured.erosion.total_function_mass()), + findings: view.select( + measured + .erosion + .eroded_functions() + .iter() + .map(ErodedFunctionFinding::new), + ), + }, + duplication: DuplicationSection { + ratio: Decimal::rounded(measured.duplication.ratio()), + reference_range: ranges.entry(Metric::Duplication.key()), + clone_lines: measured.duplication.clone_lines.count(), + clone_groups: view.select( + measured + .duplication + .clone_groups + .iter() + .map(CloneGroupFinding::new), + ), + }, + verbosity: VerbositySection { + ratio: Decimal::rounded(measured.verbosity.ratio()), + reference_range: ranges.entry(Metric::Verbosity.key()), + verbose_lines: measured.verbosity.verbose_lines(), + flagged_lines: measured.verbosity.flagged_line_count(), + clone_lines: measured.verbosity.clone_line_count(), + findings: view.map(measured.verbosity.flagged_lines()), + }, + import_cycles: ImportCyclesSection { + ratio: Decimal::rounded(measured.import_cycles.ratio()), + reference_range: ranges.entry(Metric::ImportCycles.key()), + modules_in_import_cycles: measured.import_cycles.modules_in_import_cycles(), + modules: measured.import_cycles.modules(), + findings: view.select( + measured + .import_cycles + .cycles() + .iter() + .map(ImportCycleFinding::new), + ), + unresolved_imports: UnresolvedImportsSection::new(&measured.import_cycles, view), + }, boundaries, external_metrics, packages: package_sections(model, &measured), @@ -662,28 +796,6 @@ fn source_lines(model: &CodeModel) -> u64 { .sum() } -impl ErosionSection { - fn new( - erosion: &Erosion, - ranges: &ReferenceRangeScope, - shown: FindingsShown, - ) -> ErosionSection { - ErosionSection { - ratio: Decimal::rounded(erosion.ratio()), - reference_range: ranges.entry(Metric::Erosion.key()), - eroded_function_mass: Decimal::rounded(erosion.eroded_function_mass()), - total_function_mass: Decimal::rounded(erosion.total_function_mass()), - findings: Findings::worst_first( - erosion - .eroded_functions() - .iter() - .map(ErodedFunctionFinding::new), - shown, - ), - } - } -} - impl ErodedFunctionFinding { fn new(function: &ErodedFunction) -> ErodedFunctionFinding { ErodedFunctionFinding { @@ -693,24 +805,7 @@ impl ErodedFunctionFinding { cyclomatic_complexity: function.cyclomatic_complexity, source_lines: function.source_lines, function_mass: Decimal::rounded(function.function_mass), - } - } -} - -impl DuplicationSection { - fn new( - duplication: &Duplication, - ranges: &ReferenceRangeScope, - shown: FindingsShown, - ) -> DuplicationSection { - DuplicationSection { - ratio: Decimal::rounded(duplication.ratio()), - reference_range: ranges.entry(Metric::Duplication.key()), - clone_lines: duplication.clone_lines.count(), - clone_groups: Findings::worst_first( - duplication.clone_groups.iter().map(CloneGroupFinding::new), - shown, - ), + owners: Vec::new(), } } } @@ -721,6 +816,7 @@ impl CloneGroupFinding { id: group.id.to_string(), tokens: group.tokens, locations: group.fragments.iter().map(CloneLocation::new).collect(), + owners: Vec::new(), } } } @@ -735,23 +831,6 @@ impl CloneLocation { } } -impl VerbositySection { - fn new( - verbosity: &Verbosity, - ranges: &ReferenceRangeScope, - shown: FindingsShown, - ) -> VerbositySection { - VerbositySection { - ratio: Decimal::rounded(verbosity.ratio()), - reference_range: ranges.entry(Metric::Verbosity.key()), - verbose_lines: verbosity.verbose_lines(), - flagged_lines: verbosity.flagged_line_count(), - clone_lines: verbosity.clone_line_count(), - findings: mapped_findings(verbosity.flagged_lines(), shown), - } - } -} - impl From<&FlaggedLineFinding> for FlaggedLineRow { fn from(finding: &FlaggedLineFinding) -> FlaggedLineRow { FlaggedLineRow { @@ -759,26 +838,7 @@ impl From<&FlaggedLineFinding> for FlaggedLineRow { path: finding.path.to_string(), line: finding.line, rule: finding.rule.clone(), - } - } -} - -impl ImportCyclesSection { - fn new( - import_cycles: &ImportCycles, - ranges: &ReferenceRangeScope, - shown: FindingsShown, - ) -> ImportCyclesSection { - ImportCyclesSection { - ratio: Decimal::rounded(import_cycles.ratio()), - reference_range: ranges.entry(Metric::ImportCycles.key()), - modules_in_import_cycles: import_cycles.modules_in_import_cycles(), - modules: import_cycles.modules(), - findings: Findings::worst_first( - import_cycles.cycles().iter().map(ImportCycleFinding::new), - shown, - ), - unresolved_imports: UnresolvedImportsSection::new(import_cycles, shown), + owners: Vec::new(), } } } @@ -788,16 +848,17 @@ impl ImportCycleFinding { ImportCycleFinding { id: cycle.id().to_string(), modules: cycle.modules().iter().map(RepoPath::to_string).collect(), + owners: Vec::new(), } } } impl UnresolvedImportsSection { - fn new(import_cycles: &ImportCycles, shown: FindingsShown) -> UnresolvedImportsSection { - let unresolved = import_cycles.unresolved_imports(); + fn new(import_cycles: &ImportCycles, view: FindingsView<'_>) -> UnresolvedImportsSection { + let imports = view.map(import_cycles.unresolved_imports()); UnresolvedImportsSection { - count: unresolved.len(), - imports: Findings::worst_first(unresolved.iter().map(UnresolvedImportRow::from), shown), + count: imports.listed.len() + imports.left_out, + imports, } } } @@ -808,6 +869,7 @@ impl From<&UnresolvedImport> for UnresolvedImportRow { importer: import.importer.to_string(), specifier: import.specifier.clone(), reason: import.reason.clone(), + owners: Vec::new(), } } } @@ -898,6 +960,7 @@ impl MeasuredSection { findings: FindingsShown, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + ownership: OwnershipOptions<'_>, ) -> Result { let files = model.files.len(); let lines = source_lines(&model); @@ -907,6 +970,7 @@ impl MeasuredSection { findings, metric_plugins, boundaries, + ownership, )?; Ok(MeasuredSection { files, @@ -951,6 +1015,26 @@ impl Report { budgets: &Budgets, metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, + ) -> Result { + Report::summarize_with_ownership( + languages, + submodules, + findings, + budgets, + metric_plugins, + boundaries, + OwnershipOptions::default(), + ) + } + + pub fn summarize_with_ownership( + languages: Vec, + submodules: Vec, + findings: FindingsShown, + budgets: &Budgets, + metric_plugins: &[&dyn MetricPlugin], + boundaries: Option<&BoundariesConfig>, + ownership: OwnershipOptions<'_>, ) -> Result { let (measured, unmeasured): (Vec, Vec) = languages .into_iter() @@ -975,6 +1059,7 @@ impl Report { findings, metric_plugins, boundaries, + ownership, )?, ); } @@ -993,8 +1078,14 @@ impl Report { .iter() .map(RepoPath::to_string) .collect(); - let measured = - MeasuredSection::new(model, &total_ranges, findings, metric_plugins, boundaries)?; + let measured = MeasuredSection::new( + model, + &total_ranges, + findings, + metric_plugins, + boundaries, + ownership, + )?; Ok(Report { over_budget: measured.source_sets.over_budget(budgets), skipped, diff --git a/crates/report/src/markdown.rs b/crates/report/src/markdown.rs index 5b45835..4c88e69 100644 --- a/crates/report/src/markdown.rs +++ b/crates/report/src/markdown.rs @@ -1,3 +1,4 @@ +use crate::ownership::OwnedFinding; use crate::{ BoundaryFindingRow, CloneGroupFinding, CloneLocation, DuplicationSection, ErodedFunctionFinding, ErosionSection, ExternalMetricFinding, Findings, FlaggedLineRow, @@ -359,12 +360,7 @@ fn findings_blocks(section: &SourceSetSection) -> Vec { "Erosion", §ion.erosion.findings, &ERODED_FUNCTION, - |listed| { - table( - &ERODED_FUNCTION_COLUMNS, - listed.iter().map(eroded_function_row).collect(), - ) - }, + |listed| findings_table(&ERODED_FUNCTION_COLUMNS, listed, eroded_function_row), ); push_findings( &mut blocks, @@ -378,12 +374,7 @@ fn findings_blocks(section: &SourceSetSection) -> Vec { "Verbosity", §ion.verbosity.findings, &FLAGGED_LINE, - |listed| { - table( - &FLAGGED_LINE_COLUMNS, - listed.iter().map(flagged_line_row).collect(), - ) - }, + |listed| findings_table(&FLAGGED_LINE_COLUMNS, listed, flagged_line_row), ); push_findings( &mut blocks, @@ -397,12 +388,7 @@ fn findings_blocks(section: &SourceSetSection) -> Vec { "Unresolved imports", §ion.import_cycles.unresolved_imports.imports, &UNRESOLVED_IMPORT, - |listed| { - table( - &UNRESOLVED_IMPORT_COLUMNS, - listed.iter().map(unresolved_import_row).collect(), - ) - }, + |listed| findings_table(&UNRESOLVED_IMPORT_COLUMNS, listed, unresolved_import_row), ); if let Some(boundaries) = §ion.boundaries { push_findings( @@ -410,12 +396,7 @@ fn findings_blocks(section: &SourceSetSection) -> Vec { "Boundaries", &boundaries.findings, &FINDING, - |listed| { - table( - &BOUNDARY_FINDING_COLUMNS, - listed.iter().map(boundary_finding_row).collect(), - ) - }, + |listed| findings_table(&BOUNDARY_FINDING_COLUMNS, listed, boundary_finding_row), ); } for external in section.external_metrics.values() { @@ -424,12 +405,7 @@ fn findings_blocks(section: &SourceSetSection) -> Vec { &external.name, &external.findings, &FINDING, - |listed| { - table( - &EXTERNAL_FINDING_COLUMNS, - listed.iter().map(external_finding_row).collect(), - ) - }, + |listed| findings_table(&EXTERNAL_FINDING_COLUMNS, listed, external_finding_row), ); } blocks @@ -458,6 +434,50 @@ pub(crate) fn push_findings( } } +pub(crate) fn findings_table( + columns: &[&str], + listed: &[T], + row: impl Fn(&T) -> Vec, +) -> String { + let show_owners = listed.iter().any(|item| !item.owners().is_empty()); + let mut headers: Vec<&str> = columns.to_vec(); + if show_owners { + headers.push("Owners"); + } + let rows = listed + .iter() + .map(|item| { + let mut cells = row(item); + if show_owners { + cells.push(format_owners(item.owners())); + } + cells + }) + .collect(); + table(&headers, rows) +} + +fn format_owners(owners: &[String]) -> String { + if owners.is_empty() { + "-".to_owned() + } else { + owners + .iter() + .map(String::as_str) + .map(code) + .collect::>() + .join(", ") + } +} + +fn with_owners_suffix(text: String, owners: &[String]) -> String { + if owners.is_empty() { + text + } else { + format!("{text} (owners: {})", format_owners(owners)) + } +} + pub(crate) fn eroded_function_row(function: &ErodedFunctionFinding) -> Vec { vec![ code(&format!("{}:{}", function.path, function.line)), @@ -469,7 +489,10 @@ pub(crate) fn eroded_function_row(function: &ErodedFunctionFinding) -> Vec String { let locations: Vec = group.locations.iter().map(clone_location).collect(); - format!("{} tokens: {}", group.tokens, locations.join(", ")) + with_owners_suffix( + format!("{} tokens: {}", group.tokens, locations.join(", ")), + &group.owners, + ) } fn clone_location(location: &CloneLocation) -> String { @@ -502,7 +525,7 @@ pub(crate) fn external_finding_row(finding: &ExternalMetricFinding) -> Vec String { let modules: Vec = cycle.modules.iter().map(|module| code(module)).collect(); - modules.join(", ") + with_owners_suffix(modules.join(", "), &cycle.owners) } fn unresolved_import_row(row: &UnresolvedImportRow) -> Vec { diff --git a/crates/report/src/ownership.rs b/crates/report/src/ownership.rs new file mode 100644 index 0000000..4d95464 --- /dev/null +++ b/crates/report/src/ownership.rs @@ -0,0 +1,26 @@ +use codeint_config::{Codeowners, OwnerFilter}; + +#[derive(Clone, Copy, Default)] +pub struct OwnershipOptions<'a> { + pub codeowners: Option<&'a Codeowners>, + pub owner_filter: Option<&'a OwnerFilter>, +} + +pub(crate) trait OwnedFinding { + fn assign_owners(&mut self, codeowners: &Codeowners); + fn owners(&self) -> &[String]; +} + +impl OwnershipOptions<'_> { + pub(crate) fn apply(&self, mut items: Vec) -> Vec { + if let Some(codeowners) = self.codeowners { + for item in &mut items { + item.assign_owners(codeowners); + } + } + if let Some(filter) = self.owner_filter { + items.retain(|item| filter.matches_any(item.owners())); + } + items + } +} diff --git a/crates/report/src/sarif/tests.rs b/crates/report/src/sarif/tests.rs index 78d134d..8a59c84 100644 --- a/crates/report/src/sarif/tests.rs +++ b/crates/report/src/sarif/tests.rs @@ -38,6 +38,7 @@ fn every_sarif_result_carries_its_finding_id_in_partial_fingerprints() { cyclomatic_complexity: 12, source_lines: 20, function_mass: Decimal(53.6656), + owners: Vec::new(), }]; let clones = [CloneGroupFinding { id: "2222222222222222".to_owned(), @@ -54,16 +55,19 @@ fn every_sarif_result_carries_its_finding_id_in_partial_fingerprints() { end_line: 10, }, ], + owners: Vec::new(), }]; let flagged = [FlaggedLineRow { id: "3333333333333333".to_owned(), path: "src/sign.ts".to_owned(), line: 4, rule: "else-after-return".to_owned(), + owners: Vec::new(), }]; let cycles = [ImportCycleFinding { id: "4444444444444444".to_owned(), modules: vec!["src/x.ts".to_owned(), "src/y.ts".to_owned()], + owners: Vec::new(), }]; let listed = ListedFindings { eroded_functions: &eroded, diff --git a/docs/reference.md b/docs/reference.md index 92e93a0..8a845fb 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -130,6 +130,7 @@ Edit the existing codeint.json, or delete it and run codeint init again. | `--output ` | Write the report to this file instead of standard output | | `--all` | List every Finding instead of the 20 worst per Metric | | `--format ` | The format of the report: `toon`, the default, `json`, `sarif`, or `markdown`; see [Report formats](#report-formats) | +| `--owner ` | Include only Findings whose `CODEOWNERS` owner matches this pattern | | `-h, --help` | Print the help of `codeint check` | `codeint check` measures the working tree, including uncommitted and untracked files, and prints the report: @@ -200,6 +201,7 @@ These commands measure the same repository with other options: ```sh exit=0 codeint check src codeint check --all +codeint check --owner @team codeint check --format markdown --output report.md ``` @@ -226,6 +228,7 @@ Pass a folder that exists, or leave the path out to measure the current folder. | `--output ` | Write the report to this file instead of standard output | | `--all` | List every Finding instead of the 20 worst per Metric | | `--format ` | The format of the report: `toon`, the default, `json`, `sarif`, or `markdown` | +| `--owner ` | Include only Findings whose `CODEOWNERS` owner matches this pattern | | `-h, --help` | Print the help of `codeint diff` | `codeint diff {base-ref}` compares the working tree with the merge-base of the base ref and HEAD. @@ -368,6 +371,12 @@ codeint: the Git ref "no-such-branch" does not name a commit in this repository: Pass a branch, tag, or commit that exists in this repository; fetch it first when it lives on a remote: git fetch origin main ``` +When a repository has a `CODEOWNERS` file (`.github/CODEOWNERS`, `CODEOWNERS`, or `docs/CODEOWNERS`), codeint attaches matched owners to Findings and `--owner ` filters Findings to those matching the pattern: + +```sh exit=0 +codeint diff main --owner @team +``` + #### Regressions A Regression is a Metric that got worse from the merge-base to the head side by more than its limit. From 4c12c071aa88fd9ff84138ccf494abdd8b346183 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:42:55 +0800 Subject: [PATCH 3/4] feat(cli): add co-change coupling analysis with bulk-commit filtering Extend crates/git with native gix co-change pair accumulation over the same history window as churn, excluding bulk commits above --max-commit-files (default 50) and filtering to measured Source-set paths before forming pairs. Annotate each coupled pair with co_change_count, coupling_ratio, and has_direct_import against resolved runtime imports, defaulting to Production with --include-tests and preserving ADR 0003 with no blended score. Expose co-change coupling via codeint coupling (text, TOON, JSON, Markdown) and the read-only coupling tool in codeint mcp. Closes #183 --- crates/cli/src/churn.rs | 2 +- crates/cli/src/coupling.rs | 54 +++++ crates/cli/src/lib.rs | 65 +++++- crates/cli/src/mcp.rs | 95 ++++++++- crates/cli/tests/churn.rs | 190 +++-------------- crates/cli/tests/coupling.rs | 272 ++++++++++++++++++++++++ crates/cli/tests/history_support/mod.rs | 164 ++++++++++++++ crates/cli/tests/mcp.rs | 92 ++++++-- crates/config/src/coupling.rs | 88 ++++++++ crates/config/src/lib.rs | 166 +++++++++++---- crates/git/src/churn.rs | 93 +++++++- crates/git/src/lib.rs | 2 +- crates/report/src/churn.rs | 21 +- crates/report/src/coupling.rs | 168 +++++++++++++++ crates/report/src/coupling/markdown.rs | 70 ++++++ crates/report/src/coupling/text.rs | 49 +++++ crates/report/src/lib.rs | 2 + docs/reference.md | 31 ++- 18 files changed, 1384 insertions(+), 240 deletions(-) create mode 100644 crates/cli/src/coupling.rs create mode 100644 crates/cli/tests/coupling.rs create mode 100644 crates/cli/tests/history_support/mod.rs create mode 100644 crates/config/src/coupling.rs create mode 100644 crates/report/src/coupling.rs create mode 100644 crates/report/src/coupling/markdown.rs create mode 100644 crates/report/src/coupling/text.rs diff --git a/crates/cli/src/churn.rs b/crates/cli/src/churn.rs index 299ebe6..7af90d6 100644 --- a/crates/cli/src/churn.rs +++ b/crates/cli/src/churn.rs @@ -26,7 +26,7 @@ pub(crate) fn churn( Ok(ChurnReport::summarize(languages, &input, findings)) } -fn churn_range(window: ChurnWindow) -> ChurnRange { +pub(crate) fn churn_range(window: ChurnWindow) -> ChurnRange { match window { ChurnWindow::Days(days) => ChurnRange::Days(days), ChurnWindow::Since(day) => ChurnRange::Since { diff --git a/crates/cli/src/coupling.rs b/crates/cli/src/coupling.rs new file mode 100644 index 0000000..922fb65 --- /dev/null +++ b/crates/cli/src/coupling.rs @@ -0,0 +1,54 @@ +use std::collections::BTreeSet; +use std::path::Path; + +use codeint_config::{CouplingSettings, FindingsShown, PluginHostConfig}; +use codeint_model::{CodeModel, RepoPath, SourceSet}; +use codeint_report::{CouplingHistoryInput, CouplingReport}; + +use crate::check::{CheckError, load_workspace, measure_with}; +use crate::churn::churn_range; + +pub(crate) fn coupling( + folder: &Path, + settings: CouplingSettings, + findings: FindingsShown, + plugin_host: &PluginHostConfig, +) -> Result { + let (repository, configuration, loaded) = load_workspace(folder, plugin_host)?; + let plugins = loaded.as_named(); + let tree = repository.working_tree()?; + let languages = measure_with(&tree, &plugins, &configuration)?; + let model = CodeModel::merge(languages.into_iter().map(|lang| lang.model)); + let allowed_paths = selected_source_paths(&model, settings.include_tests); + let history = repository.co_change_coupling( + churn_range(settings.window), + settings.max_commit_files, + &allowed_paths, + )?; + let input = CouplingHistoryInput { + window: settings.window, + commits_analyzed: history.commits_analyzed, + commits_excluded_by_bulk_limit: history.commits_excluded_by_bulk_limit, + max_commit_files: settings.max_commit_files, + min_co_changes: settings.min_co_changes, + min_ratio: settings.min_ratio.value(), + include_tests: settings.include_tests, + shallow: history.shallow, + touches_by_file: history.touches_by_file, + co_changes: history.co_changes, + }; + Ok(CouplingReport::summarize(&model, &input, findings)) +} + +fn selected_source_paths(model: &CodeModel, include_tests: bool) -> BTreeSet { + model + .files + .iter() + .filter(|file| match file.model.source_set { + SourceSet::Production => true, + SourceSet::Test => include_tests, + SourceSet::Generated | SourceSet::Vendored => false, + }) + .map(|file| file.path.clone()) + .collect() +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 38958b4..0320e98 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -3,6 +3,7 @@ mod check; mod churn; mod commit_measurement; +mod coupling; mod diff; mod guard; mod init; @@ -22,10 +23,13 @@ use codeint_git::ResultCache; use codeint_report::ReportError; pub use codeint_config::{ - CalendarDay, ChurnFormat, ChurnSince, ChurnWindow, FindingsShown, GuardFormat, - PluginHostConfig, ReportFormat, TrendFormat, TrendRange, + CalendarDay, ChurnFormat, ChurnSince, ChurnWindow, CouplingRatio, CouplingRatioError, + CouplingSettings, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, + TrendRange, +}; +pub use codeint_report::{ + ChurnReport, CouplingReport, DiffReport, GuardReport, Report, TrendReport, }; -pub use codeint_report::{ChurnReport, DiffReport, GuardReport, Report, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -98,6 +102,23 @@ impl Default for ChurnOptions { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CouplingOptions { + pub settings: CouplingSettings, + pub findings: FindingsShown, + pub plugin_host: PluginHostConfig, +} + +impl Default for CouplingOptions { + fn default() -> CouplingOptions { + CouplingOptions { + settings: CouplingSettings::default(), + findings: FindingsShown::WorstPerMetric(DEFAULT_WORST_FINDINGS), + plugin_host: PluginHostConfig::default(), + } + } +} + pub struct CheckOutcome { pub passed: bool, pub failures: Vec, @@ -216,6 +237,16 @@ pub fn churn(folder: &Path, options: &ChurnOptions) -> Result Result { + coupling::coupling( + folder, + options.settings, + options.findings, + &options.plugin_host, + ) + .map_err(|err| CodeintError::from_cli_error(CliError::Check(err))) +} + #[derive(Debug, thiserror::Error)] enum CliError { #[error(transparent)] @@ -347,6 +378,21 @@ fn run() -> Result { format, &plugin_host, ), + Command::Coupling { + folder, + settings, + destination, + findings, + format, + plugin_host, + } => run_coupling( + &folder, + settings, + &destination, + findings, + format, + &plugin_host, + ), } } @@ -363,6 +409,19 @@ fn run_churn( Ok(Outcome::Passed) } +fn run_coupling( + folder: &Path, + settings: CouplingSettings, + destination: &ReportDestination, + findings: FindingsShown, + format: ChurnFormat, + plugin_host: &PluginHostConfig, +) -> Result { + let report = coupling::coupling(folder, settings, findings, plugin_host)?; + write_report(&report.render(format)?, destination)?; + Ok(Outcome::Passed) +} + fn run_guard(folder: &Path, target: &Path, format: GuardFormat) -> Result { let report = guard::guard(folder, target)?; print_report(&format!("{}\n", report.render(format)?))?; diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 6394dd3..7727d55 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -3,13 +3,14 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use codeint_config::{ - CalendarDay, ChurnFormat, ChurnSince, ChurnWindow, FindingsShown, GuardFormat, - PluginHostConfig, ReportFormat, TrendFormat, TrendRange, + CalendarDay, ChurnFormat, ChurnSince, ChurnWindow, CouplingRatio, CouplingSettings, + FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, }; use serde_json::{Value, json}; use crate::{ - CheckOptions, ChurnOptions, DiffOptions, TrendOptions, check, churn, diff, guard, trend, + CheckOptions, ChurnOptions, CouplingOptions, DiffOptions, TrendOptions, check, churn, coupling, + diff, guard, trend, }; const DEFAULT_PROTOCOL_VERSION: &str = "2024-11-05"; @@ -185,6 +186,23 @@ fn handle_tools_list() -> Value { "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } } } + }, + { + "name": "coupling", + "description": "Detect pairs of files that repeatedly change together in the same commits, excluding bulk commits and flagging direct runtime imports.", + "inputSchema": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "since": { "type": "string", "description": "Lookback window in days (such as 90d) or UTC date (YYYY-MM-DD); mutually exclusive with commits." }, + "commits": { "type": "integer", "minimum": 1, "description": "Walk at most this many main-line commits from HEAD; mutually exclusive with since." }, + "max_commit_files": { "type": "integer", "minimum": 1, "description": "Exclude commits touching more than this many files (defaults to 50)." }, + "min_co_changes": { "type": "integer", "minimum": 1, "description": "Minimum co-changing commits required to report a pair (defaults to 3)." }, + "min_ratio": { "type": "number", "minimum": 0, "maximum": 1, "description": "Minimum coupling ratio between 0 and 1 required to report a pair (defaults to 0.3)." }, + "include_tests": { "type": "boolean", "description": "Include Test Source set files alongside Production files (defaults to false)." }, + "all": { "type": "boolean", "description": "Return all coupled pairs instead of the top 20." } + } + } } ] }) @@ -205,6 +223,7 @@ fn handle_tools_call( "trend" => Ok(call_trend(args, ctx)), "guard" => Ok(call_guard(args, ctx)), "churn" => Ok(call_churn(args, ctx)), + "coupling" => Ok(call_coupling(args, ctx)), other => Err((-32602, format!("Unknown tool: {other}"))), } } @@ -336,6 +355,76 @@ fn call_churn(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { }) } +fn call_coupling(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { + let settings = match parse_coupling_settings(args) { + Ok(settings) => settings, + Err(err) => return err, + }; + let folder = resolve_folder(args, ctx.default_folder); + let options = CouplingOptions { + settings, + findings: parse_findings(args), + plugin_host: ctx.plugin_host.clone(), + }; + render_json_tool(coupling(&folder, &options), |report| { + report.render(ChurnFormat::Json) + }) +} + +fn parse_coupling_settings(args: Option<&Value>) -> Result { + let defaults = CouplingSettings::default(); + let window = parse_churn_window(args)?; + let max_commit_files = parse_optional_arg( + args, + "max_commit_files", + defaults.max_commit_files, + |value| parse_positive_usize(value, "max_commit_files"), + )?; + let min_co_changes = + parse_optional_arg(args, "min_co_changes", defaults.min_co_changes, |value| { + parse_positive_usize(value, "min_co_changes") + })?; + let min_ratio = parse_optional_arg(args, "min_ratio", defaults.min_ratio, parse_ratio)?; + let include_tests = args + .and_then(|a| a.get("include_tests")) + .and_then(Value::as_bool) + .unwrap_or(defaults.include_tests); + Ok(CouplingSettings { + window, + max_commit_files, + min_co_changes, + min_ratio, + include_tests, + }) +} + +fn parse_optional_arg( + args: Option<&Value>, + name: &str, + default: T, + parse: impl FnOnce(&Value) -> Result, +) -> Result { + match args.and_then(|a| a.get(name)).filter(|v| !v.is_null()) { + Some(value) => parse(value), + None => Ok(default), + } +} + +fn parse_positive_usize(value: &Value, name: &str) -> Result { + value + .as_u64() + .and_then(|n| usize::try_from(n).ok()) + .filter(|&n| n > 0) + .ok_or_else(|| tool_err(&format!("Argument {name} must be a positive integer"))) +} + +fn parse_ratio(value: &Value) -> Result { + let ratio = value + .as_f64() + .ok_or_else(|| tool_err("Argument min_ratio must be a number between 0 and 1"))?; + CouplingRatio::new(ratio).map_err(|err| tool_err(&format!("Invalid min_ratio: {err}"))) +} + fn parse_churn_window(args: Option<&Value>) -> Result { let since_val = args.and_then(|a| a.get("since")).filter(|v| !v.is_null()); let commits_val = args.and_then(|a| a.get("commits")).filter(|v| !v.is_null()); diff --git a/crates/cli/tests/churn.rs b/crates/cli/tests/churn.rs index 5fd252f..a938b98 100644 --- a/crates/cli/tests/churn.rs +++ b/crates/cli/tests/churn.rs @@ -1,86 +1,9 @@ -use std::fs; -use std::path::Path; -use std::process::{Command, Output}; +mod history_support; -use serde_json::Value; -use tempfile::TempDir; - -struct ChurnFixture(TempDir); - -impl ChurnFixture { - fn init() -> ChurnFixture { - let dir = tempfile::tempdir().expect("tempdir"); - run_git( - dir.path(), - &["init", "-q", "-b", "main"], - "2026-05-01T10:00:00Z", - ); - ChurnFixture(dir) - } - - fn root(&self) -> &Path { - self.0.path() - } - - fn save_and_commit(&self, files: &[(&str, String)], msg: &str, when: &str) { - for (rel, content) in files { - let dest = self.root().join(rel); - fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir"); - fs::write(dest, content).expect("write"); - } - run_git(self.root(), &["add", "-A"], when); - run_git(self.root(), &["commit", "-q", "-m", msg], when); - } - - fn churn(&self, extra: &[&str]) -> Output { - exec_churn(self.root(), extra) - } - - fn churn_json(&self, extra: &[&str]) -> Value { - let args: Vec<&str> = extra.iter().copied().chain(["--format", "json"]).collect(); - let out = self.churn(&args); - assert_eq!( - out.status.code(), - Some(0), - "churn stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - serde_json::from_slice(&out.stdout).expect("valid churn JSON") - } -} - -fn run_git(cwd: &Path, args: &[&str], when: &str) { - let vars = [ - ("GIT_CONFIG_GLOBAL", "/dev/null"), - ("GIT_CONFIG_NOSYSTEM", "1"), - ("GIT_AUTHOR_NAME", "Churn"), - ("GIT_AUTHOR_EMAIL", "churn@example.invalid"), - ("GIT_COMMITTER_NAME", "Churn"), - ("GIT_COMMITTER_EMAIL", "churn@example.invalid"), - ("GIT_AUTHOR_DATE", when), - ("GIT_COMMITTER_DATE", when), - ]; - let out = Command::new("git") - .args(args) - .current_dir(cwd) - .envs(vars) - .output() - .expect("git"); - assert!( - out.status.success(), - "git {args:?}: {}", - String::from_utf8_lossy(&out.stderr) - ); -} - -fn exec_churn(cwd: &Path, extra: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_codeint")) - .arg("churn") - .args(extra) - .current_dir(cwd) - .output() - .expect("run codeint churn") -} +use history_support::{ + HistoryFixture, assert_format_contains, assert_no_blended_score_keys, + assert_shallow_and_non_git, +}; fn eroded_ts(name: &str, salt: usize) -> String { let checks: String = (1..=12) @@ -110,46 +33,9 @@ fn duplicated_ts(prefix: &str, extra: &str) -> String { ) } -fn assert_no_blended_score_keys(value: &Value) { - let forbidden = ["score", "index", "grade", "rating", "hotspot_score"]; - match value { - Value::Object(map) => { - for (k, v) in map { - let lower = k.to_ascii_lowercase(); - for word in forbidden { - assert!( - !lower.contains(word), - "ADR 0003 violation: unexpected blended key {k:?}" - ); - } - assert_no_blended_score_keys(v); - } - } - Value::Array(items) => items.iter().for_each(assert_no_blended_score_keys), - _ => {} - } -} - -fn assert_format_contains(repo: &ChurnFixture, format: &str, needles: &[&str]) { - let out = repo.churn(&["--format", format]); - assert_eq!( - out.status.code(), - Some(0), - "{format} stderr: {}", - String::from_utf8_lossy(&out.stderr) - ); - let stdout = String::from_utf8_lossy(&out.stdout); - for needle in needles { - assert!( - stdout.contains(needle), - "{format} missing {needle:?}: {stdout}" - ); - } -} - #[test] fn churn_ranks_eroded_and_duplicated_files_independently_by_commit_count_with_no_score() { - let repo = ChurnFixture::init(); + let repo = HistoryFixture::init(); repo.save_and_commit( &[ ("src/cold_eroded.ts", eroded_ts("coldEroded", 0)), @@ -197,7 +83,7 @@ fn churn_ranks_eroded_and_duplicated_files_independently_by_commit_count_with_no "2026-05-04T10:00:00Z", ); - let report = repo.churn_json(&[]); + let report = repo.run_json("churn", &[]); assert_no_blended_score_keys(&report); assert_eq!(report["commits_analyzed"], 4); assert_eq!(report["shallow"], false); @@ -228,7 +114,7 @@ fn churn_ranks_eroded_and_duplicated_files_independently_by_commit_count_with_no #[test] fn churn_respects_since_days_since_date_and_commits_window() { - let repo = ChurnFixture::init(); + let repo = HistoryFixture::init(); for (label, salt, when) in [ ("old", 1, "2026-01-01T10:00:00Z"), ("mid", 2, "2026-05-01T10:00:00Z"), @@ -238,21 +124,21 @@ fn churn_respects_since_days_since_date_and_commits_window() { repo.save_and_commit(&[("src/eroded.ts", eroded_ts(label, salt))], label, when); } - let by_days = repo.churn_json(&["--since", "30d"]); + let by_days = repo.run_json("churn", &["--since", "30d"]); assert_eq!(by_days["commits_analyzed"], 3); assert_eq!( by_days["source_sets"]["production"]["erosion"]["findings"][0]["commits"], 3 ); - let by_date = repo.churn_json(&["--since", "2026-05-05"]); + let by_date = repo.run_json("churn", &["--since", "2026-05-05"]); assert_eq!(by_date["commits_analyzed"], 2); assert_eq!( by_date["source_sets"]["production"]["erosion"]["findings"][0]["commits"], 2 ); - let by_commits = repo.churn_json(&["--commits", "2"]); + let by_commits = repo.run_json("churn", &["--commits", "2"]); assert_eq!(by_commits["commits_analyzed"], 2); assert_eq!( by_commits["source_sets"]["production"]["erosion"]["findings"][0]["commits"], @@ -260,17 +146,17 @@ fn churn_respects_since_days_since_date_and_commits_window() { ); assert_eq!( - repo.churn(&["--since", "30d", "--commits", "5"]) + repo.run("churn", &["--since", "30d", "--commits", "5"]) .status .code(), Some(2) ); - assert_eq!(repo.churn(&["--since", "0d"]).status.code(), Some(2)); + assert_eq!(repo.run("churn", &["--since", "0d"]).status.code(), Some(2)); } #[test] fn churn_renders_text_toon_json_and_markdown_formats() { - let repo = ChurnFixture::init(); + let repo = HistoryFixture::init(); repo.save_and_commit( &[("src/eroded.ts", eroded_ts("hot", 1))], "c1", @@ -282,14 +168,24 @@ fn churn_renders_text_toon_json_and_markdown_formats() { "2026-05-02T10:00:00Z", ); - assert_format_contains(&repo, "text", &["src/eroded.ts", "Erosion"]); - assert_format_contains(&repo, "toon", &["commits_analyzed: 2", "src/eroded.ts"]); - assert_format_contains(&repo, "markdown", &["# codeint churn", "`src/eroded.ts`"]); + assert_format_contains(&repo, "churn", "text", &["src/eroded.ts", "Erosion"]); + assert_format_contains( + &repo, + "churn", + "toon", + &["commits_analyzed: 2", "src/eroded.ts"], + ); + assert_format_contains( + &repo, + "churn", + "markdown", + &["# codeint churn", "`src/eroded.ts`"], + ); } #[test] fn churn_handles_shallow_clones_and_non_git_directories_gracefully() { - let origin = ChurnFixture::init(); + let origin = HistoryFixture::init(); for i in 1..=4 { origin.save_and_commit( &[("src/eroded.ts", eroded_ts("hot", i))], @@ -297,33 +193,5 @@ fn churn_handles_shallow_clones_and_non_git_directories_gracefully() { &format!("2026-05-0{i}T10:00:00Z"), ); } - - let shallow = ChurnFixture::init(); - let url = format!("file://{}", origin.root().display()); - run_git( - shallow.root(), - &["fetch", "-q", "--depth", "2", &url, "main"], - "2026-05-05T10:00:00Z", - ); - run_git( - shallow.root(), - &["reset", "-q", "--hard", "FETCH_HEAD"], - "2026-05-05T10:00:00Z", - ); - - let report = shallow.churn_json(&[]); - assert_eq!(report["shallow"], true); - assert_eq!(report["commits_analyzed"], 2); - let warning = report["warning"].as_str().expect("shallow clone warning"); - assert!(warning.contains("shallow"), "warning: {warning}"); - assert!(warning.contains("--unshallow"), "warning: {warning}"); - - let non_git = tempfile::tempdir().expect("non-git tempdir"); - let out = exec_churn(non_git.path(), &[]); - assert_eq!(out.status.code(), Some(2)); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!( - stderr.contains("not inside a Git repository"), - "stderr: {stderr}" - ); + assert_shallow_and_non_git(&origin, "churn", &[]); } diff --git a/crates/cli/tests/coupling.rs b/crates/cli/tests/coupling.rs new file mode 100644 index 0000000..663d576 --- /dev/null +++ b/crates/cli/tests/coupling.rs @@ -0,0 +1,272 @@ +mod history_support; + +use history_support::{ + HistoryFixture, assert_format_contains, assert_no_blended_score_keys, + assert_shallow_and_non_git, +}; + +fn commit_const_pair( + repo: &HistoryFixture, + left: (&str, &str), + right: (&str, &str), + count: usize, + day_prefix: &str, +) { + for step in 1..=count { + repo.save_and_commit( + &[ + (left.0, format!("export const {} = {step};\n", left.1)), + (right.0, format!("export const {} = {step};\n", right.1)), + ], + &format!("pair {day_prefix} {step}"), + &format!("2026-05-{day_prefix}{step}T10:00:00Z"), + ); + } +} + +#[test] +fn coupling_detects_co_changed_pairs_flags_direct_imports_and_omits_blended_scores() { + let repo = HistoryFixture::init(); + for step in 1..=4 { + let mut files = vec![ + ( + "src/billing/invoice.ts", + format!("export const invoiceVersion = {step};\n"), + ), + ( + "src/shipping/label.ts", + format!("export const labelVersion = {step};\n"), + ), + ]; + if step == 1 { + files.push(( + "src/unrelated.ts", + "export const unrelated = 1;\n".to_owned(), + )); + } + repo.save_and_commit( + &files, + &format!("hidden pair {step}"), + &format!("2026-05-0{step}T10:00:00Z"), + ); + } + for step in 1..=3 { + repo.save_and_commit( + &[ + ( + "src/orders/model.ts", + format!( + "export function formatOrder(id: number): number {{ return id + {step}; }}\n" + ), + ), + ( + "src/orders/handler.ts", + format!( + "import {{ formatOrder }} from \"./model\";\nexport const handled = formatOrder({step});\n" + ), + ), + ], + &format!("direct import pair {step}"), + &format!("2026-05-1{step}T10:00:00Z"), + ); + } + repo.save_and_commit( + &[( + "src/orders/model.ts", + "export function formatOrder(id: number): number { return id + 99; }\n".to_owned(), + )], + "touch model alone", + "2026-05-15T10:00:00Z", + ); + + let report = repo.run_json("coupling", &[]); + assert_no_blended_score_keys(&report); + assert_eq!(report["commits_analyzed"], 8); + assert_eq!(report["commits_excluded_by_bulk_limit"], 0); + assert_eq!(report["max_commit_files"], 50); + assert_eq!(report["min_co_changes"], 3); + assert_eq!(report["shallow"], false); + assert!(report.get("warning").is_none()); + + let pairs = report["pairs"].as_array().expect("pairs array"); + assert_eq!(pairs.len(), 2); + + assert_eq!(pairs[0]["file_a"], "src/billing/invoice.ts"); + assert_eq!(pairs[0]["file_b"], "src/shipping/label.ts"); + assert_eq!(pairs[0]["co_change_count"], 4); + assert_eq!(pairs[0]["file_a_commits"], 4); + assert_eq!(pairs[0]["file_b_commits"], 4); + assert_eq!(pairs[0]["coupling_ratio"], 1.0); + assert_eq!(pairs[0]["has_direct_import"], false); + + assert_eq!(pairs[1]["file_a"], "src/orders/handler.ts"); + assert_eq!(pairs[1]["file_b"], "src/orders/model.ts"); + assert_eq!(pairs[1]["co_change_count"], 3); + assert_eq!(pairs[1]["file_a_commits"], 3); + assert_eq!(pairs[1]["file_b_commits"], 4); + assert_eq!(pairs[1]["coupling_ratio"], 0.75); + assert_eq!(pairs[1]["has_direct_import"], true); + + let strict_ratio = repo.run_json("coupling", &["--min-ratio", "0.9"]); + let strict_pairs = strict_ratio["pairs"].as_array().expect("strict pairs"); + assert_eq!(strict_pairs.len(), 1); + assert_eq!(strict_pairs[0]["file_a"], "src/billing/invoice.ts"); + + let high_min_count = repo.run_json("coupling", &["--min-co-changes", "4"]); + let high_pairs = high_min_count["pairs"].as_array().expect("high pairs"); + assert_eq!(high_pairs.len(), 1); + assert_eq!(high_pairs[0]["file_a"], "src/billing/invoice.ts"); +} + +#[test] +fn coupling_excludes_bulk_commits_above_max_commit_files_ceiling() { + let repo = HistoryFixture::init(); + for step in 1..=4 { + let files: Vec<(&str, String)> = vec![ + ("src/bulk_a.ts", format!("export const a = {step};\n")), + ("src/bulk_b.ts", format!("export const b = {step};\n")), + ("src/bulk_c.ts", format!("export const c = {step};\n")), + ("src/bulk_d.ts", format!("export const d = {step};\n")), + ("src/bulk_e.ts", format!("export const e = {step};\n")), + ("src/bulk_f.ts", format!("export const f = {step};\n")), + ]; + repo.save_and_commit( + &files, + &format!("bulk format {step}"), + &format!("2026-05-0{step}T10:00:00Z"), + ); + } + commit_const_pair( + &repo, + ("src/real_x.ts", "x"), + ("src/real_y.ts", "y"), + 3, + "1", + ); + + let filtered = repo.run_json("coupling", &["--max-commit-files", "4"]); + assert_eq!(filtered["commits_analyzed"], 7); + assert_eq!(filtered["commits_excluded_by_bulk_limit"], 4); + assert_eq!(filtered["max_commit_files"], 4); + let pairs = filtered["pairs"].as_array().expect("filtered pairs"); + assert_eq!(pairs.len(), 1); + assert_eq!(pairs[0]["file_a"], "src/real_x.ts"); + assert_eq!(pairs[0]["file_b"], "src/real_y.ts"); + assert_eq!(pairs[0]["co_change_count"], 3); + + let wide = repo.run_json("coupling", &["--max-commit-files", "10"]); + assert_eq!(wide["commits_excluded_by_bulk_limit"], 0); + let wide_pairs = wide["pairs"].as_array().expect("wide pairs"); + assert!( + wide_pairs + .iter() + .any(|p| p["file_a"] == "src/bulk_a.ts" && p["file_b"] == "src/bulk_b.ts"), + "expected bulk pair when ceiling allows it: {wide_pairs:?}" + ); +} + +#[test] +fn coupling_focuses_on_production_by_default_and_includes_tests_with_flag() { + let repo = HistoryFixture::init(); + for step in 1..=4 { + repo.save_and_commit( + &[ + ("src/calc.ts", format!("export const calc = {step};\n")), + ( + "src/calc.test.ts", + format!( + "import {{ calc }} from \"./calc\";\nexport const checked = calc + {step};\n" + ), + ), + ], + &format!("calc and test {step}"), + &format!("2026-05-0{step}T10:00:00Z"), + ); + } + commit_const_pair( + &repo, + ("src/calc.ts", "calc"), + ("src/audit.ts", "audit"), + 3, + "1", + ); + + let prod_only = repo.run_json("coupling", &[]); + assert_eq!(prod_only["source_sets"], serde_json::json!(["production"])); + let prod_pairs = prod_only["pairs"].as_array().expect("prod pairs"); + assert_eq!(prod_pairs.len(), 1); + assert_eq!(prod_pairs[0]["file_a"], "src/audit.ts"); + assert_eq!(prod_pairs[0]["file_b"], "src/calc.ts"); + assert_eq!(prod_pairs[0]["has_direct_import"], false); + + let with_tests = repo.run_json("coupling", &["--include-tests"]); + assert_eq!( + with_tests["source_sets"], + serde_json::json!(["production", "test"]) + ); + let test_pairs = with_tests["pairs"].as_array().expect("with_tests pairs"); + assert!( + test_pairs.iter().any(|p| { + p["file_a"] == "src/calc.test.ts" + && p["file_b"] == "src/calc.ts" + && p["has_direct_import"] == true + }), + "expected calc.test.ts + calc.ts pair with --include-tests: {test_pairs:?}" + ); + assert!( + test_pairs + .iter() + .any(|p| p["file_a"] == "src/audit.ts" && p["file_b"] == "src/calc.ts"), + "expected production pair to remain with --include-tests: {test_pairs:?}" + ); +} + +#[test] +fn coupling_renders_all_formats_and_handles_shallow_non_git_and_invalid_args() { + let repo = HistoryFixture::init(); + commit_const_pair( + &repo, + ("src/alpha.ts", "alpha"), + ("src/beta.ts", "beta"), + 3, + "0", + ); + + assert_format_contains( + &repo, + "coupling", + "text", + &["src/alpha.ts", "src/beta.ts", "hidden"], + ); + assert_format_contains( + &repo, + "coupling", + "toon", + &["commits_analyzed: 3", "src/alpha.ts", "src/beta.ts"], + ); + assert_format_contains( + &repo, + "coupling", + "markdown", + &["# codeint coupling", "`src/alpha.ts`", "`src/beta.ts`"], + ); + + assert_eq!( + repo.run("coupling", &["--since", "30d", "--commits", "5"]) + .status + .code(), + Some(2) + ); + assert_eq!( + repo.run("coupling", &["--min-ratio", "1.5"]).status.code(), + Some(2) + ); + assert_eq!( + repo.run("coupling", &["--max-commit-files", "0"]) + .status + .code(), + Some(2) + ); + + assert_shallow_and_non_git(&repo, "coupling", &["--min-co-changes", "2"]); +} diff --git a/crates/cli/tests/history_support/mod.rs b/crates/cli/tests/history_support/mod.rs new file mode 100644 index 0000000..ceb816b --- /dev/null +++ b/crates/cli/tests/history_support/mod.rs @@ -0,0 +1,164 @@ +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +use serde_json::Value; +use tempfile::TempDir; + +pub(crate) struct HistoryFixture(TempDir); + +impl HistoryFixture { + pub(crate) fn init() -> HistoryFixture { + let dir = tempfile::tempdir().expect("tempdir"); + run_git( + dir.path(), + &["init", "-q", "-b", "main"], + "2026-05-01T10:00:00Z", + ); + HistoryFixture(dir) + } + + fn root(&self) -> &Path { + self.0.path() + } + + pub(crate) fn save_and_commit(&self, files: &[(&str, String)], msg: &str, when: &str) { + for (rel, content) in files { + let dest = self.root().join(rel); + fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir"); + fs::write(dest, content).expect("write"); + } + run_git(self.root(), &["add", "-A"], when); + run_git(self.root(), &["commit", "-q", "-m", msg], when); + } + + pub(crate) fn run(&self, subcommand: &str, extra: &[&str]) -> Output { + exec_subcommand(self.root(), subcommand, extra) + } + + pub(crate) fn run_json(&self, subcommand: &str, extra: &[&str]) -> Value { + let args: Vec<&str> = extra.iter().copied().chain(["--format", "json"]).collect(); + let out = self.run(subcommand, &args); + assert_eq!( + out.status.code(), + Some(0), + "{subcommand} stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + serde_json::from_slice(&out.stdout).expect("valid JSON report") + } + + fn shallow_clone_of(&self, depth: &str) -> HistoryFixture { + let shallow = HistoryFixture::init(); + let url = format!("file://{}", self.root().display()); + run_git( + shallow.root(), + &["fetch", "-q", "--depth", depth, &url, "main"], + "2026-05-05T10:00:00Z", + ); + run_git( + shallow.root(), + &["reset", "-q", "--hard", "FETCH_HEAD"], + "2026-05-05T10:00:00Z", + ); + shallow + } +} + +fn run_git(cwd: &Path, args: &[&str], when: &str) { + let vars = [ + ("GIT_CONFIG_GLOBAL", "/dev/null"), + ("GIT_CONFIG_NOSYSTEM", "1"), + ("GIT_AUTHOR_NAME", "History"), + ("GIT_AUTHOR_EMAIL", "history@example.invalid"), + ("GIT_COMMITTER_NAME", "History"), + ("GIT_COMMITTER_EMAIL", "history@example.invalid"), + ("GIT_AUTHOR_DATE", when), + ("GIT_COMMITTER_DATE", when), + ]; + let out = Command::new("git") + .args(args) + .current_dir(cwd) + .envs(vars) + .output() + .expect("git"); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); +} + +fn exec_subcommand(cwd: &Path, subcommand: &str, extra: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .arg(subcommand) + .args(extra) + .current_dir(cwd) + .output() + .expect("run codeint") +} + +pub(crate) fn assert_no_blended_score_keys(value: &Value) { + let forbidden = ["score", "index", "grade", "rating", "hotspot_score"]; + match value { + Value::Object(map) => { + for (k, v) in map { + let lower = k.to_ascii_lowercase(); + for word in forbidden { + assert!( + !lower.contains(word), + "ADR 0003 violation: unexpected blended key {k:?}" + ); + } + assert_no_blended_score_keys(v); + } + } + Value::Array(items) => items.iter().for_each(assert_no_blended_score_keys), + _ => {} + } +} + +pub(crate) fn assert_format_contains( + repo: &HistoryFixture, + subcommand: &str, + format: &str, + needles: &[&str], +) { + let out = repo.run(subcommand, &["--format", format]); + assert_eq!( + out.status.code(), + Some(0), + "{subcommand} {format} stderr: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8_lossy(&out.stdout); + for needle in needles { + assert!( + stdout.contains(needle), + "{subcommand} {format} missing {needle:?}: {stdout}" + ); + } +} + +pub(crate) fn assert_shallow_and_non_git( + origin: &HistoryFixture, + subcommand: &str, + shallow_args: &[&str], +) { + let shallow = origin.shallow_clone_of("2"); + let report = shallow.run_json(subcommand, shallow_args); + assert_eq!(report["shallow"], true); + assert_eq!(report["commits_analyzed"], 2); + let warning = report["warning"].as_str().expect("shallow clone warning"); + assert!(warning.contains("shallow"), "warning: {warning}"); + assert!(warning.contains("--unshallow"), "warning: {warning}"); + + let non_git = tempfile::tempdir().expect("non-git tempdir"); + let out = exec_subcommand(non_git.path(), subcommand, &[]); + assert_eq!(out.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("not inside a Git repository"), + "stderr: {stderr}" + ); +} diff --git a/crates/cli/tests/mcp.rs b/crates/cli/tests/mcp.rs index 09a0f69..6d99889 100644 --- a/crates/cli/tests/mcp.rs +++ b/crates/cli/tests/mcp.rs @@ -77,7 +77,10 @@ fn mcp_initialize_list_and_call_tools() { assert_eq!(responses[0]["result"]["serverInfo"]["name"], "codeint"); let tools = responses[1]["result"]["tools"].as_array().unwrap(); let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["check", "diff", "trend", "guard", "churn"]); + assert_eq!( + names, + ["check", "diff", "trend", "guard", "churn", "coupling"] + ); assert_eq!(responses[2]["result"]["isError"], false); let check_payload: Value = serde_json::from_str( @@ -215,6 +218,17 @@ fn tool_call(id: u64, name: &str, arguments: Value) -> Value { }) } +fn parse_tool_ok(response: &Value) -> Value { + assert_eq!(response["result"]["isError"], false); + serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap() +} + +fn assert_tool_err_contains(response: &Value, needle: &str) { + assert_eq!(response["result"]["isError"], true); + let err_text = response["result"]["content"][0]["text"].as_str().unwrap(); + assert!(err_text.contains(needle), "err: {err_text}"); +} + #[test] fn mcp_churn_tool_reports_file_churn_and_handles_non_git_directory() { let repo = init_sample_repo(); @@ -231,23 +245,73 @@ fn mcp_churn_tool_reports_file_churn_and_handles_non_git_directory() { ], ); assert_eq!(responses.len(), 2); - assert_eq!(responses[0]["result"]["isError"], false); - let payload: Value = serde_json::from_str( - responses[0]["result"]["content"][0]["text"] - .as_str() - .unwrap(), - ) - .unwrap(); + let payload = parse_tool_ok(&responses[0]); assert_eq!(payload["commits_analyzed"], 1); assert_eq!(payload["shallow"], false); assert!(payload.get("score").is_none()); + assert_tool_err_contains(&responses[1], "not inside a Git repository"); +} - assert_eq!(responses[1]["result"]["isError"], true); - let err_text = responses[1]["result"]["content"][0]["text"] - .as_str() +#[test] +fn mcp_coupling_tool_reports_co_change_pairs_bulk_exclusion_and_errors() { + let repo = init_sample_repo(); + let commit_pair = |step: usize, when: &str| { + std::fs::create_dir_all(repo.path().join("src")).unwrap(); + std::fs::write( + repo.path().join("src/a.ts"), + format!("export const a = {step};\n"), + ) .unwrap(); - assert!( - err_text.contains("not inside a Git repository"), - "err: {err_text}" + std::fs::write( + repo.path().join("src/b.ts"), + format!("export const b = {step};\n"), + ) + .unwrap(); + for args in [vec!["add", "-A"], vec!["commit", "-q", "-m", "pair"]] { + let status = Command::new("git") + .args(&args) + .current_dir(repo.path()) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .env("GIT_AUTHOR_DATE", when) + .env("GIT_COMMITTER_DATE", when) + .status() + .unwrap(); + assert!(status.success(), "git {args:?} failed"); + } + }; + commit_pair(1, "2026-05-01T10:00:00Z"); + commit_pair(2, "2026-05-02T10:00:00Z"); + commit_pair(3, "2026-05-03T10:00:00Z"); + + let non_git = TempDir::new().unwrap(); + let responses = send_mcp_requests( + repo.path(), + &[ + tool_call( + 1, + "coupling", + json!({"commits": 10, "max_commit_files": 20, "min_co_changes": 3, "min_ratio": 0.5}), + ), + tool_call( + 2, + "coupling", + json!({"path": non_git.path().to_string_lossy()}), + ), + ], ); + assert_eq!(responses.len(), 2); + let payload = parse_tool_ok(&responses[0]); + assert_eq!(payload["commits_analyzed"], 4); + assert_eq!(payload["pairs"][0]["file_a"], "src/a.ts"); + assert_eq!(payload["pairs"][0]["file_b"], "src/b.ts"); + assert_eq!(payload["pairs"][0]["co_change_count"], 3); + assert_eq!(payload["pairs"][0]["coupling_ratio"], 1.0); + assert_eq!(payload["pairs"][0]["has_direct_import"], false); + assert!(payload.get("score").is_none()); + assert_tool_err_contains(&responses[1], "not inside a Git repository"); } diff --git a/crates/config/src/coupling.rs b/crates/config/src/coupling.rs new file mode 100644 index 0000000..adf739d --- /dev/null +++ b/crates/config/src/coupling.rs @@ -0,0 +1,88 @@ +use std::fmt; +use std::str::FromStr; + +use crate::ChurnWindow; + +pub const DEFAULT_MAX_COMMIT_FILES: usize = 50; +pub const DEFAULT_MIN_CO_CHANGES: usize = 3; +pub const DEFAULT_MIN_COUPLING_RATIO: f64 = 0.3; + +#[derive(Debug, Clone, Copy)] +pub struct CouplingRatio(f64); + +impl CouplingRatio { + pub fn new(value: f64) -> Result { + if value.is_finite() && (0.0..=1.0).contains(&value) { + let normalized = if value == 0.0 { 0.0 } else { value }; + Ok(CouplingRatio(normalized)) + } else { + Err(CouplingRatioError { + text: value.to_string(), + }) + } + } + + pub fn value(self) -> f64 { + self.0 + } +} + +impl Default for CouplingRatio { + fn default() -> CouplingRatio { + CouplingRatio(DEFAULT_MIN_COUPLING_RATIO) + } +} + +impl PartialEq for CouplingRatio { + fn eq(&self, other: &Self) -> bool { + self.0.to_bits() == other.0.to_bits() + } +} + +impl Eq for CouplingRatio {} + +impl fmt::Display for CouplingRatio { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{}", self.0) + } +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{text:?} is not a coupling ratio between 0 and 1, such as 0.3")] +pub struct CouplingRatioError { + text: String, +} + +impl FromStr for CouplingRatio { + type Err = CouplingRatioError; + + fn from_str(text: &str) -> Result { + let value = text.parse::().map_err(|_| CouplingRatioError { + text: text.to_owned(), + })?; + CouplingRatio::new(value).map_err(|_| CouplingRatioError { + text: text.to_owned(), + }) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CouplingSettings { + pub window: ChurnWindow, + pub max_commit_files: usize, + pub min_co_changes: usize, + pub min_ratio: CouplingRatio, + pub include_tests: bool, +} + +impl Default for CouplingSettings { + fn default() -> CouplingSettings { + CouplingSettings { + window: ChurnWindow::default(), + max_commit_files: DEFAULT_MAX_COMMIT_FILES, + min_co_changes: DEFAULT_MIN_CO_CHANGES, + min_ratio: CouplingRatio::default(), + include_tests: false, + } + } +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 3b7b662..8c2ac09 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -9,6 +9,7 @@ mod calendar_day; mod churn; mod codeint_json; mod config_error; +mod coupling; mod regression_limits; mod result_cache_folder; @@ -24,6 +25,10 @@ pub use codeint_json::{ write_starter_configuration, }; pub use config_error::{ConfigurationFileError, JsonType, KeyPath, KeySegment}; +pub use coupling::{ + CouplingRatio, CouplingRatioError, CouplingSettings, DEFAULT_MAX_COMMIT_FILES, + DEFAULT_MIN_CO_CHANGES, DEFAULT_MIN_COUPLING_RATIO, +}; pub use regression_limits::{NewFindingsRule, RatioRise, RegressionLimit, RegressionLimits}; const DEFAULT_PLUGIN_DOWNLOAD_TIMEOUT_SECONDS: u64 = 60; @@ -168,6 +173,14 @@ pub enum Command { format: ChurnFormat, plugin_host: PluginHostConfig, }, + Coupling { + folder: PathBuf, + settings: CouplingSettings, + destination: ReportDestination, + findings: FindingsShown, + format: ChurnFormat, + plugin_host: PluginHostConfig, + }, } #[derive(Debug)] @@ -258,7 +271,7 @@ enum CommandArguments { version: Option, }, #[command( - about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, trend, guard, and churn tools" + about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, trend, guard, churn, and coupling tools" )] Mcp, #[command( @@ -282,38 +295,77 @@ enum CommandArguments { about = "Rank eroded and duplicated files alongside their Git commit churn independently per Metric" )] Churn { + #[command(flatten)] + history: HistoryReportArguments, + }, + #[command( + about = "Detect pairs of files that repeatedly change together in the same commits and flag direct runtime imports" + )] + Coupling { + #[command(flatten)] + history: HistoryReportArguments, #[arg( - long, - value_name = "WINDOW", - conflicts_with = "commits", - help = "Lookback window in days (such as 90d) or a UTC date (YYYY-MM-DD); defaults to 90d" + long = "max-commit-files", + value_name = "COUNT", + default_value_t = std::num::NonZeroUsize::new(DEFAULT_MAX_COMMIT_FILES).expect("non-zero default"), + help = "Exclude commits touching more than this many files from co-change pair accumulation" )] - since: Option, + max_commit_files: std::num::NonZeroUsize, #[arg( - long, + long = "min-co-changes", value_name = "COUNT", - conflicts_with = "since", - help = "Walk at most this many main-line commits from HEAD" + default_value_t = std::num::NonZeroUsize::new(DEFAULT_MIN_CO_CHANGES).expect("non-zero default"), + help = "Report only pairs that changed together in at least this many commits" )] - commits: Option, + min_co_changes: std::num::NonZeroUsize, #[arg( - long, - value_name = "FILE", - help = "Write the report to this file instead of standard output" + long = "min-ratio", + value_name = "RATIO", + default_value_t = CouplingRatio::default(), + help = "Report only pairs whose coupling ratio is at least this value between 0 and 1" )] - output: Option, - #[arg(long, help = "List every Finding instead of the 20 worst per Metric")] - all: bool, + min_ratio: CouplingRatio, #[arg( - long, - value_enum, - default_value_t = ChurnFormat::Toon, - help = "The format of the report" + long = "include-tests", + help = "Include Test Source set files alongside Production files" )] - format: ChurnFormat, + include_tests: bool, }, } +#[derive(Debug, clap::Args)] +struct HistoryReportArguments { + #[arg( + long, + value_name = "WINDOW", + conflicts_with = "commits", + help = "Lookback window in days (such as 90d) or a UTC date (YYYY-MM-DD); defaults to 90d" + )] + since: Option, + #[arg( + long, + value_name = "COUNT", + conflicts_with = "since", + help = "Walk at most this many main-line commits from HEAD" + )] + commits: Option, + #[arg( + long, + value_name = "FILE", + help = "Write the report to this file instead of standard output" + )] + output: Option, + #[arg(long, help = "List every Finding instead of the 20 worst per Metric")] + all: bool, + #[arg( + long, + value_enum, + default_value_t = ChurnFormat::Toon, + help = "The format of the report" + )] + format: ChurnFormat, +} + #[derive(Debug, clap::Args)] struct ReportArguments { #[arg( @@ -372,35 +424,69 @@ fn build_command( target: path, format, }), - CommandArguments::Churn { - since, - commits, - output, - all, - format, - } => build_churn_command(current_folder, since, commits, output, all, format), + CommandArguments::Churn { history } => build_churn_command(current_folder, history), + CommandArguments::Coupling { + history, + max_commit_files, + min_co_changes, + min_ratio, + include_tests, + } => build_coupling_command( + current_folder, + history, + max_commit_files.get(), + min_co_changes.get(), + min_ratio, + include_tests, + ), } } -fn build_churn_command( - current_folder: &Path, +fn resolve_churn_window( since: Option, commits: Option, - output: Option, - all: bool, - format: ChurnFormat, -) -> Result { - let window = match (since, commits) { +) -> ChurnWindow { + match (since, commits) { (Some(since), None) => ChurnWindow::from(since), (None, Some(count)) => ChurnWindow::Commits(count.get()), _ => ChurnWindow::default(), - }; + } +} + +fn build_churn_command( + current_folder: &Path, + history: HistoryReportArguments, +) -> Result { Ok(Command::Churn { folder: current_folder.to_path_buf(), - window, - destination: report_destination(current_folder, output)?, - findings: findings_shown(all), - format, + window: resolve_churn_window(history.since, history.commits), + destination: report_destination(current_folder, history.output)?, + findings: findings_shown(history.all), + format: history.format, + plugin_host: plugin_host_config_of_this_process(current_folder), + }) +} + +fn build_coupling_command( + current_folder: &Path, + history: HistoryReportArguments, + max_commit_files: usize, + min_co_changes: usize, + min_ratio: CouplingRatio, + include_tests: bool, +) -> Result { + Ok(Command::Coupling { + folder: current_folder.to_path_buf(), + settings: CouplingSettings { + window: resolve_churn_window(history.since, history.commits), + max_commit_files, + min_co_changes, + min_ratio, + include_tests, + }, + destination: report_destination(current_folder, history.output)?, + findings: findings_shown(history.all), + format: history.format, plugin_host: plugin_host_config_of_this_process(current_folder), }) } diff --git a/crates/git/src/churn.rs b/crates/git/src/churn.rs index d4c8566..6ab32ce 100644 --- a/crates/git/src/churn.rs +++ b/crates/git/src/churn.rs @@ -23,6 +23,22 @@ pub struct FileChurnSummary { pub touches_by_file: BTreeMap, } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CoChangeSummary { + pub commits_analyzed: usize, + pub commits_excluded_by_bulk_limit: usize, + pub shallow: bool, + pub truncated_by_shallow_boundary: bool, + pub touches_by_file: BTreeMap, + pub co_changes: BTreeMap<(RepoPath, RepoPath), usize>, +} + +struct WalkOutcome { + commits_analyzed: usize, + shallow: bool, + truncated_by_shallow_boundary: bool, +} + enum EffectiveRange { Commits(usize), Since(i64), @@ -49,6 +65,62 @@ impl EffectiveRange { impl Repository { pub fn file_churn(&self, range: ChurnRange) -> Result { + let mut touches_by_file: BTreeMap = BTreeMap::new(); + let outcome = self.walk_touched_commits(range, |touched| { + for path in touched { + *touches_by_file.entry(path).or_insert(0) += 1; + } + })?; + Ok(FileChurnSummary { + commits_analyzed: outcome.commits_analyzed, + shallow: outcome.shallow, + truncated_by_shallow_boundary: outcome.truncated_by_shallow_boundary, + touches_by_file, + }) + } + + pub fn co_change_coupling( + &self, + range: ChurnRange, + max_commit_files: usize, + allowed_paths: &BTreeSet, + ) -> Result { + let mut commits_excluded_by_bulk_limit = 0usize; + let mut touches_by_file: BTreeMap = BTreeMap::new(); + let mut co_changes: BTreeMap<(RepoPath, RepoPath), usize> = BTreeMap::new(); + let outcome = self.walk_touched_commits(range, |touched| { + if touched.len() > max_commit_files { + commits_excluded_by_bulk_limit += 1; + return; + } + let measured: Vec = touched + .into_iter() + .filter(|path| allowed_paths.contains(path)) + .collect(); + for path in &measured { + *touches_by_file.entry(path.clone()).or_insert(0) += 1; + } + for (index, left) in measured.iter().enumerate() { + for right in &measured[index + 1..] { + *co_changes.entry((left.clone(), right.clone())).or_insert(0) += 1; + } + } + })?; + Ok(CoChangeSummary { + commits_analyzed: outcome.commits_analyzed, + commits_excluded_by_bulk_limit, + shallow: outcome.shallow, + truncated_by_shallow_boundary: outcome.truncated_by_shallow_boundary, + touches_by_file, + co_changes, + }) + } + + fn walk_touched_commits( + &self, + range: ChurnRange, + on_commit: impl FnMut(BTreeSet), + ) -> Result { let head = self.repository.head_id().map_err(GitError::NoHistory)?; let shallow_boundary = self .repository @@ -73,19 +145,25 @@ impl Repository { })? .seconds; let effective = EffectiveRange::from_head(range, head_time); - self.walk_churn(head_id, &effective, shallow, shallow_boundary.as_ref()) + self.walk_commits( + head_id, + &effective, + shallow, + shallow_boundary.as_ref(), + on_commit, + ) } - fn walk_churn( + fn walk_commits( &self, start: ObjectId, effective: &EffectiveRange, shallow: bool, shallow_boundary: Option<&gix::shallow::Commits>, - ) -> Result { + mut on_commit: impl FnMut(BTreeSet), + ) -> Result { let mut commits_analyzed = 0usize; let mut truncated_by_shallow_boundary = false; - let mut touches_by_file: BTreeMap = BTreeMap::new(); let mut next = Some(start); while let Some(id) = next { let commit = CommitId(id); @@ -109,16 +187,13 @@ impl Repository { found.parent_ids().next().map(|parent| parent.detach()) }; let touched = self.touched_files_in_commit(commit, &found, parent_id)?; - for path in touched { - *touches_by_file.entry(path).or_insert(0) += 1; - } + on_commit(touched); next = parent_id; } - Ok(FileChurnSummary { + Ok(WalkOutcome { commits_analyzed, shallow, truncated_by_shallow_boundary, - touches_by_file, }) } diff --git a/crates/git/src/lib.rs b/crates/git/src/lib.rs index 5c2b739..2cf476e 100644 --- a/crates/git/src/lib.rs +++ b/crates/git/src/lib.rs @@ -13,7 +13,7 @@ mod churn; mod history; mod result_cache; -pub use churn::{ChurnRange, FileChurnSummary}; +pub use churn::{ChurnRange, CoChangeSummary, FileChurnSummary}; pub use history::{CommitRange, HistoryCommit}; pub use result_cache::{ResultCache, ResultCacheError}; diff --git a/crates/report/src/churn.rs b/crates/report/src/churn.rs index 58437a3..50b460a 100644 --- a/crates/report/src/churn.rs +++ b/crates/report/src/churn.rs @@ -135,12 +135,7 @@ impl ChurnReport { } pub fn render(&self, format: ChurnFormat) -> Result { - match format { - ChurnFormat::Text => Ok(text::render(self)), - ChurnFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), - ChurnFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), - ChurnFormat::Markdown => Ok(markdown::render(self)), - } + render_churn_format(self, format, text::render, markdown::render) } fn named_source_sets(&self) -> impl Iterator { @@ -271,6 +266,20 @@ impl DuplicationChurnSection { } } +pub(crate) fn render_churn_format( + report: &T, + format: ChurnFormat, + render_text: impl FnOnce(&T) -> String, + render_markdown: impl FnOnce(&T) -> String, +) -> Result { + match format { + ChurnFormat::Text => Ok(render_text(report)), + ChurnFormat::Toon => toon_format::encode_default(report).map_err(ReportError::Toon), + ChurnFormat::Json => serde_json::to_string_pretty(report).map_err(ReportError::Json), + ChurnFormat::Markdown => Ok(render_markdown(report)), + } +} + fn compare_duplicated_rows(left: &DuplicatedChurnFile, right: &DuplicatedChurnFile) -> Ordering { right .commits diff --git a/crates/report/src/coupling.rs b/crates/report/src/coupling.rs new file mode 100644 index 0000000..e28dae3 --- /dev/null +++ b/crates/report/src/coupling.rs @@ -0,0 +1,168 @@ +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet}; + +use codeint_config::{ChurnFormat, ChurnWindow, FindingsShown}; +use codeint_model::{CodeModel, ImportResolution, RepoPath}; +use serde::Serialize; + +use crate::churn::render_churn_format; +use crate::{Decimal, FindingKind, Findings, ReportError}; + +mod markdown; +mod text; + +const SHALLOW_WARNING: &str = "Repository is a shallow clone; co-change coupling counts stop at the shallow boundary and may be incomplete. Fetch full history with `git fetch --unshallow`."; + +pub struct CouplingHistoryInput { + pub window: ChurnWindow, + pub commits_analyzed: usize, + pub commits_excluded_by_bulk_limit: usize, + pub max_commit_files: usize, + pub min_co_changes: usize, + pub min_ratio: f64, + pub include_tests: bool, + pub shallow: bool, + pub touches_by_file: BTreeMap, + pub co_changes: BTreeMap<(RepoPath, RepoPath), usize>, +} + +#[derive(Debug, Serialize)] +pub struct CouplingReport { + window: String, + commits_analyzed: usize, + commits_excluded_by_bulk_limit: usize, + max_commit_files: usize, + min_co_changes: usize, + min_ratio: Decimal, + source_sets: Vec<&'static str>, + shallow: bool, + #[serde(skip_serializing_if = "Option::is_none")] + warning: Option, + #[serde(flatten)] + pairs: Findings, +} + +#[derive(Debug, Serialize)] +struct CoupledPairRow { + file_a: String, + file_b: String, + co_change_count: usize, + file_a_commits: usize, + file_b_commits: usize, + coupling_ratio: Decimal, + has_direct_import: bool, +} + +impl FindingKind for CoupledPairRow { + const LIST_KEY: &'static str = "pairs"; + const LEFT_OUT_KEY: &'static str = "pairs_left_out"; +} + +impl CouplingReport { + pub fn summarize( + model: &CodeModel, + history: &CouplingHistoryInput, + findings: FindingsShown, + ) -> CouplingReport { + let direct_imports = direct_import_pairs(model); + let min_ratio = Decimal::rounded(history.min_ratio); + let mut rows: Vec = history + .co_changes + .iter() + .filter_map(|((file_a, file_b), &co_change_count)| { + build_pair_row( + file_a, + file_b, + co_change_count, + history, + min_ratio.0, + &direct_imports, + ) + }) + .collect(); + rows.sort_by(compare_pairs); + let source_sets = if history.include_tests { + vec!["production", "test"] + } else { + vec!["production"] + }; + let warning = history.shallow.then(|| SHALLOW_WARNING.to_owned()); + CouplingReport { + window: history.window.to_string(), + commits_analyzed: history.commits_analyzed, + commits_excluded_by_bulk_limit: history.commits_excluded_by_bulk_limit, + max_commit_files: history.max_commit_files, + min_co_changes: history.min_co_changes, + min_ratio, + source_sets, + shallow: history.shallow, + warning, + pairs: Findings::worst_first(rows.into_iter(), findings), + } + } + + pub fn render(&self, format: ChurnFormat) -> Result { + render_churn_format(self, format, text::render, markdown::render) + } +} + +fn direct_import_pairs(model: &CodeModel) -> BTreeSet<(RepoPath, RepoPath)> { + let mut edges = BTreeSet::new(); + for import in &model.runtime_imports { + if let ImportResolution::Resolved(target) = &import.resolution { + edges.insert(ordered_pair(&import.importer, target)); + } + } + edges +} + +fn ordered_pair(left: &RepoPath, right: &RepoPath) -> (RepoPath, RepoPath) { + if left <= right { + (left.clone(), right.clone()) + } else { + (right.clone(), left.clone()) + } +} + +fn build_pair_row( + file_a: &RepoPath, + file_b: &RepoPath, + co_change_count: usize, + history: &CouplingHistoryInput, + min_ratio: f64, + direct_imports: &BTreeSet<(RepoPath, RepoPath)>, +) -> Option { + if co_change_count < history.min_co_changes { + return None; + } + let file_a_commits = history.touches_by_file.get(file_a).copied().unwrap_or(0); + let file_b_commits = history.touches_by_file.get(file_b).copied().unwrap_or(0); + let union = file_a_commits + file_b_commits - co_change_count; + if union == 0 { + return None; + } + let coupling_ratio = Decimal::rounded(co_change_count as f64 / union as f64); + if coupling_ratio.0 < min_ratio { + return None; + } + let has_direct_import = direct_imports.contains(&ordered_pair(file_a, file_b)); + Some(CoupledPairRow { + file_a: file_a.to_string(), + file_b: file_b.to_string(), + co_change_count, + file_a_commits, + file_b_commits, + coupling_ratio, + has_direct_import, + }) +} + +fn compare_pairs(left: &CoupledPairRow, right: &CoupledPairRow) -> Ordering { + right + .co_change_count + .cmp(&left.co_change_count) + .then_with(|| right.coupling_ratio.0.total_cmp(&left.coupling_ratio.0)) + .then_with(|| left.has_direct_import.cmp(&right.has_direct_import)) + .then_with(|| left.file_a.cmp(&right.file_a)) + .then_with(|| left.file_b.cmp(&right.file_b)) +} diff --git a/crates/report/src/coupling/markdown.rs b/crates/report/src/coupling/markdown.rs new file mode 100644 index 0000000..bd49ac6 --- /dev/null +++ b/crates/report/src/coupling/markdown.rs @@ -0,0 +1,70 @@ +use super::CouplingReport; +use crate::markdown::{code, table}; + +const TITLE: &str = "# codeint coupling"; + +pub(super) fn render(report: &CouplingReport) -> String { + let mut blocks = vec![TITLE.to_owned(), summary_line(report)]; + if let Some(warning) = &report.warning { + blocks.push(format!("> Warning: {warning}")); + } + let rows: Vec> = report + .pairs + .listed + .iter() + .map(|row| { + vec![ + code(&row.file_a), + code(&row.file_b), + row.co_change_count.to_string(), + row.coupling_ratio.0.to_string(), + row.file_a_commits.to_string(), + row.file_b_commits.to_string(), + if row.has_direct_import { + "yes".to_owned() + } else { + "no (hidden)".to_owned() + }, + ] + }) + .collect(); + if rows.is_empty() { + blocks.push("No coupled file pairs met the configured limits.".to_owned()); + } else { + blocks.push(table( + &[ + "File A", + "File B", + "Co-changes", + "Coupling ratio", + "File A commits", + "File B commits", + "Direct import", + ], + rows, + )); + } + if report.pairs.left_out > 0 { + blocks.push(format!( + "{} additional coupled pairs omitted (pass `--all` to show every pair).", + report.pairs.left_out + )); + } + blocks.join("\n\n") +} + +fn summary_line(report: &CouplingReport) -> String { + let noun = if report.commits_analyzed == 1 { + "commit" + } else { + "commits" + }; + format!( + "codeint analyzed {} {noun} (window: `{}`, excluded bulk commits > {} files: {}, Source sets: `{}`).", + report.commits_analyzed, + report.window, + report.max_commit_files, + report.commits_excluded_by_bulk_limit, + report.source_sets.join(", ") + ) +} diff --git a/crates/report/src/coupling/text.rs b/crates/report/src/coupling/text.rs new file mode 100644 index 0000000..18801ff --- /dev/null +++ b/crates/report/src/coupling/text.rs @@ -0,0 +1,49 @@ +use std::fmt::Write as _; + +use super::CouplingReport; + +pub(super) fn render(report: &CouplingReport) -> String { + let mut out = String::new(); + let _ = writeln!( + out, + "codeint coupling (window: {}, commits analyzed: {}, excluded bulk commits: {}, max_commit_files: {}, source_sets: {})", + report.window, + report.commits_analyzed, + report.commits_excluded_by_bulk_limit, + report.max_commit_files, + report.source_sets.join(", ") + ); + if let Some(warning) = &report.warning { + let _ = writeln!(out, "warning: {warning}"); + } + if report.pairs.listed.is_empty() { + let _ = writeln!( + out, + " none (min_co_changes={}, min_ratio={})", + report.min_co_changes, report.min_ratio.0 + ); + return out.trim_end_matches('\n').to_owned(); + } + for row in &report.pairs.listed { + let edge = if row.has_direct_import { + "direct" + } else { + "hidden" + }; + let _ = writeln!( + out, + " {} <-> {} co_changes={} ratio={} commits={}/{} import={}", + row.file_a, + row.file_b, + row.co_change_count, + row.coupling_ratio.0, + row.file_a_commits, + row.file_b_commits, + edge + ); + } + if report.pairs.left_out > 0 { + let _ = writeln!(out, " ... {} more", report.pairs.left_out); + } + out.trim_end_matches('\n').to_owned() +} diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index 71a95f4..671304f 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -19,6 +19,7 @@ use serde::ser::SerializeMap; use serde::{Deserialize, Serialize, Serializer}; mod churn; +mod coupling; mod diff; mod guard; mod markdown; @@ -29,6 +30,7 @@ mod tests; mod trend; pub use churn::{ChurnHistoryInput, ChurnReport}; +pub use coupling::{CouplingHistoryInput, CouplingReport}; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use measurement::CommitMeasurement; diff --git a/docs/reference.md b/docs/reference.md index ce89aa8..1f2aa3b 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -28,9 +28,10 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `trend` | Measure each commit of the main line and print each Metric over time; see [`codeint trend`](#codeint-trend) | | `init` | Write a starter `codeint.json`; see [`codeint init`](#codeint-init) | | `update` | Update a standalone codeint binary in place from GitHub Releases; see [`codeint update`](#codeint-update) | -| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, `guard`, and `churn` tools; see [`codeint mcp`](#codeint-mcp) | +| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, `guard`, `churn`, and `coupling` tools; see [`codeint mcp`](#codeint-mcp) | | `guard` | Show the architectural boundary zone, allowed and denied target zones, `public_files` constraints, and allowed importers for a file path; see [`codeint guard`](#codeint-guard) | | `churn` | Rank eroded and duplicated files alongside their Git commit churn independently per Metric; see [`codeint churn`](#codeint-churn) | +| `coupling` | Detect pairs of files that repeatedly change together in the same commits and flag direct runtime imports; see [`codeint coupling`](#codeint-coupling) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -488,7 +489,7 @@ codeint 0.5.0 is already up to date (v0.5.0) | `-h, --help` | Print the help of `codeint mcp` | `codeint mcp` runs a local Model Context Protocol (MCP) server over standard input and standard output with no open network port. -It exposes five read-only tools (`check`, `diff`, `trend`, `guard`, and `churn`) so coding agents can measure Software entropy, inspect architectural boundaries, rank high-churn eroded or duplicated files, and fix Regressions before opening a pull request. +It exposes six read-only tools (`check`, `diff`, `trend`, `guard`, `churn`, and `coupling`) so coding agents can measure Software entropy, inspect architectural boundaries, rank high-churn eroded or duplicated files, detect co-change coupling, and fix Regressions before opening a pull request. When standard input closes, the server exits with code 0: ```sh exit=0 @@ -537,6 +538,32 @@ codeint churn --format json --output churn.json codeint churn --format markdown ``` +### `codeint coupling` + +| Option | Meaning | +| ------ | ------- | +| `--since ` | Lookback window in days (such as `90d`) or a UTC date (`YYYY-MM-DD`); defaults to `90d` | +| `--commits ` | Walk at most this many main-line commits from HEAD | +| `--output ` | Write the report to this file instead of standard output | +| `--all` | List every Finding instead of the 20 worst per Metric | +| `--format ` | The format of the report: `toon`, the default, `text`, `json`, or `markdown` | +| `--max-commit-files ` | Exclude commits touching more than this many files from co-change pair accumulation; defaults to `50` | +| `--min-co-changes ` | Report only pairs that changed together in at least this many commits; defaults to `3` | +| `--min-ratio ` | Report only pairs whose coupling ratio is at least this value between 0 and 1; defaults to `0.3` | +| `--include-tests` | Include Test Source set files alongside Production files | +| `-h, --help` | Print the help of `codeint coupling` | + +`codeint coupling` walks main-line Git history natively via `gix` to find pairs of files that repeatedly change together in the same commits, excludes bulk commits above `--max-commit-files`, and flags whether each coupled pair has a direct runtime import edge. +By default it measures Production files only; pass `--include-tests` to include Test files as well. + +```sh exit=0 +codeint coupling +codeint coupling --since 90d --max-commit-files 50 --min-co-changes 3 --min-ratio 0.3 --format text +codeint coupling --commits 10 --include-tests --all --format toon +codeint coupling --format json --output coupling.json +codeint coupling --format markdown +``` + ## Exit codes | Exit code | Meaning | From 3a7d069613cfe4e34a4310897c0dc2b939a9e560 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 11:43:50 +0800 Subject: [PATCH 4/4] fix(cli): resolve CodeQL and interrogate findings on Spec #171 --- crates/cli/src/mcp.rs | 166 +++++++++++++----------- crates/cli/src/remedy.rs | 24 ++-- crates/cli/tests/churn.rs | 64 ++++++++- crates/cli/tests/coupling.rs | 77 ++++++++++- crates/cli/tests/history_support/mod.rs | 16 ++- crates/cli/tests/mcp.rs | 29 +++++ crates/config/src/codeowners.rs | 17 ++- crates/config/src/codeowners/tests.rs | 43 ++++++ crates/git/src/churn.rs | 11 +- crates/report/src/churn/markdown.rs | 73 +++++++++++ crates/report/src/coupling.rs | 15 ++- crates/report/src/coupling/text.rs | 2 +- 12 files changed, 430 insertions(+), 107 deletions(-) diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index f2ef283..95026e6 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -253,51 +253,67 @@ fn handle_tools_call( .and_then(|p| p.get("name")) .and_then(Value::as_str) .ok_or_else(|| (-32602, "Missing tool name".to_owned()))?; - let args = params.and_then(|p| p.get("arguments")); - match name { - "check" => Ok(call_check(args, ctx)), - "diff" => Ok(unwrap_tool_result(call_diff(args, ctx))), - "trend" => Ok(call_trend(args, ctx)), - "guard" => Ok(unwrap_tool_result(call_guard(args, ctx))), - "impact" => Ok(unwrap_tool_result(call_impact(args, ctx))), - "trace" => Ok(unwrap_tool_result(call_trace(args, ctx))), - "churn" => Ok(unwrap_tool_result(call_churn(args, ctx))), - "coupling" => Ok(unwrap_tool_result(call_coupling(args, ctx))), - other => Err((-32602, format!("Unknown tool: {other}"))), + let args = match parse_tool_arguments(params) { + Ok(args) => args, + Err(err) => return Ok(err), + }; + dispatch_tool(name, args, ctx) +} + +fn parse_tool_arguments(params: Option<&Value>) -> Result, Value> { + match params.and_then(|p| p.get("arguments")) { + None => Ok(None), + Some(value) if value.is_object() => Ok(Some(value)), + Some(_) => Err(tool_err("Tool arguments must be a JSON object")), } } -fn unwrap_tool_result(result: Result) -> Value { - result.unwrap_or_else(|err| err) +fn dispatch_tool( + name: &str, + args: Option<&Value>, + ctx: &ServerContext<'_>, +) -> Result { + let result = match name { + "check" => call_check(args, ctx), + "diff" => call_diff(args, ctx), + "trend" => call_trend(args, ctx), + "guard" => call_guard(args, ctx), + "impact" => call_impact(args, ctx), + "trace" => call_trace(args, ctx), + "churn" => call_churn(args, ctx), + "coupling" => call_coupling(args, ctx), + other => return Err((-32602, format!("Unknown tool: {other}"))), + }; + Ok(result.unwrap_or_else(|err| err)) } -fn call_check(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let folder = resolve_folder(args, ctx.default_folder); +fn call_check(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result { + let folder = resolve_folder(args, ctx.default_folder)?; let options = CheckOptions { - findings: parse_findings(args), + findings: parse_findings(args)?, package: parse_package(args), owner: None, plugin_host: ctx.plugin_host.clone(), }; - match check(&folder, &options) { + Ok(match check(&folder, &options) { Ok(outcome) => render_outcome( outcome.passed, outcome.failures, outcome.report.render(ReportFormat::Json), ), Err(err) => tool_err(&err.to_string()), - } + }) } fn call_diff(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result { let base_ref = required_str_arg(args, "base_ref")?; - let folder = resolve_folder(args, ctx.default_folder); + let folder = resolve_folder(args, ctx.default_folder)?; let options = DiffOptions { head_ref: args .and_then(|a| a.get("head_ref")) .and_then(Value::as_str) .map(str::to_owned), - findings: parse_findings(args), + findings: parse_findings(args)?, package: parse_package(args), owner: None, result_cache: ctx.result_cache.clone(), @@ -334,8 +350,8 @@ fn render_outcome( fn render_json_tool( result: Result, render: impl FnOnce(T) -> Result, -) -> Value { - match result { +) -> Result { + Ok(match result { Ok(report) => match render(report) { Ok(rendered) => { let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null); @@ -344,7 +360,7 @@ fn render_json_tool( Err(err) => tool_err(&err.to_string()), }, Err(err) => tool_err(&err.to_string()), - } + }) } fn required_str_arg<'a>(args: Option<&'a Value>, name: &str) -> Result<&'a str, Value> { @@ -353,12 +369,20 @@ fn required_str_arg<'a>(args: Option<&'a Value>, name: &str) -> Result<&'a str, .ok_or_else(|| tool_err(&format!("Missing required argument: {name}"))) } -fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let folder = resolve_folder(args, ctx.default_folder); +fn call_guard(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result { + let file = required_str_arg(args, "file")?; + let folder = resolve_folder(args, ctx.default_folder)?; + render_json_tool(guard(&folder, Path::new(file)), |report| { + report.render(GuardFormat::Json) + }) +} + +fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result { + let folder = resolve_folder(args, ctx.default_folder)?; let range = match args.and_then(|a| a.get("since")).and_then(Value::as_str) { Some(day_str) => match CalendarDay::from_str(day_str) { Ok(day) => TrendRange::Since(day), - Err(err) => return tool_err(&format!("Invalid since date {day_str:?}: {err}")), + Err(err) => return Err(tool_err(&format!("Invalid since date {day_str:?}: {err}"))), }, None => TrendOptions::default().range, }; @@ -372,17 +396,8 @@ fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { }) } -fn call_guard(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result { - let file = required_str_arg(args, "file")?; - let folder = resolve_folder(args, ctx.default_folder); - Ok(render_json_tool( - guard(&folder, Path::new(file)), - |report| report.render(GuardFormat::Json), - )) -} - fn call_impact(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result { - let folder = resolve_folder(args, ctx.default_folder); + let folder = resolve_folder(args, ctx.default_folder)?; let paths = parse_string_array(args, "paths")?; let changed = args .and_then(|a| a.get("changed")) @@ -402,15 +417,15 @@ fn call_impact(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result, ctx: &ServerContext<'_>) -> Result { let from = required_str_arg(args, "from")?; let to = required_str_arg(args, "to")?; - let folder = resolve_folder(args, ctx.default_folder); + let folder = resolve_folder(args, ctx.default_folder)?; let max_paths = match args.and_then(|a| a.get("max_paths")) { Some(value) => parse_usize_arg( value, @@ -427,34 +442,33 @@ fn call_trace(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result, ctx: &ServerContext<'_>) -> Result { let options = ChurnOptions { window: parse_churn_window(args)?, - findings: parse_findings(args), + findings: parse_findings(args)?, plugin_host: ctx.plugin_host.clone(), }; - let folder = resolve_folder(args, ctx.default_folder); - Ok(render_json_tool(churn(&folder, &options), |report| { + let folder = resolve_folder(args, ctx.default_folder)?; + render_json_tool(churn(&folder, &options), |report| { report.render(ChurnFormat::Json) - })) + }) } fn call_coupling(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result { let options = CouplingOptions { settings: parse_coupling_settings(args)?, - findings: parse_findings(args), + findings: parse_findings(args)?, plugin_host: ctx.plugin_host.clone(), }; - let folder = resolve_folder(args, ctx.default_folder); - Ok(render_json_tool(coupling(&folder, &options), |report| { + let folder = resolve_folder(args, ctx.default_folder)?; + render_json_tool(coupling(&folder, &options), |report| { report.render(ChurnFormat::Json) - })) + }) } fn parse_string_array(args: Option<&Value>, name: &str) -> Result, Value> { @@ -497,10 +511,10 @@ fn parse_coupling_settings(args: Option<&Value>) -> Result) -> Result Result { + value + .as_bool() + .ok_or_else(|| tool_err(&format!("Argument {name} must be a boolean"))) +} + fn parse_optional_arg( args: Option<&Value>, name: &str, @@ -570,30 +590,30 @@ fn parse_package(args: Option<&Value>) -> Option { .map(str::to_owned) } -fn resolve_folder(args: Option<&Value>, default_folder: &Path) -> PathBuf { - match args.and_then(|a| a.get("path")).and_then(Value::as_str) { - Some(p) if !p.is_empty() => { - let candidate = PathBuf::from(p); - if candidate.is_absolute() { - candidate - } else { - default_folder.join(candidate) - } +fn resolve_folder(args: Option<&Value>, default_folder: &Path) -> Result { + parse_optional_arg(args, "path", default_folder.to_path_buf(), |value| { + let path = value + .as_str() + .ok_or_else(|| tool_err("Argument path must be a string"))?; + if path.is_empty() { + return Ok(default_folder.to_path_buf()); } - _ => default_folder.to_path_buf(), - } + let candidate = PathBuf::from(path); + Ok(if candidate.is_absolute() { + candidate + } else { + default_folder.join(candidate) + }) + }) } -fn parse_findings(args: Option<&Value>) -> FindingsShown { - if args - .and_then(|a| a.get("all")) - .and_then(Value::as_bool) - .unwrap_or(false) - { +fn parse_findings(args: Option<&Value>) -> Result { + let all = parse_optional_arg(args, "all", false, |value| parse_bool_arg(value, "all"))?; + Ok(if all { FindingsShown::All } else { CheckOptions::default().findings - } + }) } fn tool_ok(payload: Value) -> Value { diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 7c88c9e..cc5e5bf 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -70,17 +70,6 @@ fn check_remedy(error: &CheckError) -> &'static str { } } -fn codeowners_remedy(error: &CodeownersError) -> &'static str { - match error { - CodeownersError::Read { .. } => { - "Check that the CODEOWNERS file is readable UTF-8, then run codeint again." - } - CodeownersError::InvalidOwnerPattern { .. } => { - "Pass a valid glob pattern to --owner, such as @org/team or @org/*." - } - } -} - fn guard_remedy(error: &GuardError) -> &'static str { match error { GuardError::Git(error) => git_remedy(error), @@ -189,7 +178,7 @@ fn git_remedy(error: &GitError) -> &'static str { "Pass a base ref that shares history with the head, which is HEAD unless you pass --head; in a shallow clone, fetch more history: git fetch --unshallow" } GitError::NoHistory(_) => { - "Commit once, then run codeint trend again; it measures the commits of the current branch." + "Commit once, then run codeint again; history commands measure the commits of the current branch." } GitError::MergeBase { .. } | GitError::History { .. } @@ -376,3 +365,14 @@ fn starter_configuration_remedy(error: &StarterConfigurationError) -> &'static s } } } + +fn codeowners_remedy(error: &CodeownersError) -> &'static str { + match error { + CodeownersError::Read { .. } => { + "Check that the CODEOWNERS file is readable UTF-8, then run codeint again." + } + CodeownersError::InvalidOwnerPattern { .. } => { + "Pass a valid glob pattern to --owner, such as @org/team or @org/*." + } + } +} diff --git a/crates/cli/tests/churn.rs b/crates/cli/tests/churn.rs index a938b98..687f8fa 100644 --- a/crates/cli/tests/churn.rs +++ b/crates/cli/tests/churn.rs @@ -2,14 +2,14 @@ mod history_support; use history_support::{ HistoryFixture, assert_format_contains, assert_no_blended_score_keys, - assert_shallow_and_non_git, + assert_shallow_and_non_git, assert_unborn_repo_remedy, }; -fn eroded_ts(name: &str, salt: usize) -> String { +fn eroded_ts(name: &str, variant: usize) -> String { let checks: String = (1..=12) - .map(|i| format!(" if (v === {i}) return {};\n", i + salt)) + .map(|i| format!(" if (v === {i}) return {};\n", i + variant)) .collect(); - format!("export function {name}(v: number): number {{\n{checks} return {salt};\n}}\n") + format!("export function {name}(v: number): number {{\n{checks} return {variant};\n}}\n") } fn duplicated_ts(prefix: &str, extra: &str) -> String { @@ -115,13 +115,13 @@ fn churn_ranks_eroded_and_duplicated_files_independently_by_commit_count_with_no #[test] fn churn_respects_since_days_since_date_and_commits_window() { let repo = HistoryFixture::init(); - for (label, salt, when) in [ + for (label, variant, when) in [ ("old", 1, "2026-01-01T10:00:00Z"), ("mid", 2, "2026-05-01T10:00:00Z"), ("recent", 3, "2026-05-10T10:00:00Z"), ("head", 4, "2026-05-15T10:00:00Z"), ] { - repo.save_and_commit(&[("src/eroded.ts", eroded_ts(label, salt))], label, when); + repo.save_and_commit(&[("src/eroded.ts", eroded_ts(label, variant))], label, when); } let by_days = repo.run_json("churn", &["--since", "30d"]); @@ -195,3 +195,55 @@ fn churn_handles_shallow_clones_and_non_git_directories_gracefully() { } assert_shallow_and_non_git(&origin, "churn", &[]); } + +#[test] +fn churn_shallow_boundary_does_not_fabricate_touches_for_untouched_files() { + let origin = HistoryFixture::init(); + origin.save_and_commit( + &[ + ("src/cold_eroded.ts", eroded_ts("coldEroded", 1)), + ("src/hot_eroded.ts", eroded_ts("hotEroded", 1)), + ], + "c1", + "2026-05-01T10:00:00Z", + ); + for step in 2..=4 { + origin.save_and_commit( + &[("src/hot_eroded.ts", eroded_ts("hotEroded", step))], + &format!("c{step}"), + &format!("2026-05-0{step}T10:00:00Z"), + ); + } + + let depth_one = origin.shallow_clone_of("1").run_json("churn", &[]); + assert_eq!(depth_one["shallow"], true); + assert_eq!(depth_one["commits_analyzed"], 0); + let depth_one_findings = depth_one["source_sets"]["production"]["erosion"]["findings"] + .as_array() + .expect("depth 1 findings"); + for row in depth_one_findings { + assert_eq!(row["commits"], 0, "unexpected fabricated touch: {row}"); + } + + let depth_two = origin.shallow_clone_of("2").run_json("churn", &[]); + assert_eq!(depth_two["shallow"], true); + assert_eq!(depth_two["commits_analyzed"], 1); + let depth_two_findings = depth_two["source_sets"]["production"]["erosion"]["findings"] + .as_array() + .expect("depth 2 findings"); + let commits_of = |path: &str| { + depth_two_findings + .iter() + .find(|row| row["path"] == path) + .expect("path present")["commits"] + .as_u64() + .expect("commits count") + }; + assert_eq!(commits_of("src/hot_eroded.ts"), 1); + assert_eq!(commits_of("src/cold_eroded.ts"), 0); +} + +#[test] +fn churn_on_unborn_repository_gives_command_agnostic_remedy() { + assert_unborn_repo_remedy("churn"); +} diff --git a/crates/cli/tests/coupling.rs b/crates/cli/tests/coupling.rs index 663d576..8741ddd 100644 --- a/crates/cli/tests/coupling.rs +++ b/crates/cli/tests/coupling.rs @@ -2,7 +2,7 @@ mod history_support; use history_support::{ HistoryFixture, assert_format_contains, assert_no_blended_score_keys, - assert_shallow_and_non_git, + assert_shallow_and_non_git, assert_unborn_repo_remedy, }; fn commit_const_pair( @@ -270,3 +270,78 @@ fn coupling_renders_all_formats_and_handles_shallow_non_git_and_invalid_args() { assert_shallow_and_non_git(&repo, "coupling", &["--min-co-changes", "2"]); } + +#[test] +fn coupling_shallow_boundary_does_not_fabricate_co_changes_for_untouched_files() { + let origin = HistoryFixture::init(); + origin.save_and_commit( + &[ + ("src/cold_a.ts", "export const coldA = 1;\n".to_owned()), + ("src/cold_b.ts", "export const coldB = 1;\n".to_owned()), + ("src/hot_a.ts", "export const hotA = 1;\n".to_owned()), + ("src/hot_b.ts", "export const hotB = 1;\n".to_owned()), + ], + "c1", + "2026-05-01T10:00:00Z", + ); + for step in 2..=4 { + origin.save_and_commit( + &[ + ("src/hot_a.ts", format!("export const hotA = {step};\n")), + ("src/hot_b.ts", format!("export const hotB = {step};\n")), + ], + &format!("c{step}"), + &format!("2026-05-0{step}T10:00:00Z"), + ); + } + + let args = ["--min-co-changes", "1", "--min-ratio", "0"]; + let depth_one = origin.shallow_clone_of("1").run_json("coupling", &args); + assert_eq!(depth_one["shallow"], true); + assert_eq!(depth_one["commits_analyzed"], 0); + assert_eq!(depth_one["pairs"].as_array().expect("pairs").len(), 0); + + let depth_two = origin.shallow_clone_of("2").run_json("coupling", &args); + assert_eq!(depth_two["shallow"], true); + assert_eq!(depth_two["commits_analyzed"], 1); + let observed: Vec<(&str, &str, u64)> = depth_two["pairs"] + .as_array() + .expect("pairs") + .iter() + .map(|row| { + ( + row["file_a"].as_str().expect("file_a"), + row["file_b"].as_str().expect("file_b"), + row["co_change_count"].as_u64().expect("co_change_count"), + ) + }) + .collect(); + assert_eq!(observed, vec![("src/hot_a.ts", "src/hot_b.ts", 1)]); +} + +#[test] +fn coupling_compares_exact_ratio_against_unrounded_min_ratio_and_handles_unborn_repo() { + let repo = HistoryFixture::init(); + commit_const_pair(&repo, ("src/a.ts", "a"), ("src/b.ts", "b"), 4, "0"); + repo.save_and_commit( + &[("src/a.ts", "export const a = 99;\n".to_owned())], + "touch a alone", + "2026-05-10T10:00:00Z", + ); + repo.save_and_commit( + &[("src/b.ts", "export const b = 99;\n".to_owned())], + "touch b alone", + "2026-05-11T10:00:00Z", + ); + + let excluded = repo.run_json("coupling", &["--min-ratio", "0.6667"]); + assert_eq!(excluded["pairs"].as_array().expect("pairs").len(), 0); + + let included = repo.run_json("coupling", &["--min-ratio", "0.66666"]); + assert_eq!(included["min_ratio"], 0.66666); + let pairs = included["pairs"].as_array().expect("pairs"); + assert_eq!(pairs.len(), 1); + assert_eq!(pairs[0]["coupling_ratio"], 0.6667); + + assert_unborn_repo_remedy("coupling"); +} diff --git a/crates/cli/tests/history_support/mod.rs b/crates/cli/tests/history_support/mod.rs index ceb816b..361b189 100644 --- a/crates/cli/tests/history_support/mod.rs +++ b/crates/cli/tests/history_support/mod.rs @@ -48,7 +48,7 @@ impl HistoryFixture { serde_json::from_slice(&out.stdout).expect("valid JSON report") } - fn shallow_clone_of(&self, depth: &str) -> HistoryFixture { + pub(crate) fn shallow_clone_of(&self, depth: &str) -> HistoryFixture { let shallow = HistoryFixture::init(); let url = format!("file://{}", self.root().display()); run_git( @@ -148,7 +148,7 @@ pub(crate) fn assert_shallow_and_non_git( let shallow = origin.shallow_clone_of("2"); let report = shallow.run_json(subcommand, shallow_args); assert_eq!(report["shallow"], true); - assert_eq!(report["commits_analyzed"], 2); + assert_eq!(report["commits_analyzed"], 1); let warning = report["warning"].as_str().expect("shallow clone warning"); assert!(warning.contains("shallow"), "warning: {warning}"); assert!(warning.contains("--unshallow"), "warning: {warning}"); @@ -162,3 +162,15 @@ pub(crate) fn assert_shallow_and_non_git( "stderr: {stderr}" ); } + +pub(crate) fn assert_unborn_repo_remedy(subcommand: &str) { + let empty = HistoryFixture::init(); + let out = empty.run(subcommand, &[]); + assert_eq!(out.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!( + stderr.contains("Commit once, then run codeint again"), + "stderr: {stderr}" + ); + assert!(!stderr.contains("codeint trend"), "stderr: {stderr}"); +} diff --git a/crates/cli/tests/mcp.rs b/crates/cli/tests/mcp.rs index ed14a94..d4645ce 100644 --- a/crates/cli/tests/mcp.rs +++ b/crates/cli/tests/mcp.rs @@ -218,3 +218,32 @@ fn mcp_coupling_tool_reports_co_change_pairs_bulk_exclusion_and_errors() { assert!(payload.get("score").is_none()); assert_tool_err_contains(&responses[1], "not inside a Git repository"); } + +#[test] +fn mcp_churn_and_coupling_reject_non_object_arguments_and_wrong_types() { + let repo = init_sample_repo(); + let responses = send_mcp_requests( + repo.path(), + &[ + mcp_tool_call(1, "churn", json!("not-an-object")), + mcp_tool_call(2, "churn", json!([])), + mcp_tool_call(3, "churn", json!(null)), + mcp_tool_call(4, "churn", json!({"all": "true"})), + mcp_tool_call(5, "churn", json!({"path": 42})), + mcp_tool_call(6, "coupling", json!([1, 2])), + mcp_tool_call(7, "coupling", json!({"include_tests": "true"})), + mcp_tool_call(8, "coupling", json!({"all": 1})), + mcp_tool_call(9, "coupling", json!({"path": true})), + ], + ); + assert_eq!(responses.len(), 9); + assert_tool_err_contains(&responses[0], "JSON object"); + assert_tool_err_contains(&responses[1], "JSON object"); + assert_tool_err_contains(&responses[2], "JSON object"); + assert_tool_err_contains(&responses[3], "all"); + assert_tool_err_contains(&responses[4], "path"); + assert_tool_err_contains(&responses[5], "JSON object"); + assert_tool_err_contains(&responses[6], "include_tests"); + assert_tool_err_contains(&responses[7], "all"); + assert_tool_err_contains(&responses[8], "path"); +} diff --git a/crates/config/src/codeowners.rs b/crates/config/src/codeowners.rs index f2fa622..a54bae4 100644 --- a/crates/config/src/codeowners.rs +++ b/crates/config/src/codeowners.rs @@ -49,6 +49,7 @@ impl Codeowners { } pub fn parse(text: &str) -> Codeowners { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); let rules = text.lines().filter_map(parse_rule).collect(); Codeowners { rules } } @@ -129,6 +130,9 @@ fn take_pattern(line: &str) -> (String, &str) { while let Some((index, ch)) = chars.next() { if ch == '\\' { if let Some(&(_, next)) = chars.peek() { + if matches!(next, '\\' | '*' | '?' | '[' | ']' | '{' | '}') { + pattern.push('\\'); + } pattern.push(next); chars.next(); } @@ -176,6 +180,7 @@ fn compile_pattern(pattern: &str) -> Option> { for glob in patterns { let matcher = GlobBuilder::new(&glob) .literal_separator(true) + .backslash_escape(true) .build() .ok()? .compile_matcher(); @@ -186,5 +191,15 @@ fn compile_pattern(pattern: &str) -> Option> { fn last_segment_has_wildcard(pattern: &str) -> bool { let last = pattern.rsplit('/').next().unwrap_or(pattern); - last.contains('*') || last.contains('?') || last.contains('[') + let mut chars = last.chars(); + while let Some(ch) = chars.next() { + if ch == '\\' { + chars.next(); + continue; + } + if matches!(ch, '*' | '?' | '[') { + return true; + } + } + false } diff --git a/crates/config/src/codeowners/tests.rs b/crates/config/src/codeowners/tests.rs index 7a60a60..1d74403 100644 --- a/crates/config/src/codeowners/tests.rs +++ b/crates/config/src/codeowners/tests.rs @@ -151,3 +151,46 @@ fn owner_filter_matches_case_insensitively_and_supports_wildcards() { assert!(glob.matches("@ORG/UI-CORE")); assert!(!glob.matches("@other/api-core")); } + +#[test] +fn escaped_glob_metacharacters_match_literals_and_compile() { + assert_owners_table( + "\ +app/users/\\[id\\]/page.ts @users-team +app/routes/\\[slug\\] @routes-team +src/a\\[b.ts @unclosed-team +src/star\\*.ts @star-team +src/q\\?.ts @question-team +src/\\{a,b\\}.ts @brace-team +", + &[ + ("app/users/[id]/page.ts", &["@users-team"]), + ("app/users/i/page.ts", &[]), + ("app/routes/[slug]/index.ts", &["@routes-team"]), + ("app/routes/s/index.ts", &[]), + ("src/a[b.ts", &["@unclosed-team"]), + ("src/star*.ts", &["@star-team"]), + ("src/starX.ts", &[]), + ("src/q?.ts", &["@question-team"]), + ("src/q1.ts", &[]), + ("src/{a,b}.ts", &["@brace-team"]), + ("src/a.ts", &[]), + ], + ); +} + +#[test] +fn leading_utf8_bom_is_stripped_before_parsing_rules() { + assert_owners_table( + "\u{feff}/src/ @src-team\n", + &[("src/app.ts", &["@src-team"]), ("other/app.ts", &[])], + ); + assert_owners_table( + "\u{feff}* @global-team\n", + &[("README.md", &["@global-team"])], + ); + assert_owners_table( + "\u{feff}# leading comment\nsrc/a.ts @a-team\n", + &[("src/a.ts", &["@a-team"]), ("src/b.ts", &[])], + ); +} diff --git a/crates/git/src/churn.rs b/crates/git/src/churn.rs index 6ab32ce..eec0d4f 100644 --- a/crates/git/src/churn.rs +++ b/crates/git/src/churn.rs @@ -178,14 +178,13 @@ impl Repository { if !effective.admits(commits_analyzed, committed_at) { break; } - commits_analyzed += 1; let at_boundary = shallow_boundary.is_some_and(|boundary| boundary.contains(&id)); - let parent_id = if at_boundary { + if at_boundary { truncated_by_shallow_boundary = true; - None - } else { - found.parent_ids().next().map(|parent| parent.detach()) - }; + break; + } + commits_analyzed += 1; + let parent_id = found.parent_ids().next().map(|parent| parent.detach()); let touched = self.touched_files_in_commit(commit, &found, parent_id)?; on_commit(touched); next = parent_id; diff --git a/crates/report/src/churn/markdown.rs b/crates/report/src/churn/markdown.rs index 29d1d9f..6197985 100644 --- a/crates/report/src/churn/markdown.rs +++ b/crates/report/src/churn/markdown.rs @@ -34,6 +34,7 @@ fn push_table_section( empty_note: &str, headers: &[&str], rows: Vec>, + left_out: usize, ) { blocks.push(heading); if rows.is_empty() { @@ -41,6 +42,12 @@ fn push_table_section( } else { blocks.push(table(headers, rows)); } + if left_out > 0 { + let noun = if left_out == 1 { "file" } else { "files" }; + blocks.push(format!( + "{left_out} more {noun} omitted (pass `--all` to show every file)." + )); + } } fn push_erosion_blocks(blocks: &mut Vec, section: &ErosionChurnSection) { @@ -73,6 +80,7 @@ fn push_erosion_blocks(blocks: &mut Vec, section: &ErosionChurnSection) "Max CC", ], rows, + section.findings.left_out, ); } @@ -99,5 +107,70 @@ fn push_duplication_blocks(blocks: &mut Vec, section: &DuplicationChurnS "No duplicated files.", &["File", "Commits", "Clone lines", "Clone groups"], rows, + section.findings.left_out, ); } + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + + use super::*; + use crate::churn::{DuplicatedChurnFile, ErodedChurnFile, SourceSetChurnSection, SourceSetKey}; + use crate::{Decimal, Findings}; + + #[test] + fn markdown_emits_truncation_notice_when_findings_are_left_out() { + let mut source_sets = BTreeMap::new(); + source_sets.insert( + SourceSetKey::Production, + SourceSetChurnSection { + files: 5, + erosion: ErosionChurnSection { + ratio: Decimal(0.5), + eroded_function_mass: Decimal(10.0), + total_function_mass: Decimal(20.0), + findings: Findings { + listed: vec![ErodedChurnFile { + path: "src/hot.ts".to_owned(), + commits: 4, + eroded_functions: 1, + eroded_function_mass: Decimal(10.0), + max_cyclomatic_complexity: 12, + }], + left_out: 1, + }, + }, + duplication: DuplicationChurnSection { + ratio: Decimal(0.25), + clone_lines: 30, + findings: Findings { + listed: vec![DuplicatedChurnFile { + path: "src/dup.ts".to_owned(), + commits: 3, + clone_lines: 15, + clone_groups: 1, + }], + left_out: 2, + }, + }, + }, + ); + let report = ChurnReport { + window: "90d".to_owned(), + commits_analyzed: 4, + shallow: false, + warning: None, + source_sets, + }; + let rendered = render(&report); + assert!( + rendered.contains("1 more file omitted (pass `--all` to show every file)."), + "rendered:\n{rendered}" + ); + assert!( + rendered.contains("2 more files omitted (pass `--all` to show every file)."), + "rendered:\n{rendered}" + ); + } +} diff --git a/crates/report/src/coupling.rs b/crates/report/src/coupling.rs index e28dae3..6819ba3 100644 --- a/crates/report/src/coupling.rs +++ b/crates/report/src/coupling.rs @@ -33,7 +33,7 @@ pub struct CouplingReport { commits_excluded_by_bulk_limit: usize, max_commit_files: usize, min_co_changes: usize, - min_ratio: Decimal, + min_ratio: f64, source_sets: Vec<&'static str>, shallow: bool, #[serde(skip_serializing_if = "Option::is_none")] @@ -65,7 +65,11 @@ impl CouplingReport { findings: FindingsShown, ) -> CouplingReport { let direct_imports = direct_import_pairs(model); - let min_ratio = Decimal::rounded(history.min_ratio); + let min_ratio = if history.min_ratio == 0.0 { + 0.0 + } else { + history.min_ratio + }; let mut rows: Vec = history .co_changes .iter() @@ -75,7 +79,7 @@ impl CouplingReport { file_b, co_change_count, history, - min_ratio.0, + min_ratio, &direct_imports, ) }) @@ -141,10 +145,11 @@ fn build_pair_row( if union == 0 { return None; } - let coupling_ratio = Decimal::rounded(co_change_count as f64 / union as f64); - if coupling_ratio.0 < min_ratio { + let raw_ratio = co_change_count as f64 / union as f64; + if raw_ratio < min_ratio { return None; } + let coupling_ratio = Decimal::rounded(raw_ratio); let has_direct_import = direct_imports.contains(&ordered_pair(file_a, file_b)); Some(CoupledPairRow { file_a: file_a.to_string(), diff --git a/crates/report/src/coupling/text.rs b/crates/report/src/coupling/text.rs index 18801ff..ff035d7 100644 --- a/crates/report/src/coupling/text.rs +++ b/crates/report/src/coupling/text.rs @@ -20,7 +20,7 @@ pub(super) fn render(report: &CouplingReport) -> String { let _ = writeln!( out, " none (min_co_changes={}, min_ratio={})", - report.min_co_changes, report.min_ratio.0 + report.min_co_changes, report.min_ratio ); return out.trim_end_matches('\n').to_owned(); }