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#[cfg(windows)]
17mod refs;
18#[cfg(windows)]
19use refs::{clone_into, clone_moved};
20
21pub fn config_path(repo: &Path, key: &str) -> Option<PathBuf> {
23 let v = git(repo, &["config", "--get", key]).ok()?;
24 let v = match repo_name(repo) {
25 Ok(name) => v.replace("{repo}", &name),
26 Err(_) => v,
27 };
28 Some(match v.strip_prefix("~/") {
29 Some(rest) => std::env::home_dir().unwrap_or_default().join(rest),
30 None => PathBuf::from(v),
31 })
32}
33
34pub fn repo_name(dir: &Path) -> io::Result<String> {
43 let common = git(
44 dir,
45 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
46 )?;
47 let common = Path::new(&common);
48 let named = if common.file_name().is_some_and(|n| n == ".git") {
49 common.parent().unwrap_or(common)
50 } else {
51 common
52 };
53 let name = named.file_name().unwrap_or_default().to_string_lossy();
54 Ok(name.strip_suffix(".git").unwrap_or(&name).to_string())
55}
56
57pub const DEFAULT_SHARE: &[&str] = &[
60 ".uv-cache",
61 ".next",
62 ".turbo",
63 ".nuxt",
64 ".svelte-kit",
65 ".parcel-cache",
66 ".gradle",
67 ".mypy_cache",
68 ".ruff_cache",
69 ".pytest_cache",
70];
71
72static PROBES: LazyLock<Mutex<HashMap<(PathBuf, PathBuf), bool>>> =
74 LazyLock::new(|| Mutex::new(HashMap::new()));
75
76fn err(msg: String) -> io::Error {
77 io::Error::other(msg)
78}
79
80#[derive(Clone, Debug)]
82pub struct Options {
83 pub share: Vec<String>,
85 pub warm_interval: std::time::Duration,
88 pub force: u8,
91}
92
93impl Default for Options {
94 fn default() -> Self {
95 Options {
96 share: DEFAULT_SHARE.iter().map(ToString::to_string).collect(),
97 warm_interval: std::time::Duration::from_secs(3600),
98 force: 0,
99 }
100 }
101}
102
103impl Options {
104 pub fn from_repo(repo: &Path) -> Options {
106 let mut opts = Options::default();
107 let extra = git(repo, &["config", "--get-all", "cow.share"]).unwrap_or_default();
108 for d in extra.lines().map(str::trim).filter(|d| !d.is_empty()) {
109 if !opts.share.iter().any(|l| l == d) {
110 opts.share.push(d.to_string());
111 }
112 }
113 if let Some(i) = git(repo, &["config", "--get", "cow.warmInterval"])
114 .ok()
115 .and_then(|v| parse_interval(&v))
116 {
117 opts.warm_interval = i;
118 }
119 opts
120 }
121}
122
123fn parse_interval(v: &str) -> Option<std::time::Duration> {
125 let v = v.trim();
126 if v == "never" {
127 return Some(std::time::Duration::MAX);
128 }
129 let (n, unit) = match v.strip_suffix('h') {
130 Some(n) => (n, 3600),
131 None => match v.strip_suffix('m') {
132 Some(n) => (n, 60),
133 None => (v.strip_suffix('s').unwrap_or(v), 1),
134 },
135 };
136 n.trim()
137 .parse::<u64>()
138 .ok()
139 .map(|n| std::time::Duration::from_secs(n * unit))
140}
141
142#[cfg(target_os = "macos")]
144fn clone_into(src: &Path, dst_dir: &Path) -> io::Result<()> {
145 unsafe extern "C" {
146 fn clonefile(src: *const c_char, dst: *const c_char, flags: u32) -> c_int;
147 }
148 const CLONE_NOFOLLOW: u32 = 1;
149 let name = src
150 .file_name()
151 .ok_or_else(|| err(format!("{} has no name", src.display())))?;
152 let s = CString::new(src.as_os_str().as_bytes()).map_err(io::Error::other)?;
153 let d = CString::new(dst_dir.join(name).as_os_str().as_bytes()).map_err(io::Error::other)?;
154 if unsafe { clonefile(s.as_ptr(), d.as_ptr(), CLONE_NOFOLLOW) } != 0 {
156 let e = io::Error::last_os_error();
157 return Err(err(format!("clonefile {}: {e}", src.display())));
158 }
159 Ok(())
160}
161
162#[cfg(not(any(target_os = "macos", windows)))]
163fn clone_into(src: &Path, dst_dir: &Path) -> io::Result<()> {
164 let out = Command::new("cp")
166 .args(["-a", "--reflink=always"])
167 .arg(src)
168 .arg(dst_dir)
169 .output()?;
170 if !out.status.success() {
171 return Err(err(format!(
172 "cp {}: {}",
173 src.display(),
174 String::from_utf8_lossy(&out.stderr).trim()
175 )));
176 }
177 Ok(())
178}
179
180#[cfg(not(windows))]
185fn clone_moved(src: &Path, dst_dir: &Path, _from: &Path, _to: &Path) -> io::Result<()> {
186 clone_into(src, dst_dir)
187}
188
189pub const REPO_ENV: &[&str] = &[
192 "GIT_DIR",
193 "GIT_WORK_TREE",
194 "GIT_INDEX_FILE",
195 "GIT_COMMON_DIR",
196 "GIT_OBJECT_DIRECTORY",
197 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
198 "GIT_PREFIX",
199];
200
201pub fn git(dir: &Path, args: &[&str]) -> io::Result<String> {
209 let mut cmd = Command::new("git");
210 for var in REPO_ENV {
211 cmd.env_remove(var);
212 }
213 let out = cmd.arg("-C").arg(dir).args(args).output()?;
214 if !out.status.success() {
215 return Err(err(format!(
216 "git {args:?}: {}",
217 String::from_utf8_lossy(&out.stderr).trim()
218 )));
219 }
220 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
221}
222
223pub fn can_clone(src_dir: &Path, dst_dir: &Path) -> bool {
226 probe(src_dir, dst_dir).unwrap_or(false)
227}
228
229fn probe(src_dir: &Path, dst_dir: &Path) -> io::Result<bool> {
232 let key = (src_dir.to_path_buf(), dst_dir.to_path_buf());
233 let mut probes = PROBES.lock().unwrap_or_else(PoisonError::into_inner);
236 if let Some(known) = probes.get(&key) {
237 return Ok(*known);
238 }
239 let id = std::process::id();
240 let src = src_dir.join(format!(".cow-probe-{id}"));
241 let into = dst_dir.join(format!(".cow-probe-dir-{id}"));
242 let res = fs::write(&src, b"x")
243 .and_then(|()| fs::create_dir_all(&into))
244 .map(|()| clone_into(&src, &into).is_ok());
245 let _ = fs::remove_file(&src);
246 let _ = fs::remove_dir_all(&into);
247 if let Ok(ok) = res {
248 probes.insert(key, ok);
249 }
250 res.map_err(|e| {
251 err(format!(
252 "cannot write in {} or {}: {e}",
253 src_dir.display(),
254 dst_dir.display()
255 ))
256 })
257}
258
259fn beside(template: &Path, ext: &str) -> PathBuf {
261 let name = template.file_name().unwrap_or_default().to_string_lossy();
262 template.with_file_name(format!(".{name}.{ext}"))
263}
264
265fn lock_template(template: &Path) -> io::Result<File> {
267 let file = File::options()
268 .write(true)
269 .create(true)
270 .truncate(false)
271 .open(beside(template, "lock"))?;
272 file.lock()?;
273 Ok(file)
274}
275
276fn real(dir: &Path, args: &[&str]) -> Option<PathBuf> {
277 git(dir, args).ok().and_then(|p| fs::canonicalize(p).ok())
278}
279
280fn remove_any(path: &Path) {
281 #[cfg(windows)]
282 use std::os::windows::fs::FileTypeExt;
283
284 match fs::symlink_metadata(path) {
285 #[cfg(windows)]
287 Ok(m) if m.file_type().is_symlink_dir() => {
288 let _ = fs::remove_dir(path);
289 }
290 Ok(m) if m.is_dir() => {
291 let _ = fs::remove_dir_all(path);
292 }
293 Ok(_) => {
294 let _ = fs::remove_file(path);
295 }
296 Err(_) => {}
297 }
298}
299
300fn discard(template: &Path) {
302 let aside = beside(template, "trash");
303 remove_any(&aside);
304 if fs::rename(template, &aside).is_ok() {
305 remove_any(&aside);
306 } else {
307 remove_any(template);
308 }
309}
310
311fn made_by_git_cow(template: &Path) -> bool {
314 beside(template, "lock").exists()
315}
316
317#[derive(Debug)]
323#[non_exhaustive]
324pub enum Foreign {
325 Files(PathBuf),
327 Checkout(PathBuf),
329 Branch(PathBuf, String),
331 Repository(PathBuf),
333 Inside(PathBuf, PathBuf),
335 Unreadable(PathBuf, String),
337 Detached(PathBuf),
339 Nested(PathBuf, PathBuf),
341 Home(PathBuf),
343}
344
345impl std::fmt::Display for Foreign {
346 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
347 let elsewhere = "so git-cow never uses it as its extra checkout";
348 match self {
349 Foreign::Files(p) => write!(
350 f,
351 "'{}' holds files and is not a git-cow extra checkout, so it is left alone",
352 p.display()
353 ),
354 Foreign::Checkout(p) => write!(f, "'{}' is a main checkout, {elsewhere}", p.display()),
355 Foreign::Branch(p, b) => write!(
356 f,
357 "'{}' is a worktree on branch {b}, {elsewhere}",
358 p.display()
359 ),
360 Foreign::Repository(p) => {
361 write!(f, "'{}' is a git repository, {elsewhere}", p.display())
362 }
363 Foreign::Inside(p, top) => write!(
364 f,
365 "'{}' holds files tracked by the checkout at '{}', {elsewhere}",
366 p.display(),
367 top.display()
368 ),
369 Foreign::Unreadable(p, why) => write!(
370 f,
371 "git cannot read the worktree at '{}' ({why}), {elsewhere}",
372 p.display()
373 ),
374 Foreign::Detached(p) => write!(
375 f,
376 "'{}' is a worktree git-cow did not make or one in the middle of a rebase, merge or bisect, {elsewhere}",
377 p.display()
378 ),
379 Foreign::Nested(p, inner) => write!(
380 f,
381 "'{}' holds the checkout or repository at '{}', {elsewhere}",
382 p.display(),
383 inner.display()
384 ),
385 Foreign::Home(p) => write!(
386 f,
387 "'{}' is or holds the home folder, {elsewhere}",
388 p.display()
389 ),
390 }
391 }
392}
393
394impl std::error::Error for Foreign {}
395
396fn foreign(template: &Path) -> Option<Foreign> {
399 let made = made_by_git_cow(template);
400 let path = template.to_path_buf();
401 if !occupied(template) {
402 return None;
403 }
404 if template.join("HEAD").is_file()
405 && template.join("objects").is_dir()
406 && template.join("refs").is_dir()
407 {
408 return Some(Foreign::Repository(path));
409 }
410 let dot = template.join(".git");
411 if dot.is_dir() && occupied(&dot) {
413 return Some(Foreign::Checkout(path));
414 }
415 if dot.is_file() {
416 let gitdir = git(template, &["rev-parse", "--absolute-git-dir"]);
417 let common = real(
418 template,
419 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
420 );
421 match (gitdir, common) {
422 (Ok(gitdir), Some(common))
423 if real(template, &["rev-parse", "--show-toplevel"])
424 == fs::canonicalize(template).ok() =>
425 {
426 if fs::canonicalize(&gitdir).ok().as_ref() == Some(&common) {
427 return Some(Foreign::Checkout(path));
428 }
429 if let Ok(b) = git(template, &["symbolic-ref", "-q", "--short", "HEAD"]) {
430 return Some(Foreign::Branch(path, b));
431 }
432 let busy = [
434 "rebase-merge",
435 "rebase-apply",
436 "MERGE_HEAD",
437 "BISECT_LOG",
438 "CHERRY_PICK_HEAD",
439 "REVERT_HEAD",
440 "sequencer",
441 ]
442 .iter()
443 .any(|f| Path::new(&gitdir).join(f).exists());
444 return (!made || busy).then_some(Foreign::Detached(path));
445 }
446 (Err(_), _) if made => return None,
448 (Err(e), _) => return Some(Foreign::Unreadable(path, e.to_string())),
449 _ => {}
451 }
452 }
453 let home = std::env::home_dir().and_then(|h| fs::canonicalize(h).ok());
455 if let (Some(home), Ok(real)) = (home, fs::canonicalize(template))
456 && home.starts_with(&real)
457 {
458 return Some(Foreign::Home(path));
459 }
460 if git(template, &["ls-files"]).is_ok_and(|o| !o.is_empty()) {
461 let top = real(template, &["rev-parse", "--show-toplevel"]).unwrap_or_default();
462 return Some(Foreign::Inside(path, top));
463 }
464 if let Some(inner) = nested_repository(template) {
465 return Some(Foreign::Nested(path, inner));
466 }
467 Some(Foreign::Files(path))
469}
470
471fn nested_repository(dir: &Path) -> Option<PathBuf> {
474 let mut stack = vec![dir.to_path_buf()];
475 while let Some(d) = stack.pop() {
476 let Ok(entries) = fs::read_dir(&d) else {
477 continue;
478 };
479 for entry in entries.flatten() {
480 let path = entry.path();
481 let Ok(kind) = entry.file_type() else {
482 continue;
483 };
484 if entry.file_name() == ".git" && (kind.is_file() || occupied(&path)) {
485 return Some(d);
486 }
487 if kind.is_dir() {
488 if path.join("HEAD").is_file() && path.join("objects").is_dir() {
489 return Some(path);
490 }
491 stack.push(path);
492 }
493 }
494 }
495 None
496}
497
498fn refresh_template(repo: &Path, template: &Path, start: &str) -> io::Result<()> {
500 remove_any(&beside(template, "trash"));
501 if template.join(".git").exists()
502 && git(template, &["checkout", "--detach", "--force", start]).is_ok()
503 {
504 return Ok(());
505 }
506 discard(template);
507 if clone_checkout(repo, template, start).is_ok() {
508 return Ok(());
509 }
510 discard(template);
511 git(
512 repo,
513 &[
514 "worktree",
515 "add",
516 "-f",
517 "--detach",
518 &template.to_string_lossy(),
519 start,
520 ],
521 )?;
522 Ok(())
523}
524
525fn clone_checkout(repo: &Path, template: &Path, start: &str) -> io::Result<()> {
528 let top = PathBuf::from(git(repo, &["rev-parse", "--show-toplevel"])?);
529 let parent = template
530 .parent()
531 .ok_or_else(|| err("template has no parent".into()))?;
532 if !can_clone(&top, parent) {
533 return Err(err("checkout and template cannot share blocks".into()));
534 }
535 git(
536 repo,
537 &[
538 "worktree",
539 "add",
540 "-f",
541 "--no-checkout",
542 "--detach",
543 &template.to_string_lossy(),
544 start,
545 ],
546 )?;
547 for name in git(&top, &["ls-tree", "--name-only", "HEAD"])?.lines() {
548 let src = top.join(name);
549 if src.symlink_metadata().is_ok() {
550 clone_into(&src, template)?;
551 }
552 }
553 let src_git = git(&top, &["rev-parse", "--absolute-git-dir"])?;
554 let tpl_git = git(template, &["rev-parse", "--absolute-git-dir"])?;
555 fs::copy(
556 Path::new(&src_git).join("index"),
557 Path::new(&tpl_git).join("index"),
558 )?;
559 let _ = git(template, &["update-index", "-q", "--refresh"]);
560 git(template, &["reset", "--hard", "-q"])?;
561 git(template, &["clean", "-fdxq"])?;
562 Ok(())
563}
564
565fn ignored_dirs(src: &Path, share: &[String]) -> io::Result<Vec<String>> {
568 let out = git(
569 src,
570 &[
571 "ls-files",
572 "--others",
573 "--ignored",
574 "--exclude-standard",
575 "--directory",
576 ],
577 )?;
578 Ok(out
579 .lines()
580 .filter_map(|l| l.strip_suffix('/'))
581 .filter(|n| {
582 !n.is_empty()
583 && n.split('/')
584 .all(|c| !c.starts_with('.') || share.iter().any(|s| s == c))
585 })
586 .map(String::from)
587 .collect())
588}
589
590fn within(root: &Path, path: &Path) -> bool {
592 path.ancestors()
593 .skip(1)
594 .find_map(|a| fs::canonicalize(a).ok())
595 .is_some_and(|a| a.starts_with(root))
596}
597
598fn absolute(path: &Path) -> io::Result<PathBuf> {
600 let mut out = PathBuf::new();
601 for c in std::path::absolute(path)?.components() {
602 match c {
603 std::path::Component::ParentDir => {
604 out.pop();
605 }
606 std::path::Component::CurDir => {}
607 c => out.push(c),
608 }
609 }
610 Ok(out)
611}
612
613fn warm_template(src: &Path, template: &Path, share: &[String]) -> io::Result<()> {
616 let staging = beside(template, "warm");
617 let root = fs::canonicalize(template)?;
618 for dir in ignored_dirs(src, share)? {
619 if !git(template, &["ls-files", "--", &dir])
621 .unwrap_or_default()
622 .is_empty()
623 {
624 continue;
625 }
626 let _ = fs::remove_dir_all(&staging);
627 fs::create_dir_all(&staging)?;
628 let _ = (|| {
630 clone_moved(&src.join(&dir), &staging, src, template)?;
631 let dst = template.join(&dir);
632 if !within(&root, &dst) {
634 return Ok(());
635 }
636 let _ = fs::remove_dir_all(&dst);
637 if let Some(parent) = dst.parent() {
638 fs::create_dir_all(parent)?;
639 }
640 let base = Path::new(&dir).file_name().unwrap_or_default();
641 fs::rename(staging.join(base), dst)
642 })();
643 let _ = fs::remove_dir_all(&staging);
644 }
645 Ok(())
646}
647
648pub fn warm(src: &Path, template: &Path) -> io::Result<()> {
657 warm_with(src, template, &Options::default())
658}
659
660pub fn warm_with(src: &Path, template: &Path, opts: &Options) -> io::Result<()> {
668 let template = &absolute(template)?;
669 if !template.join(".git").exists() {
670 return Err(err(format!("no template at {}", template.display())));
671 }
672 if let Some(f) = foreign(template) {
673 return Err(io::Error::other(f));
674 }
675 let _lock = lock_template(template)?;
676 warm_template(src, template, &opts.share)?;
677 stamp(template)
678}
679
680pub fn remove_template(repo: &Path, template: &Path) -> io::Result<()> {
691 let template = &absolute(template)?;
692 if template.parent().is_none_or(|p| !p.exists()) {
693 return Ok(());
694 }
695 if let Some(f) = foreign(template) {
696 return Err(io::Error::other(f));
697 }
698 let _lock = lock_template(template)?;
699 let registered = template.join(".git").exists();
700 let aside = beside(template, "trash");
701 remove_any(&aside);
702 let moved = fs::rename(template, &aside).is_ok();
704 if registered
705 && let Err(e) = git(
706 repo,
707 &["worktree", "remove", "--force", &template.to_string_lossy()],
708 )
709 {
710 if moved {
711 let _ = fs::rename(&aside, template);
712 }
713 return Err(e);
714 }
715 remove_any(&aside);
716 remove_any(template);
717 let _ = fs::remove_dir_all(beside(template, "warm"));
718 for ext in ["warmed", "lock"] {
719 match fs::remove_file(beside(template, ext)) {
720 Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
721 _ => {}
722 }
723 }
724 Ok(())
725}
726
727fn stamp_path(template: &Path) -> PathBuf {
729 beside(template, "warmed")
730}
731
732fn stamp(template: &Path) -> io::Result<()> {
733 fs::write(stamp_path(template), b"")
734}
735
736fn warmed_within(template: &Path, interval: std::time::Duration) -> bool {
737 fs::metadata(stamp_path(template))
738 .and_then(|m| m.modified())
739 .ok()
740 .and_then(|t| t.elapsed().ok())
741 .is_some_and(|age| age < interval)
742}
743
744#[derive(Debug)]
747pub struct Occupied(pub PathBuf);
748
749impl std::fmt::Display for Occupied {
750 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
751 write!(f, "'{}' already exists", self.0.display())
752 }
753}
754
755impl std::error::Error for Occupied {}
756
757pub fn is_occupied(e: &io::Error) -> bool {
760 matches!(e.get_ref(), Some(inner) if inner.is::<Occupied>())
761}
762
763#[derive(Debug)]
766pub struct Unsupported(pub &'static str);
767
768impl std::fmt::Display for Unsupported {
769 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
770 f.write_str(self.0)
771 }
772}
773
774impl std::error::Error for Unsupported {}
775
776pub fn is_unsupported(e: &io::Error) -> bool {
779 matches!(e.get_ref(), Some(inner) if inner.is::<Unsupported>())
780}
781
782pub fn is_refused(e: &io::Error) -> bool {
785 e.get_ref()
786 .is_some_and(|inner| inner.is::<Occupied>() || inner.is::<Foreign>())
787}
788
789fn new_branch_name(
792 repo: &Path,
793 wt: &Path,
794 new_branch: Option<&str>,
795 commitish: Option<&str>,
796) -> Option<String> {
797 let b = match (new_branch, commitish) {
798 (Some(b), _) => b.to_string(),
799 (None, None) => wt.file_name()?.to_string_lossy().into_owned(),
800 _ => return None,
801 };
802 git(
803 repo,
804 &["rev-parse", "--verify", "-q", &format!("refs/heads/{b}")],
805 )
806 .is_err()
807 .then_some(b)
808}
809
810fn occupied(wt: &Path) -> bool {
812 match fs::symlink_metadata(wt) {
813 Err(_) => false,
814 Ok(m) if m.is_dir() => fs::read_dir(wt).map_or(true, |mut d| d.next().is_some()),
815 Ok(_) => true,
816 }
817}
818
819fn populate(template: &Path, wt: &Path) -> io::Result<()> {
821 for entry in fs::read_dir(template)? {
822 let entry = entry?;
823 if entry.file_name() == ".git" {
824 continue;
825 }
826 clone_into(&entry.path(), wt)?;
827 }
828
829 let tpl_git = git(template, &["rev-parse", "--absolute-git-dir"])?;
832 let wt_git = git(wt, &["rev-parse", "--absolute-git-dir"])?;
833 fs::copy(
834 Path::new(&tpl_git).join("index"),
835 Path::new(&wt_git).join("index"),
836 )?;
837 let _ = git(wt, &["update-index", "-q", "--refresh"]);
838 git(wt, &["reset", "--hard", "-q"])?;
839 Ok(())
840}
841
842pub fn add(
852 repo: &Path,
853 template: &Path,
854 template_start: &str,
855 wt: &Path,
856 new_branch: Option<&str>,
857 commitish: Option<&str>,
858) -> io::Result<()> {
859 add_with(
860 repo,
861 template,
862 template_start,
863 wt,
864 new_branch,
865 commitish,
866 &Options::default(),
867 )
868}
869
870pub fn add_with(
878 repo: &Path,
879 template: &Path,
880 template_start: &str,
881 wt: &Path,
882 new_branch: Option<&str>,
883 commitish: Option<&str>,
884 opts: &Options,
885) -> io::Result<()> {
886 let wt = &absolute(wt)?;
888 let template = &absolute(template)?;
889 if occupied(wt) {
890 return Err(io::Error::new(
891 io::ErrorKind::AlreadyExists,
892 Occupied(wt.clone()),
893 ));
894 }
895 let wt_parent = wt
896 .parent()
897 .ok_or_else(|| err("worktree has no parent".into()))?;
898 let tpl_parent = template
899 .parent()
900 .ok_or_else(|| err("template has no parent".into()))?;
901 fs::create_dir_all(wt_parent)?;
902 fs::create_dir_all(tpl_parent)?;
903 if !probe(tpl_parent, wt_parent)? {
904 return Err(io::Error::other(Unsupported("volume cannot clone files")));
905 }
906
907 let replace = match foreign(template) {
909 Some(Foreign::Files(_)) if opts.force > 0 => true,
910 Some(f) => return Err(io::Error::other(f)),
911 None => false,
912 };
913 let _lock = lock_template(template)?;
914 if replace {
915 discard(template);
916 }
917 refresh_template(repo, template, template_start)?;
918 if template.join(".gitmodules").exists() {
919 return Err(io::Error::other(Unsupported(
921 "submodules are not supported",
922 )));
923 }
924 let never = opts.warm_interval == std::time::Duration::MAX;
927 if !never && (opts.warm_interval.is_zero() || !warmed_within(template, opts.warm_interval)) {
928 let _ = warm_template(repo, template, &opts.share);
929 let _ = stamp(template);
930 }
931
932 let ours = new_branch_name(repo, wt, new_branch, commitish);
934 let wt_s = wt.to_string_lossy();
937 let mut args = vec!["worktree", "add", "--no-checkout"];
938 args.extend(std::iter::repeat_n("--force", opts.force.into()));
939 if let Some(b) = new_branch {
940 args.extend(["-b", b]);
941 }
942 args.push(&wt_s);
943 args.extend(commitish);
944 let was_dir = wt.is_dir();
945 if let Err(e) = git(repo, &args) {
946 if let Some(b) = &ours {
947 let _ = git(repo, &["branch", "-D", b.as_str()]);
948 }
949 return Err(e);
950 }
951 let res = populate(template, wt);
952 if res.is_err() {
953 let _ = git(
954 repo,
955 &["worktree", "remove", "--force", &wt.to_string_lossy()],
956 );
957 let _ = fs::remove_dir_all(wt);
958 if was_dir {
959 let _ = fs::create_dir(wt);
960 }
961 if let Some(b) = &ours {
962 let _ = git(repo, &["branch", "-D", b.as_str()]);
963 }
964 }
965 res
966}
967
968pub fn add_from_checkout(
981 repo: &Path,
982 wt: &Path,
983 commitish: &str,
984 opts: &Options,
985) -> io::Result<()> {
986 let wt = &absolute(wt)?;
987 if occupied(wt) {
988 return Err(io::Error::new(
989 io::ErrorKind::AlreadyExists,
990 Occupied(wt.clone()),
991 ));
992 }
993 let Ok(top) = git(repo, &["rev-parse", "--show-toplevel"]).map(PathBuf::from) else {
994 return Err(io::Error::other(Unsupported("repository has no checkout")));
995 };
996 let wt_parent = wt
997 .parent()
998 .ok_or_else(|| err("worktree has no parent".into()))?;
999 fs::create_dir_all(wt_parent)?;
1000 if !probe(&top, wt_parent)? {
1001 return Err(io::Error::other(Unsupported("volume cannot clone files")));
1002 }
1003 let tracks_modules =
1005 |rev: &str| git(&top, &["cat-file", "-e", &format!("{rev}:.gitmodules")]).is_ok();
1006 if top.join(".gitmodules").exists() || tracks_modules("HEAD") || tracks_modules(commitish) {
1007 return Err(io::Error::other(Unsupported(
1008 "submodules are not supported",
1009 )));
1010 }
1011
1012 let was_dir = wt.is_dir();
1013 let res = clone_checkout(&top, wt, commitish);
1014 if res.is_ok() {
1015 let _ = warm_template(&top, wt, &opts.share);
1017 } else {
1018 let _ = git(
1019 &top,
1020 &["worktree", "remove", "--force", &wt.to_string_lossy()],
1021 );
1022 let _ = fs::remove_dir_all(wt);
1023 if was_dir {
1024 let _ = fs::create_dir(wt);
1025 }
1026 }
1027 res
1028}
1029
1030#[derive(Debug)]
1032#[expect(
1033 clippy::exhaustive_enums,
1034 reason = "a clone or a plain worktree is the whole answer, and #[non_exhaustive] would break callers that match it"
1035)]
1036pub enum Added {
1037 Cloned,
1039 Plain(io::Error),
1041}
1042
1043pub fn add_or_plain(
1052 repo: &Path,
1053 template: &Path,
1054 template_start: &str,
1055 wt: &Path,
1056 new_branch: Option<&str>,
1057 commitish: Option<&str>,
1058 opts: &Options,
1059) -> io::Result<Added> {
1060 let wt = &absolute(wt)?;
1061 let Err(why) = add_with(
1062 repo,
1063 template,
1064 template_start,
1065 wt,
1066 new_branch,
1067 commitish,
1068 opts,
1069 ) else {
1070 return Ok(Added::Cloned);
1071 };
1072 if is_refused(&why) {
1073 return Err(why);
1074 }
1075
1076 let wt_s = wt.to_string_lossy();
1077 let mut args = vec!["worktree", "add"];
1078 args.extend(std::iter::repeat_n("--force", opts.force.into()));
1079 if let Some(b) = new_branch {
1080 args.extend(["-b", b]);
1081 }
1082 args.push(&wt_s);
1083 args.extend(commitish);
1084 let ours = new_branch_name(repo, wt, new_branch, commitish);
1085 if let Err(e) = git(repo, &args) {
1086 if let Some(b) = &ours {
1088 let _ = git(repo, &["branch", "-D", b.as_str()]);
1089 }
1090 return Err(err(format!("{e}, after cloning failed: {why}")));
1091 }
1092 Ok(Added::Plain(why))
1093}