#![allow(
clippy::print_stderr,
reason = "human stderr notes for slow churn and file-score failures are preserved from the health pipeline"
)]
use std::time::Instant;
use colored::Colorize;
use fallow_config::ResolvedConfig;
use fallow_output::FileHealthScore;
use crate::results::DeadCodeAnalysisArtifacts;
use super::filters::filter_coverage_gaps;
use super::hotspots;
use super::scoring::{self, compute_file_scores};
use super::test_reach::SharedTestReach;
use super::{HealthError, HealthExecutionOptions};
type FileScoreResult = (Option<scoring::FileScoreOutput>, Option<usize>, Option<f64>);
type FileScoresAndChurn = (FileScoreResult, f64, Option<hotspots::ChurnFetchResult>);
#[derive(Clone, Copy)]
pub struct FileScoresAndChurnInput<'a> {
pub(crate) opts: &'a HealthExecutionOptions<'a>,
pub(crate) config: &'a ResolvedConfig,
pub(crate) modules: &'a [crate::source::ModuleInfo],
pub(crate) file_paths:
&'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
pub(crate) changed_files: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
pub(crate) ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
pub(crate) ignore_set: &'a globset::GlobSet,
pub(crate) istanbul_coverage: Option<&'a scoring::IstanbulCoverage>,
pub(crate) needs_file_scores: bool,
pub(crate) threshold_resolver: &'a super::threshold_overrides::ThresholdOverrideResolver,
pub(crate) enforce_crap: bool,
pub(crate) test_reach: &'a SharedTestReach<'a>,
}
pub fn compute_file_scores_and_churn<T>(
input: FileScoresAndChurnInput<'_>,
before_scores: impl FnOnce() -> Result<(T, Option<DeadCodeAnalysisArtifacts>), HealthError>,
) -> Result<(FileScoresAndChurn, T), HealthError> {
let needs_churn = input.opts.hotspots || input.opts.targets;
std::thread::scope(|s| {
let churn_handle = needs_churn
.then(|| s.spawn(|| hotspots::fetch_churn_data(input.opts, &input.config.cache_dir)));
let (before, precomputed_for_scores) = before_scores()?;
let t = Instant::now();
let score_result = if input.needs_file_scores {
compute_filtered_file_scores(FileScoreInput {
config: input.config,
modules: input.modules,
file_paths: input.file_paths,
changed_files: input.changed_files,
ws_roots: input.ws_roots,
ignore_set: input.ignore_set,
istanbul_coverage: input.istanbul_coverage,
pre_computed: precomputed_for_scores,
crap_thresholds: scoring::CrapScoreThresholds {
resolver: input.threshold_resolver,
enforce_crap: input.enforce_crap,
},
with_static_links: needs_churn,
test_reach: input.test_reach,
shallow_directories: input.opts.shallow_directories,
})?
} else {
(None, None, None)
};
let fs_ms = t.elapsed().as_secs_f64() * 1000.0;
let churn = match churn_handle {
Some(handle) => handle
.join()
.map_err(|_| HealthError::message("churn thread panicked", 2))?,
None => None,
};
Ok(((score_result, fs_ms, churn), before))
})
}
pub fn print_slow_churn_note(
opts: &HealthExecutionOptions<'_>,
churn_fetch: Option<&hotspots::ChurnFetchResult>,
) {
if let Some(cf) = churn_fetch
&& !cf.cache_hit
&& !opts.no_cache
&& !opts.quiet
&& cf.git_log_ms > 500.0
{
eprintln!(
"{}",
format!(
" note: git churn analysis took {:.1}s (cached for next run at same HEAD)",
cf.git_log_ms / 1000.0
)
.dimmed()
);
}
}
pub fn health_file_scores_slice(
score_output: Option<&scoring::FileScoreOutput>,
) -> &[FileHealthScore] {
score_output.map_or(&[] as &[_], |output| output.scores.as_slice())
}
struct FileScoreInput<'a> {
config: &'a ResolvedConfig,
modules: &'a [crate::source::ModuleInfo],
file_paths: &'a rustc_hash::FxHashMap<crate::discover::FileId, &'a std::path::PathBuf>,
changed_files: Option<&'a rustc_hash::FxHashSet<std::path::PathBuf>>,
ws_roots: Option<&'a crate::workspace_scope::WorkspaceScope>,
ignore_set: &'a globset::GlobSet,
istanbul_coverage: Option<&'a scoring::IstanbulCoverage>,
pre_computed: Option<DeadCodeAnalysisArtifacts>,
crap_thresholds: scoring::CrapScoreThresholds<'a>,
with_static_links: bool,
test_reach: &'a SharedTestReach<'a>,
shallow_directories: bool,
}
fn compute_filtered_file_scores(input: FileScoreInput<'_>) -> Result<FileScoreResult, HealthError> {
let mut analysis_output = if let Some(pre) = input.pre_computed {
pre
} else {
crate::dead_code::analyze_with_parse_result(input.config, input.modules)
.map_err(|e| HealthError::message(format!("analysis failed: {e}"), 2))?
};
crate::effective_severity::apply_prop_drilling_severities(
&mut analysis_output.results,
input.config,
);
let shallow_directories = input
.shallow_directories
.then_some(analysis_output.graph.as_ref())
.flatten()
.map(|graph| {
super::shallow_directories::find_shallow_directories(
&super::shallow_directories::ShallowDirectoriesInput {
graph: graph.as_graph(),
modules: input.modules,
root: &input.config.root,
config: &input.config.health.shallow_directories,
},
)
})
.map(|mut report| {
scope_shallow_directories(
&mut report,
&input.config.root,
input.ws_roots,
input.ignore_set,
input.changed_files,
);
report
});
match compute_file_scores(
scoring::FileScoreComputeInput {
modules: input.modules,
file_paths: input.file_paths,
changed_files: input.changed_files,
istanbul_coverage: input.istanbul_coverage,
root: &input.config.root,
crap_thresholds: input.crap_thresholds,
with_static_links: input.with_static_links,
test_reach: input.test_reach.get(),
},
analysis_output,
) {
Ok(mut output) => {
output.shallow_directories = shallow_directories;
if let Some(ws) = input.ws_roots {
output.scores.retain(|s| ws.contains(&s.path));
}
if !input.ignore_set.is_empty() {
output.scores.retain(|s| {
let relative = s.path.strip_prefix(&input.config.root).unwrap_or(&s.path);
!input.ignore_set.is_match(relative)
});
}
filter_coverage_gaps(
&mut output.coverage.report,
&mut output.coverage.runtime_paths,
input.config,
input.changed_files,
input.ws_roots,
input.ignore_set,
);
let total_scored = output.scores.len();
let avg = if total_scored > 0 {
let sum: f64 = output.scores.iter().map(|s| s.maintainability_index).sum();
Some((sum / total_scored as f64 * 10.0).round() / 10.0)
} else {
None
};
Ok((Some(output), Some(total_scored), avg))
}
Err(e) => {
eprintln!("Warning: failed to compute file scores: {e}");
super::diagnostics::record_health_diagnostic(
&input.config.root,
None,
fallow_types::workspace::WorkspaceDiagnosticKind::FileScoresUnavailable {
error: e,
},
);
Ok((None, Some(0), None))
}
}
}
fn scope_shallow_directories(
report: &mut fallow_output::ShallowDirectoriesReport,
root: &std::path::Path,
ws_roots: Option<&crate::workspace_scope::WorkspaceScope>,
ignore_set: &globset::GlobSet,
changed_files: Option<&rustc_hash::FxHashSet<std::path::PathBuf>>,
) {
report.directories.retain(|dir| {
let absolute = root.join(&dir.path);
ws_roots.is_none_or(|ws| ws.contains(&absolute))
&& !super::shallow_directories::matches_directory(ignore_set, &dir.path)
&& changed_files
.is_none_or(|changed| changed.iter().any(|file| file.starts_with(&absolute)))
});
report.total = report.directories.len();
}