Skip to main content

orch/engine/git/
cow.rs

1//! Copy-on-write task worktrees cloned from a per-project template by the git-cow crate, see docs/content/docs/cow-worktrees.md
2
3use crate::sys::home;
4use std::env;
5use std::path::{Path, PathBuf};
6
7use git_cow::cleanup::{self, Action, Done, Options};
8use tokio::task;
9
10fn template_dir(project: &str) -> anyhow::Result<PathBuf> {
11    Ok(home::state_dir()?.join("templates").join(project))
12}
13
14// Called after a task PR merges and before its worktree is removed.
15// Projects with a working checkout are warmed from that checkout instead
16pub async fn warm_from_merged(repo_root: &Path, project: &str, wt_dir: &Path) {
17    let (repo, wt) = (repo_root.to_path_buf(), wt_dir.to_path_buf());
18    let Ok(template) = template_dir(project) else {
19        return;
20    };
21    let res = task::spawn_blocking(move || {
22        let bare =
23            git_cow::git(&repo, &["rev-parse", "--is-bare-repository"]).is_ok_and(|v| v == "true");
24        let wt_parent = wt.parent().unwrap_or(&wt);
25        let templates = template.parent().unwrap_or(&template);
26        if !bare || !template.join(".git").exists() || !git_cow::can_clone(templates, wt_parent) {
27            return Ok(());
28        }
29        git_cow::warm(&wt, &template)
30    })
31    .await;
32    if let Ok(Err(e)) = res {
33        tracing::debug!(error = %e, "template warm-up from merged task failed");
34    }
35}
36
37// The step after a merge: git-cow removes the worktree and its local branch when the work is in
38// `base`, merged or squash-merged. False when the worktree stays, so the caller removes it
39pub async fn remove_landed(repo_root: &Path, wt_dir: &Path, base: Option<&str>) -> bool {
40    let (repo, wt) = (repo_root.to_path_buf(), wt_dir.to_path_buf());
41    let opts = Options {
42        base: base.map(String::from),
43        ..Options::default()
44    };
45    let res = task::spawn_blocking(move || {
46        let plan = cleanup::plan_worktree(&repo, &wt, &opts)?;
47        for item in plan.items() {
48            if let Action::Keep(why) = item.action() {
49                tracing::debug!(worktree = %wt.display(), state = item.state().label(), %why, "git-cow keeps the worktree");
50            }
51        }
52        let mut removed = false;
53        for done in cleanup::execute(&plan) {
54            match done {
55                Done::Removed(path) => {
56                    removed = true;
57                    tracing::info!(worktree = %path.display(), "landed worktree removed");
58                }
59                Done::Deleted { branch, backup, .. } => {
60                    tracing::info!(%branch, %backup, "landed local branch deleted");
61                }
62                Done::Failed { what, why } => {
63                    tracing::warn!(%what, %why, "git-cow cleanup left an item");
64                }
65                _ => {}
66            }
67        }
68        anyhow::Ok(removed)
69    })
70    .await;
71    match res {
72        Ok(Ok(removed)) => removed,
73        Ok(Err(e)) => {
74            tracing::debug!(error = %e, "git-cow cleanup plan failed");
75            false
76        }
77        Err(e) => {
78            tracing::warn!(error = %e, "git-cow cleanup task failed");
79            false
80        }
81    }
82}
83
84// Create `wt_dir` as a worktree of `branch` by cloning the project template checked out at `start`.
85// On error nothing is left behind and the caller falls back to `git worktree add`
86pub async fn create_worktree(
87    main_dir: &Path,
88    project: &str,
89    wt_dir: &Path,
90    branch: &str,
91    start: &str,
92) -> anyhow::Result<()> {
93    if env::var("ORCH_COW_WORKTREES").is_ok_and(|v| v == "0") {
94        anyhow::bail!("disabled by ORCH_COW_WORKTREES=0");
95    }
96    let template = template_dir(project)?;
97    let (repo, wt, branch, start) = (
98        main_dir.to_path_buf(),
99        wt_dir.to_path_buf(),
100        branch.to_string(),
101        start.to_string(),
102    );
103    task::spawn_blocking(move || git_cow::add(&repo, &template, &start, &wt, None, Some(&branch)))
104        .await??;
105    Ok(())
106}
107
108#[cfg(test)]
109mod tests {
110    use std::fs;
111    use std::process::Command;
112
113    use super::*;
114
115    fn sh(dir: &Path, args: &[&str]) {
116        let mut cmd = Command::new("git");
117        cmd.current_dir(dir);
118        // Global commit.gpgsign calls the operator's signer (1Password)
119        if args.first() == Some(&"commit") {
120            cmd.args(["-c", "commit.gpgsign=false"]);
121        }
122        let st = cmd.args(args).status().unwrap();
123        assert!(st.success(), "git {args:?}");
124    }
125
126    // CI jobs on a clone-capable volume set this so a failed probe fails the test
127    fn expect_clone() -> bool {
128        env::var("ORCH_COW_EXPECT_CLONE").is_ok_and(|v| v == "1")
129    }
130
131    fn repo_with_origin() -> (tempfile::TempDir, tempfile::TempDir, tempfile::TempDir) {
132        let remote = tempfile::tempdir().unwrap();
133        sh(remote.path(), &["init", "--bare", "-b", "main"]);
134        let project = tempfile::tempdir().unwrap();
135        sh(
136            project.path(),
137            &["clone", remote.path().to_str().unwrap(), "."],
138        );
139        sh(project.path(), &["config", "user.email", "t@t.com"]);
140        sh(project.path(), &["config", "user.name", "T"]);
141        fs::write(project.path().join("a.txt"), "a\n").unwrap();
142        fs::write(project.path().join("d.txt"), "d\n").unwrap();
143        sh(project.path(), &["add", "."]);
144        sh(project.path(), &["commit", "-m", "init"]);
145        sh(project.path(), &["push", "origin", "HEAD:main"]);
146        sh(project.path(), &["fetch", "origin"]);
147        let home = tempfile::tempdir().unwrap();
148        (remote, project, home)
149    }
150
151    #[tokio::test]
152    #[serial_test::serial(orch_home)]
153    async fn clone_gives_clean_worktree_or_falls_back() {
154        let (_remote, project, home) = repo_with_origin();
155        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
156        unsafe { env::set_var("ORCH_HOME", home.path()) };
157        let templates = home.path().join("state/templates");
158        fs::create_dir_all(&templates).unwrap();
159        let wt_dir = home.path().join("worktrees/p/task-1");
160        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
161        sh(project.path(), &["branch", "task-1", "origin/main"]);
162
163        // Volumes without clone support (ext4, HFS+) take the else branch
164        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
165        if expect_clone() {
166            assert!(
167                supported,
168                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
169            );
170        }
171        let res = create_worktree(project.path(), "p", &wt_dir, "task-1", "main").await;
172        if supported {
173            res.expect("clone path should succeed");
174            assert_eq!(fs::read_to_string(wt_dir.join("a.txt")).unwrap(), "a\n");
175            let status = Command::new("git")
176                .args(["status", "--porcelain"])
177                .current_dir(&wt_dir)
178                .output()
179                .unwrap();
180            assert!(status.stdout.is_empty(), "clone must have a clean index");
181            assert!(super::super::worktree::validate_worktree_gitdir(&wt_dir).await);
182        } else {
183            assert!(res.is_err());
184            assert!(!wt_dir.exists(), "failed clone must leave no directory");
185        }
186        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
187        unsafe { env::remove_var("ORCH_HOME") };
188    }
189
190    #[tokio::test]
191    #[serial_test::serial(orch_home)]
192    async fn branch_differing_from_template_gets_its_own_files() {
193        let (_remote, project, home) = repo_with_origin();
194        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
195        unsafe { env::set_var("ORCH_HOME", home.path()) };
196        let templates = home.path().join("state/templates");
197        fs::create_dir_all(&templates).unwrap();
198        let wt_dir = home.path().join("worktrees/p/task-3");
199        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
200
201        // Task branch: a.txt changed, b.txt added, d.txt deleted
202        sh(
203            project.path(),
204            &["checkout", "-q", "-b", "task-3", "origin/main"],
205        );
206        fs::write(project.path().join("a.txt"), "changed\n").unwrap();
207        fs::write(project.path().join("b.txt"), "b\n").unwrap();
208        fs::remove_file(project.path().join("d.txt")).unwrap();
209        sh(project.path(), &["add", "-A"]);
210        sh(project.path(), &["commit", "-m", "task"]);
211        sh(project.path(), &["checkout", "-q", "--detach"]);
212
213        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
214        if expect_clone() {
215            assert!(
216                supported,
217                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
218            );
219        }
220        if supported {
221            create_worktree(project.path(), "p", &wt_dir, "task-3", "main")
222                .await
223                .expect("clone path should succeed");
224            assert_eq!(
225                fs::read_to_string(wt_dir.join("a.txt")).unwrap(),
226                "changed\n"
227            );
228            assert_eq!(fs::read_to_string(wt_dir.join("b.txt")).unwrap(), "b\n");
229            assert!(!wt_dir.join("d.txt").exists());
230            let status = Command::new("git")
231                .args(["status", "--porcelain"])
232                .current_dir(&wt_dir)
233                .output()
234                .unwrap();
235            assert!(status.stdout.is_empty(), "clone must have a clean index");
236        }
237        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
238        unsafe { env::remove_var("ORCH_HOME") };
239    }
240
241    #[tokio::test]
242    #[serial_test::serial(orch_home)]
243    async fn checkout_ignored_dirs_reach_template_and_clone() {
244        let (_remote, project, home) = repo_with_origin();
245        fs::write(
246            project.path().join(".gitignore"),
247            "out/\n.env\n.local/\nnode/\n",
248        )
249        .unwrap();
250        sh(project.path(), &["add", "."]);
251        sh(project.path(), &["commit", "-m", "ignore"]);
252        sh(project.path(), &["push", "origin", "HEAD:main"]);
253        sh(project.path(), &["fetch", "origin"]);
254        fs::create_dir_all(project.path().join("out/sub")).unwrap();
255        fs::write(project.path().join("out/sub/dep.bin"), "dep\n").unwrap();
256        fs::create_dir_all(project.path().join(".local")).unwrap();
257        fs::write(project.path().join(".local/settings"), "x\n").unwrap();
258        fs::create_dir_all(project.path().join("pkg/a/node")).unwrap();
259        fs::write(project.path().join("pkg/a/node/dep.bin"), "nested\n").unwrap();
260        fs::create_dir_all(project.path().join("pkg/a/.hidden/node")).unwrap();
261        fs::write(project.path().join("pkg/a/.hidden/node/x"), "x\n").unwrap();
262        fs::write(project.path().join("pkg/a/keep.txt"), "k\n").unwrap();
263        fs::write(project.path().join(".env"), "secret\n").unwrap();
264
265        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
266        unsafe { env::set_var("ORCH_HOME", home.path()) };
267        let templates = home.path().join("state/templates");
268        fs::create_dir_all(&templates).unwrap();
269        let wt_dir = home.path().join("worktrees/p/task-4");
270        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
271        sh(project.path(), &["branch", "task-4", "origin/main"]);
272
273        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
274        if expect_clone() {
275            assert!(
276                supported,
277                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
278            );
279        }
280        if supported {
281            create_worktree(project.path(), "p", &wt_dir, "task-4", "main")
282                .await
283                .expect("clone path should succeed");
284            let tpl = templates.join("p");
285            for root in [&tpl, &wt_dir] {
286                assert_eq!(
287                    fs::read_to_string(root.join("out/sub/dep.bin")).unwrap(),
288                    "dep\n"
289                );
290                assert!(!root.join(".env").exists(), "loose ignored file was copied");
291                assert!(!root.join(".local").exists(), "hidden dir was copied");
292                assert!(
293                    !root.join("pkg/a/.hidden").exists(),
294                    "nested hidden dir was copied"
295                );
296                assert_eq!(
297                    fs::read_to_string(root.join("pkg/a/node/dep.bin")).unwrap(),
298                    "nested\n"
299                );
300            }
301            // The worktree keeps its own gitdir
302            assert!(wt_dir.join(".git").is_file());
303            assert_ne!(
304                fs::read_to_string(wt_dir.join(".git")).unwrap(),
305                fs::read_to_string(tpl.join(".git")).unwrap()
306            );
307            // git-cow warms the template from the checkout at most once an hour, so a second task
308            // right after the first keeps the build output the template already has
309            fs::remove_file(project.path().join("out/sub/dep.bin")).unwrap();
310            fs::write(project.path().join("out/new.bin"), "new\n").unwrap();
311            let wt2 = home.path().join("worktrees/p/task-5");
312            sh(project.path(), &["branch", "task-5", "origin/main"]);
313            create_worktree(project.path(), "p", &wt2, "task-5", "main")
314                .await
315                .unwrap();
316            assert!(wt2.join("out/sub/dep.bin").exists());
317            assert!(!wt2.join("out/new.bin").exists());
318        }
319        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
320        unsafe { env::remove_var("ORCH_HOME") };
321    }
322
323    #[tokio::test]
324    #[serial_test::serial(orch_home)]
325    async fn merged_task_ignored_dirs_reach_template_of_bare_project() {
326        let (remote, project, home) = repo_with_origin();
327        fs::write(project.path().join(".gitignore"), "out/\n").unwrap();
328        sh(project.path(), &["add", "."]);
329        sh(project.path(), &["commit", "-m", "ignore"]);
330        sh(project.path(), &["push", "origin", "HEAD:main"]);
331        let bare = home.path().join("bare.git");
332        sh(
333            home.path(),
334            &[
335                "clone",
336                "--bare",
337                remote.path().to_str().unwrap(),
338                "bare.git",
339            ],
340        );
341        sh(&bare, &["branch", "task-6", "main"]);
342
343        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
344        unsafe { env::set_var("ORCH_HOME", home.path()) };
345        let templates = home.path().join("state/templates");
346        fs::create_dir_all(&templates).unwrap();
347        let wt_dir = home.path().join("worktrees/pb/task-6");
348        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
349
350        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
351        if expect_clone() {
352            assert!(
353                supported,
354                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
355            );
356        }
357        if supported {
358            create_worktree(&bare, "pb", &wt_dir, "task-6", "main")
359                .await
360                .expect("clone path should succeed");
361            let tpl = templates.join("pb");
362            assert!(!tpl.join("out").exists());
363
364            fs::create_dir_all(wt_dir.join("out")).unwrap();
365            fs::write(wt_dir.join("out/dep.bin"), "dep\n").unwrap();
366            fs::write(wt_dir.join("loose.log"), "x\n").unwrap();
367
368            // A project with a working checkout is not warmed from tasks
369            warm_from_merged(project.path(), "pb", &wt_dir).await;
370            assert!(!tpl.join("out").exists());
371
372            warm_from_merged(&bare, "pb", &wt_dir).await;
373            assert_eq!(
374                fs::read_to_string(tpl.join("out/dep.bin")).unwrap(),
375                "dep\n"
376            );
377            assert!(!tpl.join("loose.log").exists());
378            assert!(tpl.join(".git").is_file());
379        }
380        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
381        unsafe { env::remove_var("ORCH_HOME") };
382    }
383
384    // A task worktree on `branch` with one commit, pushed, as a task leaves it before the merge
385    fn task_worktree(project: &Path, home: &Path, branch: &str) -> PathBuf {
386        let wt = home.join("worktrees/p").join(branch);
387        fs::create_dir_all(wt.parent().unwrap()).unwrap();
388        let wt_str = wt.to_str().unwrap();
389        sh(
390            project,
391            &["worktree", "add", "-b", branch, wt_str, "origin/main"],
392        );
393        fs::write(wt.join("task.txt"), "work\n").unwrap();
394        sh(&wt, &["add", "."]);
395        sh(&wt, &["commit", "-m", "task work"]);
396        sh(&wt, &["push", "origin", branch]);
397        wt
398    }
399
400    fn squash_merge(project: &Path, branch: &str) {
401        sh(project, &["merge", "--squash", branch]);
402        sh(project, &["commit", "-m", "task work (#1)"]);
403        sh(project, &["push", "origin", "HEAD:main"]);
404    }
405
406    fn ref_exists(project: &Path, name: &str) -> bool {
407        let out = Command::new("git")
408            .current_dir(project)
409            .args(["for-each-ref", name])
410            .output()
411            .unwrap();
412        !out.stdout.is_empty()
413    }
414
415    #[tokio::test]
416    async fn remove_landed_removes_a_squash_merged_worktree_and_keeps_a_backup() {
417        if !cleanup::squash_check_works() {
418            return;
419        }
420        let (_remote, project, home) = repo_with_origin();
421        let wt = task_worktree(project.path(), home.path(), "task-7");
422        squash_merge(project.path(), "task-7");
423
424        assert!(remove_landed(project.path(), &wt, None).await);
425        assert!(!wt.exists());
426        assert!(!ref_exists(project.path(), "refs/heads/task-7"));
427        assert!(ref_exists(project.path(), "refs/git-cow/deleted/"));
428    }
429
430    #[tokio::test]
431    async fn remove_landed_keeps_a_worktree_whose_work_is_not_in_the_base() {
432        let (_remote, project, home) = repo_with_origin();
433        let wt = task_worktree(project.path(), home.path(), "task-8");
434
435        assert!(!remove_landed(project.path(), &wt, None).await);
436        assert!(wt.join("task.txt").exists());
437        assert!(ref_exists(project.path(), "refs/heads/task-8"));
438    }
439
440    #[tokio::test]
441    async fn remove_landed_keeps_a_merged_worktree_with_an_untracked_file() {
442        if !cleanup::squash_check_works() {
443            return;
444        }
445        let (_remote, project, home) = repo_with_origin();
446        let wt = task_worktree(project.path(), home.path(), "task-9");
447        squash_merge(project.path(), "task-9");
448        // Without the file git-cow removes this worktree, as the squash-merged test shows
449        fs::write(wt.join("notes.txt"), "not committed\n").unwrap();
450
451        assert!(!remove_landed(project.path(), &wt, None).await);
452        assert!(wt.join("notes.txt").exists());
453        assert!(ref_exists(project.path(), "refs/heads/task-9"));
454    }
455
456    #[tokio::test]
457    #[serial_test::serial(orch_home)]
458    async fn env_switch_disables_clone_path() {
459        let (_remote, project, home) = repo_with_origin();
460        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
461        unsafe { env::set_var("ORCH_HOME", home.path()) };
462        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
463        unsafe { env::set_var("ORCH_COW_WORKTREES", "0") };
464        let wt_dir = home.path().join("worktrees/p/task-2");
465        let res = create_worktree(project.path(), "p", &wt_dir, "task-2", "main").await;
466        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
467        unsafe { env::remove_var("ORCH_COW_WORKTREES") };
468        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
469        unsafe { env::remove_var("ORCH_HOME") };
470        assert!(res.is_err());
471        assert!(!wt_dir.exists());
472    }
473}