Skip to main content

blyte_cli/
provenance.rs

1//! Records the git state of each directory a research run may read, so the
2//! report can say what was read rather than leave the reader to guess.
3
4use std::path::{Path, PathBuf};
5use std::process::{Command, Output};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum SourceState {
9    /// The path is not inside a git work tree.
10    NotGit,
11    Git {
12        /// Full commit id of HEAD.
13        head: String,
14        /// None when HEAD is detached.
15        branch: Option<String>,
16        /// Lines of `git status --porcelain`.
17        uncommitted: usize,
18        /// e.g. "origin/main"; None when origin/HEAD is not set.
19        default_ref: Option<String>,
20        /// (behind, ahead) of HEAD against `default_ref`; None when `default_ref` is None.
21        behind_ahead: Option<(usize, usize)>,
22    },
23    /// A git command failed unexpectedly: the command and its stderr.
24    Unknown(String),
25}
26
27/// Runs one git command in `path`. A spawn failure is an error naming the command.
28fn run_git(path: &Path, args: &[&str]) -> Result<Output, String> {
29    Command::new("git")
30        .args(args)
31        .current_dir(path)
32        .output()
33        .map_err(|e| format!("git {}: {e}", args.join(" ")))
34}
35
36fn stdout_trimmed(out: &Output) -> String {
37    String::from_utf8_lossy(&out.stdout).trim().to_string()
38}
39
40fn failure(args: &[&str], out: &Output) -> String {
41    let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
42    format!("git {}: {stderr}", args.join(" "))
43}
44
45/// Runs a `git symbolic-ref -q` style command where exit 1 with empty output
46/// means "not set". Returns Ok(None) for that case.
47fn optional_ref(path: &Path, args: &[&str]) -> Result<Option<String>, String> {
48    let out = run_git(path, args)?;
49    if out.status.success() {
50        let value = stdout_trimmed(&out);
51        if value.is_empty() {
52            return Err(failure(args, &out));
53        }
54        return Ok(Some(value));
55    }
56    if out.status.code() == Some(1) && stdout_trimmed(&out).is_empty() {
57        return Ok(None);
58    }
59    Err(failure(args, &out))
60}
61
62fn git_state(path: &Path) -> Result<SourceState, String> {
63    let inside = run_git(path, &["rev-parse", "--is-inside-work-tree"])?;
64    if !inside.status.success() {
65        let stderr = String::from_utf8_lossy(&inside.stderr);
66        if stderr.contains("not a git repository") {
67            return Ok(SourceState::NotGit);
68        }
69        return Err(failure(&["rev-parse", "--is-inside-work-tree"], &inside));
70    }
71    if stdout_trimmed(&inside) != "true" {
72        return Ok(SourceState::NotGit);
73    }
74
75    let head_args = ["rev-parse", "HEAD"];
76    let head_out = run_git(path, &head_args)?;
77    if !head_out.status.success() {
78        return Err(failure(&head_args, &head_out));
79    }
80    let head = stdout_trimmed(&head_out);
81
82    let branch = optional_ref(path, &["symbolic-ref", "--short", "-q", "HEAD"])?;
83
84    let status_args = ["status", "--porcelain"];
85    let status_out = run_git(path, &status_args)?;
86    if !status_out.status.success() {
87        return Err(failure(&status_args, &status_out));
88    }
89    let uncommitted = String::from_utf8_lossy(&status_out.stdout)
90        .lines()
91        .filter(|l| !l.trim().is_empty())
92        .count();
93
94    let default_ref = optional_ref(
95        path,
96        &["symbolic-ref", "--short", "-q", "refs/remotes/origin/HEAD"],
97    )?;
98
99    let behind_ahead = match &default_ref {
100        None => None,
101        Some(default) => {
102            let range = format!("HEAD...{default}");
103            let rev_args = ["rev-list", "--left-right", "--count", range.as_str()];
104            let out = run_git(path, &rev_args)?;
105            if !out.status.success() {
106                return Err(failure(&rev_args, &out));
107            }
108            let text = stdout_trimmed(&out);
109            let parsed: Vec<&str> = text.split_whitespace().collect();
110            let numbers: Result<Vec<usize>, _> =
111                parsed.iter().map(|s| s.parse::<usize>()).collect();
112            match numbers {
113                // rev-list prints "<only in HEAD> <only in default>": ahead, behind.
114                Ok(v) if v.len() == 2 => Some((v[1], v[0])),
115                _ => {
116                    return Err(format!(
117                        "git rev-list --left-right --count: unexpected output `{text}`"
118                    ))
119                }
120            }
121        }
122    };
123
124    Ok(SourceState::Git {
125        head,
126        branch,
127        uncommitted,
128        default_ref,
129        behind_ahead,
130    })
131}
132
133/// The git state of `path`. Never guesses: a failing command yields `Unknown`.
134pub fn source_state(path: &Path) -> SourceState {
135    match git_state(path) {
136        Ok(state) => state,
137        Err(msg) => SourceState::Unknown(msg),
138    }
139}
140
141fn describe(path: &Path, state: &SourceState) -> String {
142    let p = path.display();
143    match state {
144        SourceState::NotGit => format!("- `{p}`: not a git repository"),
145        SourceState::Unknown(msg) => format!("- `{p}`: unknown ({msg})"),
146        SourceState::Git {
147            head,
148            branch,
149            uncommitted,
150            default_ref,
151            behind_ahead,
152        } => {
153            let position = match branch {
154                Some(b) => format!("branch `{b}` at `{head}`"),
155                None => format!("detached HEAD at `{head}`"),
156            };
157            let distance = match (default_ref, behind_ahead) {
158                (Some(default), Some((behind, ahead))) => {
159                    if *behind == 0 && *ahead == 0 {
160                        format!("level with `{default}` (as last fetched)")
161                    } else {
162                        format!(
163                            "{behind} behind and {ahead} ahead of `{default}` (as last fetched)"
164                        )
165                    }
166                }
167                _ => "no `origin/HEAD` to compare with".to_string(),
168            };
169            let work = match uncommitted {
170                0 => "clean".to_string(),
171                1 => "1 uncommitted change".to_string(),
172                n => format!("{n} uncommitted changes"),
173            };
174            format!("- `{p}`: {position}, {distance}, {work}")
175        }
176    }
177}
178
179/// The "Source state" block that research prompts and reports carry.
180pub fn render(sources: &[(PathBuf, SourceState)]) -> String {
181    let mut out = String::from("## Source state (written by the harness)\n\n");
182    for (path, state) in sources {
183        out.push_str(&describe(path, state));
184        out.push('\n');
185    }
186    out.push_str(
187        "\nThis is what the files on disk were when the run started. It is not necessarily the default branch.\n\
188         Commit ids not listed here or shown in tool output must not be cited.",
189    );
190    out
191}
192
193/// The first lines of a research report whose run did not end `verified`.
194pub fn unverified_banner(outcome: &str, turns: Option<u64>) -> String {
195    let after = match turns {
196        Some(n) => format!(" after {n} turns"),
197        None => String::new(),
198    };
199    format!(
200        "> **Not verified.** This research run ended as `{outcome}`{after}. The report below did not pass blyte's checks and may be an unfinished draft: check it before relying on it.\n\n"
201    )
202}
203
204/// Put `unverified_banner` at the top of the report at `path`, unless `outcome` is "verified".
205/// The rest of the file is kept byte for byte. A file that cannot be read or written is an error.
206pub fn mark_if_unverified(path: &Path, outcome: &str, turns: Option<u64>) -> std::io::Result<()> {
207    if outcome == "verified" {
208        return Ok(());
209    }
210    let body = std::fs::read(path)?;
211    let banner = unverified_banner(outcome, turns);
212    if body.starts_with(banner.as_bytes()) {
213        return Ok(());
214    }
215    let mut combined = Vec::with_capacity(banner.len() + body.len());
216    combined.extend_from_slice(banner.as_bytes());
217    combined.extend_from_slice(&body);
218    std::fs::write(path, combined)
219}