Skip to main content

git_cow/
lib.rs

1//! Git worktrees cloned from a per-repository template checkout, sharing disk blocks until written.
2//! macOS clones whole directories with clonefile(2), Linux uses `cp --reflink=always` (FICLONE)
3
4use std::collections::HashMap;
5#[cfg(target_os = "macos")]
6use std::ffi::{CString, c_char, c_int};
7use std::fs::{self, File};
8use std::io;
9#[cfg(target_os = "macos")]
10use std::os::unix::ffi::OsStrExt;
11use std::path::{Path, PathBuf};
12use std::process::Command;
13use std::sync::{LazyLock, Mutex, PoisonError};
14
15pub mod cleanup;
16
17/// A path from git config `key` in `repo`, with `~/` and `{repo}` expanded
18pub fn config_path(repo: &Path, key: &str) -> Option<PathBuf> {
19    let v = git(repo, &["config", "--get", key]).ok()?;
20    let v = match repo_name(repo) {
21        Ok(name) => v.replace("{repo}", &name),
22        Err(_) => v,
23    };
24    let home = std::env::var("HOME").unwrap_or_default();
25    Some(match v.strip_prefix("~/") {
26        Some(rest) => Path::new(&home).join(rest),
27        None => PathBuf::from(v),
28    })
29}
30
31/**
32 * The repository's name: the folder of its main checkout, or a bare repository's name without
33 * `.git`
34 *
35 * # Errors
36 *
37 * When `dir` is not in a repository
38 **/
39pub fn repo_name(dir: &Path) -> io::Result<String> {
40    let common = git(
41        dir,
42        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
43    )?;
44    let common = Path::new(&common);
45    let named = if common.file_name().is_some_and(|n| n == ".git") {
46        common.parent().unwrap_or(common)
47    } else {
48        common
49    };
50    let name = named.file_name().unwrap_or_default().to_string_lossy();
51    Ok(name.strip_suffix(".git").unwrap_or(&name).to_string())
52}
53
54/// Hidden directories that hold only build caches, so they are shared like any other ignored
55/// directory. Every other path with a hidden component is tool or agent config and stays out
56pub const DEFAULT_SHARE: &[&str] = &[
57    ".uv-cache",
58    ".next",
59    ".turbo",
60    ".nuxt",
61    ".svelte-kit",
62    ".parcel-cache",
63    ".gradle",
64    ".mypy_cache",
65    ".ruff_cache",
66    ".pytest_cache",
67];
68
69// Clone support per (source dir, destination dir), probed once per process
70static PROBES: LazyLock<Mutex<HashMap<(PathBuf, PathBuf), bool>>> =
71    LazyLock::new(|| Mutex::new(HashMap::new()));
72
73fn err(msg: String) -> io::Error {
74    io::Error::other(msg)
75}
76
77/// What to share and how often to refresh the template from the checkout
78#[derive(Clone, Debug)]
79pub struct Options {
80    /// Hidden directories shared like any other ignored directory
81    pub share: Vec<String>,
82    /// [`add_with`] warms the template from the checkout at most this often, zero means every time
83    /// and `Duration::MAX` never
84    pub warm_interval: std::time::Duration,
85    /// How many times to pass `--force` to `git worktree add`, which counts it like `-f -f`. Any
86    /// count also lets [`add_with`] replace [`Foreign::Files`], and never another kind
87    pub force: u8,
88}
89
90impl Default for Options {
91    fn default() -> Self {
92        Options {
93            share: DEFAULT_SHARE.iter().map(ToString::to_string).collect(),
94            warm_interval: std::time::Duration::from_secs(3600),
95            force: 0,
96        }
97    }
98}
99
100impl Options {
101    /// The defaults plus every `cow.share` entry and `cow.warmInterval` from `repo`'s git config
102    pub fn from_repo(repo: &Path) -> Options {
103        let mut opts = Options::default();
104        let extra = git(repo, &["config", "--get-all", "cow.share"]).unwrap_or_default();
105        for d in extra.lines().map(str::trim).filter(|d| !d.is_empty()) {
106            if !opts.share.iter().any(|l| l == d) {
107                opts.share.push(d.to_string());
108            }
109        }
110        if let Some(i) = git(repo, &["config", "--get", "cow.warmInterval"])
111            .ok()
112            .and_then(|v| parse_interval(&v))
113        {
114            opts.warm_interval = i;
115        }
116        opts
117    }
118}
119
120// "0", "90" (seconds), "30m", "1h", "never"
121fn parse_interval(v: &str) -> Option<std::time::Duration> {
122    let v = v.trim();
123    if v == "never" {
124        return Some(std::time::Duration::MAX);
125    }
126    let (n, unit) = match v.strip_suffix('h') {
127        Some(n) => (n, 3600),
128        None => match v.strip_suffix('m') {
129            Some(n) => (n, 60),
130            None => (v.strip_suffix('s').unwrap_or(v), 1),
131        },
132    };
133    n.trim()
134        .parse::<u64>()
135        .ok()
136        .map(|n| std::time::Duration::from_secs(n * unit))
137}
138
139// Clone `src`, a file or a whole directory, to `dst_dir/<its name>` in one call
140#[cfg(target_os = "macos")]
141fn clone_into(src: &Path, dst_dir: &Path) -> io::Result<()> {
142    unsafe extern "C" {
143        fn clonefile(src: *const c_char, dst: *const c_char, flags: u32) -> c_int;
144    }
145    const CLONE_NOFOLLOW: u32 = 1;
146    let name = src
147        .file_name()
148        .ok_or_else(|| err(format!("{} has no name", src.display())))?;
149    let s = CString::new(src.as_os_str().as_bytes()).map_err(io::Error::other)?;
150    let d = CString::new(dst_dir.join(name).as_os_str().as_bytes()).map_err(io::Error::other)?;
151    // SAFETY: both pointers come from CStrings that outlive the call, and clonefile only reads them
152    if unsafe { clonefile(s.as_ptr(), d.as_ptr(), CLONE_NOFOLLOW) } != 0 {
153        let e = io::Error::last_os_error();
154        return Err(err(format!("clonefile {}: {e}", src.display())));
155    }
156    Ok(())
157}
158
159#[cfg(not(target_os = "macos"))]
160fn clone_into(src: &Path, dst_dir: &Path) -> io::Result<()> {
161    // fails instead of copying when the volume cannot clone
162    let out = Command::new("cp")
163        .args(["-a", "--reflink=always"])
164        .arg(src)
165        .arg(dst_dir)
166        .output()?;
167    if !out.status.success() {
168        return Err(err(format!(
169            "cp {}: {}",
170            src.display(),
171            String::from_utf8_lossy(&out.stderr).trim()
172        )));
173    }
174    Ok(())
175}
176
177/// Variables that point git at another repository or index than `-C` names, set by hooks or
178/// `git --git-dir`. git-cow's own calls would read or rewrite the user's repository through them
179pub const REPO_ENV: &[&str] = &[
180    "GIT_DIR",
181    "GIT_WORK_TREE",
182    "GIT_INDEX_FILE",
183    "GIT_COMMON_DIR",
184    "GIT_OBJECT_DIRECTORY",
185    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
186    "GIT_PREFIX",
187];
188
189/**
190 * Runs git in `dir`, without [`REPO_ENV`], and returns its trimmed stdout
191 *
192 * # Errors
193 *
194 * When git cannot start, or exits with an error that holds its stderr
195 **/
196pub fn git(dir: &Path, args: &[&str]) -> io::Result<String> {
197    let mut cmd = Command::new("git");
198    for var in REPO_ENV {
199        cmd.env_remove(var);
200    }
201    let out = cmd.arg("-C").arg(dir).args(args).output()?;
202    if !out.status.success() {
203        return Err(err(format!(
204            "git {args:?}: {}",
205            String::from_utf8_lossy(&out.stderr).trim()
206        )));
207    }
208    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
209}
210
211/// Whether a file in `src_dir` clones into `dst_dir`: both on one volume that supports it.
212/// Probed with one small file, since filesystem names miss mount options like XFS without reflink
213pub fn can_clone(src_dir: &Path, dst_dir: &Path) -> bool {
214    probe(src_dir, dst_dir).unwrap_or(false)
215}
216
217// `can_clone`, with an error when the probe file cannot be written, such as no permission or a
218// full disk, since the user can fix that and the volume may clone fine
219fn probe(src_dir: &Path, dst_dir: &Path) -> io::Result<bool> {
220    let key = (src_dir.to_path_buf(), dst_dir.to_path_buf());
221    // Held through the probe, since threads probing at once would share its file names
222    // a panic elsewhere while holding it leaves only cached probe results, still valid
223    let mut probes = PROBES.lock().unwrap_or_else(PoisonError::into_inner);
224    if let Some(known) = probes.get(&key) {
225        return Ok(*known);
226    }
227    let id = std::process::id();
228    let src = src_dir.join(format!(".cow-probe-{id}"));
229    let into = dst_dir.join(format!(".cow-probe-dir-{id}"));
230    let res = fs::write(&src, b"x")
231        .and_then(|()| fs::create_dir_all(&into))
232        .map(|()| clone_into(&src, &into).is_ok());
233    let _ = fs::remove_file(&src);
234    let _ = fs::remove_dir_all(&into);
235    if let Ok(ok) = res {
236        probes.insert(key, ok);
237    }
238    res.map_err(|e| {
239        err(format!(
240            "cannot write in {} or {}: {e}",
241            src_dir.display(),
242            dst_dir.display()
243        ))
244    })
245}
246
247// A file next to the template, `.<name>.<ext>`
248fn beside(template: &Path, ext: &str) -> PathBuf {
249    let name = template.file_name().unwrap_or_default().to_string_lossy();
250    template.with_file_name(format!(".{name}.{ext}"))
251}
252
253// Held while a template changes, so a clone never sees it half updated, across processes too
254fn lock_template(template: &Path) -> io::Result<File> {
255    let file = File::create(beside(template, "lock"))?;
256    file.lock()?;
257    Ok(file)
258}
259
260fn real(dir: &Path, args: &[&str]) -> Option<PathBuf> {
261    git(dir, args).ok().and_then(|p| fs::canonicalize(p).ok())
262}
263
264fn remove_any(path: &Path) {
265    match fs::symlink_metadata(path) {
266        Ok(m) if m.is_dir() => {
267            let _ = fs::remove_dir_all(path);
268        }
269        Ok(_) => {
270            let _ = fs::remove_file(path);
271        }
272        Err(_) => {}
273    }
274}
275
276// Move `template` aside, then delete it, so a delete cut short never leaves files at its path
277fn discard(template: &Path) {
278    let aside = beside(template, "trash");
279    remove_any(&aside);
280    if fs::rename(template, &aside).is_ok() {
281        remove_any(&aside);
282    } else {
283        remove_any(template);
284    }
285}
286
287// Every git-cow version takes this lock before it makes a template, so a path with the lock
288// beside it holds what is left of git-cow's own template
289fn made_by_git_cow(template: &Path) -> bool {
290    beside(template, "lock").exists()
291}
292
293/**
294 * A template path that is not a git-cow extra checkout, inside the `io::Error` that [`add_with`],
295 * [`warm_with`] and [`remove_template`] return. They leave it alone, and only [`Options::force`]
296 * in [`add_with`] replaces [`Foreign::Files`]. The message names the path, the advice is the caller's
297 **/
298#[derive(Debug)]
299#[non_exhaustive]
300pub enum Foreign {
301    /// A file, or a directory with files outside git
302    Files(PathBuf),
303    /// A main checkout, which git-cow would reset or delete
304    Checkout(PathBuf),
305    /// A worktree on this branch, while extra checkouts are always detached
306    Branch(PathBuf, String),
307    /// A git repository itself, bare or a `.git` directory
308    Repository(PathBuf),
309    /// A directory with files tracked by the checkout at the second path
310    Inside(PathBuf, PathBuf),
311    /// A worktree git cannot read, for this reason, that git-cow did not make
312    Unreadable(PathBuf, String),
313    /// A detached worktree with no git-cow lock beside it, or one in a rebase, merge or bisect
314    Detached(PathBuf),
315    /// A directory holding the checkout or repository at the second path
316    Nested(PathBuf, PathBuf),
317    /// The home folder, or a folder above it
318    Home(PathBuf),
319}
320
321impl std::fmt::Display for Foreign {
322    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
323        let elsewhere = "so git-cow never uses it as its extra checkout";
324        match self {
325            Foreign::Files(p) => write!(
326                f,
327                "'{}' holds files and is not a git-cow extra checkout, so it is left alone",
328                p.display()
329            ),
330            Foreign::Checkout(p) => write!(f, "'{}' is a main checkout, {elsewhere}", p.display()),
331            Foreign::Branch(p, b) => write!(
332                f,
333                "'{}' is a worktree on branch {b}, {elsewhere}",
334                p.display()
335            ),
336            Foreign::Repository(p) => {
337                write!(f, "'{}' is a git repository, {elsewhere}", p.display())
338            }
339            Foreign::Inside(p, top) => write!(
340                f,
341                "'{}' holds files tracked by the checkout at '{}', {elsewhere}",
342                p.display(),
343                top.display()
344            ),
345            Foreign::Unreadable(p, why) => write!(
346                f,
347                "git cannot read the worktree at '{}' ({why}), {elsewhere}",
348                p.display()
349            ),
350            Foreign::Detached(p) => write!(
351                f,
352                "'{}' is a worktree git-cow did not make or one in the middle of a rebase, merge or bisect, {elsewhere}",
353                p.display()
354            ),
355            Foreign::Nested(p, inner) => write!(
356                f,
357                "'{}' holds the checkout or repository at '{}', {elsewhere}",
358                p.display(),
359                inner.display()
360            ),
361            Foreign::Home(p) => write!(
362                f,
363                "'{}' is or holds the home folder, {elsewhere}",
364                p.display()
365            ),
366        }
367    }
368}
369
370impl std::error::Error for Foreign {}
371
372// What git-cow never made a template of. Templates are detached linked worktrees, of this or
373// another repository with the same name
374fn foreign(template: &Path) -> Option<Foreign> {
375    let made = made_by_git_cow(template);
376    let path = template.to_path_buf();
377    if !occupied(template) {
378        return None;
379    }
380    if template.join("HEAD").is_file()
381        && template.join("objects").is_dir()
382        && template.join("refs").is_dir()
383    {
384        return Some(Foreign::Repository(path));
385    }
386    let dot = template.join(".git");
387    // a template's `.git` is always a file, and only an empty `.git` directory is no repository
388    if dot.is_dir() && occupied(&dot) {
389        return Some(Foreign::Checkout(path));
390    }
391    if dot.is_file() {
392        let gitdir = git(template, &["rev-parse", "--absolute-git-dir"]);
393        let common = real(
394            template,
395            &["rev-parse", "--path-format=absolute", "--git-common-dir"],
396        );
397        match (gitdir, common) {
398            (Ok(gitdir), Some(common))
399                if real(template, &["rev-parse", "--show-toplevel"])
400                    == fs::canonicalize(template).ok() =>
401            {
402                if fs::canonicalize(&gitdir).ok().as_ref() == Some(&common) {
403                    return Some(Foreign::Checkout(path));
404                }
405                if let Ok(b) = git(template, &["symbolic-ref", "-q", "--short", "HEAD"]) {
406                    return Some(Foreign::Branch(path, b));
407                }
408                // a detached HEAD is git-cow's only with its lock, and never while a user is mid-rebase
409                let busy = [
410                    "rebase-merge",
411                    "rebase-apply",
412                    "MERGE_HEAD",
413                    "BISECT_LOG",
414                    "CHERRY_PICK_HEAD",
415                    "REVERT_HEAD",
416                    "sequencer",
417                ]
418                .iter()
419                .any(|f| Path::new(&gitdir).join(f).exists());
420                return (!made || busy).then_some(Foreign::Detached(path));
421            }
422            // what is left of git-cow's own template is rebuilt, as before
423            (Err(_), _) if made => return None,
424            (Err(e), _) => return Some(Foreign::Unreadable(path, e.to_string())),
425            // a `.git` git reads as some other checkout's, so it is files inside that one
426            _ => {}
427        }
428    }
429    // before the scan, which would walk all of home
430    let home = std::env::var_os("HOME").and_then(|h| fs::canonicalize(h).ok());
431    if let (Some(home), Ok(real)) = (home, fs::canonicalize(template))
432        && home.starts_with(&real)
433    {
434        return Some(Foreign::Home(path));
435    }
436    if git(template, &["ls-files"]).is_ok_and(|o| !o.is_empty()) {
437        let top = real(template, &["rev-parse", "--show-toplevel"]).unwrap_or_default();
438        return Some(Foreign::Inside(path, top));
439    }
440    if let Some(inner) = nested_repository(template) {
441        return Some(Foreign::Nested(path, inner));
442    }
443    // the lock outlives the template, so without a `.git` it proves nothing and --force decides
444    Some(Foreign::Files(path))
445}
446
447// The first checkout or repository below `dir`, without following symlinks. An empty `.git`
448// directory holds nothing, so it does not count
449fn nested_repository(dir: &Path) -> Option<PathBuf> {
450    let mut stack = vec![dir.to_path_buf()];
451    while let Some(d) = stack.pop() {
452        let Ok(entries) = fs::read_dir(&d) else {
453            continue;
454        };
455        for entry in entries.flatten() {
456            let path = entry.path();
457            let Ok(kind) = entry.file_type() else {
458                continue;
459            };
460            if entry.file_name() == ".git" && (kind.is_file() || occupied(&path)) {
461                return Some(d);
462            }
463            if kind.is_dir() {
464                if path.join("HEAD").is_file() && path.join("objects").is_dir() {
465                    return Some(path);
466                }
467                stack.push(path);
468            }
469        }
470    }
471    None
472}
473
474// Create the template checkout, or move it to `start`
475fn refresh_template(repo: &Path, template: &Path, start: &str) -> io::Result<()> {
476    remove_any(&beside(template, "trash"));
477    if template.join(".git").exists()
478        && git(template, &["checkout", "--detach", "--force", start]).is_ok()
479    {
480        return Ok(());
481    }
482    discard(template);
483    if clone_checkout(repo, template, start).is_ok() {
484        return Ok(());
485    }
486    discard(template);
487    git(
488        repo,
489        &[
490            "worktree",
491            "add",
492            "-f",
493            "--detach",
494            &template.to_string_lossy(),
495            start,
496        ],
497    )?;
498    Ok(())
499}
500
501// Make the extra checkout by cloning the user's checkout, so only files that differ from `start`
502// take disk. Edits, untracked and ignored files are cleaned out, the warm-up adds build output back
503fn clone_checkout(repo: &Path, template: &Path, start: &str) -> io::Result<()> {
504    let top = PathBuf::from(git(repo, &["rev-parse", "--show-toplevel"])?);
505    let parent = template
506        .parent()
507        .ok_or_else(|| err("template has no parent".into()))?;
508    if !can_clone(&top, parent) {
509        return Err(err("checkout and template cannot share blocks".into()));
510    }
511    git(
512        repo,
513        &[
514            "worktree",
515            "add",
516            "-f",
517            "--no-checkout",
518            "--detach",
519            &template.to_string_lossy(),
520            start,
521        ],
522    )?;
523    for name in git(&top, &["ls-tree", "--name-only", "HEAD"])?.lines() {
524        let src = top.join(name);
525        if src.symlink_metadata().is_ok() {
526            clone_into(&src, template)?;
527        }
528    }
529    let src_git = git(&top, &["rev-parse", "--absolute-git-dir"])?;
530    let tpl_git = git(template, &["rev-parse", "--absolute-git-dir"])?;
531    fs::copy(
532        Path::new(&src_git).join("index"),
533        Path::new(&tpl_git).join("index"),
534    )?;
535    let _ = git(template, &["update-index", "-q", "--refresh"]);
536    git(template, &["reset", "--hard", "-q"])?;
537    git(template, &["clean", "-fdxq"])?;
538    Ok(())
539}
540
541// Gitignored directories of a checkout at any depth, which hold whatever its tooling produced.
542// A hidden component must be in `share`, anything else hidden is tool or agent config
543fn ignored_dirs(src: &Path, share: &[String]) -> io::Result<Vec<String>> {
544    let out = git(
545        src,
546        &[
547            "ls-files",
548            "--others",
549            "--ignored",
550            "--exclude-standard",
551            "--directory",
552        ],
553    )?;
554    Ok(out
555        .lines()
556        .filter_map(|l| l.strip_suffix('/'))
557        .filter(|n| {
558            !n.is_empty()
559                && n.split('/')
560                    .all(|c| !c.starts_with('.') || share.iter().any(|s| s == c))
561        })
562        .map(String::from)
563        .collect())
564}
565
566// Whether `path`, or the nearest part of it that exists, resolves inside `root`
567fn within(root: &Path, path: &Path) -> bool {
568    path.ancestors()
569        .skip(1)
570        .find_map(|a| fs::canonicalize(a).ok())
571        .is_some_and(|a| a.starts_with(root))
572}
573
574// `std::path::absolute` with `..` resolved by name, so `repo/..` is never a path git-cow deletes
575fn absolute(path: &Path) -> io::Result<PathBuf> {
576    let mut out = PathBuf::new();
577    for c in std::path::absolute(path)?.components() {
578        match c {
579            std::path::Component::ParentDir => {
580                out.pop();
581            }
582            std::path::Component::CurDir => {}
583            c => out.push(c),
584        }
585    }
586    Ok(out)
587}
588
589// Swap a clone of each ignored directory of `src` into the template. Loose ignored files stay
590// out, so local secrets such as .env never reach a worktree
591fn warm_template(src: &Path, template: &Path, share: &[String]) -> io::Result<()> {
592    let staging = beside(template, "warm");
593    let root = fs::canonicalize(template)?;
594    for dir in ignored_dirs(src, share)? {
595        // A directory the template commit tracks is not build output
596        if !git(template, &["ls-files", "--", &dir])
597            .unwrap_or_default()
598            .is_empty()
599        {
600            continue;
601        }
602        let _ = fs::remove_dir_all(&staging);
603        fs::create_dir_all(&staging)?;
604        // One directory that cannot be cloned only costs that directory's sharing
605        let _ = (|| {
606            clone_into(&src.join(&dir), &staging)?;
607            let dst = template.join(&dir);
608            // a tracked symlink on the way would lead the swap out of the template
609            if !within(&root, &dst) {
610                return Ok(());
611            }
612            let _ = fs::remove_dir_all(&dst);
613            if let Some(parent) = dst.parent() {
614                fs::create_dir_all(parent)?;
615            }
616            let base = Path::new(&dir).file_name().unwrap_or_default();
617            fs::rename(staging.join(base), dst)
618        })();
619        let _ = fs::remove_dir_all(&staging);
620    }
621    Ok(())
622}
623
624/**
625 * Refresh an existing `template` with the gitignored directories of `src`, a checkout or a
626 * worktree whose work merged. Shares the hidden directories in [`DEFAULT_SHARE`]
627 *
628 * # Errors
629 *
630 * As [`warm_with`]
631 **/
632pub fn warm(src: &Path, template: &Path) -> io::Result<()> {
633    warm_with(src, template, &Options::default())
634}
635
636/**
637 * [`warm`] with your own [`Options`]. It always warms, the interval only applies to [`add_with`]
638 *
639 * # Errors
640 *
641 * When `template` is no extra checkout or is [`Foreign`], or its lock or a git call fails
642 **/
643pub fn warm_with(src: &Path, template: &Path, opts: &Options) -> io::Result<()> {
644    let template = &absolute(template)?;
645    if !template.join(".git").exists() {
646        return Err(err(format!("no template at {}", template.display())));
647    }
648    if let Some(f) = foreign(template) {
649        return Err(io::Error::other(f));
650    }
651    let _lock = lock_template(template)?;
652    warm_template(src, template, &opts.share)?;
653    stamp(template)
654}
655
656/**
657 * Remove `template`, its registration in `repo`, and the lock, stamp and staging files next to it.
658 * A path that is not an extra checkout git-cow made fails with [`Foreign`] and stays. Call it
659 * only when no [`add`] or [`warm`] on this template can run: one waiting for the lock would get a
660 * deleted file, and the next caller a new one
661 *
662 * # Errors
663 *
664 * When `template` is [`Foreign`], or `git worktree remove` or deleting a file fails
665 **/
666pub fn remove_template(repo: &Path, template: &Path) -> io::Result<()> {
667    let template = &absolute(template)?;
668    if template.parent().is_none_or(|p| !p.exists()) {
669        return Ok(());
670    }
671    if let Some(f) = foreign(template) {
672        return Err(io::Error::other(f));
673    }
674    let _lock = lock_template(template)?;
675    let registered = template.join(".git").exists();
676    let aside = beside(template, "trash");
677    remove_any(&aside);
678    // aside before git deletes it in place, so a delete cut short never leaves files at the path
679    let moved = fs::rename(template, &aside).is_ok();
680    if registered
681        && let Err(e) = git(
682            repo,
683            &["worktree", "remove", "--force", &template.to_string_lossy()],
684        )
685    {
686        if moved {
687            let _ = fs::rename(&aside, template);
688        }
689        return Err(e);
690    }
691    remove_any(&aside);
692    remove_any(template);
693    let _ = fs::remove_dir_all(beside(template, "warm"));
694    for ext in ["warmed", "lock"] {
695        match fs::remove_file(beside(template, ext)) {
696            Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
697            _ => {}
698        }
699    }
700    Ok(())
701}
702
703// Marks when the template was last warmed, so add_with can skip a warm-up it did recently
704fn stamp_path(template: &Path) -> PathBuf {
705    beside(template, "warmed")
706}
707
708fn stamp(template: &Path) -> io::Result<()> {
709    fs::write(stamp_path(template), b"")
710}
711
712fn warmed_within(template: &Path, interval: std::time::Duration) -> bool {
713    fs::metadata(stamp_path(template))
714        .and_then(|m| m.modified())
715        .ok()
716        .and_then(|t| t.elapsed().ok())
717        .is_some_and(|age| age < interval)
718}
719
720/// The error inside the [`io::ErrorKind::AlreadyExists`] that [`add_with`] returns for a `wt` that
721/// exists and is not empty. Test for it with [`is_occupied`]
722#[derive(Debug)]
723pub struct Occupied(pub PathBuf);
724
725impl std::fmt::Display for Occupied {
726    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
727        write!(f, "'{}' already exists", self.0.display())
728    }
729}
730
731impl std::error::Error for Occupied {}
732
733/// Whether `e` is [`add_with`] refusing a `wt` that exists and is not empty, where a plain
734/// `git worktree add` would fail too
735pub fn is_occupied(e: &io::Error) -> bool {
736    matches!(e.get_ref(), Some(inner) if inner.is::<Occupied>())
737}
738
739/// The error inside the `io::Error` when git-cow cannot clone here at all: the volume has no
740/// clone support or the repository has submodules. Test for it with [`is_unsupported`]
741#[derive(Debug)]
742pub struct Unsupported(pub &'static str);
743
744impl std::fmt::Display for Unsupported {
745    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
746        f.write_str(self.0)
747    }
748}
749
750impl std::error::Error for Unsupported {}
751
752/// Whether `e` is [`Unsupported`], where a plain `git worktree add` is expected. Any other clone
753/// error also falls back in [`add_or_plain`], and a caller may warn that cloning failed
754pub fn is_unsupported(e: &io::Error) -> bool {
755    matches!(e.get_ref(), Some(inner) if inner.is::<Unsupported>())
756}
757
758/// Whether `e` is [`Occupied`] or [`Foreign`], a path git-cow leaves alone. A plain
759/// `git worktree add` must not run instead, since the path needs the user first
760pub fn is_refused(e: &io::Error) -> bool {
761    e.get_ref()
762        .is_some_and(|inner| inner.is::<Occupied>() || inner.is::<Foreign>())
763}
764
765// The branch git worktree add creates if none has its name yet, so a failed add may delete it:
766// `-b`, or without a commit-ish one named after the path
767fn new_branch_name(
768    repo: &Path,
769    wt: &Path,
770    new_branch: Option<&str>,
771    commitish: Option<&str>,
772) -> Option<String> {
773    let b = match (new_branch, commitish) {
774        (Some(b), _) => b.to_string(),
775        (None, None) => wt.file_name()?.to_string_lossy().into_owned(),
776        _ => return None,
777    };
778    git(
779        repo,
780        &["rev-parse", "--verify", "-q", &format!("refs/heads/{b}")],
781    )
782    .is_err()
783    .then_some(b)
784}
785
786// Something git worktree add refuses: anything but a missing path or an empty directory
787fn occupied(wt: &Path) -> bool {
788    match fs::symlink_metadata(wt) {
789        Err(_) => false,
790        Ok(m) if m.is_dir() => fs::read_dir(wt).map_or(true, |mut d| d.next().is_some()),
791        Ok(_) => true,
792    }
793}
794
795// Fill `wt`, already a worktree with no files, from the template
796fn populate(template: &Path, wt: &Path) -> io::Result<()> {
797    for entry in fs::read_dir(template)? {
798        let entry = entry?;
799        if entry.file_name() == ".git" {
800            continue;
801        }
802        clone_into(&entry.path(), wt)?;
803    }
804
805    // The template index describes the cloned files. Refresh its stat data for the new inodes,
806    // then reset only the files where the worktree's commit differs from the template's
807    let tpl_git = git(template, &["rev-parse", "--absolute-git-dir"])?;
808    let wt_git = git(wt, &["rev-parse", "--absolute-git-dir"])?;
809    fs::copy(
810        Path::new(&tpl_git).join("index"),
811        Path::new(&wt_git).join("index"),
812    )?;
813    let _ = git(wt, &["update-index", "-q", "--refresh"]);
814    git(wt, &["reset", "--hard", "-q"])?;
815    Ok(())
816}
817
818/**
819 * Create `wt` by cloning `template`, refreshed to `template_start` and warmed from `repo` first.
820 * `new_branch` and `commitish` are `git worktree add`'s. Like it, refuses a `wt` that exists and
821 * is not empty, and on error removes only the worktree and branch this call created
822 *
823 * # Errors
824 *
825 * As [`add_with`]
826 **/
827pub fn add(
828    repo: &Path,
829    template: &Path,
830    template_start: &str,
831    wt: &Path,
832    new_branch: Option<&str>,
833    commitish: Option<&str>,
834) -> io::Result<()> {
835    add_with(
836        repo,
837        template,
838        template_start,
839        wt,
840        new_branch,
841        commitish,
842        &Options::default(),
843    )
844}
845
846/**
847 * [`add`] with your own [`Options`]
848 *
849 * # Errors
850 *
851 * When `wt` is [`Occupied`], the template path is [`Foreign`], cloning is [`Unsupported`], or a git or file call fails. [`is_refused`] and [`is_unsupported`] tell them apart
852 **/
853pub fn add_with(
854    repo: &Path,
855    template: &Path,
856    template_start: &str,
857    wt: &Path,
858    new_branch: Option<&str>,
859    commitish: Option<&str>,
860    opts: &Options,
861) -> io::Result<()> {
862    // git resolves a relative path against `repo` and the file calls against the current directory
863    let wt = &absolute(wt)?;
864    let template = &absolute(template)?;
865    if occupied(wt) {
866        return Err(io::Error::new(
867            io::ErrorKind::AlreadyExists,
868            Occupied(wt.clone()),
869        ));
870    }
871    let wt_parent = wt
872        .parent()
873        .ok_or_else(|| err("worktree has no parent".into()))?;
874    let tpl_parent = template
875        .parent()
876        .ok_or_else(|| err("template has no parent".into()))?;
877    fs::create_dir_all(wt_parent)?;
878    fs::create_dir_all(tpl_parent)?;
879    if !probe(tpl_parent, wt_parent)? {
880        return Err(io::Error::other(Unsupported("volume cannot clone files")));
881    }
882
883    // checked before the lock, so a refused path gets no lock file beside it
884    let replace = match foreign(template) {
885        Some(Foreign::Files(_)) if opts.force > 0 => true,
886        Some(f) => return Err(io::Error::other(f)),
887        None => false,
888    };
889    let _lock = lock_template(template)?;
890    if replace {
891        discard(template);
892    }
893    refresh_template(repo, template, template_start)?;
894    if template.join(".gitmodules").exists() {
895        // A cloned submodule `.git` file would point into the template's gitdir
896        return Err(io::Error::other(Unsupported(
897            "submodules are not supported",
898        )));
899    }
900    // Re-cloning big caches on every add costs seconds, and a template an hour old only means a
901    // little more rebuilding. Bare repositories have no ignored files, so nothing changes for them
902    let never = opts.warm_interval == std::time::Duration::MAX;
903    if !never && (opts.warm_interval.is_zero() || !warmed_within(template, opts.warm_interval)) {
904        let _ = warm_template(repo, template, &opts.share);
905        let _ = stamp(template);
906    }
907
908    // Only a branch this call creates may be removed on failure, never one that was there before
909    let ours = new_branch_name(repo, wt, new_branch, commitish);
910    // --no-checkout creates the gitdir entry and the `.git` file, so git state stays per worktree.
911    // Until it succeeds `wt` is not ours, so a failure here only drops the branch git made first
912    let wt_s = wt.to_string_lossy();
913    let mut args = vec!["worktree", "add", "--no-checkout"];
914    args.extend(std::iter::repeat_n("--force", opts.force.into()));
915    if let Some(b) = new_branch {
916        args.extend(["-b", b]);
917    }
918    args.push(&wt_s);
919    args.extend(commitish);
920    let was_dir = wt.is_dir();
921    if let Err(e) = git(repo, &args) {
922        if let Some(b) = &ours {
923            let _ = git(repo, &["branch", "-D", b.as_str()]);
924        }
925        return Err(e);
926    }
927    let res = populate(template, wt);
928    if res.is_err() {
929        let _ = git(
930            repo,
931            &["worktree", "remove", "--force", &wt.to_string_lossy()],
932        );
933        let _ = fs::remove_dir_all(wt);
934        if was_dir {
935            let _ = fs::create_dir(wt);
936        }
937        if let Some(b) = &ours {
938            let _ = git(repo, &["branch", "-D", b.as_str()]);
939        }
940    }
941    res
942}
943
944/// How [`add_or_plain`] made the worktree
945#[derive(Debug)]
946#[expect(
947    clippy::exhaustive_enums,
948    reason = "a clone or a plain worktree is the whole answer, and #[non_exhaustive] would break callers that match it"
949)]
950pub enum Added {
951    /// Cloned from the template
952    Cloned,
953    /// With `git worktree add`, since cloning failed for this reason, [`Unsupported`] or not
954    Plain(io::Error),
955}
956
957/**
958 * [`add_with`], or `git worktree add` with the same `wt`, `new_branch` and `commitish` when
959 * cloning fails. A path [`is_refused`] is returned with no plain add
960 *
961 * # Errors
962 *
963 * When the path [`is_refused`], or the plain `git worktree add` fails too
964 **/
965pub fn add_or_plain(
966    repo: &Path,
967    template: &Path,
968    template_start: &str,
969    wt: &Path,
970    new_branch: Option<&str>,
971    commitish: Option<&str>,
972    opts: &Options,
973) -> io::Result<Added> {
974    let wt = &absolute(wt)?;
975    let Err(why) = add_with(
976        repo,
977        template,
978        template_start,
979        wt,
980        new_branch,
981        commitish,
982        opts,
983    ) else {
984        return Ok(Added::Cloned);
985    };
986    if is_refused(&why) {
987        return Err(why);
988    }
989
990    let wt_s = wt.to_string_lossy();
991    let mut args = vec!["worktree", "add"];
992    args.extend(std::iter::repeat_n("--force", opts.force.into()));
993    if let Some(b) = new_branch {
994        args.extend(["-b", b]);
995    }
996    args.push(&wt_s);
997    args.extend(commitish);
998    let ours = new_branch_name(repo, wt, new_branch, commitish);
999    if let Err(e) = git(repo, &args) {
1000        // git creates the branch before it checks the path
1001        if let Some(b) = &ours {
1002            let _ = git(repo, &["branch", "-D", b.as_str()]);
1003        }
1004        return Err(err(format!("{e}, after cloning failed: {why}")));
1005    }
1006    Ok(Added::Plain(why))
1007}