Skip to main content

git_cow/
cleanup.rs

1//! Worktrees and local branches whose work already landed in a base branch, and their removal.
2//! [`plan`] judges every worktree and branch, [`execute`] removes what the plan marks, and saves
3//! each commit it lets go of under `refs/git-cow/deleted/` first
4
5use 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
16// Ahead of every git call here: no fsmonitor or gpg program from a repository's own config, and
17// no index refresh written back. `git status` can still run a clean filter, so only cleanup does
18const QUIET: &[&str] = &[
19    "-c",
20    "core.fsmonitor=false",
21    "-c",
22    "log.showSignature=false",
23    "--no-optional-locks",
24];
25
26// Files a rebase, merge, bisect, cherry-pick or revert in progress leaves in a worktree's gitdir
27const 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
37// Reads attributes from the empty tree, so no merge driver or filter a repository names runs
38const NO_ATTRIBUTES: &str = "--attr-source=4b825dc642cb6eb9a060e54bf8d69288fbee4904";
39
40// Diffs compared byte for byte, without a diff program or textconv filter a repository may set
41const 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    // a partial clone would fetch a missing blob, through ssh or a credential helper
59    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
75// `git patch-id --verbatim` of what `args` prints, fed through a pipe so no byte is changed.
76// Whitespace counts, so a later fix to indentation is never taken for the squash that landed
77fn 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/// How far a worktree's or branch's work landed in the base
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114#[non_exhaustive]
115pub enum State {
116    /// An ancestor of the base
117    Merged,
118    /// Squash-merged: one base commit made the whole change and nothing reverted it
119    Squashed,
120    /// Not in the base, and its upstream branch is gone
121    Gone,
122    /// Not in the base
123    Active,
124}
125
126impl State {
127    /// The word the plan prints
128    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    /// Merged or squashed, so the work is in the base
138    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
150// The main worktree, or the bare repository, and every linked worktree after it. Read with -z, so
151// a path holding a newline stays one path
152fn 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/// The branch a plan compares with
191#[derive(Debug)]
192pub struct Base {
193    /// The name it resolved to, such as `origin/main`
194    pub name: String,
195    /// Its commit when the plan was made
196    pub oid: String,
197    // the local branch the base stands for, which cleanup never deletes
198    local: Option<String>,
199}
200
201// The branch work lands on: the one named, or the remote's default, or a local main. A remote's
202// HEAD is followed to the branch it names, and the plan prints that name
203fn 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
246// The branch in `<remote>/<branch>`, taking the longest remote name that fits, since a remote name
247// may hold a slash
248fn 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
262// In a partial clone reading a branch's blobs would fetch them, so only ancestry counts there
263fn 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    // patch ids of what the rev changed since the merge base, and of undoing it
271    own: String,
272    undo: String,
273    // base commits after the merge base, children before parents
274    commits: String,
275    mb: String,
276}
277
278// None for an ancestor of the base, or a rev that changes nothing in total
279fn 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
312// A new empty folder in the repository's git dir, which on Unix only its owner can write and on
313// Windows keeps the ACL it inherits. A folder that already exists is never reused, since git would
314// read objects planted in it before the real ones
315fn 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
336// The tree of a three way merge, written to a throwaway object folder over the repository's so the
337// repository gets no new objects. None on a conflict
338fn 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    // --attr-source covers only the tree, info/attributes would still name a merge driver
345    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
381// Replaying the rev's change onto `c`'s parent gives exactly `c`, so `c` is its squash and not the
382// same patch made somewhere else in a file
383fn 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
388// A base commit after the squash `c` reverts it: git revert names it, or the patch undoes the rev.
389// An undo hidden in other work goes unseen, but the work stays in `c` in the base's history
390fn 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
415// One base commit after the merge base is the rev's squash, replayed exactly, and no later base
416// commit reverts it
417fn 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
432// Patch ids of `commits`, all in one `git log`. An empty commit has none, so it matches nothing
433fn 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
461// Merged is an ancestor of the base. Squashed is git-extras' check with whitespace counted, made
462// sure by replaying the squash, and not reverted since
463fn 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
509// Edits, staged changes and every untracked file, whatever status.showUntrackedFiles says, and
510// files marked assume-unchanged or skip-worktree, whose edits git status hides. Empty when clean
511fn 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
537// A folder, or any folder below it, that is a repository of its own. Symlinks are not followed,
538// since removing the worktree removes only the link
539fn 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
558// An untracked or ignored folder holding a repository, whose history a remove takes with it
559fn 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    // a status that fails hides what is inside, so it counts as holding one
574    !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
582// Each linked worktree's admin folder in the common git dir, keyed by the worktree path its
583// `gitdir` file names
584fn 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
604// What a worktree holds that git keeps nowhere else: submodules and other repositories inside it,
605// refs of its own, a rebase, merge or bisect. Read from its admin folder, so a missing folder too
606fn 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
639// Claude Code removes its own worktrees, and a session may still run in one
640fn 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
650// Branches a rebase or bisect in any worktree works on, which git lists as detached
651fn 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/// What [`execute`] does with an item
688#[derive(Clone, Copy, Debug, PartialEq, Eq)]
689#[non_exhaustive]
690pub enum Action {
691    /// Remove the worktree, or delete the branch with no worktree
692    Remove,
693    /// Leave it, for this reason
694    Keep(Keep),
695}
696
697/// Why a plan keeps a worktree or branch
698#[derive(Clone, Copy, Debug, PartialEq, Eq)]
699#[non_exhaustive]
700pub enum Keep {
701    /// Its work is not in the base
702    NotLanded,
703    /// `git worktree lock` holds it
704    Locked,
705    /// The `dir` the plan was made from is inside it
706    Inside,
707    /// Claude Code removes its own worktrees, and a session may still run in one
708    ClaudeCode,
709    /// It is on the base branch, the default branch, the main checkout's branch, or a branch a
710    /// rebase or bisect works on
711    BaseBranch,
712    /// Its folder is gone, kept unless [`Options::force`]
713    FolderMissing,
714    /// It holds submodules
715    Submodules,
716    /// It holds another repository in an untracked or ignored folder
717    Repository,
718    /// A rebase, merge, bisect, cherry-pick or revert is in progress in it
719    Busy,
720    /// It has refs of its own under `refs/worktree/` or `refs/bisect/`
721    OwnRefs,
722    /// git cannot read its state
723    Unreadable,
724    /// It has edits or untracked files, kept unless [`Options::force`]
725    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/// What to compare with, and whether to remove worktrees with changes or a missing folder too
754#[derive(Clone, Debug, Default)]
755pub struct Options {
756    /// The branch work lands on, or the remote's default branch, then a local main or master
757    pub base: Option<String>,
758    /// Also remove landed worktrees with changes or a missing folder. Never a worktree holding
759    /// a repository, submodules, refs of its own or a rebase
760    pub force: bool,
761}
762
763/**
764 * One worktree, or a local branch with no worktree, and what the plan does with it. Only [`plan`]
765 * and [`plan_worktree`] make one, and a caller can read but never change it, so [`execute`] only
766 * ever removes what the plan judged safe:
767 *
768 * ```compile_fail
769 * # use git_cow::cleanup::{self, Action, Options};
770 * # let plan = cleanup::plan(std::path::Path::new("."), &Options::default()).unwrap();
771 * plan.items()[0].action = Action::Remove;
772 * ```
773 **/
774#[derive(Debug)]
775pub struct Item {
776    path: Option<PathBuf>,
777    branch: Option<String>,
778    state: State,
779    action: Action,
780    // the commit and the changes the plan judged, so the run skips anything that moved since
781    oid: String,
782    changes: String,
783    // whether removing this worktree also deletes its branch
784    branch_too: bool,
785    forced: Force,
786    // the worktree's admin folder, whose HEAD reflog may hold commits no ref has
787    admin: Option<PathBuf>,
788}
789
790impl Item {
791    /// The worktree, or None for a branch with no worktree
792    pub fn path(&self) -> Option<&Path> {
793        self.path.as_deref()
794    }
795
796    /// Its branch, or None for a detached worktree
797    pub fn branch(&self) -> Option<&str> {
798        self.branch.as_deref()
799    }
800
801    /// How far its work landed
802    pub fn state(&self) -> State {
803        self.state
804    }
805
806    /// What [`execute`] does with it
807    pub fn action(&self) -> Action {
808        self.action
809    }
810
811    /// The commit the plan judged
812    pub fn oid(&self) -> &str {
813        &self.oid
814    }
815
816    /// Whether removing it also deletes its branch, which it does only when every worktree on
817    /// that branch goes
818    pub fn deletes_branch(&self) -> bool {
819        self.branch_too
820    }
821
822    /// Whether removing it drops edits or untracked files, which only [`Options::force`] allows
823    pub fn discards_changes(&self) -> bool {
824        !self.changes.is_empty()
825    }
826}
827
828/// Every worktree and local branch [`plan`] judged
829#[derive(Debug)]
830pub struct Plan {
831    repo: PathBuf,
832    base: Base,
833    items: Vec<Item>,
834}
835
836impl Plan {
837    /// The main worktree or bare repository every git call runs in
838    pub fn repo(&self) -> &Path {
839        &self.repo
840    }
841
842    /// What the plan compared with
843    pub fn base(&self) -> &Base {
844        &self.base
845    }
846
847    /// One per worktree, then one per local branch with no worktree
848    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    // A branch goes with the last of its worktrees, and only when every one of them goes
912    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
930/**
931 * Judge every worktree of the repository at `dir`, and every local branch with no worktree,
932 * against the base. It changes nothing
933 *
934 * # Errors
935 *
936 * When `dir` is not in a repository, no base branch resolves, or git cannot list the branches
937 **/
938pub fn plan(dir: &Path, opts: &Options) -> io::Result<Plan> {
939    judge(dir, opts, None)
940}
941
942/**
943 * Judge only the worktree at `wt`, as a tool does with a worktree it made once its work landed.
944 * The plan has that one item, and deletes its branch only if no other worktree has it
945 *
946 * # Errors
947 *
948 * When `wt` is not a worktree of the repository at `dir`, or is an extra checkout, or as [`plan`]
949 **/
950pub 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    // every call runs from the main worktree, so removing the one you stand in breaks nothing
963    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    // Local branches with no worktree, never one checked out anywhere, an extra checkout too
974    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        // the others on its branch decide whether its branch may go
990        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    // a symbolic ref such as master pointing at main is an alias, deleting it would delete main
1004    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
1051// The branch HEAD names in `dir`, from the full ref so a tag with the same name cannot shorten it
1052fn 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
1058// The local default branch, kept even when cleanup compares with another one
1059fn base_of(repo: &Path) -> Option<String> {
1060    base(repo, None).ok().and_then(|b| b.local)
1061}
1062
1063// Whether a worktree is still as the plan saw it: same commit, same branch, same changes
1064fn 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
1072// Where cleanup keeps every commit it lets go of, one folder per run, so gc never prunes them
1073const BACKUP: &str = "refs/git-cow/deleted";
1074
1075// A worktree folder name as a ref name part
1076fn 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
1094// Commits only the worktree's HEAD reflog holds, saved before git deletes that reflog with it
1095fn 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        // an empty old value makes update-ref refuse a ref that exists
1115        run(repo, &["update-ref", &backup, oid, ""])?;
1116    }
1117    Ok(())
1118}
1119
1120// Delete the local `b` only if it still points at `oid` and no worktree has it checked out now,
1121// after saving it under the backup refs. Only refs/heads changes, a remote is never touched
1122fn 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    // git branch -D drops these too
1146    let _ = run(
1147        repo,
1148        &["config", "--remove-section", &format!("branch.{b}")],
1149    );
1150    Ok(backup)
1151}
1152
1153/// What [`execute`] did
1154#[derive(Debug)]
1155#[non_exhaustive]
1156pub enum Done {
1157    /// Removed this worktree
1158    Removed(PathBuf),
1159    /// Deleted this local branch, after saving it as `backup`
1160    Deleted {
1161        /// The branch
1162        branch: String,
1163        /// The commit it pointed at
1164        oid: String,
1165        /// The ref that keeps it, `git branch <branch> <backup>` restores it
1166        backup: String,
1167    },
1168    /// Left this worktree or branch, for this reason
1169    Failed {
1170        /// The worktree path or branch name
1171        what: String,
1172        /// Why
1173        why: String,
1174    },
1175}
1176
1177/**
1178 * Remove every worktree and delete every branch the plan marks [`Action::Remove`]. Each commit
1179 * it lets go of is saved under `refs/git-cow/deleted/<seconds>-<pid>-<call>/` first, and an item that moved since
1180 * the plan stays
1181 **/
1182pub 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
1243/// Whether this git can tell a squash merge: it needs `patch-id --verbatim` and `--attr-source`,
1244/// both in git 2.40. Without them squash-merged branches show as active and stay
1245pub 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/// A linked worktree and how far its work landed, None when no base branch resolves
1256#[derive(Debug)]
1257pub struct Surveyed {
1258    /// The worktree
1259    pub path: PathBuf,
1260    /// Its branch, or None when detached
1261    pub branch: Option<String>,
1262    /// How far its work landed
1263    pub state: Option<State>,
1264}
1265
1266/**
1267 * Every linked worktree of the repository at `dir` but the extra checkouts, with how far its work
1268 * landed. It reads only commits and refs, never a worktree's files, so no filter or hook a
1269 * repository sets can run, which makes it fit for repositories you did not make
1270 *
1271 * # Errors
1272 *
1273 * When `dir` is not in a repository
1274 **/
1275pub 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
1302/**
1303 * Whether `path` is a git-cow extra checkout of the repository at `repo`: under a `.git-cow`
1304 * folder, at `cow.base`, or with the lock file git-cow keeps beside each one. git lists real
1305 * paths while `cow.base` may go through a symlink, so both sides are resolved
1306 **/
1307pub 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}