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 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
30static 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#[derive(Clone, Debug)]
40pub struct Options {
41 pub share: Vec<String>,
43 pub warm_interval: std::time::Duration,
46 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 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
81fn 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#[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 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 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
138pub 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
150pub 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
170pub fn can_clone(src_dir: &Path, dst_dir: &Path) -> bool {
173 probe(src_dir, dst_dir).unwrap_or(false)
174}
175
176fn probe(src_dir: &Path, dst_dir: &Path) -> io::Result<bool> {
179 let key = (src_dir.to_path_buf(), dst_dir.to_path_buf());
180 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
206fn 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
212fn 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
235fn 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
246fn made_by_git_cow(template: &Path) -> bool {
249 beside(template, "lock").exists()
250}
251
252#[derive(Debug)]
256#[non_exhaustive]
257pub enum Foreign {
258 Files(PathBuf),
260 Checkout(PathBuf),
262 Branch(PathBuf, String),
264 Repository(PathBuf),
266 Inside(PathBuf, PathBuf),
268 Unreadable(PathBuf, String),
270 Detached(PathBuf),
272 Nested(PathBuf, PathBuf),
274 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
329fn 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 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 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 (Err(_), _) if made => return None,
381 (Err(e), _) => return Some(Foreign::Unreadable(path, e.to_string())),
382 _ => {}
384 }
385 }
386 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 Some(Foreign::Files(path))
402}
403
404fn 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
431fn 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
458fn 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
498fn 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
523fn 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
531fn 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
546fn 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 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 let _ = (|| {
563 clone_into(&src.join(&dir), &staging)?;
564 let dst = template.join(&dir);
565 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
581pub fn warm(src: &Path, template: &Path) -> io::Result<()> {
588 warm_with(src, template, &Options::default())
589}
590
591pub 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
609pub 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 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
654fn 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#[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
684pub fn is_occupied(e: &io::Error) -> bool {
687 matches!(e.get_ref(), Some(inner) if inner.is::<Occupied>())
688}
689
690#[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
703pub fn is_unsupported(e: &io::Error) -> bool {
706 matches!(e.get_ref(), Some(inner) if inner.is::<Unsupported>())
707}
708
709pub fn is_refused(e: &io::Error) -> bool {
712 e.get_ref()
713 .is_some_and(|inner| inner.is::<Occupied>() || inner.is::<Foreign>())
714}
715
716fn 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
737fn 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
746fn 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 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
769pub 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
795pub 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 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 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 return Err(io::Error::other(Unsupported(
844 "submodules are not supported",
845 )));
846 }
847 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 let ours = new_branch_name(repo, wt, new_branch, commitish);
857 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#[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,
900 Plain(io::Error),
902}
903
904pub 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 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}