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/// Resolve the base ref of an audit rooted at `root`.
53///
54/// The order is: the explicit ref, then the `FALLOW_AUDIT_BASE` override
55/// (issue #1168: a consumer can pin the base without editing a generated gate
56/// script), then auto-detection. Each ref is validated before git sees it.
57///
58/// # Errors
59///
60/// Returns [`AuditBaseError::InvalidRef`] for a ref that is not a valid git
61/// ref, and [`AuditBaseError::NotDetected`] when no base branch can be found.
62pub fn resolve_audit_base(
63    root: &Path,
64    explicit: Option<&str>,
65) -> Result<ResolvedAuditBase, AuditBaseError> {
66    resolve_audit_base_with_override(
67        root,
68        explicit,
69        parse_audit_base_override(std::env::var("FALLOW_AUDIT_BASE").ok()),
70    )
71}
72
73fn resolve_audit_base_with_override(
74    root: &Path,
75    explicit: Option<&str>,
76    env_override: Option<String>,
77) -> Result<ResolvedAuditBase, AuditBaseError> {
78    if let Some(explicit) = explicit {
79        validate(explicit, AuditBaseOrigin::Explicit)?;
80        return Ok(ResolvedAuditBase {
81            git_ref: explicit.to_string(),
82            description: None,
83            inherited_refs: Vec::new(),
84        });
85    }
86    if let Some(env_ref) = env_override {
87        validate(&env_ref, AuditBaseOrigin::Environment)?;
88        return Ok(ResolvedAuditBase {
89            description: Some(format!("FALLOW_AUDIT_BASE={env_ref}")),
90            git_ref: env_ref,
91            inherited_refs: Vec::new(),
92        });
93    }
94    let detected =
95        repo_refs::auto_detect_audit_base_ref(root).ok_or(AuditBaseError::NotDetected)?;
96    validate(&detected.git_ref, AuditBaseOrigin::Detected)?;
97    Ok(detected)
98}
99
100/// Resolve the base ref of an audit rooted at `root` from the candidates
101/// that the resolver decided: the named base, then auto-detection, then the
102/// fallback.
103///
104/// # Errors
105///
106/// Returns [`AuditBaseError::InvalidRef`] for a ref that is not a valid git
107/// ref, and [`AuditBaseError::NotDetected`] when no candidate gives a base.
108pub fn resolve_audit_base_decided(
109    root: &Path,
110    decision: &AuditBaseDecision,
111) -> Result<ResolvedAuditBase, AuditBaseError> {
112    if let Some(named) = &decision.named {
113        let value = named.value().clone();
114        return if matches!(named.source(), Source::Environment { .. }) {
115            resolve_audit_base_with_override(root, None, Some(value))
116        } else {
117            resolve_audit_base_with_override(root, Some(&value), None)
118        };
119    }
120    match resolve_audit_base_with_override(root, None, None) {
121        Err(AuditBaseError::NotDetected) => {
122            let Some(fallback) = &decision.fallback else {
123                return Err(AuditBaseError::NotDetected);
124            };
125            validate(fallback.value(), AuditBaseOrigin::ChangedSince)?;
126            Ok(ResolvedAuditBase {
127                description: Some(format!("FALLOW_CHANGED_SINCE={}", fallback.value())),
128                git_ref: fallback.value().clone(),
129                inherited_refs: Vec::new(),
130            })
131        }
132        other => other,
133    }
134}
135
136fn validate(value: &str, origin: AuditBaseOrigin) -> Result<(), AuditBaseError> {
137    fallow_engine::validate::validate_git_ref(value)
138        .map(|_| ())
139        .map_err(|reason| AuditBaseError::InvalidRef {
140            origin,
141            value: value.to_string(),
142            reason,
143        })
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn the_override_is_trimmed_and_an_empty_one_is_unset() {
152        assert_eq!(parse_audit_base_override(None), None);
153        assert_eq!(parse_audit_base_override(Some(String::new())), None);
154        assert_eq!(parse_audit_base_override(Some("   ".to_string())), None);
155        assert_eq!(
156            parse_audit_base_override(Some("  origin/main  ".to_string())),
157            Some("origin/main".to_string())
158        );
159    }
160
161    #[test]
162    fn an_explicit_ref_wins_over_the_override() {
163        let resolved = resolve_audit_base_with_override(
164            Path::new("."),
165            Some("main"),
166            Some("upstream/main".to_string()),
167        )
168        .expect("explicit ref resolves");
169        assert_eq!(resolved.git_ref, "main");
170        assert_eq!(resolved.description, None);
171    }
172
173    #[test]
174    fn the_override_names_its_source() {
175        let resolved = resolve_audit_base_with_override(
176            Path::new("."),
177            None,
178            Some("upstream/main".to_string()),
179        )
180        .expect("override resolves");
181        assert_eq!(resolved.git_ref, "upstream/main");
182        assert_eq!(
183            resolved.description.as_deref(),
184            Some("FALLOW_AUDIT_BASE=upstream/main")
185        );
186    }
187
188    #[test]
189    fn an_invalid_override_names_its_origin() {
190        let error = resolve_audit_base_with_override(
191            Path::new("."),
192            None,
193            Some("--upload-pack=evil".to_string()),
194        )
195        .expect_err("an option-like ref is refused");
196        assert!(
197            matches!(
198                error,
199                AuditBaseError::InvalidRef {
200                    origin: AuditBaseOrigin::Environment,
201                    ..
202                }
203            ),
204            "{error:?}"
205        );
206    }
207}