Skip to main content

fallow_engine/resolved_run/
audit_base.rs

1//! The base ref of an audit, before git sees it.
2//!
3//! The order is the base ref that the caller names, then
4//! `FALLOW_AUDIT_BASE`, then the base that the audit detects from the
5//! upstream or the remote default branch. Only when the audit detects no
6//! base does the MCP server use `FALLOW_CHANGED_SINCE`. The detection reads
7//! git, so the caller of [`decide_audit_base`] runs it.
8
9use fallow_config::{CommandKind, EnvVar, RunInputs};
10use fallow_types::sourced::{Scope, Source, Sourced};
11
12use super::env_policy::applies;
13
14/// The base ref candidates of one audit.
15#[derive(Debug, Clone, Default, PartialEq, Eq)]
16pub struct AuditBaseDecision {
17    /// The base ref that the caller or `FALLOW_AUDIT_BASE` names. `None`
18    /// means the audit detects the base.
19    pub named: Option<Sourced<String>>,
20    /// The base ref when the audit detects no base: `FALLOW_CHANGED_SINCE`
21    /// on the MCP server.
22    pub fallback: Option<Sourced<String>>,
23}
24
25/// Decide the base ref candidates of an audit from the run inputs. A run of
26/// another command has none.
27///
28/// A `FALLOW_AUDIT_BASE` value is trimmed. An empty value, a value with only
29/// spaces and a value that is not valid UTF-8 count as unset, as an empty
30/// `FALLOW_CHANGED_SINCE` does.
31#[must_use]
32pub fn decide_audit_base(inputs: &RunInputs) -> AuditBaseDecision {
33    if inputs.command != CommandKind::Audit {
34        return AuditBaseDecision::default();
35    }
36    let read = |var: EnvVar| {
37        if !applies(var, inputs.surface(), inputs.command) {
38            return None;
39        }
40        inputs
41            .env()
42            .get(var)
43            .and_then(|value| value.to_str())
44            .map(str::to_owned)
45    };
46    let environment = |value: String, var: EnvVar| {
47        Sourced::new(
48            value,
49            Source::Environment { name: var.name() },
50            Scope::Global,
51        )
52    };
53    let named = inputs
54        .audit_base
55        .as_ref()
56        .map(|given| {
57            Sourced::new(
58                given.value.clone(),
59                Source::Given {
60                    origin: given.origin,
61                },
62                Scope::Global,
63            )
64        })
65        .or_else(|| {
66            read(EnvVar::AuditBase)
67                .map(|value| value.trim().to_owned())
68                .filter(|value| !value.is_empty())
69                .map(|value| environment(value, EnvVar::AuditBase))
70        });
71    let fallback = read(EnvVar::ChangedSince)
72        .filter(|value| !value.is_empty())
73        .map(|value| environment(value, EnvVar::ChangedSince));
74    AuditBaseDecision { named, fallback }
75}
76
77#[cfg(test)]
78#[path = "audit_base_tests.rs"]
79mod tests;