1use 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
11pub 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
26static 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#[derive(Clone, Debug)]
36pub struct Options {
37 pub share: Vec<String>,
39 pub warm_interval: std::time::Duration,
42 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 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
77fn 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#[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 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
135pub 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
147pub 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
163pub fn can_clone(src_dir: &Path, dst_dir: &Path) -> bool {
166 probe(src_dir, dst_dir).unwrap_or(false)
167}
168
169fn probe(src_dir: &Path, dst_dir: &Path) -> io::Result<bool> {
172 let key = (src_dir.to_path_buf(), dst_dir.to_path_buf());
173 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
198fn 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
204fn 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
227fn 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
238fn made_by_git_cow(template: &Path) -> bool {
241 beside(template, "lock").exists()
242}
243
244#[derive(Debug)]
248#[non_exhaustive]
249pub enum Foreign {
250 Files(PathBuf),
252 Checkout(PathBuf),
254 Branch(PathBuf, String),
256 Repository(PathBuf),
258 Inside(PathBuf, PathBuf),
260 Unreadable(PathBuf, String),
262 Detached(PathBuf),
264 Nested(PathBuf, PathBuf),
266 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
321fn 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 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 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 (Err(_), _) if made => return None,
372 (Err(e), _) => return Some(Foreign::Unreadable(path, e.to_string())),
373 _ => {}
375 }
376 }
377 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 Some(Foreign::Files(path))
393}
394
395fn 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
422fn 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
449fn 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
489fn 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
514fn 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
522fn 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
537fn 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 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 let _ = (|| {
554 clone_into(&src.join(&dir), &staging)?;
555 let dst = template.join(&dir);
556 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
572pub fn warm(src: &Path, template: &Path) -> io::Result<()> {
575 warm_with(src, template, &Options::default())
576}
577
578pub 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
592pub 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 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
633fn 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#[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
663pub fn is_occupied(e: &io::Error) -> bool {
666 e.get_ref().is_some_and(|inner| inner.is::<Occupied>())
667}
668
669#[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
682pub fn is_unsupported(e: &io::Error) -> bool {
685 e.get_ref().is_some_and(|inner| inner.is::<Unsupported>())
686}
687
688pub fn is_refused(e: &io::Error) -> bool {
691 e.get_ref()
692 .is_some_and(|inner| inner.is::<Occupied>() || inner.is::<Foreign>())
693}
694
695fn 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
716fn 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
725fn 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 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
748pub 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
770pub 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 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 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 return Err(io::Error::other(Unsupported(
815 "submodules are not supported",
816 )));
817 }
818 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 let ours = new_branch_name(repo, wt, new_branch, commitish);
828 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#[derive(Debug)]
864pub enum Added {
865 Cloned,
867 Plain(io::Error),
869}
870
871pub 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 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}