1use 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
17pub 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
31pub 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
54pub 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
69static 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#[derive(Clone, Debug)]
79pub struct Options {
80 pub share: Vec<String>,
82 pub warm_interval: std::time::Duration,
85 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 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
120fn 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#[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 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 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
177pub 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
189pub 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
211pub fn can_clone(src_dir: &Path, dst_dir: &Path) -> bool {
214 probe(src_dir, dst_dir).unwrap_or(false)
215}
216
217fn probe(src_dir: &Path, dst_dir: &Path) -> io::Result<bool> {
220 let key = (src_dir.to_path_buf(), dst_dir.to_path_buf());
221 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
247fn 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
253fn 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
276fn 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
287fn made_by_git_cow(template: &Path) -> bool {
290 beside(template, "lock").exists()
291}
292
293#[derive(Debug)]
299#[non_exhaustive]
300pub enum Foreign {
301 Files(PathBuf),
303 Checkout(PathBuf),
305 Branch(PathBuf, String),
307 Repository(PathBuf),
309 Inside(PathBuf, PathBuf),
311 Unreadable(PathBuf, String),
313 Detached(PathBuf),
315 Nested(PathBuf, PathBuf),
317 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
372fn 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 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 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 (Err(_), _) if made => return None,
424 (Err(e), _) => return Some(Foreign::Unreadable(path, e.to_string())),
425 _ => {}
427 }
428 }
429 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 Some(Foreign::Files(path))
445}
446
447fn 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
474fn 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
501fn 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
541fn 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
566fn 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
574fn 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
589fn 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 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 let _ = (|| {
606 clone_into(&src.join(&dir), &staging)?;
607 let dst = template.join(&dir);
608 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
624pub fn warm(src: &Path, template: &Path) -> io::Result<()> {
633 warm_with(src, template, &Options::default())
634}
635
636pub 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
656pub 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 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
703fn 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#[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
733pub fn is_occupied(e: &io::Error) -> bool {
736 matches!(e.get_ref(), Some(inner) if inner.is::<Occupied>())
737}
738
739#[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
752pub fn is_unsupported(e: &io::Error) -> bool {
755 matches!(e.get_ref(), Some(inner) if inner.is::<Unsupported>())
756}
757
758pub fn is_refused(e: &io::Error) -> bool {
761 e.get_ref()
762 .is_some_and(|inner| inner.is::<Occupied>() || inner.is::<Foreign>())
763}
764
765fn 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
786fn 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
795fn 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 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
818pub 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
846pub 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 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 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 return Err(io::Error::other(Unsupported(
897 "submodules are not supported",
898 )));
899 }
900 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 let ours = new_branch_name(repo, wt, new_branch, commitish);
910 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#[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,
953 Plain(io::Error),
955}
956
957pub 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 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}