diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index 8bdf90e..8ee67e2 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -1,9 +1,9 @@ -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use std::string::FromUtf8Error; use codeint_config::{ - Codeowners, CodeownersError, Configuration, ConfigurationFileError, FindingsShown, + Codeowners, CodeownersError, Configuration, ConfigurationFileError, EntryPoints, FindingsShown, LanguageCoverage, OwnerFilter, PluginHostConfig, SourceSetOverrides, read_configuration, }; use codeint_git::{GitError, Repository, Snapshot}; @@ -12,10 +12,12 @@ use codeint_lang_php::Php; use codeint_lang_python::Python; use codeint_lang_rust::Rust; use codeint_lang_ts::{TypeScriptAndJavaScript, vue_reference_ranges}; +use codeint_metrics::OrphanFiles; use codeint_model::{ - CodeModel, InvalidReferenceRange, LanguagePlugin, LowerError, Manifest, MetricPlugin, - MetricPluginError, Package, ReferenceRanges, RepoPath, ResolveError, SkippedFile, SourceFile, - Workspace, WorkspaceError, choose_manifests, resolve_runtime_imports, settle_source_set, + CodeModel, InvalidReferenceRange, LanguagePlugin, LanguagePluginError, LowerError, Manifest, + MetricPlugin, 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, @@ -44,6 +46,8 @@ pub(crate) enum CheckError { #[error(transparent)] PluginHost(#[from] PluginHostError), #[error(transparent)] + LanguagePlugin(#[from] LanguagePluginError), + #[error(transparent)] MetricPlugin(#[from] MetricPluginError), #[error("{}", format_extension_conflict(first, second, extension, path.as_ref()))] ExtensionConflict { @@ -389,6 +393,34 @@ fn check_with( ) } +pub(crate) struct MeasuredSnapshot { + pub(crate) languages: Vec, + pub(crate) entry_points_by_language: BTreeMap>, +} + +pub(crate) fn compute_orphan_files( + snapshot: &MeasuredSnapshot, + selected: Option<&SelectedPackage>, +) -> (Option, BTreeMap) { + let mut by_language = BTreeMap::new(); + for language in &snapshot.languages { + let entry_points = snapshot + .entry_points_by_language + .get(&language.plugin) + .map(Vec::as_slice) + .unwrap_or(&[]); + if let Some(measured) = + OrphanFiles::measure_filtered(&language.model, entry_points, |path| { + selected.is_none_or(|pkg| pkg.matches(language.model.workspace.package_of(path))) + }) + { + by_language.insert(language.plugin.clone(), measured); + } + } + let total = OrphanFiles::merge(by_language.values().cloned()); + (total, by_language) +} + fn check_loaded( repository: &Repository, configuration: &Configuration, @@ -399,14 +431,20 @@ fn check_loaded( ownership: OwnershipOptions<'_>, ) -> Result { let tree = repository.working_tree()?; - 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); + let mut snapshot = measure_snapshot(&tree, plugins, configuration)?; + let selected = if let Some(requested) = package { + let workspace = workspace_of_languages(&snapshot.languages); + Some(select_workspace_package(&workspace, requested)?) + } else { + None + }; + let (orphan_files, orphan_files_by_language) = + compute_orphan_files(&snapshot, selected.as_ref()); + if let Some(selected) = &selected { + filter_languages_to_package(&mut snapshot.languages, selected); } Ok(Report::summarize_with_options( - languages, + snapshot.languages, tree.submodules().to_vec(), ReportOptions { findings, @@ -414,6 +452,8 @@ fn check_loaded( metric_plugins, boundaries: configuration.boundaries.as_ref(), duplication: configuration.duplication, + orphan_files: orphan_files.as_ref(), + orphan_files_by_language: Some(&orphan_files_by_language), ownership, }, )?) @@ -424,6 +464,14 @@ pub(crate) fn measure_with( plugins: &[NamedLanguagePlugin<'_>], configuration: &Configuration, ) -> Result, CheckError> { + Ok(measure_snapshot(tree, plugins, configuration)?.languages) +} + +pub(crate) fn measure_snapshot( + tree: &Snapshot, + plugins: &[NamedLanguagePlugin<'_>], + configuration: &Configuration, +) -> Result { let names: Vec<&str> = plugins.iter().map(|plugin| plugin.name).collect(); let coverage = configuration.languages.coverage_of(&names)?; measure( @@ -431,6 +479,7 @@ pub(crate) fn measure_with( plugins, &coverage, &configuration.source_set_overrides, + &configuration.entry_points, ) } @@ -439,19 +488,30 @@ fn measure( plugins: &[NamedLanguagePlugin<'_>], coverage: &[LanguageCoverage<'_>], overrides: &SourceSetOverrides, -) -> Result, CheckError> { + configured_entry_points: &EntryPoints, +) -> Result { let covered_files = assign_files_to_plugins(tree, plugins, coverage)?; let manifests_by_plugin = read_manifests(tree, plugins)?; let workspace = find_workspace(plugins, &manifests_by_plugin)?; - let mut models: Vec = plugins - .iter() - .map(|_| CodeModel { - workspace: workspace.clone(), - ..CodeModel::default() - }) - .collect(); - let outcomes = if let Some(reader) = tree.working_tree_reader() { - covered_files + let outcomes = lower_covered_files(tree, plugins, &covered_files, overrides)?; + let models = collect_plugin_models(plugins.len(), workspace, outcomes); + resolve_measured_snapshot( + tree, + plugins, + models, + manifests_by_plugin, + configured_entry_points, + ) +} + +fn lower_covered_files( + tree: &Snapshot, + plugins: &[NamedLanguagePlugin<'_>], + covered_files: &[(&RepoPath, usize)], + overrides: &SourceSetOverrides, +) -> Result, CheckError> { + if let Some(reader) = tree.working_tree_reader() { + return covered_files .par_iter() .map(|&(path, index)| { let bytes = reader.read(path)?; @@ -460,22 +520,34 @@ fn measure( lower_bytes(bytes, path, plugins[index].plugin, overrides), )) }) - .collect::, CheckError>>()? - } else { - let loaded = covered_files - .iter() - .map(|&(path, index)| Ok((path, index, tree.read(path)?))) - .collect::, CheckError>>()?; - loaded - .into_par_iter() - .map(|(path, index, bytes)| { - ( - index, - lower_bytes(bytes, path, plugins[index].plugin, overrides), - ) - }) - .collect() - }; + .collect(); + } + let loaded = covered_files + .iter() + .map(|&(path, index)| Ok((path, index, tree.read(path)?))) + .collect::, CheckError>>()?; + Ok(loaded + .into_par_iter() + .map(|(path, index, bytes)| { + ( + index, + lower_bytes(bytes, path, plugins[index].plugin, overrides), + ) + }) + .collect()) +} + +fn collect_plugin_models( + plugin_count: usize, + workspace: Workspace, + outcomes: Vec<(usize, LoweredFile)>, +) -> Vec { + let mut models: Vec = (0..plugin_count) + .map(|_| CodeModel { + workspace: workspace.clone(), + ..CodeModel::default() + }) + .collect(); for (index, outcome) in outcomes { let model = &mut models[index]; match outcome { @@ -484,23 +556,54 @@ fn measure( LoweredFile::Skipped(skipped) => model.skipped.push(skipped), } } - plugins - .iter() - .zip(models) - .zip(manifests_by_plugin) - .map(|((named, mut model), manifests)| { - let importers: Vec<&SourceFile> = model.files.iter().collect(); - let reference_ranges = select_reference_ranges(named, &model, &manifests)?; - model.runtime_imports = - resolve_runtime_imports(named.plugin, tree.files(), manifests, &importers) - .map_err(CheckError::Resolve)?; - Ok(MeasuredLanguage { - plugin: named.name.to_owned(), - model, - reference_ranges, - }) - }) - .collect() + models +} + +fn resolve_measured_snapshot( + tree: &Snapshot, + plugins: &[NamedLanguagePlugin<'_>], + models: Vec, + manifests_by_plugin: Vec>, + configured_entry_points: &EntryPoints, +) -> Result { + let mut languages = Vec::with_capacity(plugins.len()); + let mut entry_points_by_language = BTreeMap::new(); + for ((named, mut model), manifests) in plugins.iter().zip(models).zip(manifests_by_plugin) { + let importers: Vec<&SourceFile> = model.files.iter().collect(); + let reference_ranges = select_reference_ranges(named, &model, &manifests)?; + let manifest_entries = named.plugin.entry_points(tree.files(), manifests.clone())?; + let combined_entries = + combine_entry_points(manifest_entries, &model.files, configured_entry_points); + model.runtime_imports = + resolve_runtime_imports(named.plugin, tree.files(), manifests, &importers) + .map_err(CheckError::Resolve)?; + entry_points_by_language.insert(named.name.to_owned(), combined_entries); + languages.push(MeasuredLanguage { + plugin: named.name.to_owned(), + model, + reference_ranges, + }); + } + Ok(MeasuredSnapshot { + languages, + entry_points_by_language, + }) +} + +fn combine_entry_points( + manifest_entries: Vec, + files: &[SourceFile], + configured: &EntryPoints, +) -> Vec { + let mut entries: BTreeSet = manifest_entries.into_iter().collect(); + if !configured.is_empty() { + for file in files { + if configured.matches(&file.path) { + entries.insert(file.path.clone()); + } + } + } + entries.into_iter().collect() } fn select_reference_ranges( diff --git a/crates/cli/src/check/tests.rs b/crates/cli/src/check/tests.rs index 55eec1e..3c75b70 100644 --- a/crates/cli/src/check/tests.rs +++ b/crates/cli/src/check/tests.rs @@ -723,6 +723,7 @@ struct ParallelProofPlugin { arrivals: AtomicUsize, barrier: Barrier, expected: usize, + fail_entry_points: bool, } impl ParallelProofPlugin { @@ -731,6 +732,16 @@ impl ParallelProofPlugin { arrivals: AtomicUsize::new(0), barrier: Barrier::new(expected), expected, + fail_entry_points: false, + } + } + + fn failing_entry_points() -> ParallelProofPlugin { + ParallelProofPlugin { + arrivals: AtomicUsize::new(0), + barrier: Barrier::new(1), + expected: 0, + fail_entry_points: true, } } } @@ -795,6 +806,11 @@ impl LanguagePlugin for ParallelProofPlugin { _repository_paths: &[RepoPath], _manifests: Vec, ) -> Result, codeint_model::LanguagePluginError> { + if self.fail_entry_points { + return Err(codeint_model::LanguagePluginError::InvalidEntryPointPath { + path: "../outside.parallel".to_owned(), + }); + } Ok(Vec::new()) } @@ -1004,3 +1020,25 @@ fn a_single_plugin_listing_one_extension_twice_does_not_conflict_with_itself() { "unexpected report: {report}" ); } + +#[test] +fn an_invalid_entry_point_from_a_language_plugin_stops_the_check() { + let folder = repository(&[("main.parallel", "one\n")]); + let plugin = ParallelProofPlugin::failing_entry_points(); + let named = NamedLanguagePlugin { + name: "bad-entry", + plugin: &plugin, + }; + + let result = check_with(folder.path(), &[named], FindingsShown::All); + + assert!( + matches!( + result, + Err(CheckError::LanguagePlugin( + codeint_model::LanguagePluginError::InvalidEntryPointPath { .. } + )) + ), + "unexpected result: {result:?}" + ); +} diff --git a/crates/cli/src/commit_measurement.rs b/crates/cli/src/commit_measurement.rs index 09ee477..0dd99f2 100644 --- a/crates/cli/src/commit_measurement.rs +++ b/crates/cli/src/commit_measurement.rs @@ -5,13 +5,13 @@ use codeint_report::CommitMeasurement; use serde::Serialize; use crate::check::{ - BUILT_IN_LANGUAGE_PLUGINS, CheckError, LoadedPlugins, SelectedPackage, filter_model_to_package, - measure_with, select_workspace_package, + BUILT_IN_LANGUAGE_PLUGINS, CheckError, LoadedPlugins, SelectedPackage, compute_orphan_files, + filter_model_to_package, measure_snapshot, select_workspace_package, workspace_of_languages, }; use crate::describe; const CODEINT_VERSION: &str = env!("CARGO_PKG_VERSION"); -const MEASUREMENT_CACHE_VERSION: u32 = 2; +const MEASUREMENT_CACHE_VERSION: u32 = 3; #[derive(Serialize)] struct MeasurementSettings<'configuration> { @@ -131,20 +131,29 @@ pub(crate) fn measure_all_languages_for_package( ) -> 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 snapshot = measure_snapshot(tree, &named, configuration)?; let selected = if let Some(requested) = package { - let selected = select_workspace_package(&model.workspace, requested)?; - filter_model_to_package(&mut model, &selected); - Some(selected) + let workspace = workspace_of_languages(&snapshot.languages); + Some(select_workspace_package(&workspace, requested)?) } else { None }; - let measurement = CommitMeasurement::of_with_config( + let (orphan_files, _) = compute_orphan_files(&snapshot, selected.as_ref()); + let mut model = CodeModel::merge( + snapshot + .languages + .into_iter() + .map(|language| language.model), + ); + if let Some(selected) = &selected { + filter_model_to_package(&mut model, selected); + } + let measurement = CommitMeasurement::of_with_options( model, &metric_plugins, configuration.boundaries.as_ref(), configuration.duplication, + orphan_files.as_ref(), )?; Ok((selected, measurement)) } @@ -157,15 +166,22 @@ fn measure_all_languages_selected( ) -> Result { 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 snapshot = measure_snapshot(tree, &named, configuration)?; + let (orphan_files, _) = compute_orphan_files(&snapshot, selected); + let mut model = CodeModel::merge( + snapshot + .languages + .into_iter() + .map(|language| language.model), + ); if let Some(selected) = selected { filter_model_to_package(&mut model, selected); } - Ok(CommitMeasurement::of_with_config( + Ok(CommitMeasurement::of_with_options( model, &metric_plugins, configuration.boundaries.as_ref(), configuration.duplication, + orphan_files.as_ref(), )?) } diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs index 81ad45d..d5f1c68 100644 --- a/crates/cli/src/mcp.rs +++ b/crates/cli/src/mcp.rs @@ -129,7 +129,7 @@ pub(crate) fn tool_definitions() -> Vec { vec![ McpToolSchema { name: "check".to_owned(), - description: "Measure Software entropy of a Git repository working tree (Erosion, Duplication, Verbosity, Import cycles) and report any Budget failures.".to_owned(), + description: "Measure Software entropy of a Git repository working tree (Erosion, Duplication, Verbosity, Import cycles, Boundaries, Orphan files) and report any Budget failures.".to_owned(), input_schema: json!({ "type": "object", "properties": { diff --git a/crates/cli/src/remedy.rs b/crates/cli/src/remedy.rs index 96d2483..ce08a05 100644 --- a/crates/cli/src/remedy.rs +++ b/crates/cli/src/remedy.rs @@ -3,7 +3,7 @@ use codeint_config::{ }; use codeint_git::GitError; use codeint_metrics::ImpactError; -use codeint_model::{MetricPluginError, WorkspaceError}; +use codeint_model::{LanguagePluginError, MetricPluginError, WorkspaceError}; use codeint_plugin_host::PluginHostError; use codeint_report::{SavedReportError, TraceError}; @@ -76,6 +76,12 @@ fn check_remedy(error: &CheckError) -> &'static str { CheckError::Configuration(error) => configuration_file_remedy(error), CheckError::Codeowners(error) => codeowners_remedy(error), CheckError::Workspace(error) => workspace_remedy(error), + other => check_plugin_remedy(other), + } +} + +fn check_plugin_remedy(error: &CheckError) -> &'static str { + match error { CheckError::Resolve(_) => { "This is a defect in the Language plugin; report it to the author of the Language plugin." } @@ -83,7 +89,9 @@ fn check_remedy(error: &CheckError) -> &'static str { "Fix the Reference ranges that the Language plugin supplies, or report the defect to its author." } CheckError::PluginHost(error) => plugin_host_remedy(error), + CheckError::LanguagePlugin(error) => language_plugin_remedy(error), CheckError::MetricPlugin(error) => metric_plugin_remedy(error), + _ => "Check the plugin configuration in codeint.json.", } } @@ -427,6 +435,16 @@ fn plugin_runtime_remedy(error: &PluginHostError) -> &'static str { } } +fn language_plugin_remedy(error: &LanguagePluginError) -> &'static str { + match error { + LanguagePluginError::MemoryLimitExceeded { .. } + | LanguagePluginError::TimeLimitExceeded { .. } => { + "Raise plugin_limits.memory_mb or plugin_limits.timeout_ms in codeint.json if the Language plugin needs more resources, or fix the defect in the plugin." + } + _ => "Fix the defect in the Language plugin, or report it to the plugin's author.", + } +} + fn metric_plugin_remedy(error: &MetricPluginError) -> &'static str { match error { MetricPluginError::MemoryLimitExceeded { .. } diff --git a/crates/cli/tests/check.rs b/crates/cli/tests/check.rs index 6879313..e42a24b 100644 --- a/crates/cli/tests/check.rs +++ b/crates/cli/tests/check.rs @@ -2719,7 +2719,7 @@ fn an_unknown_key_in_codeint_json_is_named_with_the_allowed_keys_and_exits_2() { fn an_unknown_top_level_key_in_codeint_json_is_named_and_exits_2() { assert_codeint_json_is_rejected( r#"{ "budget": {} }"#, - "codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries, duplication", + "codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries, duplication, entry_points", UNKNOWN_KEY_REMEDY, ); } @@ -3937,7 +3937,7 @@ fn a_budget_for_an_unknown_metric_names_the_metrics_and_exits_2() { assert_codeint_json_is_rejected( r#"{ "budgets": { "production": { "complexity": 0.1 } } }"#, "codeint.json has an unknown key budgets.production.complexity; \ - the keys allowed there are erosion, duplication, verbosity, import_cycles, boundaries", + the keys allowed there are erosion, duplication, verbosity, import_cycles, boundaries, orphan_files", UNKNOWN_KEY_REMEDY, ); } diff --git a/crates/cli/tests/config.rs b/crates/cli/tests/config.rs index a0e06e2..da2953e 100644 --- a/crates/cli/tests/config.rs +++ b/crates/cli/tests/config.rs @@ -104,6 +104,13 @@ fn config_resolved_reports_defaults_only_across_text_json_and_toon_formats() { json!(0.85), "default", ); + assert_setting(&payload, "entry_points", json!([]), "default"); + assert_setting( + &payload, + "regression_limits.production.orphan_files.new_findings", + json!("any_new_finding"), + "default", + ); let text = invoke_ok_stdout(repo.path(), &["config", "--resolved"]); assert!(text.contains("source_sets.production = [] [default]")); @@ -148,7 +155,8 @@ fn config_resolved_merges_file_and_cli_overrides_with_per_field_provenance() { "duplication": { "near_clones": true, "min_similarity": 0.9 - } + }, + "entry_points": ["src/worker.ts"] }))); let file_only = resolved_json(repo.path(), &[]); @@ -202,6 +210,7 @@ fn config_resolved_merges_file_and_cli_overrides_with_per_field_provenance() { ); assert_setting(&file_only, "duplication.near_clones", json!(true), "file"); assert_setting(&file_only, "duplication.min_similarity", json!(0.9), "file"); + assert_setting(&file_only, "entry_points", json!(["src/worker.ts"]), "file"); let with_cli = resolved_json( repo.path(), diff --git a/crates/cli/tests/orphan_files.rs b/crates/cli/tests/orphan_files.rs new file mode 100644 index 0000000..9644360 --- /dev/null +++ b/crates/cli/tests/orphan_files.rs @@ -0,0 +1,430 @@ +mod common; + +use std::path::Path; +use std::process::Command; + +use common::{init_git_repo, mcp_payload, mcp_tool_call, send_mcp_requests}; +use serde_json::{Value, json}; +use tempfile::TempDir; + +fn run_codeint(dir: &Path, cache_dir: Option<&Path>, args: &[&str], expected_code: i32) -> String { + let mut command = Command::new(env!("CARGO_BIN_EXE_codeint")); + command.args(args).current_dir(dir); + if let Some(cache) = cache_dir { + command.env("CODEINT_CACHE_DIR", cache); + } + let output = command.output().expect("run codeint"); + assert_eq!( + output.status.code(), + Some(expected_code), + "codeint {args:?} exited {:?}; stderr: {}", + output.status.code(), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).expect("stdout utf8") +} + +fn run_json(dir: &Path, cache_dir: Option<&Path>, args: &[&str], expected_code: i32) -> Value { + let stdout = run_codeint(dir, cache_dir, args, expected_code); + serde_json::from_str(&stdout).expect("valid JSON output") +} + +fn write_file(dir: &Path, rel: &str, body: &str) { + let path = dir.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent dirs"); + } + std::fs::write(path, body).expect("write fixture file"); +} + +fn orphan_finding_paths(section: &Value) -> Vec<&str> { + section["findings"] + .as_array() + .expect("orphan findings array") + .iter() + .map(|entry| entry["path"].as_str().expect("finding path")) + .collect() +} + +fn check_json(dir: &Path, expected_code: i32) -> Value { + run_json(dir, None, &["check", "--format", "json"], expected_code) +} + +fn production_orphans(report: &Value) -> &Value { + &report["source_sets"]["production"]["orphan_files"] +} + +fn diff_main_json(dir: &Path, cache: &Path, expected_code: i32) -> Value { + run_json( + dir, + Some(cache), + &["diff", "main", "--format", "json"], + expected_code, + ) +} + +#[test] +fn ts_check_reports_orphan_files_across_toon_json_sarif_and_markdown_excluding_generated_and_vendored() + { + let repo = init_git_repo(&[ + ( + "package.json", + r#"{"name": "demo", "main": "./src/index.ts"}"#, + ), + ( + "src/index.ts", + "import { live } from './live';\nexport const run = () => live();\n", + ), + ("src/live.ts", "export const live = () => 1;\n"), + ("src/dead.ts", "export const dead = () => 2;\n"), + ("src/helper.ts", "export const helper = () => 3;\n"), + ( + "src/helper.test.ts", + "import { helper } from './helper';\nexport const check = () => helper();\n", + ), + ( + "src/gen.ts", + "// @generated\nexport const generated = () => 4;\n", + ), + ("vendor/third.ts", "export const vendored = () => 5;\n"), + ]); + + let report = run_json(repo.path(), None, &["check", "--format", "json"], 0); + assert!(report.get("score").is_none()); + let prod = &report["source_sets"]["production"]; + let orphan = &prod["orphan_files"]; + assert_eq!(orphan["orphan_files"], 2); + assert_eq!(orphan["evaluated_files"], 4); + assert_eq!(orphan["entry_points"], 1); + assert_eq!(orphan["unreferenced"], 1); + assert_eq!(orphan["test_only"], 1); + assert_eq!(orphan["ratio"], 0.5); + + let findings = orphan["findings"].as_array().expect("orphan findings"); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0]["path"], "src/dead.ts"); + assert_eq!(findings[0]["kind"], "unreferenced"); + assert!(findings[0].get("test_importers").is_none()); + assert_eq!(findings[1]["path"], "src/helper.ts"); + assert_eq!(findings[1]["kind"], "test-only"); + assert_eq!(findings[1]["test_importers"], json!(["src/helper.test.ts"])); + assert!( + findings[1]["message"] + .as_str() + .unwrap() + .contains("only imported by tests") + ); + + assert!(report["source_sets"]["test"].get("orphan_files").is_none()); + assert!( + report["source_sets"]["generated"] + .get("orphan_files") + .is_none() + ); + assert!( + report["source_sets"]["vendored"] + .get("orphan_files") + .is_none() + ); + + let toon = run_codeint(repo.path(), None, &["check"], 0); + assert!(toon.contains("orphan_files:")); + assert!(toon.contains("src/dead.ts")); + assert!(toon.contains("src/helper.ts")); + assert!(toon.contains("test-only")); + assert!(toon.contains("unreferenced")); + + let sarif = run_json(repo.path(), None, &["check", "--format", "sarif"], 0); + let results: Vec<&Value> = sarif["runs"][0]["results"] + .as_array() + .expect("sarif results") + .iter() + .filter(|item| item["ruleId"] == "orphan_files") + .collect(); + assert_eq!(results.len(), 2); + assert_eq!( + results[1]["relatedLocations"][0]["physicalLocation"]["artifactLocation"]["uri"], + "src/helper.test.ts" + ); + assert_eq!( + results[0]["partialFingerprints"]["codeintFindingId"], + findings[0]["id"] + ); + + let markdown = run_codeint(repo.path(), None, &["check", "--format", "markdown"], 0); + assert!(markdown.contains("| Production | Orphan files | 0.5 |")); + assert!(markdown.contains("### Orphan files")); + assert!(markdown.contains("`src/dead.ts`")); + assert!(markdown.contains("`src/helper.ts`")); + assert!(markdown.contains("test-only")); +} + +#[test] +fn silent_no_op_when_no_entry_points_and_activates_via_config_entry_points_globs() { + let repo = init_git_repo(&[ + ( + "src/routes/home.ts", + "import { shared } from '../shared';\nexport const home = () => shared();\n", + ), + ("src/shared.ts", "export const shared = () => 1;\n"), + ("src/abandoned.ts", "export const abandoned = () => 2;\n"), + ]); + + let silent = run_json(repo.path(), None, &["check", "--format", "json"], 0); + assert!( + silent["source_sets"]["production"] + .get("orphan_files") + .is_none() + ); + + write_file( + repo.path(), + "codeint.json", + r#"{"entry_points": ["src/routes/**/*.ts"]}"#, + ); + + let active = run_json(repo.path(), None, &["check", "--format", "json"], 0); + let orphan = &active["source_sets"]["production"]["orphan_files"]; + assert_eq!(orphan["evaluated_files"], 3); + assert_eq!(orphan["entry_points"], 1); + assert_eq!(orphan["orphan_files"], 1); + assert_eq!(orphan["findings"][0]["path"], "src/abandoned.ts"); + assert_eq!(orphan["findings"][0]["kind"], "unreferenced"); +} + +#[test] +fn monorepo_cross_package_reachability_and_isolated_package_safety() { + let repo = init_git_repo(&[ + ( + "package.json", + r#"{"name": "mono", "private": true, "workspaces": ["packages/*"]}"#, + ), + ( + "packages/app/package.json", + r#"{"name": "@mono/app", "main": "./src/index.ts"}"#, + ), + ( + "packages/app/src/index.ts", + "import { used } from '@mono/lib';\nexport const start = () => used();\n", + ), + ( + "packages/lib/package.json", + r#"{"name": "@mono/lib", "exports": {".": "./src/used.ts"}}"#, + ), + ("packages/lib/src/used.ts", "export const used = () => 1;\n"), + ( + "packages/lib/src/unused.ts", + "export const unused = () => 2;\n", + ), + ("packages/docs/package.json", r#"{"name": "@mono/docs"}"#), + ( + "packages/docs/src/page.ts", + "export const page = () => 3;\n", + ), + ]); + + let report = check_json(repo.path(), 0); + let orphan = production_orphans(&report); + assert_eq!(orphan["evaluated_files"], 3); + assert_eq!(orphan["orphan_files"], 1); + assert_eq!( + orphan_finding_paths(orphan), + vec!["packages/lib/src/unused.ts"] + ); +} + +fn init_single_entry_repo(name: &str, extra: &[(&str, &str)]) -> (TempDir, TempDir) { + let manifest = format!(r#"{{"name": "{name}", "main": "./src/index.ts"}}"#); + let mut files: Vec<(&str, &str)> = vec![ + ("package.json", manifest.as_str()), + ("src/index.ts", "export const main = () => 1;\n"), + ]; + files.extend_from_slice(extra); + (TempDir::new().expect("cache dir"), init_git_repo(&files)) +} + +#[test] +fn budget_and_diff_regression_gating_with_stable_finding_ids() { + let (cache, repo) = init_single_entry_repo( + "gate", + &[("src/legacy_dead.ts", "export const legacy = () => 2;\n")], + ); + + write_file( + repo.path(), + "codeint.json", + r#"{"budgets": {"production": {"orphan_files": 0}}}"#, + ); + let over_budget = run_json(repo.path(), None, &["check", "--format", "json"], 1); + assert_eq!(over_budget["over_budget"][0]["metric"], "orphan_files"); + + write_file(repo.path(), "codeint.json", "{}"); + let unchanged_diff = diff_main_json(repo.path(), cache.path(), 0); + let diff_orphans = &unchanged_diff["source_sets"]["production"]["orphan_files"]; + assert_eq!(diff_orphans["new"].as_array().unwrap().len(), 0); + assert_eq!(diff_orphans["resolved"].as_array().unwrap().len(), 0); + assert_eq!(diff_orphans["unchanged"], 1); + + write_file( + repo.path(), + "src/new_dead.ts", + "export const added = () => 3;\n", + ); + let regressed_diff = diff_main_json(repo.path(), cache.path(), 1); + let regressed_orphans = ®ressed_diff["source_sets"]["production"]["orphan_files"]; + assert_eq!(regressed_orphans["new"].as_array().unwrap().len(), 1); + assert_eq!(regressed_orphans["new"][0]["path"], "src/new_dead.ts"); + assert_eq!(regressed_orphans["unchanged"], 1); + assert_eq!(regressed_diff["regressions"][0]["metric"], "orphan_files"); + + std::fs::remove_file(repo.path().join("src/new_dead.ts")).expect("remove new_dead.ts"); + write_file( + repo.path(), + "src/index.ts", + "import { legacy } from './legacy_dead';\nexport const main = () => legacy();\n", + ); + let resolved_diff = diff_main_json(repo.path(), cache.path(), 0); + let resolved_orphans = &resolved_diff["source_sets"]["production"]["orphan_files"]; + assert_eq!(resolved_orphans["new"].as_array().unwrap().len(), 0); + assert_eq!(resolved_orphans["resolved"].as_array().unwrap().len(), 1); + assert_eq!( + resolved_orphans["resolved"][0]["path"], + "src/legacy_dead.ts" + ); + assert_eq!(resolved_orphans["unchanged"], 0); +} + +#[test] +fn multi_language_rust_and_python_check_and_mcp_expose_orphan_files() { + let repo = init_git_repo(&[ + ( + "Cargo.toml", + "[package]\nname = \"svc\"\nversion = \"0.1.0\"\n", + ), + ( + "src/lib.rs", + "mod live;\nuse crate::live::value;\npub fn entry() -> i32 { value() }\n", + ), + ("src/live.rs", "pub fn value() -> i32 { 1 }\n"), + ("src/dead.rs", "pub fn unused() -> i32 { 2 }\n"), + ( + "pyproject.toml", + "[project]\nname = \"pyapp\"\nversion = \"0.1.0\"\n[project.scripts]\npyapp = \"app.cli:main\"\n", + ), + ("app/__init__.py", ""), + ( + "app/cli.py", + "from app.used import run\ndef main():\n return run()\n", + ), + ("app/used.py", "def run():\n return 1\n"), + ("app/unused.py", "def stale():\n return 2\n"), + ("app/helper_for_tests.py", "def helper():\n return 3\n"), + ( + "tests/test_helper.py", + "from app.helper_for_tests import helper\ndef test_it():\n assert helper() == 3\n", + ), + ]); + + let report = check_json(repo.path(), 0); + let total_orphans = production_orphans(&report); + let paths = orphan_finding_paths(total_orphans); + assert!(paths.contains(&"src/dead.rs"), "got {paths:?}"); + assert!(paths.contains(&"app/unused.py"), "got {paths:?}"); + assert!(paths.contains(&"app/helper_for_tests.py"), "got {paths:?}"); + assert!(!paths.contains(&"src/live.rs"), "got {paths:?}"); + assert!(!paths.contains(&"app/used.py"), "got {paths:?}"); + + let test_only_finding = total_orphans["findings"] + .as_array() + .unwrap() + .iter() + .find(|f| f["path"] == "app/helper_for_tests.py") + .expect("python test-only finding"); + assert_eq!(test_only_finding["kind"], "test-only"); + + let rust_orphans = &report["languages"]["rust"]["source_sets"]["production"]["orphan_files"]; + assert!(orphan_finding_paths(rust_orphans).contains(&"src/dead.rs")); + let py_orphans = &report["languages"]["python"]["source_sets"]["production"]["orphan_files"]; + assert!(orphan_finding_paths(py_orphans).contains(&"app/unused.py")); + + write_file( + repo.path(), + "app/extra_orphan.py", + "def extra():\n return 4\n", + ); + let mcp_calls = [ + mcp_tool_call(1, "check", json!({})), + mcp_tool_call(2, "diff", json!({"base_ref": "main"})), + ]; + let responses = send_mcp_requests(repo.path(), &mcp_calls); + let check_payload = mcp_payload(&responses[0]); + let mcp_orphans = &check_payload["report"]["source_sets"]["production"]["orphan_files"]; + assert!(orphan_finding_paths(mcp_orphans).contains(&"app/extra_orphan.py")); + let diff_payload = mcp_payload(&responses[1]); + assert_eq!(diff_payload["passed"], false); + assert_eq!( + diff_payload["report"]["source_sets"]["production"]["orphan_files"]["new"][0]["path"], + "app/extra_orphan.py" + ); +} + +#[test] +fn orphan_files_attach_codeowners_and_filter_with_owner_in_check_and_diff() { + let (cache, repo) = init_single_entry_repo( + "owned", + &[ + ("src/backend_dead.ts", "export const backend = () => 2;\n"), + ( + ".github/CODEOWNERS", + "src/backend_dead.ts @org/backend\nsrc/frontend_dead.ts @org/frontend\n", + ), + ], + ); + + let check_all = check_json(repo.path(), 0); + let check_findings = production_orphans(&check_all)["findings"] + .as_array() + .expect("check orphan findings"); + assert_eq!(check_findings.len(), 1); + assert_eq!(check_findings[0]["owners"], json!(["@org/backend"])); + + let check_md = run_codeint(repo.path(), None, &["check", "--format", "markdown"], 0); + assert!(check_md.contains("| File | Kind | Details | Owners |")); + assert!(check_md.contains("`@org/backend`")); + + write_file( + repo.path(), + "src/frontend_dead.ts", + "export const frontend = () => 3;\n", + ); + let check_filtered = run_json( + repo.path(), + None, + &["check", "--format", "json", "--owner", "@org/frontend"], + 0, + ); + assert_eq!( + orphan_finding_paths(production_orphans(&check_filtered)), + vec!["src/frontend_dead.ts"] + ); + + let diff_filtered = run_json( + repo.path(), + Some(cache.path()), + &[ + "diff", + "main", + "--format", + "json", + "--owner", + "@org/frontend", + ], + 1, + ); + let diff_new = diff_filtered["source_sets"]["production"]["orphan_files"]["new"] + .as_array() + .expect("diff new orphan findings"); + assert_eq!(diff_new.len(), 1); + assert_eq!(diff_new[0]["path"], "src/frontend_dead.ts"); + assert_eq!(diff_new[0]["owners"], json!(["@org/frontend"])); +} diff --git a/crates/cli/tests/report.rs b/crates/cli/tests/report.rs index 6767456..53b92ae 100644 --- a/crates/cli/tests/report.rs +++ b/crates/cli/tests/report.rs @@ -445,6 +445,22 @@ fn rerenders_markdown_without_overflow_when_left_out_is_usize_max() { ); } +fn capture_containing_and_verify_parity( + root: &Path, + cache: &Path, + base_args: &[&str], + expected_code: i32, + expected_snippet: &str, + file_name: &str, +) { + let mut json_args = base_args.to_vec(); + json_args.extend(["--format", "json"]); + let json_run = invoke(root, cache, &json_args, None); + assert_eq!(json_run.status.code(), Some(expected_code)); + assert!(utf8(&json_run.stdout).contains(expected_snippet)); + verify_parity(root, cache, base_args, &json_run.stdout, file_name); +} + #[test] fn rerenders_check_and_diff_json_with_codeowners_owners_losslessly() { let base_file = verbose_ts("sign"); @@ -457,36 +473,68 @@ fn rerenders_check_and_diff_json_with_codeowners_owners_losslessly() { let added = eroded_ts("route", 14); populate(dir.path(), &[("src/route.ts", &added)]); - let check_json = invoke( + capture_containing_and_verify_parity( dir.path(), cache.path(), - &["check", "--format", "json"], - None, + &["check"], + 0, + "\"@platform\"", + "owned-check.json", ); - assert_eq!(check_json.status.code(), Some(0)); - assert!(utf8(&check_json.stdout).contains("\"@platform\"")); - verify_parity( + capture_containing_and_verify_parity( dir.path(), cache.path(), - &["check"], - &check_json.stdout, - "owned-check.json", + &["diff", "main"], + 1, + "\"@platform\"", + "owned-diff.json", ); +} - let diff_json = invoke( +#[test] +fn rerenders_check_and_diff_json_with_orphan_files_losslessly() { + let (dir, cache) = setup_workspace(&[ + ("package.json", r#"{"name":"app","main":"src/index.ts"}"#), + ( + "src/index.ts", + "import { live } from \"./live\";\nexport const run = (): number => live();\n", + ), + ("src/live.ts", "export const live = (): number => 1;\n"), + ("src/unused.ts", "export const unused = (): number => 2;\n"), + ( + "src/tested_only.ts", + "export const onlyTest = (): number => 3;\n", + ), + ( + "src/tested_only.test.ts", + "import { onlyTest } from \"./tested_only\";\nexport const check = (): number => onlyTest();\n", + ), + ]); + commit_all(dir.path(), "base"); + + capture_containing_and_verify_parity( dir.path(), cache.path(), - &["diff", "main", "--format", "json"], - None, + &["check"], + 0, + "\"orphan_files\"", + "orphans-check.json", ); - assert_eq!(diff_json.status.code(), Some(1)); - assert!(utf8(&diff_json.stdout).contains("\"@platform\"")); - verify_parity( + + populate( + dir.path(), + &[( + "src/new_orphan.ts", + "export const extra = (): number => 4;\n", + )], + ); + capture_containing_and_verify_parity( dir.path(), cache.path(), &["diff", "main"], - &diff_json.stdout, - "owned-diff.json", + 1, + "\"orphan_files\"", + "orphans-diff.json", ); } diff --git a/crates/cli/tests/schema.rs b/crates/cli/tests/schema.rs index f336004..6ca896d 100644 --- a/crates/cli/tests/schema.rs +++ b/crates/cli/tests/schema.rs @@ -175,7 +175,13 @@ fn schema_matches_live_cli_commands_flags_metrics_formats_mcp_tools_version_and_ .collect(); assert_eq!( metric_keys, - ["erosion", "duplication", "verbosity", "import_cycles"] + [ + "erosion", + "duplication", + "verbosity", + "import_cycles", + "orphan_files", + ] ); for metric in manifest["metrics"].as_array().expect("metrics array") { assert!(!metric["name"].as_str().unwrap_or_default().is_empty()); diff --git a/crates/config/src/codeint_json.rs b/crates/config/src/codeint_json.rs index 20fab4c..6e9c96b 100644 --- a/crates/config/src/codeint_json.rs +++ b/crates/config/src/codeint_json.rs @@ -100,9 +100,27 @@ pub struct Configuration { pub plugin_limits: PluginLimits, pub boundaries: Option, pub duplication: DuplicationConfig, + pub entry_points: EntryPoints, effective: ConfigurationFile, } +#[derive(Debug, Default)] +pub struct EntryPoints { + globs: Option, +} + +impl EntryPoints { + pub fn is_empty(&self) -> bool { + self.globs.is_none() + } + + pub fn matches(&self, path: &RepoPath) -> bool { + self.globs + .as_ref() + .is_some_and(|globs| globs.is_match(path.as_str())) + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct Sha256Digest([u8; 32]); @@ -228,7 +246,7 @@ impl Configuration { fn allowed_metric_keys(external_metric_keys: &[&str]) -> Vec { Metric::BUILT_IN_KEYS .iter() - .chain(["boundaries"].iter()) + .chain(["boundaries", "orphan_files"].iter()) .chain(external_metric_keys.iter()) .map(|key| (*key).to_owned()) .collect() @@ -237,6 +255,7 @@ fn allowed_metric_keys(external_metric_keys: &[&str]) -> Vec { fn is_known_metric(key: &str, external_metric_keys: &[&str]) -> bool { Metric::BUILT_IN_KEYS.contains(&key) || key == "boundaries" + || key == "orphan_files" || external_metric_keys.contains(&key) } @@ -439,6 +458,11 @@ struct ConfigurationFile { description = "Settings for Duplication detection, including opt-in shingle-based near-clone detection. Exact Clone groups remain the default when omitted." )] duplication: DuplicationConfigFile, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[schemars( + description = "Globs of repository-relative paths treated as additional Production entry points for Orphan files detection, combined with manifest-discovered entry points." + )] + entry_points: Vec, } #[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)] @@ -543,6 +567,9 @@ struct RegressionLimitsFile { #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] #[schemars(description = "The Regression limit of Boundaries in every Source set.")] boundaries: RegressionLimitSetting, + #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] + #[schemars(description = "The Regression limit of Orphan files in every Source set.")] + orphan_files: RegressionLimitSetting, #[serde(default, skip_serializing_if = "MetricRegressionLimits::is_unset")] #[schemars(description = "The Regression limits of the Production Source set.")] production: MetricRegressionLimits, @@ -576,6 +603,9 @@ struct MetricRegressionLimits { #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] #[schemars(description = "The Regression limit of Boundaries in this Source set.")] boundaries: RegressionLimitSetting, + #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")] + #[schemars(description = "The Regression limit of Orphan files in this Source set.")] + orphan_files: RegressionLimitSetting, #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")] external: BTreeMap, } @@ -588,6 +618,7 @@ impl MetricRegressionLimits { &self.verbosity, &self.import_cycles, &self.boundaries, + &self.orphan_files, ] .into_iter() .chain(self.external.values()) @@ -601,6 +632,7 @@ impl MetricRegressionLimits { verbosity, import_cycles, boundaries, + orphan_files, external, } = self; [ @@ -609,6 +641,7 @@ impl MetricRegressionLimits { (Metric::Verbosity.key().to_owned(), verbosity), (Metric::ImportCycles.key().to_owned(), import_cycles), ("boundaries".to_owned(), boundaries), + ("orphan_files".to_owned(), orphan_files), ] .into_iter() .chain(external) @@ -670,6 +703,13 @@ struct MetricBudgets { description = "The highest Boundaries ratio, from 0 to 1." )] boundaries: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars( + with = "f64", + range(min = 0, max = 1), + description = "The highest Orphan files ratio, from 0 to 1." + )] + orphan_files: Option, #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")] external: BTreeMap, } @@ -883,6 +923,8 @@ fn parse_value_with_overrides( append_boundaries_settings(raw.as_ref(), parsed_boundaries.as_ref(), &mut settings); let parsed_duplication = duplication_config(file.duplication)?; append_duplication_settings(raw.as_ref(), parsed_duplication, &mut settings); + let parsed_entry_points = entry_points(&file.entry_points)?; + append_entry_points_setting(raw.as_ref(), &effective.entry_points, &mut settings); let configuration = Configuration { effective, source_set_overrides, @@ -893,6 +935,7 @@ fn parse_value_with_overrides( plugin_limits, boundaries: parsed_boundaries, duplication: parsed_duplication, + entry_points: parsed_entry_points, }; Ok(ResolvedConfiguration { config_file, @@ -902,6 +945,29 @@ fn parse_value_with_overrides( }) } +fn entry_points(globs: &[String]) -> Result { + if globs.is_empty() { + return Ok(EntryPoints::default()); + } + let key = KeyPath::default().child(KeySegment::Key("entry_points".to_owned())); + Ok(EntryPoints { + globs: Some(glob_set(&key, globs)?), + }) +} + +fn append_entry_points_setting( + raw: Option<&Value>, + entries: &[String], + settings: &mut Vec, +) { + let source = if has_json_path(raw, &["entry_points"]) { + ConfigProvenance::File + } else { + ConfigProvenance::Default + }; + push_setting(settings, "entry_points", json!(entries), source); +} + fn duplication_config( file: DuplicationConfigFile, ) -> Result { @@ -1083,7 +1149,7 @@ fn append_regression_limit_settings( ) { let mut metric_keys: Vec = Metric::BUILT_IN_KEYS .iter() - .chain(["boundaries"].iter()) + .chain(["boundaries", "orphan_files"].iter()) .map(|key| (*key).to_owned()) .collect(); metric_keys.extend(limits.extra_metric_keys()); @@ -1282,6 +1348,7 @@ impl MetricBudgets { "verbosity" => self.verbosity = Some(budget), "import_cycles" => self.import_cycles = Some(budget), "boundaries" => self.boundaries = Some(budget), + "orphan_files" => self.orphan_files = Some(budget), other => { self.external.insert(other.to_owned(), budget); } @@ -1372,6 +1439,7 @@ fn regression_limits(file: RegressionLimitsFile) -> RegressionLimits { verbosity, import_cycles, boundaries, + orphan_files, production, test, generated, @@ -1384,6 +1452,7 @@ fn regression_limits(file: RegressionLimitsFile) -> RegressionLimits { verbosity, import_cycles, boundaries, + orphan_files, external, } .by_metric() @@ -1435,6 +1504,7 @@ fn budgets(file: SourceSetBudgets) -> Budgets { verbosity, import_cycles, boundaries, + orphan_files, external, } = metric_budgets; [ @@ -1443,6 +1513,7 @@ fn budgets(file: SourceSetBudgets) -> Budgets { (Metric::Verbosity.key().to_owned(), verbosity), (Metric::ImportCycles.key().to_owned(), import_cycles), ("boundaries".to_owned(), boundaries), + ("orphan_files".to_owned(), orphan_files), ] .into_iter() .filter_map(move |(metric, ratio)| Some((source_set, metric, ratio?))) diff --git a/crates/config/src/codeint_json/starter.rs b/crates/config/src/codeint_json/starter.rs index 1c309b5..2a31b27 100644 --- a/crates/config/src/codeint_json/starter.rs +++ b/crates/config/src/codeint_json/starter.rs @@ -70,6 +70,7 @@ fn starter_configuration_text(languages: &[DetectedLanguage]) -> String { plugin_limits: Default::default(), boundaries: None, duplication: Default::default(), + entry_points: Vec::new(), languages: (!languages.is_empty()).then(|| { languages .iter() diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index 0d11d92..c6183d1 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -27,10 +27,11 @@ pub use cli_schema::{ }; pub use codeint_json::{ Budget, Budgets, Configuration, ConfigurationInspection, DetectedLanguage, DuplicationConfig, - LanguageCoverage, Languages, MinSimilarity, PluginDeclaration, PluginKind, PluginLimits, - PluginSource, SchemaVersionStatus, Sha256Digest, SourceSetOverrides, StarterConfigurationError, - configuration_schema, inspect_configuration, is_broken_symlink, published_schema_address, - read_configuration, read_resolved_configuration, write_starter_configuration, + EntryPoints, LanguageCoverage, Languages, MinSimilarity, PluginDeclaration, PluginKind, + PluginLimits, PluginSource, SchemaVersionStatus, Sha256Digest, SourceSetOverrides, + StarterConfigurationError, configuration_schema, inspect_configuration, is_broken_symlink, + published_schema_address, read_configuration, read_resolved_configuration, + write_starter_configuration, }; pub use codeowners::{Codeowners, CodeownersError, OwnerFilter}; pub use config_error::{ConfigurationFileError, JsonType, KeyPath, KeySegment}; diff --git a/crates/config/src/regression_limits.rs b/crates/config/src/regression_limits.rs index 4ce8d4f..5a85b52 100644 --- a/crates/config/src/regression_limits.rs +++ b/crates/config/src/regression_limits.rs @@ -80,7 +80,10 @@ impl RegressionLimit { }; fn default_for_key(metric_key: &str) -> RegressionLimit { - if metric_key == Metric::ImportCycles.key() || metric_key == "boundaries" { + if metric_key == Metric::ImportCycles.key() + || metric_key == "boundaries" + || metric_key == "orphan_files" + { RegressionLimit::DEFAULT_FOR_IMPORT_CYCLES } else { RegressionLimit::DEFAULT @@ -156,7 +159,8 @@ impl RegressionLimits { pub(crate) fn extra_metric_keys(&self) -> Vec { let mut keys = BTreeSet::new(); for (_, key) in self.metric_keys() { - if !Metric::BUILT_IN_KEYS.contains(&key) && key != "boundaries" { + if !Metric::BUILT_IN_KEYS.contains(&key) && key != "boundaries" && key != "orphan_files" + { keys.insert(key.to_owned()); } } diff --git a/crates/config/tests/entry_points.rs b/crates/config/tests/entry_points.rs new file mode 100644 index 0000000..cbacf1b --- /dev/null +++ b/crates/config/tests/entry_points.rs @@ -0,0 +1,109 @@ +use std::path::{Path, PathBuf}; + +use codeint_config::{Configuration, NewFindingsRule, read_configuration}; +use codeint_model::{RepoPath, SourceSet}; + +struct TempFolder(PathBuf); + +impl TempFolder { + fn new(name: &str) -> TempFolder { + let path = + std::env::temp_dir().join(format!("codeint-config-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("create temp dir"); + TempFolder(path) + } + + fn path(&self) -> &Path { + &self.0 + } +} + +impl Drop for TempFolder { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[test] +fn parses_entry_points_orphan_files_budget_and_regression_limits() { + let dir = TempFolder::new("entry-points-valid"); + std::fs::write( + dir.path().join("codeint.json"), + r#"{ + "entry_points": ["src/pages/**/*.tsx", "scripts/cli.ts"], + "budgets": { + "production": { + "orphan_files": 0.0 + } + }, + "regression_limits": { + "orphan_files": { + "ratio_rise": 0.02 + }, + "production": { + "orphan_files": { + "new_findings": "any_new_finding" + } + } + } +}"#, + ) + .expect("write codeint.json"); + + let config = read_configuration(dir.path()).expect("valid configuration"); + config + .validate_metrics(&[]) + .expect("orphan_files is a known built-in metric"); + + let budget = config + .budgets + .budget_for_key(SourceSet::Production, "orphan_files") + .expect("production orphan_files budget"); + assert_eq!(budget.ratio(), 0.0); + + let prod_limit = config + .regression_limits + .limit_for_key(SourceSet::Production, "orphan_files"); + assert_eq!(prod_limit.ratio_rise.ratio(), 0.02); + assert_eq!(prod_limit.new_findings, NewFindingsRule::AnyNewFinding); + + let default_config = Configuration::default(); + let default_limit = default_config + .regression_limits + .limit_for_key(SourceSet::Production, "orphan_files"); + assert_eq!(default_limit.new_findings, NewFindingsRule::AnyNewFinding); + + assert!(!config.entry_points.is_empty()); + assert!( + config + .entry_points + .matches(&RepoPath::new("src/pages/blog/post.tsx").expect("path")) + ); + assert!( + config + .entry_points + .matches(&RepoPath::new("scripts/cli.ts").expect("path")) + ); + assert!( + !config + .entry_points + .matches(&RepoPath::new("src/lib/unused.ts").expect("path")) + ); +} + +#[test] +fn rejects_invalid_entry_points_glob() { + let dir = TempFolder::new("entry-points-invalid"); + std::fs::write( + dir.path().join("codeint.json"), + r#"{ "entry_points": ["src/[unclosed"] }"#, + ) + .expect("write codeint.json"); + + let error = read_configuration(dir.path()).expect_err("invalid glob must fail"); + assert!( + error.to_string().contains("entry_points[0]"), + "unexpected error: {error}" + ); +} diff --git a/crates/metrics/src/lib.rs b/crates/metrics/src/lib.rs index 482a2df..effdd71 100644 --- a/crates/metrics/src/lib.rs +++ b/crates/metrics/src/lib.rs @@ -7,9 +7,11 @@ mod finding_id; mod impact; mod import_cycles; mod line_share; +mod orphan_files; mod trace; mod verbosity; +pub use crate::orphan_files::{OrphanFileFinding, OrphanFileKind, OrphanFiles}; pub use boundaries::{ Boundaries, BoundaryEdgeCheck, BoundaryFinding, BoundaryFindingKind, BoundaryPolicy, }; diff --git a/crates/metrics/src/orphan_files.rs b/crates/metrics/src/orphan_files.rs new file mode 100644 index 0000000..70580c6 --- /dev/null +++ b/crates/metrics/src/orphan_files.rs @@ -0,0 +1,381 @@ +use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; + +use codeint_model::{CodeModel, ImportResolution, Package, RepoPath, SourceSet}; + +use crate::finding_id::{FindingId, FindingIds}; + +#[cfg(test)] +mod tests; + +const ORPHAN_FILES_METRIC_KEY: &str = "orphan_files"; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum OrphanFileKind { + Unreferenced, + TestOnly, +} + +impl OrphanFileKind { + pub fn key(self) -> &'static str { + match self { + OrphanFileKind::Unreferenced => "unreferenced", + OrphanFileKind::TestOnly => "test-only", + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OrphanFileFinding { + pub id: FindingId, + pub path: RepoPath, + pub kind: OrphanFileKind, + pub test_importers: Vec, + pub message: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OrphanFiles { + entry_points: Vec, + evaluated_files: usize, + findings: Vec, +} + +struct ImportGraphs { + forward: Vec>, + reverse_non_test: Vec>, + direct_test_importers: Vec>, +} + +struct PendingOrphan { + path: RepoPath, + kind: OrphanFileKind, + test_importers: Vec, + message: String, +} + +impl OrphanFiles { + pub fn measure(model: &CodeModel, entry_points: &[RepoPath]) -> Option { + OrphanFiles::measure_filtered(model, entry_points, |_| true) + } + + pub fn measure_filtered( + model: &CodeModel, + entry_points: &[RepoPath], + include_in_report: impl Fn(&RepoPath) -> bool, + ) -> Option { + let index_of: HashMap<&RepoPath, usize> = model + .files + .iter() + .enumerate() + .map(|(index, file)| (&file.path, index)) + .collect(); + let source_sets: Vec = model + .files + .iter() + .map(|file| file.model.source_set) + .collect(); + let roots = collect_roots(&index_of, &source_sets, entry_points); + if roots.is_empty() { + return None; + } + let graphs = build_import_graphs(model, &index_of, &source_sets); + let live = traverse_live(&roots, &graphs.forward, &source_sets); + let active_packages = active_packages_of(model, &live); + let reached_by_test = traverse_test_reachable( + &graphs.direct_test_importers, + &graphs.forward, + &live, + &source_sets, + ); + + let mut evaluated_files = 0usize; + let mut pending = Vec::new(); + for (index, file) in model.files.iter().enumerate() { + if file.model.source_set != SourceSet::Production { + continue; + } + if let Some(active) = &active_packages + && !active.contains(&model.workspace.package_of(&file.path)) + { + continue; + } + if !include_in_report(&file.path) { + continue; + } + evaluated_files += 1; + if live[index] { + continue; + } + let (kind, test_importers, message) = if reached_by_test[index] { + let importers = collect_reaching_test_importers( + index, + &graphs.direct_test_importers, + &graphs.reverse_non_test, + &live, + model, + ); + let message = format!( + "Production file {} is unreachable from Production entry points (only imported by tests)", + file.path + ); + (OrphanFileKind::TestOnly, importers, message) + } else { + let message = format!( + "Production file {} is unreachable from any entry point", + file.path + ); + (OrphanFileKind::Unreferenced, Vec::new(), message) + }; + pending.push(PendingOrphan { + path: file.path.clone(), + kind, + test_importers, + message, + }); + } + + if evaluated_files == 0 { + return None; + } + + let mut reported_roots: Vec = roots + .iter() + .map(|&index| model.files[index].path.clone()) + .filter(&include_in_report) + .collect(); + reported_roots.sort(); + reported_roots.dedup(); + + Some(OrphanFiles { + entry_points: reported_roots, + evaluated_files, + findings: assign_finding_ids(pending), + }) + } + + pub fn merge(measurements: impl IntoIterator) -> Option { + let mut iter = measurements.into_iter().peekable(); + iter.peek()?; + let mut entry_points = BTreeSet::new(); + let mut evaluated_files = 0usize; + let mut findings = Vec::new(); + for measurement in iter { + evaluated_files += measurement.evaluated_files; + entry_points.extend(measurement.entry_points); + findings.extend(measurement.findings); + } + if evaluated_files == 0 { + return None; + } + findings.sort_by(|left, right| left.path.cmp(&right.path)); + findings.dedup_by(|left, right| left.path == right.path); + Some(OrphanFiles { + entry_points: entry_points.into_iter().collect(), + evaluated_files, + findings, + }) + } + + pub fn ratio(&self) -> f64 { + if self.evaluated_files > 0 { + self.findings.len() as f64 / self.evaluated_files as f64 + } else { + 0.0 + } + } + + pub fn entry_points(&self) -> &[RepoPath] { + &self.entry_points + } + + pub fn evaluated_files(&self) -> usize { + self.evaluated_files + } + + pub fn findings(&self) -> &[OrphanFileFinding] { + &self.findings + } + + pub fn unreferenced_count(&self) -> usize { + self.findings + .iter() + .filter(|finding| finding.kind == OrphanFileKind::Unreferenced) + .count() + } + + pub fn test_only_count(&self) -> usize { + self.findings + .iter() + .filter(|finding| finding.kind == OrphanFileKind::TestOnly) + .count() + } +} + +fn collect_roots( + index_of: &HashMap<&RepoPath, usize>, + source_sets: &[SourceSet], + entry_points: &[RepoPath], +) -> BTreeSet { + let mut roots = BTreeSet::new(); + for entry in entry_points { + if let Some(&index) = index_of.get(entry) + && source_sets[index] == SourceSet::Production + { + roots.insert(index); + } + } + roots +} + +fn build_import_graphs( + model: &CodeModel, + index_of: &HashMap<&RepoPath, usize>, + source_sets: &[SourceSet], +) -> ImportGraphs { + let count = model.files.len(); + let mut forward = vec![Vec::new(); count]; + let mut reverse_non_test = vec![Vec::new(); count]; + let mut direct_test_importers = vec![BTreeSet::new(); count]; + for runtime_import in &model.runtime_imports { + let ImportResolution::Resolved(target) = &runtime_import.resolution else { + continue; + }; + let (Some(&from), Some(&to)) = + (index_of.get(&runtime_import.importer), index_of.get(target)) + else { + continue; + }; + if source_sets[from] == SourceSet::Test { + if source_sets[to] != SourceSet::Test { + direct_test_importers[to].insert(from); + } + } else { + forward[from].push(to); + if source_sets[to] != SourceSet::Test { + reverse_non_test[to].push(from); + } + } + } + ImportGraphs { + forward, + reverse_non_test, + direct_test_importers, + } +} + +fn traverse_live( + roots: &BTreeSet, + forward: &[Vec], + source_sets: &[SourceSet], +) -> Vec { + let mut visited = vec![false; forward.len()]; + let mut queue = VecDeque::new(); + for &root in roots { + visited[root] = true; + queue.push_back(root); + } + while let Some(node) = queue.pop_front() { + for &target in &forward[node] { + if !visited[target] && source_sets[target] != SourceSet::Test { + visited[target] = true; + queue.push_back(target); + } + } + } + visited +} + +fn active_packages_of<'model>( + model: &'model CodeModel, + live: &[bool], +) -> Option>> { + if !model.workspace.has_members() { + return None; + } + let active = live + .iter() + .enumerate() + .filter(|&(_, &is_live)| is_live) + .map(|(index, _)| model.workspace.package_of(&model.files[index].path)) + .collect(); + Some(active) +} + +fn traverse_test_reachable( + direct_test_importers: &[BTreeSet], + forward: &[Vec], + live: &[bool], + source_sets: &[SourceSet], +) -> Vec { + let mut reached = vec![false; forward.len()]; + let mut queue = VecDeque::new(); + for (node, importers) in direct_test_importers.iter().enumerate() { + if !importers.is_empty() && !live[node] && source_sets[node] != SourceSet::Test { + reached[node] = true; + queue.push_back(node); + } + } + while let Some(node) = queue.pop_front() { + for &target in &forward[node] { + if !reached[target] && !live[target] && source_sets[target] != SourceSet::Test { + reached[target] = true; + queue.push_back(target); + } + } + } + reached +} + +fn collect_reaching_test_importers( + start: usize, + direct_test_importers: &[BTreeSet], + reverse_non_test: &[Vec], + live: &[bool], + model: &CodeModel, +) -> Vec { + if !direct_test_importers[start].is_empty() { + let mut paths: Vec = direct_test_importers[start] + .iter() + .map(|&index| model.files[index].path.clone()) + .collect(); + paths.sort(); + return paths; + } + let mut visited = HashSet::new(); + let mut queue = VecDeque::new(); + let mut test_indices = BTreeSet::new(); + visited.insert(start); + queue.push_back(start); + while let Some(node) = queue.pop_front() { + test_indices.extend(direct_test_importers[node].iter().copied()); + for &importer in &reverse_non_test[node] { + if !live[importer] && visited.insert(importer) { + queue.push_back(importer); + } + } + } + let mut paths: Vec = test_indices + .into_iter() + .map(|index| model.files[index].path.clone()) + .collect(); + paths.sort(); + paths +} + +fn assign_finding_ids(mut pending: Vec) -> Vec { + pending.sort_by(|left, right| left.path.cmp(&right.path)); + let mut ids = FindingIds::for_key(ORPHAN_FILES_METRIC_KEY); + pending + .into_iter() + .map(|item| { + let id = ids.next_in_source_order([&item.path], []); + OrphanFileFinding { + id, + path: item.path, + kind: item.kind, + test_importers: item.test_importers, + message: item.message, + } + }) + .collect() +} diff --git a/crates/metrics/src/orphan_files/tests.rs b/crates/metrics/src/orphan_files/tests.rs new file mode 100644 index 0000000..dc9ed1a --- /dev/null +++ b/crates/metrics/src/orphan_files/tests.rs @@ -0,0 +1,319 @@ +use codeint_model::{ + CodeModel, FileModel, ImportResolution, RepoPath, RuntimeImport, SourceFile, SourceSet, + Workspace, +}; + +use super::{OrphanFileKind, OrphanFiles}; + +fn repo_path(text: &str) -> RepoPath { + RepoPath::new(text).expect("valid repo path") +} + +fn source_file(name: &str, source_set: SourceSet) -> SourceFile { + SourceFile { + path: repo_path(name), + model: FileModel { + source_set, + source_lines: 5, + functions: Vec::new(), + tokens: Vec::new(), + flagged_lines: Vec::new(), + runtime_imports: Vec::new(), + }, + } +} + +fn build_model( + files: &[(&str, SourceSet)], + edges: &[(&str, &str)], + workspace_members: &[&str], +) -> CodeModel { + CodeModel { + files: files + .iter() + .map(|(name, set)| source_file(name, *set)) + .collect(), + runtime_imports: edges + .iter() + .map(|(from, to)| RuntimeImport { + importer: repo_path(from), + specifier: format!("./{to}"), + resolution: ImportResolution::Resolved(repo_path(to)), + }) + .collect(), + workspace: Workspace::new(workspace_members.iter().copied().map(repo_path)), + ..CodeModel::default() + } +} + +fn production_model(files: &[&str], edges: &[(&str, &str)]) -> CodeModel { + let entries: Vec<(&str, SourceSet)> = files + .iter() + .map(|name| (*name, SourceSet::Production)) + .collect(); + build_model(&entries, edges, &[]) +} + +fn orphan_paths(measured: &OrphanFiles) -> Vec<&str> { + measured + .findings() + .iter() + .map(|finding| finding.path.as_str()) + .collect() +} + +#[test] +fn detects_live_unreferenced_and_test_only_production_files() { + let model = build_model( + &[ + ("src/index.ts", SourceSet::Production), + ("src/live.ts", SourceSet::Production), + ("src/deep.ts", SourceSet::Production), + ("src/dead.ts", SourceSet::Production), + ("src/test_only.ts", SourceSet::Production), + ("src/test_only_dep.ts", SourceSet::Production), + ("src/test_only.test.ts", SourceSet::Test), + ("src/live.test.ts", SourceSet::Test), + ], + &[ + ("src/index.ts", "src/live.ts"), + ("src/live.ts", "src/deep.ts"), + ("src/test_only.test.ts", "src/test_only.ts"), + ("src/test_only.ts", "src/test_only_dep.ts"), + ("src/live.test.ts", "src/live.ts"), + ], + &[], + ); + + let measured = OrphanFiles::measure(&model, &[repo_path("src/index.ts")]) + .expect("entry point activates orphan-file detection"); + + assert_eq!(measured.evaluated_files(), 6); + assert_eq!(measured.entry_points(), &[repo_path("src/index.ts")]); + assert_eq!(measured.unreferenced_count(), 1); + assert_eq!(measured.test_only_count(), 2); + assert_eq!(measured.findings().len(), 3); + assert!((measured.ratio() - 0.5).abs() < 1e-9); + + let summary: Vec<(&str, OrphanFileKind, Vec<&str>)> = measured + .findings() + .iter() + .map(|f| { + ( + f.path.as_str(), + f.kind, + f.test_importers.iter().map(RepoPath::as_str).collect(), + ) + }) + .collect(); + assert_eq!( + summary, + vec![ + ("src/dead.ts", OrphanFileKind::Unreferenced, vec![]), + ( + "src/test_only.ts", + OrphanFileKind::TestOnly, + vec!["src/test_only.test.ts"], + ), + ( + "src/test_only_dep.ts", + OrphanFileKind::TestOnly, + vec!["src/test_only.test.ts"], + ), + ] + ); + assert!( + measured.findings()[1] + .message + .contains("only imported by tests") + ); +} + +#[test] +fn reachable_import_cycle_is_live_while_unreachable_import_cycle_is_orphan() { + let model = production_model( + &[ + "src/main.ts", + "src/live_a.ts", + "src/live_b.ts", + "src/dead_a.ts", + "src/dead_b.ts", + ], + &[ + ("src/main.ts", "src/live_a.ts"), + ("src/live_a.ts", "src/live_b.ts"), + ("src/live_b.ts", "src/live_a.ts"), + ("src/dead_a.ts", "src/dead_b.ts"), + ("src/dead_b.ts", "src/dead_a.ts"), + ], + ); + + let measured = OrphanFiles::measure(&model, &[repo_path("src/main.ts")]) + .expect("entry point activates detection"); + + assert_eq!( + orphan_paths(&measured), + vec!["src/dead_a.ts", "src/dead_b.ts"] + ); + assert_eq!(measured.unreferenced_count(), 2); + assert_eq!(measured.test_only_count(), 0); +} + +#[test] +fn stays_silently_inactive_when_zero_entry_points_exist() { + let model = build_model( + &[ + ("src/a.ts", SourceSet::Production), + ("src/b.ts", SourceSet::Production), + ("src/a.test.ts", SourceSet::Test), + ], + &[("src/a.test.ts", "src/a.ts")], + &[], + ); + + assert!(OrphanFiles::measure(&model, &[]).is_none()); + assert!(OrphanFiles::measure(&model, &[repo_path("src/missing.ts")]).is_none()); + assert!(OrphanFiles::measure(&model, &[repo_path("src/a.test.ts")]).is_none()); +} + +#[test] +fn excludes_generated_and_vendored_source_sets() { + let model = build_model( + &[ + ("src/index.ts", SourceSet::Production), + ("src/orphan.ts", SourceSet::Production), + ("src/schema.g.ts", SourceSet::Generated), + ("vendor/lib.ts", SourceSet::Vendored), + ], + &[], + &[], + ); + + let measured = OrphanFiles::measure(&model, &[repo_path("src/index.ts")]) + .expect("entry point activates detection"); + + assert_eq!(measured.evaluated_files(), 2); + assert_eq!(orphan_paths(&measured), vec!["src/orphan.ts"]); +} + +#[test] +fn generated_and_vendored_entry_points_do_not_activate_orphan_detection() { + let single = build_model( + &[ + ("app/main.ts", SourceSet::Production), + ("app/util.ts", SourceSet::Production), + ("app/types.g.ts", SourceSet::Generated), + ("vendor/pkg.ts", SourceSet::Vendored), + ], + &[], + &[], + ); + for candidates in [ + vec![repo_path("app/types.g.ts")], + vec![repo_path("vendor/pkg.ts")], + vec![repo_path("app/types.g.ts"), repo_path("vendor/pkg.ts")], + ] { + assert!(OrphanFiles::measure(&single, &candidates).is_none()); + } + + let workspace = build_model( + &[ + ("mods/web/main.ts", SourceSet::Production), + ("mods/web/unused.ts", SourceSet::Production), + ("mods/gen/service.ts", SourceSet::Production), + ("mods/gen/router.g.ts", SourceSet::Generated), + ("mods/gen/vendor/entry.ts", SourceSet::Vendored), + ], + &[], + &["mods/web", "mods/gen"], + ); + let measured = OrphanFiles::measure( + &workspace, + &[ + repo_path("mods/web/main.ts"), + repo_path("mods/gen/router.g.ts"), + repo_path("mods/gen/vendor/entry.ts"), + ], + ) + .expect("production root activates detection"); + + assert_eq!( + ( + measured.entry_points(), + measured.evaluated_files(), + orphan_paths(&measured), + ), + ( + &[repo_path("mods/web/main.ts")][..], + 2, + vec!["mods/web/unused.ts"], + ) + ); +} + +#[test] +fn traverses_cross_package_imports_and_skips_unrooted_isolated_packages() { + let model = build_model( + &[ + ("packages/app/src/index.ts", SourceSet::Production), + ("packages/lib/src/used.ts", SourceSet::Production), + ("packages/lib/src/unused.ts", SourceSet::Production), + ("packages/site/pages/home.ts", SourceSet::Production), + ("packages/site/pages/about.ts", SourceSet::Production), + ], + &[("packages/app/src/index.ts", "packages/lib/src/used.ts")], + &["packages/app", "packages/lib", "packages/site"], + ); + + let measured = OrphanFiles::measure(&model, &[repo_path("packages/app/src/index.ts")]) + .expect("entry point in app activates detection"); + + assert_eq!(measured.evaluated_files(), 3); + assert_eq!(orphan_paths(&measured), vec!["packages/lib/src/unused.ts"]); + + let lib_only = + OrphanFiles::measure_filtered(&model, &[repo_path("packages/app/src/index.ts")], |path| { + path.as_str().starts_with("packages/lib/") + }) + .expect("lib package stays active via cross-package import"); + assert_eq!(lib_only.evaluated_files(), 2); + assert_eq!(lib_only.findings().len(), 1); + assert_eq!( + lib_only.findings()[0].path.as_str(), + "packages/lib/src/unused.ts" + ); +} + +#[test] +fn assigns_stable_finding_ids_and_merges_across_languages() { + let ts_model = build_model( + &[ + ("web/index.ts", SourceSet::Production), + ("web/dead.ts", SourceSet::Production), + ], + &[], + &[], + ); + let py_model = build_model( + &[ + ("api/main.py", SourceSet::Production), + ("api/dead.py", SourceSet::Production), + ], + &[], + &[], + ); + + let first_ts = OrphanFiles::measure(&ts_model, &[repo_path("web/index.ts")]).expect("ts"); + let second_ts = OrphanFiles::measure(&ts_model, &[repo_path("web/index.ts")]).expect("ts"); + assert_eq!(first_ts.findings()[0].id, second_ts.findings()[0].id); + + let py = OrphanFiles::measure(&py_model, &[repo_path("api/main.py")]).expect("py"); + assert_ne!(first_ts.findings()[0].id, py.findings()[0].id); + + let merged = OrphanFiles::merge([first_ts, py]).expect("merged"); + assert_eq!(merged.evaluated_files(), 4); + assert_eq!(merged.findings().len(), 2); + assert_eq!(merged.findings()[0].path.as_str(), "api/dead.py"); + assert_eq!(merged.findings()[1].path.as_str(), "web/dead.ts"); + assert!((merged.ratio() - 0.5).abs() < 1e-9); +} diff --git a/crates/report/src/diff.rs b/crates/report/src/diff.rs index fd3c953..d1a9801 100644 --- a/crates/report/src/diff.rs +++ b/crates/report/src/diff.rs @@ -14,7 +14,8 @@ use crate::sarif::{ListedExternalMetric, ListedFindings, SarifLog}; use crate::{ BoundaryFindingRow, BudgetFailure, CloneFamilyFinding, CloneGroupFinding, Decimal, ErodedFunctionFinding, ExternalMetricFinding, Findings, FlaggedLineRow, ImportCycleFinding, - PerSourceSet, ReportError, clustered_clone_group_ids, unlisted_clone_family_group_ids, + OrphanFileRow, PerSourceSet, ReportError, clustered_clone_group_ids, + unlisted_clone_family_group_ids, }; mod markdown; @@ -96,6 +97,8 @@ struct SourceSetChanges { import_cycles: MetricChanges, #[serde(default, skip_serializing_if = "Option::is_none")] boundaries: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + orphan_files: Option>, #[serde(default, flatten)] external_metrics: BTreeMap, } @@ -264,6 +267,10 @@ impl DiffReport { .boundaries .as_ref() .map_or(&[], |boundaries| boundaries.new.listed.as_slice()), + orphan_files: changes + .orphan_files + .as_ref() + .map_or(&[], |orphans| orphans.new.listed.as_slice()), external_metrics: changes .external_metrics .iter() @@ -499,6 +506,12 @@ fn over_budget(source_sets: &SourceSetChangesSections, budgets: &Budgets) -> Vec .iter() .map(move |boundaries| (source_set, "boundaries", boundaries.head_ratio.0)), ) + .chain( + changes + .orphan_files + .iter() + .map(move |orphans| (source_set, "orphan_files", orphans.head_ratio.0)), + ) .chain( changes.external_metrics.iter().map(move |(key, metric)| { (source_set, key.as_str(), metric.changes.head_ratio.0) @@ -537,6 +550,9 @@ impl SourceSetChanges { if let Some(boundaries) = &self.boundaries { found.extend(boundaries.regressions(source_set, "boundaries", limits)); } + if let Some(orphan_files) = &self.orphan_files { + found.extend(orphan_files.regressions(source_set, "orphan_files", limits)); + } for (key, external) in &self.external_metrics { found.extend(external.changes.regressions(source_set, key, limits)); } @@ -662,6 +678,7 @@ fn numerator_key(metric_key: &str) -> &'static str { "verbosity" => "verbose_lines", "import_cycles" => "modules_in_import_cycles", "boundaries" => "boundary_findings", + "orphan_files" => "orphan_files", _ => "numerator", } } @@ -737,6 +754,15 @@ fn source_set_changes( ownership, )), }; + let orphan_files = match (base.orphan_files, head.orphan_files) { + (None, None) => None, + (base_orphans, head_orphans) => Some(classify( + base_orphans.unwrap_or_default(), + head_orphans.unwrap_or_default(), + shown, + ownership, + )), + }; let duplication_groups = classify(base.duplication, head.duplication, shown, ownership); let base_families = ownership.apply(base.clone_families); let head_families = ownership.apply(head.clone_families); @@ -769,6 +795,7 @@ fn source_set_changes( verbosity: classify(base.verbosity, head.verbosity, shown, ownership), import_cycles: classify(base.import_cycles, head.import_cycles, shown, ownership), boundaries, + orphan_files, external_metrics, } } @@ -814,3 +841,9 @@ impl Identified for BoundaryFindingRow { &self.id } } + +impl Identified for OrphanFileRow { + fn id(&self) -> &str { + &self.id + } +} diff --git a/crates/report/src/diff/markdown.rs b/crates/report/src/diff/markdown.rs index fe289fa..23415ff 100644 --- a/crates/report/src/diff/markdown.rs +++ b/crates/report/src/diff/markdown.rs @@ -3,9 +3,9 @@ use crate::Findings; use crate::markdown::{ BOUNDARY_FINDING_COLUMNS, CLONE_FAMILY, CLONE_GROUP, ERODED_FUNCTION, ERODED_FUNCTION_COLUMNS, EXTERNAL_FINDING_COLUMNS, FINDING, FLAGGED_LINE, FLAGGED_LINE_COLUMNS, IMPORT_CYCLE, Noun, - boundary_finding_row, clone_family_item, clone_group_item, code, eroded_function_row, - external_finding_row, findings_table, flagged_line_row, import_cycle_item, list, push_findings, - sentence_item, table, + ORPHAN_FILE, ORPHAN_FILE_COLUMNS, boundary_finding_row, clone_family_item, clone_group_item, + code, eroded_function_row, external_finding_row, findings_table, flagged_line_row, + import_cycle_item, list, orphan_file_row, push_findings, sentence_item, table, }; const TITLE: &str = "# codeint diff"; @@ -76,6 +76,9 @@ fn metric_rows(source_set: &str, changes: &SourceSetChanges) -> Vec> if let Some(boundaries) = &changes.boundaries { rows.push(metric_row(source_set, "Boundaries", boundaries)); } + if let Some(orphan_files) = &changes.orphan_files { + rows.push(metric_row(source_set, "Orphan files", orphan_files)); + } for external in changes.external_metrics.values() { rows.push(metric_row(source_set, &external.name, &external.changes)); } @@ -149,6 +152,15 @@ fn findings_blocks(changes: &SourceSetChanges) -> Vec { findings_table(&BOUNDARY_FINDING_COLUMNS, listed, boundary_finding_row) }); } + if let Some(orphan_files) = &changes.orphan_files { + push_changes( + &mut blocks, + "Orphan files", + orphan_files, + &ORPHAN_FILE, + |listed| findings_table(&ORPHAN_FILE_COLUMNS, listed, orphan_file_row), + ); + } for external in changes.external_metrics.values() { push_changes( &mut blocks, diff --git a/crates/report/src/lib.rs b/crates/report/src/lib.rs index e21e861..2f156c2 100644 --- a/crates/report/src/lib.rs +++ b/crates/report/src/lib.rs @@ -10,7 +10,8 @@ use codeint_config::{ use codeint_metrics::{ Boundaries, BoundaryEdgeCheck, BoundaryFinding, BoundaryPolicy, CloneFamily, CloneGroup, Duplication, ErodedFunction, Erosion, FlaggedLineFinding, Fragment, ImportCycle, ImportCycles, - MinimumCloneTokens, MinimumDistinctTokens, NearCloneConfig, UnresolvedImport, Verbosity, + MinimumCloneTokens, MinimumDistinctTokens, NearCloneConfig, OrphanFileFinding, OrphanFiles, + UnresolvedImport, Verbosity, }; use codeint_model::{ CodeModel, ExternalFinding, Metric, MetricPlugin, MetricPluginError, Package, ReferenceRange, @@ -211,12 +212,38 @@ struct SourceSetSection { import_cycles: ImportCyclesSection, #[serde(default, skip_serializing_if = "Option::is_none")] boundaries: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + orphan_files: Option, #[serde(default, flatten)] external_metrics: BTreeMap, #[serde(default, skip_serializing_if = "Vec::is_empty")] packages: Vec, } +#[derive(Debug, Serialize, Deserialize)] +struct OrphanFilesSection { + ratio: Decimal, + orphan_files: usize, + evaluated_files: usize, + entry_points: usize, + unreferenced: usize, + test_only: usize, + #[serde(flatten)] + findings: Findings, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct OrphanFileRow { + id: String, + path: String, + kind: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + test_importers: Vec, + message: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + owners: Vec, +} + #[derive(Debug, Serialize, Deserialize)] struct BoundariesSection { ratio: Decimal, @@ -682,6 +709,7 @@ impl_single_path_owner!(FlaggedLineRow, path); impl_single_path_owner!(UnresolvedImportRow, importer); impl_single_path_owner!(ExternalMetricFinding, path); impl_single_path_owner!(BoundaryFindingRow, importer); +impl_single_path_owner!(OrphanFileRow, path); impl OwnedFinding for CloneGroupFinding { fn assign_owners(&mut self, codeowners: &Codeowners) { @@ -719,6 +747,10 @@ impl FindingKind for BoundaryFindingRow { const LIST_KEY: &'static str = "findings"; } +impl FindingKind for OrphanFileRow { + const LIST_KEY: &'static str = "findings"; +} + struct ConfigBoundaryPolicy<'config>(&'config BoundariesConfig); impl BoundaryPolicy for ConfigBoundaryPolicy<'_> { @@ -809,12 +841,47 @@ impl ExternalMetricFinding { } } +impl OrphanFilesSection { + fn new(orphan_files: &OrphanFiles, view: FindingsView<'_>) -> OrphanFilesSection { + let all_findings = orphan_files.findings(); + let findings = view.map(all_findings); + OrphanFilesSection { + ratio: Decimal::rounded(orphan_files.ratio()), + orphan_files: all_findings.len(), + evaluated_files: orphan_files.evaluated_files(), + entry_points: orphan_files.entry_points().len(), + unreferenced: orphan_files.unreferenced_count(), + test_only: orphan_files.test_only_count(), + findings, + } + } +} + +impl From<&OrphanFileFinding> for OrphanFileRow { + fn from(finding: &OrphanFileFinding) -> OrphanFileRow { + let test_importers = finding + .test_importers + .iter() + .map(RepoPath::to_string) + .collect(); + OrphanFileRow { + id: finding.id.to_string(), + path: finding.path.to_string(), + kind: finding.kind.key().to_owned(), + test_importers, + message: finding.message.clone(), + owners: Vec::new(), + } + } +} + #[derive(Clone, Copy)] struct SectionOptions<'a> { findings: FindingsShown, metric_plugins: &'a [&'a dyn MetricPlugin], boundaries: Option<&'a BoundariesConfig>, duplication: DuplicationConfig, + orphan_files: Option<&'a OrphanFiles>, ownership: OwnershipOptions<'a>, } @@ -831,6 +898,9 @@ impl SourceSetSections { boundaries: options .boundaries .filter(|config| config.applies_to_source_set(source_set)), + orphan_files: options + .orphan_files + .filter(|_| source_set == SourceSet::Production), ..options }; *sections.slot(source_set) = @@ -869,6 +939,12 @@ impl SourceSetSections { .iter() .map(move |boundaries| (source_set, "boundaries", boundaries.ratio.0)), ) + .chain( + section + .orphan_files + .iter() + .map(move |orphans| (source_set, "orphan_files", orphans.ratio.0)), + ) .chain( section .external_metrics @@ -895,6 +971,9 @@ impl SourceSetSection { .boundaries .as_ref() .map(|evaluated| BoundariesSection::new(evaluated, view)); + let orphan_files = options + .orphan_files + .map(|measured| OrphanFilesSection::new(measured, view)); let mut external_metrics = BTreeMap::new(); for plugin in options.metric_plugins { let result = plugin.measure(model)?; @@ -961,6 +1040,7 @@ impl SourceSetSection { unresolved_imports: UnresolvedImportsSection::new(&measured.import_cycles, view), }, boundaries, + orphan_files, external_metrics, packages: package_sections(model, &measured), }) @@ -1241,6 +1321,8 @@ pub struct ReportOptions<'a> { pub metric_plugins: &'a [&'a dyn MetricPlugin], pub boundaries: Option<&'a BoundariesConfig>, pub duplication: DuplicationConfig, + pub orphan_files: Option<&'a OrphanFiles>, + pub orphan_files_by_language: Option<&'a BTreeMap>, pub ownership: OwnershipOptions<'a>, } @@ -1316,6 +1398,8 @@ impl Report { metric_plugins, boundaries, duplication: DuplicationConfig::default(), + orphan_files: None, + orphan_files_by_language: None, ownership: OwnershipOptions::default(), }, ) @@ -1339,6 +1423,8 @@ impl Report { metric_plugins, boundaries, duplication, + orphan_files: None, + orphan_files_by_language: None, ownership: OwnershipOptions::default(), }, ) @@ -1362,6 +1448,8 @@ impl Report { metric_plugins, boundaries, duplication: DuplicationConfig::default(), + orphan_files: None, + orphan_files_by_language: None, ownership, }, ) @@ -1377,6 +1465,7 @@ impl Report { metric_plugins: options.metric_plugins, boundaries: options.boundaries, duplication: options.duplication, + orphan_files: options.orphan_files, ownership: options.ownership, }; let (measured, unmeasured): (Vec, Vec) = languages @@ -1394,12 +1483,18 @@ impl Report { _ => { let mut per_language = BTreeMap::new(); for language in &measured { + let language_orphans = options + .orphan_files_by_language + .and_then(|map| map.get(&language.plugin)); per_language.insert( language.plugin.clone(), MeasuredSection::new( language.model.clone(), &ReferenceRangeScope::OneLanguage(language.reference_ranges.clone()), - section_options, + SectionOptions { + orphan_files: language_orphans, + ..section_options + }, )?, ); } diff --git a/crates/report/src/markdown.rs b/crates/report/src/markdown.rs index e9e09ed..53948ae 100644 --- a/crates/report/src/markdown.rs +++ b/crates/report/src/markdown.rs @@ -2,8 +2,8 @@ use crate::ownership::OwnedFinding; use crate::{ BoundaryFindingRow, CloneFamilyFinding, CloneGroupFinding, CloneLocation, DuplicationSection, ErodedFunctionFinding, ErosionSection, ExternalMetricFinding, Findings, FlaggedLineRow, - ImportCycleFinding, ImportCyclesSection, MeasuredSection, PackageSection, ReferenceRangeEntry, - Report, SourceSetSection, UnresolvedImportRow, VerbositySection, + ImportCycleFinding, ImportCyclesSection, MeasuredSection, OrphanFileRow, PackageSection, + ReferenceRangeEntry, Report, SourceSetSection, UnresolvedImportRow, VerbositySection, }; #[cfg(test)] @@ -43,6 +43,7 @@ pub(crate) const BOUNDARY_FINDING_COLUMNS: [&str; 6] = [ "Rule", "Reason", ]; +pub(crate) const ORPHAN_FILE_COLUMNS: [&str; 3] = ["File", "Kind", "Details"]; const UNRESOLVED_IMPORT_COLUMNS: [&str; 3] = ["Importer", "Specifier", "Reason"]; pub(crate) struct Noun { @@ -102,6 +103,10 @@ pub(crate) const FINDING: Noun = Noun { one: "Finding", many: "Findings", }; +pub(crate) const ORPHAN_FILE: Noun = Noun { + one: "orphan file", + many: "orphan files", +}; const UNRESOLVED_IMPORT: Noun = Noun { one: "unresolved import", many: "unresolved imports", @@ -329,6 +334,21 @@ fn metric_rows(source_set: &str, section: &SourceSetSection) -> Vec> "not applicable".to_string(), ]); } + if let Some(orphan_files) = §ion.orphan_files { + rows.push(vec![ + source_set.to_string(), + "Orphan files".to_string(), + orphan_files.ratio.0.to_string(), + format!( + "{} of {} evaluated files unreachable ({} unreferenced, {} test-only)", + orphan_files.orphan_files, + orphan_files.evaluated_files, + orphan_files.unreferenced, + orphan_files.test_only + ), + "not applicable".to_string(), + ]); + } for external in section.external_metrics.values() { rows.push(row( &external.name, @@ -418,6 +438,15 @@ fn findings_blocks(section: &SourceSetSection) -> Vec { |listed| findings_table(&BOUNDARY_FINDING_COLUMNS, listed, boundary_finding_row), ); } + if let Some(orphan_files) = §ion.orphan_files { + push_findings( + &mut blocks, + "Orphan files", + &orphan_files.findings, + &ORPHAN_FILE, + |listed| findings_table(&ORPHAN_FILE_COLUMNS, listed, orphan_file_row), + ); + } for external in section.external_metrics.values() { push_findings( &mut blocks, @@ -598,6 +627,21 @@ pub(crate) fn boundary_finding_row(row: &BoundaryFindingRow) -> Vec { ] } +pub(crate) fn orphan_file_row(row: &OrphanFileRow) -> Vec { + let details = if row.test_importers.is_empty() { + prose(&row.message) + } else { + let importers: Vec = row + .test_importers + .iter() + .map(String::as_str) + .map(code) + .collect(); + format!("only imported by tests: {}", importers.join(", ")) + }; + vec![code(&row.path), prose(&row.kind), details] +} + fn files_not_measured(report: &Report) -> Vec { let skipped = report .skipped diff --git a/crates/report/src/measurement.rs b/crates/report/src/measurement.rs index 7d95edc..a20ae2e 100644 --- a/crates/report/src/measurement.rs +++ b/crates/report/src/measurement.rs @@ -1,12 +1,13 @@ use std::collections::BTreeMap; use codeint_config::{Boundaries as BoundariesConfig, DuplicationConfig}; +use codeint_metrics::OrphanFiles; use codeint_model::{CodeModel, MetricPlugin, MetricPluginError, SourceSet}; use serde::{Deserialize, Serialize}; use crate::{ BoundaryFindingRow, CloneFamilyFinding, CloneGroupFinding, ErodedFunctionFinding, - ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, Measured, + ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, Measured, OrphanFileRow, }; #[derive(Debug, Serialize, Deserialize)] @@ -27,6 +28,8 @@ pub(crate) struct SourceSetMeasurement { pub(crate) import_cycles: MetricMeasurement, #[serde(default, skip_serializing_if = "Option::is_none")] pub(crate) boundaries: Option>, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub(crate) orphan_files: Option>, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub(crate) external_metrics: BTreeMap, } @@ -85,6 +88,16 @@ impl CommitMeasurement { metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, duplication: DuplicationConfig, + ) -> Result { + CommitMeasurement::of_with_options(model, metric_plugins, boundaries, duplication, None) + } + + pub fn of_with_options( + model: CodeModel, + metric_plugins: &[&dyn MetricPlugin], + boundaries: Option<&BoundariesConfig>, + duplication: DuplicationConfig, + orphan_files: Option<&OrphanFiles>, ) -> Result { let source_sets = model.into_source_sets(); Ok(CommitMeasurement { @@ -93,24 +106,28 @@ impl CommitMeasurement { metric_plugins, boundaries.filter(|config| config.applies_to_source_set(SourceSet::Production)), duplication, + orphan_files, )?, test: SourceSetMeasurement::of( source_sets.get(SourceSet::Test), metric_plugins, boundaries.filter(|config| config.applies_to_source_set(SourceSet::Test)), duplication, + None, )?, generated: SourceSetMeasurement::of( source_sets.get(SourceSet::Generated), metric_plugins, boundaries.filter(|config| config.applies_to_source_set(SourceSet::Generated)), duplication, + None, )?, vendored: SourceSetMeasurement::of( source_sets.get(SourceSet::Vendored), metric_plugins, boundaries.filter(|config| config.applies_to_source_set(SourceSet::Vendored)), duplication, + None, )?, }) } @@ -131,20 +148,15 @@ impl SourceSetMeasurement { metric_plugins: &[&dyn MetricPlugin], boundaries: Option<&BoundariesConfig>, duplication_config: DuplicationConfig, + orphan_files: Option<&OrphanFiles>, ) -> Result { let measured = Measured::new(model, boundaries, duplication_config); let boundaries = measured .boundaries .as_ref() - .map(|evaluated| MetricMeasurement { - ratio: evaluated.ratio(), - numerator: evaluated.findings().len() as f64, - findings_worst_first: evaluated - .findings() - .iter() - .map(BoundaryFindingRow::from) - .collect(), - }); + .map(|evaluated| finding_measurement(evaluated.ratio(), evaluated.findings())); + let orphan_files = orphan_files + .map(|evaluated| finding_measurement(evaluated.ratio(), evaluated.findings())); let mut external_metrics = BTreeMap::new(); for plugin in metric_plugins { let result = plugin.measure(model)?; @@ -173,11 +185,23 @@ impl SourceSetMeasurement { verbosity: verbosity(&measured), import_cycles: import_cycles(&measured), boundaries, + orphan_files, external_metrics, }) } } +fn finding_measurement<'a, T: 'a, R: From<&'a T>>( + ratio: f64, + findings: &'a [T], +) -> MetricMeasurement { + MetricMeasurement { + ratio, + numerator: findings.len() as f64, + findings_worst_first: findings.iter().map(R::from).collect(), + } +} + fn erosion(measured: &Measured) -> MetricMeasurement { MetricMeasurement { ratio: measured.erosion.ratio(), diff --git a/crates/report/src/sarif.rs b/crates/report/src/sarif.rs index 875e89f..48fdb53 100644 --- a/crates/report/src/sarif.rs +++ b/crates/report/src/sarif.rs @@ -4,11 +4,11 @@ use serde::Serialize; use codeint_model::{Metric, SourceSet}; -use crate::schema::{BUILT_IN_METRICS, built_in_metric_descriptor}; +use crate::schema::{BUILT_IN_METRICS, ORPHAN_FILES_DESCRIPTOR, built_in_metric_descriptor}; use crate::{ BoundaryFindingRow, CloneFamilyFinding, CloneGroupFinding, CloneLocation, - ErodedFunctionFinding, ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, Report, - SourceSetSection, + ErodedFunctionFinding, ExternalMetricFinding, FlaggedLineRow, ImportCycleFinding, + OrphanFileRow, Report, SourceSetSection, }; #[cfg(test)] @@ -146,6 +146,7 @@ pub(crate) struct ListedFindings<'findings> { pub(crate) flagged_lines: &'findings [FlaggedLineRow], pub(crate) import_cycles: &'findings [ImportCycleFinding], pub(crate) boundaries: &'findings [BoundaryFindingRow], + pub(crate) orphan_files: &'findings [OrphanFileRow], pub(crate) external_metrics: Vec>, } @@ -167,6 +168,9 @@ impl SarifLog { let has_boundaries = collected .iter() .any(|(_, listed)| !listed.boundaries.is_empty()); + let has_orphan_files = collected + .iter() + .any(|(_, listed)| !listed.orphan_files.is_empty()); let mut external_rules: BTreeMap = BTreeMap::new(); for (_, listed) in &collected { for external in &listed.external_metrics { @@ -181,6 +185,11 @@ impl SarifLog { rules.push(boundaries_descriptor()); index }); + let orphan_files_rule_index = has_orphan_files.then(|| { + let index = rules.len(); + rules.push(orphan_files_descriptor()); + index + }); let mut external_rule_indices: BTreeMap = BTreeMap::new(); for (key, (name, description)) in external_rules { let index = rules.len(); @@ -219,6 +228,7 @@ impl SarifLog { *source_set, listed, boundaries_rule_index, + orphan_files_rule_index, &external_rule_indices, ) }) @@ -317,6 +327,16 @@ fn boundaries_descriptor() -> Rule { } } +fn orphan_files_descriptor() -> Rule { + Rule { + id: "orphan_files".to_owned(), + name: ORPHAN_FILES_DESCRIPTOR.name.to_owned(), + short_description: Text::from(ORPHAN_FILES_DESCRIPTOR.short_description), + full_description: Text::from(ORPHAN_FILES_DESCRIPTOR.full_description), + help: Text::from(ORPHAN_FILES_DESCRIPTOR.help), + } +} + impl<'findings> ListedFindings<'findings> { fn of_section(section: &'findings SourceSetSection) -> ListedFindings<'findings> { ListedFindings { @@ -330,6 +350,10 @@ impl<'findings> ListedFindings<'findings> { .boundaries .as_ref() .map_or(&[], |boundaries| boundaries.findings.listed.as_slice()), + orphan_files: section + .orphan_files + .as_ref() + .map_or(&[], |orphans| orphans.findings.listed.as_slice()), external_metrics: section .external_metrics .iter() @@ -348,6 +372,7 @@ fn results( source_set: SourceSet, listed: &ListedFindings<'_>, boundaries_rule_index: Option, + orphan_files_rule_index: Option, external_rule_indices: &BTreeMap, ) -> Vec { let eroded_functions = listed.eroded_functions.iter().map(|function| { @@ -415,6 +440,27 @@ fn results( }, } }); + let orphan_files = listed.orphan_files.iter().map(|finding| SarifResult { + rule_id: "orphan_files".to_owned(), + rule_index: orphan_files_rule_index.unwrap_or_default(), + level: "note", + message: Text { + text: finding.message.clone(), + }, + locations: [Location::in_repository(&finding.path, 1, None)], + related_locations: related( + finding + .test_importers + .iter() + .map(|importer| Location::in_repository(importer, 1, None)), + ), + partial_fingerprints: PartialFingerprints { + codeint_finding_id: finding.id.clone(), + }, + properties: ResultProperties { + source_set: source_set.key(), + }, + }); let external_findings = listed.external_metrics.iter().flat_map(|external| { let rule_index = external_rule_indices .get(external.key) @@ -447,6 +493,7 @@ fn results( .chain(flagged_lines) .chain(import_cycles) .chain(boundaries) + .chain(orphan_files) .chain(external_findings) .collect() } diff --git a/crates/report/src/sarif/tests.rs b/crates/report/src/sarif/tests.rs index e0751fd..800cdb9 100644 --- a/crates/report/src/sarif/tests.rs +++ b/crates/report/src/sarif/tests.rs @@ -78,6 +78,7 @@ fn every_sarif_result_carries_its_finding_id_in_partial_fingerprints() { flagged_lines: &flagged, import_cycles: &cycles, boundaries: &[], + orphan_files: &[], external_metrics: Vec::new(), }; @@ -187,6 +188,7 @@ fn clone_family_sarif_result_replaces_its_member_clone_groups_and_keeps_standalo flagged_lines: &[], import_cycles: &[], boundaries: &[], + orphan_files: &[], external_metrics: Vec::new(), }; diff --git a/crates/report/src/schema.rs b/crates/report/src/schema.rs index 0d9ece1..9553062 100644 --- a/crates/report/src/schema.rs +++ b/crates/report/src/schema.rs @@ -59,6 +59,13 @@ pub(crate) fn built_in_metric_descriptor(metric: Metric) -> BuiltInMetricDescrip } } +pub(crate) const ORPHAN_FILES_DESCRIPTOR: BuiltInMetricDescriptor = BuiltInMetricDescriptor { + name: "Orphan files", + short_description: "A Production file unreachable from any entry point", + full_description: "Orphan files measures the share of Production files that cannot be reached through resolved runtime imports from any manifest-declared or configured entry point, annotating files imported only by tests as test-only.", + help: "Delete the unused Production file (and any stale tests that only import it), wire it into an entry point, or add its path glob to entry_points in codeint.json.", +}; + #[derive(Debug, Clone, PartialEq, Serialize)] pub struct SchemaReport { name: String, @@ -113,7 +120,7 @@ impl SchemaReport { exit_codes: Vec, ) -> SchemaReport { let default_limits = RegressionLimits::default(); - let metrics = BUILT_IN_METRICS + let mut metrics: Vec = BUILT_IN_METRICS .into_iter() .map(|metric| { let descriptor = built_in_metric_descriptor(metric); @@ -129,6 +136,16 @@ impl SchemaReport { } }) .collect(); + let orphan_limit = default_limits.limit_for_key(SourceSet::Production, "orphan_files"); + metrics.push(MetricSchema { + key: "orphan_files", + name: ORPHAN_FILES_DESCRIPTOR.name, + short_description: ORPHAN_FILES_DESCRIPTOR.short_description, + description: ORPHAN_FILES_DESCRIPTOR.full_description, + unit: "ratio", + default_ratio_rise_limit: orphan_limit.ratio_rise.ratio(), + default_new_findings_rule: orphan_limit.new_findings, + }); let source_sets = SOURCE_SETS.into_iter().map(SourceSet::key).collect(); SchemaReport { name: cli.name, diff --git a/docs/reference.md b/docs/reference.md index c30be82..17119c1 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -821,6 +821,7 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `budgets.{source_set}` | object | The Budgets of this Source set; empty by default | | `budgets.{source_set}.{metric}` | number from 0 to 1 | The highest ratio of this Metric in this Source set | | `budgets.{source_set}.boundaries` | number from 0 to 1 | The highest Boundaries ratio in this Source set | +| `budgets.{source_set}.orphan_files` | number from 0 to 1 | The highest Orphan files ratio in this Source set | | `regression_limits` | object | How much each Metric may get worse in `codeint diff`; see [Regression limits](#regression-limits) | | `regression_limits.{metric}` | object | The Regression limit of this Metric in every Source set | | `regression_limits.{metric}.ratio_rise` | number from 0 to 1 | The highest ratio rise that passes | @@ -828,6 +829,9 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `regression_limits.boundaries` | object | The Regression limit of Boundaries in every Source set | | `regression_limits.boundaries.ratio_rise` | number from 0 to 1 | The highest Boundaries ratio rise that passes | | `regression_limits.boundaries.new_findings` | string | When new Boundaries Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | +| `regression_limits.orphan_files` | object | The Regression limit of Orphan files in every Source set | +| `regression_limits.orphan_files.ratio_rise` | number from 0 to 1 | The highest Orphan files ratio rise that passes | +| `regression_limits.orphan_files.new_findings` | string | When new Orphan files Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | | `regression_limits.{source_set}` | object | The Regression limits of this Source set only | | `regression_limits.{source_set}.{metric}` | object | The Regression limit of this Metric in this Source set | | `regression_limits.{source_set}.{metric}.ratio_rise` | number from 0 to 1 | The highest ratio rise that passes | @@ -835,6 +839,9 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `regression_limits.{source_set}.boundaries` | object | The Regression limit of Boundaries in this Source set | | `regression_limits.{source_set}.boundaries.ratio_rise` | number from 0 to 1 | The highest Boundaries ratio rise that passes | | `regression_limits.{source_set}.boundaries.new_findings` | string | When new Boundaries Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | +| `regression_limits.{source_set}.orphan_files` | object | The Regression limit of Orphan files in this Source set | +| `regression_limits.{source_set}.orphan_files.ratio_rise` | number from 0 to 1 | The highest Orphan files ratio rise that passes | +| `regression_limits.{source_set}.orphan_files.new_findings` | string | When new Orphan files Findings are a Regression: `any_new_finding` (default), `numerator_rise_with_new_findings`, or `never` | | `languages` | list of objects | Which Language plugin measures which folders; see [Languages](#languages) | | `languages[].plugin` | string | The name of the Language plugin, such as `typescript-javascript` | | `languages[].include` | list of strings | Globs of repository-relative folders or files that the Language plugin measures; a folder covers every file below it | @@ -861,6 +868,7 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace | `duplication` | object | Settings for Duplication detection, including opt-in shingle-based near-clone detection; see [Duplication](#duplication) | | `duplication.near_clones` | boolean | When `true`, detect near-duplicate code blocks using shingle similarity in addition to exact Clone groups; `false` by default | | `duplication.min_similarity` | number in (0, 1] | Minimum Jaccard shingle similarity required for two blocks to match as a near-clone; `0.85` by default | +| `entry_points` | list of strings | Globs of repository-relative paths treated as additional Production entry points for Orphan files detection; empty by default | A key that the schema does not have, or a value of the wrong type, stops the run with exit code 2 and names the key. With this `codeint.json`: @@ -876,7 +884,7 @@ codeint check ``` ```text stderr -codeint: codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries, duplication +codeint: codeint.json has an unknown key budget; the keys allowed there are $schema, source_sets, budgets, regression_limits, languages, plugins, plugin_limits, boundaries, duplication, entry_points Remove the key, or correct its spelling to one of the allowed keys. ``` @@ -1161,6 +1169,40 @@ Near-clone mode honors the same `import-or-export`, minimum token, and minimum d codeint check ``` +### Orphan files + +Orphan files detection traverses resolved runtime imports from the union of manifest-declared entry points (such as `package.json`, `Cargo.toml`, `pyproject.toml`, `composer.json`, and `pubspec.yaml`) and configured `entry_points` globs in `codeint.json`. +Production files unreachable from any Production entry point are reported as `unreferenced`, or as `test-only` when still imported by Test files. +Generated and Vendored Source sets are excluded, and when no entry points exist for a language or isolated Workspace package, Orphan files reporting stays silently inactive. +In `codeint diff`, each Orphan files Finding carries a stable `id` so pre-existing orphans remain unchanged while newly introduced orphans fail by default (`new_findings: "any_new_finding"`). + +```json codeint.json +{ + "entry_points": ["src/*.ts"], + "budgets": { + "production": { + "orphan_files": 0 + } + }, + "regression_limits": { + "orphan_files": { + "ratio_rise": 0.01, + "new_findings": "any_new_finding" + }, + "production": { + "orphan_files": { + "ratio_rise": 0, + "new_findings": "any_new_finding" + } + } + } +} +``` + +```sh exit=0 +codeint check +``` + ## Result cache codeint caches the measurement of each commit it reads from Git objects, so a second `codeint diff` against the same base reads it back instead of measuring the commit again. diff --git a/plugins/languages/dart/src/entry_points.rs b/plugins/languages/dart/src/entry_points.rs new file mode 100644 index 0000000..1f65977 --- /dev/null +++ b/plugins/languages/dart/src/entry_points.rs @@ -0,0 +1,110 @@ +use std::collections::{BTreeMap, BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; +use serde::Deserialize; + +use crate::workspaces::PUBSPEC_MANIFEST; + +#[derive(Deserialize)] +struct PubspecEntryPoints { + name: Option, + executables: Option>>, +} + +pub(crate) fn discover(repository_paths: &[String], manifests: &[Manifest]) -> Vec { + let dart_files: HashSet<&str> = repository_paths + .iter() + .map(String::as_str) + .filter(|path| path.ends_with(".dart")) + .collect(); + let suffix = format!("/{PUBSPEC_MANIFEST}"); + let mut results = BTreeSet::new(); + for manifest in manifests { + let base_dir = if manifest.path == PUBSPEC_MANIFEST { + "" + } else if let Some(dir) = manifest.path.strip_suffix(&suffix) { + dir + } else { + continue; + }; + if let Ok(Some(spec)) = serde_saphyr::from_str::>(&manifest.text) + { + spec.collect_entries(base_dir, repository_paths, &dart_files, &mut results); + } + } + results.into_iter().collect() +} + +impl PubspecEntryPoints { + fn collect_entries( + &self, + base_dir: &str, + repository_paths: &[String], + dart_files: &HashSet<&str>, + out: &mut BTreeSet, + ) { + if let Some(pkg) = self + .name + .as_deref() + .map(str::trim) + .filter(|n| !n.is_empty() && !n.contains('/') && !n.contains('\\') && *n != "..") + && let Some(lib_file) = normalize_relative_path(base_dir, &format!("lib/{pkg}.dart")) + && dart_files.contains(lib_file.as_str()) + { + out.insert(lib_file); + } + if let Some(executables) = self.executables.as_ref() { + collect_declared_executables(base_dir, executables, dart_files, out); + } + collect_bin_directory(base_dir, repository_paths, out); + } +} + +fn collect_declared_executables( + base_dir: &str, + executables: &BTreeMap>, + dart_files: &HashSet<&str>, + out: &mut BTreeSet, +) { + for (command, explicit) in executables { + let target = explicit + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| command.trim()); + if target.is_empty() + || target.starts_with('/') + || target.contains('\\') + || target.split('/').any(|segment| segment == "..") + { + continue; + } + let rel = if target.ends_with(".dart") { + format!("bin/{target}") + } else { + format!("bin/{target}.dart") + }; + if let Some(candidate) = normalize_relative_path(base_dir, &rel) + && dart_files.contains(candidate.as_str()) + { + out.insert(candidate); + } + } +} + +fn collect_bin_directory(base_dir: &str, repository_paths: &[String], out: &mut BTreeSet) { + let prefix = if base_dir.is_empty() { + "bin/".to_owned() + } else { + format!("{base_dir}/bin/") + }; + for path in repository_paths { + if let Some(rest) = path.strip_prefix(&prefix) + && !rest.contains('/') + && rest.ends_with(".dart") + { + out.insert(path.clone()); + } + } +} diff --git a/plugins/languages/dart/src/lib.rs b/plugins/languages/dart/src/lib.rs index 9179e00..17d11dd 100644 --- a/plugins/languages/dart/src/lib.rs +++ b/plugins/languages/dart/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod entry_points; mod functions; mod imports; mod lexer; @@ -16,6 +17,7 @@ use codeint_model::language::{ }; use codeint_model::token_text_hash; +use crate::entry_points::discover as discover_entry_points; use crate::lexer::{DartKind, DartToken}; pub use rules::flagged_line_rules; @@ -95,8 +97,8 @@ impl Guest for Dart { lower_dart(&path, &text) } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + discover_entry_points(&repository_paths, &manifests) } fn extensions() -> Vec { diff --git a/plugins/languages/dart/tests/entry_points.rs b/plugins/languages/dart/tests/entry_points.rs new file mode 100644 index 0000000..0342980 --- /dev/null +++ b/plugins/languages/dart/tests/entry_points.rs @@ -0,0 +1,77 @@ +use codeint_lang_dart::Dart; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_executables_default_lib_and_bin_entries_from_pubspec() { + let mut paths = Vec::new(); + for raw in [ + "pubspec.yaml", + "lib/toolkit.dart", + "lib/src/internal.dart", + "lib/secret.dart", + "bin/run_cli.dart", + "bin/direct.dart", + "bin/extra.dart", + "bin/internal/helper.dart", + "packages/core/pubspec.yaml", + "packages/core/lib/core_lib.dart", + "packages/core/lib/src/impl.dart", + "packages/core/bin/serve.dart", + ] { + paths.push(RepoPath::new(raw).unwrap()); + } + + let root = Manifest { + path: "pubspec.yaml".into(), + text: "name: toolkit\nexecutables:\n cli: run_cli\n direct:\n missing_cmd: absent\n escape: ../lib/secret\n".into(), + }; + let core = Manifest { + path: "packages/core/pubspec.yaml".into(), + text: "name: core_lib\n".into(), + }; + + let found: Vec = Dart + .entry_points(&paths, vec![root, core]) + .expect("valid entry points") + .into_iter() + .map(|path| path.as_str().to_owned()) + .collect(); + assert_eq!( + found, + [ + "bin/direct.dart", + "bin/extra.dart", + "bin/run_cli.dart", + "lib/toolkit.dart", + "packages/core/bin/serve.dart", + "packages/core/lib/core_lib.dart", + ] + ); +} + +#[test] +fn returns_empty_when_pubspec_has_no_matching_entry_points_or_is_invalid() { + let paths = [ + RepoPath::new("pubspec.yaml").unwrap(), + RepoPath::new("lib/helper.dart").unwrap(), + ]; + let no_match = Dart + .entry_points( + &paths, + vec![Manifest { + path: "pubspec.yaml".into(), + text: "name: app\n".into(), + }], + ) + .expect("valid empty result"); + let malformed = Dart + .entry_points( + &paths, + vec![Manifest { + path: "pubspec.yaml".into(), + text: "executables: [\n".into(), + }], + ) + .expect("valid empty result"); + assert!(no_match.is_empty() && malformed.is_empty()); +} diff --git a/plugins/languages/php/src/entry_points.rs b/plugins/languages/php/src/entry_points.rs new file mode 100644 index 0000000..c294f42 --- /dev/null +++ b/plugins/languages/php/src/entry_points.rs @@ -0,0 +1,56 @@ +use std::collections::{BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; +use serde_json::Value; + +use crate::workspaces::COMPOSER_MANIFEST; + +pub(crate) fn extract(repository_paths: &[String], manifests: &[Manifest]) -> Vec { + let available: HashSet<&str> = repository_paths.iter().map(String::as_str).collect(); + let available_ref = &available; + let nested_suffix = format!("/{COMPOSER_MANIFEST}"); + let collected: BTreeSet = manifests + .iter() + .filter_map(|manifest| { + let dir = if manifest.path == COMPOSER_MANIFEST { + "" + } else { + manifest.path.strip_suffix(&nested_suffix)? + }; + let parsed = serde_json::from_str::(&manifest.text).ok()?; + Some( + bin_strings(parsed.get("bin")?) + .into_iter() + .filter_map(move |raw| resolve_composer_bin(dir, &raw, available_ref)), + ) + }) + .flatten() + .collect(); + collected.into_iter().collect() +} + +fn bin_strings(value: &Value) -> Vec { + match value { + Value::String(single) => vec![single.clone()], + Value::Array(items) => items + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect(), + _ => Vec::new(), + } +} + +fn resolve_composer_bin(base_dir: &str, raw: &str, available: &HashSet<&str>) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() + || trimmed.starts_with('/') + || trimmed.contains('\\') + || trimmed.split('/').any(|segment| segment == "..") + { + return None; + } + let normalized = normalize_relative_path(base_dir, trimmed)?; + (!normalized.is_empty() && available.contains(normalized.as_str())).then_some(normalized) +} diff --git a/plugins/languages/php/src/lib.rs b/plugins/languages/php/src/lib.rs index f95671e..3bfe336 100644 --- a/plugins/languages/php/src/lib.rs +++ b/plugins/languages/php/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod entry_points; mod functions; mod imports; mod lexer; @@ -16,6 +17,7 @@ use codeint_model::language::{ }; use codeint_model::token_text_hash; +use crate::entry_points::extract as extract_entry_points; use crate::lexer::{RawKind, RawToken}; pub use rules::flagged_line_rules; @@ -102,7 +104,7 @@ impl Guest for Php { Vec::new() } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + extract_entry_points(&repository_paths, &manifests) } } diff --git a/plugins/languages/php/tests/entry_points.rs b/plugins/languages/php/tests/entry_points.rs new file mode 100644 index 0000000..41b5e2b --- /dev/null +++ b/plugins/languages/php/tests/entry_points.rs @@ -0,0 +1,98 @@ +use codeint_lang_php::Php; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_bin_entry_points_from_composer_manifests() { + let manifest = |path: &str, text: &str| Manifest { + path: path.into(), + text: text.into(), + }; + let repo_paths = [ + "composer.json", + "bin/console", + "bin/worker.php", + "src/Helper.php", + "packages/cli/composer.json", + "packages/cli/scripts/run.php", + "packages/tool/composer.json", + "packages/tool/tool.php", + ] + .map(|path| RepoPath::new(path).unwrap()); + + let manifests = vec![ + manifest( + "composer.json", + r#"{"name": "acme/app", "bin": ["bin/console", "./bin/worker.php", "bin/missing.php", "../outside.php", "/abs.php", "bin/console"]}"#, + ), + manifest( + "packages/cli/composer.json", + r#"{"name": "acme/cli", "bin": ["scripts/run.php"]}"#, + ), + manifest( + "packages/tool/composer.json", + r#"{"name": "acme/tool", "bin": "tool.php"}"#, + ), + ]; + + let found: Vec = Php + .entry_points(&repo_paths, manifests) + .expect("valid entry points") + .into_iter() + .map(|path| path.as_str().to_owned()) + .collect(); + assert_eq!( + found, + [ + "bin/console", + "bin/worker.php", + "packages/cli/scripts/run.php", + "packages/tool/tool.php", + ] + ); +} + +#[test] +fn returns_empty_when_composer_manifest_has_no_bin_or_is_invalid() { + let paths = [ + RepoPath::new("composer.json").unwrap(), + RepoPath::new("src/App.php").unwrap(), + ]; + let psr4_only = r#"{"name": "acme/lib", "autoload": {"psr-4": {"Acme\\": "src/"}}}"#; + let empty_count = [psr4_only, "{invalid"] + .into_iter() + .map(|body| { + Php.entry_points( + &paths, + vec![Manifest { + path: "composer.json".into(), + text: body.into(), + }], + ) + .expect("valid empty result") + .len() + }) + .sum::(); + assert_eq!(empty_count, 0); +} + +#[test] +fn rejects_parent_traversal_in_nested_composer_bin() { + let files = [ + RepoPath::new("packages/cli/composer.json").unwrap(), + RepoPath::new("packages/cli/bin/run.php").unwrap(), + RepoPath::new("packages/other/secret.php").unwrap(), + ]; + let entries = Php + .entry_points( + &files, + vec![Manifest { + path: "packages/cli/composer.json".into(), + text: r#"{"name": "acme/cli", "bin": ["../other/secret.php", "./../other/secret.php", "bin/../../other/secret.php", "bin/run.php"]}"#.into(), + }], + ) + .expect("entry points"); + assert_eq!( + entries, + [RepoPath::new("packages/cli/bin/run.php").unwrap()] + ); +} diff --git a/plugins/languages/python/src/entry_points.rs b/plugins/languages/python/src/entry_points.rs new file mode 100644 index 0000000..889be03 --- /dev/null +++ b/plugins/languages/python/src/entry_points.rs @@ -0,0 +1,256 @@ +use std::collections::{BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; + +pub(crate) fn discover(repository_paths: &[String], manifests: &[Manifest]) -> Vec { + let py_files: HashSet<&str> = repository_paths + .iter() + .map(String::as_str) + .filter(|path| path.ends_with(".py")) + .collect(); + let mut entries = BTreeSet::new(); + for (base_dir, doc) in parsed_pyprojects(manifests) { + let roots = package_search_roots(base_dir); + collect_script_entries(&doc, &roots, &py_files, &mut entries); + collect_declared_packages(&doc, base_dir, &py_files, &mut entries); + } + entries.into_iter().collect() +} + +fn parsed_pyprojects(manifests: &[Manifest]) -> Vec<(&str, toml::Value)> { + manifests + .iter() + .filter_map(|manifest| { + let dir = if manifest.path == "pyproject.toml" { + "" + } else { + manifest.path.strip_suffix("/pyproject.toml")? + }; + let doc = toml::from_str::(&manifest.text).ok()?; + Some((dir, doc)) + }) + .collect() +} + +fn package_search_roots(base_dir: &str) -> [String; 2] { + let src_root = if base_dir.is_empty() { + "src".to_owned() + } else { + format!("{base_dir}/src") + }; + [base_dir.to_owned(), src_root] +} + +fn collect_script_entries( + doc: &toml::Value, + roots: &[String], + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + if let Some(project) = doc.get("project") { + for section in ["scripts", "gui-scripts"] { + if let Some(table) = project.get(section).and_then(toml::Value::as_table) { + for spec in table.values().filter_map(toml::Value::as_str) { + resolve_module_spec(spec, roots, py_files, found); + } + } + } + if let Some(groups) = project.get("entry-points").and_then(toml::Value::as_table) { + for group in groups.values().filter_map(toml::Value::as_table) { + for spec in group.values().filter_map(toml::Value::as_str) { + resolve_module_spec(spec, roots, py_files, found); + } + } + } + } + collect_poetry_scripts(doc, roots, py_files, found); +} + +fn collect_poetry_scripts( + doc: &toml::Value, + roots: &[String], + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let Some(scripts) = doc + .get("tool") + .and_then(|v| v.get("poetry")) + .and_then(|v| v.get("scripts")) + .and_then(toml::Value::as_table) + else { + return; + }; + for value in scripts.values() { + let spec = value.as_str().or_else(|| { + value + .get("callable") + .or_else(|| value.get("reference")) + .and_then(toml::Value::as_str) + }); + if let Some(target) = spec { + resolve_module_spec(target, roots, py_files, found); + } + } +} + +fn resolve_module_spec( + spec: &str, + roots: &[String], + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let Some(rel_path) = module_spec_to_rel_path(spec) else { + return; + }; + for root in roots { + let Some(base) = normalize_relative_path(root, &rel_path) else { + continue; + }; + if base.is_empty() { + continue; + } + for candidate in [ + format!("{base}.py"), + format!("{base}/__init__.py"), + format!("{base}/__main__.py"), + ] { + if py_files.contains(candidate.as_str()) { + found.insert(candidate); + return; + } + } + } +} + +fn module_spec_to_rel_path(spec: &str) -> Option { + let module_part = spec + .trim() + .split(':') + .next()? + .split('[') + .next()? + .split_whitespace() + .next()? + .trim(); + if module_part.is_empty() || module_part.contains('/') || module_part.contains('\\') { + return None; + } + let segments: Vec<&str> = module_part.split('.').collect(); + if segments.iter().any(|seg| seg.is_empty() || *seg == "..") { + return None; + } + Some(segments.join("/")) +} + +fn collect_declared_packages( + doc: &toml::Value, + base_dir: &str, + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let Some(tool) = doc.get("tool") else { + return; + }; + let setuptools = tool + .get("setuptools") + .and_then(|v| v.get("packages")) + .and_then(toml::Value::as_array); + let hatch = tool + .get("hatch") + .and_then(|v| v.get("build")) + .and_then(|v| v.get("targets")) + .and_then(|v| v.get("wheel")) + .and_then(|v| v.get("packages")) + .and_then(toml::Value::as_array); + for list in [setuptools, hatch].into_iter().flatten() { + for pkg in list.iter().filter_map(toml::Value::as_str) { + resolve_package_dir(base_dir, None, pkg, py_files, found); + } + } + collect_poetry_packages(tool, base_dir, py_files, found); +} + +fn collect_poetry_packages( + tool: &toml::Value, + base_dir: &str, + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let Some(packages) = tool + .get("poetry") + .and_then(|v| v.get("packages")) + .and_then(toml::Value::as_array) + else { + return; + }; + for entry in packages { + if let Some(pkg) = entry.as_str() { + resolve_package_dir(base_dir, None, pkg, py_files, found); + } else if let Some(include) = entry.get("include").and_then(toml::Value::as_str) { + let from = entry.get("from").and_then(toml::Value::as_str); + resolve_package_dir(base_dir, from, include, py_files, found); + } + } +} + +fn resolve_package_dir( + base_dir: &str, + from: Option<&str>, + pkg: &str, + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + let trimmed = pkg.trim(); + if trimmed.is_empty() + || trimmed.starts_with('/') + || trimmed.contains('\\') + || trimmed.split('/').any(|segment| segment == "..") + { + return; + } + let rel_pkg = if trimmed.contains('/') { + trimmed.to_owned() + } else { + trimmed.replace('.', "/") + }; + for root in candidate_package_roots(base_dir, from, trimmed.contains('/')) { + if let Some(pkg_dir) = normalize_relative_path(&root, &rel_pkg) + && !pkg_dir.is_empty() + { + record_package_init_files(&pkg_dir, py_files, found); + } + } +} + +fn candidate_package_roots(base_dir: &str, from: Option<&str>, has_slash: bool) -> Vec { + if let Some(from_dir) = from { + let trimmed = from_dir.trim(); + if trimmed.starts_with('/') + || trimmed.contains('\\') + || trimmed.split('/').any(|segment| segment == "..") + { + return Vec::new(); + } + return normalize_relative_path(base_dir, trimmed) + .into_iter() + .collect(); + } + if has_slash { + return vec![base_dir.to_owned()]; + } + package_search_roots(base_dir).into() +} + +fn record_package_init_files( + pkg_dir: &str, + py_files: &HashSet<&str>, + found: &mut BTreeSet, +) { + for entry_file in ["__init__.py", "__main__.py"] { + let candidate = format!("{pkg_dir}/{entry_file}"); + if py_files.contains(candidate.as_str()) { + found.insert(candidate); + } + } +} diff --git a/plugins/languages/python/src/lib.rs b/plugins/languages/python/src/lib.rs index 5916f89..9f6fc02 100644 --- a/plugins/languages/python/src/lib.rs +++ b/plugins/languages/python/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod entry_points; mod functions; mod imports; mod lexer; @@ -15,6 +16,8 @@ use codeint_model::language::{ use codeint_model::scan::build_reference_ranges; use codeint_model::token_text_hash; +use crate::entry_points::discover as discover_entry_points; + pub use rules::flagged_line_rules; pub struct Python; @@ -56,8 +59,8 @@ impl Guest for Python { Vec::new() } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + discover_entry_points(&repository_paths, &manifests) } fn lower(path: String, text: String) -> Result { diff --git a/plugins/languages/python/tests/entry_points.rs b/plugins/languages/python/tests/entry_points.rs new file mode 100644 index 0000000..8f688ef --- /dev/null +++ b/plugins/languages/python/tests/entry_points.rs @@ -0,0 +1,109 @@ +use codeint_lang_python::Python; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_project_scripts_gui_scripts_entry_points_and_declared_packages() { + let snapshot: Vec = [ + "pyproject.toml", + "src/demo/cli.py", + "src/demo/pkg/__init__.py", + "demo/gui.py", + "demo/plugin.py", + "helper_pkg/__init__.py", + "packages/worker/pyproject.toml", + "packages/worker/src/worker/__init__.py", + "packages/worker/src/worker/__main__.py", + "packages/worker/src/worker/entry.py", + "packages/worker/src/worker/jobs.py", + "packages/poetry_app/pyproject.toml", + "packages/poetry_app/src/papp/__init__.py", + ] + .iter() + .map(|item| RepoPath::new(*item).unwrap()) + .collect(); + + let manifests = vec![ + Manifest { + path: "pyproject.toml".to_owned(), + text: "[project]\nname = \"demo\"\n[project.scripts]\napp-cli = \"demo.cli:main\"\npkg-cmd = \"demo.pkg:run [extra]\"\nmissing-cmd = \"demo.absent:run\"\n[project.gui-scripts]\napp-gui = \"demo.gui:launch\"\n[project.entry-points.\"demo.plugins\"]\next = \"demo.plugin:Plugin\"\n[tool.setuptools]\npackages = [\"helper_pkg\"]\n".to_owned(), + }, + Manifest { + path: "packages/worker/pyproject.toml".to_owned(), + text: "[project]\nname = \"worker\"\n[tool.poetry.scripts]\nrun-worker = \"worker.entry:start\"\njob-runner = { callable = \"worker.jobs:main\" }\n[tool.hatch.build.targets.wheel]\npackages = [\"src/worker\"]\n".to_owned(), + }, + Manifest { + path: "packages/poetry_app/pyproject.toml".to_owned(), + text: "[tool.poetry]\nname = \"papp\"\npackages = [{ include = \"papp\", from = \"src\" }]\n".to_owned(), + }, + ]; + + let found: Vec = Python + .entry_points(&snapshot, manifests) + .expect("valid entry points") + .into_iter() + .map(|path| path.as_str().to_owned()) + .collect(); + assert_eq!( + found, + [ + "demo/gui.py", + "demo/plugin.py", + "helper_pkg/__init__.py", + "packages/poetry_app/src/papp/__init__.py", + "packages/worker/src/worker/__init__.py", + "packages/worker/src/worker/__main__.py", + "packages/worker/src/worker/entry.py", + "packages/worker/src/worker/jobs.py", + "src/demo/cli.py", + "src/demo/pkg/__init__.py", + ] + ); +} + +#[test] +fn returns_empty_when_pyproject_declares_no_entry_points_or_is_invalid() { + let snapshot = [ + RepoPath::new("pyproject.toml").unwrap(), + RepoPath::new("webapp/__init__.py").unwrap(), + RepoPath::new("webapp/views.py").unwrap(), + ]; + let plain = Manifest { + path: "pyproject.toml".to_owned(), + text: "[project]\nname = \"webapp\"\n".to_owned(), + }; + let broken = Manifest { + path: "pyproject.toml".to_owned(), + text: "[project\nname =".to_owned(), + }; + assert_eq!( + Python + .entry_points(&snapshot, vec![plain]) + .expect("valid empty result"), + Vec::::new() + ); + assert_eq!( + Python + .entry_points(&snapshot, vec![broken]) + .expect("valid empty result"), + Vec::::new() + ); +} + +#[test] +fn rejects_parent_traversal_in_nested_pyproject_entries() { + let repo = [ + "packages/app/pyproject.toml", + "packages/app/src/app/__init__.py", + "packages/other/secret/__init__.py", + "packages/other/secret.py", + ] + .map(|item| RepoPath::new(item).unwrap()); + let pyproject = Manifest { + path: "packages/app/pyproject.toml".to_owned(), + text: "[project]\nname = \"app\"\n[project.scripts]\nescape = \"../other.secret:main\"\ndotted = \"..other.secret:main\"\n[tool.setuptools]\npackages = [\"../other/secret\"]\n[tool.hatch.build.targets.wheel]\npackages = [\"src/../../other/secret\"]\n[tool.poetry]\npackages = [{ include = \"../other/secret\" }, { include = \"secret\", from = \"../other\" }, { include = \"app\", from = \"src\" }]\n".to_owned(), + }; + assert_eq!( + Python.entry_points(&repo, vec![pyproject]).unwrap(), + [RepoPath::new("packages/app/src/app/__init__.py").unwrap()] + ); +} diff --git a/plugins/languages/rust/src/entry_points.rs b/plugins/languages/rust/src/entry_points.rs new file mode 100644 index 0000000..159291f --- /dev/null +++ b/plugins/languages/rust/src/entry_points.rs @@ -0,0 +1,155 @@ +use std::collections::{BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; +use serde::Deserialize; + +use crate::workspaces::CARGO_MANIFEST; + +#[derive(Deserialize)] +struct CargoTargets { + package: Option, + lib: Option, + #[serde(default)] + bin: Vec, +} + +#[derive(Deserialize)] +struct PackageMeta { + name: Option, + autolib: Option, + autobins: Option, +} + +#[derive(Deserialize)] +struct TargetSpec { + name: Option, + path: Option, +} + +pub(crate) fn entry_points(repository_paths: &[String], manifests: &[Manifest]) -> Vec { + let index = CrateTargetIndex { + all_paths: repository_paths, + present: repository_paths.iter().map(String::as_str).collect(), + }; + let mut targets = BTreeSet::new(); + let suffix = format!("/{CARGO_MANIFEST}"); + for manifest in manifests { + let base_dir = match manifest.path.as_str() { + CARGO_MANIFEST => "", + other => match other.strip_suffix(&suffix) { + Some(dir) => dir, + None => continue, + }, + }; + if let Ok(parsed) = toml::from_str::(&manifest.text) { + parsed.collect_into(&index, base_dir, &mut targets); + } + } + targets.into_iter().collect() +} + +struct CrateTargetIndex<'a> { + all_paths: &'a [String], + present: HashSet<&'a str>, +} + +impl CrateTargetIndex<'_> { + fn record(&self, base_dir: &str, rel: &str, out: &mut BTreeSet) -> bool { + let trimmed = rel.trim(); + if trimmed.is_empty() + || trimmed.starts_with('/') + || trimmed.contains('\\') + || trimmed.split('/').any(|segment| segment == "..") + { + return false; + } + let Some(candidate) = normalize_relative_path(base_dir, trimmed) else { + return false; + }; + if !candidate.is_empty() && self.present.contains(candidate.as_str()) { + out.insert(candidate); + true + } else { + false + } + } + + fn scan_auto_bins(&self, base_dir: &str, out: &mut BTreeSet) { + let prefix = if base_dir.is_empty() { + "src/bin/".to_owned() + } else { + format!("{base_dir}/src/bin/") + }; + for path in self.all_paths { + let Some(rest) = path.strip_prefix(&prefix) else { + continue; + }; + let is_top_level = !rest.contains('/') && rest.ends_with(".rs"); + let is_subdir_main = rest + .strip_suffix("/main.rs") + .is_some_and(|dir| !dir.is_empty() && !dir.contains('/')); + if is_top_level || is_subdir_main { + out.insert(path.clone()); + } + } + } +} + +impl CargoTargets { + fn collect_into( + &self, + index: &CrateTargetIndex<'_>, + base_dir: &str, + out: &mut BTreeSet, + ) { + let Some(package) = self.package.as_ref() else { + return; + }; + if let Some(explicit) = self.lib.as_ref().and_then(|spec| spec.path.as_deref()) { + index.record(base_dir, explicit, out); + } else if self.lib.is_some() || package.autolib != Some(false) { + index.record(base_dir, "src/lib.rs", out); + } + for bin in &self.bin { + if let Some(explicit) = bin.path.as_deref() { + index.record(base_dir, explicit, out); + } else if let Some(name) = bin.name.as_deref() { + record_named_bin(index, base_dir, package.name.as_deref(), name, out); + } + } + if package.autobins != Some(false) { + index.record(base_dir, "src/main.rs", out); + index.scan_auto_bins(base_dir, out); + } + } +} + +fn record_named_bin( + index: &CrateTargetIndex<'_>, + base_dir: &str, + package_name: Option<&str>, + bin_name: &str, + out: &mut BTreeSet, +) { + let bin_name = bin_name.trim(); + if bin_name.is_empty() + || bin_name.contains('/') + || bin_name.contains('\\') + || bin_name == "." + || bin_name == ".." + { + return; + } + let direct = format!("src/bin/{bin_name}.rs"); + if index.record(base_dir, &direct, out) { + return; + } + let nested = format!("src/bin/{bin_name}/main.rs"); + if index.record(base_dir, &nested, out) { + return; + } + if package_name == Some(bin_name) { + index.record(base_dir, "src/main.rs", out); + } +} diff --git a/plugins/languages/rust/src/lib.rs b/plugins/languages/rust/src/lib.rs index 10f2c5e..0dc8024 100644 --- a/plugins/languages/rust/src/lib.rs +++ b/plugins/languages/rust/src/lib.rs @@ -1,6 +1,7 @@ #![forbid(unsafe_code)] mod cfg_test; +mod entry_points; mod functions; mod imports; mod resolution; @@ -17,6 +18,7 @@ use codeint_model::language::{ }; use crate::cfg_test::excluded_cfg_test_lines; +use crate::entry_points::entry_points as discover_entry_points; use crate::functions::{CodeLines, functions}; use crate::imports::runtime_import_specifiers; use crate::resolution::{RustResolver, manifest_paths}; @@ -69,10 +71,6 @@ impl Guest for Rust { Vec::new() } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() - } - fn manifest_paths(repository_paths: Vec) -> Vec { manifest_paths(&repository_paths) } @@ -104,4 +102,8 @@ impl Guest for Rust { ], ) } + + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + discover_entry_points(&repository_paths, &manifests) + } } diff --git a/plugins/languages/rust/tests/entry_points.rs b/plugins/languages/rust/tests/entry_points.rs new file mode 100644 index 0000000..137b8b8 --- /dev/null +++ b/plugins/languages/rust/tests/entry_points.rs @@ -0,0 +1,155 @@ +use codeint_lang_rust::Rust; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_explicit_and_default_lib_and_bin_targets_from_cargo_manifests() { + let files: Vec = [ + "Cargo.toml", + "src/lib.rs", + "crates/core/Cargo.toml", + "crates/core/src/lib.rs", + "crates/core/src/main.rs", + "crates/core/src/helper.rs", + "crates/core/src/bin/tool.rs", + "crates/core/src/bin/worker/main.rs", + "crates/core/src/bin/worker/extra.rs", + "crates/custom/Cargo.toml", + "crates/custom/src/custom_lib.rs", + "crates/custom/src/cli_main.rs", + "crates/custom/src/bin/named.rs", + "crates/disabled/Cargo.toml", + "crates/disabled/src/lib.rs", + "crates/disabled/src/main.rs", + ] + .into_iter() + .map(|raw| RepoPath::new(raw).expect("valid repo path")) + .collect(); + + let manifests = [ + ("Cargo.toml", "[workspace]\nmembers = [\"crates/*\"]\n"), + ("crates/core/Cargo.toml", "[package]\nname = \"core\"\n"), + ( + "crates/custom/Cargo.toml", + "[package]\nname = \"custom\"\nautobins = false\n[lib]\npath = \"src/custom_lib.rs\"\n[[bin]]\nname = \"cli\"\npath = \"src/cli_main.rs\"\n[[bin]]\nname = \"named\"\n[[bin]]\nname = \"missing\"\npath = \"src/missing.rs\"\n", + ), + ( + "crates/disabled/Cargo.toml", + "[package]\nname = \"disabled\"\nautolib = false\nautobins = false\n", + ), + ] + .into_iter() + .map(|(path, text)| Manifest { + path: path.to_owned(), + text: text.to_owned(), + }) + .collect(); + + let found: Vec = Rust + .entry_points(&files, manifests) + .expect("valid entry points") + .into_iter() + .map(|path| path.as_str().to_owned()) + .collect(); + assert_eq!( + found, + [ + "crates/core/src/bin/tool.rs", + "crates/core/src/bin/worker/main.rs", + "crates/core/src/lib.rs", + "crates/core/src/main.rs", + "crates/custom/src/bin/named.rs", + "crates/custom/src/cli_main.rs", + "crates/custom/src/custom_lib.rs", + ] + ); +} + +#[test] +fn handles_root_crate_empty_targets_and_invalid_manifests() { + let root_files = [ + RepoPath::new("Cargo.toml").unwrap(), + RepoPath::new("src/lib.rs").unwrap(), + RepoPath::new("src/main.rs").unwrap(), + RepoPath::new("src/bin/extra.rs").unwrap(), + ]; + let root_manifest = Manifest { + path: "Cargo.toml".into(), + text: "[package]\nname = \"root_app\"\nautobins = false\n[[bin]]\nname = \"root_app\"\n[[bin]]\nname = \"escape\"\npath = \"../outside.rs\"\n[[bin]]\nname = \"abs\"\npath = \"/etc/passwd\"\n".into(), + }; + let root_found: Vec = Rust + .entry_points(&root_files, vec![root_manifest]) + .expect("valid entry points") + .into_iter() + .map(|path| path.as_str().to_owned()) + .collect(); + assert_eq!(root_found, ["src/lib.rs", "src/main.rs"]); + + let no_targets = [ + RepoPath::new("Cargo.toml").unwrap(), + RepoPath::new("src/helper.rs").unwrap(), + ]; + for text in [ + "[workspace]\nmembers = [\"crates/*\"]\n", + "[package]\nname = \"empty\"\n", + "[package\nname =", + ] { + let entry = Manifest { + path: "Cargo.toml".into(), + text: text.into(), + }; + assert!( + Rust.entry_points(&no_targets, vec![entry]) + .expect("valid empty result") + .is_empty() + ); + } +} + +fn cargo_entries(paths: &[&str], manifest_path: &str, text: &str) -> Vec { + let repo: Vec = paths + .iter() + .map(|raw| RepoPath::new(*raw).unwrap()) + .collect(); + Rust.entry_points( + &repo, + vec![Manifest { + path: manifest_path.into(), + text: text.into(), + }], + ) + .unwrap() + .into_iter() + .map(|entry| entry.as_str().to_owned()) + .collect() +} + +#[test] +fn rejects_parent_traversal_in_nested_cargo_paths_and_bin_names() { + let entries = cargo_entries( + &[ + "crates/app/Cargo.toml", + "crates/app/src/main.rs", + "crates/app/src/secret.rs", + "crates/app/src/bin/sub/tool.rs", + "crates/other/src/lib.rs", + "crates/other/src/main.rs", + ], + "crates/app/Cargo.toml", + "[package]\nname = \"app\"\nautolib = false\nautobins = false\n[lib]\npath = \"../other/src/lib.rs\"\n[[bin]]\nname = \"escape_path\"\npath = \"../other/src/main.rs\"\n[[bin]]\nname = \"../secret\"\n[[bin]]\nname = \"../../other/src/main\"\n[[bin]]\nname = \"sub/tool\"\n[[bin]]\nname = \"..\"\n", + ); + assert!(entries.is_empty()); +} + +#[test] +fn includes_default_lib_when_autolib_is_false_and_lib_table_has_no_path() { + let entries = cargo_entries( + &[ + "crates/explicit_lib/Cargo.toml", + "crates/explicit_lib/src/lib.rs", + "crates/explicit_lib/src/main.rs", + ], + "crates/explicit_lib/Cargo.toml", + "[package]\nname = \"explicit_lib\"\nautolib = false\nautobins = false\n[lib]\ncrate-type = [\"cdylib\"]\n", + ); + assert_eq!(entries, ["crates/explicit_lib/src/lib.rs"]); +} diff --git a/plugins/languages/ts/src/entry_points.rs b/plugins/languages/ts/src/entry_points.rs new file mode 100644 index 0000000..f309d29 --- /dev/null +++ b/plugins/languages/ts/src/entry_points.rs @@ -0,0 +1,368 @@ +use std::collections::{BTreeSet, HashSet}; + +use codeint_model::language::Manifest; +use codeint_model::scan::normalize_relative_path; +use serde_json::Value; + +use crate::workspaces::PACKAGE_MANIFEST; + +const OUTPUT_TO_SOURCE_ALIASES: [(&str, &[&str]); 4] = [ + (".js", &[".ts", ".tsx"]), + (".jsx", &[".tsx"]), + (".mjs", &[".mts"]), + (".cjs", &[".cts"]), +]; + +pub(crate) fn entry_points( + repository_paths: &[String], + manifests: &[Manifest], + extensions: &[&str], +) -> Vec { + let mut finder = TsEntryFinder::new(repository_paths, extensions); + for manifest in manifests { + finder.scan_manifest(manifest); + } + finder.entries.into_iter().collect() +} + +struct TsEntryFinder<'a> { + paths: &'a [String], + extensions: &'a [&'a str], + file_set: HashSet<&'a str>, + entries: BTreeSet, +} + +impl<'a> TsEntryFinder<'a> { + fn new(paths: &'a [String], extensions: &'a [&'a str]) -> TsEntryFinder<'a> { + TsEntryFinder { + paths, + extensions, + file_set: paths.iter().map(String::as_str).collect(), + entries: BTreeSet::new(), + } + } + + fn scan_manifest(&mut self, manifest: &Manifest) { + let base_dir = if manifest.path == PACKAGE_MANIFEST { + "" + } else if let Some(dir) = manifest.path.strip_suffix(&format!("/{PACKAGE_MANIFEST}")) { + dir + } else { + return; + }; + let Ok(doc) = serde_json::from_str::(&manifest.text) else { + return; + }; + for key in ["main", "module"] { + if let Some(target) = doc.get(key).and_then(Value::as_str) { + self.resolve_source_target(base_dir, target); + } + } + if let Some(bin) = doc.get("bin") { + self.collect_bin(base_dir, bin); + } + if let Some(exports) = doc.get("exports") { + self.collect_exports(base_dir, exports); + } + } + + fn collect_bin(&mut self, base_dir: &str, bin: &Value) { + if let Some(target) = bin.as_str() { + self.resolve_bin_target(base_dir, target); + return; + } + if let Some(map) = bin.as_object() { + for target in map.values().filter_map(Value::as_str) { + self.resolve_bin_target(base_dir, target); + } + } + } + + fn collect_exports(&mut self, base_dir: &str, value: &Value) { + if let Value::Object(map) = value { + let exclusions: Vec<&str> = map + .iter() + .filter(|(key, item)| key.starts_with('.') && is_null_exclusion(item)) + .map(|(key, _)| key.as_str()) + .collect(); + for (key, item) in map { + if is_null_exclusion(item) { + continue; + } + let export_key = key.starts_with('.').then_some(key.as_str()); + let active_exclusions = if export_key.is_some() { + exclusions.as_slice() + } else { + &[] + }; + self.collect_export_target(base_dir, export_key, active_exclusions, item); + } + return; + } + self.collect_export_target(base_dir, None, &[], value); + } + + fn collect_export_target( + &mut self, + base_dir: &str, + export_key: Option<&str>, + exclusions: &[&str], + value: &Value, + ) { + match value { + Value::String(target) if target.contains('*') => { + self.resolve_wildcard_export(base_dir, target, export_key, exclusions); + } + Value::String(target) => self.resolve_source_target(base_dir, target), + Value::Array(items) => { + for item in items { + self.collect_export_target(base_dir, export_key, exclusions, item); + } + } + Value::Object(map) => { + for item in map.values() { + self.collect_export_target(base_dir, export_key, exclusions, item); + } + } + _ => {} + } + } + + fn resolve_bin_target(&mut self, base_dir: &str, raw: &str) { + let Some(candidate) = normalize_entry_path(base_dir, raw) else { + return; + }; + if is_nested_candidate(base_dir, &candidate) + && self.file_set.contains(candidate.as_str()) + && (is_ts_source_file(&candidate, self.extensions) || has_no_extension(&candidate)) + { + self.entries.insert(candidate); + return; + } + self.resolve_source_candidate(base_dir, &candidate); + } + + fn resolve_source_target(&mut self, base_dir: &str, raw: &str) { + if let Some(candidate) = normalize_entry_path(base_dir, raw) { + self.resolve_source_candidate(base_dir, &candidate); + } + } + + fn resolve_source_candidate(&mut self, base_dir: &str, candidate: &str) { + if is_declaration_file(candidate) { + return; + } + let allow_file = is_nested_candidate(base_dir, candidate); + if allow_file + && self.file_set.contains(candidate) + && is_ts_source_file(candidate, self.extensions) + { + self.entries.insert(candidate.to_owned()); + return; + } + if allow_file && let Some(aliased) = self.resolve_output_alias(candidate) { + self.entries.insert(aliased); + return; + } + if let Some(expanded) = self.resolve_extension_or_index(candidate, allow_file) { + self.entries.insert(expanded); + } + } + + fn resolve_output_alias(&self, candidate: &str) -> Option { + for (output_ext, source_exts) in OUTPUT_TO_SOURCE_ALIASES { + let Some(stem) = candidate.strip_suffix(output_ext) else { + continue; + }; + for source_ext in source_exts { + let aliased = format!("{stem}{source_ext}"); + if self.file_set.contains(aliased.as_str()) && !is_declaration_file(&aliased) { + return Some(aliased); + } + } + } + None + } + + fn resolve_extension_or_index(&self, candidate: &str, allow_extension: bool) -> Option { + if allow_extension { + for ext in self.extensions { + let with_ext = format!("{candidate}.{ext}"); + if self.file_set.contains(with_ext.as_str()) && !is_declaration_file(&with_ext) { + return Some(with_ext); + } + } + } + for ext in self.extensions { + let index_file = format!("{candidate}/index.{ext}"); + if self.file_set.contains(index_file.as_str()) { + return Some(index_file); + } + } + None + } + + fn resolve_wildcard_export( + &mut self, + base_dir: &str, + raw: &str, + export_key: Option<&str>, + exclusions: &[&str], + ) { + let Some((prefix, suffix)) = wildcard_prefix(base_dir, raw) else { + return; + }; + let key_parts = export_key.and_then(split_single_wildcard); + for path in self.paths { + if is_within_base_dir(base_dir, path) + && let Some(matched_suffix) = wildcard_suffix_match(path, &prefix, suffix) + && path.len() > prefix.len() + matched_suffix.len() + && is_ts_source_file(path, self.extensions) + && !is_excluded_export(path, &prefix, matched_suffix, key_parts, exclusions) + { + self.entries.insert(path.clone()); + } + } + } +} + +fn is_null_exclusion(value: &Value) -> bool { + match value { + Value::Null => true, + Value::Array(items) => !items.is_empty() && items.iter().all(is_null_exclusion), + Value::Object(map) => !map.is_empty() && map.values().all(is_null_exclusion), + _ => false, + } +} + +fn is_nested_candidate(base_dir: &str, candidate: &str) -> bool { + base_dir.is_empty() || candidate != base_dir +} + +fn is_within_base_dir(base_dir: &str, path: &str) -> bool { + base_dir.is_empty() + || path + .strip_prefix(base_dir) + .is_some_and(|rest| rest.starts_with('/')) +} + +fn split_single_wildcard(pattern: &str) -> Option<(&str, &str)> { + let (prefix, suffix) = pattern.split_once('*')?; + (!suffix.contains('*')).then_some((prefix, suffix)) +} + +fn has_parent_segment(path: &str) -> bool { + path.split('/').any(|segment| segment == "..") +} + +fn ensure_wildcard_slash(base_dir: &str, prefix_raw: &str, normalized_prefix: String) -> String { + if !normalized_prefix.is_empty() && (prefix_raw.ends_with('/') || normalized_prefix == base_dir) + { + format!("{normalized_prefix}/") + } else { + normalized_prefix + } +} + +fn wildcard_prefix<'a>(base_dir: &str, raw: &'a str) -> Option<(String, &'a str)> { + let trimmed = raw.trim(); + if trimmed.starts_with('/') || trimmed.contains('\\') { + return None; + } + let (prefix_raw, suffix) = split_single_wildcard(trimmed)?; + if has_parent_segment(prefix_raw) || has_parent_segment(suffix) { + return None; + } + let normalized_prefix = normalize_relative_path(base_dir, prefix_raw)?; + let prefix = ensure_wildcard_slash(base_dir, prefix_raw, normalized_prefix); + Some((prefix, suffix)) +} + +fn is_excluded_export( + path: &str, + prefix: &str, + matched_suffix: &str, + key_parts: Option<(&str, &str)>, + exclusions: &[&str], +) -> bool { + let Some((key_prefix, key_suffix)) = key_parts else { + return false; + }; + if exclusions.is_empty() { + return false; + } + let captured = &path[prefix.len()..path.len() - matched_suffix.len()]; + let subpath = format!("{key_prefix}{captured}{key_suffix}"); + exclusions.iter().any(|&exclusion| { + matches_exclusion(&subpath, exclusion, key_prefix.len(), key_suffix.len()) + }) +} + +fn matches_exclusion( + subpath: &str, + exclusion: &str, + key_prefix_len: usize, + key_suffix_len: usize, +) -> bool { + let Some((excl_prefix, excl_suffix)) = split_single_wildcard(exclusion) else { + return subpath == exclusion; + }; + let more_specific = excl_prefix.len() > key_prefix_len + || (excl_prefix.len() == key_prefix_len && excl_suffix.len() >= key_suffix_len); + more_specific + && subpath.starts_with(excl_prefix) + && subpath.ends_with(excl_suffix) + && subpath.len() >= excl_prefix.len() + excl_suffix.len() +} + +fn wildcard_suffix_match<'a>(path: &str, prefix: &str, suffix: &'a str) -> Option<&'a str> { + if !path.starts_with(prefix) { + return None; + } + if path.ends_with(suffix) { + return Some(suffix); + } + for (output_ext, source_exts) in OUTPUT_TO_SOURCE_ALIASES { + if suffix == output_ext { + for source_ext in source_exts { + if path.ends_with(source_ext) { + return Some(source_ext); + } + } + } + } + None +} + +fn normalize_entry_path(base_dir: &str, raw: &str) -> Option { + let trimmed = raw.trim(); + if trimmed.is_empty() + || trimmed.starts_with('/') + || trimmed.contains('\\') + || has_parent_segment(trimmed) + { + return None; + } + let normalized = normalize_relative_path(base_dir, trimmed)?; + (!normalized.is_empty()).then_some(normalized) +} + +fn is_declaration_file(path: &str) -> bool { + path.ends_with(".d.ts") || path.ends_with(".d.mts") || path.ends_with(".d.cts") +} + +fn is_ts_source_file(path: &str, extensions: &[&str]) -> bool { + if is_declaration_file(path) { + return false; + } + let file_name = path.rsplit_once('/').map_or(path, |(_, name)| name); + let Some((_, ext)) = file_name.rsplit_once('.') else { + return false; + }; + extensions.contains(&ext) +} + +fn has_no_extension(path: &str) -> bool { + let file_name = path.rsplit_once('/').map_or(path, |(_, name)| name); + !file_name.contains('.') +} diff --git a/plugins/languages/ts/src/lib.rs b/plugins/languages/ts/src/lib.rs index c40cc53..a3fddf7 100644 --- a/plugins/languages/ts/src/lib.rs +++ b/plugins/languages/ts/src/lib.rs @@ -1,5 +1,6 @@ #![forbid(unsafe_code)] +mod entry_points; mod functions; mod nesting; mod resolution; @@ -21,6 +22,7 @@ use oxc_parser::Parser; use oxc_parser::config::TokensParserConfig; use oxc_span::SourceType; +use crate::entry_points::entry_points as discover_entry_points; use crate::functions::{CodeLines, functions}; use crate::resolution::{ProjectResolver, manifest_paths}; use crate::runtime_imports::runtime_import_specifiers; @@ -78,8 +80,8 @@ impl Guest for TypeScriptAndJavaScript { Vec::new() } - fn entry_points(_repository_paths: Vec, _manifests: Vec) -> Vec { - Vec::new() + fn entry_points(repository_paths: Vec, manifests: Vec) -> Vec { + discover_entry_points(&repository_paths, &manifests, &EXTENSIONS) } fn reference_ranges() -> Vec { diff --git a/plugins/languages/ts/tests/entry_points.rs b/plugins/languages/ts/tests/entry_points.rs new file mode 100644 index 0000000..cacc1a6 --- /dev/null +++ b/plugins/languages/ts/tests/entry_points.rs @@ -0,0 +1,299 @@ +use codeint_lang_ts::TypeScriptAndJavaScript; +use codeint_model::{LanguagePlugin, Manifest, RepoPath}; + +#[test] +fn extracts_main_module_bin_and_exports_from_package_json() { + let repo: Vec = [ + "package.json", + "tsconfig.json", + "pnpm-workspace.yaml", + "src/index.ts", + "src/esm.mts", + "src/cli.ts", + "src/alt-cli.js", + "src/button.tsx", + "src/fallback.ts", + "src/features/auth.ts", + "src/features/billing.ts", + "src/features/auth.d.ts", + "dist/index.d.ts", + "bin/tool", + "packages/cli/package.json", + "packages/cli/src/entry.ts", + "packages/cli/src/esm.ts", + "packages/cli/src/dir/index.ts", + "packages/cli/bin/run.mjs", + ] + .map(|p| RepoPath::new(p).unwrap()) + .into(); + let root_pkg = r#"{ + "name": "demo", + "main": "./src/index.ts", + "module": "./src/esm.mts", + "bin": { + "demo-cli": "./src/cli.ts", + "alt": "src/alt-cli.js", + "raw": "./bin/tool", + "missing": "./bin/absent.js" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./src/index.ts", + "default": "./dist/missing.js" + }, + "./button": { + "bun": "./src/button.tsx" + }, + "./fallback": ["./dist/nope.js", "./src/fallback.ts"], + "./features/*": "./src/features/*.js", + "./internal/*": null, + "./package.json": "./package.json", + "./escape": "../outside.ts", + "./abs": "/etc/passwd" + } + }"#; + let cli_pkg = r#"{ + "name": "@demo/cli", + "main": "./src/entry.js", + "module": "./src/esm", + "bin": "./bin/run.mjs", + "exports": "./src/dir" + }"#; + let manifests = vec![ + Manifest { + path: "package.json".into(), + text: root_pkg.into(), + }, + Manifest { + path: "tsconfig.json".into(), + text: r#"{"compilerOptions": {}}"#.into(), + }, + Manifest { + path: "pnpm-workspace.yaml".into(), + text: "packages:\n - packages/*\n".into(), + }, + Manifest { + path: "packages/cli/package.json".into(), + text: cli_pkg.into(), + }, + ]; + + let expected: Vec = [ + "bin/tool", + "packages/cli/bin/run.mjs", + "packages/cli/src/dir/index.ts", + "packages/cli/src/entry.ts", + "packages/cli/src/esm.ts", + "src/alt-cli.js", + "src/button.tsx", + "src/cli.ts", + "src/esm.mts", + "src/fallback.ts", + "src/features/auth.ts", + "src/features/billing.ts", + "src/index.ts", + ] + .into_iter() + .map(|entry| RepoPath::new(entry).unwrap()) + .collect(); + assert_eq!( + TypeScriptAndJavaScript + .entry_points(&repo, manifests) + .expect("valid entry points"), + expected + ); +} + +#[test] +fn returns_empty_when_package_json_declares_no_entry_points_or_is_invalid() { + let repo: Vec = ["package.json", "src/index.ts", "src/helper.ts"] + .map(|p| RepoPath::new(p).unwrap()) + .into(); + for manifests in [ + vec![Manifest { + path: "package.json".into(), + text: r#"{"name": "webapp", "dependencies": {"react": "19.0.0"}}"#.into(), + }], + vec![Manifest { + path: "package.json".into(), + text: "{not valid json".into(), + }], + Vec::new(), + ] { + assert!( + TypeScriptAndJavaScript + .entry_points(&repo, manifests) + .expect("valid empty result") + .is_empty() + ); + } +} + +fn discover_ts(paths: &[&str], manifests: &[(&str, &str)]) -> Vec { + let repo: Vec = paths.iter().map(|p| RepoPath::new(*p).unwrap()).collect(); + let specs = manifests + .iter() + .map(|(path, text)| Manifest { + path: (*path).into(), + text: (*text).into(), + }) + .collect(); + TypeScriptAndJavaScript + .entry_points(&repo, specs) + .unwrap() + .into_iter() + .map(|entry| entry.as_str().to_owned()) + .collect() +} + +#[test] +fn rejects_parent_traversal_in_nested_package_json_entries() { + let app_pkg = r#"{ + "name": "@demo/app", + "main": "../other/secret.ts", + "module": "./../other/secret.ts", + "bin": { "bad": "../other/bin.js" }, + "exports": { + ".": "./src/index.ts", + "./escape": "../other/secret.ts", + "./wild/*": "../other/wild/*.ts", + "./dotdot/*": "./../*.ts" + } + }"#; + let found = discover_ts( + &[ + "packages/app/package.json", + "packages/app/src/index.ts", + "packages/other/secret.ts", + "packages/other/bin.js", + "packages/other/wild/a.ts", + ], + &[("packages/app/package.json", app_pkg)], + ); + assert_eq!(found, ["packages/app/src/index.ts"]); +} + +#[test] +fn subtracts_null_excluded_subpaths_from_wildcard_exports() { + let root_pkg = r#"{ + "name": "demo", + "exports": { + "./*": { "import": "./src/*.js" }, + "./secret": null, + "./internal/*": null, + "./internal/public/*": "./src/internal/public/*.ts" + } + }"#; + let lib_pkg = r#"{ + "name": "@demo/lib", + "exports": { + "./*.js": "./src/*.ts", + "./private/*.js": null + } + }"#; + let found = discover_ts( + &[ + "package.json", + "src/public.ts", + "src/secret.ts", + "src/internal/helper.ts", + "src/internal/deep/util.ts", + "src/internal/public/api.ts", + "packages/lib/package.json", + "packages/lib/src/open.ts", + "packages/lib/src/private/hidden.ts", + ], + &[ + ("package.json", root_pkg), + ("packages/lib/package.json", lib_pkg), + ], + ); + assert_eq!( + found, + [ + "packages/lib/src/open.ts", + "src/internal/public/api.ts", + "src/public.ts", + ] + ); +} + +fn assert_discovered(paths: &[&str], manifests: &[(&str, &str)], expected: &[&str]) { + assert_eq!(discover_ts(paths, manifests), expected); +} + +#[test] +fn wildcard_exports_in_nested_package_do_not_escape_to_sibling_directories() { + assert_discovered( + &[ + "packages/app/package.json", + "packages/app/index.ts", + "packages/app-other/secret.ts", + "packages/dot/package.json", + "packages/dot/local.ts", + "packages/dot-other/secret.ts", + ], + &[ + ( + "packages/app/package.json", + r#"{"name":"@demo/app","exports":{"./*":"*.ts"}}"#, + ), + ( + "packages/dot/package.json", + r#"{"name":"@demo/dot","exports":{"./*":"./.*.ts"}}"#, + ), + ], + &["packages/app/index.ts", "packages/dot/local.ts"], + ); +} + +#[test] +fn subtracts_nested_conditional_and_array_null_exclusions_from_wildcard_exports() { + let pkg = r#"{ + "name": "demo", + "exports": { + "./*": "./src/*.ts", + "./internal/*": { "default": null }, + "./dual/*": { "import": null, "require": null }, + "./blocked/*": [null], + "./mixed/*": { "import": null, "default": "./src/mixed/*.ts" } + } + }"#; + assert_discovered( + &[ + "package.json", + "src/public.ts", + "src/internal/secret.ts", + "src/dual/hidden.ts", + "src/blocked/nope.ts", + "src/mixed/ok.ts", + ], + &[("package.json", pkg)], + &["src/mixed/ok.ts", "src/public.ts"], + ); +} + +#[test] +fn nested_package_dot_main_resolves_package_index_instead_of_sibling_file() { + for (manifest, pkg_path, sibling, index) in [ + ( + r#"{"name":"@demo/app","main":"./"}"#, + "packages/app/package.json", + "packages/app.ts", + "packages/app/index.ts", + ), + ( + r#"{"name":"@demo/lib","main":".","bin":"./"}"#, + "packages/lib/package.json", + "packages/lib.ts", + "packages/lib/index.ts", + ), + ] { + assert_discovered( + &[pkg_path, sibling, index], + &[(pkg_path, manifest)], + &[index], + ); + } +} diff --git a/schema/codeint.schema.json b/schema/codeint.schema.json index 0b6f495..7d04480 100644 --- a/schema/codeint.schema.json +++ b/schema/codeint.schema.json @@ -63,6 +63,13 @@ "duplication": { "$ref": "#/$defs/DuplicationConfigFile", "description": "Settings for Duplication detection, including opt-in shingle-based near-clone detection. Exact Clone groups remain the default when omitted." + }, + "entry_points": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Globs of repository-relative paths treated as additional Production entry points for Orphan files detection, combined with manifest-discovered entry points." } }, "title": "codeint.json", @@ -170,6 +177,13 @@ "description": "The highest Boundaries ratio, from 0 to 1.", "minimum": 0, "maximum": 1 + }, + "orphan_files": { + "type": "number", + "format": "double", + "description": "The highest Orphan files ratio, from 0 to 1.", + "minimum": 0, + "maximum": 1 } }, "additionalProperties": { @@ -205,6 +219,10 @@ "$ref": "#/$defs/RegressionLimitSetting", "description": "The Regression limit of Boundaries in every Source set." }, + "orphan_files": { + "$ref": "#/$defs/RegressionLimitSetting", + "description": "The Regression limit of Orphan files in every Source set." + }, "production": { "$ref": "#/$defs/MetricRegressionLimits", "description": "The Regression limits of the Production Source set." @@ -273,6 +291,10 @@ "boundaries": { "$ref": "#/$defs/RegressionLimitSetting", "description": "The Regression limit of Boundaries in this Source set." + }, + "orphan_files": { + "$ref": "#/$defs/RegressionLimitSetting", + "description": "The Regression limit of Orphan files in this Source set." } }, "additionalProperties": {