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