Skip to main content

orch/engine/git/
commit.rs

1//! How orch commits. A repository that uses shipcheck commits through `shipcheck commit`, which
2//! commits only a tree its checks passed, any other repository through git
3
4use super::shipcheck::Shipcheck;
5use std::path::Path;
6use std::process::Output;
7
8use tokio::process::Command;
9
10use crate::cmd::CommandErrorContext;
11use crate::config;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Tool {
15    Git,
16    Shipcheck,
17}
18
19impl Tool {
20    /// The same rule the agent prompt follows: shipcheck when the repository opts in and the
21    /// installed shipcheck has `commit`, git otherwise
22    pub async fn detect(dir: &Path) -> Self {
23        // Without the file there is nothing to ask, and asking runs `shipcheck --help`
24        if !dir.join("shipcheck.toml").exists() {
25            return Tool::Git;
26        }
27
28        match Shipcheck::detect(dir).await {
29            Shipcheck::Available => Tool::Shipcheck,
30            Shipcheck::Absent | Shipcheck::NotInstalled | Shipcheck::Outdated => Tool::Git,
31        }
32    }
33}
34
35/// Whether a commit may skip shipcheck's gate
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum When {
38    /// Only a tree shipcheck already passed, for steps during a session
39    Tested,
40    /// Commit anyway, for the end of a session, so the agent's work is never left uncommitted.
41    /// shipcheck's hooks run the checks when the branch is pushed
42    Always,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub enum Outcome {
47    Committed,
48    Nothing,
49    /// The commit did not happen, and the tree is as it was. shipcheck refuses a tree without a passing run
50    Refused {
51        by: Tool,
52        reason: String,
53    },
54}
55
56fn identity(agent: &str) -> (String, String) {
57    let name = config::get("git.name").unwrap_or_else(|_| format!("{agent}[bot]"));
58    let email = config::get("git.email")
59        .unwrap_or_else(|_| format!("{agent}[bot]@users.noreply.github.com"));
60    (name, email)
61}
62
63/// The git commit behind every orch commit: the agent's identity, and never the operator's signing agent
64pub async fn git_commit(dir: &Path, message: &str, agent: &str) -> anyhow::Result<Output> {
65    let (name, email) = identity(agent);
66    Command::new("git")
67        .args(["-c", "commit.gpgsign=false", "commit", "-m", message])
68        .env("GIT_AUTHOR_NAME", &name)
69        .env("GIT_COMMITTER_NAME", &name)
70        .env("GIT_AUTHOR_EMAIL", &email)
71        .env("GIT_COMMITTER_EMAIL", &email)
72        .current_dir(dir)
73        .output_with_context()
74        .await
75}
76
77async fn shipcheck_commit(
78    dir: &Path,
79    bin: &Path,
80    message: &str,
81    agent: &str,
82) -> anyhow::Result<Outcome> {
83    let (name, email) = identity(agent);
84    let out = Command::new(bin)
85        .args(["commit", "-m", message])
86        .env("GIT_AUTHOR_NAME", &name)
87        .env("GIT_COMMITTER_NAME", &name)
88        .env("GIT_AUTHOR_EMAIL", &email)
89        .env("GIT_COMMITTER_EMAIL", &email)
90        .current_dir(dir)
91        .output_with_context()
92        .await?;
93    if out.status.success() {
94        return Ok(Outcome::Committed);
95    }
96
97    let why = String::from_utf8_lossy(&out.stderr).trim().to_string();
98    Ok(Outcome::Refused {
99        by: Tool::Shipcheck,
100        reason: format!("shipcheck commit refused, run `shipcheck run` first: {why}"),
101    })
102}
103
104/// Commit every change in `dir` with the tool the repository uses
105pub async fn commit_all(
106    dir: &Path,
107    message: &str,
108    agent: &str,
109    when: When,
110) -> anyhow::Result<Outcome> {
111    let tool = Tool::detect(dir).await;
112    let bin = which::which("shipcheck").unwrap_or_else(|_| "shipcheck".into());
113    commit_with(dir, tool, &bin, message, agent, when).await
114}
115
116async fn commit_with(
117    dir: &Path,
118    tool: Tool,
119    shipcheck: &Path,
120    message: &str,
121    agent: &str,
122    when: When,
123) -> anyhow::Result<Outcome> {
124    if !has_changes(dir).await {
125        return Ok(Outcome::Nothing);
126    }
127
128    if tool == Tool::Shipcheck {
129        let outcome = shipcheck_commit(dir, shipcheck, message, agent).await?;
130        let Outcome::Refused { reason, .. } = &outcome else {
131            return Ok(outcome);
132        };
133        if when == When::Tested {
134            return Ok(outcome);
135        }
136
137        tracing::info!(reason = %reason, "committing untested work through git at the end of the session");
138    }
139
140    let add = Command::new("git")
141        .args(["add", "-A"])
142        .current_dir(dir)
143        .output_with_context()
144        .await?;
145    if !add.status.success() {
146        tracing::warn!("git add -A failed");
147        return Ok(Outcome::Refused {
148            by: Tool::Git,
149            reason: String::from_utf8_lossy(&add.stderr).trim().to_string(),
150        });
151    }
152
153    let out = git_commit(dir, message, agent).await?;
154    if out.status.success() {
155        return Ok(Outcome::Committed);
156    }
157
158    let reason = String::from_utf8_lossy(&out.stderr).trim().to_string();
159    unstage(dir, &reason).await?;
160    Ok(Outcome::Refused {
161        by: Tool::Git,
162        reason,
163    })
164}
165
166/// Leave a failed commit's files unstaged, so the next check sees them and can retry cleanly
167async fn unstage(dir: &Path, commit_err: &str) -> anyhow::Result<()> {
168    let restore = Command::new("git")
169        .args(["restore", "--staged", "."])
170        .current_dir(dir)
171        .output_with_context()
172        .await;
173    let restore_err = match restore {
174        Ok(o) if o.status.success() => return Ok(()),
175        Ok(o) => String::from_utf8_lossy(&o.stderr).trim().to_string(),
176        Err(e) => e.to_string(),
177    };
178    tracing::warn!(err = %restore_err, "git restore --staged failed, falling back to git reset HEAD -- .");
179    let reset = Command::new("git")
180        .args(["reset", "HEAD", "--", "."])
181        .current_dir(dir)
182        .output_with_context()
183        .await?;
184    if !reset.status.success() {
185        anyhow::bail!(
186            "git commit failed and cleanup failed (git restore --staged + git reset HEAD -- .): commit stderr: {commit_err}; restore: {restore_err}; reset stderr: {}",
187            String::from_utf8_lossy(&reset.stderr).trim()
188        );
189    }
190
191    Ok(())
192}
193
194/// Check if there are uncommitted changes in the working directory.
195pub async fn has_changes(dir: &Path) -> bool {
196    // Check for staged, unstaged, and untracked files
197    let diff = Command::new("git")
198        .args(["diff", "--quiet"])
199        .current_dir(dir)
200        .status()
201        .await;
202
203    let cached = Command::new("git")
204        .args(["diff", "--cached", "--quiet"])
205        .current_dir(dir)
206        .status()
207        .await;
208
209    let untracked = Command::new("git")
210        .args(["ls-files", "--others", "--exclude-standard"])
211        .current_dir(dir)
212        .output_with_context()
213        .await;
214
215    let has_diff = diff.is_ok_and(|s| !s.success());
216    let has_cached = cached.is_ok_and(|s| !s.success());
217    let has_untracked =
218        untracked.is_ok_and(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty());
219
220    has_diff || has_cached || has_untracked
221}
222
223#[cfg(test)]
224mod tests {
225    use std::fs;
226    use std::fs::Permissions;
227    use std::os::unix::fs::PermissionsExt;
228    use std::path::PathBuf;
229    use std::process;
230
231    use super::*;
232
233    fn git(dir: &Path, args: &[&str]) -> String {
234        let out = process::Command::new("git")
235            .args([
236                "-c",
237                "user.name=T",
238                "-c",
239                "user.email=t@t",
240                "-c",
241                "commit.gpgsign=false",
242            ])
243            .args(args)
244            .current_dir(dir)
245            .output()
246            .unwrap();
247        assert!(
248            out.status.success(),
249            "git {args:?}: {}",
250            String::from_utf8_lossy(&out.stderr)
251        );
252        String::from_utf8_lossy(&out.stdout).to_string()
253    }
254
255    fn repo() -> tempfile::TempDir {
256        let dir = tempfile::tempdir().unwrap();
257        git(dir.path(), &["init", "-b", "main"]);
258        fs::write(dir.path().join("base.txt"), "base").unwrap();
259        git(dir.path(), &["add", "base.txt"]);
260        git(dir.path(), &["commit", "-m", "base"]);
261        dir
262    }
263
264    /// A stand-in for shipcheck: `ok` commits like `shipcheck commit`, anything else refuses
265    fn fake_shipcheck(dir: &Path, ok: bool) -> PathBuf {
266        let bin = dir.join("shipcheck");
267        let body = if ok {
268            "#!/bin/sh\ngit add -A && git -c commit.gpgsign=false commit -q -m \"$3\"\n"
269        } else {
270            "#!/bin/sh\necho 'no passing result for this tree' >&2\nexit 1\n"
271        };
272        fs::write(&bin, body).unwrap();
273        fs::set_permissions(&bin, Permissions::from_mode(0o755)).unwrap();
274        bin
275    }
276
277    #[tokio::test]
278    async fn git_commits_every_change_and_reports_nothing_on_a_clean_tree() {
279        let dir = repo();
280        let missing = Path::new("/nonexistent/shipcheck");
281        fs::write(dir.path().join("a.txt"), "a").unwrap();
282        let out = commit_with(
283            dir.path(),
284            Tool::Git,
285            missing,
286            "step",
287            "claude",
288            When::Tested,
289        )
290        .await
291        .unwrap();
292        assert_eq!(out, Outcome::Committed);
293        assert!(
294            git(dir.path(), &["log", "-1", "--format=%s%n%an"]).starts_with("step\nclaude[bot]")
295        );
296        let out = commit_with(
297            dir.path(),
298            Tool::Git,
299            missing,
300            "again",
301            "claude",
302            When::Tested,
303        )
304        .await
305        .unwrap();
306        assert_eq!(out, Outcome::Nothing);
307    }
308
309    #[tokio::test]
310    async fn a_shipcheck_refusal_commits_nothing_and_leaves_the_tree() {
311        let dir = repo();
312        let bins = tempfile::tempdir().unwrap();
313        let bin = fake_shipcheck(bins.path(), false);
314        let head = git(dir.path(), &["rev-parse", "HEAD"]);
315        fs::write(dir.path().join("untested.txt"), "x").unwrap();
316        let out = commit_with(
317            dir.path(),
318            Tool::Shipcheck,
319            &bin,
320            "step",
321            "claude",
322            When::Tested,
323        )
324        .await
325        .unwrap();
326        match out {
327            Outcome::Refused { by, reason } => {
328                assert_eq!(by, Tool::Shipcheck);
329                assert!(reason.contains("shipcheck run"), "{reason}");
330            }
331            other => panic!("expected a refusal, got {other:?}"),
332        }
333        assert_eq!(git(dir.path(), &["rev-parse", "HEAD"]), head);
334        assert_eq!(
335            git(dir.path(), &["status", "--porcelain"]),
336            "?? untested.txt\n"
337        );
338    }
339
340    #[tokio::test]
341    async fn an_accepting_shipcheck_commits() {
342        let dir = repo();
343        let bins = tempfile::tempdir().unwrap();
344        let bin = fake_shipcheck(bins.path(), true);
345        fs::write(dir.path().join("tested.txt"), "x").unwrap();
346        let out = commit_with(
347            dir.path(),
348            Tool::Shipcheck,
349            &bin,
350            "tested step",
351            "claude",
352            When::Tested,
353        )
354        .await
355        .unwrap();
356        assert_eq!(out, Outcome::Committed);
357        assert_eq!(
358            git(dir.path(), &["log", "-1", "--format=%s"]).trim(),
359            "tested step"
360        );
361    }
362
363    #[tokio::test]
364    async fn the_end_of_a_session_commits_untested_work_through_git() {
365        let dir = repo();
366        let bins = tempfile::tempdir().unwrap();
367        let bin = fake_shipcheck(bins.path(), false);
368        fs::write(dir.path().join("untested.txt"), "x").unwrap();
369        let out = commit_with(
370            dir.path(),
371            Tool::Shipcheck,
372            &bin,
373            "final",
374            "claude",
375            When::Always,
376        )
377        .await
378        .unwrap();
379        assert_eq!(out, Outcome::Committed);
380        assert_eq!(git(dir.path(), &["status", "--porcelain"]), "");
381        assert_eq!(
382            git(dir.path(), &["log", "-1", "--format=%s"]).trim(),
383            "final"
384        );
385    }
386}