Skip to main content

magi/
foreign_checkout.rs

1//! Guarded fast-forward delivery to a hand-written branch's worktree.
2
3use std::path::{Path, PathBuf};
4
5use anyhow::{Context, Result, ensure};
6use serde::{Deserialize, Serialize};
7
8use crate::{git, run::RunState};
9
10/// A foreign checkout is evidence, never a worktree owned by the run.
11#[derive(Clone, Debug, Serialize, Deserialize)]
12pub struct ForeignCheckout {
13    /// Original branch, distinct from the isolated review branch.
14    pub branch: String,
15    /// Canonical checkout path.
16    pub path: PathBuf,
17    /// Canonical Git administration directory, to detect path replacement.
18    pub git_dir: PathBuf,
19    /// Last head delivered or observed when the review began.
20    pub synced_head: String,
21}
22
23pub(crate) fn quote(s: &str) -> String {
24    format!("'{}'", s.replace('\'', "'\\''"))
25}
26
27async fn administration(path: &Path) -> Result<PathBuf> {
28    let dir = git::git(path, &["rev-parse", "--absolute-git-dir"]).await?;
29    Ok(std::fs::canonicalize(dir.trim())?)
30}
31
32/// Inspect without modifying the checkout, including untracked files and Git operations.
33pub(crate) async fn inspect(repo: &Path, branch: &str, path: &Path) -> Result<ForeignCheckout> {
34    let checkout = ForeignCheckout {
35        branch: branch.to_owned(),
36        path: std::fs::canonicalize(path)?,
37        git_dir: administration(path).await?,
38        synced_head: git::rev_parse(repo, &format!("refs/heads/{branch}")).await?,
39    };
40    checkout.validate(repo).await?;
41    Ok(checkout)
42}
43
44impl ForeignCheckout {
45    pub(crate) async fn validate(&self, repo: &Path) -> Result<()> {
46        ensure!(
47            administration(&self.path).await? == self.git_dir,
48            "checkout was replaced"
49        );
50        ensure!(
51            git::git(
52                &self.path,
53                &[
54                    "--no-optional-locks",
55                    "status",
56                    "--porcelain",
57                    "--untracked-files=all",
58                    "--ignore-submodules=none"
59                ]
60            )
61            .await?
62            .is_empty(),
63            "checkout is dirty"
64        );
65        ensure!(
66            git::git(&self.path, &["symbolic-ref", "HEAD"]).await?
67                == format!("refs/heads/{}", self.branch),
68            "checkout switched branches"
69        );
70        let checkout_head = git::rev_parse(&self.path, "HEAD").await?;
71        let branch_head = git::rev_parse(repo, &format!("refs/heads/{}", self.branch)).await?;
72        ensure!(
73            checkout_head == self.synced_head && branch_head == self.synced_head,
74            "branch moved since the last synchronization (expected {}, checkout {}, branch {})",
75            self.synced_head,
76            checkout_head,
77            branch_head
78        );
79        for name in [
80            "locked",
81            "index.lock",
82            "HEAD.lock",
83            "rebase-merge",
84            "rebase-apply",
85            "sequencer",
86            "MERGE_HEAD",
87            "CHERRY_PICK_HEAD",
88            "REVERT_HEAD",
89            "BISECT_LOG",
90        ] {
91            ensure!(
92                !self.git_dir.join(name).exists(),
93                "checkout has a lock or Git operation in progress ({name})"
94            );
95        }
96        Ok(())
97    }
98
99    /// Fast-forward only after revalidating the original checkout and branch.
100    pub(crate) async fn deliver(&mut self, repo: &Path, head: &str) -> Result<()> {
101        self.validate(repo).await?;
102        ensure!(
103            git::is_ancestor(repo, &self.synced_head, head).await,
104            "review rewrote history; automatic delivery requires a fast-forward"
105        );
106        if head != self.synced_head {
107            git::git(
108                &self.path,
109                &[
110                    "-c",
111                    "core.hooksPath=/dev/null",
112                    "merge",
113                    "--ff-only",
114                    "--no-autostash",
115                    "--no-edit",
116                    head,
117                ],
118            )
119            .await?;
120            self.synced_head = head.to_owned();
121            self.validate(repo).await?;
122        }
123        Ok(())
124    }
125}
126
127/// Deliver the isolated head before completion or publication; failures retain both trees.
128/// Acquires the configured repository coordination lease before inspecting or delivering.
129pub(crate) async fn write_back(state: &mut RunState, head: &str) -> Result<bool> {
130    let Some(mut checkout) = state.foreign_checkout.clone() else {
131        return Ok(true);
132    };
133    let inherited = crate::repo_lock::WaitPolicy::current();
134    let wait = crate::repo_lock::WaitPolicy::new(
135        std::time::Duration::from_secs(state.config.graph.timeout_resource_wait),
136        move || inherited.cancelled(),
137    );
138    let _coordination = crate::repo_lock::SeatLease::operation_with(
139        &state.repo,
140        state.config.coordination.as_ref(),
141        &wait,
142    )
143    .await?;
144    if let Err(error) = checkout.deliver(&state.repo, head).await {
145        let shadow = state.winner().map(|w| w.branch.as_str()).unwrap_or(head);
146        let message = format!(
147            "foreign checkout delivery refused: {error:#}. Review fixes remain on `{shadow}`. After resolving the checkout, run: git -C {} merge --ff-only {}",
148            quote(&checkout.path.to_string_lossy()),
149            quote(shadow)
150        );
151        state.status = crate::run::RunStatus::Blocked;
152        state.event("foreign-checkout", &message);
153        state.save()?;
154        crate::notices::raise(
155            crate::notices::Notice::error(&format!("foreign-checkout:{}", state.id), message)
156                .link(crate::notices::Link::Run {
157                    id: state.id.clone(),
158                })
159                .about([state.id.clone()]),
160        );
161        return Ok(false);
162    }
163    state.foreign_checkout = Some(checkout);
164    state
165        .save()
166        .context("save foreign checkout synchronization")?;
167    Ok(true)
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    async fn fixture() -> (tempfile::TempDir, PathBuf, ForeignCheckout) {
175        let dir = tempfile::tempdir().unwrap();
176        let repo = dir.path().join("repo");
177        std::fs::create_dir_all(&repo).unwrap();
178        git::git(&repo, &["init", "-b", "main"]).await.unwrap();
179        git::git(&repo, &["config", "user.name", "Test"])
180            .await
181            .unwrap();
182        git::git(&repo, &["config", "user.email", "test@example.invalid"])
183            .await
184            .unwrap();
185        git::git(&repo, &["commit", "--allow-empty", "-m", "base"])
186            .await
187            .unwrap();
188        let path = dir.path().join("foreign");
189        git::worktree_add_branch(&repo, &path, "topic", "main")
190            .await
191            .unwrap();
192        let checkout = inspect(&repo, "topic", &path).await.unwrap();
193        (dir, repo, checkout)
194    }
195
196    #[tokio::test]
197    async fn locked_checkout_is_refused_without_removing_its_lock() {
198        let (_dir, repo, mut checkout) = fixture().await;
199        let lock = checkout.git_dir.join("locked");
200        std::fs::write(&lock, "operator lock").unwrap();
201        let head = checkout.synced_head.clone();
202        assert!(
203            checkout
204                .deliver(&repo, &head)
205                .await
206                .unwrap_err()
207                .to_string()
208                .contains("lock")
209        );
210        assert_eq!(std::fs::read_to_string(lock).unwrap(), "operator lock");
211        assert_eq!(git::rev_parse(&checkout.path, "HEAD").await.unwrap(), head);
212    }
213
214    #[tokio::test]
215    async fn rewritten_review_is_refused_without_moving_the_foreign_branch() {
216        let (_dir, repo, mut checkout) = fixture().await;
217        git::git(
218            &checkout.path,
219            &["commit", "--allow-empty", "-m", "original work"],
220        )
221        .await
222        .unwrap();
223        checkout.synced_head = git::rev_parse(&checkout.path, "HEAD").await.unwrap();
224        let rewritten = git::rev_parse(&repo, "main").await.unwrap();
225        assert!(
226            checkout
227                .deliver(&repo, &rewritten)
228                .await
229                .unwrap_err()
230                .to_string()
231                .contains("rewrote history")
232        );
233        assert_eq!(
234            git::rev_parse(&checkout.path, "HEAD").await.unwrap(),
235            checkout.synced_head
236        );
237        assert!(git::is_clean(&checkout.path).await.unwrap());
238    }
239}