From 3f8dc05dd31d90d3fc1784ae253110529d3659a2 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 08:06:21 +0800 Subject: [PATCH 1/4] feat(cli): add trace command and MCP tool for shortest import paths Add cycle-safe shortest-path BFS over resolved runtime imports in codeint-metrics, structured TraceReport rendering (TOON, JSON, text) in codeint-report, the codeint trace CLI subcommand with --all and --max-paths, and the matching read-only trace tool in codeint mcp. Closes #179 --- crates/cli/src/lib.rs | 83 +++++++- crates/cli/src/mcp.rs | 57 ++++- crates/cli/src/remedy.rs | 40 ++-- crates/cli/src/trace.rs | 81 ++++++++ crates/cli/tests/common/mod.rs | 62 ++++++ crates/cli/tests/mcp.rs | 67 +----- crates/cli/tests/trace.rs | 334 ++++++++++++++++++++++++++++++ crates/config/src/lib.rs | 76 ++++++- crates/metrics/src/lib.rs | 2 + crates/metrics/src/trace.rs | 223 ++++++++++++++++++++ crates/metrics/src/trace/tests.rs | 124 +++++++++++ crates/report/src/lib.rs | 3 + crates/report/src/trace.rs | 69 ++++++ docs/reference.md | 44 +++- 14 files changed, 1185 insertions(+), 80 deletions(-) create mode 100644 crates/cli/src/trace.rs create mode 100644 crates/cli/tests/common/mod.rs create mode 100644 crates/cli/tests/trace.rs create mode 100644 crates/metrics/src/trace.rs create mode 100644 crates/metrics/src/trace/tests.rs create mode 100644 crates/report/src/trace.rs diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index bec0ed4..f4c5a97 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -6,6 +6,7 @@ mod diff; mod init; mod mcp; mod remedy; +mod trace; mod trend; mod update; @@ -15,14 +16,17 @@ use std::io::Write; use std::path::{Path, PathBuf}; use std::process::ExitCode; -use codeint_config::{Command, ConfigError, ReportDestination, read_invocation}; +use codeint_config::{ + Command, ConfigError, DEFAULT_MAX_TRACE_PATHS, ReportDestination, read_invocation, +}; use codeint_git::ResultCache; use codeint_report::ReportError; pub use codeint_config::{ - CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, + CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TraceFormat, TrendFormat, + TrendRange, }; -pub use codeint_report::{DiffReport, Report, TrendReport}; +pub use codeint_report::{DiffReport, Report, TraceReport, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -78,6 +82,23 @@ impl Default for TrendOptions { } } +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TraceOptions { + pub all: bool, + pub max_paths: usize, + pub plugin_host: PluginHostConfig, +} + +impl Default for TraceOptions { + fn default() -> TraceOptions { + TraceOptions { + all: false, + max_paths: DEFAULT_MAX_TRACE_PATHS, + plugin_host: PluginHostConfig::default(), + } + } +} + pub struct CheckOutcome { pub passed: bool, pub failures: Vec, @@ -178,6 +199,23 @@ pub fn trend(folder: &Path, options: &TrendOptions) -> Result Result { + trace::trace( + folder, + from, + to, + options.all, + options.max_paths, + &options.plugin_host, + ) + .map_err(|err| CodeintError::from_cli_error(CliError::Trace(err))) +} + pub fn init(folder: &Path) -> Result { init::init(folder).map_err(|err| CodeintError::from_cli_error(CliError::Init(err))) } @@ -189,6 +227,8 @@ enum CliError { #[error(transparent)] Check(#[from] check::CheckError), #[error(transparent)] + Trace(#[from] trace::TraceCommandError), + #[error(transparent)] Init(#[from] init::InitError), #[error(transparent)] Update(#[from] update::UpdateError), @@ -280,6 +320,23 @@ fn run() -> Result { result_cache, &plugin_host, ), + Command::Trace { + folder, + from, + to, + all, + max_paths, + destination, + format, + plugin_host, + } => { + let options = TraceOptions { + all, + max_paths, + plugin_host, + }; + run_trace(&folder, &from, &to, &destination, format, &options) + } Command::Init { folder } => run_init(&folder), Command::Update { check_only, @@ -363,6 +420,26 @@ fn run_trend( Ok(Outcome::Passed) } +fn run_trace( + folder: &Path, + from: &str, + to: &str, + destination: &ReportDestination, + format: TraceFormat, + options: &TraceOptions, +) -> Result { + let report = trace::trace( + folder, + from, + to, + options.all, + options.max_paths, + &options.plugin_host, + )?; + write_report(&report.render(format)?, destination)?; + Ok(Outcome::Passed) +} + fn write_report(report: &str, destination: &ReportDestination) -> Result<(), CliError> { let text = format!("{report}\n"); match destination { diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index e8553c7..2ce6560 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -3,11 +3,12 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use codeint_config::{ - CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, + CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TraceFormat, TrendFormat, + TrendRange, }; use serde_json::{Value, json}; -use crate::{CheckOptions, DiffOptions, TrendOptions, check, diff, trend}; +use crate::{CheckOptions, DiffOptions, TraceOptions, TrendOptions, check, diff, trace, trend}; const DEFAULT_PROTOCOL_VERSION: &str = "2024-11-05"; @@ -157,6 +158,21 @@ fn handle_tools_list() -> Value { "since": { "type": "string", "description": "UTC date YYYY-MM-DD to start the trend from." } } } + }, + { + "name": "trace", + "description": "Find the shortest runtime import path(s) connecting two repository files.", + "inputSchema": { + "type": "object", + "required": ["from", "to"], + "properties": { + "from": { "type": "string", "description": "Repository-relative path of the starting module." }, + "to": { "type": "string", "description": "Repository-relative path of the target module." }, + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "all": { "type": "boolean", "description": "Return all shortest paths up to max_paths instead of a single shortest path." }, + "max_paths": { "type": "integer", "minimum": 1, "description": "Maximum number of shortest paths to return when all is true (default 10)." } + } + } } ] }) @@ -175,6 +191,7 @@ fn handle_tools_call( "check" => Ok(call_check(args, ctx)), "diff" => Ok(call_diff(args, ctx)), "trend" => Ok(call_trend(args, ctx)), + "trace" => Ok(call_trace(args, ctx)), other => Err((-32602, format!("Unknown tool: {other}"))), } } @@ -263,6 +280,42 @@ fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { } } +fn call_trace(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { + let Some(from) = args.and_then(|a| a.get("from")).and_then(Value::as_str) else { + return tool_err("Missing required argument: from"); + }; + let Some(to) = args.and_then(|a| a.get("to")).and_then(Value::as_str) else { + return tool_err("Missing required argument: to"); + }; + 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); + 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"), + }, + None => TraceOptions::default().max_paths, + }; + let options = TraceOptions { + all, + max_paths, + plugin_host: ctx.plugin_host.clone(), + }; + match trace(&folder, from, to, &options) { + Ok(report) => match report.render(TraceFormat::Json) { + Ok(rendered) => { + let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null); + tool_ok(payload) + } + Err(err) => tool_err(&err.to_string()), + }, + Err(err) => tool_err(&err.to_string()), + } +} + fn resolve_folder(args: Option<&Value>, default_folder: &Path) -> PathBuf { match args.and_then(|a| a.get("path")).and_then(Value::as_str) { Some(p) if !p.is_empty() => { diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 8dc91ef..253c523 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -2,28 +2,25 @@ use codeint_config::{ConfigError, ConfigurationFileError, StarterConfigurationEr use codeint_git::GitError; use codeint_model::{MetricPluginError, WorkspaceError}; use codeint_plugin_host::PluginHostError; +use codeint_report::TraceError; use crate::CliError; use crate::check::CheckError; use crate::init::InitError; +use crate::trace::TraceCommandError; use crate::update::UpdateError; pub(crate) fn remedy(error: &CliError) -> &'static str { match error { CliError::Config(error) => config_remedy(error), - CliError::Check(CheckError::Git(error)) => git_remedy(error), - CliError::Check(CheckError::Configuration(error)) => configuration_file_remedy(error), - CliError::Check(CheckError::Workspace(error)) => workspace_remedy(error), - CliError::Check(CheckError::Resolve(_)) => { - "This is a defect in the Language plugin; report it to the author of the Language plugin." - } - CliError::Check(CheckError::ReferenceRange(_)) => { - "Fix the Reference ranges that the Language plugin supplies, or report the defect to its author." + CliError::Check(error) => check_remedy(error), + CliError::Trace(TraceCommandError::Check(error)) => check_remedy(error), + CliError::Trace(TraceCommandError::UnknownModule { .. }) + | CliError::Trace(TraceCommandError::Trace(TraceError::UnknownModule { .. })) => { + "Pass repository-relative paths of files measured by codeint (not ignored, unparsable, declaration-only, or outside the repository)." } - CliError::Check(CheckError::PluginHost(error)) => plugin_host_remedy(error), - CliError::Check(CheckError::MetricPlugin(error)) => metric_plugin_remedy(error), - CliError::Check(CheckError::ExtensionConflict { .. }) => { - "Assign separate directories to each Language plugin in the languages setting of codeint.json." + CliError::Trace(TraceCommandError::Trace(TraceError::InvalidMaxPaths)) => { + "Pass a positive integer (at least 1) for --max-paths." } CliError::Init(InitError::Git(GitError::NotInRepository { .. })) => { "Run codeint init inside a Git repository; it writes codeint.json at the root of the repository." @@ -43,6 +40,25 @@ pub(crate) fn remedy(error: &CliError) -> &'static str { } } +fn check_remedy(error: &CheckError) -> &'static str { + match error { + CheckError::Git(error) => git_remedy(error), + CheckError::Configuration(error) => configuration_file_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." + } + CheckError::ReferenceRange(_) => { + "Fix the Reference ranges that the Language plugin supplies, or report the defect to its author." + } + 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." + } + } +} + fn update_remedy(error: &UpdateError) -> &'static str { match error { UpdateError::ManagedByPackageManager { .. } => { diff --git a/crates/cli/src/trace.rs b/crates/cli/src/trace.rs new file mode 100644 index 0000000..794b627 --- /dev/null +++ b/crates/cli/src/trace.rs @@ -0,0 +1,81 @@ +use std::path::Path; + +use codeint_config::{PluginHostConfig, read_configuration}; +use codeint_git::Repository; +use codeint_model::{CodeModel, RepoPath}; +use codeint_report::{TraceError, TraceReport}; + +use crate::check::{CheckError, LoadedPlugins, measure_with}; + +#[derive(Debug, thiserror::Error)] +pub(crate) enum TraceCommandError { + #[error(transparent)] + Check(#[from] CheckError), + #[error("file {path:?} is not in the measured Code model")] + UnknownModule { path: String }, + #[error(transparent)] + Trace(#[from] TraceError), +} + +pub(crate) fn trace( + folder: &Path, + from: &str, + to: &str, + all: bool, + max_paths: usize, + plugin_host: &PluginHostConfig, +) -> Result { + let repository = Repository::discover(folder).map_err(CheckError::from)?; + let configuration = read_configuration(repository.root()).map_err(CheckError::from)?; + let loaded = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; + let plugins = loaded.as_named(); + let tree = repository.working_tree().map_err(CheckError::from)?; + let languages = measure_with(&tree, &plugins, &configuration)?; + let model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + let from_path = resolve_model_path(from, folder, repository.root(), &model)?; + let to_path = resolve_model_path(to, folder, repository.root(), &model)?; + Ok(TraceReport::trace( + &model, &from_path, &to_path, all, max_paths, + )?) +} + +fn resolve_model_path( + raw: &str, + folder: &Path, + repository_root: &Path, + model: &CodeModel, +) -> Result { + let normalized = normalize_relative_str(raw); + if let Ok(candidate) = RepoPath::new(normalized) + && model.files.iter().any(|file| file.path == candidate) + { + return Ok(candidate); + } + if let (Ok(canonical_root), Ok(canonical_target)) = ( + std::fs::canonicalize(repository_root), + std::fs::canonicalize(folder.join(raw)), + ) && let Ok(relative) = canonical_target.strip_prefix(&canonical_root) + { + let joined = relative + .components() + .filter_map(|component| component.as_os_str().to_str()) + .collect::>() + .join("/"); + if let Ok(candidate) = RepoPath::new(joined) + && model.files.iter().any(|file| file.path == candidate) + { + return Ok(candidate); + } + } + Err(TraceCommandError::UnknownModule { + path: raw.to_owned(), + }) +} + +fn normalize_relative_str(raw: &str) -> String { + let mut normalized = raw.replace('\\', "/"); + while let Some(stripped) = normalized.strip_prefix("./") { + normalized = stripped.to_owned(); + } + normalized +} diff --git a/crates/cli/tests/common/mod.rs b/crates/cli/tests/common/mod.rs new file mode 100644 index 0000000..b91c2e8 --- /dev/null +++ b/crates/cli/tests/common/mod.rs @@ -0,0 +1,62 @@ +use std::io::Write; +use std::path::Path; +use std::process::{Command, Stdio}; + +use serde_json::Value; +use tempfile::TempDir; + +pub(crate) fn init_git_repo(files: &[(&str, &str)]) -> TempDir { + let dir = TempDir::new().unwrap(); + let run_git = |args: &[&str]| { + let status = Command::new("git") + .args(args) + .current_dir(dir.path()) + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .status() + .unwrap(); + assert!(status.success(), "git {args:?} failed"); + }; + run_git(&["init", "-q", "-b", "main"]); + for (rel, content) in files { + let path = dir.path().join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(path, content).unwrap(); + } + run_git(&["add", "."]); + run_git(&["commit", "-q", "-m", "initial"]); + dir +} + +pub(crate) fn send_mcp_requests(dir: &Path, requests: &[Value]) -> Vec { + let mut child = Command::new(env!("CARGO_BIN_EXE_codeint")) + .arg("mcp") + .current_dir(dir) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + { + let mut stdin = child.stdin.take().unwrap(); + for req in requests { + writeln!(stdin, "{req}").unwrap(); + } + } + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "codeint mcp failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout) + .unwrap() + .lines() + .filter(|l| !l.trim().is_empty()) + .map(|l| serde_json::from_str(l).unwrap()) + .collect() +} diff --git a/crates/cli/tests/mcp.rs b/crates/cli/tests/mcp.rs index 0ef1089..e3c1cf0 100644 --- a/crates/cli/tests/mcp.rs +++ b/crates/cli/tests/mcp.rs @@ -1,67 +1,14 @@ -use std::io::Write; -use std::process::{Command, Stdio}; +mod common; use serde_json::{Value, json}; -use tempfile::TempDir; - -fn init_sample_repo() -> TempDir { - let dir = TempDir::new().unwrap(); - let run_git = |args: &[&str]| { - let status = Command::new("git") - .args(args) - .current_dir(dir.path()) - .env("GIT_AUTHOR_NAME", "Test") - .env("GIT_AUTHOR_EMAIL", "test@example.com") - .env("GIT_COMMITTER_NAME", "Test") - .env("GIT_COMMITTER_EMAIL", "test@example.com") - .status() - .unwrap(); - assert!(status.success(), "git {args:?} failed"); - }; - run_git(&["init", "-q", "-b", "main"]); - std::fs::write( - dir.path().join("app.ts"), - "export function greet(x: number): number {\n return x + 1;\n}\n", - ) - .unwrap(); - run_git(&["add", "."]); - run_git(&["commit", "-q", "-m", "initial"]); - dir -} - -fn send_mcp_requests(dir: &std::path::Path, requests: &[Value]) -> Vec { - let mut child = Command::new(env!("CARGO_BIN_EXE_codeint")) - .arg("mcp") - .current_dir(dir) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .unwrap(); - { - let mut stdin = child.stdin.take().unwrap(); - for req in requests { - writeln!(stdin, "{req}").unwrap(); - } - } - let output = child.wait_with_output().unwrap(); - assert!( - output.status.success(), - "codeint mcp failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - String::from_utf8(output.stdout) - .unwrap() - .lines() - .filter(|l| !l.trim().is_empty()) - .map(|l| serde_json::from_str(l).unwrap()) - .collect() -} #[test] fn mcp_initialize_list_and_call_tools() { - let repo = init_sample_repo(); - let responses = send_mcp_requests( + let repo = common::init_git_repo(&[( + "app.ts", + "export function greet(x: number): number {\n return x + 1;\n}\n", + )]); + let responses = common::send_mcp_requests( repo.path(), &[ json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}}), @@ -77,7 +24,7 @@ fn mcp_initialize_list_and_call_tools() { assert_eq!(responses[0]["result"]["serverInfo"]["name"], "codeint"); let tools = responses[1]["result"]["tools"].as_array().unwrap(); let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["check", "diff", "trend"]); + assert_eq!(names, ["check", "diff", "trend", "trace"]); assert_eq!(responses[2]["result"]["isError"], false); let check_payload: Value = serde_json::from_str( diff --git a/crates/cli/tests/trace.rs b/crates/cli/tests/trace.rs new file mode 100644 index 0000000..5c1f55c --- /dev/null +++ b/crates/cli/tests/trace.rs @@ -0,0 +1,334 @@ +mod common; + +use std::path::Path; +use std::process::{Command, Output}; + +use common::{init_git_repo, send_mcp_requests}; +use serde_json::{Value, json}; + +fn run_codeint(dir: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .args(args) + .current_dir(dir) + .output() + .unwrap() +} + +#[test] +fn trace_finds_shortest_runtime_import_path_in_cli_json_text_and_toon() { + let repo = init_git_repo(&[ + ( + "src/a.ts", + "import { b } from './b';\nimport { d } from './d';\nexport const a = b + d;\n", + ), + ( + "src/b.ts", + "import { c } from './c';\nexport const b = c + 1;\n", + ), + ( + "src/c.ts", + "import { target } from './target';\nexport const c = target + 1;\n", + ), + ( + "src/d.ts", + "import { target } from './target';\nexport const d = target + 2;\n", + ), + ("src/target.ts", "export const target = 42;\n"), + ]); + + let json_output = run_codeint( + repo.path(), + &["trace", "src/a.ts", "src/target.ts", "--format", "json"], + ); + assert!( + json_output.status.success(), + "trace json failed: {}", + String::from_utf8_lossy(&json_output.stderr) + ); + let parsed: Value = serde_json::from_slice(&json_output.stdout).unwrap(); + assert_eq!(parsed["from"], "src/a.ts"); + assert_eq!(parsed["to"], "src/target.ts"); + assert_eq!(parsed["connected"], true); + assert_eq!(parsed["shortest_distance"], 2); + assert_eq!(parsed["truncated"], false); + assert_eq!( + parsed["paths"], + json!([["src/a.ts", "src/d.ts", "src/target.ts"]]) + ); + + let text_output = run_codeint( + repo.path(), + &["trace", "src/a.ts", "src/target.ts", "--format", "text"], + ); + assert!(text_output.status.success()); + let text = String::from_utf8(text_output.stdout).unwrap(); + assert_eq!(text.trim(), "src/a.ts -> src/d.ts -> src/target.ts"); + + let toon_output = run_codeint(repo.path(), &["trace", "src/a.ts", "src/target.ts"]); + assert!(toon_output.status.success()); + let toon = String::from_utf8(toon_output.stdout).unwrap(); + assert!(toon.contains("from: src/a.ts"), "toon output: {toon}"); + assert!(toon.contains("to: src/target.ts"), "toon output: {toon}"); + assert!(toon.contains("connected: true"), "toon output: {toon}"); +} + +#[test] +fn trace_all_returns_multiple_shortest_paths_deterministically_with_cap() { + let repo = init_git_repo(&[ + ( + "src/entry.ts", + "import { m1 } from './m1';\nimport { m2 } from './m2';\nimport { m3 } from './m3';\nexport const e = m1 + m2 + m3;\n", + ), + ( + "src/m1.ts", + "import { leaf } from './leaf';\nexport const m1 = leaf;\n", + ), + ( + "src/m2.ts", + "import { leaf } from './leaf';\nexport const m2 = leaf;\n", + ), + ( + "src/m3.ts", + "import { leaf } from './leaf';\nexport const m3 = leaf;\n", + ), + ("src/leaf.ts", "export const leaf = 1;\n"), + ]); + + let all_output = run_codeint( + repo.path(), + &[ + "trace", + "src/entry.ts", + "src/leaf.ts", + "--all", + "--format", + "json", + ], + ); + assert!(all_output.status.success()); + let parsed: Value = serde_json::from_slice(&all_output.stdout).unwrap(); + assert_eq!(parsed["shortest_distance"], 2); + assert_eq!(parsed["truncated"], false); + assert_eq!( + parsed["paths"], + json!([ + ["src/entry.ts", "src/m1.ts", "src/leaf.ts"], + ["src/entry.ts", "src/m2.ts", "src/leaf.ts"], + ["src/entry.ts", "src/m3.ts", "src/leaf.ts"], + ]) + ); + + let capped_output = run_codeint( + repo.path(), + &[ + "trace", + "src/entry.ts", + "src/leaf.ts", + "--all", + "--max-paths", + "2", + "--format", + "json", + ], + ); + assert!(capped_output.status.success()); + let capped: Value = serde_json::from_slice(&capped_output.stdout).unwrap(); + assert_eq!(capped["truncated"], true); + assert_eq!( + capped["paths"], + json!([ + ["src/entry.ts", "src/m1.ts", "src/leaf.ts"], + ["src/entry.ts", "src/m2.ts", "src/leaf.ts"], + ]) + ); +} + +#[test] +fn trace_handles_cycles_disconnected_modules_and_missing_paths() { + let repo = init_git_repo(&[ + ( + "src/a.ts", + "import { b } from './b';\nexport const a = b;\n", + ), + ( + "src/b.ts", + "import { a } from './a';\nimport { c } from './c';\nexport const b = a + c;\n", + ), + ( + "src/c.ts", + "import { a } from './a';\nexport const c = a;\n", + ), + ("src/isolated.ts", "export const isolated = 0;\n"), + ]); + + let cyclic_output = run_codeint( + repo.path(), + &["trace", "src/a.ts", "src/c.ts", "--all", "--format", "json"], + ); + assert!(cyclic_output.status.success()); + let cyclic: Value = serde_json::from_slice(&cyclic_output.stdout).unwrap(); + assert_eq!(cyclic["connected"], true); + assert_eq!(cyclic["shortest_distance"], 2); + assert_eq!( + cyclic["paths"], + json!([["src/a.ts", "src/b.ts", "src/c.ts"]]) + ); + + let disconnected_output = run_codeint( + repo.path(), + &["trace", "src/a.ts", "src/isolated.ts", "--format", "json"], + ); + assert_eq!(disconnected_output.status.code(), Some(0)); + let disconnected: Value = serde_json::from_slice(&disconnected_output.stdout).unwrap(); + assert_eq!(disconnected["connected"], false); + assert_eq!(disconnected["shortest_distance"], Value::Null); + assert_eq!(disconnected["paths"], json!([])); + assert_eq!(disconnected["truncated"], false); + + let disconnected_text = run_codeint( + repo.path(), + &["trace", "src/a.ts", "src/isolated.ts", "--format", "text"], + ); + assert_eq!(disconnected_text.status.code(), Some(0)); + assert_eq!( + String::from_utf8(disconnected_text.stdout).unwrap().trim(), + "No runtime import path from src/a.ts to src/isolated.ts" + ); + + let missing_output = run_codeint(repo.path(), &["trace", "src/a.ts", "src/does-not-exist.ts"]); + assert_eq!(missing_output.status.code(), Some(2)); + let stderr = String::from_utf8(missing_output.stderr).unwrap(); + assert!( + stderr.contains("src/does-not-exist.ts"), + "expected missing path in stderr, got: {stderr}" + ); +} + +#[test] +fn mcp_trace_tool_returns_paths_and_errors_cleanly() { + let repo = init_git_repo(&[ + ( + "src/a.ts", + "import { b } from './b';\nexport const a = b;\n", + ), + ( + "src/b.ts", + "import { a } from './a';\nimport { c } from './c';\nexport const b = a + c;\n", + ), + ("src/c.ts", "export const c = 1;\n"), + ("src/other.ts", "export const other = 2;\n"), + ]); + + let responses = send_mcp_requests( + repo.path(), + &[ + json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}}), + json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}), + json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "trace", "arguments": {"from": "src/a.ts", "to": "src/c.ts"}}}), + json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "trace", "arguments": {"from": "src/a.ts", "to": "src/other.ts"}}}), + json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "trace", "arguments": {"from": "src/a.ts", "to": "src/missing.ts"}}}), + ], + ); + + assert_eq!(responses.len(), 5); + let tools = responses[1]["result"]["tools"].as_array().unwrap(); + assert!( + tools.iter().any(|tool| tool["name"] == "trace"), + "expected trace tool in tools/list: {tools:?}" + ); + + assert_eq!(responses[2]["result"]["isError"], false); + let found: Value = serde_json::from_str( + responses[2]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(found["connected"], true); + assert_eq!(found["shortest_distance"], 2); + assert_eq!( + found["paths"], + json!([["src/a.ts", "src/b.ts", "src/c.ts"]]) + ); + + assert_eq!(responses[3]["result"]["isError"], false); + let disconnected: Value = serde_json::from_str( + responses[3]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(disconnected["connected"], false); + assert_eq!(disconnected["paths"], json!([])); + + assert_eq!(responses[4]["result"]["isError"], true); + let err_text = responses[4]["result"]["content"][0]["text"] + .as_str() + .unwrap(); + assert!( + err_text.contains("src/missing.ts"), + "expected missing path in MCP error: {err_text}" + ); +} + +#[test] +fn trace_works_across_source_sets_and_python_and_rejects_zero_max_paths() { + let repo = init_git_repo(&[ + ( + "src/app.test.ts", + "import { helper } from './helper';\nexport const tested = helper();\n", + ), + ( + "src/helper.ts", + "import { core } from './core';\nexport function helper(): number { return core; }\n", + ), + ("src/core.ts", "export const core = 7;\n"), + ( + "py/main.py", + "from . import util\n\ndef run():\n return util.value()\n", + ), + ("py/util.py", "def value():\n return 1\n"), + ("py/__init__.py", ""), + ]); + + let cross_set = run_codeint( + repo.path(), + &[ + "trace", + "src/app.test.ts", + "src/core.ts", + "--format", + "json", + ], + ); + assert!(cross_set.status.success()); + let parsed: Value = serde_json::from_slice(&cross_set.stdout).unwrap(); + assert_eq!(parsed["connected"], true); + assert_eq!( + parsed["paths"], + json!([["src/app.test.ts", "src/helper.ts", "src/core.ts"]]) + ); + + let py_trace = run_codeint( + repo.path(), + &["trace", "py/main.py", "py/util.py", "--format", "text"], + ); + assert!(py_trace.status.success()); + assert_eq!( + String::from_utf8(py_trace.stdout).unwrap().trim(), + "py/main.py -> py/util.py" + ); + + let zero_cap = run_codeint( + repo.path(), + &[ + "trace", + "src/app.test.ts", + "src/core.ts", + "--all", + "--max-paths", + "0", + ], + ); + assert_eq!(zero_cap.status.code(), Some(2)); +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 5f9a88b..11016fc 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -93,6 +93,15 @@ pub enum TrendFormat { Markdown, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum TraceFormat { + Toon, + Json, + Text, +} + +pub const DEFAULT_MAX_TRACE_PATHS: usize = 10; + const LATEST_COMMITS_OF_A_TREND: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -128,6 +137,16 @@ pub enum Command { result_cache: Option, plugin_host: PluginHostConfig, }, + Trace { + folder: PathBuf, + from: String, + to: String, + all: bool, + max_paths: usize, + destination: ReportDestination, + format: TraceFormat, + plugin_host: PluginHostConfig, + }, Init { folder: PathBuf, }, @@ -212,6 +231,44 @@ enum CommandArguments { )] format: TrendFormat, }, + #[command(about = "Find the shortest runtime import path between two files in the repository")] + Trace { + #[arg( + value_name = "FROM", + help = "Repository-relative path of the starting module" + )] + from: String, + #[arg( + value_name = "TO", + help = "Repository-relative path of the target module" + )] + to: String, + #[arg( + long, + help = "List all shortest runtime import paths up to --max-paths" + )] + all: bool, + #[arg( + long = "max-paths", + value_name = "COUNT", + default_value_t = DEFAULT_MAX_TRACE_PATHS, + help = "Maximum number of shortest paths to list when --all is set" + )] + max_paths: usize, + #[arg( + long, + value_name = "FILE", + help = "Write the report to this file instead of standard output" + )] + output: Option, + #[arg( + long, + value_enum, + default_value_t = TraceFormat::Toon, + help = "The format of the report" + )] + format: TraceFormat, + }, #[command( about = "Write a starter codeint.json at the root of the Git repository that contains the current folder" )] @@ -231,7 +288,7 @@ enum CommandArguments { version: Option, }, #[command( - about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, and trend tools" + about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, trend, and trace tools" )] Mcp, } @@ -282,6 +339,23 @@ pub fn read_invocation() -> Result { result_cache: result_cache_folder_of_this_process(¤t_folder), plugin_host: plugin_host_config_of_this_process(¤t_folder), }, + CommandArguments::Trace { + from, + to, + all, + max_paths, + output, + format, + } => Command::Trace { + folder: current_folder.clone(), + from, + to, + all, + max_paths, + destination: report_destination(¤t_folder, output)?, + format, + plugin_host: plugin_host_config_of_this_process(¤t_folder), + }, CommandArguments::Init => Command::Init { folder: current_folder, }, diff --git a/crates/metrics/src/lib.rs b/crates/metrics/src/lib.rs index a168e66..fff9f55 100644 --- a/crates/metrics/src/lib.rs +++ b/crates/metrics/src/lib.rs @@ -5,6 +5,7 @@ mod erosion; mod finding_id; mod import_cycles; mod line_share; +mod trace; mod verbosity; pub use duplication::{ @@ -14,4 +15,5 @@ pub use erosion::{ErodedFunction, Erosion, FunctionMasses}; pub use finding_id::FindingId; pub use import_cycles::{ImportCycle, ImportCycles, ModuleShare, UnresolvedImport}; pub use line_share::LineShare; +pub use trace::{DEFAULT_MAX_TRACE_PATHS, TraceError, TraceResult, trace_imports}; pub use verbosity::{FlaggedLineFinding, Verbosity}; diff --git a/crates/metrics/src/trace.rs b/crates/metrics/src/trace.rs new file mode 100644 index 0000000..22bb97f --- /dev/null +++ b/crates/metrics/src/trace.rs @@ -0,0 +1,223 @@ +use std::collections::{BTreeMap, VecDeque}; +use std::error::Error; +use std::fmt; + +use codeint_model::{CodeModel, ImportResolution, RepoPath}; + +#[cfg(test)] +mod tests; + +pub const DEFAULT_MAX_TRACE_PATHS: usize = 10; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TraceError { + UnknownModule { path: RepoPath }, + InvalidMaxPaths, +} + +impl fmt::Display for TraceError { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + TraceError::UnknownModule { path } => { + write!(formatter, "file {path} is not in the measured Code model") + } + TraceError::InvalidMaxPaths => write!(formatter, "max_paths must be at least 1"), + } + } +} + +impl Error for TraceError {} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TraceResult { + pub from: RepoPath, + pub to: RepoPath, + pub connected: bool, + pub shortest_distance: Option, + pub paths: Vec>, + pub truncated: bool, +} + +pub fn trace_imports( + model: &CodeModel, + from: &RepoPath, + to: &RepoPath, + all_shortest: bool, + max_paths: usize, +) -> Result { + if max_paths == 0 { + return Err(TraceError::InvalidMaxPaths); + } + let mut modules: Vec<&RepoPath> = model.files.iter().map(|file| &file.path).collect(); + modules.sort(); + modules.dedup(); + let index_of: BTreeMap<&RepoPath, usize> = modules + .iter() + .enumerate() + .map(|(index, path)| (*path, index)) + .collect(); + let Some(&from_idx) = index_of.get(from) else { + return Err(TraceError::UnknownModule { path: from.clone() }); + }; + let Some(&to_idx) = index_of.get(to) else { + return Err(TraceError::UnknownModule { path: to.clone() }); + }; + if from_idx == to_idx { + return Ok(TraceResult { + from: from.clone(), + to: to.clone(), + connected: true, + shortest_distance: Some(0), + paths: vec![vec![from.clone()]], + truncated: false, + }); + } + let adjacency = build_adjacency(model, &index_of, modules.len()); + let (dist, parents) = shortest_path_dag(&adjacency, from_idx, to_idx); + let Some(target_distance) = dist[to_idx] else { + return Ok(TraceResult { + from: from.clone(), + to: to.clone(), + connected: false, + shortest_distance: None, + paths: Vec::new(), + truncated: false, + }); + }; + let forward = build_forward_shortest_dag(&parents, to_idx, modules.len()); + let limit = if all_shortest { max_paths } else { 1 }; + let (index_paths, truncated) = collect_shortest_paths(&forward, from_idx, to_idx, limit); + let paths = index_paths + .into_iter() + .map(|chain| { + chain + .into_iter() + .map(|index| modules[index].clone()) + .collect() + }) + .collect(); + Ok(TraceResult { + from: from.clone(), + to: to.clone(), + connected: true, + shortest_distance: Some(target_distance), + paths, + truncated: all_shortest && truncated, + }) +} + +fn build_adjacency( + model: &CodeModel, + index_of: &BTreeMap<&RepoPath, usize>, + node_count: usize, +) -> Vec> { + let mut adjacency = vec![Vec::new(); node_count]; + for runtime_import in &model.runtime_imports { + if let ImportResolution::Resolved(target) = &runtime_import.resolution + && let (Some(&from), Some(&to)) = + (index_of.get(&runtime_import.importer), index_of.get(target)) + { + adjacency[from].push(to); + } + } + for neighbors in &mut adjacency { + neighbors.sort_unstable(); + neighbors.dedup(); + } + adjacency +} + +fn shortest_path_dag( + adjacency: &[Vec], + from_idx: usize, + to_idx: usize, +) -> (Vec>, Vec>) { + let node_count = adjacency.len(); + let mut dist = vec![None; node_count]; + let mut parents = vec![Vec::new(); node_count]; + let mut queue = VecDeque::new(); + dist[from_idx] = Some(0); + queue.push_back(from_idx); + while let Some(current) = queue.pop_front() { + let current_dist = dist[current].unwrap_or(0); + if let Some(target_dist) = dist[to_idx] + && current_dist >= target_dist + { + continue; + } + for &next in &adjacency[current] { + match dist[next] { + None => { + dist[next] = Some(current_dist + 1); + parents[next].push(current); + queue.push_back(next); + } + Some(next_dist) if next_dist == current_dist + 1 => { + parents[next].push(current); + } + Some(_) => {} + } + } + } + (dist, parents) +} + +fn build_forward_shortest_dag( + parents: &[Vec], + to_idx: usize, + node_count: usize, +) -> Vec> { + let mut forward = vec![Vec::new(); node_count]; + let mut visited = vec![false; node_count]; + let mut queue = VecDeque::new(); + visited[to_idx] = true; + queue.push_back(to_idx); + while let Some(node) = queue.pop_front() { + for &parent in &parents[node] { + forward[parent].push(node); + if !visited[parent] { + visited[parent] = true; + queue.push_back(parent); + } + } + } + for children in &mut forward { + children.sort_unstable(); + children.dedup(); + } + forward +} + +fn collect_shortest_paths( + forward: &[Vec], + from_idx: usize, + to_idx: usize, + limit: usize, +) -> (Vec>, bool) { + let mut collected = Vec::new(); + let mut truncated = false; + let mut current_path = vec![from_idx]; + let mut stack: Vec<(usize, usize)> = vec![(from_idx, 0)]; + while let Some(&mut (node, ref mut next_child)) = stack.last_mut() { + if node == to_idx { + if collected.len() < limit { + collected.push(current_path.clone()); + } else { + truncated = true; + break; + } + stack.pop(); + current_path.pop(); + continue; + } + if let Some(&child) = forward[node].get(*next_child) { + *next_child += 1; + current_path.push(child); + stack.push((child, 0)); + } else { + stack.pop(); + current_path.pop(); + } + } + (collected, truncated) +} diff --git a/crates/metrics/src/trace/tests.rs b/crates/metrics/src/trace/tests.rs new file mode 100644 index 0000000..647b9f2 --- /dev/null +++ b/crates/metrics/src/trace/tests.rs @@ -0,0 +1,124 @@ +use codeint_model::{ + CodeModel, FileModel, ImportResolution, RepoPath, RuntimeImport, SourceFile, SourceSet, +}; + +use super::{DEFAULT_MAX_TRACE_PATHS, TraceError, trace_imports}; + +fn repo_path(path: &str) -> RepoPath { + RepoPath::new(path).unwrap() +} + +fn model_with_edges(files: &[&str], edges: &[(&str, &str)]) -> CodeModel { + let mut model = CodeModel::default(); + for path in files { + model.files.push(SourceFile { + path: repo_path(path), + model: FileModel { + source_lines: 1, + source_set: SourceSet::Production, + functions: Vec::new(), + tokens: Vec::new(), + flagged_lines: Vec::new(), + runtime_imports: Vec::new(), + }, + }); + } + for (from, to) in edges { + model.runtime_imports.push(RuntimeImport { + importer: repo_path(from), + specifier: (*to).to_owned(), + resolution: ImportResolution::Resolved(repo_path(to)), + }); + } + model +} + +#[test] +fn trace_same_module_returns_zero_distance_single_path() { + let model = model_with_edges(&["a.ts"], &[("a.ts", "a.ts")]); + let result = trace_imports( + &model, + &repo_path("a.ts"), + &repo_path("a.ts"), + true, + DEFAULT_MAX_TRACE_PATHS, + ) + .unwrap(); + assert!(result.connected); + assert_eq!(result.shortest_distance, Some(0)); + assert_eq!(result.paths, vec![vec![repo_path("a.ts")]]); + assert!(!result.truncated); +} + +#[test] +fn trace_single_mode_sets_truncated_false_even_when_multiple_shortest_paths_exist() { + let model = model_with_edges( + &["a.ts", "b.ts", "c.ts", "d.ts"], + &[ + ("a.ts", "c.ts"), + ("a.ts", "b.ts"), + ("b.ts", "d.ts"), + ("c.ts", "d.ts"), + ], + ); + let result = trace_imports( + &model, + &repo_path("a.ts"), + &repo_path("d.ts"), + false, + DEFAULT_MAX_TRACE_PATHS, + ) + .unwrap(); + assert!(result.connected); + assert_eq!(result.shortest_distance, Some(2)); + assert_eq!( + result.paths, + vec![vec![ + repo_path("a.ts"), + repo_path("b.ts"), + repo_path("d.ts") + ]] + ); + assert!(!result.truncated); +} + +#[test] +fn trace_rejects_zero_max_paths_and_unknown_modules() { + let model = model_with_edges(&["a.ts"], &[]); + assert_eq!( + trace_imports(&model, &repo_path("a.ts"), &repo_path("a.ts"), true, 0), + Err(TraceError::InvalidMaxPaths) + ); + assert_eq!( + trace_imports( + &model, + &repo_path("missing.ts"), + &repo_path("a.ts"), + false, + 10 + ), + Err(TraceError::UnknownModule { + path: repo_path("missing.ts") + }) + ); +} + +#[test] +fn trace_terminates_on_dense_cycle_without_looping() { + let model = model_with_edges( + &["a.ts", "b.ts", "c.ts", "d.ts"], + &[ + ("a.ts", "b.ts"), + ("b.ts", "a.ts"), + ("b.ts", "c.ts"), + ("c.ts", "b.ts"), + ("c.ts", "a.ts"), + ("a.ts", "a.ts"), + ], + ); + let result = trace_imports(&model, &repo_path("a.ts"), &repo_path("d.ts"), true, 10).unwrap(); + assert!(!result.connected); + assert_eq!(result.shortest_distance, None); + assert!(result.paths.is_empty()); + assert!(!result.truncated); +} diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index 9d01d58..57526bd 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -20,10 +20,13 @@ mod measurement; mod sarif; #[cfg(test)] mod tests; +mod trace; mod trend; +pub use codeint_metrics::TraceError; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; pub use measurement::CommitMeasurement; +pub use trace::TraceReport; pub use trend::{TrendPoint, TrendReport}; const DECIMAL_SCALE: f64 = 10_000.0; diff --git a/crates/report/src/trace.rs b/crates/report/src/trace.rs new file mode 100644 index 0000000..72b33a5 --- /dev/null +++ b/crates/report/src/trace.rs @@ -0,0 +1,69 @@ +use codeint_config::TraceFormat; +use codeint_metrics::{TraceError, TraceResult, trace_imports}; +use codeint_model::{CodeModel, RepoPath}; +use serde::Serialize; + +use crate::ReportError; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct TraceReport { + pub from: String, + pub to: String, + pub connected: bool, + pub shortest_distance: Option, + pub paths: Vec>, + pub truncated: bool, +} + +impl TraceReport { + pub fn trace( + model: &CodeModel, + from: &RepoPath, + to: &RepoPath, + all_shortest: bool, + max_paths: usize, + ) -> Result { + trace_imports(model, from, to, all_shortest, max_paths).map(TraceReport::of) + } + + pub fn of(result: TraceResult) -> TraceReport { + TraceReport { + from: result.from.to_string(), + to: result.to.to_string(), + connected: result.connected, + shortest_distance: result.shortest_distance, + paths: result + .paths + .into_iter() + .map(|chain| chain.into_iter().map(|path| path.to_string()).collect()) + .collect(), + truncated: result.truncated, + } + } + + pub fn render(&self, format: TraceFormat) -> Result { + match format { + TraceFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), + TraceFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), + TraceFormat::Text => Ok(render_text(self)), + } + } +} + +fn render_text(report: &TraceReport) -> String { + if !report.connected { + return format!( + "No runtime import path from {} to {}", + report.from, report.to + ); + } + let mut lines: Vec = report + .paths + .iter() + .map(|chain| chain.join(" -> ")) + .collect(); + if report.truncated { + lines.push(format!("(truncated at {} paths)", report.paths.len())); + } + lines.join("\n") +} diff --git a/docs/reference.md b/docs/reference.md index a0bd3b8..ac2c2f6 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -26,9 +26,10 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `check` | Measure the working tree and print the report; see [`codeint check`](#codeint-check) | | `diff` | Compare the working tree, or a head Git ref, with the merge-base of a base Git ref; see [`codeint diff`](#codeint-diff) | | `trend` | Measure each commit of the main line and print each Metric over time; see [`codeint trend`](#codeint-trend) | +| `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`, and `trend` tools; see [`codeint mcp`](#codeint-mcp) | +| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, and `trace` tools; see [`codeint mcp`](#codeint-mcp) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -459,6 +460,45 @@ codeint reads each commit from Git objects, so it never checks out a commit and Every commit uses the `codeint.json` of the working tree, as `codeint diff` does. Each commit goes through the [result cache](#result-cache), so a repeated trend measures only the commits that are new since the last run. +### `codeint trace` + +| Argument | Meaning | +| -------- | ------- | +| `` | Repository-relative path of the starting module | +| `` | Repository-relative path of the target module | + +| Option | Meaning | +| ------ | ------- | +| `--all` | List all shortest runtime import paths up to `--max-paths` | +| `--max-paths ` | Maximum number of shortest paths to list when `--all` is set | +| `--output ` | Write the report to this file instead of standard output | +| `--format ` | The format of the report: `toon`, the default, `json`, or `text` | +| `-h, --help` | Print the help of `codeint trace` | + +`codeint trace` finds the shortest runtime import path connecting two measured files in the working tree. +When no runtime import path connects them, it reports `connected: false` and exits with code 0: + +```sh exit=0 +codeint trace src/sign.ts src/parse.ts +``` + +```text stdout +from: src/sign.ts +to: src/parse.ts +connected: false +shortest_distance: null +paths: [] +truncated: false +``` + +These commands exercise `--all`, `--max-paths`, `--output`, and each output format: + +```sh exit=0 +codeint trace src/sign.ts src/parse.ts --format toon +codeint trace src/sign.ts src/parse.ts --format text +codeint trace src/sign.ts src/parse.ts --all --max-paths 5 --format json --output trace.json +``` + ### `codeint update` | Option | Meaning | @@ -486,7 +526,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 three read-only tools (`check`, `diff`, and `trend`) so coding agents can measure Software entropy and fix Regressions before opening a pull request. +It exposes four read-only tools (`check`, `diff`, `trend`, and `trace`) so coding agents can measure Software entropy, inspect import paths, and fix Regressions before opening a pull request. When standard input closes, the server exits with code 0: ```sh exit=0 From a913fbace34bb20c078695ffbc2f5639ba501591 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 08:06:23 +0800 Subject: [PATCH 2/4] feat(cli): add impact blast-radius command and MCP tool Compute transitive reverse-dependency blast radius over the full resolved runtime import graph (preserving Test -> Production edges), supporting direct vs. transitive distances, fan-in/fan-out, transitive import weight, Production vs. Test separation, affected Workspace packages, multiple target paths, --depth caps, --changed via native gix, text/JSON/TOON formats, and the matching MCP impact tool. Closes #180 --- Cargo.lock | 2 + crates/cli/Cargo.toml | 1 + crates/cli/src/impact.rs | 143 +++++++++++++ crates/cli/src/lib.rs | 64 +++++- crates/cli/src/mcp.rs | 68 ++++++- crates/cli/src/remedy.rs | 55 +++-- crates/cli/tests/impact.rs | 385 +++++++++++++++++++++++++++++++++++ crates/cli/tests/mcp.rs | 70 ++++++- crates/config/src/lib.rs | 67 ++++++ crates/git/src/lib.rs | 33 +++ crates/metrics/Cargo.toml | 1 + crates/metrics/src/impact.rs | 217 ++++++++++++++++++++ crates/metrics/src/lib.rs | 2 + crates/report/src/impact.rs | 265 ++++++++++++++++++++++++ crates/report/src/lib.rs | 2 + docs/reference.md | 29 ++- 16 files changed, 1380 insertions(+), 24 deletions(-) create mode 100644 crates/cli/src/impact.rs create mode 100644 crates/cli/tests/impact.rs create mode 100644 crates/metrics/src/impact.rs create mode 100644 crates/report/src/impact.rs diff --git a/Cargo.lock b/Cargo.lock index ef7306e..a1ed559 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -290,6 +290,7 @@ dependencies = [ "codeint-lang-python", "codeint-lang-rust", "codeint-lang-ts", + "codeint-metrics", "codeint-model", "codeint-plugin-host", "codeint-report", @@ -387,6 +388,7 @@ name = "codeint-metrics" version = "0.5.0" dependencies = [ "codeint-model", + "thiserror", ] [[package]] diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index b4a5506..ce7ba53 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -17,6 +17,7 @@ codeint-lang-php = { workspace = true } codeint-lang-python = { workspace = true } codeint-lang-rust = { workspace = true } codeint-lang-ts = { workspace = true } +codeint-metrics = { workspace = true } codeint-model = { workspace = true } codeint-plugin-host = { workspace = true } codeint-report = { workspace = true } diff --git a/crates/cli/src/impact.rs b/crates/cli/src/impact.rs new file mode 100644 index 0000000..e4650eb --- /dev/null +++ b/crates/cli/src/impact.rs @@ -0,0 +1,143 @@ +use std::collections::HashSet; +use std::path::{Component, Path, PathBuf}; + +use codeint_config::{PluginHostConfig, read_configuration}; +use codeint_git::Repository; +use codeint_metrics::{ImpactAnalysis, ImpactError}; +use codeint_model::{CodeModel, RepoPath}; +use codeint_report::{ChangedBase, ImpactReport}; + +use crate::check::{CheckError, LoadedPlugins, measure_with}; + +#[derive(Debug, thiserror::Error)] +pub(crate) enum ImpactCommandError { + #[error(transparent)] + Check(#[from] CheckError), + #[error(transparent)] + Analysis(#[from] ImpactError), + #[error("provide at least one target file path or pass --changed ")] + MissingTargets, + #[error("{path:?} is outside the Git repository")] + PathOutsideRepository { path: String }, + #[error("{path:?} is not a valid repository file path")] + InvalidTargetPath { path: String }, +} + +pub(crate) struct ImpactRequest<'a> { + pub(crate) paths: &'a [String], + pub(crate) changed: Option<&'a str>, + pub(crate) depth: Option, + pub(crate) plugin_host: &'a PluginHostConfig, +} + +pub(crate) fn impact( + folder: &Path, + request: &ImpactRequest<'_>, +) -> Result { + if request.paths.is_empty() && request.changed.is_none() { + return Err(ImpactCommandError::MissingTargets); + } + let repository = Repository::discover(folder).map_err(CheckError::Git)?; + let configuration = read_configuration(repository.root()).map_err(CheckError::Configuration)?; + let loaded = LoadedPlugins::load(repository.root(), &configuration, request.plugin_host)?; + let plugins = loaded.as_named(); + let tree = repository.working_tree().map_err(CheckError::Git)?; + let languages = measure_with(&tree, &plugins, &configuration)?; + let model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + + let mut target_paths = Vec::new(); + for raw in request.paths { + target_paths.push(resolve_target_path(folder, repository.root(), raw)?); + } + + let changed_base = if let Some(base_ref) = request.changed { + let changed = repository + .changed_files_since(base_ref) + .map_err(CheckError::Git)?; + let measured_paths: HashSet<&RepoPath> = + model.files.iter().map(|file| &file.path).collect(); + for path in changed.files { + if measured_paths.contains(&path) { + target_paths.push(path); + } + } + Some(ChangedBase { + git_ref: base_ref.to_owned(), + merge_base: changed.merge_base.to_string(), + }) + } else { + None + }; + + let analysis = ImpactAnalysis::compute(&model, &target_paths, request.depth)?; + Ok(ImpactReport::from_analysis(analysis, changed_base)) +} + +fn resolve_target_path( + folder: &Path, + repo_root: &Path, + raw: &str, +) -> Result { + if raw.is_empty() { + return Err(ImpactCommandError::InvalidTargetPath { + path: raw.to_owned(), + }); + } + let base_folder = std::fs::canonicalize(folder).unwrap_or_else(|_| folder.to_path_buf()); + let root = std::fs::canonicalize(repo_root).unwrap_or_else(|_| repo_root.to_path_buf()); + let candidate = Path::new(raw); + let combined = if candidate.is_absolute() { + candidate.to_path_buf() + } else { + base_folder.join(candidate) + }; + let normalized = normalize_lexical(&combined); + let relative = + normalized + .strip_prefix(&root) + .map_err(|_| ImpactCommandError::PathOutsideRepository { + path: raw.to_owned(), + })?; + let mut segments = Vec::new(); + for component in relative.components() { + match component { + Component::Normal(part) => { + let text = part + .to_str() + .ok_or_else(|| ImpactCommandError::InvalidTargetPath { + path: raw.to_owned(), + })?; + segments.push(text); + } + _ => { + return Err(ImpactCommandError::InvalidTargetPath { + path: raw.to_owned(), + }); + } + } + } + if segments.is_empty() { + return Err(ImpactCommandError::InvalidTargetPath { + path: raw.to_owned(), + }); + } + RepoPath::new(segments.join("/")).map_err(|_| ImpactCommandError::InvalidTargetPath { + path: raw.to_owned(), + }) +} + +fn normalize_lexical(path: &Path) -> PathBuf { + let mut normalized = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + if !normalized.pop() { + normalized.push(component.as_os_str()); + } + } + other => normalized.push(other.as_os_str()), + } + } + normalized +} diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index bec0ed4..f47f58c 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -3,6 +3,7 @@ mod check; mod commit_measurement; mod diff; +mod impact; mod init; mod mcp; mod remedy; @@ -20,9 +21,10 @@ use codeint_git::ResultCache; use codeint_report::ReportError; pub use codeint_config::{ - CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, + CalendarDay, FindingsShown, ImpactFormat, PluginHostConfig, ReportFormat, TrendFormat, + TrendRange, }; -pub use codeint_report::{DiffReport, Report, TrendReport}; +pub use codeint_report::{DiffReport, ImpactReport, Report, TrendReport}; const DEFAULT_WORST_FINDINGS: usize = 20; const DEFAULT_TREND_COMMITS: usize = 20; @@ -78,6 +80,14 @@ impl Default for TrendOptions { } } +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct ImpactOptions { + pub paths: Vec, + pub changed: Option, + pub depth: Option, + pub plugin_host: PluginHostConfig, +} + pub struct CheckOutcome { pub passed: bool, pub failures: Vec, @@ -178,6 +188,17 @@ pub fn trend(folder: &Path, options: &TrendOptions) -> Result Result { + let request = impact::ImpactRequest { + paths: &options.paths, + changed: options.changed.as_deref(), + depth: options.depth, + plugin_host: &options.plugin_host, + }; + impact::impact(folder, &request) + .map_err(|err| CodeintError::from_cli_error(CliError::Impact(err))) +} + pub fn init(folder: &Path) -> Result { init::init(folder).map_err(|err| CodeintError::from_cli_error(CliError::Init(err))) } @@ -189,6 +210,8 @@ enum CliError { #[error(transparent)] Check(#[from] check::CheckError), #[error(transparent)] + Impact(#[from] impact::ImpactCommandError), + #[error(transparent)] Init(#[from] init::InitError), #[error(transparent)] Update(#[from] update::UpdateError), @@ -280,6 +303,23 @@ fn run() -> Result { result_cache, &plugin_host, ), + Command::Impact { + folder, + paths, + changed, + depth, + destination, + format, + plugin_host, + } => run_impact( + &folder, + &paths, + changed.as_deref(), + depth, + &destination, + format, + &plugin_host, + ), Command::Init { folder } => run_init(&folder), Command::Update { check_only, @@ -363,6 +403,26 @@ fn run_trend( Ok(Outcome::Passed) } +fn run_impact( + folder: &Path, + paths: &[String], + changed: Option<&str>, + depth: Option, + destination: &ReportDestination, + format: ImpactFormat, + plugin_host: &PluginHostConfig, +) -> Result { + let request = impact::ImpactRequest { + paths, + changed, + depth, + plugin_host, + }; + let report = impact::impact(folder, &request)?; + write_report(&report.render(format)?, destination)?; + Ok(Outcome::Passed) +} + fn write_report(report: &str, destination: &ReportDestination) -> Result<(), CliError> { let text = format!("{report}\n"); match destination { diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index e8553c7..b5e8785 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -3,11 +3,12 @@ use std::path::{Path, PathBuf}; use std::str::FromStr; use codeint_config::{ - CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, + CalendarDay, FindingsShown, ImpactFormat, PluginHostConfig, ReportFormat, TrendFormat, + TrendRange, }; use serde_json::{Value, json}; -use crate::{CheckOptions, DiffOptions, TrendOptions, check, diff, trend}; +use crate::{CheckOptions, DiffOptions, ImpactOptions, TrendOptions, check, diff, impact, trend}; const DEFAULT_PROTOCOL_VERSION: &str = "2024-11-05"; @@ -157,6 +158,23 @@ fn handle_tools_list() -> Value { "since": { "type": "string", "description": "UTC date YYYY-MM-DD to start the trend from." } } } + }, + { + "name": "impact", + "description": "Compute the transitive reverse-dependency blast radius of one or more repository files (or files changed since a base Git ref), separating Production and Test dependents and listing affected Workspace packages.", + "inputSchema": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "paths": { + "type": "array", + "items": { "type": "string" }, + "description": "Repository-relative file paths to analyze." + }, + "changed": { "type": "string", "description": "Optional base Git ref; analyze files changed since its merge-base with HEAD." }, + "depth": { "type": "integer", "minimum": 0, "description": "Optional maximum reverse-dependency hop distance to traverse." } + } + } } ] }) @@ -175,6 +193,7 @@ fn handle_tools_call( "check" => Ok(call_check(args, ctx)), "diff" => Ok(call_diff(args, ctx)), "trend" => Ok(call_trend(args, ctx)), + "impact" => Ok(call_impact(args, ctx)), other => Err((-32602, format!("Unknown tool: {other}"))), } } @@ -263,6 +282,51 @@ fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { } } +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(), + }; + 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"), + }, + None => None, + }; + let options = ImpactOptions { + paths, + changed, + depth, + plugin_host: ctx.plugin_host.clone(), + }; + match impact(&folder, &options) { + Ok(report) => match report.render(ImpactFormat::Json) { + Ok(rendered) => { + let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null); + tool_ok(payload) + } + Err(err) => tool_err(&err.to_string()), + }, + Err(err) => tool_err(&err.to_string()), + } +} + fn resolve_folder(args: Option<&Value>, default_folder: &Path) -> PathBuf { match args.and_then(|a| a.get("path")).and_then(Value::as_str) { Some(p) if !p.is_empty() => { diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 8dc91ef..fb36700 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -1,30 +1,20 @@ use codeint_config::{ConfigError, ConfigurationFileError, StarterConfigurationError}; use codeint_git::GitError; +use codeint_metrics::ImpactError; use codeint_model::{MetricPluginError, WorkspaceError}; use codeint_plugin_host::PluginHostError; use crate::CliError; use crate::check::CheckError; +use crate::impact::ImpactCommandError; use crate::init::InitError; use crate::update::UpdateError; pub(crate) fn remedy(error: &CliError) -> &'static str { match error { CliError::Config(error) => config_remedy(error), - CliError::Check(CheckError::Git(error)) => git_remedy(error), - CliError::Check(CheckError::Configuration(error)) => configuration_file_remedy(error), - CliError::Check(CheckError::Workspace(error)) => workspace_remedy(error), - CliError::Check(CheckError::Resolve(_)) => { - "This is a defect in the Language plugin; report it to the author of the Language plugin." - } - CliError::Check(CheckError::ReferenceRange(_)) => { - "Fix the Reference ranges that the Language plugin supplies, or report the defect to its author." - } - CliError::Check(CheckError::PluginHost(error)) => plugin_host_remedy(error), - CliError::Check(CheckError::MetricPlugin(error)) => metric_plugin_remedy(error), - CliError::Check(CheckError::ExtensionConflict { .. }) => { - "Assign separate directories to each Language plugin in the languages setting of codeint.json." - } + CliError::Check(error) => check_remedy(error), + CliError::Impact(error) => impact_remedy(error), CliError::Init(InitError::Git(GitError::NotInRepository { .. })) => { "Run codeint init inside a Git repository; it writes codeint.json at the root of the repository." } @@ -43,6 +33,43 @@ pub(crate) fn remedy(error: &CliError) -> &'static str { } } +fn check_remedy(error: &CheckError) -> &'static str { + match error { + CheckError::Git(error) => git_remedy(error), + CheckError::Configuration(error) => configuration_file_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." + } + CheckError::ReferenceRange(_) => { + "Fix the Reference ranges that the Language plugin supplies, or report the defect to its author." + } + 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." + } + } +} + +fn impact_remedy(error: &ImpactCommandError) -> &'static str { + match error { + ImpactCommandError::Check(error) => check_remedy(error), + ImpactCommandError::Analysis(ImpactError::TargetNotInCodeModel { .. }) => { + "Pass a tracked or non-ignored source file that a Language plugin measures, or check the file path." + } + ImpactCommandError::MissingTargets => { + "Pass one or more repository file paths, or pass --changed to analyze changed files." + } + ImpactCommandError::PathOutsideRepository { .. } => { + "Pass a file path inside the Git repository." + } + ImpactCommandError::InvalidTargetPath { .. } => { + "Pass a repository-relative file path using forward slashes." + } + } +} + fn update_remedy(error: &UpdateError) -> &'static str { match error { UpdateError::ManagedByPackageManager { .. } => { diff --git a/crates/cli/tests/impact.rs b/crates/cli/tests/impact.rs new file mode 100644 index 0000000..f9c236f --- /dev/null +++ b/crates/cli/tests/impact.rs @@ -0,0 +1,385 @@ +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +use serde_json::Value; +use tempfile::TempDir; + +const GIT_ENV: [(&str, &str); 6] = [ + ("GIT_CONFIG_GLOBAL", "/dev/null"), + ("GIT_CONFIG_NOSYSTEM", "1"), + ("GIT_AUTHOR_NAME", "ImpactTest"), + ("GIT_AUTHOR_EMAIL", "impact@example.invalid"), + ("GIT_COMMITTER_NAME", "ImpactTest"), + ("GIT_COMMITTER_EMAIL", "impact@example.invalid"), +]; + +struct RepoFixture { + dir: TempDir, +} + +impl RepoFixture { + fn new() -> RepoFixture { + let fixture = RepoFixture { + dir: tempfile::tempdir().expect("tempdir"), + }; + fixture.git(&["init", "--quiet", "--initial-branch", "main"]); + fixture + } + + fn root(&self) -> &Path { + self.dir.path() + } + + fn write(&self, relative: &str, content: &str) { + let full = self.root().join(relative); + if let Some(parent) = full.parent() { + fs::create_dir_all(parent).expect("create parent"); + } + fs::write(full, content).expect("write file"); + } + + fn git(&self, args: &[&str]) -> String { + let mut cmd = Command::new("git"); + cmd.args(args).current_dir(self.root()); + for (k, v) in GIT_ENV { + cmd.env(k, v); + } + let output = cmd.output().expect("run git"); + assert!( + output.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).expect("utf8") + } + + fn commit(&self, msg: &str) { + self.git(&["add", "--all"]); + self.git(&["commit", "--quiet", "--message", msg]); + } + + fn run_impact(&self, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .arg("impact") + .args(args) + .current_dir(self.root()) + .output() + .expect("run codeint impact") + } + + fn impact_json(&self, args: &[&str]) -> Value { + let mut full_args = args.to_vec(); + full_args.extend(["--format", "json"]); + let output = self.run_impact(&full_args); + assert_eq!( + output.status.code(), + Some(0), + "codeint impact failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("valid JSON") + } +} + +fn dependent_paths_and_distances(list: &Value) -> Vec<(String, u64)> { + list.as_array() + .expect("array") + .iter() + .map(|item| { + ( + item["path"].as_str().expect("path").to_owned(), + item["distance"].as_u64().expect("distance"), + ) + }) + .collect() +} + +#[test] +fn impact_reports_direct_and_transitive_dependents_separating_production_and_test() { + let repo = RepoFixture::new(); + repo.write("src/leaf.ts", "export const leaf = 1;\n"); + repo.write( + "src/mid.ts", + "import { leaf } from './leaf';\nexport const mid = leaf + 1;\n", + ); + repo.write( + "src/app.ts", + "import { mid } from './mid';\nexport const app = mid + 1;\n", + ); + repo.write("src/unrelated.ts", "export const unrelated = 0;\n"); + repo.write( + "src/leaf.test.ts", + "import { leaf } from './leaf';\nexport const testLeaf = leaf;\n", + ); + repo.write( + "src/mid.test.ts", + "import { mid } from './mid';\nexport const testMid = mid;\n", + ); + repo.commit("initial"); + + let report = repo.impact_json(&["src/leaf.ts"]); + + assert_eq!(report["targets"].as_array().expect("targets").len(), 1); + let target = &report["targets"][0]; + assert_eq!(target["path"], "src/leaf.ts"); + assert_eq!(target["source_set"], "production"); + assert_eq!(target["fan_in"], 2); + assert_eq!(target["fan_out"], 0); + assert_eq!(target["transitive_import_weight"], 4); + + assert_eq!(report["summary"]["direct_dependents"], 2); + assert_eq!(report["summary"]["transitive_dependents"], 2); + assert_eq!(report["summary"]["total_dependents"], 4); + assert_eq!(report["summary"]["fan_in"], 2); + assert_eq!(report["summary"]["fan_out"], 0); + assert_eq!(report["summary"]["transitive_import_weight"], 4); + + assert_eq!( + dependent_paths_and_distances(&report["production"]["direct"]), + vec![("src/mid.ts".to_owned(), 1)] + ); + assert_eq!( + dependent_paths_and_distances(&report["production"]["transitive"]), + vec![("src/app.ts".to_owned(), 2)] + ); + assert_eq!( + dependent_paths_and_distances(&report["test"]["direct"]), + vec![("src/leaf.test.ts".to_owned(), 1)] + ); + assert_eq!( + dependent_paths_and_distances(&report["test"]["transitive"]), + vec![("src/mid.test.ts".to_owned(), 2)] + ); +} + +#[test] +fn impact_supports_depth_cap_and_handles_import_cycles_without_looping() { + let repo = RepoFixture::new(); + repo.write( + "src/a.ts", + "import { c } from './c';\nexport const a = () => c;\n", + ); + repo.write( + "src/b.ts", + "import { a } from './a';\nexport const b = () => a;\n", + ); + repo.write( + "src/c.ts", + "import { b } from './b';\nexport const c = () => b;\n", + ); + repo.write( + "src/entry.ts", + "import { c } from './c';\nexport const entry = () => c;\n", + ); + repo.commit("cycle"); + + let full = repo.impact_json(&["src/a.ts"]); + assert_eq!( + dependent_paths_and_distances(&full["production"]["direct"]), + vec![("src/b.ts".to_owned(), 1)] + ); + assert_eq!( + dependent_paths_and_distances(&full["production"]["transitive"]), + vec![("src/c.ts".to_owned(), 2), ("src/entry.ts".to_owned(), 3),] + ); + assert_eq!(full["targets"][0]["fan_in"], 1); + assert_eq!(full["targets"][0]["fan_out"], 1); + assert_eq!(full["targets"][0]["transitive_import_weight"], 3); + + let capped = repo.impact_json(&["src/a.ts", "--depth", "1"]); + assert_eq!(capped["depth_limit"], 1); + assert_eq!( + dependent_paths_and_distances(&capped["production"]["direct"]), + vec![("src/b.ts".to_owned(), 1)] + ); + assert_eq!( + dependent_paths_and_distances(&capped["production"]["transitive"]), + Vec::<(String, u64)>::new() + ); + assert_eq!(capped["summary"]["total_dependents"], 1); +} + +#[test] +fn impact_supports_multiple_target_paths_with_deterministic_ordering() { + let repo = RepoFixture::new(); + repo.write("src/a.ts", "export const a = 1;\n"); + repo.write("src/b.ts", "export const b = 2;\n"); + repo.write( + "src/z_direct.ts", + "import { a } from './a';\nexport const z = a;\n", + ); + repo.write( + "src/c_direct.ts", + "import { b } from './b';\nexport const c = b;\n", + ); + repo.write( + "src/top.ts", + "import { c } from './c_direct';\nimport { z } from './z_direct';\nexport const top = c + z;\n", + ); + repo.commit("multi"); + + let report = repo.impact_json(&["src/b.ts", "src/a.ts"]); + let target_paths: Vec<&str> = report["targets"] + .as_array() + .expect("targets") + .iter() + .map(|t| t["path"].as_str().expect("path")) + .collect(); + assert_eq!(target_paths, vec!["src/a.ts", "src/b.ts"]); + assert_eq!( + dependent_paths_and_distances(&report["production"]["direct"]), + vec![ + ("src/c_direct.ts".to_owned(), 1), + ("src/z_direct.ts".to_owned(), 1), + ] + ); + assert_eq!( + dependent_paths_and_distances(&report["production"]["transitive"]), + vec![("src/top.ts".to_owned(), 2)] + ); +} + +#[test] +fn impact_supports_changed_base_using_git_merge_base() { + let repo = RepoFixture::new(); + repo.write("src/core.ts", "export const core = 1;\n"); + repo.write( + "src/service.ts", + "import { core } from './core';\nexport const service = core + 1;\n", + ); + repo.write("src/other.ts", "export const other = 1;\n"); + repo.commit("base"); + let merge_base = repo.git(&["rev-parse", "HEAD"]).trim().to_owned(); + + repo.git(&["switch", "--quiet", "--create", "feature"]); + repo.write("src/core.ts", "export const core = 42;\n"); + repo.write("README.md", "# docs change\n"); + repo.commit("feature change"); + + repo.git(&["switch", "--quiet", "main"]); + repo.write("src/other.ts", "export const other = 99;\n"); + repo.commit("main advance"); + + repo.git(&["switch", "--quiet", "feature"]); + + let report = repo.impact_json(&["--changed", "main"]); + assert_eq!(report["changed_base"]["ref"], "main"); + assert_eq!(report["changed_base"]["merge_base"], merge_base); + let target_paths: Vec<&str> = report["targets"] + .as_array() + .expect("targets") + .iter() + .map(|t| t["path"].as_str().expect("path")) + .collect(); + assert_eq!(target_paths, vec!["src/core.ts"]); + assert_eq!( + dependent_paths_and_distances(&report["production"]["direct"]), + vec![("src/service.ts".to_owned(), 1)] + ); +} + +#[test] +fn impact_lists_affected_workspace_packages_in_monorepo() { + let repo = RepoFixture::new(); + repo.write( + "package.json", + r#"{ "name": "mono", "private": true, "workspaces": ["packages/*"] }"#, + ); + repo.write( + "packages/core/package.json", + r#"{ "name": "@mono/core", "main": "src/index.ts" }"#, + ); + repo.write("packages/core/src/index.ts", "export const coreVal = 1;\n"); + repo.write( + "packages/api/package.json", + r#"{ "name": "@mono/api", "main": "src/index.ts" }"#, + ); + repo.write( + "packages/api/src/index.ts", + "import { coreVal } from '../../core/src/index';\nexport const apiVal = coreVal + 1;\n", + ); + repo.write( + "packages/web/package.json", + r#"{ "name": "@mono/web", "main": "src/index.ts" }"#, + ); + repo.write( + "packages/web/src/index.ts", + "import { apiVal } from '../../api/src/index';\nexport const webVal = apiVal + 1;\n", + ); + repo.commit("monorepo"); + + let report = repo.impact_json(&["packages/core/src/index.ts"]); + let affected: Vec<&str> = report["affected_packages"] + .as_array() + .expect("affected_packages") + .iter() + .map(|v| v.as_str().expect("pkg")) + .collect(); + assert_eq!(affected, vec!["packages/api", "packages/web"]); + assert_eq!(report["targets"][0]["package"], "packages/core"); +} + +#[test] +fn impact_renders_text_and_toon_formats() { + let repo = RepoFixture::new(); + repo.write("src/util.ts", "export const util = 1;\n"); + repo.write( + "src/app.ts", + "import { util } from './util';\nexport const app = util;\n", + ); + repo.write( + "src/util.test.ts", + "import { util } from './util';\nexport const t = util;\n", + ); + repo.commit("formats"); + + let text_out = repo.run_impact(&["src/util.ts", "--format", "text"]); + assert_eq!(text_out.status.code(), Some(0)); + let text = String::from_utf8(text_out.stdout).expect("utf8"); + assert!(text.contains("Targets (1):"), "missing targets: {text}"); + assert!(text.contains("src/util.ts"), "missing target path: {text}"); + assert!( + text.contains("Production dependents (1):"), + "missing production section: {text}" + ); + assert!(text.contains("src/app.ts"), "missing prod dep: {text}"); + assert!( + text.contains("Test dependents (1):"), + "missing test section: {text}" + ); + assert!( + text.contains("src/util.test.ts"), + "missing test dep: {text}" + ); + + let toon_out = repo.run_impact(&["src/util.ts", "--format", "toon"]); + assert_eq!(toon_out.status.code(), Some(0)); + let toon_str = String::from_utf8(toon_out.stdout).expect("utf8"); + let decoded: Value = toon_format::decode_default(&toon_str).expect("valid TOON"); + assert_eq!(decoded["summary"]["total_dependents"], 2); +} + +#[test] +fn impact_errors_when_target_is_not_in_measured_code_model() { + let repo = RepoFixture::new(); + repo.write("src/real.ts", "export const real = 1;\n"); + repo.commit("initial"); + + let missing = repo.run_impact(&["src/missing.ts"]); + assert_eq!(missing.status.code(), Some(2)); + assert!(missing.stdout.is_empty()); + let stderr = String::from_utf8_lossy(&missing.stderr); + assert!( + stderr.contains("src/missing.ts is not in the measured Code model"), + "unexpected stderr: {stderr}" + ); + + let outside = repo.run_impact(&["../outside.ts"]); + assert_eq!(outside.status.code(), Some(2)); + let outside_err = String::from_utf8_lossy(&outside.stderr); + assert!( + outside_err.contains("outside the Git repository"), + "unexpected stderr: {outside_err}" + ); +} diff --git a/crates/cli/tests/mcp.rs b/crates/cli/tests/mcp.rs index 0ef1089..7071b74 100644 --- a/crates/cli/tests/mcp.rs +++ b/crates/cli/tests/mcp.rs @@ -70,14 +70,15 @@ fn mcp_initialize_list_and_call_tools() { json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "check", "arguments": {}}}), json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "diff", "arguments": {"base_ref": "main"}}}), json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "trend", "arguments": {}}}), - json!({"jsonrpc": "2.0", "id": 6, "method": "unknown/method"}), + json!({"jsonrpc": "2.0", "id": 6, "method": "tools/call", "params": {"name": "impact", "arguments": {"paths": ["app.ts"]}}}), + json!({"jsonrpc": "2.0", "id": 7, "method": "unknown/method"}), ], ); - assert_eq!(responses.len(), 6); + assert_eq!(responses.len(), 7); assert_eq!(responses[0]["result"]["serverInfo"]["name"], "codeint"); let tools = responses[1]["result"]["tools"].as_array().unwrap(); let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["check", "diff", "trend"]); + assert_eq!(names, ["check", "diff", "trend", "impact"]); assert_eq!(responses[2]["result"]["isError"], false); let check_payload: Value = serde_json::from_str( @@ -91,5 +92,66 @@ fn mcp_initialize_list_and_call_tools() { assert_eq!(responses[3]["result"]["isError"], false); assert_eq!(responses[4]["result"]["isError"], false); - assert_eq!(responses[5]["error"]["code"], -32601); + assert_eq!(responses[5]["result"]["isError"], false); + let impact_payload: Value = serde_json::from_str( + responses[5]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(impact_payload["targets"][0]["path"], "app.ts"); + assert_eq!(impact_payload["summary"]["total_dependents"], 0); + assert_eq!(responses[6]["error"]["code"], -32601); +} + +#[test] +fn mcp_impact_tool_reports_blast_radius_depth_and_errors() { + let repo = init_sample_repo(); + std::fs::write( + repo.path().join("consumer.ts"), + "import { greet } from './app';\nexport const run = () => greet(1);\n", + ) + .unwrap(); + std::fs::write( + repo.path().join("app.test.ts"), + "import { greet } from './app';\nexport const testGreet = greet(2);\n", + ) + .unwrap(); + let responses = send_mcp_requests( + repo.path(), + &[ + json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "impact", "arguments": {"paths": ["app.ts"], "depth": 1}}}), + json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "impact", "arguments": {"changed": "main"}}}), + json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "impact", "arguments": {"paths": ["missing.ts"]}}}), + ], + ); + assert_eq!(responses.len(), 3); + assert_eq!(responses[0]["result"]["isError"], false); + let direct: Value = serde_json::from_str( + responses[0]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(direct["summary"]["direct_dependents"], 2); + assert_eq!(direct["production"]["direct"][0]["path"], "consumer.ts"); + assert_eq!(direct["test"]["direct"][0]["path"], "app.test.ts"); + + assert_eq!(responses[1]["result"]["isError"], false); + let changed: Value = serde_json::from_str( + responses[1]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(changed["changed_base"]["ref"], "main"); + assert_eq!(changed["targets"].as_array().unwrap().len(), 2); + + assert_eq!(responses[2]["result"]["isError"], true); + assert!( + responses[2]["result"]["content"][0]["text"] + .as_str() + .unwrap() + .contains("missing.ts is not in the measured Code model") + ); } diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 5f9a88b..9260492 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -93,6 +93,13 @@ pub enum TrendFormat { Markdown, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] +pub enum ImpactFormat { + Toon, + Json, + Text, +} + const LATEST_COMMITS_OF_A_TREND: usize = 20; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -128,6 +135,15 @@ pub enum Command { result_cache: Option, plugin_host: PluginHostConfig, }, + Impact { + folder: PathBuf, + paths: Vec, + changed: Option, + depth: Option, + destination: ReportDestination, + format: ImpactFormat, + plugin_host: PluginHostConfig, + }, Init { folder: PathBuf, }, @@ -212,6 +228,42 @@ enum CommandArguments { )] format: TrendFormat, }, + #[command( + about = "Compute the transitive reverse-dependency blast radius of one or more repository files" + )] + Impact { + #[arg( + value_name = "PATH", + required_unless_present = "changed", + help = "Repository file paths to analyze" + )] + paths: Vec, + #[arg( + long, + value_name = "BASE_REF", + help = "Analyze files changed since the merge-base of this Git ref and HEAD" + )] + changed: Option, + #[arg( + long, + value_name = "N", + help = "Maximum reverse-dependency hop distance to traverse" + )] + depth: Option, + #[arg( + long, + value_name = "FILE", + help = "Write the report to this file instead of standard output" + )] + output: Option, + #[arg( + long, + value_enum, + default_value_t = ImpactFormat::Toon, + help = "The format of the report" + )] + format: ImpactFormat, + }, #[command( about = "Write a starter codeint.json at the root of the Git repository that contains the current folder" )] @@ -282,6 +334,21 @@ pub fn read_invocation() -> Result { result_cache: result_cache_folder_of_this_process(¤t_folder), plugin_host: plugin_host_config_of_this_process(¤t_folder), }, + CommandArguments::Impact { + paths, + changed, + depth, + output, + format, + } => Command::Impact { + folder: current_folder.clone(), + paths, + changed, + depth, + destination: report_destination(¤t_folder, output)?, + format, + plugin_host: plugin_host_config_of_this_process(¤t_folder), + }, CommandArguments::Init => Command::Init { folder: current_folder, }, diff --git a/crates/git/src/lib.rs b/crates/git/src/lib.rs index 54c7c7c..2e2d288 100644 --- a/crates/git/src/lib.rs +++ b/crates/git/src/lib.rs @@ -97,6 +97,11 @@ pub struct Repository { root: PathBuf, } +pub struct ChangedFiles { + pub merge_base: CommitId, + pub files: Vec, +} + pub struct Snapshot { files: Vec, submodules: Vec, @@ -224,6 +229,27 @@ impl Repository { }, }) } + + pub fn changed_files_since(&self, base_ref: &str) -> Result { + let merge_base = self.merge_base_with_head(base_ref)?; + let base = self.commit(merge_base)?; + let working = self.working_tree()?; + let mut changed = Vec::new(); + for path in working.files() { + let is_changed = match base.contains_file(path) { + false => true, + true => working.read(path)? != base.read(path)?, + }; + if is_changed { + changed.push(path.clone()); + } + } + changed.sort(); + Ok(ChangedFiles { + merge_base, + files: changed, + }) + } } impl Snapshot { @@ -235,6 +261,13 @@ impl Snapshot { &self.submodules } + fn contains_file(&self, path: &RepoPath) -> bool { + match &self.contents { + Contents::Commit { blobs, .. } => blobs.contains_key(path), + Contents::WorkingTree { .. } => self.files.binary_search(path).is_ok(), + } + } + pub fn working_tree_reader(&self) -> Option> { match &self.contents { Contents::WorkingTree { root } => Some(WorkingTreeReader { root }), diff --git a/crates/metrics/Cargo.toml b/crates/metrics/Cargo.toml index a112b64..56a2ec4 100644 --- a/crates/metrics/Cargo.toml +++ b/crates/metrics/Cargo.toml @@ -7,6 +7,7 @@ publish.workspace = true [dependencies] codeint-model = { workspace = true } +thiserror = { workspace = true } [lints] workspace = true diff --git a/crates/metrics/src/impact.rs b/crates/metrics/src/impact.rs new file mode 100644 index 0000000..8ac04b3 --- /dev/null +++ b/crates/metrics/src/impact.rs @@ -0,0 +1,217 @@ +use std::collections::{BTreeSet, HashMap, VecDeque}; + +use codeint_model::{CodeModel, ImportResolution, RepoPath, SourceSet}; + +#[derive(Debug, thiserror::Error)] +pub enum ImpactError { + #[error("{path} is not in the measured Code model")] + TargetNotInCodeModel { path: RepoPath }, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImpactTarget { + pub path: RepoPath, + pub source_set: SourceSet, + pub package: Option, + pub fan_in: usize, + pub fan_out: usize, + pub transitive_import_weight: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImpactDependent { + pub path: RepoPath, + pub distance: usize, + pub source_set: SourceSet, + pub package: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ImpactSummary { + pub direct_dependents: usize, + pub transitive_dependents: usize, + pub total_dependents: usize, + pub fan_in: usize, + pub fan_out: usize, + pub transitive_import_weight: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImpactAnalysis { + pub targets: Vec, + pub depth_limit: Option, + pub summary: ImpactSummary, + pub dependents: Vec, + pub affected_packages: Vec, +} + +impl ImpactAnalysis { + pub fn compute( + model: &CodeModel, + targets: &[RepoPath], + max_depth: Option, + ) -> Result { + let index_of: HashMap<&RepoPath, usize> = model + .files + .iter() + .enumerate() + .map(|(index, file)| (&file.path, index)) + .collect(); + + let mut unique_target_indices: BTreeSet = BTreeSet::new(); + for target in targets { + let Some(&index) = index_of.get(target) else { + return Err(ImpactError::TargetNotInCodeModel { + path: target.clone(), + }); + }; + unique_target_indices.insert(index); + } + + let mut forward: Vec> = vec![BTreeSet::new(); model.files.len()]; + let mut reverse: Vec> = vec![BTreeSet::new(); model.files.len()]; + for runtime_import in &model.runtime_imports { + if let ImportResolution::Resolved(target) = &runtime_import.resolution + && let (Some(&from), Some(&to)) = + (index_of.get(&runtime_import.importer), index_of.get(target)) + && from != to + { + forward[from].insert(to); + reverse[to].insert(from); + } + } + + let has_workspace_members = model.workspace.has_members(); + let package_name = |path: &RepoPath| -> Option { + has_workspace_members.then(|| model.workspace.package_of(path).to_string()) + }; + + let mut target_rows: Vec = unique_target_indices + .iter() + .map(|&index| { + let file = &model.files[index]; + ImpactTarget { + path: file.path.clone(), + source_set: file.model.source_set, + package: package_name(&file.path), + fan_in: reverse[index].len(), + fan_out: forward[index].len(), + transitive_import_weight: reverse_reachable_count(&reverse, index, max_depth), + } + }) + .collect(); + target_rows.sort_by(|left, right| left.path.cmp(&right.path)); + + let distances = multi_source_reverse_bfs(&reverse, &unique_target_indices, max_depth); + let mut dependents: Vec = distances + .into_iter() + .enumerate() + .filter_map(|(index, distance)| { + let distance = distance?; + if distance == 0 { + return None; + } + let file = &model.files[index]; + Some(ImpactDependent { + path: file.path.clone(), + distance, + source_set: file.model.source_set, + package: package_name(&file.path), + }) + }) + .collect(); + dependents.sort_by(|left, right| { + left.distance + .cmp(&right.distance) + .then_with(|| left.path.cmp(&right.path)) + }); + + let direct_dependents = dependents.iter().filter(|dep| dep.distance == 1).count(); + let transitive_dependents = dependents.len() - direct_dependents; + let total_dependents = dependents.len(); + + let fan_out = unique_target_indices + .iter() + .flat_map(|&index| forward[index].iter().copied()) + .filter(|target_import| !unique_target_indices.contains(target_import)) + .collect::>() + .len(); + + let affected_packages: Vec = if has_workspace_members { + dependents + .iter() + .filter_map(|dep| dep.package.clone()) + .collect::>() + .into_iter() + .collect() + } else { + Vec::new() + }; + + Ok(ImpactAnalysis { + targets: target_rows, + depth_limit: max_depth, + summary: ImpactSummary { + direct_dependents, + transitive_dependents, + total_dependents, + fan_in: direct_dependents, + fan_out, + transitive_import_weight: total_dependents, + }, + dependents, + affected_packages, + }) + } +} + +fn reverse_reachable_count( + reverse: &[BTreeSet], + start: usize, + max_depth: Option, +) -> usize { + let mut visited = vec![false; reverse.len()]; + visited[start] = true; + let mut queue = VecDeque::new(); + queue.push_back((start, 0_usize)); + let mut count = 0; + while let Some((node, depth)) = queue.pop_front() { + if max_depth.is_some_and(|limit| depth >= limit) { + continue; + } + for &neighbor in &reverse[node] { + if !visited[neighbor] { + visited[neighbor] = true; + count += 1; + queue.push_back((neighbor, depth + 1)); + } + } + } + count +} + +fn multi_source_reverse_bfs( + reverse: &[BTreeSet], + starts: &BTreeSet, + max_depth: Option, +) -> Vec> { + let mut distances = vec![None; reverse.len()]; + let mut queue = VecDeque::new(); + for &start in starts { + distances[start] = Some(0); + queue.push_back(start); + } + while let Some(node) = queue.pop_front() { + let depth = distances[node].unwrap_or(0); + if max_depth.is_some_and(|limit| depth >= limit) { + continue; + } + for &neighbor in &reverse[node] { + if distances[neighbor].is_none() { + distances[neighbor] = Some(depth + 1); + queue.push_back(neighbor); + } + } + } + distances +} diff --git a/crates/metrics/src/lib.rs b/crates/metrics/src/lib.rs index a168e66..3dc2e01 100644 --- a/crates/metrics/src/lib.rs +++ b/crates/metrics/src/lib.rs @@ -3,6 +3,7 @@ mod duplication; mod erosion; mod finding_id; +mod impact; mod import_cycles; mod line_share; mod verbosity; @@ -12,6 +13,7 @@ pub use duplication::{ }; pub use erosion::{ErodedFunction, Erosion, FunctionMasses}; pub use finding_id::FindingId; +pub use impact::{ImpactAnalysis, ImpactDependent, ImpactError, ImpactSummary, ImpactTarget}; pub use import_cycles::{ImportCycle, ImportCycles, ModuleShare, UnresolvedImport}; pub use line_share::LineShare; pub use verbosity::{FlaggedLineFinding, Verbosity}; diff --git a/crates/report/src/impact.rs b/crates/report/src/impact.rs new file mode 100644 index 0000000..515472a --- /dev/null +++ b/crates/report/src/impact.rs @@ -0,0 +1,265 @@ +use std::fmt::Write; + +use codeint_config::ImpactFormat; +use codeint_metrics::{ImpactAnalysis, ImpactDependent, ImpactSummary, ImpactTarget}; +use codeint_model::SourceSet; +use serde::Serialize; + +use crate::ReportError; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +pub struct ChangedBase { + #[serde(rename = "ref")] + pub git_ref: String, + pub merge_base: String, +} + +#[derive(Debug, Serialize)] +pub struct ImpactReport { + targets: Vec, + #[serde(skip_serializing_if = "Option::is_none")] + changed_base: Option, + #[serde(skip_serializing_if = "Option::is_none")] + depth_limit: Option, + summary: ImpactSummaryRow, + production: SourceSetImpact, + test: SourceSetImpact, + #[serde(skip_serializing_if = "SourceSetImpact::is_empty")] + generated: SourceSetImpact, + #[serde(skip_serializing_if = "SourceSetImpact::is_empty")] + vendored: SourceSetImpact, + #[serde(skip_serializing_if = "Vec::is_empty")] + affected_packages: Vec, +} + +#[derive(Debug, Serialize)] +struct ImpactTargetRow { + path: String, + source_set: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + package: Option, + fan_in: usize, + fan_out: usize, + transitive_import_weight: usize, +} + +#[derive(Debug, Serialize)] +struct ImpactSummaryRow { + direct_dependents: usize, + transitive_dependents: usize, + total_dependents: usize, + fan_in: usize, + fan_out: usize, + transitive_import_weight: usize, +} + +#[derive(Debug, Default, Serialize)] +struct SourceSetImpact { + direct: Vec, + transitive: Vec, +} + +impl SourceSetImpact { + fn is_empty(&self) -> bool { + self.direct.is_empty() && self.transitive.is_empty() + } +} + +#[derive(Debug, Serialize)] +struct ImpactDependentRow { + path: String, + distance: usize, + #[serde(skip_serializing_if = "Option::is_none")] + package: Option, +} + +impl ImpactReport { + pub fn from_analysis( + analysis: ImpactAnalysis, + changed_base: Option, + ) -> ImpactReport { + let mut production = SourceSetImpact::default(); + let mut test = SourceSetImpact::default(); + let mut generated = SourceSetImpact::default(); + let mut vendored = SourceSetImpact::default(); + + for dependent in analysis.dependents { + let bucket = match dependent.source_set { + SourceSet::Production => &mut production, + SourceSet::Test => &mut test, + SourceSet::Generated => &mut generated, + SourceSet::Vendored => &mut vendored, + }; + let row = ImpactDependentRow::from_dependent(dependent); + if row.distance == 1 { + bucket.direct.push(row); + } else { + bucket.transitive.push(row); + } + } + + ImpactReport { + targets: analysis + .targets + .into_iter() + .map(ImpactTargetRow::from_target) + .collect(), + changed_base, + depth_limit: analysis.depth_limit, + summary: ImpactSummaryRow::from_summary(analysis.summary), + production, + test, + generated, + vendored, + affected_packages: analysis.affected_packages, + } + } + + pub fn render(&self, format: ImpactFormat) -> Result { + match format { + ImpactFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), + ImpactFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), + ImpactFormat::Text => Ok(render_text(self)), + } + } +} + +impl ImpactTargetRow { + fn from_target(target: ImpactTarget) -> ImpactTargetRow { + ImpactTargetRow { + path: target.path.to_string(), + source_set: source_set_key(target.source_set), + package: target.package, + fan_in: target.fan_in, + fan_out: target.fan_out, + transitive_import_weight: target.transitive_import_weight, + } + } +} + +impl ImpactSummaryRow { + fn from_summary(summary: ImpactSummary) -> ImpactSummaryRow { + ImpactSummaryRow { + direct_dependents: summary.direct_dependents, + transitive_dependents: summary.transitive_dependents, + total_dependents: summary.total_dependents, + fan_in: summary.fan_in, + fan_out: summary.fan_out, + transitive_import_weight: summary.transitive_import_weight, + } + } +} + +impl ImpactDependentRow { + fn from_dependent(dependent: ImpactDependent) -> ImpactDependentRow { + ImpactDependentRow { + path: dependent.path.to_string(), + distance: dependent.distance, + package: dependent.package, + } + } +} + +fn source_set_key(source_set: SourceSet) -> &'static str { + match source_set { + SourceSet::Production => "production", + SourceSet::Test => "test", + SourceSet::Generated => "generated", + SourceSet::Vendored => "vendored", + } +} + +fn render_text(report: &ImpactReport) -> String { + let mut out = String::new(); + if let Some(base) = &report.changed_base { + let _ = writeln!( + out, + "Changed base: {} (merge-base {})", + base.git_ref, base.merge_base + ); + } + if let Some(depth) = report.depth_limit { + let _ = writeln!(out, "Depth limit: {depth}"); + } + let _ = writeln!(out, "Targets ({}):", report.targets.len()); + if report.targets.is_empty() { + let _ = writeln!(out, " (none)"); + } else { + for target in &report.targets { + let pkg = target + .package + .as_deref() + .map(|p| format!(" [{p}]")) + .unwrap_or_default(); + let _ = writeln!( + out, + " {} ({}){} fan-in={} fan-out={} weight={}", + target.path, + target.source_set, + pkg, + target.fan_in, + target.fan_out, + target.transitive_import_weight + ); + } + } + let _ = writeln!( + out, + "Summary: {} direct, {} transitive, {} total dependents (fan-in={}, fan-out={}, weight={})", + report.summary.direct_dependents, + report.summary.transitive_dependents, + report.summary.total_dependents, + report.summary.fan_in, + report.summary.fan_out, + report.summary.transitive_import_weight + ); + write_source_set_section(&mut out, "Production dependents", &report.production); + write_source_set_section(&mut out, "Test dependents", &report.test); + if !report.generated.is_empty() { + write_source_set_section(&mut out, "Generated dependents", &report.generated); + } + if !report.vendored.is_empty() { + write_source_set_section(&mut out, "Vendored dependents", &report.vendored); + } + if !report.affected_packages.is_empty() { + let _ = writeln!( + out, + "Affected Workspace packages ({}):", + report.affected_packages.len() + ); + for pkg in &report.affected_packages { + let _ = writeln!(out, " {pkg}"); + } + } + out.trim_end().to_owned() +} + +fn write_source_set_section(out: &mut String, heading: &str, section: &SourceSetImpact) { + let total = section.direct.len() + section.transitive.len(); + let _ = writeln!(out, "{heading} ({total}):"); + if total == 0 { + let _ = writeln!(out, " (none)"); + return; + } + if !section.direct.is_empty() { + let _ = writeln!(out, " Direct (distance 1):"); + for dep in §ion.direct { + write_dependent_line(out, dep); + } + } + if !section.transitive.is_empty() { + let _ = writeln!(out, " Transitive (distance >= 2):"); + for dep in §ion.transitive { + write_dependent_line(out, dep); + } + } +} + +fn write_dependent_line(out: &mut String, dep: &ImpactDependentRow) { + let pkg = dep + .package + .as_deref() + .map(|p| format!(" [{p}]")) + .unwrap_or_default(); + let _ = writeln!(out, " {} (distance {}){}", dep.path, dep.distance, pkg); +} diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index 9d01d58..554b157 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -15,6 +15,7 @@ use serde::ser::SerializeMap; use serde::{Deserialize, Serialize, Serializer}; mod diff; +mod impact; mod markdown; mod measurement; mod sarif; @@ -23,6 +24,7 @@ mod tests; mod trend; pub use diff::{BaseCommit, DiffReport, Head, HeadCommit}; +pub use impact::{ChangedBase, ImpactReport}; pub use measurement::CommitMeasurement; pub use trend::{TrendPoint, TrendReport}; diff --git a/docs/reference.md b/docs/reference.md index a0bd3b8..f199e95 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -26,9 +26,10 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `check` | Measure the working tree and print the report; see [`codeint check`](#codeint-check) | | `diff` | Compare the working tree, or a head Git ref, with the merge-base of a base Git ref; see [`codeint diff`](#codeint-diff) | | `trend` | Measure each commit of the main line and print each Metric over time; see [`codeint trend`](#codeint-trend) | +| `impact` | Compute the transitive reverse-dependency blast radius of one or more repository files; see [`codeint impact`](#codeint-impact) | | `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`, and `trend` tools; see [`codeint mcp`](#codeint-mcp) | +| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, `trend`, and `impact` tools; see [`codeint mcp`](#codeint-mcp) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -459,6 +460,30 @@ codeint reads each commit from Git objects, so it never checks out a commit and Every commit uses the `codeint.json` of the working tree, as `codeint diff` does. Each commit goes through the [result cache](#result-cache), so a repeated trend measures only the commits that are new since the last run. +### `codeint impact` + +| Argument | Meaning | +| -------- | ------- | +| `[PATH]...` | Repository file paths to analyze | + +| Option | Meaning | +| ------ | ------- | +| `--changed ` | Analyze files changed since the merge-base of this Git ref and HEAD | +| `--depth ` | Maximum reverse-dependency hop distance to traverse | +| `--output ` | Write the report to this file instead of standard output | +| `--format ` | The format of the report: `toon`, the default, `json`, or `text` | +| `-h, --help` | Print the help of `codeint impact` | + +`codeint impact` computes the transitive reverse-dependency blast radius of one or more repository files, distinguishing direct dependents (distance 1) from transitive dependents (distance 2 or more), separating Production dependents from Test dependents, and listing affected Workspace packages: + +```sh exit=0 +codeint impact src/sign.ts +codeint impact --changed main +codeint impact src/sign.ts --depth 1 --format text +codeint impact src/sign.ts --format toon +codeint impact src/sign.ts --format json --output impact.json +``` + ### `codeint update` | Option | Meaning | @@ -486,7 +511,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 three read-only tools (`check`, `diff`, and `trend`) so coding agents can measure Software entropy and fix Regressions before opening a pull request. +It exposes four read-only tools (`check`, `diff`, `trend`, and `impact`) so coding agents can measure Software entropy, inspect reverse-dependency blast radius, and fix Regressions before opening a pull request. When standard input closes, the server exits with code 0: ```sh exit=0 From 9b0db6495f02ebcf60a7e5c807da59e65b99827f Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 08:31:24 +0800 Subject: [PATCH 3/4] feat(cli): add --package filter across check, diff, trace, and impact Scope Metrics, Findings, Budgets, Regressions, and graph queries to a single Workspace package while preserving cross-package runtime import resolution. Closes #181 --- crates/cli/src/check.rs | 129 +++++++++- crates/cli/src/commit_measurement.rs | 70 +++++- crates/cli/src/diff.rs | 37 ++- crates/cli/src/impact.rs | 12 +- crates/cli/src/lib.rs | 70 ++++-- crates/cli/src/mcp.rs | 16 +- crates/cli/src/remedy.rs | 3 + crates/cli/src/trace.rs | 11 +- crates/cli/tests/common/mod.rs | 2 + crates/cli/tests/package_filter.rs | 338 +++++++++++++++++++++++++++ crates/config/src/lib.rs | 28 +++ crates/metrics/src/impact.rs | 25 ++ docs/reference.md | 28 +++ 13 files changed, 723 insertions(+), 46 deletions(-) create mode 100644 crates/cli/tests/package_filter.rs diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index d0a2725..8b9408c 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -14,8 +14,8 @@ use codeint_lang_rust::Rust; use codeint_lang_ts::{TypeScriptAndJavaScript, vue_reference_ranges}; use codeint_model::{ CodeModel, InvalidReferenceRange, LanguagePlugin, LowerError, Manifest, MetricPlugin, - MetricPluginError, ReferenceRanges, RepoPath, ResolveError, SkippedFile, SourceFile, Workspace, - WorkspaceError, choose_manifests, resolve_runtime_imports, settle_source_set, + MetricPluginError, Package, ReferenceRanges, RepoPath, ResolveError, SkippedFile, SourceFile, + Workspace, WorkspaceError, choose_manifests, resolve_runtime_imports, settle_source_set, }; use codeint_plugin_host::{ PluginHostError, WasmLanguagePlugin, WasmMetricPlugin, load_language_plugins_with_limits, @@ -50,6 +50,119 @@ pub(crate) enum CheckError { extension: String, path: Option, }, + #[error("{}", format_unknown_workspace_package(requested, available))] + UnknownWorkspacePackage { + requested: String, + available: Vec, + }, +} + +fn format_unknown_workspace_package(requested: &str, available: &[String]) -> String { + if available.is_empty() { + format!( + "Workspace package {requested:?} was not found; no Workspace packages were discovered in this repository" + ) + } else { + format!( + "Workspace package {requested:?} was not found; discovered Workspace packages: {}", + available.join(", ") + ) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) enum SelectedPackage { + Root, + Member(RepoPath), +} + +impl SelectedPackage { + pub(crate) fn as_str(&self) -> &str { + match self { + SelectedPackage::Root => ".", + SelectedPackage::Member(root) => root.as_str(), + } + } + + pub(crate) fn matches(&self, package: Package<'_>) -> bool { + match (self, package) { + (SelectedPackage::Root, Package::Root) => true, + (SelectedPackage::Member(selected), Package::Member(actual)) => selected == actual, + _ => false, + } + } +} + +pub(crate) fn select_workspace_package( + workspace: &Workspace, + requested: &str, +) -> Result { + let available: Vec = workspace.member_roots().map(ToString::to_string).collect(); + if !workspace.has_members() { + return Err(CheckError::UnknownWorkspacePackage { + requested: requested.to_owned(), + available, + }); + } + let normalized = normalize_package_path(requested); + if normalized == "." { + return Ok(SelectedPackage::Root); + } + if let Ok(candidate) = RepoPath::new(normalized) + && workspace.member_roots().any(|root| root == &candidate) + { + return Ok(SelectedPackage::Member(candidate)); + } + Err(CheckError::UnknownWorkspacePackage { + requested: requested.to_owned(), + available, + }) +} + +fn normalize_package_path(raw: &str) -> String { + let replaced = raw.replace('\\', "/"); + let mut trimmed = replaced.as_str(); + while let Some(stripped) = trimmed.strip_prefix("./") { + trimmed = stripped; + } + trimmed = trimmed.trim_end_matches('/'); + if trimmed.is_empty() && !raw.is_empty() && replaced.trim_end_matches('/') == "." { + return ".".to_owned(); + } + trimmed.to_owned() +} + +pub(crate) fn workspace_of_languages(languages: &[MeasuredLanguage]) -> Workspace { + let mut workspace = Workspace::default(); + for language in languages { + workspace.join(language.model.workspace.clone()); + } + workspace +} + +pub(crate) fn filter_model_to_package(model: &mut CodeModel, selected: &SelectedPackage) { + let workspace = std::mem::take(&mut model.workspace); + model + .files + .retain(|file| selected.matches(workspace.package_of(&file.path))); + model + .skipped + .retain(|file| selected.matches(workspace.package_of(&file.path))); + model + .declaration_only + .retain(|path| selected.matches(workspace.package_of(path))); + model + .runtime_imports + .retain(|import| selected.matches(workspace.package_of(&import.importer))); +} + +pub(crate) fn filter_languages_to_package( + languages: &mut [MeasuredLanguage], + selected: &SelectedPackage, +) { + for language in languages { + filter_model_to_package(&mut language.model, selected); + } } fn format_extension_conflict( @@ -165,6 +278,7 @@ impl LoadedPlugins { pub(crate) fn check( folder: &Path, findings: FindingsShown, + package: Option<&str>, plugin_host: &PluginHostConfig, ) -> Result { let repository = Repository::discover(folder)?; @@ -178,6 +292,7 @@ pub(crate) fn check( &plugins, &metric_plugins, findings, + package, ) } @@ -190,7 +305,7 @@ fn check_with( let repository = Repository::discover(folder)?; let configuration = read_configuration(repository.root())?; configuration.validate_metrics(&[])?; - check_loaded(&repository, &configuration, plugins, &[], findings) + check_loaded(&repository, &configuration, plugins, &[], findings, None) } fn check_loaded( @@ -199,9 +314,15 @@ fn check_loaded( plugins: &[NamedLanguagePlugin<'_>], metric_plugins: &[&dyn MetricPlugin], findings: FindingsShown, + package: Option<&str>, ) -> Result { let tree = repository.working_tree()?; - let languages = measure_with(&tree, plugins, configuration)?; + let mut languages = measure_with(&tree, plugins, configuration)?; + if let Some(requested) = package { + let workspace = workspace_of_languages(&languages); + let selected = select_workspace_package(&workspace, requested)?; + filter_languages_to_package(&mut languages, &selected); + } Ok(Report::summarize_with_metrics( languages, tree.submodules().to_vec(), diff --git a/crates/cli/src/commit_measurement.rs b/crates/cli/src/commit_measurement.rs index 00ef066..d375700 100644 --- a/crates/cli/src/commit_measurement.rs +++ b/crates/cli/src/commit_measurement.rs @@ -4,7 +4,10 @@ use codeint_model::CodeModel; use codeint_report::CommitMeasurement; use serde::Serialize; -use crate::check::{BUILT_IN_LANGUAGE_PLUGINS, CheckError, LoadedPlugins, measure_with}; +use crate::check::{ + BUILT_IN_LANGUAGE_PLUGINS, CheckError, LoadedPlugins, SelectedPackage, filter_model_to_package, + measure_with, select_workspace_package, +}; use crate::describe; const CODEINT_VERSION: &str = env!("CARGO_PKG_VERSION"); @@ -14,6 +17,8 @@ struct MeasurementSettings<'configuration> { codeint_version: &'static str, language_plugins: Vec, configuration: &'configuration Configuration, + #[serde(skip_serializing_if = "Option::is_none")] + package: Option<&'configuration str>, } #[derive(Serialize)] @@ -36,6 +41,16 @@ impl<'run> CommitMeasurer<'run> { configuration: &'run Configuration, plugins: &'run LoadedPlugins, result_cache: Option<&'run ResultCache>, + ) -> CommitMeasurer<'run> { + CommitMeasurer::for_package(repository, configuration, plugins, result_cache, None) + } + + pub(crate) fn for_package( + repository: &'run Repository, + configuration: &'run Configuration, + plugins: &'run LoadedPlugins, + result_cache: Option<&'run ResultCache>, + package: Option<&'run str>, ) -> CommitMeasurer<'run> { let mut language_plugins: Vec = BUILT_IN_LANGUAGE_PLUGINS .iter() @@ -58,22 +73,40 @@ impl<'run> CommitMeasurer<'run> { codeint_version: CODEINT_VERSION, language_plugins, configuration, + package, }, result_cache, } } pub(crate) fn measure(&self, commit: CommitId) -> Result { + self.measure_with_package(commit, None) + } + + pub(crate) fn measure_selected_package( + &self, + commit: CommitId, + selected: Option<&SelectedPackage>, + ) -> Result { + self.measure_with_package(commit, selected) + } + + fn measure_with_package( + &self, + commit: CommitId, + selected: Option<&SelectedPackage>, + ) -> Result { if let Some(cached) = self .result_cache .and_then(|cache| cache.read(commit, &self.settings)) { return Ok(cached); } - let measurement = measure_all_languages( + let measurement = measure_all_languages_selected( &self.repository.commit(commit)?, self.plugins, self.configuration, + selected, )?; if let Some(cache) = self.result_cache && let Err(error) = cache.write(commit, &self.settings, &measurement) @@ -87,16 +120,39 @@ impl<'run> CommitMeasurer<'run> { } } -pub(crate) fn measure_all_languages( +pub(crate) fn measure_all_languages_for_package( + tree: &Snapshot, + plugins: &LoadedPlugins, + configuration: &Configuration, + package: Option<&str>, +) -> Result<(Option, CommitMeasurement), CheckError> { + let named = plugins.as_named(); + let metric_plugins = plugins.metric_plugins(); + let languages = measure_with(tree, &named, configuration)?; + let mut model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + let selected = if let Some(requested) = package { + let selected = select_workspace_package(&model.workspace, requested)?; + filter_model_to_package(&mut model, &selected); + Some(selected) + } else { + None + }; + let measurement = CommitMeasurement::of_with_metrics(model, &metric_plugins)?; + Ok((selected, measurement)) +} + +fn measure_all_languages_selected( tree: &Snapshot, plugins: &LoadedPlugins, configuration: &Configuration, + selected: Option<&SelectedPackage>, ) -> Result { let named = plugins.as_named(); let metric_plugins = plugins.metric_plugins(); let languages = measure_with(tree, &named, configuration)?; - Ok(CommitMeasurement::of_with_metrics( - CodeModel::merge(languages.into_iter().map(|language| language.model)), - &metric_plugins, - )?) + let mut model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + if let Some(selected) = selected { + filter_model_to_package(&mut model, selected); + } + Ok(CommitMeasurement::of_with_metrics(model, &metric_plugins)?) } diff --git a/crates/cli/src/diff.rs b/crates/cli/src/diff.rs index 7edaca9..a812ef2 100644 --- a/crates/cli/src/diff.rs +++ b/crates/cli/src/diff.rs @@ -5,7 +5,7 @@ use codeint_git::{CommitId, GitError, Repository, ResultCache}; use codeint_report::{BaseCommit, DiffReport, Head, HeadCommit}; use crate::check::{CheckError, LoadedPlugins}; -use crate::commit_measurement::{CommitMeasurer, measure_all_languages}; +use crate::commit_measurement::{CommitMeasurer, measure_all_languages_for_package}; pub(crate) struct Refs<'a> { pub(crate) base: &'a str, @@ -22,6 +22,7 @@ pub(crate) fn diff( folder: &Path, refs: Refs<'_>, findings: FindingsShown, + package: Option<&str>, result_cache: Option<&ResultCache>, plugin_host: &PluginHostConfig, ) -> Result { @@ -33,12 +34,36 @@ pub(crate) fn diff( head, head_commit, } = sides(&repository, &refs)?; - let measurer = CommitMeasurer::new(&repository, &configuration, &plugins, result_cache); - let base_measurement = measurer.measure(merge_base)?; - let head_measurement = match head_commit { - Some(commit) => measurer.measure(commit)?, - None => measure_all_languages(&repository.working_tree()?, &plugins, &configuration)?, + let (selected, head_measurement) = match head_commit { + Some(commit) => { + if let Some(requested) = package { + measure_all_languages_for_package( + &repository.commit(commit)?, + &plugins, + &configuration, + Some(requested), + )? + } else { + let measurer = + CommitMeasurer::new(&repository, &configuration, &plugins, result_cache); + (None, measurer.measure(commit)?) + } + } + None => measure_all_languages_for_package( + &repository.working_tree()?, + &plugins, + &configuration, + package, + )?, }; + let base_measurer = CommitMeasurer::for_package( + &repository, + &configuration, + &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( BaseCommit { git_ref: refs.base.to_owned(), diff --git a/crates/cli/src/impact.rs b/crates/cli/src/impact.rs index e4650eb..e0314d5 100644 --- a/crates/cli/src/impact.rs +++ b/crates/cli/src/impact.rs @@ -7,7 +7,7 @@ use codeint_metrics::{ImpactAnalysis, ImpactError}; use codeint_model::{CodeModel, RepoPath}; use codeint_report::{ChangedBase, ImpactReport}; -use crate::check::{CheckError, LoadedPlugins, measure_with}; +use crate::check::{CheckError, LoadedPlugins, measure_with, select_workspace_package}; #[derive(Debug, thiserror::Error)] pub(crate) enum ImpactCommandError { @@ -27,6 +27,7 @@ pub(crate) struct ImpactRequest<'a> { pub(crate) paths: &'a [String], pub(crate) changed: Option<&'a str>, pub(crate) depth: Option, + pub(crate) package: Option<&'a str>, pub(crate) plugin_host: &'a PluginHostConfig, } @@ -44,6 +45,10 @@ pub(crate) fn impact( let tree = repository.working_tree().map_err(CheckError::Git)?; let languages = measure_with(&tree, &plugins, &configuration)?; let model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + let selected_package = match request.package { + Some(requested) => Some(select_workspace_package(&model.workspace, requested)?), + None => None, + }; let mut target_paths = Vec::new(); for raw in request.paths { @@ -69,7 +74,10 @@ pub(crate) fn impact( None }; - let analysis = ImpactAnalysis::compute(&model, &target_paths, request.depth)?; + let mut analysis = ImpactAnalysis::compute(&model, &target_paths, request.depth)?; + if let Some(selected) = selected_package { + analysis = analysis.scoped_to_package(selected.as_str()); + } Ok(ImpactReport::from_analysis(analysis, changed_base)) } diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 6a3d446..fcd66ab 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -35,6 +35,7 @@ const DEFAULT_TREND_COMMITS: usize = 20; #[derive(Debug, Clone, PartialEq, Eq)] pub struct CheckOptions { pub findings: FindingsShown, + pub package: Option, pub plugin_host: PluginHostConfig, } @@ -42,6 +43,7 @@ impl Default for CheckOptions { fn default() -> CheckOptions { CheckOptions { findings: FindingsShown::WorstPerMetric(DEFAULT_WORST_FINDINGS), + package: None, plugin_host: PluginHostConfig::default(), } } @@ -51,6 +53,7 @@ impl Default for CheckOptions { pub struct DiffOptions { pub head_ref: Option, pub findings: FindingsShown, + pub package: Option, pub result_cache: Option, pub plugin_host: PluginHostConfig, } @@ -60,6 +63,7 @@ impl Default for DiffOptions { DiffOptions { head_ref: None, findings: FindingsShown::WorstPerMetric(DEFAULT_WORST_FINDINGS), + package: None, result_cache: None, plugin_host: PluginHostConfig::default(), } @@ -88,6 +92,7 @@ pub struct ImpactOptions { pub paths: Vec, pub changed: Option, pub depth: Option, + pub package: Option, pub plugin_host: PluginHostConfig, } @@ -95,6 +100,7 @@ pub struct ImpactOptions { pub struct TraceOptions { pub all: bool, pub max_paths: usize, + pub package: Option, pub plugin_host: PluginHostConfig, } @@ -103,6 +109,7 @@ impl Default for TraceOptions { TraceOptions { all: false, max_paths: DEFAULT_MAX_TRACE_PATHS, + package: None, plugin_host: PluginHostConfig::default(), } } @@ -151,8 +158,13 @@ impl fmt::Display for CodeintError { impl Error for CodeintError {} pub fn check(folder: &Path, options: &CheckOptions) -> Result { - let report = check::check(folder, options.findings, &options.plugin_host) - .map_err(|err| CodeintError::from_cli_error(CliError::Check(err)))?; + let report = check::check( + folder, + options.findings, + options.package.as_deref(), + &options.plugin_host, + ) + .map_err(|err| CodeintError::from_cli_error(CliError::Check(err)))?; let failures: Vec = report .over_budget() .iter() @@ -196,6 +208,7 @@ fn measure_diff( folder, refs, options.findings, + options.package.as_deref(), cache.as_ref(), &options.plugin_host, ) @@ -212,6 +225,7 @@ pub fn impact(folder: &Path, options: &ImpactOptions) -> Result Result { destination, findings, format, + package, plugin_host, - } => run_check(&folder, &destination, findings, format, &plugin_host), + } => run_check( + &folder, + &destination, + findings, + format, + package.as_deref(), + &plugin_host, + ), Command::Diff { folder, base_ref, @@ -315,12 +338,14 @@ fn run() -> Result { destination, findings, format, + package, result_cache, plugin_host, } => { let options = DiffOptions { head_ref, findings, + package, result_cache, plugin_host, }; @@ -346,24 +371,27 @@ fn run() -> Result { paths, changed, depth, + package, destination, format, plugin_host, - } => run_impact( - &folder, - &paths, - changed.as_deref(), - depth, - &destination, - format, - &plugin_host, - ), + } => { + let request = impact::ImpactRequest { + paths: &paths, + changed: changed.as_deref(), + depth, + package: package.as_deref(), + plugin_host: &plugin_host, + }; + run_impact(&folder, &request, &destination, format) + } Command::Trace { folder, from, to, all, max_paths, + package, destination, format, plugin_host, @@ -371,6 +399,7 @@ fn run() -> Result { let options = TraceOptions { all, max_paths, + package, plugin_host, }; run_trace(&folder, &from, &to, &destination, format, &options) @@ -419,9 +448,10 @@ fn run_check( destination: &ReportDestination, findings: FindingsShown, format: ReportFormat, + package: Option<&str>, plugin_host: &PluginHostConfig, ) -> Result { - let report = check::check(folder, findings, plugin_host)?; + let report = check::check(folder, findings, package, plugin_host)?; write_report(&report.render(format)?, destination)?; Ok(Outcome::from_failures( report @@ -460,20 +490,11 @@ fn run_trend( fn run_impact( folder: &Path, - paths: &[String], - changed: Option<&str>, - depth: Option, + request: &impact::ImpactRequest<'_>, destination: &ReportDestination, format: ImpactFormat, - plugin_host: &PluginHostConfig, ) -> Result { - let request = impact::ImpactRequest { - paths, - changed, - depth, - plugin_host, - }; - let report = impact::impact(folder, &request)?; + let report = impact::impact(folder, request)?; write_report(&report.render(format)?, destination)?; Ok(Outcome::Passed) } @@ -492,6 +513,7 @@ fn run_trace( to, options.all, options.max_paths, + options.package.as_deref(), &options.plugin_host, )?; write_report(&report.render(format)?, destination)?; diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 92519d8..49f467f 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -133,6 +133,7 @@ fn handle_tools_list() -> Value { "type": "object", "properties": { "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "package": { "type": "string", "description": "Optional Workspace package path to scope measurement and output." }, "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } } } @@ -147,6 +148,7 @@ fn handle_tools_list() -> Value { "base_ref": { "type": "string", "description": "Base Git ref such as main or origin/main." }, "head_ref": { "type": "string", "description": "Optional head Git ref instead of the working tree." }, "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "package": { "type": "string", "description": "Optional Workspace package path to scope measurement and output." }, "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } } } @@ -175,7 +177,8 @@ fn handle_tools_list() -> Value { "description": "Repository-relative file paths to analyze." }, "changed": { "type": "string", "description": "Optional base Git ref; analyze files changed since its merge-base with HEAD." }, - "depth": { "type": "integer", "minimum": 0, "description": "Optional maximum reverse-dependency hop distance to traverse." } + "depth": { "type": "integer", "minimum": 0, "description": "Optional maximum reverse-dependency hop distance to traverse." }, + "package": { "type": "string", "description": "Optional Workspace package path to scope reported dependents." } } } }, @@ -189,6 +192,7 @@ fn handle_tools_list() -> Value { "from": { "type": "string", "description": "Repository-relative path of the starting module." }, "to": { "type": "string", "description": "Repository-relative path of the target module." }, "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "package": { "type": "string", "description": "Optional Workspace package path to scope the query." }, "all": { "type": "boolean", "description": "Return all shortest paths up to max_paths instead of a single shortest path." }, "max_paths": { "type": "integer", "minimum": 1, "description": "Maximum number of shortest paths to return when all is true (default 10)." } } @@ -221,6 +225,7 @@ fn call_check(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { let folder = resolve_folder(args, ctx.default_folder); let options = CheckOptions { findings: parse_findings(args), + package: parse_package(args), plugin_host: ctx.plugin_host.clone(), }; match check(&folder, &options) { @@ -244,6 +249,7 @@ fn call_diff(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { .and_then(Value::as_str) .map(str::to_owned), findings: parse_findings(args), + package: parse_package(args), result_cache: ctx.result_cache.clone(), plugin_host: ctx.plugin_host.clone(), }; @@ -332,6 +338,7 @@ fn call_impact(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { paths, changed, depth, + package: parse_package(args), plugin_host: ctx.plugin_host.clone(), }; match impact(&folder, &options) { @@ -362,6 +369,7 @@ fn call_trace(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { let options = TraceOptions { all, max_paths, + package: parse_package(args), plugin_host: ctx.plugin_host.clone(), }; match trace(&folder, from, to, &options) { @@ -370,6 +378,12 @@ fn call_trace(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { } } +fn parse_package(args: Option<&Value>) -> Option { + args.and_then(|a| a.get("package")) + .and_then(Value::as_str) + .map(str::to_owned) +} + fn render_json_report(rendered: Result) -> Value { match rendered { Ok(text) => { diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 1db1a03..66b13a3 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -59,6 +59,9 @@ fn check_remedy(error: &CheckError) -> &'static str { 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." + } } } diff --git a/crates/cli/src/trace.rs b/crates/cli/src/trace.rs index 794b627..c6113bd 100644 --- a/crates/cli/src/trace.rs +++ b/crates/cli/src/trace.rs @@ -5,7 +5,9 @@ use codeint_git::Repository; use codeint_model::{CodeModel, RepoPath}; use codeint_report::{TraceError, TraceReport}; -use crate::check::{CheckError, LoadedPlugins, measure_with}; +use crate::check::{ + CheckError, LoadedPlugins, filter_model_to_package, measure_with, select_workspace_package, +}; #[derive(Debug, thiserror::Error)] pub(crate) enum TraceCommandError { @@ -23,6 +25,7 @@ pub(crate) fn trace( to: &str, all: bool, max_paths: usize, + package: Option<&str>, plugin_host: &PluginHostConfig, ) -> Result { let repository = Repository::discover(folder).map_err(CheckError::from)?; @@ -31,7 +34,11 @@ pub(crate) fn trace( let plugins = loaded.as_named(); let tree = repository.working_tree().map_err(CheckError::from)?; let languages = measure_with(&tree, &plugins, &configuration)?; - let model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + let mut model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + if let Some(requested) = package { + let selected = select_workspace_package(&model.workspace, requested)?; + filter_model_to_package(&mut model, &selected); + } let from_path = resolve_model_path(from, folder, repository.root(), &model)?; let to_path = resolve_model_path(to, folder, repository.root(), &model)?; Ok(TraceReport::trace( diff --git a/crates/cli/tests/common/mod.rs b/crates/cli/tests/common/mod.rs index b91c2e8..2f438d2 100644 --- a/crates/cli/tests/common/mod.rs +++ b/crates/cli/tests/common/mod.rs @@ -11,6 +11,8 @@ pub(crate) fn init_git_repo(files: &[(&str, &str)]) -> TempDir { let status = Command::new("git") .args(args) .current_dir(dir.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") diff --git a/crates/cli/tests/package_filter.rs b/crates/cli/tests/package_filter.rs new file mode 100644 index 0000000..69a6fd2 --- /dev/null +++ b/crates/cli/tests/package_filter.rs @@ -0,0 +1,338 @@ +mod common; + +use std::fs; +use std::path::Path; +use std::process::{Command, Output}; + +use common::{init_git_repo, send_mcp_requests}; +use serde_json::{Value, json}; +use tempfile::TempDir; + +const WEB_IMPORTS_API: &str = + "import { apiVal } from '@mono/api';\nexport const webVal = apiVal + 1;\n"; + +fn run_codeint(dir: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .args(args) + .current_dir(dir) + .output() + .unwrap() +} + +fn run_json(dir: &Path, args: &[&str], expected_code: i32) -> Value { + let mut full = args.to_vec(); + full.extend(["--format", "json"]); + let output = run_codeint(dir, &full); + assert_eq!( + output.status.code(), + Some(expected_code), + "unexpected exit for {full:?}, stderr: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap() +} + +fn mcp_payload(response: &Value) -> Value { + assert_eq!(response["result"]["isError"], false); + serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap() +} + +fn eroded_function(name: &str) -> String { + format!( + "export function {name}(x: number): number {{\n\ + if (x === 1) return 1;\n\ + if (x === 2) return 2;\n\ + if (x === 3) return 3;\n\ + if (x === 4) return 4;\n\ + if (x === 5) return 5;\n\ + if (x === 6) return 6;\n\ + if (x === 7) return 7;\n\ + if (x === 8) return 8;\n\ + if (x === 9) return 9;\n\ + if (x === 10) return 10;\n\ + if (x === 11) return 11;\n\ + return 0;\n\ + }}\n" + ) +} + +fn init_ts_monorepo(web_src: &str, codeint_json: Option<&str>) -> TempDir { + let mut files: Vec<(&str, &str)> = vec![ + ( + "package.json", + r#"{ "name": "mono", "private": true, "workspaces": ["packages/*"] }"#, + ), + ( + "packages/core/package.json", + r#"{ "name": "@mono/core", "main": "src/index.ts" }"#, + ), + ("packages/core/src/index.ts", "export const coreVal = 1;\n"), + ( + "packages/api/package.json", + r#"{ "name": "@mono/api", "main": "src/index.ts" }"#, + ), + ( + "packages/api/src/helper.ts", + "import { coreVal } from '@mono/core';\nexport const helperVal = coreVal + 1;\n", + ), + ( + "packages/api/src/index.ts", + "import { helperVal } from './helper';\nexport const apiVal = helperVal + 1;\n", + ), + ( + "packages/web/package.json", + r#"{ "name": "@mono/web", "main": "src/index.ts" }"#, + ), + ("packages/web/src/index.ts", web_src), + ]; + if let Some(config) = codeint_json { + files.push(("codeint.json", config)); + } + init_git_repo(&files) +} + +#[test] +fn check_package_scopes_metrics_findings_budgets_and_preserves_cross_package_imports() { + let bad_web = eroded_function("erodedWeb"); + let repo = init_ts_monorepo( + &bad_web, + Some(r#"{ "budgets": { "production": { "erosion": 0.1 } } }"#), + ); + + let _whole = run_json(repo.path(), &["check"], 1); + let parsed = run_json(repo.path(), &["check", "--package", "packages/api/"], 0); + assert_eq!(parsed["files"], 2); + assert_eq!(parsed["source_sets"]["production"]["files"], 2); + assert_eq!(parsed["source_sets"]["production"]["erosion"]["ratio"], 0.0); + assert_eq!( + parsed["source_sets"]["production"]["import_cycles"]["unresolved_imports"]["count"], + 0 + ); + + let web_parsed = run_json(repo.path(), &["check", "--package", "packages/web"], 1); + assert_eq!(web_parsed["files"], 1); + assert_eq!( + web_parsed["source_sets"]["production"]["erosion"]["findings"][0]["path"], + "packages/web/src/index.ts" + ); +} + +#[test] +fn diff_package_scopes_findings_budgets_and_regressions() { + let repo = init_ts_monorepo(WEB_IMPORTS_API, None); + fs::write( + repo.path().join("packages/web/src/index.ts"), + eroded_function("erodedWeb"), + ) + .unwrap(); + + let _whole = run_json(repo.path(), &["diff", "main"], 1); + let api_parsed = run_json( + repo.path(), + &["diff", "main", "--package", "packages/api"], + 0, + ); + assert_eq!( + api_parsed["source_sets"]["production"]["erosion"]["new"], + json!([]) + ); + + let web_parsed = run_json( + repo.path(), + &["diff", "main", "--package", "packages/web"], + 1, + ); + assert_eq!( + web_parsed["source_sets"]["production"]["erosion"]["new"][0]["path"], + "packages/web/src/index.ts" + ); +} + +fn trace_args<'a>(from: &'a str, to: &'a str, pkg: &'a str) -> [&'a str; 5] { + ["trace", from, to, "--package", pkg] +} + +fn impact_args<'a>(target: &'a str, pkg: &'a str) -> [&'a str; 4] { + ["impact", target, "--package", pkg] +} + +#[test] +fn trace_package_scopes_graph_to_selected_package() { + let repo = init_ts_monorepo(WEB_IMPORTS_API, None); + + let parsed = run_json( + repo.path(), + &trace_args( + "packages/api/src/index.ts", + "packages/api/src/helper.ts", + "packages/api", + ), + 0, + ); + assert_eq!(parsed["connected"], true); + assert_eq!( + parsed["paths"], + json!([["packages/api/src/index.ts", "packages/api/src/helper.ts"]]) + ); + + let outside = run_codeint( + repo.path(), + &trace_args( + "packages/web/src/index.ts", + "packages/api/src/index.ts", + "packages/api", + ), + ); + assert_eq!(outside.status.code(), Some(2)); +} + +fn assert_impact_summary(parsed: &Value, direct: u64, transitive: u64, total: u64, pkg: &str) { + assert_eq!(parsed["summary"]["direct_dependents"], direct); + assert_eq!(parsed["summary"]["transitive_dependents"], transitive); + assert_eq!(parsed["summary"]["total_dependents"], total); + assert_eq!(parsed["affected_packages"], json!([pkg])); +} + +fn impact_package_json(dir: &Path, target: &str, pkg: &str) -> Value { + run_json(dir, &impact_args(target, pkg), 0) +} + +#[test] +fn impact_package_scopes_dependents_while_preserving_cross_package_transitivity() { + let repo = init_ts_monorepo(WEB_IMPORTS_API, None); + + let web_parsed = impact_package_json(repo.path(), "packages/core/src/index.ts", "packages/web"); + assert_impact_summary(&web_parsed, 0, 1, 1, "packages/web"); + assert_eq!( + web_parsed["production"]["transitive"][0]["path"], + "packages/web/src/index.ts" + ); + assert_eq!(web_parsed["production"]["transitive"][0]["distance"], 3); + + let api_parsed = impact_package_json(repo.path(), "packages/core/src/index.ts", "packages/api"); + assert_impact_summary(&api_parsed, 1, 1, 2, "packages/api"); +} + +#[test] +fn unknown_package_exits_2_and_lists_discovered_workspace_packages() { + let repo = init_ts_monorepo("export const webVal = 1;\n", None); + let trace_missing = trace_args( + "packages/api/src/index.ts", + "packages/api/src/helper.ts", + "packages/missing", + ); + let impact_missing = impact_args("packages/core/src/index.ts", "packages/missing"); + let invocations: [&[&str]; 4] = [ + &["check", "--package", "packages/missing"], + &["diff", "main", "--package", "packages/missing"], + &trace_missing, + &impact_missing, + ]; + + for args in invocations { + let output = run_codeint(repo.path(), args); + assert_eq!( + output.status.code(), + Some(2), + "expected exit 2 for {args:?}, got {:?}", + output.status.code() + ); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!( + stderr.contains("packages/missing"), + "stderr missing requested package for {args:?}: {stderr}" + ); + for expected in ["packages/api", "packages/core", "packages/web"] { + assert!( + stderr.contains(expected), + "stderr missing discovered package {expected} for {args:?}: {stderr}" + ); + } + } +} + +#[test] +fn rust_cargo_workspace_supports_package_filter() { + let repo = init_git_repo(&[ + ( + "Cargo.toml", + "[workspace]\nmembers = [\"crates/alpha\", \"crates/beta\"]\nresolver = \"2\"\n", + ), + ( + "crates/alpha/Cargo.toml", + "[package]\nname = \"alpha\"\nversion = \"0.1.0\"\nedition = \"2021\"\n", + ), + ("crates/alpha/src/lib.rs", "pub fn value() -> i32 { 1 }\n"), + ( + "crates/beta/Cargo.toml", + "[package]\nname = \"beta\"\nversion = \"0.1.0\"\nedition = \"2021\"\n", + ), + ( + "crates/beta/src/helper.rs", + "pub fn helper() -> i32 { 2 }\n", + ), + ( + "crates/beta/src/lib.rs", + "mod helper;\nuse crate::helper::helper;\npub fn doubled() -> i32 { helper() * 2 }\n", + ), + ]); + + let parsed = run_json(repo.path(), &["check", "--package", "crates/beta"], 0); + assert_eq!(parsed["files"], 2); + + let impact_parsed = run_json( + repo.path(), + &[ + "impact", + "crates/beta/src/helper.rs", + "--package", + "crates/beta", + ], + 0, + ); + assert_eq!(impact_parsed["affected_packages"], json!(["crates/beta"])); + assert_eq!( + impact_parsed["production"]["direct"][0]["path"], + "crates/beta/src/lib.rs" + ); + + let unknown_rust = run_codeint(repo.path(), &["check", "--package", "crates/gamma"]); + assert_eq!(unknown_rust.status.code(), Some(2)); + let stderr = String::from_utf8_lossy(&unknown_rust.stderr); + assert!(stderr.contains("crates/alpha")); + assert!(stderr.contains("crates/beta")); +} + +#[test] +fn mcp_tools_support_package_filter() { + let repo = init_ts_monorepo(WEB_IMPORTS_API, None); + + let responses = send_mcp_requests( + repo.path(), + &[ + json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}}), + json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "check", "arguments": {"package": "packages/api"}}}), + json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "diff", "arguments": {"base_ref": "main", "package": "packages/api"}}}), + json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "trace", "arguments": {"from": "packages/api/src/index.ts", "to": "packages/api/src/helper.ts", "package": "packages/api"}}}), + json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "impact", "arguments": {"paths": ["packages/core/src/index.ts"], "package": "packages/web"}}}), + json!({"jsonrpc": "2.0", "id": 6, "method": "tools/call", "params": {"name": "check", "arguments": {"package": "packages/missing"}}}), + ], + ); + + assert_eq!(mcp_payload(&responses[1])["report"]["files"], 2); + assert_eq!(mcp_payload(&responses[2])["passed"], true); + assert_eq!(mcp_payload(&responses[3])["connected"], true); + assert_eq!( + mcp_payload(&responses[4])["affected_packages"], + json!(["packages/web"]) + ); + + assert_eq!(responses[5]["result"]["isError"], true); + let err_text = responses[5]["result"]["content"][0]["text"] + .as_str() + .unwrap(); + assert!( + err_text.contains("packages/api"), + "expected discovered packages in MCP error: {err_text}" + ); +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 0f8a636..234e3aa 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -123,6 +123,7 @@ pub enum Command { destination: ReportDestination, findings: FindingsShown, format: ReportFormat, + package: Option, plugin_host: PluginHostConfig, }, Diff { @@ -132,6 +133,7 @@ pub enum Command { destination: ReportDestination, findings: FindingsShown, format: ReportFormat, + package: Option, result_cache: Option, plugin_host: PluginHostConfig, }, @@ -148,6 +150,7 @@ pub enum Command { paths: Vec, changed: Option, depth: Option, + package: Option, destination: ReportDestination, format: ImpactFormat, plugin_host: PluginHostConfig, @@ -158,6 +161,7 @@ pub enum Command { to: String, all: bool, max_paths: usize, + package: Option, destination: ReportDestination, format: TraceFormat, plugin_host: PluginHostConfig, @@ -270,6 +274,12 @@ enum CommandArguments { help = "Maximum number of shortest paths to list when --all is set" )] max_paths: usize, + #[arg( + long, + value_name = "PATH", + help = "Scope the query to this Workspace package" + )] + package: Option, #[arg( long, value_name = "FILE", @@ -306,6 +316,12 @@ enum CommandArguments { help = "Maximum reverse-dependency hop distance to traverse" )] depth: Option, + #[arg( + long, + value_name = "PATH", + help = "Scope reported dependents to this Workspace package" + )] + package: Option, #[arg( long, value_name = "FILE", @@ -346,6 +362,12 @@ enum CommandArguments { #[derive(Debug, clap::Args)] struct ReportArguments { + #[arg( + long, + value_name = "PATH", + help = "Scope measurement and output to this Workspace package" + )] + package: Option, #[arg( long, value_name = "FILE", @@ -394,6 +416,7 @@ pub fn read_invocation() -> Result { paths, changed, depth, + package, output, format, } => Command::Impact { @@ -401,6 +424,7 @@ pub fn read_invocation() -> Result { paths, changed, depth, + package, destination: report_destination(¤t_folder, output)?, format, plugin_host: plugin_host_config_of_this_process(¤t_folder), @@ -410,6 +434,7 @@ pub fn read_invocation() -> Result { to, all, max_paths, + package, output, format, } => Command::Trace { @@ -418,6 +443,7 @@ pub fn read_invocation() -> Result { to, all, max_paths, + package, destination: report_destination(¤t_folder, output)?, format, plugin_host: plugin_host_config_of_this_process(¤t_folder), @@ -445,6 +471,7 @@ fn build_check_command( destination: report_destination(current_folder, report.output)?, findings: findings_shown(report.all), format: report.format, + package: report.package, plugin_host: plugin_host_config_of_this_process(current_folder), }) } @@ -462,6 +489,7 @@ fn build_diff_command( destination: report_destination(current_folder, report.output)?, findings: findings_shown(report.all), format: report.format, + package: report.package, result_cache: result_cache_folder_of_this_process(current_folder), plugin_host: plugin_host_config_of_this_process(current_folder), }) diff --git a/crates/metrics/src/impact.rs b/crates/metrics/src/impact.rs index 8ac04b3..b3d290e 100644 --- a/crates/metrics/src/impact.rs +++ b/crates/metrics/src/impact.rs @@ -163,6 +163,31 @@ impl ImpactAnalysis { affected_packages, }) } + + pub fn scoped_to_package(mut self, package: &str) -> ImpactAnalysis { + self.dependents + .retain(|dep| dep.package.as_deref() == Some(package)); + let direct_dependents = self + .dependents + .iter() + .filter(|dep| dep.distance == 1) + .count(); + let total_dependents = self.dependents.len(); + let transitive_dependents = total_dependents - direct_dependents; + self.summary.direct_dependents = direct_dependents; + self.summary.transitive_dependents = transitive_dependents; + self.summary.total_dependents = total_dependents; + self.summary.fan_in = direct_dependents; + self.summary.transitive_import_weight = total_dependents; + self.affected_packages = self + .dependents + .iter() + .filter_map(|dep| dep.package.clone()) + .collect::>() + .into_iter() + .collect(); + self + } } fn reverse_reachable_count( diff --git a/docs/reference.md b/docs/reference.md index 7cdef9d..e79f2bc 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -128,6 +128,7 @@ Edit the existing codeint.json, or delete it and run codeint init again. | Option | Meaning | | ------ | ------- | +| `--package ` | Scope measurement and output to this Workspace package | | `--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) | @@ -215,6 +216,12 @@ codeint: missing does not exist Pass a folder that exists, or leave the path out to measure the current folder. ``` +Passing `--package ` in a repository without that Workspace package stops the run with exit code 2: + +```sh exit=2 +codeint check --package packages/missing +``` + ### `codeint diff` | Argument | Meaning | @@ -224,6 +231,7 @@ Pass a folder that exists, or leave the path out to measure the current folder. | Option | Meaning | | ------ | ------- | | `--head ` | Measure this Git ref from Git objects instead of the working tree; the merge-base is then taken with this ref instead of HEAD | +| `--package ` | Scope measurement and output to this Workspace package | | `--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` | @@ -308,6 +316,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 ``` +Passing `--package ` for a Workspace package that does not exist stops the run with exit code 2: + +```sh exit=2 +codeint diff main --package packages/missing +``` + #### Compare two refs `--head {ref}` measures a second ref instead of the working tree, so you can compare two commits or two branches. @@ -471,6 +485,7 @@ Each commit goes through the [result cache](#result-cache), so a repeated trend | ------ | ------- | | `--changed ` | Analyze files changed since the merge-base of this Git ref and HEAD | | `--depth ` | Maximum reverse-dependency hop distance to traverse | +| `--package ` | Scope reported dependents to this Workspace package | | `--output ` | Write the report to this file instead of standard output | | `--format ` | The format of the report: `toon`, the default, `json`, or `text` | | `-h, --help` | Print the help of `codeint impact` | @@ -485,6 +500,12 @@ codeint impact src/sign.ts --format toon codeint impact src/sign.ts --format json --output impact.json ``` +Passing `--package ` for a Workspace package that does not exist stops the run with exit code 2: + +```sh exit=2 +codeint impact src/sign.ts --package packages/missing +``` + ### `codeint trace` | Argument | Meaning | @@ -496,6 +517,7 @@ codeint impact src/sign.ts --format json --output impact.json | ------ | ------- | | `--all` | List all shortest runtime import paths up to `--max-paths` | | `--max-paths ` | Maximum number of shortest paths to list when `--all` is set | +| `--package ` | Scope the query to this Workspace package | | `--output ` | Write the report to this file instead of standard output | | `--format ` | The format of the report: `toon`, the default, `json`, or `text` | | `-h, --help` | Print the help of `codeint trace` | @@ -524,6 +546,12 @@ codeint trace src/sign.ts src/parse.ts --format text codeint trace src/sign.ts src/parse.ts --all --max-paths 5 --format json --output trace.json ``` +Passing `--package ` for a Workspace package that does not exist stops the run with exit code 2: + +```sh exit=2 +codeint trace src/sign.ts src/parse.ts --package packages/missing +``` + ### `codeint update` | Option | Meaning | From 90918321c814d5ff2c2b218e49cbfb1f84eedaa3 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Mon, 23 Nov 2026 09:15:35 +0800 Subject: [PATCH 4/4] refactor(cli): resolve codeint diff regressions on Spec #170 --- crates/cli/src/check.rs | 43 ++- crates/cli/src/diff.rs | 77 +++--- crates/cli/src/impact.rs | 95 ++++--- crates/cli/src/lib.rs | 41 +-- crates/cli/src/mcp.rs | 54 ++-- crates/cli/src/remedy.rs | 40 ++- crates/cli/src/trace.rs | 18 +- crates/cli/src/trend.rs | 20 +- crates/cli/tests/common/mod.rs | 16 +- crates/cli/tests/impact.rs | 425 +++++++++++++++-------------- crates/cli/tests/mcp.rs | 86 +----- crates/cli/tests/package_filter.rs | 78 +++--- crates/cli/tests/trace.rs | 152 ++++------- crates/config/src/lib.rs | 330 +++++++++++----------- crates/report/src/diff.rs | 4 +- crates/report/src/impact.rs | 6 +- crates/report/src/lib.rs | 52 +++- crates/report/src/trace.rs | 6 +- crates/report/src/trend.rs | 4 +- 19 files changed, 790 insertions(+), 757 deletions(-) diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index 8b9408c..fd91aae 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -275,20 +275,49 @@ impl LoadedPlugins { } } +pub(crate) struct WorkspaceContext { + pub(crate) repository: Repository, + pub(crate) configuration: Configuration, + pub(crate) plugins: LoadedPlugins, +} + +impl WorkspaceContext { + pub(crate) fn load( + folder: &Path, + plugin_host: &PluginHostConfig, + ) -> Result { + let repository = Repository::discover(folder)?; + let configuration = read_configuration(repository.root())?; + let plugins = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; + Ok(WorkspaceContext { + repository, + configuration, + plugins, + }) + } + + pub(crate) fn measure_working_tree_model(&self) -> Result { + let plugins = self.plugins.as_named(); + let tree = self.repository.working_tree()?; + let languages = measure_with(&tree, &plugins, &self.configuration)?; + Ok(CodeModel::merge( + languages.into_iter().map(|language| language.model), + )) + } +} + pub(crate) fn check( folder: &Path, findings: FindingsShown, package: Option<&str>, plugin_host: &PluginHostConfig, ) -> Result { - let repository = Repository::discover(folder)?; - let configuration = read_configuration(repository.root())?; - let loaded = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; - let plugins = loaded.as_named(); - let metric_plugins = loaded.metric_plugins(); + let context = WorkspaceContext::load(folder, plugin_host)?; + let plugins = context.plugins.as_named(); + let metric_plugins = context.plugins.metric_plugins(); check_loaded( - &repository, - &configuration, + &context.repository, + &context.configuration, &plugins, &metric_plugins, findings, diff --git a/crates/cli/src/diff.rs b/crates/cli/src/diff.rs index a812ef2..d389e0c 100644 --- a/crates/cli/src/diff.rs +++ b/crates/cli/src/diff.rs @@ -1,10 +1,10 @@ use std::path::Path; -use codeint_config::{FindingsShown, PluginHostConfig, read_configuration}; +use codeint_config::{FindingsShown, PluginHostConfig}; use codeint_git::{CommitId, GitError, Repository, ResultCache}; -use codeint_report::{BaseCommit, DiffReport, Head, HeadCommit}; +use codeint_report::{BaseCommit, CommitMeasurement, DiffReport, Head, HeadCommit}; -use crate::check::{CheckError, LoadedPlugins}; +use crate::check::{CheckError, SelectedPackage, WorkspaceContext}; use crate::commit_measurement::{CommitMeasurer, measure_all_languages_for_package}; pub(crate) struct Refs<'a> { @@ -26,40 +26,17 @@ pub(crate) fn diff( result_cache: Option<&ResultCache>, plugin_host: &PluginHostConfig, ) -> Result { - let repository = Repository::discover(folder)?; - let configuration = read_configuration(repository.root())?; - let plugins = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; + let context = WorkspaceContext::load(folder, plugin_host)?; let Sides { merge_base, head, head_commit, - } = sides(&repository, &refs)?; - let (selected, head_measurement) = match head_commit { - Some(commit) => { - if let Some(requested) = package { - measure_all_languages_for_package( - &repository.commit(commit)?, - &plugins, - &configuration, - Some(requested), - )? - } else { - let measurer = - CommitMeasurer::new(&repository, &configuration, &plugins, result_cache); - (None, measurer.measure(commit)?) - } - } - None => measure_all_languages_for_package( - &repository.working_tree()?, - &plugins, - &configuration, - package, - )?, - }; + } = sides(&context.repository, &refs)?; + let (selected, head_measurement) = measure_head(&context, head_commit, package, result_cache)?; let base_measurer = CommitMeasurer::for_package( - &repository, - &configuration, - &plugins, + &context.repository, + &context.configuration, + &context.plugins, result_cache, selected.as_ref().map(|pkg| pkg.as_str()), ); @@ -73,11 +50,43 @@ pub(crate) fn diff( base_measurement, head_measurement, findings, - &configuration.budgets, - &configuration.regression_limits, + &context.configuration.budgets, + &context.configuration.regression_limits, )) } +fn measure_head( + context: &WorkspaceContext, + head_commit: Option, + package: Option<&str>, + result_cache: Option<&ResultCache>, +) -> Result<(Option, CommitMeasurement), CheckError> { + let Some(commit) = head_commit else { + return measure_all_languages_for_package( + &context.repository.working_tree()?, + &context.plugins, + &context.configuration, + package, + ); + }; + if let Some(requested) = package { + measure_all_languages_for_package( + &context.repository.commit(commit)?, + &context.plugins, + &context.configuration, + Some(requested), + ) + } else { + let measurer = CommitMeasurer::new( + &context.repository, + &context.configuration, + &context.plugins, + result_cache, + ); + Ok((None, measurer.measure(commit)?)) + } +} + fn sides(repository: &Repository, refs: &Refs<'_>) -> Result { match refs.head { None => Ok(Sides { diff --git a/crates/cli/src/impact.rs b/crates/cli/src/impact.rs index e0314d5..684dea6 100644 --- a/crates/cli/src/impact.rs +++ b/crates/cli/src/impact.rs @@ -1,13 +1,13 @@ use std::collections::HashSet; use std::path::{Component, Path, PathBuf}; -use codeint_config::{PluginHostConfig, read_configuration}; +use codeint_config::PluginHostConfig; use codeint_git::Repository; use codeint_metrics::{ImpactAnalysis, ImpactError}; use codeint_model::{CodeModel, RepoPath}; use codeint_report::{ChangedBase, ImpactReport}; -use crate::check::{CheckError, LoadedPlugins, measure_with, select_workspace_package}; +use crate::check::{CheckError, WorkspaceContext, select_workspace_package}; #[derive(Debug, thiserror::Error)] pub(crate) enum ImpactCommandError { @@ -38,47 +38,68 @@ pub(crate) fn impact( if request.paths.is_empty() && request.changed.is_none() { return Err(ImpactCommandError::MissingTargets); } - let repository = Repository::discover(folder).map_err(CheckError::Git)?; - let configuration = read_configuration(repository.root()).map_err(CheckError::Configuration)?; - let loaded = LoadedPlugins::load(repository.root(), &configuration, request.plugin_host)?; - let plugins = loaded.as_named(); - let tree = repository.working_tree().map_err(CheckError::Git)?; - let languages = measure_with(&tree, &plugins, &configuration)?; - let model = CodeModel::merge(languages.into_iter().map(|language| language.model)); - let selected_package = match request.package { - Some(requested) => Some(select_workspace_package(&model.workspace, requested)?), - None => None, - }; + let context = WorkspaceContext::load(folder, request.plugin_host)?; + let model = context.measure_working_tree_model()?; + let selected_package = request + .package + .map(|requested| select_workspace_package(&model.workspace, requested)) + .transpose()?; + let (target_paths, changed_base) = collect_targets( + folder, + &context.repository, + &model, + request.paths, + request.changed, + )?; + let mut analysis = ImpactAnalysis::compute(&model, &target_paths, request.depth)?; + if let Some(selected) = selected_package { + analysis = analysis.scoped_to_package(selected.as_str()); + } + Ok(ImpactReport::from_analysis(analysis, changed_base)) +} - let mut target_paths = Vec::new(); - for raw in request.paths { +fn collect_targets( + folder: &Path, + repository: &Repository, + model: &CodeModel, + raw_paths: &[String], + changed_ref: Option<&str>, +) -> Result<(Vec, Option), ImpactCommandError> { + let mut target_paths = Vec::with_capacity(raw_paths.len()); + for raw in raw_paths { target_paths.push(resolve_target_path(folder, repository.root(), raw)?); } - - let changed_base = if let Some(base_ref) = request.changed { - let changed = repository - .changed_files_since(base_ref) - .map_err(CheckError::Git)?; - let measured_paths: HashSet<&RepoPath> = - model.files.iter().map(|file| &file.path).collect(); - for path in changed.files { - if measured_paths.contains(&path) { - target_paths.push(path); - } - } - Some(ChangedBase { - git_ref: base_ref.to_owned(), - merge_base: changed.merge_base.to_string(), - }) - } else { - None + let changed_base = match changed_ref { + Some(base_ref) => Some(collect_changed_targets( + repository, + model, + base_ref, + &mut target_paths, + )?), + None => None, }; + Ok((target_paths, changed_base)) +} - let mut analysis = ImpactAnalysis::compute(&model, &target_paths, request.depth)?; - if let Some(selected) = selected_package { - analysis = analysis.scoped_to_package(selected.as_str()); +fn collect_changed_targets( + repository: &Repository, + model: &CodeModel, + base_ref: &str, + target_paths: &mut Vec, +) -> Result { + let changed = repository + .changed_files_since(base_ref) + .map_err(CheckError::Git)?; + let measured_paths: HashSet<&RepoPath> = model.files.iter().map(|file| &file.path).collect(); + for path in changed.files { + if measured_paths.contains(&path) { + target_paths.push(path); + } } - Ok(ImpactReport::from_analysis(analysis, changed_base)) + Ok(ChangedBase { + git_ref: base_ref.to_owned(), + merge_base: changed.merge_base.to_string(), + }) } fn resolve_target_path( diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index fcd66ab..3083f12 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -29,27 +29,14 @@ pub use codeint_config::{ }; pub use codeint_report::{DiffReport, ImpactReport, Report, TraceReport, TrendReport}; -const DEFAULT_WORST_FINDINGS: usize = 20; -const DEFAULT_TREND_COMMITS: usize = 20; - -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct CheckOptions { pub findings: FindingsShown, pub package: Option, pub plugin_host: PluginHostConfig, } -impl Default for CheckOptions { - fn default() -> CheckOptions { - CheckOptions { - findings: FindingsShown::WorstPerMetric(DEFAULT_WORST_FINDINGS), - package: None, - plugin_host: PluginHostConfig::default(), - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct DiffOptions { pub head_ref: Option, pub findings: FindingsShown, @@ -58,35 +45,13 @@ pub struct DiffOptions { pub plugin_host: PluginHostConfig, } -impl Default for DiffOptions { - fn default() -> DiffOptions { - DiffOptions { - head_ref: None, - findings: FindingsShown::WorstPerMetric(DEFAULT_WORST_FINDINGS), - package: None, - result_cache: None, - plugin_host: PluginHostConfig::default(), - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct TrendOptions { pub range: TrendRange, pub result_cache: Option, pub plugin_host: PluginHostConfig, } -impl Default for TrendOptions { - fn default() -> TrendOptions { - TrendOptions { - range: TrendRange::Latest(DEFAULT_TREND_COMMITS), - result_cache: None, - plugin_host: PluginHostConfig::default(), - } - } -} - #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct ImpactOptions { pub paths: Vec, diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 49f467f..678876b 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -239,8 +239,9 @@ fn call_check(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { } fn call_diff(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let Some(base_ref) = args.and_then(|a| a.get("base_ref")).and_then(Value::as_str) else { - return tool_err("Missing required argument: base_ref"); + let base_ref = match required_str(args, "base_ref") { + Ok(value) => value, + Err(err) => return err, }; let folder = resolve_folder(args, ctx.default_folder); let options = DiffOptions { @@ -295,16 +296,9 @@ fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { result_cache: ctx.result_cache.clone(), plugin_host: ctx.plugin_host.clone(), }; - match trend(&folder, &options) { - Ok(report) => match report.render(TrendFormat::Json) { - Ok(rendered) => { - let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null); - tool_ok(payload) - } - Err(err) => tool_err(&err.to_string()), - }, - Err(err) => tool_err(&err.to_string()), - } + render_tool_result(trend(&folder, &options), |report| { + report.render(TrendFormat::Json) + }) } fn call_impact(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { @@ -341,18 +335,19 @@ fn call_impact(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { package: parse_package(args), plugin_host: ctx.plugin_host.clone(), }; - match impact(&folder, &options) { - Ok(report) => render_json_report(report.render(ImpactFormat::Json)), - Err(err) => tool_err(&err.to_string()), - } + render_tool_result(impact(&folder, &options), |report| { + report.render(ImpactFormat::Json) + }) } fn call_trace(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { - let Some(from) = args.and_then(|a| a.get("from")).and_then(Value::as_str) else { - return tool_err("Missing required argument: from"); + let from = match required_str(args, "from") { + Ok(value) => value, + Err(err) => return err, }; - let Some(to) = args.and_then(|a| a.get("to")).and_then(Value::as_str) else { - return tool_err("Missing required argument: to"); + let to = match required_str(args, "to") { + Ok(value) => value, + Err(err) => return err, }; let folder = resolve_folder(args, ctx.default_folder); let all = args @@ -372,12 +367,27 @@ fn call_trace(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { package: parse_package(args), plugin_host: ctx.plugin_host.clone(), }; - match trace(&folder, from, to, &options) { - Ok(report) => render_json_report(report.render(TraceFormat::Json)), + render_tool_result(trace(&folder, from, to, &options), |report| { + report.render(TraceFormat::Json) + }) +} + +fn render_tool_result( + result: Result, + render: impl FnOnce(T) -> Result, +) -> Value { + match result { + Ok(report) => render_json_report(render(report)), Err(err) => tool_err(&err.to_string()), } } +fn required_str<'a>(args: Option<&'a Value>, key: &str) -> Result<&'a str, Value> { + args.and_then(|a| a.get(key)) + .and_then(Value::as_str) + .ok_or_else(|| tool_err(&format!("Missing required argument: {key}"))) +} + fn parse_package(args: Option<&Value>) -> Option { args.and_then(|a| a.get("package")) .and_then(Value::as_str) diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 66b13a3..574417a 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -17,21 +17,8 @@ pub(crate) fn remedy(error: &CliError) -> &'static str { CliError::Config(error) => config_remedy(error), CliError::Check(error) => check_remedy(error), CliError::Impact(error) => impact_remedy(error), - CliError::Trace(TraceCommandError::Check(error)) => check_remedy(error), - CliError::Trace(TraceCommandError::UnknownModule { .. }) - | CliError::Trace(TraceCommandError::Trace(TraceError::UnknownModule { .. })) => { - "Pass repository-relative paths of files measured by codeint (not ignored, unparsable, declaration-only, or outside the repository)." - } - CliError::Trace(TraceCommandError::Trace(TraceError::InvalidMaxPaths)) => { - "Pass a positive integer (at least 1) for --max-paths." - } - CliError::Init(InitError::Git(GitError::NotInRepository { .. })) => { - "Run codeint init inside a Git repository; it writes codeint.json at the root of the repository." - } - CliError::Init(InitError::Git(error)) => git_remedy(error), - CliError::Init(InitError::StarterConfiguration(error)) => { - starter_configuration_remedy(error) - } + CliError::Trace(error) => trace_remedy(error), + CliError::Init(error) => init_remedy(error), CliError::Update(error) => update_remedy(error), CliError::Report(_) => { "This is a defect in codeint; report it at https://github.com/avidianity/codeint/issues." @@ -43,6 +30,29 @@ pub(crate) fn remedy(error: &CliError) -> &'static str { } } +fn trace_remedy(error: &TraceCommandError) -> &'static str { + match error { + TraceCommandError::Check(error) => check_remedy(error), + TraceCommandError::UnknownModule { .. } + | TraceCommandError::Trace(TraceError::UnknownModule { .. }) => { + "Pass repository-relative paths of files measured by codeint (not ignored, unparsable, declaration-only, or outside the repository)." + } + TraceCommandError::Trace(TraceError::InvalidMaxPaths) => { + "Pass a positive integer (at least 1) for --max-paths." + } + } +} + +fn init_remedy(error: &InitError) -> &'static str { + match error { + InitError::Git(GitError::NotInRepository { .. }) => { + "Run codeint init inside a Git repository; it writes codeint.json at the root of the repository." + } + InitError::Git(error) => git_remedy(error), + InitError::StarterConfiguration(error) => starter_configuration_remedy(error), + } +} + fn check_remedy(error: &CheckError) -> &'static str { match error { CheckError::Git(error) => git_remedy(error), diff --git a/crates/cli/src/trace.rs b/crates/cli/src/trace.rs index c6113bd..c4bec3d 100644 --- a/crates/cli/src/trace.rs +++ b/crates/cli/src/trace.rs @@ -1,12 +1,11 @@ use std::path::Path; -use codeint_config::{PluginHostConfig, read_configuration}; -use codeint_git::Repository; +use codeint_config::PluginHostConfig; use codeint_model::{CodeModel, RepoPath}; use codeint_report::{TraceError, TraceReport}; use crate::check::{ - CheckError, LoadedPlugins, filter_model_to_package, measure_with, select_workspace_package, + CheckError, WorkspaceContext, filter_model_to_package, select_workspace_package, }; #[derive(Debug, thiserror::Error)] @@ -28,19 +27,14 @@ pub(crate) fn trace( package: Option<&str>, plugin_host: &PluginHostConfig, ) -> Result { - let repository = Repository::discover(folder).map_err(CheckError::from)?; - let configuration = read_configuration(repository.root()).map_err(CheckError::from)?; - let loaded = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; - let plugins = loaded.as_named(); - let tree = repository.working_tree().map_err(CheckError::from)?; - let languages = measure_with(&tree, &plugins, &configuration)?; - let mut model = CodeModel::merge(languages.into_iter().map(|language| language.model)); + let context = WorkspaceContext::load(folder, plugin_host)?; + let mut model = context.measure_working_tree_model()?; if let Some(requested) = package { let selected = select_workspace_package(&model.workspace, requested)?; filter_model_to_package(&mut model, &selected); } - let from_path = resolve_model_path(from, folder, repository.root(), &model)?; - let to_path = resolve_model_path(to, folder, repository.root(), &model)?; + let from_path = resolve_model_path(from, folder, context.repository.root(), &model)?; + let to_path = resolve_model_path(to, folder, context.repository.root(), &model)?; Ok(TraceReport::trace( &model, &from_path, &to_path, all, max_paths, )?) diff --git a/crates/cli/src/trend.rs b/crates/cli/src/trend.rs index e86b2e1..db9127f 100644 --- a/crates/cli/src/trend.rs +++ b/crates/cli/src/trend.rs @@ -1,10 +1,10 @@ use std::path::Path; -use codeint_config::{CalendarDay, PluginHostConfig, TrendRange, read_configuration}; -use codeint_git::{CommitRange, Repository, ResultCache}; +use codeint_config::{CalendarDay, PluginHostConfig, TrendRange}; +use codeint_git::{CommitRange, ResultCache}; use codeint_report::{TrendPoint, TrendReport}; -use crate::check::{CheckError, LoadedPlugins}; +use crate::check::{CheckError, WorkspaceContext}; use crate::commit_measurement::CommitMeasurer; pub(crate) fn trend( @@ -13,11 +13,15 @@ pub(crate) fn trend( result_cache: Option<&ResultCache>, plugin_host: &PluginHostConfig, ) -> Result { - let repository = Repository::discover(folder)?; - let configuration = read_configuration(repository.root())?; - let plugins = LoadedPlugins::load(repository.root(), &configuration, plugin_host)?; - let measurer = CommitMeasurer::new(&repository, &configuration, &plugins, result_cache); - let points = repository + let context = WorkspaceContext::load(folder, plugin_host)?; + let measurer = CommitMeasurer::new( + &context.repository, + &context.configuration, + &context.plugins, + result_cache, + ); + let points = context + .repository .first_parent_history(commit_range(range))? .into_iter() .map(|history_commit| { diff --git a/crates/cli/tests/common/mod.rs b/crates/cli/tests/common/mod.rs index 2f438d2..496905f 100644 --- a/crates/cli/tests/common/mod.rs +++ b/crates/cli/tests/common/mod.rs @@ -2,7 +2,7 @@ use std::io::Write; use std::path::Path; use std::process::{Command, Stdio}; -use serde_json::Value; +use serde_json::{Value, json}; use tempfile::TempDir; pub(crate) fn init_git_repo(files: &[(&str, &str)]) -> TempDir { @@ -62,3 +62,17 @@ pub(crate) fn send_mcp_requests(dir: &Path, requests: &[Value]) -> Vec { .map(|l| serde_json::from_str(l).unwrap()) .collect() } + +pub(crate) fn mcp_payload(response: &Value) -> Value { + assert_eq!(response["result"]["isError"], false); + serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap() +} + +pub(crate) fn mcp_tool_call(id: u64, name: &str, arguments: Value) -> Value { + json!({ + "jsonrpc": "2.0", + "id": id, + "method": "tools/call", + "params": { "name": name, "arguments": arguments } + }) +} diff --git a/crates/cli/tests/impact.rs b/crates/cli/tests/impact.rs index f9c236f..f2cf68d 100644 --- a/crates/cli/tests/impact.rs +++ b/crates/cli/tests/impact.rs @@ -1,85 +1,52 @@ +mod common; + use std::fs; use std::path::Path; use std::process::{Command, Output}; -use serde_json::Value; -use tempfile::TempDir; - -const GIT_ENV: [(&str, &str); 6] = [ - ("GIT_CONFIG_GLOBAL", "/dev/null"), - ("GIT_CONFIG_NOSYSTEM", "1"), - ("GIT_AUTHOR_NAME", "ImpactTest"), - ("GIT_AUTHOR_EMAIL", "impact@example.invalid"), - ("GIT_COMMITTER_NAME", "ImpactTest"), - ("GIT_COMMITTER_EMAIL", "impact@example.invalid"), -]; +use common::{init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests}; +use serde_json::{Value, json}; -struct RepoFixture { - dir: TempDir, +fn run_impact(dir: &Path, args: &[&str]) -> Output { + Command::new(env!("CARGO_BIN_EXE_codeint")) + .arg("impact") + .args(args) + .current_dir(dir) + .output() + .expect("run codeint impact") } -impl RepoFixture { - fn new() -> RepoFixture { - let fixture = RepoFixture { - dir: tempfile::tempdir().expect("tempdir"), - }; - fixture.git(&["init", "--quiet", "--initial-branch", "main"]); - fixture - } - - fn root(&self) -> &Path { - self.dir.path() - } - - fn write(&self, relative: &str, content: &str) { - let full = self.root().join(relative); - if let Some(parent) = full.parent() { - fs::create_dir_all(parent).expect("create parent"); - } - fs::write(full, content).expect("write file"); - } - - fn git(&self, args: &[&str]) -> String { - let mut cmd = Command::new("git"); - cmd.args(args).current_dir(self.root()); - for (k, v) in GIT_ENV { - cmd.env(k, v); - } - let output = cmd.output().expect("run git"); - assert!( - output.status.success(), - "git {args:?} failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - String::from_utf8(output.stdout).expect("utf8") - } - - fn commit(&self, msg: &str) { - self.git(&["add", "--all"]); - self.git(&["commit", "--quiet", "--message", msg]); - } - - fn run_impact(&self, args: &[&str]) -> Output { - Command::new(env!("CARGO_BIN_EXE_codeint")) - .arg("impact") - .args(args) - .current_dir(self.root()) - .output() - .expect("run codeint impact") - } +fn impact_json(dir: &Path, args: &[&str]) -> Value { + let mut full_args = args.to_vec(); + full_args.extend(["--format", "json"]); + let output = run_impact(dir, &full_args); + assert_eq!( + output.status.code(), + Some(0), + "codeint impact failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).expect("valid JSON") +} - fn impact_json(&self, args: &[&str]) -> Value { - let mut full_args = args.to_vec(); - full_args.extend(["--format", "json"]); - let output = self.run_impact(&full_args); - assert_eq!( - output.status.code(), - Some(0), - "codeint impact failed: {}", - String::from_utf8_lossy(&output.stderr) - ); - serde_json::from_slice(&output.stdout).expect("valid JSON") - } +fn git_stdout(dir: &Path, args: &[&str]) -> String { + let output = Command::new("git") + .args(args) + .current_dir(dir) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_AUTHOR_NAME", "ImpactTest") + .env("GIT_AUTHOR_EMAIL", "impact@example.invalid") + .env("GIT_COMMITTER_NAME", "ImpactTest") + .env("GIT_COMMITTER_EMAIL", "impact@example.invalid") + .output() + .expect("run git"); + assert!( + output.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).expect("utf8") } fn dependent_paths_and_distances(list: &Value) -> Vec<(String, u64)> { @@ -97,28 +64,28 @@ fn dependent_paths_and_distances(list: &Value) -> Vec<(String, u64)> { #[test] fn impact_reports_direct_and_transitive_dependents_separating_production_and_test() { - let repo = RepoFixture::new(); - repo.write("src/leaf.ts", "export const leaf = 1;\n"); - repo.write( - "src/mid.ts", - "import { leaf } from './leaf';\nexport const mid = leaf + 1;\n", - ); - repo.write( - "src/app.ts", - "import { mid } from './mid';\nexport const app = mid + 1;\n", - ); - repo.write("src/unrelated.ts", "export const unrelated = 0;\n"); - repo.write( - "src/leaf.test.ts", - "import { leaf } from './leaf';\nexport const testLeaf = leaf;\n", - ); - repo.write( - "src/mid.test.ts", - "import { mid } from './mid';\nexport const testMid = mid;\n", - ); - repo.commit("initial"); - - let report = repo.impact_json(&["src/leaf.ts"]); + let repo = init_git_repo(&[ + ("src/leaf.ts", "export const leaf = 1;\n"), + ( + "src/mid.ts", + "import { leaf } from './leaf';\nexport const mid = leaf + 1;\n", + ), + ( + "src/app.ts", + "import { mid } from './mid';\nexport const app = mid + 1;\n", + ), + ("src/unrelated.ts", "export const unrelated = 0;\n"), + ( + "src/leaf.test.ts", + "import { leaf } from './leaf';\nexport const testLeaf = leaf;\n", + ), + ( + "src/mid.test.ts", + "import { mid } from './mid';\nexport const testMid = mid;\n", + ), + ]); + + let report = impact_json(repo.path(), &["src/leaf.ts"]); assert_eq!(report["targets"].as_array().expect("targets").len(), 1); let target = &report["targets"][0]; @@ -155,39 +122,39 @@ fn impact_reports_direct_and_transitive_dependents_separating_production_and_tes #[test] fn impact_supports_depth_cap_and_handles_import_cycles_without_looping() { - let repo = RepoFixture::new(); - repo.write( - "src/a.ts", - "import { c } from './c';\nexport const a = () => c;\n", - ); - repo.write( - "src/b.ts", - "import { a } from './a';\nexport const b = () => a;\n", - ); - repo.write( - "src/c.ts", - "import { b } from './b';\nexport const c = () => b;\n", - ); - repo.write( - "src/entry.ts", - "import { c } from './c';\nexport const entry = () => c;\n", - ); - repo.commit("cycle"); - - let full = repo.impact_json(&["src/a.ts"]); + let repo = init_git_repo(&[ + ( + "src/a.ts", + "import { c } from './c';\nexport const a = () => c;\n", + ), + ( + "src/b.ts", + "import { a } from './a';\nexport const b = () => a;\n", + ), + ( + "src/c.ts", + "import { b } from './b';\nexport const c = () => b;\n", + ), + ( + "src/entry.ts", + "import { c } from './c';\nexport const entry = () => c;\n", + ), + ]); + + let full = impact_json(repo.path(), &["src/a.ts"]); assert_eq!( dependent_paths_and_distances(&full["production"]["direct"]), vec![("src/b.ts".to_owned(), 1)] ); assert_eq!( dependent_paths_and_distances(&full["production"]["transitive"]), - vec![("src/c.ts".to_owned(), 2), ("src/entry.ts".to_owned(), 3),] + vec![("src/c.ts".to_owned(), 2), ("src/entry.ts".to_owned(), 3)] ); assert_eq!(full["targets"][0]["fan_in"], 1); assert_eq!(full["targets"][0]["fan_out"], 1); assert_eq!(full["targets"][0]["transitive_import_weight"], 3); - let capped = repo.impact_json(&["src/a.ts", "--depth", "1"]); + let capped = impact_json(repo.path(), &["src/a.ts", "--depth", "1"]); assert_eq!(capped["depth_limit"], 1); assert_eq!( dependent_paths_and_distances(&capped["production"]["direct"]), @@ -202,24 +169,24 @@ fn impact_supports_depth_cap_and_handles_import_cycles_without_looping() { #[test] fn impact_supports_multiple_target_paths_with_deterministic_ordering() { - let repo = RepoFixture::new(); - repo.write("src/a.ts", "export const a = 1;\n"); - repo.write("src/b.ts", "export const b = 2;\n"); - repo.write( - "src/z_direct.ts", - "import { a } from './a';\nexport const z = a;\n", - ); - repo.write( - "src/c_direct.ts", - "import { b } from './b';\nexport const c = b;\n", - ); - repo.write( - "src/top.ts", - "import { c } from './c_direct';\nimport { z } from './z_direct';\nexport const top = c + z;\n", - ); - repo.commit("multi"); - - let report = repo.impact_json(&["src/b.ts", "src/a.ts"]); + let repo = init_git_repo(&[ + ("src/a.ts", "export const a = 1;\n"), + ("src/b.ts", "export const b = 2;\n"), + ( + "src/z_direct.ts", + "import { a } from './a';\nexport const z = a;\n", + ), + ( + "src/c_direct.ts", + "import { b } from './b';\nexport const c = b;\n", + ), + ( + "src/top.ts", + "import { c } from './c_direct';\nimport { z } from './z_direct';\nexport const top = c + z;\n", + ), + ]); + + let report = impact_json(repo.path(), &["src/b.ts", "src/a.ts"]); let target_paths: Vec<&str> = report["targets"] .as_array() .expect("targets") @@ -242,28 +209,31 @@ fn impact_supports_multiple_target_paths_with_deterministic_ordering() { #[test] fn impact_supports_changed_base_using_git_merge_base() { - let repo = RepoFixture::new(); - repo.write("src/core.ts", "export const core = 1;\n"); - repo.write( - "src/service.ts", - "import { core } from './core';\nexport const service = core + 1;\n", - ); - repo.write("src/other.ts", "export const other = 1;\n"); - repo.commit("base"); - let merge_base = repo.git(&["rev-parse", "HEAD"]).trim().to_owned(); - - repo.git(&["switch", "--quiet", "--create", "feature"]); - repo.write("src/core.ts", "export const core = 42;\n"); - repo.write("README.md", "# docs change\n"); - repo.commit("feature change"); - - repo.git(&["switch", "--quiet", "main"]); - repo.write("src/other.ts", "export const other = 99;\n"); - repo.commit("main advance"); - - repo.git(&["switch", "--quiet", "feature"]); - - let report = repo.impact_json(&["--changed", "main"]); + let repo = init_git_repo(&[ + ("src/core.ts", "export const core = 1;\n"), + ( + "src/service.ts", + "import { core } from './core';\nexport const service = core + 1;\n", + ), + ("src/other.ts", "export const other = 1;\n"), + ]); + let root = repo.path(); + let merge_base = git_stdout(root, &["rev-parse", "HEAD"]).trim().to_owned(); + + git_stdout(root, &["switch", "--quiet", "--create", "feature"]); + fs::write(root.join("src/core.ts"), "export const core = 42;\n").expect("write"); + fs::write(root.join("README.md"), "# docs change\n").expect("write"); + git_stdout(root, &["add", "--all"]); + git_stdout(root, &["commit", "--quiet", "--message", "feature change"]); + + git_stdout(root, &["switch", "--quiet", "main"]); + fs::write(root.join("src/other.ts"), "export const other = 99;\n").expect("write"); + git_stdout(root, &["add", "--all"]); + git_stdout(root, &["commit", "--quiet", "--message", "main advance"]); + + git_stdout(root, &["switch", "--quiet", "feature"]); + + let report = impact_json(root, &["--changed", "main"]); assert_eq!(report["changed_base"]["ref"], "main"); assert_eq!(report["changed_base"]["merge_base"], merge_base); let target_paths: Vec<&str> = report["targets"] @@ -281,35 +251,34 @@ fn impact_supports_changed_base_using_git_merge_base() { #[test] fn impact_lists_affected_workspace_packages_in_monorepo() { - let repo = RepoFixture::new(); - repo.write( - "package.json", - r#"{ "name": "mono", "private": true, "workspaces": ["packages/*"] }"#, - ); - repo.write( - "packages/core/package.json", - r#"{ "name": "@mono/core", "main": "src/index.ts" }"#, - ); - repo.write("packages/core/src/index.ts", "export const coreVal = 1;\n"); - repo.write( - "packages/api/package.json", - r#"{ "name": "@mono/api", "main": "src/index.ts" }"#, - ); - repo.write( - "packages/api/src/index.ts", - "import { coreVal } from '../../core/src/index';\nexport const apiVal = coreVal + 1;\n", - ); - repo.write( - "packages/web/package.json", - r#"{ "name": "@mono/web", "main": "src/index.ts" }"#, - ); - repo.write( - "packages/web/src/index.ts", - "import { apiVal } from '../../api/src/index';\nexport const webVal = apiVal + 1;\n", - ); - repo.commit("monorepo"); + let mut owned: Vec<(String, String)> = vec![( + "package.json".to_owned(), + r#"{ "name": "mono", "private": true, "workspaces": ["packages/*"] }"#.to_owned(), + )]; + for (pkg, src) in [ + ("core", "export const coreVal = 1;\n"), + ( + "api", + "import { coreVal } from '../../core/src/index';\nexport const apiVal = coreVal + 1;\n", + ), + ( + "web", + "import { apiVal } from '../../api/src/index';\nexport const webVal = apiVal + 1;\n", + ), + ] { + owned.push(( + format!("packages/{pkg}/package.json"), + format!(r#"{{ "name": "@mono/{pkg}", "main": "src/index.ts" }}"#), + )); + owned.push((format!("packages/{pkg}/src/index.ts"), src.to_owned())); + } + let refs: Vec<(&str, &str)> = owned + .iter() + .map(|(path, content)| (path.as_str(), content.as_str())) + .collect(); + let repo = init_git_repo(&refs); - let report = repo.impact_json(&["packages/core/src/index.ts"]); + let report = impact_json(repo.path(), &["packages/core/src/index.ts"]); let affected: Vec<&str> = report["affected_packages"] .as_array() .expect("affected_packages") @@ -322,19 +291,19 @@ fn impact_lists_affected_workspace_packages_in_monorepo() { #[test] fn impact_renders_text_and_toon_formats() { - let repo = RepoFixture::new(); - repo.write("src/util.ts", "export const util = 1;\n"); - repo.write( - "src/app.ts", - "import { util } from './util';\nexport const app = util;\n", - ); - repo.write( - "src/util.test.ts", - "import { util } from './util';\nexport const t = util;\n", - ); - repo.commit("formats"); - - let text_out = repo.run_impact(&["src/util.ts", "--format", "text"]); + let repo = init_git_repo(&[ + ("src/util.ts", "export const util = 1;\n"), + ( + "src/app.ts", + "import { util } from './util';\nexport const app = util;\n", + ), + ( + "src/util.test.ts", + "import { util } from './util';\nexport const t = util;\n", + ), + ]); + + let text_out = run_impact(repo.path(), &["src/util.ts", "--format", "text"]); assert_eq!(text_out.status.code(), Some(0)); let text = String::from_utf8(text_out.stdout).expect("utf8"); assert!(text.contains("Targets (1):"), "missing targets: {text}"); @@ -353,7 +322,7 @@ fn impact_renders_text_and_toon_formats() { "missing test dep: {text}" ); - let toon_out = repo.run_impact(&["src/util.ts", "--format", "toon"]); + let toon_out = run_impact(repo.path(), &["src/util.ts", "--format", "toon"]); assert_eq!(toon_out.status.code(), Some(0)); let toon_str = String::from_utf8(toon_out.stdout).expect("utf8"); let decoded: Value = toon_format::decode_default(&toon_str).expect("valid TOON"); @@ -362,11 +331,9 @@ fn impact_renders_text_and_toon_formats() { #[test] fn impact_errors_when_target_is_not_in_measured_code_model() { - let repo = RepoFixture::new(); - repo.write("src/real.ts", "export const real = 1;\n"); - repo.commit("initial"); + let repo = init_git_repo(&[("src/real.ts", "export const real = 1;\n")]); - let missing = repo.run_impact(&["src/missing.ts"]); + let missing = run_impact(repo.path(), &["src/missing.ts"]); assert_eq!(missing.status.code(), Some(2)); assert!(missing.stdout.is_empty()); let stderr = String::from_utf8_lossy(&missing.stderr); @@ -375,7 +342,7 @@ fn impact_errors_when_target_is_not_in_measured_code_model() { "unexpected stderr: {stderr}" ); - let outside = repo.run_impact(&["../outside.ts"]); + let outside = run_impact(repo.path(), &["../outside.ts"]); assert_eq!(outside.status.code(), Some(2)); let outside_err = String::from_utf8_lossy(&outside.stderr); assert!( @@ -383,3 +350,51 @@ fn impact_errors_when_target_is_not_in_measured_code_model() { "unexpected stderr: {outside_err}" ); } + +#[test] +fn mcp_impact_tool_reports_blast_radius_depth_and_errors() { + let repo = init_git_repo(&[( + "app.ts", + "export function greet(x: number): number {\n return x + 1;\n}\n", + )]); + fs::write( + repo.path().join("consumer.ts"), + "import { greet } from './app';\nexport const run = () => greet(1);\n", + ) + .unwrap(); + fs::write( + repo.path().join("app.test.ts"), + "import { greet } from './app';\nexport const testGreet = greet(2);\n", + ) + .unwrap(); + let responses = send_mcp_requests( + repo.path(), + &[ + mcp_tool_call(1, "impact", json!({"paths": ["app.ts"], "depth": 1})), + mcp_tool_call(2, "impact", json!({"changed": "main"})), + mcp_tool_call(3, "impact", json!({"paths": ["missing.ts"]})), + ], + ); + assert_eq!(responses.len(), 3); + let direct = mcp_payload(&responses[0]); + assert_eq!(direct["summary"]["direct_dependents"], 2); + assert_eq!(direct["production"]["direct"][0]["path"], "consumer.ts"); + assert_eq!(direct["test"]["direct"][0]["path"], "app.test.ts"); + + let changed = mcp_payload(&responses[1]); + assert_eq!(changed["changed_base"]["ref"], "main"); + assert_eq!(changed["targets"].as_array().unwrap().len(), 2); + + assert_mcp_error_contains( + &responses[2], + "missing.ts is not in the measured Code model", + ); +} + +fn assert_mcp_error_contains(response: &Value, expected: &str) { + assert_eq!(response["result"]["isError"], true); + let text = response["result"]["content"][0]["text"] + .as_str() + .expect("error text"); + assert!(text.contains(expected), "unexpected MCP error: {text}"); +} diff --git a/crates/cli/tests/mcp.rs b/crates/cli/tests/mcp.rs index 8ad9fb4..1a10808 100644 --- a/crates/cli/tests/mcp.rs +++ b/crates/cli/tests/mcp.rs @@ -1,23 +1,24 @@ mod common; -use serde_json::{Value, json}; +use common::{init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests}; +use serde_json::json; #[test] fn mcp_initialize_list_and_call_tools() { - let repo = common::init_git_repo(&[( + let repo = init_git_repo(&[( "app.ts", "export function greet(x: number): number {\n return x + 1;\n}\n", )]); - let responses = common::send_mcp_requests( + let responses = send_mcp_requests( repo.path(), &[ json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}}), json!({"jsonrpc": "2.0", "method": "notifications/initialized"}), json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}), - json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "check", "arguments": {}}}), - json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "diff", "arguments": {"base_ref": "main"}}}), - json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "trend", "arguments": {}}}), - json!({"jsonrpc": "2.0", "id": 6, "method": "tools/call", "params": {"name": "impact", "arguments": {"paths": ["app.ts"]}}}), + mcp_tool_call(3, "check", json!({})), + mcp_tool_call(4, "diff", json!({"base_ref": "main"})), + mcp_tool_call(5, "trend", json!({})), + mcp_tool_call(6, "impact", json!({"paths": ["app.ts"]})), json!({"jsonrpc": "2.0", "id": 7, "method": "unknown/method"}), ], ); @@ -27,81 +28,14 @@ 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", "impact", "trace"]); - assert_eq!(responses[2]["result"]["isError"], false); - let check_payload: Value = serde_json::from_str( - responses[2]["result"]["content"][0]["text"] - .as_str() - .unwrap(), - ) - .unwrap(); + let check_payload = mcp_payload(&responses[2]); assert_eq!(check_payload["passed"], true); assert_eq!(check_payload["report"]["files"], 1); assert_eq!(responses[3]["result"]["isError"], false); assert_eq!(responses[4]["result"]["isError"], false); - assert_eq!(responses[5]["result"]["isError"], false); - let impact_payload: Value = serde_json::from_str( - responses[5]["result"]["content"][0]["text"] - .as_str() - .unwrap(), - ) - .unwrap(); + let impact_payload = mcp_payload(&responses[5]); assert_eq!(impact_payload["targets"][0]["path"], "app.ts"); assert_eq!(impact_payload["summary"]["total_dependents"], 0); assert_eq!(responses[6]["error"]["code"], -32601); } - -#[test] -fn mcp_impact_tool_reports_blast_radius_depth_and_errors() { - let repo = common::init_git_repo(&[( - "app.ts", - "export function greet(x: number): number {\n return x + 1;\n}\n", - )]); - std::fs::write( - repo.path().join("consumer.ts"), - "import { greet } from './app';\nexport const run = () => greet(1);\n", - ) - .unwrap(); - std::fs::write( - repo.path().join("app.test.ts"), - "import { greet } from './app';\nexport const testGreet = greet(2);\n", - ) - .unwrap(); - let responses = common::send_mcp_requests( - repo.path(), - &[ - json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "impact", "arguments": {"paths": ["app.ts"], "depth": 1}}}), - json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "impact", "arguments": {"changed": "main"}}}), - json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "impact", "arguments": {"paths": ["missing.ts"]}}}), - ], - ); - assert_eq!(responses.len(), 3); - assert_eq!(responses[0]["result"]["isError"], false); - let direct: Value = serde_json::from_str( - responses[0]["result"]["content"][0]["text"] - .as_str() - .unwrap(), - ) - .unwrap(); - assert_eq!(direct["summary"]["direct_dependents"], 2); - assert_eq!(direct["production"]["direct"][0]["path"], "consumer.ts"); - assert_eq!(direct["test"]["direct"][0]["path"], "app.test.ts"); - - assert_eq!(responses[1]["result"]["isError"], false); - let changed: Value = serde_json::from_str( - responses[1]["result"]["content"][0]["text"] - .as_str() - .unwrap(), - ) - .unwrap(); - assert_eq!(changed["changed_base"]["ref"], "main"); - assert_eq!(changed["targets"].as_array().unwrap().len(), 2); - - assert_eq!(responses[2]["result"]["isError"], true); - assert!( - responses[2]["result"]["content"][0]["text"] - .as_str() - .unwrap() - .contains("missing.ts is not in the measured Code model") - ); -} diff --git a/crates/cli/tests/package_filter.rs b/crates/cli/tests/package_filter.rs index 69a6fd2..206bdc7 100644 --- a/crates/cli/tests/package_filter.rs +++ b/crates/cli/tests/package_filter.rs @@ -4,7 +4,7 @@ use std::fs; use std::path::Path; use std::process::{Command, Output}; -use common::{init_git_repo, send_mcp_requests}; +use common::{init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests}; use serde_json::{Value, json}; use tempfile::TempDir; @@ -32,9 +32,21 @@ fn run_json(dir: &Path, args: &[&str], expected_code: i32) -> Value { serde_json::from_slice(&output.stdout).unwrap() } -fn mcp_payload(response: &Value) -> Value { - assert_eq!(response["result"]["isError"], false); - serde_json::from_str(response["result"]["content"][0]["text"].as_str().unwrap()).unwrap() +fn assert_unknown_package_error(dir: &Path, args: &[&str], expected_packages: &[&str]) { + let output = run_codeint(dir, args); + assert_eq!( + output.status.code(), + Some(2), + "expected exit 2 for {args:?}, got {:?}", + output.status.code() + ); + let stderr = String::from_utf8_lossy(&output.stderr); + for expected in expected_packages { + assert!( + stderr.contains(expected), + "stderr missing {expected} for {args:?}: {stderr}" + ); + } } fn eroded_function(name: &str) -> String { @@ -230,24 +242,16 @@ fn unknown_package_exits_2_and_lists_discovered_workspace_packages() { ]; for args in invocations { - let output = run_codeint(repo.path(), args); - assert_eq!( - output.status.code(), - Some(2), - "expected exit 2 for {args:?}, got {:?}", - output.status.code() - ); - let stderr = String::from_utf8_lossy(&output.stderr); - assert!( - stderr.contains("packages/missing"), - "stderr missing requested package for {args:?}: {stderr}" + assert_unknown_package_error( + repo.path(), + args, + &[ + "packages/missing", + "packages/api", + "packages/core", + "packages/web", + ], ); - for expected in ["packages/api", "packages/core", "packages/web"] { - assert!( - stderr.contains(expected), - "stderr missing discovered package {expected} for {args:?}: {stderr}" - ); - } } } @@ -296,11 +300,11 @@ fn rust_cargo_workspace_supports_package_filter() { "crates/beta/src/lib.rs" ); - let unknown_rust = run_codeint(repo.path(), &["check", "--package", "crates/gamma"]); - assert_eq!(unknown_rust.status.code(), Some(2)); - let stderr = String::from_utf8_lossy(&unknown_rust.stderr); - assert!(stderr.contains("crates/alpha")); - assert!(stderr.contains("crates/beta")); + assert_unknown_package_error( + repo.path(), + &["check", "--package", "crates/gamma"], + &["crates/alpha", "crates/beta"], + ); } #[test] @@ -311,11 +315,23 @@ fn mcp_tools_support_package_filter() { repo.path(), &[ json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}}), - json!({"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "check", "arguments": {"package": "packages/api"}}}), - json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "diff", "arguments": {"base_ref": "main", "package": "packages/api"}}}), - json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "trace", "arguments": {"from": "packages/api/src/index.ts", "to": "packages/api/src/helper.ts", "package": "packages/api"}}}), - json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "impact", "arguments": {"paths": ["packages/core/src/index.ts"], "package": "packages/web"}}}), - json!({"jsonrpc": "2.0", "id": 6, "method": "tools/call", "params": {"name": "check", "arguments": {"package": "packages/missing"}}}), + mcp_tool_call(2, "check", json!({"package": "packages/api"})), + mcp_tool_call( + 3, + "diff", + json!({"base_ref": "main", "package": "packages/api"}), + ), + mcp_tool_call( + 4, + "trace", + json!({"from": "packages/api/src/index.ts", "to": "packages/api/src/helper.ts", "package": "packages/api"}), + ), + mcp_tool_call( + 5, + "impact", + json!({"paths": ["packages/core/src/index.ts"], "package": "packages/web"}), + ), + mcp_tool_call(6, "check", json!({"package": "packages/missing"})), ], ); diff --git a/crates/cli/tests/trace.rs b/crates/cli/tests/trace.rs index 5c1f55c..bf3e91a 100644 --- a/crates/cli/tests/trace.rs +++ b/crates/cli/tests/trace.rs @@ -3,17 +3,38 @@ mod common; use std::path::Path; use std::process::{Command, Output}; -use common::{init_git_repo, send_mcp_requests}; +use common::{init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests}; use serde_json::{Value, json}; -fn run_codeint(dir: &Path, args: &[&str]) -> Output { +fn run_trace(dir: &Path, args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_codeint")) + .arg("trace") .args(args) .current_dir(dir) .output() .unwrap() } +fn trace_json(dir: &Path, args: &[&str]) -> Value { + let mut full = args.to_vec(); + full.extend(["--format", "json"]); + let output = run_trace(dir, &full); + assert!( + output.status.success(), + "trace {full:?} failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + serde_json::from_slice(&output.stdout).unwrap() +} + +fn trace_text(dir: &Path, args: &[&str]) -> String { + let mut full = args.to_vec(); + full.extend(["--format", "text"]); + let output = run_trace(dir, &full); + assert_eq!(output.status.code(), Some(0)); + String::from_utf8(output.stdout).unwrap().trim().to_owned() +} + #[test] fn trace_finds_shortest_runtime_import_path_in_cli_json_text_and_toon() { let repo = init_git_repo(&[ @@ -36,16 +57,7 @@ fn trace_finds_shortest_runtime_import_path_in_cli_json_text_and_toon() { ("src/target.ts", "export const target = 42;\n"), ]); - let json_output = run_codeint( - repo.path(), - &["trace", "src/a.ts", "src/target.ts", "--format", "json"], - ); - assert!( - json_output.status.success(), - "trace json failed: {}", - String::from_utf8_lossy(&json_output.stderr) - ); - let parsed: Value = serde_json::from_slice(&json_output.stdout).unwrap(); + let parsed = trace_json(repo.path(), &["src/a.ts", "src/target.ts"]); assert_eq!(parsed["from"], "src/a.ts"); assert_eq!(parsed["to"], "src/target.ts"); assert_eq!(parsed["connected"], true); @@ -56,15 +68,12 @@ fn trace_finds_shortest_runtime_import_path_in_cli_json_text_and_toon() { json!([["src/a.ts", "src/d.ts", "src/target.ts"]]) ); - let text_output = run_codeint( - repo.path(), - &["trace", "src/a.ts", "src/target.ts", "--format", "text"], + assert_eq!( + trace_text(repo.path(), &["src/a.ts", "src/target.ts"]), + "src/a.ts -> src/d.ts -> src/target.ts" ); - assert!(text_output.status.success()); - let text = String::from_utf8(text_output.stdout).unwrap(); - assert_eq!(text.trim(), "src/a.ts -> src/d.ts -> src/target.ts"); - let toon_output = run_codeint(repo.path(), &["trace", "src/a.ts", "src/target.ts"]); + let toon_output = run_trace(repo.path(), &["src/a.ts", "src/target.ts"]); assert!(toon_output.status.success()); let toon = String::from_utf8(toon_output.stdout).unwrap(); assert!(toon.contains("from: src/a.ts"), "toon output: {toon}"); @@ -94,19 +103,7 @@ fn trace_all_returns_multiple_shortest_paths_deterministically_with_cap() { ("src/leaf.ts", "export const leaf = 1;\n"), ]); - let all_output = run_codeint( - repo.path(), - &[ - "trace", - "src/entry.ts", - "src/leaf.ts", - "--all", - "--format", - "json", - ], - ); - assert!(all_output.status.success()); - let parsed: Value = serde_json::from_slice(&all_output.stdout).unwrap(); + let parsed = trace_json(repo.path(), &["src/entry.ts", "src/leaf.ts", "--all"]); assert_eq!(parsed["shortest_distance"], 2); assert_eq!(parsed["truncated"], false); assert_eq!( @@ -118,21 +115,10 @@ fn trace_all_returns_multiple_shortest_paths_deterministically_with_cap() { ]) ); - let capped_output = run_codeint( + let capped = trace_json( repo.path(), - &[ - "trace", - "src/entry.ts", - "src/leaf.ts", - "--all", - "--max-paths", - "2", - "--format", - "json", - ], + &["src/entry.ts", "src/leaf.ts", "--all", "--max-paths", "2"], ); - assert!(capped_output.status.success()); - let capped: Value = serde_json::from_slice(&capped_output.stdout).unwrap(); assert_eq!(capped["truncated"], true); assert_eq!( capped["paths"], @@ -161,12 +147,7 @@ fn trace_handles_cycles_disconnected_modules_and_missing_paths() { ("src/isolated.ts", "export const isolated = 0;\n"), ]); - let cyclic_output = run_codeint( - repo.path(), - &["trace", "src/a.ts", "src/c.ts", "--all", "--format", "json"], - ); - assert!(cyclic_output.status.success()); - let cyclic: Value = serde_json::from_slice(&cyclic_output.stdout).unwrap(); + let cyclic = trace_json(repo.path(), &["src/a.ts", "src/c.ts", "--all"]); assert_eq!(cyclic["connected"], true); assert_eq!(cyclic["shortest_distance"], 2); assert_eq!( @@ -174,28 +155,18 @@ fn trace_handles_cycles_disconnected_modules_and_missing_paths() { json!([["src/a.ts", "src/b.ts", "src/c.ts"]]) ); - let disconnected_output = run_codeint( - repo.path(), - &["trace", "src/a.ts", "src/isolated.ts", "--format", "json"], - ); - assert_eq!(disconnected_output.status.code(), Some(0)); - let disconnected: Value = serde_json::from_slice(&disconnected_output.stdout).unwrap(); + let disconnected = trace_json(repo.path(), &["src/a.ts", "src/isolated.ts"]); assert_eq!(disconnected["connected"], false); assert_eq!(disconnected["shortest_distance"], Value::Null); assert_eq!(disconnected["paths"], json!([])); assert_eq!(disconnected["truncated"], false); - let disconnected_text = run_codeint( - repo.path(), - &["trace", "src/a.ts", "src/isolated.ts", "--format", "text"], - ); - assert_eq!(disconnected_text.status.code(), Some(0)); assert_eq!( - String::from_utf8(disconnected_text.stdout).unwrap().trim(), + trace_text(repo.path(), &["src/a.ts", "src/isolated.ts"]), "No runtime import path from src/a.ts to src/isolated.ts" ); - let missing_output = run_codeint(repo.path(), &["trace", "src/a.ts", "src/does-not-exist.ts"]); + let missing_output = run_trace(repo.path(), &["src/a.ts", "src/does-not-exist.ts"]); assert_eq!(missing_output.status.code(), Some(2)); let stderr = String::from_utf8(missing_output.stderr).unwrap(); assert!( @@ -224,9 +195,17 @@ fn mcp_trace_tool_returns_paths_and_errors_cleanly() { &[ json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}}), json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}), - json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "trace", "arguments": {"from": "src/a.ts", "to": "src/c.ts"}}}), - json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "trace", "arguments": {"from": "src/a.ts", "to": "src/other.ts"}}}), - json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "trace", "arguments": {"from": "src/a.ts", "to": "src/missing.ts"}}}), + mcp_tool_call(3, "trace", json!({"from": "src/a.ts", "to": "src/c.ts"})), + mcp_tool_call( + 4, + "trace", + json!({"from": "src/a.ts", "to": "src/other.ts"}), + ), + mcp_tool_call( + 5, + "trace", + json!({"from": "src/a.ts", "to": "src/missing.ts"}), + ), ], ); @@ -237,13 +216,7 @@ fn mcp_trace_tool_returns_paths_and_errors_cleanly() { "expected trace tool in tools/list: {tools:?}" ); - assert_eq!(responses[2]["result"]["isError"], false); - let found: Value = serde_json::from_str( - responses[2]["result"]["content"][0]["text"] - .as_str() - .unwrap(), - ) - .unwrap(); + let found = mcp_payload(&responses[2]); assert_eq!(found["connected"], true); assert_eq!(found["shortest_distance"], 2); assert_eq!( @@ -251,13 +224,7 @@ fn mcp_trace_tool_returns_paths_and_errors_cleanly() { json!([["src/a.ts", "src/b.ts", "src/c.ts"]]) ); - assert_eq!(responses[3]["result"]["isError"], false); - let disconnected: Value = serde_json::from_str( - responses[3]["result"]["content"][0]["text"] - .as_str() - .unwrap(), - ) - .unwrap(); + let disconnected = mcp_payload(&responses[3]); assert_eq!(disconnected["connected"], false); assert_eq!(disconnected["paths"], json!([])); @@ -291,38 +258,21 @@ fn trace_works_across_source_sets_and_python_and_rejects_zero_max_paths() { ("py/__init__.py", ""), ]); - let cross_set = run_codeint( - repo.path(), - &[ - "trace", - "src/app.test.ts", - "src/core.ts", - "--format", - "json", - ], - ); - assert!(cross_set.status.success()); - let parsed: Value = serde_json::from_slice(&cross_set.stdout).unwrap(); + let parsed = trace_json(repo.path(), &["src/app.test.ts", "src/core.ts"]); assert_eq!(parsed["connected"], true); assert_eq!( parsed["paths"], json!([["src/app.test.ts", "src/helper.ts", "src/core.ts"]]) ); - let py_trace = run_codeint( - repo.path(), - &["trace", "py/main.py", "py/util.py", "--format", "text"], - ); - assert!(py_trace.status.success()); assert_eq!( - String::from_utf8(py_trace.stdout).unwrap().trim(), + trace_text(repo.path(), &["py/main.py", "py/util.py"]), "py/main.py -> py/util.py" ); - let zero_cap = run_codeint( + let zero_cap = run_trace( repo.path(), &[ - "trace", "src/app.test.ts", "src/core.ts", "--all", diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 234e3aa..a5eba91 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -78,6 +78,12 @@ pub enum FindingsShown { All, } +impl Default for FindingsShown { + fn default() -> FindingsShown { + FindingsShown::WorstPerMetric(WORST_FINDINGS_PER_METRIC) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] pub enum ReportFormat { Toon, @@ -116,6 +122,12 @@ pub enum TrendRange { Since(CalendarDay), } +impl Default for TrendRange { + fn default() -> TrendRange { + TrendRange::Latest(LATEST_COMMITS_OF_A_TREND) + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub enum Command { Check { @@ -236,12 +248,8 @@ enum CommandArguments { help = "Measure every main-line commit committed on or after this day, in UTC, instead of the latest 20" )] since: Option, - #[arg( - long, - value_name = "FILE", - help = "Write the report to this file instead of standard output" - )] - output: Option, + #[command(flatten)] + output: OutputArgument, #[arg( long, value_enum, @@ -251,91 +259,11 @@ enum CommandArguments { format: TrendFormat, }, #[command(about = "Find the shortest runtime import path between two files in the repository")] - Trace { - #[arg( - value_name = "FROM", - help = "Repository-relative path of the starting module" - )] - from: String, - #[arg( - value_name = "TO", - help = "Repository-relative path of the target module" - )] - to: String, - #[arg( - long, - help = "List all shortest runtime import paths up to --max-paths" - )] - all: bool, - #[arg( - long = "max-paths", - value_name = "COUNT", - default_value_t = DEFAULT_MAX_TRACE_PATHS, - help = "Maximum number of shortest paths to list when --all is set" - )] - max_paths: usize, - #[arg( - long, - value_name = "PATH", - help = "Scope the query to this Workspace package" - )] - package: Option, - #[arg( - long, - value_name = "FILE", - help = "Write the report to this file instead of standard output" - )] - output: Option, - #[arg( - long, - value_enum, - default_value_t = TraceFormat::Toon, - help = "The format of the report" - )] - format: TraceFormat, - }, + Trace(TraceArguments), #[command( about = "Compute the transitive reverse-dependency blast radius of one or more repository files" )] - Impact { - #[arg( - value_name = "PATH", - required_unless_present = "changed", - help = "Repository file paths to analyze" - )] - paths: Vec, - #[arg( - long, - value_name = "BASE_REF", - help = "Analyze files changed since the merge-base of this Git ref and HEAD" - )] - changed: Option, - #[arg( - long, - value_name = "N", - help = "Maximum reverse-dependency hop distance to traverse" - )] - depth: Option, - #[arg( - long, - value_name = "PATH", - help = "Scope reported dependents to this Workspace package" - )] - package: Option, - #[arg( - long, - value_name = "FILE", - help = "Write the report to this file instead of standard output" - )] - output: Option, - #[arg( - long, - value_enum, - default_value_t = ImpactFormat::Toon, - help = "The format of the report" - )] - format: ImpactFormat, - }, + Impact(ImpactArguments), #[command( about = "Write a starter codeint.json at the root of the Git repository that contains the current folder" )] @@ -360,6 +288,16 @@ enum CommandArguments { Mcp, } +#[derive(Debug, clap::Args)] +struct OutputArgument { + #[arg( + long, + value_name = "FILE", + help = "Write the report to this file instead of standard output" + )] + output: Option, +} + #[derive(Debug, clap::Args)] struct ReportArguments { #[arg( @@ -368,12 +306,8 @@ struct ReportArguments { help = "Scope measurement and output to this Workspace package" )] package: Option, - #[arg( - long, - value_name = "FILE", - help = "Write the report to this file instead of standard output" - )] - output: Option, + #[command(flatten)] + output: OutputArgument, #[arg(long, help = "List every Finding instead of the 20 worst per Metric")] all: bool, #[arg( @@ -385,80 +319,121 @@ struct ReportArguments { format: ReportFormat, } +#[derive(Debug, clap::Args)] +struct TraceArguments { + #[arg( + value_name = "FROM", + help = "Repository-relative path of the starting module" + )] + from: String, + #[arg( + value_name = "TO", + help = "Repository-relative path of the target module" + )] + to: String, + #[arg( + long, + help = "List all shortest runtime import paths up to --max-paths" + )] + all: bool, + #[arg( + long = "max-paths", + value_name = "COUNT", + default_value_t = DEFAULT_MAX_TRACE_PATHS, + help = "Maximum number of shortest paths to list when --all is set" + )] + max_paths: usize, + #[arg( + long, + value_name = "PATH", + help = "Scope the query to this Workspace package" + )] + package: Option, + #[command(flatten)] + output: OutputArgument, + #[arg( + long, + value_enum, + default_value_t = TraceFormat::Toon, + help = "The format of the report" + )] + format: TraceFormat, +} + +#[derive(Debug, clap::Args)] +struct ImpactArguments { + #[arg( + value_name = "PATH", + required_unless_present = "changed", + help = "Repository file paths to analyze" + )] + paths: Vec, + #[arg( + long, + value_name = "BASE_REF", + help = "Analyze files changed since the merge-base of this Git ref and HEAD" + )] + changed: Option, + #[arg( + long, + value_name = "N", + help = "Maximum reverse-dependency hop distance to traverse" + )] + depth: Option, + #[arg( + long, + value_name = "PATH", + help = "Scope reported dependents to this Workspace package" + )] + package: Option, + #[command(flatten)] + output: OutputArgument, + #[arg( + long, + value_enum, + default_value_t = ImpactFormat::Toon, + help = "The format of the report" + )] + format: ImpactFormat, +} + pub fn read_invocation() -> Result { let arguments = Arguments::parse(); let current_folder = std::env::current_dir().map_err(ConfigError::CurrentFolder)?; - let command = match arguments.command { + let command = build_command(arguments.command, current_folder)?; + Ok(Invocation { command }) +} + +fn build_command( + arguments: CommandArguments, + current_folder: PathBuf, +) -> Result { + match arguments { CommandArguments::Check { path, report } => { - build_check_command(¤t_folder, path, report)? + build_check_command(¤t_folder, path, report) } CommandArguments::Diff { base_ref, head_ref, report, - } => build_diff_command(¤t_folder, base_ref, head_ref, report)?, + } => build_diff_command(¤t_folder, base_ref, head_ref, report), CommandArguments::Trend { since, output, format, - } => Command::Trend { - folder: current_folder.clone(), - range: since.map_or( - TrendRange::Latest(LATEST_COMMITS_OF_A_TREND), - TrendRange::Since, - ), - destination: report_destination(¤t_folder, output)?, - format, - result_cache: result_cache_folder_of_this_process(¤t_folder), - plugin_host: plugin_host_config_of_this_process(¤t_folder), - }, - CommandArguments::Impact { - paths, - changed, - depth, - package, - output, - format, - } => Command::Impact { - folder: current_folder.clone(), - paths, - changed, - depth, - package, - destination: report_destination(¤t_folder, output)?, - format, - plugin_host: plugin_host_config_of_this_process(¤t_folder), - }, - CommandArguments::Trace { - from, - to, - all, - max_paths, - package, - output, - format, - } => Command::Trace { - folder: current_folder.clone(), - from, - to, - all, - max_paths, - package, - destination: report_destination(¤t_folder, output)?, - format, - plugin_host: plugin_host_config_of_this_process(¤t_folder), - }, - CommandArguments::Init => Command::Init { + } => build_trend_command(¤t_folder, since, output.output, format), + CommandArguments::Impact(args) => build_impact_command(¤t_folder, args), + CommandArguments::Trace(args) => build_trace_command(¤t_folder, args), + CommandArguments::Init => Ok(Command::Init { folder: current_folder, - }, - CommandArguments::Update { check, version } => build_update_command(check, version), - CommandArguments::Mcp => Command::Mcp { + }), + CommandArguments::Update { check, version } => Ok(build_update_command(check, version)), + CommandArguments::Mcp => Ok(Command::Mcp { result_cache: result_cache_folder_of_this_process(¤t_folder), plugin_host: plugin_host_config_of_this_process(¤t_folder), folder: current_folder, - }, - }; - Ok(Invocation { command }) + }), + } } fn build_check_command( @@ -468,7 +443,7 @@ fn build_check_command( ) -> Result { Ok(Command::Check { folder: existing_folder(current_folder, path)?, - destination: report_destination(current_folder, report.output)?, + destination: report_destination(current_folder, report.output.output)?, findings: findings_shown(report.all), format: report.format, package: report.package, @@ -486,7 +461,7 @@ fn build_diff_command( folder: current_folder.to_path_buf(), base_ref, head_ref, - destination: report_destination(current_folder, report.output)?, + destination: report_destination(current_folder, report.output.output)?, findings: findings_shown(report.all), format: report.format, package: report.package, @@ -495,6 +470,55 @@ fn build_diff_command( }) } +fn build_trend_command( + current_folder: &Path, + since: Option, + output: Option, + format: TrendFormat, +) -> Result { + Ok(Command::Trend { + folder: current_folder.to_path_buf(), + range: since.map_or_else(TrendRange::default, TrendRange::Since), + destination: report_destination(current_folder, output)?, + format, + result_cache: result_cache_folder_of_this_process(current_folder), + plugin_host: plugin_host_config_of_this_process(current_folder), + }) +} + +fn build_impact_command( + current_folder: &Path, + args: ImpactArguments, +) -> Result { + Ok(Command::Impact { + folder: current_folder.to_path_buf(), + paths: args.paths, + changed: args.changed, + depth: args.depth, + package: args.package, + destination: report_destination(current_folder, args.output.output)?, + format: args.format, + plugin_host: plugin_host_config_of_this_process(current_folder), + }) +} + +fn build_trace_command( + current_folder: &Path, + args: TraceArguments, +) -> Result { + Ok(Command::Trace { + folder: current_folder.to_path_buf(), + from: args.from, + to: args.to, + all: args.all, + max_paths: args.max_paths, + package: args.package, + destination: report_destination(current_folder, args.output.output)?, + format: args.format, + plugin_host: plugin_host_config_of_this_process(current_folder), + }) +} + fn build_update_command(check_only: bool, version: Option) -> Command { Command::Update { check_only, diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index a5248a4..bd22b8a 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -173,8 +173,8 @@ impl DiffReport { pub fn render(&self, format: ReportFormat) -> Result { match format { - ReportFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), - ReportFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), + ReportFormat::Toon => crate::render_toon(self), + ReportFormat::Json => crate::render_json(self), ReportFormat::Sarif => serde_json::to_string_pretty(&self.new_findings_as_sarif()) .map_err(ReportError::Sarif), ReportFormat::Markdown => Ok(markdown::render(self)), diff --git a/crates/report/src/impact.rs b/crates/report/src/impact.rs index 515472a..2777f58 100644 --- a/crates/report/src/impact.rs +++ b/crates/report/src/impact.rs @@ -116,11 +116,7 @@ impl ImpactReport { } pub fn render(&self, format: ImpactFormat) -> Result { - match format { - ImpactFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), - ImpactFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), - ImpactFormat::Text => Ok(render_text(self)), - } + crate::render_text_report(self, format.into(), render_text) } } diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index dbc2da2..742d5f7 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -2,7 +2,7 @@ use std::collections::BTreeMap; -use codeint_config::{Budgets, FindingsShown, ReportFormat}; +use codeint_config::{Budgets, FindingsShown, ImpactFormat, ReportFormat, TraceFormat}; use codeint_metrics::{ CloneGroup, Duplication, ErodedFunction, Erosion, FlaggedLineFinding, Fragment, ImportCycle, ImportCycles, MinimumCloneTokens, MinimumDistinctTokens, UnresolvedImport, Verbosity, @@ -875,11 +875,57 @@ impl Report { pub fn render(&self, format: ReportFormat) -> Result { match format { - ReportFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), - ReportFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), + ReportFormat::Toon => render_toon(self), + ReportFormat::Json => render_json(self), ReportFormat::Sarif => serde_json::to_string_pretty(&sarif::SarifLog::new(self)) .map_err(ReportError::Sarif), ReportFormat::Markdown => Ok(markdown::render(self)), } } } + +pub(crate) enum TextReportFormat { + Toon, + Json, + Text, +} + +impl From for TextReportFormat { + fn from(format: ImpactFormat) -> TextReportFormat { + match format { + ImpactFormat::Toon => TextReportFormat::Toon, + ImpactFormat::Json => TextReportFormat::Json, + ImpactFormat::Text => TextReportFormat::Text, + } + } +} + +impl From for TextReportFormat { + fn from(format: TraceFormat) -> TextReportFormat { + match format { + TraceFormat::Toon => TextReportFormat::Toon, + TraceFormat::Json => TextReportFormat::Json, + TraceFormat::Text => TextReportFormat::Text, + } + } +} + +pub(crate) fn render_text_report( + value: &T, + format: TextReportFormat, + render_text: impl FnOnce(&T) -> String, +) -> Result { + match format { + TextReportFormat::Toon => render_toon(value), + TextReportFormat::Json => render_json(value), + TextReportFormat::Text => Ok(render_text(value)), + } +} + +pub(crate) fn render_toon(value: &T) -> Result { + toon_format::encode_default(value).map_err(ReportError::Toon) +} + +pub(crate) fn render_json(value: &T) -> Result { + serde_json::to_string_pretty(value).map_err(ReportError::Json) +} diff --git a/crates/report/src/trace.rs b/crates/report/src/trace.rs index 72b33a5..3db42b8 100644 --- a/crates/report/src/trace.rs +++ b/crates/report/src/trace.rs @@ -42,11 +42,7 @@ impl TraceReport { } pub fn render(&self, format: TraceFormat) -> Result { - match format { - TraceFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), - TraceFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), - TraceFormat::Text => Ok(render_text(self)), - } + crate::render_text_report(self, format.into(), render_text) } } diff --git a/crates/report/src/trend.rs b/crates/report/src/trend.rs index ba1c527..bb9d9cd 100644 --- a/crates/report/src/trend.rs +++ b/crates/report/src/trend.rs @@ -69,8 +69,8 @@ impl TrendReport { pub fn render(&self, format: TrendFormat) -> Result { match format { - TrendFormat::Toon => toon_format::encode_default(self).map_err(ReportError::Toon), - TrendFormat::Json => serde_json::to_string_pretty(self).map_err(ReportError::Json), + TrendFormat::Toon => crate::render_toon(self), + TrendFormat::Json => crate::render_json(self), TrendFormat::Markdown => Ok(markdown::render(self)), } }