Skip to main content

magi/
git.rs

1//! Git plumbing.
2//!
3//! magi drives the `git` CLI rather than linking a library: every operation it
4//! needs is a one-liner, and shelling out keeps the behaviour identical to what
5//! the operator sees when they inspect a run by hand.
6use std::path::{Path, PathBuf};
7use std::process::Stdio;
8
9use crate::proc::Quiet as _;
10use anyhow::{Context as _, Result, bail};
11use tokio::process::Command;
12
13/// Output of a completed `git` invocation.
14#[derive(Debug)]
15pub struct GitOut {
16    /// Exit status code, if the process was not killed by a signal.
17    pub code: Option<i32>,
18    /// Captured stdout, trailing newline trimmed.
19    pub stdout: String,
20    /// Captured stderr, trailing newline trimmed.
21    pub stderr: String,
22}
23
24impl GitOut {
25    /// Did the command succeed?
26    pub fn ok(&self) -> bool {
27        self.code == Some(0)
28    }
29}
30
31/// Run `git` in `cwd` with `args`, returning the captured output regardless of
32/// exit status.
33pub async fn git_raw(cwd: &Path, args: &[&str]) -> Result<GitOut> {
34    let out = Command::new("git")
35        .args(args)
36        .current_dir(cwd)
37        .quiet()
38        // A hook that opens an editor or a credential prompt would hang a
39        // headless run forever.
40        .env("GIT_TERMINAL_PROMPT", "0")
41        .env("GIT_EDITOR", "true")
42        .stdin(Stdio::null())
43        .output()
44        .await
45        .with_context(|| format!("spawn git {}", args.join(" ")))?;
46    Ok(GitOut {
47        code: out.status.code(),
48        stdout: String::from_utf8_lossy(&out.stdout).trim_end().to_owned(),
49        stderr: String::from_utf8_lossy(&out.stderr).trim_end().to_owned(),
50    })
51}
52
53/// Run `git`, failing on a non-zero exit status.
54pub async fn git(cwd: &Path, args: &[&str]) -> Result<String> {
55    let out = git_raw(cwd, args).await?;
56    if !out.ok() {
57        bail!(
58            "git {} failed in {} (exit {:?}): {}",
59            args.join(" "),
60            cwd.display(),
61            out.code,
62            if out.stderr.is_empty() {
63                out.stdout.as_str()
64            } else {
65                out.stderr.as_str()
66            }
67        );
68    }
69    Ok(out.stdout)
70}
71
72/// Absolute path to the top level of the working tree containing `path`.
73pub async fn toplevel(path: &Path) -> Result<PathBuf> {
74    let out = git(path, &["rev-parse", "--show-toplevel"]).await?;
75    Ok(PathBuf::from(out))
76}
77
78/// Resolve a revision to a full object id.
79pub async fn rev_parse(repo: &Path, rev: &str) -> Result<String> {
80    git(repo, &["rev-parse", rev]).await
81}
82
83/// Currently checked-out branch, or `None` when detached.
84pub async fn current_branch(repo: &Path) -> Result<Option<String>> {
85    let out = git_raw(repo, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await?;
86    Ok(if out.ok() && !out.stdout.is_empty() {
87        Some(out.stdout)
88    } else {
89        None
90    })
91}
92
93/// Is the working tree free of tracked modifications and untracked files?
94pub async fn is_clean(repo: &Path) -> Result<bool> {
95    Ok(git(repo, &["status", "--porcelain"]).await?.is_empty())
96}
97
98/// `git status --porcelain`, for reporting what is dirty.
99pub async fn status_porcelain(repo: &Path) -> Result<String> {
100    git(repo, &["status", "--porcelain"]).await
101}
102
103/// Create a worktree at `path` with a fresh branch `branch` starting at `base`.
104pub async fn worktree_add_branch(repo: &Path, path: &Path, branch: &str, base: &str) -> Result<()> {
105    if let Some(parent) = path.parent() {
106        tokio::fs::create_dir_all(parent).await.ok();
107    }
108    let path_s = path.to_string_lossy().to_string();
109    git(repo, &["worktree", "add", "-b", branch, &path_s, base])
110        .await
111        .map(|_| ())
112}
113
114/// Create a worktree at `path` with a detached HEAD at `rev`.
115pub async fn worktree_add_detached(repo: &Path, path: &Path, rev: &str) -> Result<()> {
116    if let Some(parent) = path.parent() {
117        tokio::fs::create_dir_all(parent).await.ok();
118    }
119    let path_s = path.to_string_lossy().to_string();
120    git(repo, &["worktree", "add", "--detach", &path_s, rev])
121        .await
122        .map(|_| ())
123}
124
125/// Move an existing detached worktree to `rev`, discarding local state.
126pub async fn reset_detached(worktree: &Path, rev: &str) -> Result<()> {
127    git(worktree, &["checkout", "--detach", rev]).await?;
128    git(worktree, &["reset", "--hard", rev]).await?;
129    git(worktree, &["clean", "-fdx"]).await?;
130    Ok(())
131}
132
133/// Remove a worktree. Returns `Ok(false)` when git refused (e.g. the path is
134/// already gone), so callers can keep folding the rest of a run.
135pub async fn worktree_remove(repo: &Path, path: &Path) -> Result<bool> {
136    let path_s = path.to_string_lossy().to_string();
137    let out = git_raw(repo, &["worktree", "remove", "--force", &path_s]).await?;
138    if out.ok() {
139        return Ok(true);
140    }
141    // A worktree whose directory was deleted by hand only needs pruning.
142    git_raw(repo, &["worktree", "prune"]).await?;
143    Ok(false)
144}
145
146/// Unregister a linked worktree whose directory is about to be deleted by
147/// hand, so the path can be `worktree add`-ed again.
148///
149/// A linked worktree's `.git` is a file whose `gitdir:` line names the
150/// bookkeeping entry inside its repository's admin directory; pruning from
151/// there removes the registration without touching the directory. No-op when
152/// `dir` is not a registered worktree (`.git` missing or not a `gitdir:`
153/// link): nothing was registered, nothing survives removal.
154pub async fn remove_worktree_from_linked(dir: &Path) {
155    let Ok(link) = std::fs::read_to_string(dir.join(".git")) else {
156        return;
157    };
158    let Some(admin) = link.strip_prefix("gitdir:").map(str::trim) else {
159        return;
160    };
161    // `<repo>/.git/worktrees/<name>`, so the repository's git dir is two
162    // levels up from here.
163    let admin = Path::new(admin);
164    let Some(common) = admin.parent().and_then(Path::parent) else {
165        return;
166    };
167    let common_s = common.to_string_lossy();
168    let _ = git_raw(dir, &["--git-dir", &common_s, "worktree", "prune"]).await;
169}
170
171/// Delete a branch, ignoring "not found".
172pub async fn branch_delete(repo: &Path, branch: &str) -> Result<bool> {
173    Ok(git_raw(repo, &["branch", "-D", branch]).await?.ok())
174}
175
176/// Does `branch` exist?
177pub async fn branch_exists(repo: &Path, branch: &str) -> Result<bool> {
178    let refname = format!("refs/heads/{branch}");
179    Ok(
180        git_raw(repo, &["show-ref", "--verify", "--quiet", &refname])
181            .await?
182            .ok(),
183    )
184}
185
186/// Patch of `head` against the merge base with `base`.
187pub async fn diff(worktree: &Path, base: &str, head: &str) -> Result<String> {
188    let range = format!("{base}...{head}");
189    git(
190        worktree,
191        &["diff", "--no-color", "--no-ext-diff", "-M", &range],
192    )
193    .await
194}
195
196/// `--stat` summary of `base...head`.
197pub async fn diff_stat(worktree: &Path, base: &str, head: &str) -> Result<String> {
198    let range = format!("{base}...{head}");
199    git(worktree, &["diff", "--no-color", "--stat", &range]).await
200}
201
202/// Number of files touched by `base...head`.
203pub async fn changed_files(worktree: &Path, base: &str, head: &str) -> Result<Vec<String>> {
204    let range = format!("{base}...{head}");
205    let out = git(worktree, &["diff", "--name-only", &range]).await?;
206    Ok(out.lines().map(str::to_owned).collect())
207}
208
209/// One-line log of `base..head`, oldest first.
210pub async fn log_oneline(worktree: &Path, base: &str, head: &str) -> Result<String> {
211    let range = format!("{base}..{head}");
212    git(
213        worktree,
214        &["log", "--reverse", "--format=%s%n%b%n--", &range],
215    )
216    .await
217}
218
219/// How many commits `head` is ahead of `base`.
220pub async fn commits_ahead(worktree: &Path, base: &str, head: &str) -> Result<usize> {
221    let range = format!("{base}..{head}");
222    let out = git(worktree, &["rev-list", "--count", &range]).await?;
223    Ok(out.trim().parse().unwrap_or(0))
224}
225
226/// Stage everything and commit under a neutral identity.
227///
228/// Used to rescue an agent that edited files but never committed: without this
229/// its candidate would silently be empty. The neutral identity is part of the
230/// blindness contract — a real `user.name` in a candidate's history would name
231/// the operator, and an agent-configured one would name the vendor.
232pub async fn commit_all(worktree: &Path, message: &str) -> Result<bool> {
233    if git(worktree, &["status", "--porcelain"]).await?.is_empty() {
234        return Ok(false);
235    }
236    git(worktree, &["add", "-A"]).await?;
237    let out = git_raw(
238        worktree,
239        &[
240            "-c",
241            "user.name=magi candidate",
242            "-c",
243            "user.email=magi@localhost",
244            "commit",
245            "--no-verify",
246            "-m",
247            message,
248        ],
249    )
250    .await?;
251    if !out.ok() {
252        bail!("rescue commit failed: {}", out.stderr);
253    }
254    Ok(true)
255}
256
257/// Enable `extensions.worktreeConfig` if it is not already on.
258///
259/// Returns `true` when magi turned it on, so the caller can turn it back off
260/// during cleanup and leave the repo exactly as it found it.
261pub async fn enable_worktree_config(repo: &Path) -> Result<bool> {
262    let out = git_raw(repo, &["config", "--get", "extensions.worktreeConfig"]).await?;
263    if out.ok() && out.stdout.trim() == "true" {
264        return Ok(false);
265    }
266    git(repo, &["config", "extensions.worktreeConfig", "true"]).await?;
267    Ok(true)
268}
269
270/// Undo [`enable_worktree_config`].
271pub async fn disable_worktree_config(repo: &Path) -> Result<()> {
272    git_raw(repo, &["config", "--unset", "extensions.worktreeConfig"]).await?;
273    Ok(())
274}
275
276/// Point a single worktree at its own hooks directory.
277///
278/// `core.hooksPath` is normally repo-wide; scoping it with `--worktree` keeps
279/// the operator's own hooks untouched in the primary worktree, and the setting
280/// disappears together with the worktree.
281pub async fn set_worktree_hooks_path(worktree: &Path, hooks_dir: &Path) -> Result<()> {
282    let dir = hooks_dir.to_string_lossy().replace('\\', "/");
283    git(worktree, &["config", "--worktree", "core.hooksPath", &dir])
284        .await
285        .map(|_| ())
286}
287
288/// Exclude a path from a worktree's status without touching `.gitignore`.
289pub async fn local_exclude(worktree: &Path, pattern: &str) -> Result<()> {
290    let git_dir = git(worktree, &["rev-parse", "--git-path", "info/exclude"]).await?;
291    let path = worktree.join(git_dir);
292    if let Some(parent) = path.parent() {
293        tokio::fs::create_dir_all(parent).await.ok();
294    }
295    let mut body = tokio::fs::read_to_string(&path).await.unwrap_or_default();
296    if body.lines().any(|l| l.trim() == pattern) {
297        return Ok(());
298    }
299    if !body.is_empty() && !body.ends_with('\n') {
300        body.push('\n');
301    }
302    body.push_str(pattern);
303    body.push('\n');
304    tokio::fs::write(&path, body)
305        .await
306        .with_context(|| format!("write {}", path.display()))?;
307    Ok(())
308}
309
310/// `git merge --no-ff` of `branch` into the currently checked-out branch.
311pub async fn merge_no_ff(repo: &Path, branch: &str, message: &str) -> Result<GitOut> {
312    git_raw(
313        repo,
314        &["merge", "--no-ff", "--no-edit", "-m", message, branch],
315    )
316    .await
317}
318
319/// Push a branch to `remote`.
320pub async fn push(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
321    git_raw(repo, &["push", "-u", remote, branch]).await
322}
323
324/// Force-push a branch that has been rewritten, refusing to clobber work
325/// pushed since this side last looked.
326///
327/// `--force-with-lease` rather than `--force`: a rebase replaces the branch's
328/// commits, so a plain push is rejected, but a blind force would also throw
329/// away anything a person pushed to the same branch meanwhile. The lease
330/// turns that case into a failure instead of a loss.
331pub async fn push_rewritten(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
332    git_raw(repo, &["push", "--force-with-lease", remote, branch]).await
333}
334
335/// Rebase a branch onto `onto`, inside a throwaway worktree.
336///
337/// A worktree of its own for two reasons. The repository magi runs in may be
338/// jj-colocated, where git `HEAD` is detached and a rebase in the primary
339/// tree would move it under the operator; and a rebase that hits a conflict
340/// leaves state behind, which is far easier to discard with the whole
341/// directory than to unpick in a tree somebody is using.
342///
343/// `Ok(None)` means it applied and the branch now points at the rebased
344/// commits. `Ok(Some(why))` means it did not: the branch is untouched, and
345/// the string is what git said - a person has to decide.
346pub async fn rebase_branch_in_temp(
347    repo: &Path,
348    scratch: &Path,
349    branch: &str,
350    onto: &str,
351) -> Result<Option<String>> {
352    // Removed first so a leftover from an interrupted attempt cannot make
353    // `worktree add` fail on a path that already exists.
354    worktree_remove(repo, scratch).await.ok();
355    git_raw(
356        repo,
357        &[
358            "worktree",
359            "add",
360            "--force",
361            &scratch.to_string_lossy(),
362            branch,
363        ],
364    )
365    .await?;
366
367    let out = git_raw(scratch, &["rebase", onto]).await?;
368    if out.ok() {
369        worktree_remove(repo, scratch).await.ok();
370        return Ok(None);
371    }
372    // Leave nothing half-rebased behind: abort, then drop the tree entirely.
373    git_raw(scratch, &["rebase", "--abort"]).await.ok();
374    let why = if out.stderr.trim().is_empty() {
375        out.stdout.trim().to_owned()
376    } else {
377        out.stderr.trim().to_owned()
378    };
379    worktree_remove(repo, scratch).await.ok();
380    Ok(Some(why))
381}
382
383/// Fetch one branch from `remote`, updating its remote-tracking ref.
384///
385/// The refspec is spelled out rather than left to `git fetch <remote>
386/// <branch>`, which writes `FETCH_HEAD` and updates
387/// `refs/remotes/<remote>/<branch>` only as a side effect of the remote's
388/// configured refspec. Naming the destination makes the thing this function
389/// exists for - a tracking ref that moved - the operation rather than a
390/// consequence of configuration magi does not own.
391///
392/// Honest note: a CI failure was first read as proof that some git versions do
393/// not update the tracking ref here. That was wrong - the fetch had nothing to
394/// update because the test had pushed to the wrong branch - so this is
395/// determinism, not a fix for a demonstrated portability bug.
396///
397/// Refs, not the working copy: nothing is checked out and no local branch
398/// moves, so this is safe to run while the operator has uncommitted work.
399/// Returned as a [`GitOut`] rather than an error so the caller can decide - a
400/// machine with no network must still be able to start a run.
401pub async fn fetch(repo: &Path, remote: &str, branch: &str) -> Result<GitOut> {
402    let refspec = format!("+refs/heads/{branch}:refs/remotes/{remote}/{branch}");
403    git_raw(repo, &["fetch", "--quiet", remote, &refspec]).await
404}
405
406/// Does this ref resolve?
407pub async fn rev_exists(repo: &Path, rev: &str) -> bool {
408    git_raw(repo, &["rev-parse", "--verify", "--quiet", rev])
409        .await
410        .is_ok_and(|o| o.ok())
411}
412
413#[cfg(test)]
414mod tests {
415    use super::*;
416
417    async fn scratch() -> (tempfile::TempDir, PathBuf) {
418        let dir = tempfile::tempdir().unwrap();
419        let repo = dir.path().join("repo");
420        tokio::fs::create_dir_all(&repo).await.unwrap();
421        git(&repo, &["init", "-b", "main"]).await.unwrap();
422        git(&repo, &["config", "user.name", "test"]).await.unwrap();
423        git(&repo, &["config", "user.email", "test@example.com"])
424            .await
425            .unwrap();
426        tokio::fs::write(repo.join("a.txt"), "one\n").await.unwrap();
427        git(&repo, &["add", "-A"]).await.unwrap();
428        git(&repo, &["commit", "-m", "init"]).await.unwrap();
429        (dir, repo)
430    }
431
432    #[tokio::test]
433    async fn a_branch_rebases_onto_a_moved_base_and_says_when_it_cannot() {
434        let (_g, repo) = scratch().await;
435
436        // A side branch touching a different file: rebases cleanly.
437        git(&repo, &["checkout", "-b", "side"]).await.unwrap();
438        tokio::fs::write(repo.join("b.txt"), "side\n")
439            .await
440            .unwrap();
441        git(&repo, &["add", "-A"]).await.unwrap();
442        git(&repo, &["commit", "-m", "side work"]).await.unwrap();
443
444        // main moves under it, which is what a repository merging other
445        // pull requests does to a competition that took two hours.
446        git(&repo, &["checkout", "main"]).await.unwrap();
447        tokio::fs::write(repo.join("c.txt"), "main\n")
448            .await
449            .unwrap();
450        git(&repo, &["add", "-A"]).await.unwrap();
451        git(&repo, &["commit", "-m", "main moved"]).await.unwrap();
452
453        let scratch_tree = repo.parent().unwrap().join("rebase-scratch");
454        let clean = rebase_branch_in_temp(&repo, &scratch_tree, "side", "main")
455            .await
456            .unwrap();
457        assert!(clean.is_none(), "a disjoint change rebases: {clean:?}");
458        assert_eq!(
459            commits_ahead(&repo, "main", "side").await.unwrap(),
460            1,
461            "one commit, replayed onto the new base"
462        );
463        assert!(
464            !scratch_tree.exists(),
465            "the throwaway worktree is not left behind"
466        );
467
468        // A real conflict: both sides edit the same line.
469        git(&repo, &["checkout", "-b", "clash"]).await.unwrap();
470        tokio::fs::write(repo.join("a.txt"), "clash\n")
471            .await
472            .unwrap();
473        git(&repo, &["add", "-A"]).await.unwrap();
474        git(&repo, &["commit", "-m", "clash"]).await.unwrap();
475        git(&repo, &["checkout", "main"]).await.unwrap();
476        tokio::fs::write(repo.join("a.txt"), "main edit\n")
477            .await
478            .unwrap();
479        git(&repo, &["add", "-A"]).await.unwrap();
480        git(&repo, &["commit", "-m", "main edit"]).await.unwrap();
481
482        let before = rev_parse(&repo, "clash").await.unwrap();
483        let why = rebase_branch_in_temp(&repo, &scratch_tree, "clash", "main")
484            .await
485            .unwrap()
486            .expect("a same-line clash cannot be rebased silently");
487        assert!(
488            why.to_lowercase().contains("conflict"),
489            "the reason is what git said, which is what a person needs: {why}"
490        );
491        assert_eq!(
492            rev_parse(&repo, "clash").await.unwrap(),
493            before,
494            "a failed rebase leaves the branch exactly where it was"
495        );
496        assert!(!scratch_tree.exists(), "and cleans up after itself");
497    }
498
499    #[tokio::test]
500    async fn clean_repo_reports_clean_then_dirty() {
501        let (_g, repo) = scratch().await;
502        assert!(is_clean(&repo).await.unwrap());
503        tokio::fs::write(repo.join("a.txt"), "two\n").await.unwrap();
504        assert!(!is_clean(&repo).await.unwrap());
505    }
506
507    #[tokio::test]
508    async fn worktree_lifecycle_and_diff() {
509        let (guard, repo) = scratch().await;
510        let base = rev_parse(&repo, "HEAD").await.unwrap();
511        let wt = guard.path().join("wt-a");
512        worktree_add_branch(&repo, &wt, "magi/test/a", &base)
513            .await
514            .unwrap();
515        tokio::fs::write(wt.join("b.txt"), "candidate\n")
516            .await
517            .unwrap();
518
519        assert!(commit_all(&wt, "candidate work").await.unwrap());
520        assert!(!commit_all(&wt, "nothing left").await.unwrap());
521
522        assert_eq!(commits_ahead(&wt, &base, "HEAD").await.unwrap(), 1);
523        let patch = diff(&wt, &base, "HEAD").await.unwrap();
524        assert!(patch.contains("b.txt"), "patch was: {patch}");
525        assert_eq!(
526            changed_files(&wt, &base, "HEAD").await.unwrap(),
527            ["b.txt".to_owned()]
528        );
529
530        // The rescue commit must not carry the operator's identity.
531        let author = git(&wt, &["log", "-1", "--format=%an <%ae>"])
532            .await
533            .unwrap();
534        assert_eq!(author, "magi candidate <magi@localhost>");
535
536        assert!(worktree_remove(&repo, &wt).await.unwrap());
537        assert!(branch_exists(&repo, "magi/test/a").await.unwrap());
538        assert!(branch_delete(&repo, "magi/test/a").await.unwrap());
539        assert!(!branch_exists(&repo, "magi/test/a").await.unwrap());
540    }
541
542    #[tokio::test]
543    async fn worktree_scoped_hooks_path_does_not_leak_to_primary() {
544        let (guard, repo) = scratch().await;
545        let base = rev_parse(&repo, "HEAD").await.unwrap();
546        let wt = guard.path().join("wt-h");
547        worktree_add_branch(&repo, &wt, "magi/test/h", &base)
548            .await
549            .unwrap();
550        let hooks = guard.path().join("hooks");
551        tokio::fs::create_dir_all(&hooks).await.unwrap();
552
553        assert!(enable_worktree_config(&repo).await.unwrap());
554        set_worktree_hooks_path(&wt, &hooks).await.unwrap();
555
556        let in_wt = git(&wt, &["config", "--get", "core.hooksPath"])
557            .await
558            .unwrap();
559        assert!(!in_wt.is_empty());
560        let in_primary = git_raw(&repo, &["config", "--get", "core.hooksPath"])
561            .await
562            .unwrap();
563        assert!(
564            !in_primary.ok(),
565            "primary worktree must keep its own hooks: {in_primary:?}"
566        );
567
568        disable_worktree_config(&repo).await.unwrap();
569    }
570
571    #[tokio::test]
572    async fn local_exclude_is_idempotent() {
573        let (_g, repo) = scratch().await;
574        local_exclude(&repo, "/.magi/").await.unwrap();
575        local_exclude(&repo, "/.magi/").await.unwrap();
576        let path = repo.join(".git/info/exclude");
577        let body = tokio::fs::read_to_string(&path).await.unwrap();
578        assert_eq!(body.matches("/.magi/").count(), 1);
579    }
580}