diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index 050322a..2b1fd40 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")] @@ -306,22 +308,54 @@ impl WorkspaceContext { } } +pub(crate) struct PreparedRun { + pub(crate) context: WorkspaceContext, + 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 context = WorkspaceContext::load(folder, plugin_host)?; + let codeowners = Codeowners::load(context.repository.root())?; + let owner_filter = owner_pattern.map(OwnerFilter::new).transpose()?; + Ok(PreparedRun { + context, + 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, package: Option<&str>, + owner: Option<&str>, plugin_host: &PluginHostConfig, ) -> Result { - let context = WorkspaceContext::load(folder, plugin_host)?; - let plugins = context.plugins.as_named(); - let metric_plugins = context.plugins.metric_plugins(); + let run = PreparedRun::load(folder, owner, plugin_host)?; + let plugins = run.context.plugins.as_named(); + let metric_plugins = run.context.plugins.metric_plugins(); check_loaded( - &context.repository, - &context.configuration, + &run.context.repository, + &run.context.configuration, &plugins, &metric_plugins, findings, package, + run.ownership(), ) } @@ -334,7 +368,15 @@ fn check_with( let repository = Repository::discover(folder)?; let configuration = read_configuration(repository.root())?; configuration.validate_metrics(&[])?; - check_loaded(&repository, &configuration, plugins, &[], findings, None) + check_loaded( + &repository, + &configuration, + plugins, + &[], + findings, + None, + OwnershipOptions::default(), + ) } fn check_loaded( @@ -344,6 +386,7 @@ fn check_loaded( metric_plugins: &[&dyn MetricPlugin], findings: FindingsShown, package: Option<&str>, + ownership: OwnershipOptions<'_>, ) -> Result { let tree = repository.working_tree()?; let mut languages = measure_with(&tree, plugins, configuration)?; @@ -352,13 +395,14 @@ fn check_loaded( let selected = select_workspace_package(&workspace, requested)?; filter_languages_to_package(&mut languages, &selected); } - 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/churn.rs b/crates/cli/src/churn.rs new file mode 100644 index 0000000..ab01e29 --- /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, WorkspaceContext, measure_with}; + +pub(crate) fn churn( + folder: &Path, + window: ChurnWindow, + findings: FindingsShown, + plugin_host: &PluginHostConfig, +) -> Result { + let context = WorkspaceContext::load(folder, plugin_host)?; + let plugins = context.plugins.as_named(); + let history = context.repository.file_churn(churn_range(window))?; + let tree = context.repository.working_tree()?; + let languages = measure_with(&tree, &plugins, &context.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)) +} + +pub(crate) 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/coupling.rs b/crates/cli/src/coupling.rs new file mode 100644 index 0000000..0965f19 --- /dev/null +++ b/crates/cli/src/coupling.rs @@ -0,0 +1,51 @@ +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, WorkspaceContext}; +use crate::churn::churn_range; + +pub(crate) fn coupling( + folder: &Path, + settings: CouplingSettings, + findings: FindingsShown, + plugin_host: &PluginHostConfig, +) -> Result { + let context = WorkspaceContext::load(folder, plugin_host)?; + let model = context.measure_working_tree_model()?; + let allowed_paths = selected_source_paths(&model, settings.include_tests); + let history = context.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/diff.rs b/crates/cli/src/diff.rs index d389e0c..2923162 100644 --- a/crates/cli/src/diff.rs +++ b/crates/cli/src/diff.rs @@ -2,9 +2,11 @@ use std::path::Path; use codeint_config::{FindingsShown, PluginHostConfig}; use codeint_git::{CommitId, GitError, Repository, ResultCache}; -use codeint_report::{BaseCommit, CommitMeasurement, DiffReport, Head, HeadCommit}; +use codeint_report::{ + BaseCommit, CommitMeasurement, DiffReport, DiffReportOptions, Head, HeadCommit, +}; -use crate::check::{CheckError, SelectedPackage, WorkspaceContext}; +use crate::check::{CheckError, PreparedRun, SelectedPackage, WorkspaceContext}; use crate::commit_measurement::{CommitMeasurer, measure_all_languages_for_package}; pub(crate) struct Refs<'a> { @@ -23,25 +25,27 @@ pub(crate) fn diff( refs: Refs<'_>, findings: FindingsShown, package: Option<&str>, + owner: Option<&str>, result_cache: Option<&ResultCache>, plugin_host: &PluginHostConfig, ) -> Result { - let context = WorkspaceContext::load(folder, plugin_host)?; + let run = PreparedRun::load(folder, owner, plugin_host)?; let Sides { merge_base, head, head_commit, - } = sides(&context.repository, &refs)?; - let (selected, head_measurement) = measure_head(&context, head_commit, package, result_cache)?; + } = sides(&run.context.repository, &refs)?; + let (selected, head_measurement) = + measure_head(&run.context, head_commit, package, result_cache)?; let base_measurer = CommitMeasurer::for_package( - &context.repository, - &context.configuration, - &context.plugins, + &run.context.repository, + &run.context.configuration, + &run.context.plugins, result_cache, selected.as_ref().map(|pkg| pkg.as_str()), ); let base_measurement = base_measurer.measure_selected_package(merge_base, selected.as_ref())?; - Ok(DiffReport::compare( + Ok(DiffReport::compare_with_options( BaseCommit { git_ref: refs.base.to_owned(), merge_base: merge_base.to_string(), @@ -49,9 +53,12 @@ pub(crate) fn diff( head, base_measurement, head_measurement, - findings, - &context.configuration.budgets, - &context.configuration.regression_limits, + DiffReportOptions { + findings, + budgets: &run.context.configuration.budgets, + limits: &run.context.configuration.regression_limits, + ownership: run.ownership(), + }, )) } diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 24ebbfd..c050187 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -1,7 +1,9 @@ #![forbid(unsafe_code)] mod check; +mod churn; mod commit_measurement; +mod coupling; mod diff; mod guard; mod impact; @@ -25,15 +27,20 @@ use codeint_git::ResultCache; use codeint_report::ReportError; pub use codeint_config::{ - CalendarDay, FindingsShown, GuardFormat, ImpactFormat, PluginHostConfig, ReportFormat, + CalendarDay, ChurnFormat, ChurnSince, ChurnWindow, CouplingRatio, CouplingRatioError, + CouplingSettings, FindingsShown, GuardFormat, ImpactFormat, PluginHostConfig, ReportFormat, TraceFormat, TrendFormat, TrendRange, }; -pub use codeint_report::{DiffReport, GuardReport, ImpactReport, Report, TraceReport, TrendReport}; +pub use codeint_report::{ + ChurnReport, CouplingReport, DiffReport, GuardReport, ImpactReport, Report, TraceReport, + TrendReport, +}; #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct CheckOptions { pub findings: FindingsShown, pub package: Option, + pub owner: Option, pub plugin_host: PluginHostConfig, } @@ -42,6 +49,7 @@ pub struct DiffOptions { pub head_ref: Option, pub findings: FindingsShown, pub package: Option, + pub owner: Option, pub result_cache: Option, pub plugin_host: PluginHostConfig, } @@ -80,6 +88,20 @@ impl Default for TraceOptions { } } } + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ChurnOptions { + pub window: ChurnWindow, + pub findings: FindingsShown, + pub plugin_host: PluginHostConfig, +} + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct CouplingOptions { + pub settings: CouplingSettings, + pub findings: FindingsShown, + pub plugin_host: PluginHostConfig, +} pub struct CheckOutcome { pub passed: bool, pub failures: Vec, @@ -128,6 +150,7 @@ pub fn check(folder: &Path, options: &CheckOptions) -> Result 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))) +} + +pub fn coupling(folder: &Path, options: &CouplingOptions) -> 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)] @@ -287,13 +331,18 @@ pub fn run_cli() -> ExitCode { } fn run() -> Result { - match read_invocation()?.command { + run_command(read_invocation()?.command) +} + +fn run_command(command: Command) -> Result { + match command { Command::Check { folder, destination, findings, format, package, + owner, plugin_host, } => run_check( &folder, @@ -301,6 +350,7 @@ fn run() -> Result { findings, format, package.as_deref(), + owner.as_deref(), &plugin_host, ), Command::Diff { @@ -311,6 +361,7 @@ fn run() -> Result { findings, format, package, + owner, result_cache, plugin_host, } => { @@ -318,6 +369,7 @@ fn run() -> Result { head_ref, findings, package, + owner, result_cache, plugin_host, }; @@ -376,6 +428,12 @@ fn run() -> Result { }; run_trace(&folder, &from, &to, &destination, format, &options) } + other => run_auxiliary_command(other), + } +} + +fn run_auxiliary_command(command: Command) -> Result { + match command { Command::Init { folder } => run_init(&folder), Command::Update { check_only, @@ -392,9 +450,66 @@ 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, + ), + Command::Coupling { + folder, + settings, + destination, + findings, + format, + plugin_host, + } => run_coupling( + &folder, + settings, + &destination, + findings, + format, + &plugin_host, + ), + _ => unreachable!("analysis commands are handled by run_command"), } } +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_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)?))?; @@ -432,9 +547,10 @@ fn run_check( findings: FindingsShown, format: ReportFormat, package: Option<&str>, + owner: Option<&str>, plugin_host: &PluginHostConfig, ) -> Result { - let report = check::check(folder, findings, package, plugin_host)?; + let report = check::check(folder, findings, package, 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 6778d01..95026e6 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -3,14 +3,15 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use codeint_config::{ - CalendarDay, FindingsShown, GuardFormat, ImpactFormat, PluginHostConfig, ReportFormat, - TraceFormat, TrendFormat, TrendRange, + CalendarDay, ChurnFormat, ChurnSince, ChurnWindow, CouplingRatio, CouplingSettings, + FindingsShown, GuardFormat, ImpactFormat, PluginHostConfig, ReportFormat, TraceFormat, + TrendFormat, TrendRange, }; use serde_json::{Value, json}; use crate::{ - CheckOptions, DiffOptions, ImpactOptions, TraceOptions, TrendOptions, check, diff, guard, - impact, trace, trend, + CheckOptions, ChurnOptions, CouplingOptions, DiffOptions, ImpactOptions, TraceOptions, + TrendOptions, check, churn, coupling, diff, guard, impact, trace, trend, }; const DEFAULT_PROTOCOL_VERSION: &str = "2024-11-05"; @@ -209,6 +210,36 @@ fn handle_tools_list() -> Value { "max_paths": { "type": "integer", "minimum": 1, "description": "Maximum number of shortest paths to return when all is true (default 10)." } } } + }, + { + "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." } + } + } + }, + { + "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." } + } + } } ] }) @@ -222,59 +253,80 @@ 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(call_diff(args, ctx)), - "trend" => Ok(call_trend(args, ctx)), - "guard" => Ok(call_guard(args, ctx)), - "impact" => Ok(call_impact(args, ctx)), - "trace" => Ok(call_trace(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 call_check(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let folder = resolve_folder(args, ctx.default_folder); +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<'_>) -> 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<'_>) -> Value { - let base_ref = match required_str_arg(args, "base_ref") { - Ok(value) => value, - Err(err) => return err, - }; - let folder = resolve_folder(args, ctx.default_folder); +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 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(), plugin_host: ctx.plugin_host.clone(), }; - match diff(&folder, base_ref, &options) { + Ok(match diff(&folder, base_ref, &options) { Ok(outcome) => render_outcome( outcome.passed, outcome.failures, outcome.report.render(ReportFormat::Json), ), Err(err) => tool_err(&err.to_string()), - } + }) } fn render_outcome( @@ -298,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); @@ -308,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> { @@ -317,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, }; @@ -336,42 +396,18 @@ fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { }) } -fn call_guard(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let file = match required_str_arg(args, "file") { - Ok(value) => value, - Err(err) => return err, - }; - let folder = resolve_folder(args, ctx.default_folder); - render_json_tool(guard(&folder, Path::new(file)), |report| { - report.render(GuardFormat::Json) - }) -} - -fn call_impact(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let folder = resolve_folder(args, ctx.default_folder); - let paths: Vec = match args.and_then(|a| a.get("paths")) { - Some(Value::Array(items)) => { - let mut parsed = Vec::with_capacity(items.len()); - for item in items { - let Some(path) = item.as_str() else { - return tool_err("Invalid paths argument: every entry must be a string"); - }; - parsed.push(path.to_owned()); - } - parsed - } - Some(_) => return tool_err("Invalid paths argument: expected an array of strings"), - None => Vec::new(), - }; +fn call_impact(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result { + let folder = resolve_folder(args, ctx.default_folder)?; + let paths = parse_string_array(args, "paths")?; let changed = args .and_then(|a| a.get("changed")) .and_then(Value::as_str) .map(str::to_owned); let depth = match args.and_then(|a| a.get("depth")) { - Some(value) => match value.as_u64().and_then(|n| usize::try_from(n).ok()) { - Some(depth) => Some(depth), - None => return tool_err("Invalid depth argument: expected a non-negative integer"), - }, + Some(value) => Some(parse_usize_arg( + value, + "Invalid depth argument: expected a non-negative integer", + )?), None => None, }; let options = ImpactOptions { @@ -386,29 +422,22 @@ fn call_impact(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { }) } -fn call_trace(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let from = match required_str_arg(args, "from") { - Ok(value) => value, - Err(err) => return err, - }; - let to = match required_str_arg(args, "to") { - Ok(value) => value, - Err(err) => return err, - }; - let folder = resolve_folder(args, ctx.default_folder); - let all = args - .and_then(|a| a.get("all")) - .and_then(Value::as_bool) - .unwrap_or(false); +fn call_trace(args: Option<&Value>, 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 max_paths = match args.and_then(|a| a.get("max_paths")) { - Some(value) => match value.as_u64().and_then(|n| usize::try_from(n).ok()) { - Some(n) => n, - None => return tool_err("Invalid argument: max_paths must be a positive integer"), - }, + Some(value) => parse_usize_arg( + value, + "Invalid argument: max_paths must be a positive integer", + )?, None => TraceOptions::default().max_paths, }; let options = TraceOptions { - all, + all: args + .and_then(|a| a.get("all")) + .and_then(Value::as_bool) + .unwrap_or(false), max_paths, package: parse_package(args), plugin_host: ctx.plugin_host.clone(), @@ -418,36 +447,173 @@ fn call_trace(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { }) } +fn call_churn(args: Option<&Value>, ctx: &ServerContext<'_>) -> Result { + let options = ChurnOptions { + window: parse_churn_window(args)?, + findings: parse_findings(args)?, + plugin_host: ctx.plugin_host.clone(), + }; + 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)?, + plugin_host: ctx.plugin_host.clone(), + }; + 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> { + match args.and_then(|a| a.get(name)) { + Some(Value::Array(items)) => items + .iter() + .map(|item| { + item.as_str().map(str::to_owned).ok_or_else(|| { + tool_err(&format!( + "Invalid {name} argument: every entry must be a string" + )) + }) + }) + .collect(), + Some(_) => Err(tool_err(&format!( + "Invalid {name} argument: expected an array of strings" + ))), + None => Ok(Vec::new()), + } +} + +fn parse_usize_arg(value: &Value, error_message: &str) -> Result { + value + .as_u64() + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| tool_err(error_message)) +} + +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 = + parse_optional_arg(args, "include_tests", defaults.include_tests, |value| { + parse_bool_arg(value, "include_tests") + })?; + Ok(CouplingSettings { + window, + max_commit_files, + min_co_changes, + min_ratio, + include_tests, + }) +} + +fn parse_bool_arg(value: &Value, name: &str) -> 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, + 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()); + 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 parse_package(args: Option<&Value>) -> Option { args.and_then(|a| a.get("package")) .and_then(Value::as_str) .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 b0e7941..cc5e5bf 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_metrics::ImpactError; use codeint_model::{MetricPluginError, WorkspaceError}; @@ -47,8 +49,15 @@ fn trace_remedy(error: &TraceCommandError) -> &'static str { fn check_remedy(error: &CheckError) -> &'static str { match error { + CheckError::ExtensionConflict { .. } => { + "Assign separate directories to each Language plugin in the languages setting of codeint.json." + } + CheckError::UnknownWorkspacePackage { .. } => { + "Pass one of the discovered Workspace package paths to --package, or omit --package to measure the whole repository." + } CheckError::Git(error) => git_remedy(error), CheckError::Configuration(error) => configuration_file_remedy(error), + CheckError::Codeowners(error) => codeowners_remedy(error), 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." @@ -58,12 +67,6 @@ fn check_remedy(error: &CheckError) -> &'static str { } CheckError::PluginHost(error) => plugin_host_remedy(error), CheckError::MetricPlugin(error) => metric_plugin_remedy(error), - CheckError::ExtensionConflict { .. } => { - "Assign separate directories to each Language plugin in the languages setting of codeint.json." - } - CheckError::UnknownWorkspacePackage { .. } => { - "Pass one of the discovered Workspace package paths to --package, or omit --package to measure the whole repository." - } } } @@ -175,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 { .. } @@ -362,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 new file mode 100644 index 0000000..687f8fa --- /dev/null +++ b/crates/cli/tests/churn.rs @@ -0,0 +1,249 @@ +mod history_support; + +use history_support::{ + HistoryFixture, assert_format_contains, assert_no_blended_score_keys, + assert_shallow_and_non_git, assert_unborn_repo_remedy, +}; + +fn eroded_ts(name: &str, variant: usize) -> String { + let checks: String = (1..=12) + .map(|i| format!(" if (v === {i}) return {};\n", i + variant)) + .collect(); + format!("export function {name}(v: number): number {{\n{checks} return {variant};\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" + ) +} + +#[test] +fn churn_ranks_eroded_and_duplicated_files_independently_by_commit_count_with_no_score() { + let repo = HistoryFixture::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.run_json("churn", &[]); + 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 = HistoryFixture::init(); + 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, variant))], label, when); + } + + 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.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.run_json("churn", &["--commits", "2"]); + assert_eq!(by_commits["commits_analyzed"], 2); + assert_eq!( + by_commits["source_sets"]["production"]["erosion"]["findings"][0]["commits"], + 2 + ); + + assert_eq!( + repo.run("churn", &["--since", "30d", "--commits", "5"]) + .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 = HistoryFixture::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, "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 = HistoryFixture::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"), + ); + } + 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/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/cli/tests/coupling.rs b/crates/cli/tests/coupling.rs new file mode 100644 index 0000000..8741ddd --- /dev/null +++ b/crates/cli/tests/coupling.rs @@ -0,0 +1,347 @@ +mod history_support; + +use history_support::{ + HistoryFixture, assert_format_contains, assert_no_blended_score_keys, + assert_shallow_and_non_git, assert_unborn_repo_remedy, +}; + +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"]); +} + +#[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 new file mode 100644 index 0000000..361b189 --- /dev/null +++ b/crates/cli/tests/history_support/mod.rs @@ -0,0 +1,176 @@ +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") + } + + pub(crate) 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"], 1); + 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}" + ); +} + +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 67020b1..d4645ce 100644 --- a/crates/cli/tests/mcp.rs +++ b/crates/cli/tests/mcp.rs @@ -1,7 +1,10 @@ mod common; +use std::process::Command; + use common::{init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests}; -use serde_json::json; +use serde_json::{Value, json}; +use tempfile::TempDir; #[test] fn mcp_initialize_list_and_call_tools() { @@ -28,7 +31,9 @@ fn mcp_initialize_list_and_call_tools() { let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); assert_eq!( names, - ["check", "diff", "trend", "guard", "impact", "trace"] + [ + "check", "diff", "trend", "guard", "impact", "trace", "churn", "coupling" + ] ); let check_payload = mcp_payload(&responses[2]); @@ -113,3 +118,132 @@ fn mcp_guard_tool_reports_existing_planned_unzoned_and_unconfigured_paths() { assert_eq!(unzoned["configured"], true); assert!(unzoned.get("zone").is_none()); } + +fn init_sample_repo() -> TempDir { + init_git_repo(&[( + "app.ts", + "export function greet(x: number): number {\n return x + 1;\n}\n", + )]) +} + +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(); + let non_git = TempDir::new().unwrap(); + let responses = send_mcp_requests( + repo.path(), + &[ + mcp_tool_call(1, "churn", json!({"commits": 10})), + mcp_tool_call( + 2, + "churn", + json!({"path": non_git.path().to_string_lossy()}), + ), + ], + ); + assert_eq!(responses.len(), 2); + let payload = mcp_payload(&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"); +} + +#[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(); + 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(), + &[ + mcp_tool_call( + 1, + "coupling", + json!({"commits": 10, "max_commit_files": 20, "min_co_changes": 3, "min_ratio": 0.5}), + ), + mcp_tool_call( + 2, + "coupling", + json!({"path": non_git.path().to_string_lossy()}), + ), + ], + ); + assert_eq!(responses.len(), 2); + let payload = mcp_payload(&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"); +} + +#[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/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/codeowners.rs b/crates/config/src/codeowners.rs new file mode 100644 index 0000000..a54bae4 --- /dev/null +++ b/crates/config/src/codeowners.rs @@ -0,0 +1,205 @@ +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 text = text.strip_prefix('\u{feff}').unwrap_or(text); + 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() { + if matches!(next, '\\' | '*' | '?' | '[' | ']' | '{' | '}') { + pattern.push('\\'); + } + 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) + .backslash_escape(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); + 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 new file mode 100644 index 0000000..1d74403 --- /dev/null +++ b/crates/config/src/codeowners/tests.rs @@ -0,0 +1,196 @@ +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")); +} + +#[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/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 7dddfa0..f9ce709 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -6,8 +6,11 @@ use clap::{Parser, Subcommand}; mod boundaries; mod calendar_day; +mod churn; mod codeint_json; +mod codeowners; mod config_error; +mod coupling; mod regression_limits; mod result_cache_folder; @@ -15,13 +18,19 @@ 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, 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 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; @@ -148,6 +157,7 @@ pub enum Command { findings: FindingsShown, format: ReportFormat, package: Option, + owner: Option, plugin_host: PluginHostConfig, }, Diff { @@ -158,6 +168,7 @@ pub enum Command { findings: FindingsShown, format: ReportFormat, package: Option, + owner: Option, result_cache: Option, plugin_host: PluginHostConfig, }, @@ -208,6 +219,22 @@ pub enum Command { target: PathBuf, format: GuardFormat, }, + Churn { + folder: PathBuf, + window: ChurnWindow, + destination: ReportDestination, + findings: FindingsShown, + format: ChurnFormat, + plugin_host: PluginHostConfig, + }, + Coupling { + folder: PathBuf, + settings: CouplingSettings, + destination: ReportDestination, + findings: FindingsShown, + format: ChurnFormat, + plugin_host: PluginHostConfig, + }, } #[derive(Debug)] @@ -300,7 +327,7 @@ enum CommandArguments { version: Option, }, #[command( - about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, trend, guard, impact, and trace tools" + about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, trend, guard, impact, trace, churn, and coupling tools" )] Mcp, #[command( @@ -320,6 +347,79 @@ enum CommandArguments { )] format: GuardFormat, }, + #[command( + 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 = "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" + )] + max_commit_files: std::num::NonZeroUsize, + #[arg( + long = "min-co-changes", + value_name = "COUNT", + 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" + )] + min_co_changes: std::num::NonZeroUsize, + #[arg( + 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" + )] + min_ratio: CouplingRatio, + #[arg( + long = "include-tests", + help = "Include Test Source set files alongside Production files" + )] + 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)] @@ -351,6 +451,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, } #[derive(Debug, clap::Args)] @@ -458,6 +564,15 @@ fn build_command( } => build_trend_command(current_folder, since, output.output, format), CommandArguments::Impact(args) => build_impact_command(current_folder, args), CommandArguments::Trace(args) => build_trace_command(current_folder, args), + other => build_auxiliary_command(current_folder, other), + } +} + +fn build_auxiliary_command( + current_folder: &Path, + arguments: CommandArguments, +) -> Result { + match arguments { CommandArguments::Init => Ok(Command::Init { folder: current_folder.to_path_buf(), }), @@ -472,9 +587,74 @@ fn build_command( target: path, 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, + ), + _ => unreachable!("analysis commands are handled by build_command"), + } +} + +fn resolve_churn_window( + since: Option, + commits: Option, +) -> 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: 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), + }) +} + fn build_check_command( current_folder: &Path, path: Option, @@ -486,6 +666,7 @@ fn build_check_command( findings: findings_shown(report.all), format: report.format, package: report.package, + owner: report.owner, plugin_host: plugin_host_config_of_this_process(current_folder), }) } @@ -504,6 +685,7 @@ fn build_diff_command( findings: findings_shown(report.all), format: report.format, package: report.package, + 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/git/src/churn.rs b/crates/git/src/churn.rs new file mode 100644 index 0000000..eec0d4f --- /dev/null +++ b/crates/git/src/churn.rs @@ -0,0 +1,361 @@ +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, +} + +#[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), +} + +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 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 + .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_commits( + head_id, + &effective, + shallow, + shallow_boundary.as_ref(), + on_commit, + ) + } + + fn walk_commits( + &self, + start: ObjectId, + effective: &EffectiveRange, + shallow: bool, + shallow_boundary: Option<&gix::shallow::Commits>, + mut on_commit: impl FnMut(BTreeSet), + ) -> Result { + let mut commits_analyzed = 0usize; + let mut truncated_by_shallow_boundary = false; + 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; + } + let at_boundary = shallow_boundary.is_some_and(|boundary| boundary.contains(&id)); + if at_boundary { + truncated_by_shallow_boundary = true; + 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; + } + Ok(WalkOutcome { + commits_analyzed, + shallow, + truncated_by_shallow_boundary, + }) + } + + 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 2e2d288..754b6e7 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, 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 new file mode 100644 index 0000000..50b460a --- /dev/null +++ b/crates/report/src/churn.rs @@ -0,0 +1,289 @@ +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 { + render_churn_format(self, format, text::render, markdown::render) + } + + 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), + } + } +} + +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 + .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..6197985 --- /dev/null +++ b/crates/report/src/churn/markdown.rs @@ -0,0 +1,176 @@ +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>, + left_out: usize, +) { + blocks.push(heading); + if rows.is_empty() { + blocks.push(empty_note.to_owned()); + } 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) { + 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, + section.findings.left_out, + ); +} + +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, + 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/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/coupling.rs b/crates/report/src/coupling.rs new file mode 100644 index 0000000..6819ba3 --- /dev/null +++ b/crates/report/src/coupling.rs @@ -0,0 +1,173 @@ +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: f64, + 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 = if history.min_ratio == 0.0 { + 0.0 + } else { + 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, + &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 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(), + 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..ff035d7 --- /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 + ); + 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/diff.rs b/crates/report/src/diff.rs index 0260e8a..ca9f61e 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 d10085e..592961c 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, ImpactFormat, ReportFormat, TraceFormat, }; use codeint_metrics::{ @@ -18,25 +18,33 @@ use codeint_model::{ use serde::ser::SerializeMap; use serde::{Deserialize, Serialize, Serializer}; +mod churn; +mod coupling; mod diff; mod guard; mod impact; mod markdown; mod measurement; +mod ownership; mod sarif; #[cfg(test)] mod tests; mod trace; mod trend; +pub use churn::{ChurnHistoryInput, ChurnReport}; pub use codeint_metrics::TraceError; -pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; +pub use coupling::{CouplingHistoryInput, CouplingReport}; +pub use diff::{BaseCommit, DiffReport, DiffReportOptions, Head, HeadCommit}; pub use guard::{GuardAllowedTarget, GuardDeniedTarget, GuardReport}; pub use impact::{ChangedBase, ImpactReport}; pub use measurement::CommitMeasurement; +pub use ownership::OwnershipOptions; pub use trace::TraceReport; 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 = @@ -157,6 +165,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)] @@ -181,6 +191,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)] @@ -248,6 +260,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)] @@ -264,6 +278,8 @@ struct CloneGroupFinding { id: String, tokens: usize, locations: Vec, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, } #[derive(Debug, Serialize, Deserialize)] @@ -290,6 +306,8 @@ struct FlaggedLineRow { path: String, line: u32, rule: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, } #[derive(Debug, Serialize)] @@ -315,12 +333,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)] @@ -407,6 +429,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 { @@ -445,6 +479,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"; } @@ -483,16 +558,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()), } } } @@ -509,6 +596,7 @@ impl From<&BoundaryFinding> for BoundaryFindingRow { target_zone: finding.target_zone.clone(), reason: finding.reason.clone(), message: finding.message.clone(), + owners: Vec::new(), } } } @@ -521,6 +609,7 @@ impl ExternalMetricFinding { line: finding.line, end_line: finding.end_line, message: finding.message.clone(), + owners: Vec::new(), } } } @@ -532,6 +621,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() { @@ -544,6 +634,7 @@ impl SourceSetSections { findings, metric_plugins, source_set_boundaries, + ownership, )?); } } @@ -617,11 +708,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 { @@ -635,12 +731,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, ), }, ); @@ -648,10 +743,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), @@ -667,28 +805,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 { @@ -698,24 +814,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(), } } } @@ -726,6 +825,7 @@ impl CloneGroupFinding { id: group.id.to_string(), tokens: group.tokens, locations: group.fragments.iter().map(CloneLocation::new).collect(), + owners: Vec::new(), } } } @@ -740,23 +840,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 { @@ -764,26 +847,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(), } } } @@ -793,16 +857,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, } } } @@ -813,6 +878,7 @@ impl From<&UnresolvedImport> for UnresolvedImportRow { importer: import.importer.to_string(), specifier: import.specifier.clone(), reason: import.reason.clone(), + owners: Vec::new(), } } } @@ -903,6 +969,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); @@ -912,6 +979,7 @@ impl MeasuredSection { findings, metric_plugins, boundaries, + ownership, )?; Ok(MeasuredSection { files, @@ -956,6 +1024,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() @@ -980,6 +1068,7 @@ impl Report { findings, metric_plugins, boundaries, + ownership, )?, ); } @@ -998,8 +1087,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 61d9650..705b281 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -30,8 +30,10 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `trace` | Find the shortest runtime import path between two files in the repository; see [`codeint trace`](#codeint-trace) | | `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`, `impact`, and `trace` tools; see [`codeint mcp`](#codeint-mcp) | +| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, `guard`, `impact`, `trace`, `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 | @@ -133,6 +135,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: @@ -203,6 +206,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 ``` @@ -236,6 +240,7 @@ codeint check --package packages/missing | `--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. @@ -384,6 +389,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. @@ -580,7 +591,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 six read-only tools (`check`, `diff`, `trend`, `guard`, `impact`, and `trace`) so coding agents can measure Software entropy, inspect architectural boundaries, reverse-dependency blast radius, and import paths, and fix Regressions before opening a pull request. +It exposes eight read-only tools (`check`, `diff`, `trend`, `guard`, `impact`, `trace`, `churn`, and `coupling`) so coding agents can measure Software entropy, inspect architectural boundaries, reverse-dependency blast radius, and import paths, 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 @@ -607,6 +618,54 @@ 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 +``` + +### `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 |