big-code-analysis 2.0.0

Tool to compute and export code metrics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Configuration for a change-history walk.
//!
//! [`Options`] is a plain data struct: the CLI / web / Python layers
//! fill it in from user input, and [`build_history_index`](crate::vcs::build_history_index)
//! consumes it. Time windows are stored already resolved to seconds so
//! the generic core never re-parses user duration strings; the
//! [`parse_window`] helper is exposed for those front ends to perform
//! that resolution (and to surface a typed [`Error`] on bad input).

use std::path::Path;

use super::error::Error;
use super::identity::AuthorHashKey;

/// Seconds in a day.
pub(crate) const SECONDS_PER_DAY: i64 = 86_400;
/// Seconds in a week.
const SECONDS_PER_WEEK: i64 = 7 * SECONDS_PER_DAY;
/// Seconds in an average Gregorian month (30.436875 days). Months and
/// years are inherently approximate; the average keeps `12mo` and `1y`
/// numerically identical (both 365.2425 days → 365 days), matching the
/// `long_window_days: 365` shown in the issue's output sample.
const SECONDS_PER_MONTH: i64 = 2_629_746;
/// Seconds in an average Gregorian year (365.2425 days).
const SECONDS_PER_YEAR: i64 = 31_556_952;

/// Default long window (`12mo` ≈ 365 days).
pub const DEFAULT_LONG_WINDOW: &str = "12mo";
/// Default recent window (`90d`).
pub const DEFAULT_RECENT_WINDOW: &str = "90d";

/// Human-facing reminder of the accepted [`parse_window`] grammar,
/// appended to every window-parse error so the message is actionable
/// without consulting the docs (issue #607).
const WINDOW_FORMAT_HINT: &str =
    "expected <N>d|w|mo|y or an ISO 8601 duration, e.g. 12mo, 90d, or P1Y6M";

/// Default bus-factor coverage (abandonment) threshold (`0.5`, per
/// Avelino). Re-exported from the bus-factor module so the front ends
/// share one source of truth for the default and the validation bound.
pub const DEFAULT_BUS_FACTOR_THRESHOLD: f64 = super::bus_factor::DEFAULT_COVERAGE_THRESHOLD;

/// Default bot-author exclusion pattern (case-insensitive, matched as a
/// substring against both the canonical author name and email). The
/// `[bot]` suffixes are regex-escaped. Mirrors the well-known automation
/// identities called out in issue #328.
pub const DEFAULT_BOT_PATTERN: &str = r"dependabot\[bot\]|renovate\[bot\]|github-actions\[bot\]|pre-commit-ci\[bot\]|mergify\[bot\]|pyup-bot";

/// Which composite risk-score formula to apply.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RiskFormula {
    /// Log-scaled weighted sum with categorical bumps (the `v1`
    /// formula documented in [`score`](crate::vcs::score)).
    #[default]
    Weighted,
    /// Each signal re-ranked to its percentile within the analyzed
    /// set, then averaged. The literature recommends relative triggers
    /// over hard thresholds for cross-project robustness.
    Percentile,
}

impl std::str::FromStr for RiskFormula {
    type Err = Error;

    /// Parse the user-facing formula name. The single source of truth
    /// shared by the web (`POST /vcs`) and Python (`vcs_metrics`) front
    /// ends; the CLI uses a clap `ValueEnum` instead.
    fn from_str(s: &str) -> Result<Self, Error> {
        match s {
            "weighted" => Ok(Self::Weighted),
            "percentile" => Ok(Self::Percentile),
            other => Err(Error::InvalidFormula(other.to_owned())),
        }
    }
}

/// Which tracked files the change-history walk ranks (issue #576).
///
/// Applied as an **additional** extension-only filter on top of the
/// `--paths` / `--include` / `--exclude` globs (AND semantics): a file
/// must pass both to be ranked. The check never reads blob content, so a
/// language detected only by an in-file modeline (Emacs / Vim) — never by
/// its extension — is treated as out-of-scope under [`Metrics`](Self::Metrics);
/// this is the one documented divergence from the content-aware `bca
/// metrics` walk.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum FileTypeScope {
    /// Only files bca computes metrics for — the same set `bca metrics`
    /// would analyze, resolved by extension via
    /// [`get_language_for_file`](crate::get_language_for_file). The
    /// default: it keeps the change-history ranking aligned with the AST
    /// hotspot tables (which only cover files-with-metrics) and keeps
    /// high-churn non-source files (`CHANGELOG.md`, `Cargo.lock`, CI
    /// config) out of the risk ranking. Extension-less files
    /// (`Makefile`, `Dockerfile`, `LICENSE`) and unknown extensions are
    /// excluded.
    #[default]
    Metrics,
    /// Every tracked, non-binary, non-symlink text file — the behaviour
    /// before the `metrics` default was introduced.
    All,
    /// A user-supplied allow-list of file extensions, normalised to
    /// lowercase with any leading dot stripped (`rs`, `py`, `toml`). A
    /// file is in scope iff its lowercased extension is in the list.
    Custom(Vec<String>),
}

impl FileTypeScope {
    /// Whether `path` is in scope, judged by extension only (no blob
    /// content is read, so this stays a cheap pre-filter on the file
    /// enumeration).
    #[must_use]
    pub fn includes(&self, path: &Path) -> bool {
        match self {
            Self::All => true,
            // Route through the same extension predicate the metrics walk
            // resolves a language with, so the `metrics` scope stays in
            // lockstep with the analyzable-file set as languages are
            // added or removed.
            Self::Metrics => crate::get_language_for_file(path).is_some(),
            Self::Custom(extensions) => path
                .extension()
                .and_then(|ext| ext.to_str())
                // The stored extensions are already lowercased, so an
                // ASCII case-insensitive compare avoids allocating a
                // lowercased copy of every file's extension in this
                // per-file path.
                .is_some_and(|ext| {
                    extensions
                        .iter()
                        .any(|allowed| allowed.eq_ignore_ascii_case(ext))
                }),
        }
    }

    /// Parse a custom comma-separated extension list, normalising each
    /// entry (trim, strip a leading dot, lowercase) and dropping blanks.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidFileTypeScope`] when the list normalises
    /// to nothing (empty, or only blanks / bare dots) — a scope that
    /// would silently rank no files — or when an entry carries an interior
    /// dot (`d.ts`, `tar.gz`, `.rs.bak`): `Path::extension()` returns only
    /// the final component, so a multi-dot suffix can never match and would
    /// silently rank nothing. Rejecting it turns that footgun into a loud
    /// error (multi-dot-suffix *support* is a separate, larger change).
    fn from_extensions(list: &str) -> Result<Self, Error> {
        let mut extensions: Vec<String> = Vec::new();
        for raw in list.split(',') {
            let normalized = raw.trim().trim_start_matches('.').to_lowercase();
            if normalized.is_empty() {
                continue;
            }
            if normalized.contains('.') {
                return Err(Error::InvalidFileTypeScope(format!(
                    "{:?} is a multi-dot suffix; `Path::extension()` only \
                     matches the final component, so it would rank no files",
                    raw.trim()
                )));
            }
            if !extensions.contains(&normalized) {
                extensions.push(normalized);
            }
        }
        if extensions.is_empty() {
            return Err(Error::InvalidFileTypeScope(format!(
                "{list:?} lists no usable file extensions"
            )));
        }
        Ok(Self::Custom(extensions))
    }
}

impl std::str::FromStr for FileTypeScope {
    type Err = Error;

    /// Parse the user-facing scope: the keywords `metrics` / `all`, or
    /// any other value as a comma-separated custom extension list. The
    /// single source of truth shared by the CLI (`--file-types`), the
    /// `bca.toml` `[vcs] file_types` key, the web front end, and Python.
    fn from_str(s: &str) -> Result<Self, Error> {
        match s.trim() {
            "" => Err(Error::InvalidFileTypeScope("the value is empty".to_owned())),
            "metrics" => Ok(Self::Metrics),
            "all" => Ok(Self::All),
            list => Self::from_extensions(list),
        }
    }
}

/// Configuration for a single change-history walk.
// The booleans are independent on/off CLI toggles (`--full-history`,
// `--include-merges`, …); packing them into a flags newtype would hide
// each one's meaning at construction sites for no real gain.
#[allow(clippy::struct_excessive_bools)]
#[derive(Clone, Debug)]
// Sealed against external struct-literal construction so future additive
// fields stay non-breaking: downstream crates start from `Options::default()`
// and assign the `pub` fields they care about (see STABILITY.md).
#[non_exhaustive]
pub struct Options {
    /// Long observation window, in seconds (default ≈ 365 days).
    pub long_window_secs: i64,
    /// Recent observation window, in seconds (default 90 days).
    pub recent_window_secs: i64,
    /// Revision to start the walk from (default `HEAD`).
    pub reference: String,
    /// Walk the full commit DAG rather than first-parent only.
    pub full_history: bool,
    /// Include merge commits (default: skip them).
    pub include_merges: bool,
    /// Follow file renames across history (default: on).
    pub follow_renames: bool,
    /// Exclude bot author identities (default: on).
    pub exclude_bots: bool,
    /// Regex matched against author name/email to detect bots.
    pub bot_pattern: String,
    /// Reference "now" as a Unix timestamp for reproducible snapshots
    /// (`--as-of`). `None` means wall-clock time at walk start.
    pub as_of: Option<i64>,
    /// Which composite score to compute.
    pub risk_formula: RiskFormula,
    /// Emit SHA-256-hashed canonical author identities (default: off —
    /// author identities never leave the process otherwise).
    pub emit_author_details: bool,
    /// Optional secret key that hardens `emit_author_details` into a keyed
    /// HMAC (issue #956). `None` (the default) emits the bare SHA-256
    /// pseudonym. Has no effect unless `emit_author_details` is set. The
    /// key is a finalization-time concern (like `emit_author_details`
    /// itself), so it never enters the persistent-cache fingerprint: the
    /// same cached walk re-finalizes under any key without a re-walk (see
    /// [`AuthorId::emit_hashed`](super::identity::AuthorId::emit_hashed)).
    pub author_hash_key: Option<AuthorHashKey>,
    /// Emit stats for files deleted at the target ref (default: off).
    pub include_deleted: bool,
    /// Compute the directory- / repo-level bus-factor aggregate from the
    /// walk (issue #332). Default off: it retains per-file authorship
    /// beyond the per-file [`Stats`](crate::vcs::Stats), which the
    /// repeated JIT-prior and per-file-injection walks neither need nor
    /// should pay for.
    pub compute_bus_factor: bool,
    /// Coverage (abandonment) threshold for the bus factor, in `(0, 1)`
    /// — the fraction of files that must be orphaned for the greedy
    /// removal to stop (default [`DEFAULT_BUS_FACTOR_THRESHOLD`], `0.5`
    /// per Avelino). Ignored unless `compute_bus_factor` is set.
    pub bus_factor_threshold: f64,
    /// Which tracked files to rank (issue #576). Defaults to
    /// [`FileTypeScope::Metrics`] — only files bca has metrics for — so
    /// high-churn non-source files do not dominate the risk ranking and
    /// the change-history view aligns with the AST hotspot tables.
    pub file_types: FileTypeScope,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            // The default-window constants are valid by construction;
            // `expect` documents the invariant (AGENTS.md permits it
            // for provably-unreachable cases). A unit test pins it.
            long_window_secs: parse_window(DEFAULT_LONG_WINDOW)
                .expect("DEFAULT_LONG_WINDOW parses"),
            recent_window_secs: parse_window(DEFAULT_RECENT_WINDOW)
                .expect("DEFAULT_RECENT_WINDOW parses"),
            reference: "HEAD".to_owned(),
            full_history: false,
            include_merges: false,
            follow_renames: true,
            exclude_bots: true,
            bot_pattern: DEFAULT_BOT_PATTERN.to_owned(),
            as_of: None,
            risk_formula: RiskFormula::Weighted,
            emit_author_details: false,
            author_hash_key: None,
            include_deleted: false,
            compute_bus_factor: false,
            bus_factor_threshold: DEFAULT_BUS_FACTOR_THRESHOLD,
            file_types: FileTypeScope::Metrics,
        }
    }
}

impl Options {
    /// Long window expressed in whole days (for the serialized
    /// `long_window_days` field and the `new_file`/age cap).
    #[must_use]
    pub fn long_window_days(&self) -> u32 {
        secs_to_days(self.long_window_secs)
    }

    /// Recent window expressed in whole days.
    #[must_use]
    pub fn recent_window_days(&self) -> u32 {
        secs_to_days(self.recent_window_secs)
    }
}

/// Round a second count to the nearest whole day, saturating into
/// `u32`. Window lengths never approach `u32::MAX` days in practice,
/// but the saturation keeps the conversion total and lint-clean.
fn secs_to_days(secs: i64) -> u32 {
    // Saturating: `secs` in the top half-day of i64 would overflow the bare
    // `+ SECONDS_PER_DAY / 2` rounding term. Saturating keeps i64::MAX at
    // i64::MAX, so it divides to a huge positive day count and `try_from`
    // saturates to u32::MAX — rather than wrapping negative and flooring to 0.
    let days = secs.saturating_add(SECONDS_PER_DAY / 2) / SECONDS_PER_DAY;
    u32::try_from(days.max(0)).unwrap_or(u32::MAX)
}

/// Validate a bus-factor coverage threshold, accepting only a finite
/// value in the open interval `(0, 1)`.
///
/// A `0` would make the first key-developer removal "exceed" the
/// abandonment fraction (bus factor always 1) and a `1` could never be
/// exceeded (bus factor = every author), so both extremes are user errors
/// rather than values to silently clamp. The single source of truth
/// shared by every front end.
///
/// # Errors
///
/// Returns [`Error::InvalidBusFactorThreshold`] when `threshold` is
/// non-finite or outside `(0, 1)`.
pub fn validate_bus_factor_threshold(threshold: f64) -> Result<f64, Error> {
    if threshold.is_finite() && threshold > 0.0 && threshold < 1.0 {
        Ok(threshold)
    } else {
        Err(Error::InvalidBusFactorThreshold(format!(
            "{threshold} is not in the open interval (0, 1)"
        )))
    }
}

/// Parse a human time-window string into seconds.
///
/// Accepts a suffix form — `<number><unit>` with unit `d` (days),
/// `w` (weeks), `mo` (months), or `y` (years) — or an ISO 8601 duration
/// (`P12M`, `P90D`, `P2Y`, `P8W`). Months and years use the average
/// Gregorian length, so `12mo`, `1y`, and `P1Y` all resolve to
/// 365 days.
///
/// # Errors
///
/// Returns [`Error::InvalidWindow`] when the input is empty, carries an
/// unrecognised unit, or has a non-numeric magnitude.
pub fn parse_window(spec: &str) -> Result<i64, Error> {
    let trimmed = spec.trim();
    if trimmed.is_empty() {
        return Err(window_error(spec, "is empty"));
    }
    if let Some(rest) = trimmed.strip_prefix(['P', 'p']) {
        return parse_iso8601(rest, spec);
    }
    // Suffix form: split the trailing alphabetic unit from the leading
    // numeric magnitude.
    let split = trimmed
        .find(|c: char| c.is_ascii_alphabetic())
        .ok_or_else(|| window_error(spec, "has no unit"))?;
    let (number, unit) = trimmed.split_at(split);
    // Report the full original input rather than the split-off magnitude:
    // for "bogus" the magnitude is empty, and quoting `""` told the user
    // nothing about what they typed (issue #607).
    let magnitude: i64 = number
        .trim()
        .parse()
        .map_err(|_| window_error(spec, "has a non-numeric magnitude"))?;
    let factor = unit_factor(unit)
        .ok_or_else(|| window_error(spec, &format!("has an unknown unit {unit:?}")))?;
    checked_window(magnitude, factor, spec)
}

/// Build an [`Error::InvalidWindow`] that quotes the full offending input
/// and appends the accepted-format hint, so every window-parse failure
/// names what the user typed and how to fix it (issue #607).
fn window_error(spec: &str, problem: &str) -> Error {
    Error::InvalidWindow(format!("{spec:?} {problem} ({WINDOW_FORMAT_HINT})"))
}

/// Seconds-per-unit for the suffix form. `mo` is months (the bare `m`
/// is intentionally rejected as ambiguous between minutes and months).
fn unit_factor(unit: &str) -> Option<i64> {
    match unit {
        "d" => Some(SECONDS_PER_DAY),
        "w" => Some(SECONDS_PER_WEEK),
        "mo" => Some(SECONDS_PER_MONTH),
        "y" => Some(SECONDS_PER_YEAR),
        _ => None,
    }
}

/// Parse the post-`P` body of an ISO 8601 duration. Only the date
/// portion is meaningful for a history window; a `T` time section is
/// rejected rather than silently ignored.
fn parse_iso8601(body: &str, original: &str) -> Result<i64, Error> {
    if body.is_empty() {
        return Err(window_error(original, "has no fields"));
    }
    let mut total: i64 = 0;
    let mut digits = String::new();
    for ch in body.chars() {
        if ch.is_ascii_digit() {
            digits.push(ch);
            continue;
        }
        if digits.is_empty() {
            return Err(window_error(
                original,
                &format!("field {ch:?} has no magnitude"),
            ));
        }
        let magnitude: i64 = digits
            .parse()
            .map_err(|_| window_error(original, "has a non-numeric magnitude"))?;
        digits.clear();
        // Date designators only: Y, M (months — date context), W, D.
        let factor = match ch {
            'Y' => SECONDS_PER_YEAR,
            'M' => SECONDS_PER_MONTH,
            'W' => SECONDS_PER_WEEK,
            'D' => SECONDS_PER_DAY,
            _ => {
                return Err(window_error(
                    original,
                    &format!("has an unsupported ISO 8601 designator {ch:?}"),
                ));
            }
        };
        total = total
            .checked_add(
                magnitude
                    .checked_mul(factor)
                    .ok_or_else(|| window_error(original, "overflows"))?,
            )
            .ok_or_else(|| window_error(original, "overflows"))?;
    }
    if !digits.is_empty() {
        return Err(window_error(
            original,
            &format!("ends with a magnitude {digits:?} lacking a designator"),
        ));
    }
    reject_non_positive(total, original)
}

/// Multiply a magnitude by its unit factor, rejecting negatives and
/// overflow.
fn checked_window(magnitude: i64, factor: i64, spec: &str) -> Result<i64, Error> {
    if magnitude < 0 {
        return Err(window_error(spec, "is negative"));
    }
    let product = magnitude
        .checked_mul(factor)
        .ok_or_else(|| window_error(spec, "overflows"))?;
    reject_non_positive(product, spec)
}

/// A zero-length window degenerates the walk (its boundary collapses
/// onto `now`, admitting no history), so reject it rather than silently
/// producing an empty result.
fn reject_non_positive(seconds: i64, spec: &str) -> Result<i64, Error> {
    if seconds <= 0 {
        return Err(window_error(spec, "is not a positive duration"));
    }
    Ok(seconds)
}

#[cfg(test)]
#[path = "options_tests.rs"]
mod tests;