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