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/cow-worktrees.md
2
3use crate::home;
4use std::env;
5use std::path::{Path, PathBuf};
6
7use tokio::task;
8
9fn template_dir(project: &str) -> anyhow::Result<PathBuf> {
10    Ok(home::state_dir()?.join("templates").join(project))
11}
12
13// Called after a task PR merges and before its worktree is removed.
14// Projects with a working checkout are warmed from that checkout instead
15pub async fn warm_from_merged(repo_root: &Path, project: &str, wt_dir: &Path) {
16    let (repo, wt) = (repo_root.to_path_buf(), wt_dir.to_path_buf());
17    let Ok(template) = template_dir(project) else {
18        return;
19    };
20    let res = task::spawn_blocking(move || {
21        let bare =
22            git_cow::git(&repo, &["rev-parse", "--is-bare-repository"]).is_ok_and(|v| v == "true");
23        let wt_parent = wt.parent().unwrap_or(&wt);
24        let templates = template.parent().unwrap_or(&template);
25        if !bare || !template.join(".git").exists() || !git_cow::can_clone(templates, wt_parent) {
26            return Ok(());
27        }
28        git_cow::warm(&wt, &template)
29    })
30    .await;
31    if let Ok(Err(e)) = res {
32        tracing::debug!(error = %e, "template warm-up from merged task failed");
33    }
34}
35
36// Create `wt_dir` as a worktree of `branch` by cloning the project template checked out at `start`.
37// On error nothing is left behind and the caller falls back to `git worktree add`
38pub async fn create_worktree(
39    main_dir: &Path,
40    project: &str,
41    wt_dir: &Path,
42    branch: &str,
43    start: &str,
44) -> anyhow::Result<()> {
45    if env::var("ORCH_COW_WORKTREES").is_ok_and(|v| v == "0") {
46        anyhow::bail!("disabled by ORCH_COW_WORKTREES=0");
47    }
48    let template = template_dir(project)?;
49    let (repo, wt, branch, start) = (
50        main_dir.to_path_buf(),
51        wt_dir.to_path_buf(),
52        branch.to_string(),
53        start.to_string(),
54    );
55    task::spawn_blocking(move || git_cow::add(&repo, &template, &start, &wt, None, Some(&branch)))
56        .await??;
57    Ok(())
58}
59
60#[cfg(test)]
61mod tests {
62    use std::fs;
63    use std::process::Command;
64
65    use super::*;
66
67    fn sh(dir: &Path, args: &[&str]) {
68        let mut cmd = Command::new("git");
69        cmd.current_dir(dir);
70        // Global commit.gpgsign calls the operator's signer (1Password)
71        if args.first() == Some(&"commit") {
72            cmd.args(["-c", "commit.gpgsign=false"]);
73        }
74        let st = cmd.args(args).status().unwrap();
75        assert!(st.success(), "git {args:?}");
76    }
77
78    // CI jobs on a clone-capable volume set this so a failed probe fails the test
79    fn expect_clone() -> bool {
80        env::var("ORCH_COW_EXPECT_CLONE").is_ok_and(|v| v == "1")
81    }
82
83    fn repo_with_origin() -> (tempfile::TempDir, tempfile::TempDir, tempfile::TempDir) {
84        let remote = tempfile::tempdir().unwrap();
85        sh(remote.path(), &["init", "--bare", "-b", "main"]);
86        let project = tempfile::tempdir().unwrap();
87        sh(
88            project.path(),
89            &["clone", remote.path().to_str().unwrap(), "."],
90        );
91        sh(project.path(), &["config", "user.email", "t@t.com"]);
92        sh(project.path(), &["config", "user.name", "T"]);
93        fs::write(project.path().join("a.txt"), "a\n").unwrap();
94        fs::write(project.path().join("d.txt"), "d\n").unwrap();
95        sh(project.path(), &["add", "."]);
96        sh(project.path(), &["commit", "-m", "init"]);
97        sh(project.path(), &["push", "origin", "HEAD:main"]);
98        sh(project.path(), &["fetch", "origin"]);
99        let home = tempfile::tempdir().unwrap();
100        (remote, project, home)
101    }
102
103    #[tokio::test]
104    #[serial_test::serial(orch_home)]
105    async fn clone_gives_clean_worktree_or_falls_back() {
106        let (_remote, project, home) = repo_with_origin();
107        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
108        unsafe { env::set_var("ORCH_HOME", home.path()) };
109        let templates = home.path().join("state/templates");
110        fs::create_dir_all(&templates).unwrap();
111        let wt_dir = home.path().join("worktrees/p/task-1");
112        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
113        sh(project.path(), &["branch", "task-1", "origin/main"]);
114
115        // Volumes without clone support (ext4, HFS+) take the else branch
116        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
117        if expect_clone() {
118            assert!(
119                supported,
120                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
121            );
122        }
123        let res = create_worktree(project.path(), "p", &wt_dir, "task-1", "main").await;
124        if supported {
125            res.expect("clone path should succeed");
126            assert_eq!(fs::read_to_string(wt_dir.join("a.txt")).unwrap(), "a\n");
127            let status = Command::new("git")
128                .args(["status", "--porcelain"])
129                .current_dir(&wt_dir)
130                .output()
131                .unwrap();
132            assert!(status.stdout.is_empty(), "clone must have a clean index");
133            assert!(super::super::worktree::validate_worktree_gitdir(&wt_dir).await);
134        } else {
135            assert!(res.is_err());
136            assert!(!wt_dir.exists(), "failed clone must leave no directory");
137        }
138        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
139        unsafe { env::remove_var("ORCH_HOME") };
140    }
141
142    #[tokio::test]
143    #[serial_test::serial(orch_home)]
144    async fn branch_differing_from_template_gets_its_own_files() {
145        let (_remote, project, home) = repo_with_origin();
146        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
147        unsafe { env::set_var("ORCH_HOME", home.path()) };
148        let templates = home.path().join("state/templates");
149        fs::create_dir_all(&templates).unwrap();
150        let wt_dir = home.path().join("worktrees/p/task-3");
151        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
152
153        // Task branch: a.txt changed, b.txt added, d.txt deleted
154        sh(
155            project.path(),
156            &["checkout", "-q", "-b", "task-3", "origin/main"],
157        );
158        fs::write(project.path().join("a.txt"), "changed\n").unwrap();
159        fs::write(project.path().join("b.txt"), "b\n").unwrap();
160        fs::remove_file(project.path().join("d.txt")).unwrap();
161        sh(project.path(), &["add", "-A"]);
162        sh(project.path(), &["commit", "-m", "task"]);
163        sh(project.path(), &["checkout", "-q", "--detach"]);
164
165        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
166        if expect_clone() {
167            assert!(
168                supported,
169                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
170            );
171        }
172        if supported {
173            create_worktree(project.path(), "p", &wt_dir, "task-3", "main")
174                .await
175                .expect("clone path should succeed");
176            assert_eq!(
177                fs::read_to_string(wt_dir.join("a.txt")).unwrap(),
178                "changed\n"
179            );
180            assert_eq!(fs::read_to_string(wt_dir.join("b.txt")).unwrap(), "b\n");
181            assert!(!wt_dir.join("d.txt").exists());
182            let status = Command::new("git")
183                .args(["status", "--porcelain"])
184                .current_dir(&wt_dir)
185                .output()
186                .unwrap();
187            assert!(status.stdout.is_empty(), "clone must have a clean index");
188        }
189        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
190        unsafe { env::remove_var("ORCH_HOME") };
191    }
192
193    #[tokio::test]
194    #[serial_test::serial(orch_home)]
195    async fn checkout_ignored_dirs_reach_template_and_clone() {
196        let (_remote, project, home) = repo_with_origin();
197        fs::write(
198            project.path().join(".gitignore"),
199            "out/\n.env\n.local/\nnode/\n",
200        )
201        .unwrap();
202        sh(project.path(), &["add", "."]);
203        sh(project.path(), &["commit", "-m", "ignore"]);
204        sh(project.path(), &["push", "origin", "HEAD:main"]);
205        sh(project.path(), &["fetch", "origin"]);
206        fs::create_dir_all(project.path().join("out/sub")).unwrap();
207        fs::write(project.path().join("out/sub/dep.bin"), "dep\n").unwrap();
208        fs::create_dir_all(project.path().join(".local")).unwrap();
209        fs::write(project.path().join(".local/settings"), "x\n").unwrap();
210        fs::create_dir_all(project.path().join("pkg/a/node")).unwrap();
211        fs::write(project.path().join("pkg/a/node/dep.bin"), "nested\n").unwrap();
212        fs::create_dir_all(project.path().join("pkg/a/.hidden/node")).unwrap();
213        fs::write(project.path().join("pkg/a/.hidden/node/x"), "x\n").unwrap();
214        fs::write(project.path().join("pkg/a/keep.txt"), "k\n").unwrap();
215        fs::write(project.path().join(".env"), "secret\n").unwrap();
216
217        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
218        unsafe { env::set_var("ORCH_HOME", home.path()) };
219        let templates = home.path().join("state/templates");
220        fs::create_dir_all(&templates).unwrap();
221        let wt_dir = home.path().join("worktrees/p/task-4");
222        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
223        sh(project.path(), &["branch", "task-4", "origin/main"]);
224
225        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
226        if expect_clone() {
227            assert!(
228                supported,
229                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
230            );
231        }
232        if supported {
233            create_worktree(project.path(), "p", &wt_dir, "task-4", "main")
234                .await
235                .expect("clone path should succeed");
236            let tpl = templates.join("p");
237            for root in [&tpl, &wt_dir] {
238                assert_eq!(
239                    fs::read_to_string(root.join("out/sub/dep.bin")).unwrap(),
240                    "dep\n"
241                );
242                assert!(!root.join(".env").exists(), "loose ignored file was copied");
243                assert!(!root.join(".local").exists(), "hidden dir was copied");
244                assert!(
245                    !root.join("pkg/a/.hidden").exists(),
246                    "nested hidden dir was copied"
247                );
248                assert_eq!(
249                    fs::read_to_string(root.join("pkg/a/node/dep.bin")).unwrap(),
250                    "nested\n"
251                );
252            }
253            // The worktree keeps its own gitdir
254            assert!(wt_dir.join(".git").is_file());
255            assert_ne!(
256                fs::read_to_string(wt_dir.join(".git")).unwrap(),
257                fs::read_to_string(tpl.join(".git")).unwrap()
258            );
259            // git-cow warms the template from the checkout at most once an hour, so a second task
260            // right after the first keeps the build output the template already has
261            fs::remove_file(project.path().join("out/sub/dep.bin")).unwrap();
262            fs::write(project.path().join("out/new.bin"), "new\n").unwrap();
263            let wt2 = home.path().join("worktrees/p/task-5");
264            sh(project.path(), &["branch", "task-5", "origin/main"]);
265            create_worktree(project.path(), "p", &wt2, "task-5", "main")
266                .await
267                .unwrap();
268            assert!(wt2.join("out/sub/dep.bin").exists());
269            assert!(!wt2.join("out/new.bin").exists());
270        }
271        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
272        unsafe { env::remove_var("ORCH_HOME") };
273    }
274
275    #[tokio::test]
276    #[serial_test::serial(orch_home)]
277    async fn merged_task_ignored_dirs_reach_template_of_bare_project() {
278        let (remote, project, home) = repo_with_origin();
279        fs::write(project.path().join(".gitignore"), "out/\n").unwrap();
280        sh(project.path(), &["add", "."]);
281        sh(project.path(), &["commit", "-m", "ignore"]);
282        sh(project.path(), &["push", "origin", "HEAD:main"]);
283        let bare = home.path().join("bare.git");
284        sh(
285            home.path(),
286            &[
287                "clone",
288                "--bare",
289                remote.path().to_str().unwrap(),
290                "bare.git",
291            ],
292        );
293        sh(&bare, &["branch", "task-6", "main"]);
294
295        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
296        unsafe { env::set_var("ORCH_HOME", home.path()) };
297        let templates = home.path().join("state/templates");
298        fs::create_dir_all(&templates).unwrap();
299        let wt_dir = home.path().join("worktrees/pb/task-6");
300        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
301
302        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
303        if expect_clone() {
304            assert!(
305                supported,
306                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
307            );
308        }
309        if supported {
310            create_worktree(&bare, "pb", &wt_dir, "task-6", "main")
311                .await
312                .expect("clone path should succeed");
313            let tpl = templates.join("pb");
314            assert!(!tpl.join("out").exists());
315
316            fs::create_dir_all(wt_dir.join("out")).unwrap();
317            fs::write(wt_dir.join("out/dep.bin"), "dep\n").unwrap();
318            fs::write(wt_dir.join("loose.log"), "x\n").unwrap();
319
320            // A project with a working checkout is not warmed from tasks
321            warm_from_merged(project.path(), "pb", &wt_dir).await;
322            assert!(!tpl.join("out").exists());
323
324            warm_from_merged(&bare, "pb", &wt_dir).await;
325            assert_eq!(
326                fs::read_to_string(tpl.join("out/dep.bin")).unwrap(),
327                "dep\n"
328            );
329            assert!(!tpl.join("loose.log").exists());
330            assert!(tpl.join(".git").is_file());
331        }
332        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
333        unsafe { env::remove_var("ORCH_HOME") };
334    }
335
336    #[tokio::test]
337    #[serial_test::serial(orch_home)]
338    async fn env_switch_disables_clone_path() {
339        let (_remote, project, home) = repo_with_origin();
340        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
341        unsafe { env::set_var("ORCH_HOME", home.path()) };
342        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
343        unsafe { env::set_var("ORCH_COW_WORKTREES", "0") };
344        let wt_dir = home.path().join("worktrees/p/task-2");
345        let res = create_worktree(project.path(), "p", &wt_dir, "task-2", "main").await;
346        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
347        unsafe { env::remove_var("ORCH_COW_WORKTREES") };
348        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
349        unsafe { env::remove_var("ORCH_HOME") };
350        assert!(res.is_err());
351        assert!(!wt_dir.exists());
352    }
353}