use std::path::{Path, PathBuf};
use fallow_output::ThresholdOverrideDimension;
use rustc_hash::{FxHashMap, FxHashSet};
#[derive(Debug, Clone, Copy)]
pub(super) struct GlobalHealthThresholds {
pub(super) cyclomatic: u16,
pub(super) cognitive: u16,
pub(super) crap: f64,
pub(super) unit_size: u32,
}
#[derive(Debug, Clone, Copy)]
pub(super) struct AppliedHealthThresholds {
pub(super) effective: fallow_output::HealthEffectiveThresholds,
pub(super) override_index: Option<usize>,
pub(super) comment_line: Option<u32>,
}
impl AppliedHealthThresholds {
#[must_use]
pub(super) const fn is_overridden(&self) -> bool {
self.override_index.is_some() || self.comment_line.is_some()
}
}
pub(super) struct CompiledInlineOverride {
pub(super) comment_line: u32,
pub(super) configured: fallow_output::HealthConfiguredThresholds,
pub(super) reason: String,
}
struct CompiledThresholdOverride {
index: usize,
matchers: globset::GlobSet,
functions: Vec<String>,
configured: fallow_output::HealthConfiguredThresholds,
reason: Option<String>,
}
pub(super) struct ThresholdOverrideMatch<'a> {
entry: &'a CompiledThresholdOverride,
}
pub(super) struct ThresholdOverrideResolver {
entries: Vec<CompiledThresholdOverride>,
pub(super) global: GlobalHealthThresholds,
cyclomatic_policy: fallow_config::CyclomaticPolicy,
max_file_lines: u32,
inline: FxHashMap<PathBuf, FxHashMap<u32, CompiledInlineOverride>>,
inline_enabled: bool,
}
impl ThresholdOverrideResolver {
#[must_use]
pub(super) fn new(
overrides: &[fallow_config::HealthThresholdOverride],
global: GlobalHealthThresholds,
) -> Self {
let entries = overrides
.iter()
.enumerate()
.map(|(index, override_entry)| {
let mut builder = globset::GlobSetBuilder::new();
for pattern in &override_entry.files {
if let Ok(glob) = fallow_config::compile_path_glob(pattern) {
builder.add(glob);
}
}
CompiledThresholdOverride {
index,
matchers: builder
.build()
.unwrap_or_else(|_| globset::GlobSet::empty()),
functions: override_entry.functions.clone(),
configured: fallow_output::HealthConfiguredThresholds {
max_cyclomatic: override_entry.max_cyclomatic,
max_cognitive: override_entry.max_cognitive,
max_crap: override_entry.max_crap,
max_unit_size: override_entry.max_unit_size,
max_file_lines: override_entry.max_file_lines,
},
reason: override_entry.reason.clone(),
}
})
.collect();
Self {
entries,
global,
cyclomatic_policy: fallow_config::CyclomaticPolicy::Standard,
max_file_lines: 0,
inline: FxHashMap::default(),
inline_enabled: true,
}
}
#[must_use]
pub(super) fn with_inline_overrides(
mut self,
enabled: bool,
modules: &[crate::source::ModuleInfo],
file_paths: &FxHashMap<crate::discover::FileId, &PathBuf>,
root: &Path,
) -> Self {
self.inline_enabled = enabled;
if !enabled {
return self;
}
for module in modules {
if module.inline_threshold_overrides.entries.is_empty() {
continue;
}
let Some(path) = file_paths.get(&module.file_id) else {
continue;
};
let relative = path.strip_prefix(root).unwrap_or(path).to_path_buf();
let by_line = self.inline.entry(relative).or_default();
for entry in &module.inline_threshold_overrides.entries {
by_line.insert(
entry.line,
CompiledInlineOverride {
comment_line: entry.comment_line,
configured: fallow_output::HealthConfiguredThresholds {
max_cyclomatic: entry.max_cyclomatic,
max_cognitive: entry.max_cognitive,
max_crap: entry.max_crap,
max_unit_size: entry.max_unit_size,
max_file_lines: None,
},
reason: entry.reason.clone(),
},
);
}
}
self
}
#[must_use]
const fn inline_enabled(&self) -> bool {
self.inline_enabled
}
#[must_use]
fn inline_at(&self, relative: &Path, line: u32) -> Option<&CompiledInlineOverride> {
if self.inline.is_empty() {
return None;
}
self.inline.get(relative)?.get(&line)
}
#[must_use]
pub(super) fn resolve_unit(
&self,
relative: &Path,
function: &str,
line: u32,
) -> (
AppliedHealthThresholds,
Vec<ThresholdOverrideMatch<'_>>,
Option<&CompiledInlineOverride>,
) {
let (mut applied, matches) = self.resolve(relative, function);
let inline = self.inline_at(relative, line);
if let Some(comment) = inline {
let configured = comment.configured;
let effective = &mut applied.effective;
if let Some(value) = configured.max_cyclomatic {
effective.max_cyclomatic = value;
applied.comment_line = Some(comment.comment_line);
}
if let Some(value) = configured.max_cognitive {
effective.max_cognitive = value;
applied.comment_line = Some(comment.comment_line);
}
if let Some(value) = configured.max_crap {
effective.max_crap = value;
applied.comment_line = Some(comment.comment_line);
}
if let Some(value) = configured.max_unit_size {
effective.max_unit_size = value;
}
}
(applied, matches, inline)
}
#[must_use]
pub(super) const fn with_max_file_lines(mut self, max_file_lines: u32) -> Self {
self.max_file_lines = max_file_lines;
self
}
#[must_use]
pub(super) const fn max_file_lines(&self) -> u32 {
self.max_file_lines
}
#[must_use]
pub(super) fn resolve_max_file_lines(
&self,
relative: &Path,
) -> (u32, Vec<ThresholdOverrideMatch<'_>>) {
let mut effective = self.max_file_lines;
let mut matches = Vec::new();
for entry in &self.entries {
if !entry.functions.is_empty() || !entry.matchers.is_match(relative) {
continue;
}
if let Some(max_file_lines) = entry.configured.max_file_lines {
effective = max_file_lines;
matches.push(ThresholdOverrideMatch { entry });
}
}
(effective, matches)
}
#[must_use]
pub(super) fn has_file_lines_overrides(&self) -> bool {
self.entries
.iter()
.any(|entry| entry.configured.max_file_lines.is_some())
}
#[must_use]
pub(super) const fn with_cyclomatic_policy(
mut self,
policy: fallow_config::CyclomaticPolicy,
) -> Self {
self.cyclomatic_policy = policy;
self
}
#[must_use]
pub(super) const fn cyclomatic_policy(&self) -> fallow_config::CyclomaticPolicy {
self.cyclomatic_policy
}
#[must_use]
pub(super) fn gate_cyclomatic(
&self,
function: &fallow_types::extract::FunctionComplexity,
) -> u16 {
super::cyclomatic_policy::gate_cyclomatic(function, self.cyclomatic_policy)
}
#[must_use]
pub(super) fn resolve(
&self,
relative: &Path,
function: &str,
) -> (AppliedHealthThresholds, Vec<ThresholdOverrideMatch<'_>>) {
let mut effective = fallow_output::HealthEffectiveThresholds {
max_cyclomatic: self.global.cyclomatic,
max_cognitive: self.global.cognitive,
max_crap: self.global.crap,
max_unit_size: self.global.unit_size,
};
let mut override_index = None;
let mut matches = Vec::new();
for entry in &self.entries {
if !entry.matchers.is_match(relative) {
continue;
}
if !entry.functions.is_empty() && !entry.functions.iter().any(|f| f == function) {
continue;
}
if let Some(max_cyclomatic) = entry.configured.max_cyclomatic {
effective.max_cyclomatic = max_cyclomatic;
override_index = Some(entry.index);
}
if let Some(max_cognitive) = entry.configured.max_cognitive {
effective.max_cognitive = max_cognitive;
override_index = Some(entry.index);
}
if let Some(max_crap) = entry.configured.max_crap {
effective.max_crap = max_crap;
override_index = Some(entry.index);
}
if let Some(max_unit_size) = entry.configured.max_unit_size {
effective.max_unit_size = max_unit_size;
}
matches.push(ThresholdOverrideMatch { entry });
}
(
AppliedHealthThresholds {
effective,
override_index,
comment_line: None,
},
matches,
)
}
#[must_use]
pub(super) fn effective_max_unit_size(
&self,
relative: &Path,
function: &str,
line: u32,
) -> u32 {
if let Some(value) = self
.inline_at(relative, line)
.and_then(|comment| comment.configured.max_unit_size)
{
return value;
}
let mut effective = self.global.unit_size;
for entry in &self.entries {
if !entry.matchers.is_match(relative) {
continue;
}
if !entry.functions.is_empty() && !entry.functions.iter().any(|f| f == function) {
continue;
}
if let Some(max_unit_size) = entry.configured.max_unit_size {
effective = max_unit_size;
}
}
effective
}
#[must_use]
pub(super) fn effective_max_crap(&self, relative: &Path, function: &str, line: u32) -> f64 {
if let Some(value) = self
.inline_at(relative, line)
.and_then(|comment| comment.configured.max_crap)
{
return value;
}
let mut effective = self.global.crap;
for entry in &self.entries {
if !entry.matchers.is_match(relative) {
continue;
}
if !entry.functions.is_empty() && !entry.functions.iter().any(|f| f == function) {
continue;
}
if let Some(max_crap) = entry.configured.max_crap {
effective = max_crap;
}
}
effective
}
fn entries(&self) -> &[CompiledThresholdOverride] {
&self.entries
}
#[must_use]
pub(super) fn is_empty(&self) -> bool {
self.entries.is_empty() && self.inline.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ThresholdOverrideStateKey {
status: &'static str,
override_index: usize,
path: Option<PathBuf>,
function: Option<String>,
line: Option<u32>,
col: Option<u32>,
dimension: ThresholdOverrideDimension,
}
#[derive(Debug, Clone, Copy)]
pub(super) struct MeasuredThresholdMetrics {
pub(super) cyclomatic: u16,
pub(super) cognitive: u16,
pub(super) crap: f64,
}
#[derive(Default)]
pub(super) struct ThresholdOverrideStateTracker {
matched_indexes: FxHashSet<usize>,
seen: FxHashSet<ThresholdOverrideStateKey>,
states: Vec<fallow_output::ThresholdOverrideState>,
inline_seen: FxHashSet<(PathBuf, u32, ThresholdOverrideDimension)>,
inline_states: Vec<fallow_output::InlineThresholdOverrideState>,
inline_problems: Vec<fallow_output::InlineThresholdOverrideProblem>,
}
#[derive(Debug, Clone, Default)]
pub(super) struct ThresholdOverrideRows {
pub(super) config: Vec<fallow_output::ThresholdOverrideState>,
pub(super) inline: Vec<fallow_output::InlineThresholdOverrideState>,
pub(super) inline_problems: Vec<fallow_output::InlineThresholdOverrideProblem>,
}
fn configured_dimensions(
configured: fallow_output::HealthConfiguredThresholds,
) -> Vec<ThresholdOverrideDimension> {
let mut dimensions = Vec::new();
if configured.max_cyclomatic.is_some()
|| configured.max_cognitive.is_some()
|| configured.max_unit_size.is_some()
|| configured.max_file_lines.is_some()
{
dimensions.push(ThresholdOverrideDimension::Complexity);
}
if configured.max_crap.is_some() {
dimensions.push(ThresholdOverrideDimension::Crap);
}
dimensions
}
const fn override_status(
global_exceeded: bool,
local_exceeded: bool,
breaches_lowered: bool,
) -> fallow_output::ThresholdOverrideStatus {
if breaches_lowered || (global_exceeded && !local_exceeded) {
fallow_output::ThresholdOverrideStatus::Active
} else if !global_exceeded {
fallow_output::ThresholdOverrideStatus::Stale
} else {
fallow_output::ThresholdOverrideStatus::Insufficient
}
}
fn resolving_index(
matches: &[ThresholdOverrideMatch<'_>],
configures: impl Fn(&fallow_output::HealthConfiguredThresholds) -> bool,
) -> Option<usize> {
matches
.iter()
.rev()
.find(|matched| configures(&matched.entry.configured))
.map(|matched| matched.entry.index)
}
impl ThresholdOverrideStateTracker {
pub(super) fn record_complexity(
&mut self,
function: ComplexityFunctionContext<'_>,
matches: &[ThresholdOverrideMatch<'_>],
global: GlobalHealthThresholds,
effective: fallow_output::HealthEffectiveThresholds,
) {
let ComplexityFunctionContext {
path,
function,
line,
col,
cyclomatic,
cognitive,
line_count,
suppressed,
} = function;
let cyclomatic_owner = resolving_index(matches, |c| c.max_cyclomatic.is_some());
let cognitive_owner = resolving_index(matches, |c| c.max_cognitive.is_some());
let unit_size_owner = resolving_index(matches, |c| c.max_unit_size.is_some());
for matched in matches {
let configured = matched.entry.configured;
let owns = |owner: Option<usize>| owner == Some(matched.entry.index);
let touches_unit_size = configured.max_unit_size.is_some();
let has_complexity_threshold = configured.max_cyclomatic.is_some()
|| configured.max_cognitive.is_some()
|| touches_unit_size;
if !has_complexity_threshold {
continue;
}
self.matched_indexes.insert(matched.entry.index);
let breaches = |max_cyclomatic: u16, max_cognitive: u16, max_unit_size: u32| {
(!suppressed && (cyclomatic > max_cyclomatic || cognitive > max_cognitive))
|| (touches_unit_size && line_count.is_some_and(|lc| lc > max_unit_size))
};
let global_exceeded = breaches(global.cyclomatic, global.cognitive, global.unit_size);
let local_exceeded = breaches(
effective.max_cyclomatic,
effective.max_cognitive,
effective.max_unit_size,
);
let breaches_lowered = (!suppressed
&& ((owns(cyclomatic_owner)
&& effective.max_cyclomatic < global.cyclomatic
&& cyclomatic > effective.max_cyclomatic)
|| (owns(cognitive_owner)
&& effective.max_cognitive < global.cognitive
&& cognitive > effective.max_cognitive)))
|| (owns(unit_size_owner)
&& effective.max_unit_size < global.unit_size
&& line_count.is_some_and(|lc| lc > effective.max_unit_size));
let status = override_status(global_exceeded, local_exceeded, breaches_lowered);
let outstanding =
if touches_unit_size && line_count.is_some_and(|lc| lc > effective.max_unit_size) {
vec![ThresholdOverrideDimension::Complexity]
} else {
Vec::new()
};
self.push_state(ThresholdOverrideStateInput {
status,
override_index: matched.entry.index,
outstanding,
path: Some(path.to_path_buf()),
function: Some(function.to_string()),
line: Some(line),
col: Some(col),
configured_thresholds: configured,
effective_thresholds: effective,
metrics: Some(fallow_output::ThresholdOverrideMetrics {
cyclomatic,
cognitive,
crap: None,
line_count,
}),
reason: matched.entry.reason.clone(),
dimension: ThresholdOverrideDimension::Complexity,
});
}
}
pub(super) fn record_file_lines(
&mut self,
file: FileLinesContext<'_>,
matches: &[ThresholdOverrideMatch<'_>],
global_max_file_lines: u32,
effective_max_file_lines: u32,
effective: fallow_output::HealthEffectiveThresholds,
) {
let breaches = |limit: u32| !file.suppressed && limit > 0 && file.line_count > limit;
let global_exceeded = breaches(global_max_file_lines);
let local_exceeded = breaches(effective_max_file_lines);
let lowered = effective_max_file_lines > 0
&& (global_max_file_lines == 0 || effective_max_file_lines < global_max_file_lines);
let owner = resolving_index(matches, |c| c.max_file_lines.is_some());
let outstanding = if local_exceeded {
vec![ThresholdOverrideDimension::Complexity]
} else {
Vec::new()
};
for matched in matches {
let breaches_lowered = lowered && local_exceeded && owner == Some(matched.entry.index);
let status = override_status(global_exceeded, local_exceeded, breaches_lowered);
self.matched_indexes.insert(matched.entry.index);
self.push_state(ThresholdOverrideStateInput {
status,
override_index: matched.entry.index,
outstanding: outstanding.clone(),
path: Some(file.path.to_path_buf()),
function: Some(fallow_output::FILE_LINES_FINDING_NAME.to_string()),
line: Some(1),
col: Some(0),
configured_thresholds: matched.entry.configured,
effective_thresholds: effective,
metrics: Some(fallow_output::ThresholdOverrideMetrics {
cyclomatic: 0,
cognitive: 0,
crap: None,
line_count: Some(file.line_count),
}),
reason: matched.entry.reason.clone(),
dimension: ThresholdOverrideDimension::Complexity,
});
}
}
pub(super) fn record_crap(
&mut self,
function: CrapFunctionContext<'_>,
metrics: MeasuredThresholdMetrics,
matches: &[ThresholdOverrideMatch<'_>],
global: GlobalHealthThresholds,
effective: fallow_output::HealthEffectiveThresholds,
) {
let CrapFunctionContext {
path,
function,
line,
col,
suppressed,
} = function;
let breaches = |limit: f64| !suppressed && metrics.crap >= limit;
let global_exceeded = breaches(global.crap);
let local_exceeded = breaches(effective.max_crap);
let lowered = effective.max_crap < global.crap && local_exceeded;
let owner = resolving_index(matches, |c| c.max_crap.is_some());
for matched in matches {
if matched.entry.configured.max_crap.is_none() {
continue;
}
self.matched_indexes.insert(matched.entry.index);
let status = override_status(
global_exceeded,
local_exceeded,
lowered && owner == Some(matched.entry.index),
);
self.push_state(ThresholdOverrideStateInput {
status,
override_index: matched.entry.index,
outstanding: Vec::new(),
path: Some(path.to_path_buf()),
function: Some(function.to_string()),
line: Some(line),
col: Some(col),
configured_thresholds: matched.entry.configured,
effective_thresholds: effective,
metrics: Some(fallow_output::ThresholdOverrideMetrics {
cyclomatic: metrics.cyclomatic,
cognitive: metrics.cognitive,
crap: Some(metrics.crap),
line_count: None,
}),
reason: matched.entry.reason.clone(),
dimension: ThresholdOverrideDimension::Crap,
});
}
}
pub(super) fn record_crap_not_applicable(
&mut self,
function: CrapFunctionContext<'_>,
measured: (u16, u16),
matches: &[ThresholdOverrideMatch<'_>],
effective: fallow_output::HealthEffectiveThresholds,
) {
let CrapFunctionContext {
path,
function,
line,
col,
suppressed: _,
} = function;
let (cyclomatic, cognitive) = measured;
for matched in matches {
if matched.entry.configured.max_crap.is_none() {
continue;
}
self.matched_indexes.insert(matched.entry.index);
self.push_state(ThresholdOverrideStateInput {
status: fallow_output::ThresholdOverrideStatus::Stale,
override_index: matched.entry.index,
outstanding: Vec::new(),
path: Some(path.to_path_buf()),
function: Some(function.to_string()),
line: Some(line),
col: Some(col),
configured_thresholds: matched.entry.configured,
effective_thresholds: effective,
metrics: Some(fallow_output::ThresholdOverrideMetrics {
cyclomatic,
cognitive,
crap: None,
line_count: None,
}),
reason: matched.entry.reason.clone(),
dimension: ThresholdOverrideDimension::Crap,
});
}
}
pub(super) fn record_no_match_entries(
&mut self,
resolver: &ThresholdOverrideResolver,
should_emit: bool,
) {
if !should_emit {
return;
}
for entry in resolver.entries() {
if self.matched_indexes.contains(&entry.index) {
continue;
}
let effective = fallow_output::HealthEffectiveThresholds {
max_cyclomatic: entry
.configured
.max_cyclomatic
.unwrap_or(resolver.global.cyclomatic),
max_cognitive: entry
.configured
.max_cognitive
.unwrap_or(resolver.global.cognitive),
max_crap: entry.configured.max_crap.unwrap_or(resolver.global.crap),
max_unit_size: entry
.configured
.max_unit_size
.unwrap_or(resolver.global.unit_size),
};
for dimension in configured_dimensions(entry.configured) {
self.push_state(ThresholdOverrideStateInput {
status: fallow_output::ThresholdOverrideStatus::NoMatch,
override_index: entry.index,
outstanding: Vec::new(),
path: None,
function: None,
line: None,
col: None,
configured_thresholds: entry.configured,
effective_thresholds: effective,
metrics: None,
reason: entry.reason.clone(),
dimension,
});
}
}
}
pub(super) fn states_mut(&mut self) -> &mut [fallow_output::ThresholdOverrideState] {
&mut self.states
}
pub(super) fn record_inline_module(
&mut self,
path: &Path,
module: &crate::source::ModuleInfo,
resolver: &ThresholdOverrideResolver,
) {
let comments = &module.inline_threshold_overrides;
if comments.is_empty() {
return;
}
for problem in &comments.problems {
self.inline_problems
.push(fallow_output::InlineThresholdOverrideProblem {
path: path.to_path_buf(),
line: problem.line,
problem: problem.kind,
token: problem.token.clone(),
});
}
if !resolver.inline_enabled() {
for entry in &comments.entries {
self.inline_problems
.push(fallow_output::InlineThresholdOverrideProblem {
path: path.to_path_buf(),
line: entry.comment_line,
problem: fallow_output::InlineThresholdProblemKind::Disabled,
token: None,
});
}
return;
}
for entry in &comments.entries {
let matched = module.complexity.iter().any(|fc| {
fc.line == entry.line && !fallow_types::extract::is_synthetic_module_unit(&fc.name)
});
if matched {
continue;
}
let configured = fallow_output::HealthConfiguredThresholds {
max_cyclomatic: entry.max_cyclomatic,
max_cognitive: entry.max_cognitive,
max_crap: entry.max_crap,
max_unit_size: entry.max_unit_size,
max_file_lines: None,
};
let global = resolver.global;
let effective = fallow_output::HealthEffectiveThresholds {
max_cyclomatic: entry.max_cyclomatic.unwrap_or(global.cyclomatic),
max_cognitive: entry.max_cognitive.unwrap_or(global.cognitive),
max_crap: entry.max_crap.unwrap_or(global.crap),
max_unit_size: entry.max_unit_size.unwrap_or(global.unit_size),
};
for dimension in configured_dimensions(configured) {
self.push_inline_state(fallow_output::InlineThresholdOverrideState {
status: fallow_output::ThresholdOverrideStatus::NoMatch,
dimension,
outstanding: Vec::new(),
path: path.to_path_buf(),
comment_line: entry.comment_line,
function: None,
line: None,
col: None,
configured_thresholds: configured,
effective_thresholds: effective,
metrics: None,
reason: entry.reason.clone(),
});
}
}
}
pub(super) fn record_inline_complexity(
&mut self,
function: ComplexityFunctionContext<'_>,
comment: &CompiledInlineOverride,
global: GlobalHealthThresholds,
effective: fallow_output::HealthEffectiveThresholds,
) {
let ComplexityFunctionContext {
path,
function,
line,
col,
cyclomatic,
cognitive,
line_count,
suppressed,
} = function;
let configured = comment.configured;
let touches_unit_size = configured.max_unit_size.is_some();
if configured.max_cyclomatic.is_none()
&& configured.max_cognitive.is_none()
&& !touches_unit_size
{
return;
}
let breaches = |max_cyclomatic: u16, max_cognitive: u16, max_unit_size: u32| {
(!suppressed && (cyclomatic > max_cyclomatic || cognitive > max_cognitive))
|| (touches_unit_size && line_count.is_some_and(|lc| lc > max_unit_size))
};
let global_exceeded = breaches(global.cyclomatic, global.cognitive, global.unit_size);
let local_exceeded = breaches(
effective.max_cyclomatic,
effective.max_cognitive,
effective.max_unit_size,
);
let breaches_lowered = (!suppressed
&& ((configured.max_cyclomatic.is_some()
&& effective.max_cyclomatic < global.cyclomatic
&& cyclomatic > effective.max_cyclomatic)
|| (configured.max_cognitive.is_some()
&& effective.max_cognitive < global.cognitive
&& cognitive > effective.max_cognitive)))
|| (touches_unit_size
&& effective.max_unit_size < global.unit_size
&& line_count.is_some_and(|lc| lc > effective.max_unit_size));
let outstanding =
if touches_unit_size && line_count.is_some_and(|lc| lc > effective.max_unit_size) {
vec![ThresholdOverrideDimension::Complexity]
} else {
Vec::new()
};
self.push_inline_state(fallow_output::InlineThresholdOverrideState {
status: override_status(global_exceeded, local_exceeded, breaches_lowered),
dimension: ThresholdOverrideDimension::Complexity,
outstanding,
path: path.to_path_buf(),
comment_line: comment.comment_line,
function: Some(function.to_string()),
line: Some(line),
col: Some(col),
configured_thresholds: configured,
effective_thresholds: effective,
metrics: Some(fallow_output::ThresholdOverrideMetrics {
cyclomatic,
cognitive,
crap: None,
line_count,
}),
reason: comment.reason.clone(),
});
}
pub(super) fn record_inline_crap(
&mut self,
function: CrapFunctionContext<'_>,
measured: (u16, u16, Option<f64>),
comment: &CompiledInlineOverride,
global: GlobalHealthThresholds,
effective: fallow_output::HealthEffectiveThresholds,
) {
let CrapFunctionContext {
path,
function,
line,
col,
suppressed,
} = function;
if comment.configured.max_crap.is_none() {
return;
}
let (cyclomatic, cognitive, crap) = measured;
let status = crap.map_or(fallow_output::ThresholdOverrideStatus::Stale, |crap| {
let breaches = |limit: f64| !suppressed && crap >= limit;
let local_exceeded = breaches(effective.max_crap);
let lowered = effective.max_crap < global.crap && local_exceeded;
override_status(breaches(global.crap), local_exceeded, lowered)
});
self.push_inline_state(fallow_output::InlineThresholdOverrideState {
status,
dimension: ThresholdOverrideDimension::Crap,
outstanding: Vec::new(),
path: path.to_path_buf(),
comment_line: comment.comment_line,
function: Some(function.to_string()),
line: Some(line),
col: Some(col),
configured_thresholds: comment.configured,
effective_thresholds: effective,
metrics: Some(fallow_output::ThresholdOverrideMetrics {
cyclomatic,
cognitive,
crap,
line_count: None,
}),
reason: comment.reason.clone(),
});
}
fn push_inline_state(&mut self, state: fallow_output::InlineThresholdOverrideState) {
if self
.inline_seen
.insert((state.path.clone(), state.comment_line, state.dimension))
{
self.inline_states.push(state);
}
}
pub(super) fn inline_states_mut(
&mut self,
) -> &mut [fallow_output::InlineThresholdOverrideState] {
&mut self.inline_states
}
pub(super) fn into_rows(mut self) -> ThresholdOverrideRows {
let mut inline = std::mem::take(&mut self.inline_states);
inline.sort_by(|a, b| {
a.path
.cmp(&b.path)
.then(a.comment_line.cmp(&b.comment_line))
.then(a.dimension.cmp(&b.dimension))
});
let mut inline_problems = std::mem::take(&mut self.inline_problems);
inline_problems.sort_by(|a, b| a.path.cmp(&b.path).then(a.line.cmp(&b.line)));
ThresholdOverrideRows {
config: self.into_states(),
inline,
inline_problems,
}
}
pub(super) fn into_states(mut self) -> Vec<fallow_output::ThresholdOverrideState> {
self.states.sort_by(|a, b| {
a.override_index
.cmp(&b.override_index)
.then(a.path.cmp(&b.path))
.then(a.function.cmp(&b.function))
.then(a.line.cmp(&b.line))
.then(a.col.cmp(&b.col))
.then(a.dimension.cmp(&b.dimension))
});
self.states
}
fn push_state(&mut self, input: ThresholdOverrideStateInput) {
let status_key = match input.status {
fallow_output::ThresholdOverrideStatus::Active => "active",
fallow_output::ThresholdOverrideStatus::Stale => "stale",
fallow_output::ThresholdOverrideStatus::Insufficient => "insufficient",
fallow_output::ThresholdOverrideStatus::NoMatch => "no_match",
};
let key = ThresholdOverrideStateKey {
status: status_key,
override_index: input.override_index,
path: input.path.clone(),
function: input.function.clone(),
line: input.line,
col: input.col,
dimension: input.dimension,
};
if !self.seen.insert(key) {
return;
}
self.states.push(fallow_output::ThresholdOverrideState {
status: input.status,
override_index: input.override_index,
dimension: input.dimension,
outstanding: input.outstanding,
path: input.path,
function: input.function,
line: input.line,
col: input.col,
configured_thresholds: input.configured_thresholds,
effective_thresholds: input.effective_thresholds,
metrics: input.metrics,
reason: input.reason,
});
}
}
#[derive(Clone, Copy)]
pub(super) struct FileLinesContext<'a> {
pub(super) path: &'a Path,
pub(super) line_count: u32,
pub(super) suppressed: bool,
}
#[derive(Clone, Copy)]
pub(super) struct ComplexityFunctionContext<'a> {
pub(super) path: &'a Path,
pub(super) function: &'a str,
pub(super) line: u32,
pub(super) col: u32,
pub(super) cyclomatic: u16,
pub(super) cognitive: u16,
pub(super) line_count: Option<u32>,
pub(super) suppressed: bool,
}
#[derive(Clone, Copy)]
pub(super) struct CrapFunctionContext<'a> {
pub(super) path: &'a Path,
pub(super) function: &'a str,
pub(super) line: u32,
pub(super) col: u32,
pub(super) suppressed: bool,
}
struct ThresholdOverrideStateInput {
status: fallow_output::ThresholdOverrideStatus,
override_index: usize,
outstanding: Vec<ThresholdOverrideDimension>,
path: Option<PathBuf>,
function: Option<String>,
line: Option<u32>,
col: Option<u32>,
configured_thresholds: fallow_output::HealthConfiguredThresholds,
effective_thresholds: fallow_output::HealthEffectiveThresholds,
metrics: Option<fallow_output::ThresholdOverrideMetrics>,
reason: Option<String>,
dimension: ThresholdOverrideDimension,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn override_files_single_star_stays_within_one_segment() {
let global = GlobalHealthThresholds {
cyclomatic: 20,
cognitive: 15,
crap: 30.0,
unit_size: 60,
};
let overrides = [fallow_config::HealthThresholdOverride {
files: vec!["src/*.ts".to_string()],
functions: Vec::new(),
max_cyclomatic: Some(40),
max_cognitive: None,
max_crap: None,
max_unit_size: None,
max_file_lines: None,
reason: None,
}];
let resolver = ThresholdOverrideResolver::new(&overrides, global);
let (direct, _) = resolver.resolve(Path::new("src/a.ts"), "run");
assert_eq!(direct.effective.max_cyclomatic, 40);
let (nested, _) = resolver.resolve(Path::new("src/nested/a.ts"), "run");
assert_eq!(nested.effective.max_cyclomatic, 20);
}
}