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