1use std::collections::{HashMap, HashSet};
6use std::io::{self, Write};
7#[cfg(unix)]
8use std::os::unix::fs::DirBuilderExt;
9use std::path::{Path, PathBuf};
10use std::process::{Command, Stdio};
11use std::sync::atomic::{AtomicUsize, Ordering};
12use std::time::{SystemTime, UNIX_EPOCH};
13
14use crate::{REPO_ENV, config_path};
15
16const QUIET: &[&str] = &[
19 "-c",
20 "core.fsmonitor=false",
21 "-c",
22 "log.showSignature=false",
23 "--no-optional-locks",
24];
25
26const BUSY: &[&str] = &[
28 "rebase-merge",
29 "rebase-apply",
30 "MERGE_HEAD",
31 "BISECT_LOG",
32 "CHERRY_PICK_HEAD",
33 "REVERT_HEAD",
34 "sequencer",
35];
36
37const NO_ATTRIBUTES: &str = "--attr-source=4b825dc642cb6eb9a060e54bf8d69288fbee4904";
39
40const DIFF: &[&str] = &[
42 "--no-ext-diff",
43 "--no-textconv",
44 "--binary",
45 "--full-index",
46 "--no-color",
47];
48
49fn err(msg: String) -> io::Error {
50 io::Error::other(msg)
51}
52
53fn git_cmd(dir: &Path) -> Command {
54 let mut cmd = Command::new("git");
55 for var in REPO_ENV {
56 cmd.env_remove(var);
57 }
58 cmd.env("GIT_NO_LAZY_FETCH", "1");
60 cmd.arg("-C").arg(dir).args(QUIET);
61 cmd
62}
63
64fn run(dir: &Path, args: &[&str]) -> io::Result<String> {
65 let out = git_cmd(dir).args(args).stderr(Stdio::piped()).output()?;
66 if !out.status.success() {
67 return Err(err(format!(
68 "git {args:?}: {}",
69 String::from_utf8_lossy(&out.stderr).trim()
70 )));
71 }
72 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
73}
74
75fn patch_ids(dir: &Path, args: &[&str], input: Option<String>) -> io::Result<String> {
78 let mut producer = git_cmd(dir)
79 .args(args)
80 .stdin(if input.is_some() {
81 Stdio::piped()
82 } else {
83 Stdio::null()
84 })
85 .stdout(Stdio::piped())
86 .stderr(Stdio::null())
87 .spawn()?;
88 let writer = match (input, producer.stdin.take()) {
89 (Some(text), Some(mut stdin)) => {
90 Some(std::thread::spawn(move || stdin.write_all(text.as_bytes())))
91 }
92 _ => None,
93 };
94 let diff = producer
95 .stdout
96 .take()
97 .ok_or_else(|| err("git gave no output pipe".into()))?;
98 let out = git_cmd(dir)
99 .args(["patch-id", "--verbatim"])
100 .stdin(diff)
101 .stderr(Stdio::null())
102 .output()?;
103 if let Some(w) = writer {
104 let _ = w.join();
105 }
106 if !producer.wait()?.success() || !out.status.success() {
107 return Err(err(format!("git {args:?} | git patch-id failed")));
108 }
109 Ok(String::from_utf8_lossy(&out.stdout).into_owned())
110}
111
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114#[non_exhaustive]
115pub enum State {
116 Merged,
118 Squashed,
120 Gone,
122 Active,
124}
125
126impl State {
127 pub fn label(self) -> &'static str {
129 match self {
130 State::Merged => "merged",
131 State::Squashed => "squashed",
132 State::Gone => "gone",
133 State::Active => "active",
134 }
135 }
136
137 pub fn landed(self) -> bool {
139 matches!(self, State::Merged | State::Squashed)
140 }
141}
142
143struct Worktree {
144 path: PathBuf,
145 branch: Option<String>,
146 head: String,
147 locked: bool,
148}
149
150fn worktrees(dir: &Path) -> io::Result<(Worktree, Vec<Worktree>)> {
153 let out = git_cmd(dir)
154 .args(["worktree", "list", "--porcelain", "-z"])
155 .stderr(Stdio::piped())
156 .output()?;
157 if !out.status.success() {
158 return Err(err(format!(
159 "git worktree list: {}",
160 String::from_utf8_lossy(&out.stderr).trim()
161 )));
162 }
163 let text = String::from_utf8_lossy(&out.stdout).into_owned();
164 let mut all = text.split("\0\0").filter(|b| !b.is_empty()).map(|block| {
165 let mut wt = Worktree {
166 path: PathBuf::new(),
167 branch: None,
168 head: String::new(),
169 locked: false,
170 };
171 for line in block.split('\0') {
172 if let Some(p) = line.strip_prefix("worktree ") {
173 wt.path = PathBuf::from(p);
174 } else if let Some(h) = line.strip_prefix("HEAD ") {
175 wt.head = h.to_string();
176 } else if let Some(b) = line.strip_prefix("branch refs/heads/") {
177 wt.branch = Some(b.to_string());
178 } else if line == "locked" || line.starts_with("locked ") {
179 wt.locked = true;
180 }
181 }
182 wt
183 });
184 let main = all
185 .next()
186 .ok_or_else(|| err("git lists no worktree".into()))?;
187 Ok((main, all.collect()))
188}
189
190#[derive(Debug)]
192pub struct Base {
193 pub name: String,
195 pub oid: String,
197 local: Option<String>,
199}
200
201fn base(repo: &Path, named: Option<&str>) -> io::Result<Base> {
204 let candidates: Vec<String> = match named {
205 Some(b) => vec![
206 run(repo, &["rev-parse", "--symbolic-full-name", b])
207 .ok()
208 .filter(|f| !f.is_empty())
209 .unwrap_or_else(|| b.to_string()),
210 ],
211 None => [
212 "refs/remotes/origin/HEAD",
213 "refs/remotes/origin/main",
214 "refs/remotes/origin/master",
215 "refs/heads/main",
216 "refs/heads/master",
217 ]
218 .map(String::from)
219 .to_vec(),
220 };
221 for c in candidates {
222 let full = run(repo, &["symbolic-ref", "-q", &c]).unwrap_or(c);
223 let Ok(oid) = run(
224 repo,
225 &["rev-parse", "--verify", "-q", &format!("{full}^{{commit}}")],
226 ) else {
227 continue;
228 };
229 let local = if let Some(rest) = full.strip_prefix("refs/remotes/") {
230 remote_branch(repo, rest)
231 } else {
232 full.strip_prefix("refs/heads/").map(String::from)
233 };
234 let name = full
235 .strip_prefix("refs/remotes/")
236 .or_else(|| full.strip_prefix("refs/heads/"))
237 .unwrap_or(&full)
238 .to_string();
239 return Ok(Base { name, oid, local });
240 }
241 Err(err(
242 "no branch to compare with, name one: git cow cleanup <branch>".into(),
243 ))
244}
245
246fn remote_branch(repo: &Path, rest: &str) -> Option<String> {
249 let remotes = run(repo, &["remote"]).unwrap_or_default();
250 remotes
251 .lines()
252 .filter_map(|r| {
253 rest.strip_prefix(r)
254 .and_then(|b| b.strip_prefix('/'))
255 .map(|b| (r.len(), b))
256 })
257 .max_by_key(|(n, _)| *n)
258 .map(|(_, b)| b.to_string())
259 .or_else(|| rest.split_once('/').map(|(_, b)| b.to_string()))
260}
261
262fn is_partial(repo: &Path) -> bool {
264 run(repo, &["config", "--get", "extensions.partialClone"]).is_ok()
265 || run(repo, &["config", "--get-regexp", r"^remote\..*\.promisor$"])
266 .is_ok_and(|o| o.lines().any(|l| l.ends_with(" true")))
267}
268
269struct Probe {
270 own: String,
272 undo: String,
273 commits: String,
275 mb: String,
276}
277
278fn squash_probe(repo: &Path, base: &str, rev: &str) -> Option<Probe> {
280 if run(repo, &["merge-base", "--is-ancestor", rev, base]).is_ok() {
281 return None;
282 }
283 let mb = run(repo, &["merge-base", base, rev]).ok()?;
284 let pid = |from: &str, to: &str| {
285 let mut args = vec!["diff"];
286 args.extend(DIFF);
287 args.extend([from, to]);
288 let out = patch_ids(repo, &args, None).ok()?;
289 out.split_whitespace().next().map(String::from)
290 };
291 let own = pid(&mb, rev)?;
292 let undo = pid(rev, &mb)?;
293 let commits = run(
294 repo,
295 &[
296 "rev-list",
297 "--no-merges",
298 "--topo-order",
299 base,
300 &format!("^{mb}"),
301 ],
302 )
303 .ok()?;
304 Some(Probe {
305 own,
306 undo,
307 commits,
308 mb,
309 })
310}
311
312fn scratch_dir(common: &Path) -> Option<PathBuf> {
316 static COUNT: AtomicUsize = AtomicUsize::new(0);
317 let nanos = SystemTime::now()
318 .duration_since(UNIX_EPOCH)
319 .map_or(0, |d| d.subsec_nanos());
320 for _ in 0..8 {
321 let n = COUNT.fetch_add(1, Ordering::Relaxed);
322 let dir = common.join(format!("git-cow-merge-{}-{nanos}-{n}", std::process::id()));
323 #[cfg_attr(not(unix), expect(unused_mut, reason = "only Unix sets a mode"))]
324 let mut builder = std::fs::DirBuilder::new();
325 #[cfg(unix)]
326 builder.mode(0o700);
327 match builder.create(&dir) {
328 Ok(()) => return Some(dir),
329 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {}
330 Err(_) => return None,
331 }
332 }
333 None
334}
335
336fn merge_tree(repo: &Path, merge_base: &str, ours: &str, theirs: &str) -> Option<String> {
339 let common = run(
340 repo,
341 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
342 )
343 .ok()?;
344 let info =
346 std::fs::read_to_string(Path::new(&common).join("info/attributes")).unwrap_or_default();
347 if info.contains("merge") {
348 return None;
349 }
350 let scratch = scratch_dir(Path::new(&common))?;
351 let merge_base = format!("--merge-base={merge_base}");
352 let out = git_cmd(repo)
353 .env("GIT_OBJECT_DIRECTORY", &scratch)
354 .env(
355 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
356 Path::new(&common).join("objects"),
357 )
358 .args([
359 NO_ATTRIBUTES,
360 "-c",
361 "core.attributesFile=/dev/null",
362 "-c",
363 "merge.default=text",
364 "merge-tree",
365 "--write-tree",
366 "--no-messages",
367 &merge_base,
368 ours,
369 theirs,
370 ])
371 .stderr(Stdio::null())
372 .output();
373 let _ = std::fs::remove_dir_all(&scratch);
374 let out = out.ok().filter(|o| o.status.success())?;
375 String::from_utf8_lossy(&out.stdout)
376 .lines()
377 .next()
378 .map(String::from)
379}
380
381fn is_its_squash(repo: &Path, mb: &str, c: &str, rev: &str) -> bool {
384 let tree = run(repo, &["rev-parse", &format!("{c}^{{tree}}")]).ok();
385 tree.is_some() && merge_tree(repo, mb, &format!("{c}^"), rev) == tree
386}
387
388fn reverted(
391 repo: &Path,
392 base: &str,
393 c: &str,
394 later: &[&str],
395 undo: &str,
396 by_commit: &HashMap<String, String>,
397) -> bool {
398 later
399 .iter()
400 .any(|l| by_commit.get(*l).map(String::as_str) == Some(undo))
401 || run(
402 repo,
403 &[
404 "log",
405 "--format=%H",
406 "--fixed-strings",
407 &format!("--grep=This reverts commit {c}"),
408 base,
409 &format!("^{c}"),
410 ],
411 )
412 .is_ok_and(|out| !out.is_empty())
413}
414
415fn squashed(
418 repo: &Path,
419 base: &str,
420 rev: &str,
421 probe: &Probe,
422 by_commit: &HashMap<String, String>,
423) -> bool {
424 let commits: Vec<&str> = probe.commits.lines().collect();
425 commits.iter().enumerate().any(|(i, c)| {
426 by_commit.get(*c) == Some(&probe.own)
427 && is_its_squash(repo, &probe.mb, c, rev)
428 && !reverted(repo, base, c, &commits[..i], &probe.undo, by_commit)
429 })
430}
431
432fn commit_patch_ids(repo: &Path, commits: &HashSet<&str>) -> HashMap<String, String> {
434 let mut by_commit = HashMap::new();
435 if commits.is_empty() {
436 return by_commit;
437 }
438 let mut args = vec![
439 "log",
440 "-p",
441 "--no-walk=unsorted",
442 "--stdin",
443 "--format=commit %H",
444 ];
445 args.extend(DIFF);
446 let input = commits.iter().fold(String::new(), |mut list, c| {
447 list.push_str(c);
448 list.push('\n');
449 list
450 });
451 if let Ok(out) = patch_ids(repo, &args, Some(input)) {
452 for line in out.lines() {
453 if let Some((pid, commit)) = line.split_once(' ') {
454 by_commit.insert(commit.to_string(), pid.to_string());
455 }
456 }
457 }
458 by_commit
459}
460
461fn states(repo: &Path, base: &Base, revs: &[(String, Option<String>)]) -> Vec<State> {
464 let partial = is_partial(repo);
465 let probes: Vec<Option<Probe>> = revs
466 .iter()
467 .map(|(rev, _)| {
468 if partial {
469 None
470 } else {
471 squash_probe(repo, &base.oid, rev)
472 }
473 })
474 .collect();
475 let wanted: HashSet<&str> = probes
476 .iter()
477 .flatten()
478 .flat_map(|p| p.commits.lines())
479 .collect();
480 let by_commit = commit_patch_ids(repo, &wanted);
481 revs.iter()
482 .zip(&probes)
483 .map(|((rev, branch), probe)| {
484 if run(repo, &["merge-base", "--is-ancestor", rev, &base.oid]).is_ok() {
485 return State::Merged;
486 }
487 if probe
488 .as_ref()
489 .is_some_and(|p| squashed(repo, &base.oid, rev, p, &by_commit))
490 {
491 return State::Squashed;
492 }
493 let gone = branch.as_deref().is_some_and(|b| {
494 run(
495 repo,
496 &[
497 "for-each-ref",
498 "--format=%(upstream:track)",
499 &format!("refs/heads/{b}"),
500 ],
501 )
502 .is_ok_and(|t| t == "[gone]")
503 });
504 if gone { State::Gone } else { State::Active }
505 })
506 .collect()
507}
508
509fn changes(path: &Path) -> String {
512 if !path.exists() {
513 return String::new();
514 }
515 let mut seen = run(
516 path,
517 &[
518 "status",
519 "--porcelain",
520 "--untracked-files=all",
521 "--ignore-submodules=none",
522 ],
523 )
524 .unwrap_or_else(|e| format!("unreadable: {e}"));
525 if let Ok(files) = run(path, &["ls-files", "-v"]) {
526 for l in files
527 .lines()
528 .filter(|l| l.starts_with(|c: char| c.is_ascii_lowercase() || c == 'S'))
529 {
530 seen.push('\n');
531 seen.push_str(l);
532 }
533 }
534 seen.trim().to_string()
535}
536
537fn repository_below(dir: &Path) -> bool {
540 let mut stack = vec![dir.to_path_buf()];
541 while let Some(d) = stack.pop() {
542 if d.join(".git").exists() || (d.join("HEAD").is_file() && d.join("objects").is_dir()) {
543 return true;
544 }
545 let Ok(entries) = std::fs::read_dir(&d) else {
546 continue;
547 };
548 stack.extend(
549 entries
550 .flatten()
551 .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
552 .map(|e| e.path()),
553 );
554 }
555 false
556}
557
558fn holds_repository(path: &Path) -> bool {
560 let Ok(out) = git_cmd(path)
561 .args([
562 "status",
563 "--porcelain",
564 "-z",
565 "--ignored=traditional",
566 "--untracked-files=normal",
567 ])
568 .stderr(Stdio::null())
569 .output()
570 else {
571 return true;
572 };
573 !out.status.success()
575 || String::from_utf8_lossy(&out.stdout)
576 .split('\0')
577 .filter_map(|e| e.strip_prefix("?? ").or_else(|| e.strip_prefix("!! ")))
578 .filter(|p| p.ends_with('/'))
579 .any(|p| repository_below(&path.join(p)))
580}
581
582fn admin_dirs(repo: &Path) -> HashMap<PathBuf, PathBuf> {
585 let mut map = HashMap::new();
586 let Ok(common) = run(
587 repo,
588 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
589 ) else {
590 return map;
591 };
592 if let Ok(entries) = std::fs::read_dir(Path::new(&common).join("worktrees")) {
593 for e in entries.flatten() {
594 if let Ok(gitfile) = std::fs::read_to_string(e.path().join("gitdir"))
595 && let Some(wt) = Path::new(gitfile.trim()).parent()
596 {
597 map.insert(wt.to_path_buf(), e.path());
598 }
599 }
600 }
601 map
602}
603
604fn own_state(repo: &Path, path: &Path, admin: Option<&PathBuf>) -> Option<Keep> {
607 let Some(admin) = admin else {
608 return Some(Keep::Unreadable);
609 };
610 let submodules = admin.join("modules").exists()
611 || path.join(".gitmodules").exists()
612 || run(path, &["ls-files", "-s"]).is_ok_and(|s| s.lines().any(|l| l.starts_with("160000")));
613 if submodules {
614 return Some(Keep::Submodules);
615 }
616 if path.exists() && holds_repository(path) {
617 return Some(Keep::Repository);
618 }
619 if BUSY.iter().any(|f| admin.join(f).exists()) {
620 return Some(Keep::Busy);
621 }
622 let admin = admin.to_string_lossy();
623 let refs = run(
624 repo,
625 &[
626 "--git-dir",
627 &admin,
628 "for-each-ref",
629 "refs/worktree/",
630 "refs/bisect/",
631 ],
632 );
633 if refs.is_ok_and(|s| !s.is_empty()) {
634 return Some(Keep::OwnRefs);
635 }
636 None
637}
638
639fn claude_worktree(path: &Path) -> bool {
641 let parts: Vec<_> = path
642 .components()
643 .map(std::path::Component::as_os_str)
644 .collect();
645 parts
646 .windows(2)
647 .any(|w| w[0] == ".claude" && w[1] == "worktrees")
648}
649
650fn busy_branches(repo: &Path) -> HashSet<String> {
652 let mut busy = HashSet::new();
653 let Ok(common) = run(
654 repo,
655 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
656 ) else {
657 return busy;
658 };
659 let common = PathBuf::from(common);
660 let mut gitdirs = vec![common.clone()];
661 if let Ok(entries) = std::fs::read_dir(common.join("worktrees")) {
662 gitdirs.extend(entries.flatten().map(|e| e.path()));
663 }
664 for g in gitdirs {
665 for f in [
666 "rebase-merge/head-name",
667 "rebase-apply/head-name",
668 "BISECT_START",
669 ] {
670 if let Ok(text) = std::fs::read_to_string(g.join(f)) {
671 let name = text.trim();
672 busy.insert(name.strip_prefix("refs/heads/").unwrap_or(name).to_string());
673 }
674 }
675 }
676 busy
677}
678
679fn rev_of(w: &Worktree) -> (String, Option<String>) {
680 let rev = w
681 .branch
682 .as_ref()
683 .map_or_else(|| w.head.clone(), |b| format!("refs/heads/{b}"));
684 (rev, w.branch.clone())
685}
686
687#[derive(Clone, Copy, Debug, PartialEq, Eq)]
689#[non_exhaustive]
690pub enum Action {
691 Remove,
693 Keep(Keep),
695}
696
697#[derive(Clone, Copy, Debug, PartialEq, Eq)]
699#[non_exhaustive]
700pub enum Keep {
701 NotLanded,
703 Locked,
705 Inside,
707 ClaudeCode,
709 BaseBranch,
712 FolderMissing,
714 Submodules,
716 Repository,
718 Busy,
720 OwnRefs,
722 Unreadable,
724 Changes,
726}
727
728impl std::fmt::Display for Keep {
729 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
730 f.write_str(match self {
731 Keep::NotLanded => "not landed",
732 Keep::Locked => "locked",
733 Keep::Inside => "you are in it",
734 Keep::ClaudeCode => "Claude Code worktree",
735 Keep::BaseBranch => "base branch",
736 Keep::FolderMissing => "folder missing",
737 Keep::Submodules => "has submodules",
738 Keep::Repository => "holds a repository",
739 Keep::Busy => "in a rebase, merge or bisect",
740 Keep::OwnRefs => "has its own refs",
741 Keep::Unreadable => "unreadable",
742 Keep::Changes => "has changes",
743 })
744 }
745}
746
747#[derive(Clone, Copy, Debug, PartialEq, Eq)]
748enum Force {
749 No,
750 Yes,
751}
752
753#[derive(Clone, Debug, Default)]
755pub struct Options {
756 pub base: Option<String>,
758 pub force: bool,
761}
762
763#[derive(Debug)]
775pub struct Item {
776 path: Option<PathBuf>,
777 branch: Option<String>,
778 state: State,
779 action: Action,
780 oid: String,
782 changes: String,
783 branch_too: bool,
785 forced: Force,
786 admin: Option<PathBuf>,
788}
789
790impl Item {
791 pub fn path(&self) -> Option<&Path> {
793 self.path.as_deref()
794 }
795
796 pub fn branch(&self) -> Option<&str> {
798 self.branch.as_deref()
799 }
800
801 pub fn state(&self) -> State {
803 self.state
804 }
805
806 pub fn action(&self) -> Action {
808 self.action
809 }
810
811 pub fn oid(&self) -> &str {
813 &self.oid
814 }
815
816 pub fn deletes_branch(&self) -> bool {
819 self.branch_too
820 }
821
822 pub fn discards_changes(&self) -> bool {
824 !self.changes.is_empty()
825 }
826}
827
828#[derive(Debug)]
830pub struct Plan {
831 repo: PathBuf,
832 base: Base,
833 items: Vec<Item>,
834}
835
836impl Plan {
837 pub fn repo(&self) -> &Path {
839 &self.repo
840 }
841
842 pub fn base(&self) -> &Base {
844 &self.base
845 }
846
847 pub fn items(&self) -> &[Item] {
849 &self.items
850 }
851}
852
853fn worktree_items(
854 repo: &Path,
855 base: &Base,
856 linked: &[Worktree],
857 protected: &HashSet<String>,
858 here: &Path,
859 force: Force,
860) -> Vec<Item> {
861 let revs: Vec<(String, Option<String>)> = linked.iter().map(rev_of).collect();
862 let admins = admin_dirs(repo);
863 let mut items = Vec::new();
864 for (wt, state) in linked.iter().zip(states(repo, base, &revs)) {
865 let changes = changes(&wt.path);
866 let admin = admins.get(&wt.path).or_else(|| {
867 let real = std::fs::canonicalize(&wt.path).ok()?;
868 admins
869 .iter()
870 .find(|(p, _)| std::fs::canonicalize(p).is_ok_and(|q| q == real))
871 .map(|(_, a)| a)
872 });
873 let inside = here.starts_with(&wt.path)
874 || std::fs::canonicalize(&wt.path).is_ok_and(|p| here.starts_with(p));
875 let action = if !state.landed() {
876 Action::Keep(Keep::NotLanded)
877 } else if wt.locked {
878 Action::Keep(Keep::Locked)
879 } else if inside {
880 Action::Keep(Keep::Inside)
881 } else if claude_worktree(&wt.path) {
882 Action::Keep(Keep::ClaudeCode)
883 } else if wt.branch.as_ref().is_some_and(|b| protected.contains(b)) {
884 Action::Keep(Keep::BaseBranch)
885 } else if !wt.path.exists() && force == Force::No {
886 Action::Keep(Keep::FolderMissing)
887 } else if let Some(why) = own_state(repo, &wt.path, admin) {
888 Action::Keep(why)
889 } else if !changes.is_empty() && force == Force::No {
890 Action::Keep(Keep::Changes)
891 } else {
892 Action::Remove
893 };
894 let forced = if !changes.is_empty() || !wt.path.exists() {
895 Force::Yes
896 } else {
897 Force::No
898 };
899 items.push(Item {
900 path: Some(wt.path.clone()),
901 branch: wt.branch.clone(),
902 changes,
903 oid: wt.head.clone(),
904 state,
905 action,
906 branch_too: false,
907 forced,
908 admin: admin.cloned(),
909 });
910 }
911 let mut last: HashMap<String, usize> = HashMap::new();
913 for (i, item) in items.iter().enumerate() {
914 if let Some(b) = &item.branch {
915 last.insert(b.clone(), i);
916 }
917 }
918 for (b, i) in &last {
919 let all_go = items
920 .iter()
921 .filter(|it| it.branch.as_ref() == Some(b))
922 .all(|it| matches!(it.action, Action::Remove));
923 if all_go && !protected.contains(b) {
924 items[*i].branch_too = true;
925 }
926 }
927 items
928}
929
930pub fn plan(dir: &Path, opts: &Options) -> io::Result<Plan> {
939 judge(dir, opts, None)
940}
941
942pub fn plan_worktree(dir: &Path, wt: &Path, opts: &Options) -> io::Result<Plan> {
951 judge(dir, opts, Some(wt))
952}
953
954fn same_path(a: &Path, b: &Path) -> bool {
955 a == b || std::fs::canonicalize(a).is_ok_and(|p| std::fs::canonicalize(b).ok() == Some(p))
956}
957
958fn judge(dir: &Path, opts: &Options, only: Option<&Path>) -> io::Result<Plan> {
959 let named = opts.base.as_deref();
960 let force = if opts.force { Force::Yes } else { Force::No };
961 let (main, linked) = worktrees(dir)?;
962 let repo = main.path.clone();
964 let base = base(&repo, named)?;
965 let here = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
966 let mut protected: HashSet<String> = base.local.iter().cloned().collect();
967 protected.extend(main.branch);
968 protected.extend(head_branch(&repo));
969 if named.is_some() {
970 protected.extend(base_of(&repo));
971 }
972 protected.extend(busy_branches(&repo));
973 let checked_out: HashSet<String> = linked.iter().filter_map(|w| w.branch.clone()).collect();
975 let mut linked: Vec<Worktree> = linked
976 .into_iter()
977 .filter(|w| !is_extra_checkout(&repo, &w.path))
978 .collect();
979 if let Some(wt) = only {
980 let target = linked
981 .iter()
982 .find(|w| same_path(&w.path, wt))
983 .ok_or_else(|| {
984 err(format!(
985 "{} is not a worktree of this repository, or is an extra checkout",
986 wt.display()
987 ))
988 })?;
989 let (path, branch) = (target.path.clone(), target.branch.clone());
991 linked.retain(|w| w.path == path || (branch.is_some() && w.branch == branch));
992 let mut items = worktree_items(&repo, &base, &linked, &protected, &here, force);
993 items.retain(|i| i.path.as_ref() == Some(&path));
994 if linked.len() > 1 {
995 for item in &mut items {
996 item.branch_too = false;
997 }
998 }
999 return Ok(Plan { repo, base, items });
1000 }
1001 let mut items = worktree_items(&repo, &base, &linked, &protected, &here, force);
1002
1003 let heads = run(
1005 &repo,
1006 &[
1007 "for-each-ref",
1008 "--format=%(refname)%00%(symref)",
1009 "refs/heads/",
1010 ],
1011 )?;
1012 let mut only = Vec::new();
1013 for entry in heads.lines() {
1014 let (full, symref) = entry.split_once('\0').unwrap_or((entry, ""));
1015 let Some(b) = full.strip_prefix("refs/heads/") else {
1016 continue;
1017 };
1018 if !symref.is_empty() {
1019 continue;
1020 }
1021 if checked_out.contains(b) || protected.contains(b) {
1022 continue;
1023 }
1024 let oid = run(&repo, &["rev-parse", "--verify", "-q", full])?;
1025 only.push((b.to_string(), oid));
1026 }
1027 let revs: Vec<(String, Option<String>)> = only
1028 .iter()
1029 .map(|(b, _)| (format!("refs/heads/{b}"), Some(b.clone())))
1030 .collect();
1031 for ((b, oid), state) in only.into_iter().zip(states(&repo, &base, &revs)) {
1032 items.push(Item {
1033 path: None,
1034 branch: Some(b),
1035 changes: String::new(),
1036 oid,
1037 state,
1038 action: if state.landed() {
1039 Action::Remove
1040 } else {
1041 Action::Keep(Keep::NotLanded)
1042 },
1043 branch_too: true,
1044 forced: Force::No,
1045 admin: None,
1046 });
1047 }
1048 Ok(Plan { repo, base, items })
1049}
1050
1051fn head_branch(dir: &Path) -> Option<String> {
1053 run(dir, &["symbolic-ref", "-q", "HEAD"])
1054 .ok()
1055 .and_then(|h| h.strip_prefix("refs/heads/").map(String::from))
1056}
1057
1058fn base_of(repo: &Path) -> Option<String> {
1060 base(repo, None).ok().and_then(|b| b.local)
1061}
1062
1063fn unchanged(item: &Item, path: &Path) -> bool {
1065 if !path.exists() {
1066 return true;
1067 }
1068 let head = run(path, &["rev-parse", "HEAD"]).unwrap_or_default();
1069 head == item.oid && head_branch(path) == item.branch && changes(path) == item.changes
1070}
1071
1072const BACKUP: &str = "refs/git-cow/deleted";
1074
1075fn ref_part(name: &str) -> String {
1077 let clean: String = name
1078 .chars()
1079 .map(|c| {
1080 if c.is_ascii_alphanumeric() || "-_".contains(c) {
1081 c
1082 } else {
1083 '-'
1084 }
1085 })
1086 .collect();
1087 if clean.is_empty() {
1088 "worktree".into()
1089 } else {
1090 clean
1091 }
1092}
1093
1094fn back_up_reflog(repo: &Path, admin: &Path, name: &str, stamp: &str) -> io::Result<()> {
1096 let admin = admin.to_string_lossy();
1097 let Ok(log) = run(
1098 repo,
1099 &["--git-dir", &admin, "reflog", "show", "--format=%H", "HEAD"],
1100 ) else {
1101 return Ok(());
1102 };
1103 let oids: HashSet<&str> = log.lines().filter(|l| !l.is_empty()).collect();
1104 if oids.is_empty() {
1105 return Ok(());
1106 }
1107 let mut args = vec!["rev-list"];
1108 args.extend(oids.iter());
1109 args.extend(["--not", "--branches", "--tags", "--remotes"]);
1110 let unreachable = run(repo, &args)?;
1111 let lost = unreachable.lines().filter(|o| oids.contains(o));
1112 for (i, oid) in lost.enumerate() {
1113 let backup = format!("{BACKUP}/{stamp}/worktree/{}/{i}", ref_part(name));
1114 run(repo, &["update-ref", &backup, oid, ""])?;
1116 }
1117 Ok(())
1118}
1119
1120fn delete_branch(repo: &Path, b: &str, oid: &str, stamp: &str) -> io::Result<String> {
1123 let (main, linked) = worktrees(repo)?;
1124 if std::iter::once(&main)
1125 .chain(&linked)
1126 .any(|w| w.branch.as_deref() == Some(b))
1127 {
1128 return Err(err(format!("{b} is checked out in a worktree")));
1129 }
1130 if busy_branches(repo).contains(b) {
1131 return Err(err(format!("a rebase or bisect works on {b}")));
1132 }
1133 let backup = format!("{BACKUP}/{stamp}/branch/{b}");
1134 run(repo, &["update-ref", &backup, oid, ""])?;
1135 run(
1136 repo,
1137 &[
1138 "update-ref",
1139 "--no-deref",
1140 "-d",
1141 &format!("refs/heads/{b}"),
1142 oid,
1143 ],
1144 )?;
1145 let _ = run(
1147 repo,
1148 &["config", "--remove-section", &format!("branch.{b}")],
1149 );
1150 Ok(backup)
1151}
1152
1153#[derive(Debug)]
1155#[non_exhaustive]
1156pub enum Done {
1157 Removed(PathBuf),
1159 Deleted {
1161 branch: String,
1163 oid: String,
1165 backup: String,
1167 },
1168 Failed {
1170 what: String,
1172 why: String,
1174 },
1175}
1176
1177pub fn execute(plan: &Plan) -> Vec<Done> {
1183 static CALLS: AtomicUsize = AtomicUsize::new(0);
1184 let repo = &plan.repo;
1185 let secs = SystemTime::now()
1186 .duration_since(UNIX_EPOCH)
1187 .map_or(0, |d| d.as_secs());
1188 let call = CALLS.fetch_add(1, Ordering::Relaxed);
1189 let stamp = format!("{secs}-{}-{call}", std::process::id());
1190 let mut done = Vec::new();
1191 for (n, item) in plan
1192 .items
1193 .iter()
1194 .filter(|i| matches!(i.action, Action::Remove))
1195 .enumerate()
1196 {
1197 if let Some(path) = &item.path {
1198 let p = path.to_string_lossy().into_owned();
1199 let failed = |why: String| Done::Failed {
1200 what: p.clone(),
1201 why,
1202 };
1203 if !unchanged(item, path) {
1204 done.push(failed("it changed since the plan".into()));
1205 continue;
1206 }
1207 let leaf = path.file_name().unwrap_or_default().to_string_lossy();
1208 let name = format!("{n}-{leaf}");
1209 if let Some(admin) = &item.admin
1210 && let Err(e) = back_up_reflog(repo, admin, &name, &stamp)
1211 {
1212 done.push(failed(format!("its reflog could not be backed up: {e}")));
1213 continue;
1214 }
1215 let mut cmd = vec!["worktree", "remove"];
1216 if item.forced == Force::Yes {
1217 cmd.push("--force");
1218 }
1219 cmd.push(&p);
1220 if let Err(e) = run(repo, &cmd) {
1221 done.push(failed(e.to_string()));
1222 continue;
1223 }
1224 done.push(Done::Removed(path.clone()));
1225 }
1226 if let (Some(b), true) = (&item.branch, item.branch_too) {
1227 done.push(match delete_branch(repo, b, &item.oid, &stamp) {
1228 Ok(backup) => Done::Deleted {
1229 branch: b.clone(),
1230 oid: item.oid.clone(),
1231 backup,
1232 },
1233 Err(e) => Done::Failed {
1234 what: format!("branch {b}"),
1235 why: e.to_string(),
1236 },
1237 });
1238 }
1239 }
1240 done
1241}
1242
1243pub fn squash_check_works() -> bool {
1246 git_cmd(&std::env::temp_dir())
1247 .args([NO_ATTRIBUTES, "patch-id", "--verbatim"])
1248 .stdin(Stdio::null())
1249 .stdout(Stdio::null())
1250 .stderr(Stdio::null())
1251 .status()
1252 .is_ok_and(|s| s.success())
1253}
1254
1255#[derive(Debug)]
1257pub struct Surveyed {
1258 pub path: PathBuf,
1260 pub branch: Option<String>,
1262 pub state: Option<State>,
1264}
1265
1266pub fn survey(dir: &Path) -> io::Result<Vec<Surveyed>> {
1276 let (main, linked) = worktrees(dir)?;
1277 let linked: Vec<Worktree> = linked
1278 .into_iter()
1279 .filter(|w| !is_extra_checkout(&main.path, &w.path))
1280 .collect();
1281 let revs: Vec<(String, Option<String>)> = linked.iter().map(rev_of).collect();
1282 let states: Vec<Option<State>> = base(&main.path, None).map_or_else(
1283 |_| vec![None; linked.len()],
1284 |b| {
1285 states(&main.path, &b, &revs)
1286 .into_iter()
1287 .map(Some)
1288 .collect()
1289 },
1290 );
1291 Ok(linked
1292 .into_iter()
1293 .zip(states)
1294 .map(|(w, state)| Surveyed {
1295 path: w.path,
1296 branch: w.branch,
1297 state,
1298 })
1299 .collect())
1300}
1301
1302pub fn is_extra_checkout(repo: &Path, path: &Path) -> bool {
1308 let real = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
1309 let locked = path.file_name().is_some_and(|n| {
1310 path.with_file_name(format!(".{}.lock", n.to_string_lossy()))
1311 .exists()
1312 });
1313 path.components().any(|c| c.as_os_str() == ".git-cow")
1314 || locked
1315 || config_path(repo, "cow.base")
1316 .or_else(|| config_path(repo, "cow.template"))
1317 .is_some_and(|t| real(&t) == real(path))
1318}