use std::path::{Path, PathBuf};
use fallow_config::{AuditGate, AuditWorsened, ResolvedConfig, RulesConfig, Severity};
use fallow_engine::changed_files::RenamedFile;
use fallow_engine::module_graph::relative_key_path;
use fallow_types::duplicates::CloneGroup;
use rustc_hash::FxHashSet;
use super::clone_regions::{
CloneRegionBase, CloneRegionHead, grade_clone_regions, has_unmatched_group,
};
use super::{AuditAnalysesView, AuditKeySnapshot};
use crate::audit_keys::{
AuditComparison, AuditDomainLedger, ChangedPaths, DeadCodeAuditLedger,
classify_complexity_attribution_against_all_with_moves, complexity_ledger_keys,
dead_code_audit_ledger, dupe_group_key, styling_ledger_keys, styling_ledger_keys_with_diff,
};
use crate::audit_moved::{MovedDeadCode, moved_dead_code_keys};
use crate::diff_risk::clones::{AcceptedCloneGroup, BaseCloneGroup};
use crate::{AuditAttribution, AuditSummary, AuditVerdict};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DupeDemotionDiffSource {
Shared(String),
Worktree,
Skipped,
}
impl DupeDemotionDiffSource {
#[must_use]
pub fn label(&self, base_ref: &str) -> String {
match self {
Self::Shared(label) => label.clone(),
Self::Worktree => format!("merge-base worktree diff vs {base_ref}"),
Self::Skipped => "skipped: no diff available".to_string(),
}
}
}
#[derive(Clone, Copy)]
pub struct SharedDiff<'a> {
pub index: &'a fallow_output::DiffIndex,
pub label: &'a str,
}
pub struct RunChange<'a> {
pub root: &'a Path,
pub base_ref: &'a str,
pub shared: Option<SharedDiff<'a>>,
pub changed_files: &'a FxHashSet<PathBuf>,
worktree: std::cell::OnceCell<Option<fallow_output::DiffIndex>>,
}
impl<'a> RunChange<'a> {
#[must_use]
pub const fn new(
root: &'a Path,
base_ref: &'a str,
shared: Option<SharedDiff<'a>>,
changed_files: &'a FxHashSet<PathBuf>,
) -> Self {
Self {
root,
base_ref,
shared,
changed_files,
worktree: std::cell::OnceCell::new(),
}
}
pub(super) fn diff_index(&self) -> Option<&fallow_output::DiffIndex> {
if let Some(shared) = self.shared {
return Some(shared.index);
}
self.worktree
.get_or_init(|| {
fallow_engine::changed_files::try_get_changed_diff(self.root, self.base_ref)
.ok()
.map(|diff| fallow_output::DiffIndex::from_unified_diff(&diff))
})
.as_ref()
}
}
fn added_line_names(
diff: &fallow_output::DiffIndex,
root: &Path,
path: &str,
symbol: &str,
) -> bool {
let file = root.join(path);
let Some(added) = diff
.key_for(&file, root)
.and_then(|key| diff.added_lines_in(&key))
else {
return false;
};
let Ok(source) = std::fs::read_to_string(&file) else {
return false;
};
source
.lines()
.zip(1_u64..)
.any(|(line, number)| added.contains(&number) && line.contains(symbol))
}
#[must_use]
pub fn compare(
view: &AuditAnalysesView<'_>,
base: Option<&AuditKeySnapshot>,
syntactic_fallback: bool,
change: &RunChange<'_>,
) -> AuditComparison {
let dead_code =
view.dead_code
.as_ref()
.map_or_else(DeadCodeAuditLedger::default, |dead_code| {
let base_keys = base.map(|snapshot| {
if syntactic_fallback {
snapshot
.syntactic_dead_code
.as_ref()
.unwrap_or(&snapshot.dead_code)
} else {
&snapshot.dead_code
}
});
let mut ledger = dead_code_audit_ledger(
dead_code.results,
dead_code.root,
dead_code.config,
base_keys,
);
if syntactic_fallback && let Some(head_syntactic) = dead_code.syntactic_keys {
ledger.demote_unattributable_introductions(head_syntactic);
}
if let Some(base_keys) = base_keys {
let moved = moved_dead_code_keys(
&ledger,
&MovedDeadCode {
base: base_keys,
changed: &changed_paths_of(change.changed_files, dead_code.root),
also_reported: dead_code.syntactic_keys.filter(|_| syntactic_fallback),
added_line_names: &|path, symbol| {
change.diff_index().is_some_and(|index| {
added_line_names(index, dead_code.root, path, symbol)
})
},
},
);
ledger.inherit_introductions(&moved);
}
ledger
});
let health_classes =
view.health
.as_ref()
.zip(base)
.map_or_else(Vec::new, |(health, snapshot)| {
let changed_paths = changed_paths_of(change.changed_files, health.root);
classify_complexity_attribution_against_all_with_moves(
&health.report.findings,
health.root,
std::iter::once(&snapshot.health).chain(&snapshot.inherited_health),
&changed_paths,
)
});
let health = view
.health
.as_ref()
.map_or_else(AuditDomainLedger::default, |health| {
let findings = &health.report.findings;
let keys = complexity_ledger_keys(findings, health.root);
let introduced = (0..findings.len()).map(|index| {
health_classes
.get(index)
.is_some_and(|class| class.introduced)
});
AuditDomainLedger::from_classified(keys.into_iter().zip(introduced), base.is_some())
});
let dupes = AuditDomainLedger::compare(
view.duplication.iter().flat_map(|duplication| {
duplication
.clone_groups
.iter()
.map(|group| dupe_group_key(group, duplication.root))
}),
base.map(|snapshot| &snapshot.dupes),
);
let styling = AuditDomainLedger::compare(
view.health
.iter()
.flat_map(|health| styling_ledger_keys(&health.report.styling_findings, health.root)),
base.map(|snapshot| &snapshot.styling),
);
AuditComparison {
dead_code,
health,
health_classes,
dupes,
dupe_regions: super::clone_regions::CloneRegions::default(),
styling,
}
}
fn changed_paths_of(changed_files: &FxHashSet<PathBuf>, root: &Path) -> ChangedPaths {
let mut paths = ChangedPaths::default();
for path in changed_files {
let key = relative_key_path(path, root);
if !path.exists() {
paths.deleted.insert(key.clone());
}
paths.changed.insert(key);
}
paths
}
#[derive(Clone, Copy)]
pub struct DupeBase<'a> {
pub keys: &'a FxHashSet<String>,
pub groups: &'a [BaseCloneGroup],
pub accepted: &'a [AcceptedCloneGroup],
pub renames: &'a [RenamedFile],
}
pub fn attribute_clone_regions(
comparison: &mut AuditComparison,
view: &AuditAnalysesView<'_>,
change: &RunChange<'_>,
base: Option<DupeBase<'_>>,
) -> Option<DupeDemotionDiffSource> {
let (Some(duplication), Some(base)) = (view.duplication.as_ref(), base) else {
return None;
};
let head = CloneRegionHead {
groups: &duplication.clone_groups,
ignored: duplication.ignored_groups,
root: duplication.root,
min_lines: duplication.config.duplicates.min_lines,
};
let changed = changed_paths_of(change.changed_files, duplication.root);
let region_base = CloneRegionBase {
keys: base.keys,
groups: base.groups,
accepted: base.accepted,
renames: base.renames,
changed: &changed,
};
let (diff, source) = if has_unmatched_group(&head, base.keys) {
match change.diff_index() {
Some(index) => (
Some(index),
Some(
change
.shared
.map_or(DupeDemotionDiffSource::Worktree, |shared| {
DupeDemotionDiffSource::Shared(shared.label.to_owned())
}),
),
),
None => (None, Some(DupeDemotionDiffSource::Skipped)),
}
} else {
(None, None)
};
let regions = grade_clone_regions(&head, ®ion_base, diff);
let keys: Vec<String> = duplication
.clone_groups
.iter()
.map(|group| dupe_group_key(group, duplication.root))
.collect();
let demoted: FxHashSet<String> = keys
.iter()
.enumerate()
.filter(|(index, _)| regions.group_demoted(*index))
.map(|(_, key)| key.clone())
.collect();
let mut ledger = AuditDomainLedger::from_classified(
keys.into_iter().enumerate().map(|(index, key)| {
let flagged = regions.group_introduced(index) || regions.group_demoted(index);
(key, flagged)
}),
true,
);
ledger.demote_introductions(&demoted);
comparison.dupes = ledger;
comparison.dupe_regions = regions;
source
}
pub fn realign_styling_introductions(
comparison: &mut AuditComparison,
view: &AuditAnalysesView<'_>,
base: Option<&AuditKeySnapshot>,
change: &RunChange<'_>,
) {
let (Some(base), Some(health)) = (base, view.health.as_ref()) else {
return;
};
if comparison.styling.introduced_count() == 0 {
return;
}
let Some(index) = change.diff_index() else {
return;
};
comparison.styling = AuditDomainLedger::compare(
styling_ledger_keys_with_diff(&health.report.styling_findings, health.root, Some(index)),
Some(&base.styling),
);
}
#[must_use]
pub fn styling_rule_severity(rules: &RulesConfig, code: &str) -> Severity {
match code {
"css-token-drift" => rules.css_token_drift,
"css-duplicate-block" => rules.css_duplicate_block,
"css-selector-complexity" => rules.css_selector_complexity,
"css-dead-surface" => rules.css_dead_surface,
"css-broken-reference" => rules.css_broken_reference,
_ => Severity::Warn,
}
}
#[must_use]
pub fn styling_finding_gates(rules: &RulesConfig, code: &str) -> bool {
styling_rule_severity(rules, code) == Severity::Error
}
fn clone_group_severity(config: &ResolvedConfig, group: &CloneGroup) -> Severity {
if config.overrides.is_empty() {
return config.rules.introduced_clone_group;
}
group
.instances
.iter()
.map(|instance| {
config
.resolve_rules_for_path(&instance.file)
.introduced_clone_group
})
.max_by_key(|severity| match severity {
Severity::Error => 2,
Severity::Warn => 1,
Severity::Off => 0,
})
.unwrap_or(config.rules.introduced_clone_group)
}
#[must_use]
pub fn outcome(
gate: AuditGate,
worsened: AuditWorsened,
view: &AuditAnalysesView<'_>,
comparison: &AuditComparison,
has_base: bool,
) -> (AuditAttribution, AuditVerdict, AuditSummary) {
let summary = summary(view, comparison);
(
attribution(gate, worsened, comparison, has_base),
verdict(gate, worsened, view, comparison, &summary),
summary,
)
}
fn complexity_verdict_flags(
gate: AuditGate,
worsened: AuditWorsened,
view: &AuditAnalysesView<'_>,
comparison: &AuditComparison,
) -> (bool, bool) {
let new_only = matches!(gate, AuditGate::NewOnly);
let Some(health) = view.health.as_ref() else {
return (false, false);
};
let mut errors = false;
let mut warnings = false;
for (index, (finding, introduced)) in health
.report
.findings
.iter()
.zip(comparison.health.introduced())
.enumerate()
{
let is_worsened = comparison
.health_classes
.get(index)
.is_some_and(crate::audit_keys::ComplexityClass::is_worsened);
let counts = !new_only || introduced || (is_worsened && worsened == AuditWorsened::Error);
if counts {
if finding.blocks() {
errors = true;
} else {
warnings = true;
}
} else if is_worsened {
warnings = true;
}
}
(errors, warnings)
}
fn duplication_verdict_flags(
new_only: bool,
view: &AuditAnalysesView<'_>,
comparison: &AuditComparison,
) -> (bool, bool) {
let Some(duplication) = view.duplication.as_ref() else {
return (false, false);
};
let introduced: Vec<bool> = comparison.dupes.introduced().collect();
let mut errors = false;
let mut warnings = false;
for (index, group) in duplication.clone_groups.iter().enumerate() {
if new_only && !introduced.get(index).copied().unwrap_or(false) {
continue;
}
match clone_group_severity(duplication.config, group) {
Severity::Error => errors = true,
Severity::Warn => warnings = true,
Severity::Off => {}
}
}
(errors, warnings)
}
fn verdict(
gate: AuditGate,
worsened: AuditWorsened,
view: &AuditAnalysesView<'_>,
comparison: &AuditComparison,
summary: &AuditSummary,
) -> AuditVerdict {
let new_only = matches!(gate, AuditGate::NewOnly);
let dead_code_errors = if new_only {
comparison.dead_code.has_introduced_errors()
} else {
dead_code_has_errors(view)
};
let dead_code_warnings = if new_only {
comparison.dead_code.has_introduced_warnings()
} else {
comparison
.dead_code
.records()
.iter()
.any(|record| record.effective_severity == Severity::Warn)
};
let (complexity_errors, complexity_warnings) =
complexity_verdict_flags(gate, worsened, view, comparison);
let styling_errors = view.health.as_ref().is_some_and(|health| {
health
.report
.styling_findings
.iter()
.zip(comparison.styling.introduced())
.any(|(finding, introduced)| {
(!new_only || introduced) && styling_finding_gates(health.rules, &finding.code)
})
});
let (clone_errors, clone_warnings) = duplication_verdict_flags(new_only, view, comparison);
let duplication_findings = if new_only {
comparison.duplication_introduced_count()
} else {
summary.duplication_clone_groups
};
let duplication_errors = view.duplication.as_ref().is_some_and(|duplication| {
duplication_findings > 0
&& duplication.threshold > 0.0
&& duplication.duplication_percentage > duplication.threshold
});
if dead_code_errors || complexity_errors || styling_errors || duplication_errors || clone_errors
{
AuditVerdict::Fail
} else if dead_code_warnings || complexity_warnings || clone_warnings {
AuditVerdict::Warn
} else {
AuditVerdict::Pass
}
}
fn dead_code_has_errors(view: &AuditAnalysesView<'_>) -> bool {
view.dead_code.as_ref().is_some_and(|dead_code| {
fallow_engine::error_severity::has_error_severity_issues(
dead_code.results,
&dead_code.config.rules,
Some(dead_code.config),
false,
)
})
}
fn attribution(
gate: AuditGate,
worsened: AuditWorsened,
comparison: &AuditComparison,
has_base: bool,
) -> AuditAttribution {
if !has_base {
return AuditAttribution {
gate,
worsened,
..AuditAttribution::default()
};
}
AuditAttribution {
gate,
worsened,
complexity_worsened: comparison.complexity_worsened_count(),
dead_code_introduced: comparison.dead_code.introduced_count(),
dead_code_inherited: comparison.dead_code.inherited_count(),
complexity_introduced: comparison.health.introduced_count(),
complexity_inherited: comparison.health.inherited_count(),
duplication_introduced: comparison.duplication_introduced_count(),
duplication_inherited: comparison.duplication_inherited_count(),
}
}
fn summary(view: &AuditAnalysesView<'_>, comparison: &AuditComparison) -> AuditSummary {
AuditSummary {
dead_code_issues: comparison.dead_code.visible_count(),
dead_code_has_errors: dead_code_has_errors(view),
dead_code_skipped: view.dead_code.is_none(),
complexity_skipped: view.health.is_none(),
duplication_skipped: view.duplication.is_none(),
complexity_findings: view
.health
.as_ref()
.map_or(0, |health| health.report.findings.len()),
max_cyclomatic: view.health.as_ref().and_then(|health| {
health
.report
.findings
.iter()
.map(|finding| finding.cyclomatic)
.max()
}),
duplication_clone_groups: view
.duplication
.as_ref()
.map_or(0, |duplication| duplication.clone_groups.len()),
}
}