Skip to main content

fallow_api/audit_run/
base_ref.rs

1//! The base ref that an audit compares against.
2
3use std::path::Path;
4
5use fallow_engine::repo_refs::{self, ResolvedAuditBase};
6use fallow_engine::resolved_run::AuditBaseDecision;
7use fallow_types::sourced::Source;
8
9/// Where an audit base ref came from.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum AuditBaseOrigin {
12    /// The caller named the ref (`--base`, `audit.base`, `changedSince`).
13    Explicit,
14    /// The `FALLOW_AUDIT_BASE` environment variable.
15    Environment,
16    /// The `FALLOW_CHANGED_SINCE` environment variable of the MCP server,
17    /// read when the audit detects no base.
18    ChangedSince,
19    /// Auto-detection from the upstream or the remote default branch.
20    Detected,
21}
22
23/// Why no audit base ref could be resolved.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum AuditBaseError {
26    /// The ref is not a valid git ref.
27    InvalidRef {
28        /// Where the ref came from.
29        origin: AuditBaseOrigin,
30        /// The ref as it was given or detected.
31        value: String,
32        /// Why the ref is not valid.
33        reason: String,
34    },
35    /// No explicit ref, no environment override, and no base branch to
36    /// detect.
37    NotDetected,
38}
39
40/// Parse a raw `FALLOW_AUDIT_BASE` value: trimmed, and `None` when it is
41/// empty or only whitespace.
42#[must_use]
43pub fn parse_audit_base_override(raw: Option<String>) -> Option<String> {
44    let trimmed = raw?.trim().to_string();
45    if trimmed.is_empty() {
46        None
47    } else {
48        Some(trimmed)
49    }
50}
51
52/// The `FALLOW_AUDIT_BASE` override of the process, parsed with
53/// [`parse_audit_base_override`].
54#[must_use]
55pub fn audit_base_override() -> Option<String> {
56    parse_audit_base_override(std::env::var("FALLOW_AUDIT_BASE").ok())
57}
58
59/// Resolve the base ref of an audit rooted at `root`.
60///
61/// The order is: the explicit ref, then the `FALLOW_AUDIT_BASE` override
62/// (issue #1168: a consumer can pin the base without editing a generated gate
63/// script), then auto-detection. Each ref is validated before git sees it.
64///
65/// # Errors
66///
67/// Returns [`AuditBaseError::InvalidRef`] for a ref that is not a valid git
68/// ref, and [`AuditBaseError::NotDetected`] when no base branch can be found.
69pub fn resolve_audit_base(
70    root: &Path,
71    explicit: Option<&str>,
72) -> Result<ResolvedAuditBase, AuditBaseError> {
73    resolve_audit_base_with_override(root, explicit, audit_base_override())
74}
75
76fn resolve_audit_base_with_override(
77    root: &Path,
78    explicit: Option<&str>,
79    env_override: Option<String>,
80) -> Result<ResolvedAuditBase, AuditBaseError> {
81    if let Some(explicit) = explicit {
82        validate(explicit, AuditBaseOrigin::Explicit)?;
83        return Ok(ResolvedAuditBase {
84            git_ref: explicit.to_string(),
85            description: None,
86            inherited_refs: Vec::new(),
87        });
88    }
89    if let Some(env_ref) = env_override {
90        validate(&env_ref, AuditBaseOrigin::Environment)?;
91        return Ok(ResolvedAuditBase {
92            description: Some(format!("FALLOW_AUDIT_BASE={env_ref}")),
93            git_ref: env_ref,
94            inherited_refs: Vec::new(),
95        });
96    }
97    let detected =
98        repo_refs::auto_detect_audit_base_ref(root).ok_or(AuditBaseError::NotDetected)?;
99    validate(&detected.git_ref, AuditBaseOrigin::Detected)?;
100    Ok(detected)
101}
102
103/// Resolve the base ref of an audit rooted at `root` from the candidates
104/// that the resolver decided: the named base, then auto-detection, then the
105/// fallback.
106///
107/// # Errors
108///
109/// Returns [`AuditBaseError::InvalidRef`] for a ref that is not a valid git
110/// ref, and [`AuditBaseError::NotDetected`] when no candidate gives a base.
111pub fn resolve_audit_base_decided(
112    root: &Path,
113    decision: &AuditBaseDecision,
114) -> Result<ResolvedAuditBase, AuditBaseError> {
115    if let Some(named) = &decision.named {
116        let value = named.value().clone();
117        return if matches!(named.source(), Source::Environment { .. }) {
118            resolve_audit_base_with_override(root, None, Some(value))
119        } else {
120            resolve_audit_base_with_override(root, Some(&value), None)
121        };
122    }
123    match resolve_audit_base_with_override(root, None, None) {
124        Err(AuditBaseError::NotDetected) => {
125            let Some(fallback) = &decision.fallback else {
126                return Err(AuditBaseError::NotDetected);
127            };
128            validate(fallback.value(), AuditBaseOrigin::ChangedSince)?;
129            Ok(ResolvedAuditBase {
130                description: Some(format!("FALLOW_CHANGED_SINCE={}", fallback.value())),
131                git_ref: fallback.value().clone(),
132                inherited_refs: Vec::new(),
133            })
134        }
135        other => other,
136    }
137}
138
139fn validate(value: &str, origin: AuditBaseOrigin) -> Result<(), AuditBaseError> {
140    fallow_engine::validate::validate_git_ref(value)
141        .map(|_| ())
142        .map_err(|reason| AuditBaseError::InvalidRef {
143            origin,
144            value: value.to_string(),
145            reason,
146        })
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn the_override_is_trimmed_and_an_empty_one_is_unset() {
155        assert_eq!(parse_audit_base_override(None), None);
156        assert_eq!(parse_audit_base_override(Some(String::new())), None);
157        assert_eq!(parse_audit_base_override(Some("   ".to_string())), None);
158        assert_eq!(
159            parse_audit_base_override(Some("  origin/main  ".to_string())),
160            Some("origin/main".to_string())
161        );
162    }
163
164    #[test]
165    fn an_explicit_ref_wins_over_the_override() {
166        let resolved = resolve_audit_base_with_override(
167            Path::new("."),
168            Some("main"),
169            Some("upstream/main".to_string()),
170        )
171        .expect("explicit ref resolves");
172        assert_eq!(resolved.git_ref, "main");
173        assert_eq!(resolved.description, None);
174    }
175
176    #[test]
177    fn the_override_names_its_source() {
178        let resolved = resolve_audit_base_with_override(
179            Path::new("."),
180            None,
181            Some("upstream/main".to_string()),
182        )
183        .expect("override resolves");
184        assert_eq!(resolved.git_ref, "upstream/main");
185        assert_eq!(
186            resolved.description.as_deref(),
187            Some("FALLOW_AUDIT_BASE=upstream/main")
188        );
189    }
190
191    #[test]
192    fn an_invalid_override_names_its_origin() {
193        let error = resolve_audit_base_with_override(
194            Path::new("."),
195            None,
196            Some("--upload-pack=evil".to_string()),
197        )
198        .expect_err("an option-like ref is refused");
199        assert!(
200            matches!(
201                error,
202                AuditBaseError::InvalidRef {
203                    origin: AuditBaseOrigin::Environment,
204                    ..
205                }
206            ),
207            "{error:?}"
208        );
209    }
210}