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};
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
15// Ahead of every git call here: no fsmonitor or gpg program from a repository's own config, and
16// no index refresh written back. `git status` can still run a clean filter, so only cleanup does
17const QUIET: &[&str] = &[
18    "-c",
19    "core.fsmonitor=false",
20    "-c",
21    "log.showSignature=false",
22    "--no-optional-locks",
23];
24
25// Files a rebase, merge, bisect, cherry-pick or revert in progress leaves in a worktree's gitdir
26const 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
36// Reads attributes from the empty tree, so no merge driver or filter a repository names runs
37const NO_ATTRIBUTES: &str = "--attr-source=4b825dc642cb6eb9a060e54bf8d69288fbee4904";
38
39// Diffs compared byte for byte, without a diff program or textconv filter a repository may set
40const 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    // a partial clone would fetch a missing blob, through ssh or a credential helper
58    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
74// `git patch-id --verbatim` of what `args` prints, fed through a pipe so no byte is changed.
75// Whitespace counts, so a later fix to indentation is never taken for the squash that landed
76fn 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/// How far a worktree's or branch's work landed in the base
112#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113#[non_exhaustive]
114pub enum State {
115    /// An ancestor of the base
116    Merged,
117    /// Squash-merged: one base commit made the whole change and nothing reverted it
118    Squashed,
119    /// Not in the base, and its upstream branch is gone
120    Gone,
121    /// Not in the base
122    Active,
123}
124
125impl State {
126    /// The word the plan prints
127    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    /// Merged or squashed, so the work is in the base
137    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
149// The main worktree, or the bare repository, and every linked worktree after it. Read with -z, so
150// a path holding a newline stays one path
151fn 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/// The branch a plan compares with
190#[derive(Debug)]
191pub struct Base {
192    /// The name it resolved to, such as `origin/main`
193    pub name: String,
194    /// Its commit when the plan was made
195    pub oid: String,
196    // the local branch the base stands for, which cleanup never deletes
197    local: Option<String>,
198}
199
200// The branch work lands on: the one named, or the remote's default, or a local main. A remote's
201// HEAD is followed to the branch it names, and the plan prints that name
202fn 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
245// The branch in `<remote>/<branch>`, taking the longest remote name that fits, since a remote name
246// may hold a slash
247fn 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
261// In a partial clone reading a branch's blobs would fetch them, so only ancestry counts there
262fn 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    // patch ids of what the rev changed since the merge base, and of undoing it
270    own: String,
271    undo: String,
272    // base commits after the merge base, children before parents
273    commits: String,
274    mb: String,
275}
276
277// None for an ancestor of the base, or a rev that changes nothing in total
278fn 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
311// A new empty folder in the repository's git dir, which only its owner can write. A folder that
312// already exists is never reused, since git would read objects planted in it before the real ones
313fn 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
330// The tree of a three way merge, written to a throwaway object folder over the repository's so the
331// repository gets no new objects. None on a conflict
332fn 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    // --attr-source covers only the tree, info/attributes would still name a merge driver
339    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
375// Replaying the rev's change onto `c`'s parent gives exactly `c`, so `c` is its squash and not the
376// same patch made somewhere else in a file
377fn 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
382// A base commit after the squash `c` reverts it: git revert names it, or the patch undoes the rev.
383// An undo hidden in other work goes unseen, but the work stays in `c` in the base's history
384fn 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
409// One base commit after the merge base is the rev's squash, replayed exactly, and no later base
410// commit reverts it
411fn 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
426// Patch ids of `commits`, all in one `git log`. An empty commit has none, so it matches nothing
427fn 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
455// Merged is an ancestor of the base. Squashed is git-extras' check with whitespace counted, made
456// sure by replaying the squash, and not reverted since
457fn 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
503// Edits, staged changes and every untracked file, whatever status.showUntrackedFiles says, and
504// files marked assume-unchanged or skip-worktree, whose edits git status hides. Empty when clean
505fn 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
531// A folder, or any folder below it, that is a repository of its own. Symlinks are not followed,
532// since removing the worktree removes only the link
533fn 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
552// An untracked or ignored folder holding a repository, whose history a remove takes with it
553fn 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    // a status that fails hides what is inside, so it counts as holding one
568    !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
576// Each linked worktree's admin folder in the common git dir, keyed by the worktree path its
577// `gitdir` file names
578fn 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
598// What a worktree holds that git keeps nowhere else: submodules and other repositories inside it,
599// refs of its own, a rebase, merge or bisect. Read from its admin folder, so a missing folder too
600fn 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
633// Claude Code removes its own worktrees, and a session may still run in one
634fn 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
644// Branches a rebase or bisect in any worktree works on, which git lists as detached
645fn 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/// What [`execute`] does with an item
682#[derive(Clone, Copy, Debug, PartialEq, Eq)]
683#[non_exhaustive]
684pub enum Action {
685    /// Remove the worktree, or delete the branch with no worktree
686    Remove,
687    /// Leave it, for this reason
688    Keep(Keep),
689}
690
691/// Why a plan keeps a worktree or branch
692#[derive(Clone, Copy, Debug, PartialEq, Eq)]
693#[non_exhaustive]
694pub enum Keep {
695    /// Its work is not in the base
696    NotLanded,
697    /// `git worktree lock` holds it
698    Locked,
699    /// The `dir` the plan was made from is inside it
700    Inside,
701    /// Claude Code removes its own worktrees, and a session may still run in one
702    ClaudeCode,
703    /// It is on the base branch, the default branch, the main checkout's branch, or a branch a
704    /// rebase or bisect works on
705    BaseBranch,
706    /// Its folder is gone, kept unless [`Options::force`]
707    FolderMissing,
708    /// It holds submodules
709    Submodules,
710    /// It holds another repository in an untracked or ignored folder
711    Repository,
712    /// A rebase, merge, bisect, cherry-pick or revert is in progress in it
713    Busy,
714    /// It has refs of its own under `refs/worktree/` or `refs/bisect/`
715    OwnRefs,
716    /// git cannot read its state
717    Unreadable,
718    /// It has edits or untracked files, kept unless [`Options::force`]
719    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/// What to compare with, and whether to remove worktrees with changes or a missing folder too
748#[derive(Clone, Debug, Default)]
749pub struct Options {
750    /// The branch work lands on, or the remote's default branch, then a local main or master
751    pub base: Option<String>,
752    /// Also remove landed worktrees with changes or a missing folder. Never a worktree holding
753    /// a repository, submodules, refs of its own or a rebase
754    pub force: bool,
755}
756
757/**
758 * One worktree, or a local branch with no worktree, and what the plan does with it. Only [`plan`]
759 * and [`plan_worktree`] make one, and a caller can read but never change it, so [`execute`] only
760 * ever removes what the plan judged safe:
761 *
762 * ```compile_fail
763 * # use git_cow::cleanup::{self, Action, Options};
764 * # let plan = cleanup::plan(std::path::Path::new("."), &Options::default()).unwrap();
765 * plan.items()[0].action = Action::Remove;
766 * ```
767 **/
768#[derive(Debug)]
769pub struct Item {
770    path: Option<PathBuf>,
771    branch: Option<String>,
772    state: State,
773    action: Action,
774    // the commit and the changes the plan judged, so the run skips anything that moved since
775    oid: String,
776    changes: String,
777    // whether removing this worktree also deletes its branch
778    branch_too: bool,
779    forced: Force,
780    // the worktree's admin folder, whose HEAD reflog may hold commits no ref has
781    admin: Option<PathBuf>,
782}
783
784impl Item {
785    /// The worktree, or None for a branch with no worktree
786    pub fn path(&self) -> Option<&Path> {
787        self.path.as_deref()
788    }
789
790    /// Its branch, or None for a detached worktree
791    pub fn branch(&self) -> Option<&str> {
792        self.branch.as_deref()
793    }
794
795    /// How far its work landed
796    pub fn state(&self) -> State {
797        self.state
798    }
799
800    /// What [`execute`] does with it
801    pub fn action(&self) -> Action {
802        self.action
803    }
804
805    /// The commit the plan judged
806    pub fn oid(&self) -> &str {
807        &self.oid
808    }
809
810    /// Whether removing it also deletes its branch, which it does only when every worktree on
811    /// that branch goes
812    pub fn deletes_branch(&self) -> bool {
813        self.branch_too
814    }
815
816    /// Whether removing it drops edits or untracked files, which only [`Options::force`] allows
817    pub fn discards_changes(&self) -> bool {
818        !self.changes.is_empty()
819    }
820}
821
822/// Every worktree and local branch [`plan`] judged
823#[derive(Debug)]
824pub struct Plan {
825    repo: PathBuf,
826    base: Base,
827    items: Vec<Item>,
828}
829
830impl Plan {
831    /// The main worktree or bare repository every git call runs in
832    pub fn repo(&self) -> &Path {
833        &self.repo
834    }
835
836    /// What the plan compared with
837    pub fn base(&self) -> &Base {
838        &self.base
839    }
840
841    /// One per worktree, then one per local branch with no worktree
842    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    // A branch goes with the last of its worktrees, and only when every one of them goes
906    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
924/**
925 * Judge every worktree of the repository at `dir`, and every local branch with no worktree,
926 * against the base. It changes nothing
927 *
928 * # Errors
929 *
930 * When `dir` is not in a repository, no base branch resolves, or git cannot list the branches
931 **/
932pub fn plan(dir: &Path, opts: &Options) -> io::Result<Plan> {
933    judge(dir, opts, None)
934}
935
936/**
937 * Judge only the worktree at `wt`, as a tool does with a worktree it made once its work landed.
938 * The plan has that one item, and deletes its branch only if no other worktree has it
939 *
940 * # Errors
941 *
942 * When `wt` is not a worktree of the repository at `dir`, or is an extra checkout, or as [`plan`]
943 **/
944pub 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    // every call runs from the main worktree, so removing the one you stand in breaks nothing
957    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    // Local branches with no worktree, never one checked out anywhere, an extra checkout too
968    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        // the others on its branch decide whether its branch may go
984        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    // a symbolic ref such as master pointing at main is an alias, deleting it would delete main
998    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
1045// The branch HEAD names in `dir`, from the full ref so a tag with the same name cannot shorten it
1046fn 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
1052// The local default branch, kept even when cleanup compares with another one
1053fn base_of(repo: &Path) -> Option<String> {
1054    base(repo, None).ok().and_then(|b| b.local)
1055}
1056
1057// Whether a worktree is still as the plan saw it: same commit, same branch, same changes
1058fn 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
1066// Where cleanup keeps every commit it lets go of, one folder per run, so gc never prunes them
1067const BACKUP: &str = "refs/git-cow/deleted";
1068
1069// A worktree folder name as a ref name part
1070fn 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
1088// Commits only the worktree's HEAD reflog holds, saved before git deletes that reflog with it
1089fn 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        // an empty old value makes update-ref refuse a ref that exists
1109        run(repo, &["update-ref", &backup, oid, ""])?;
1110    }
1111    Ok(())
1112}
1113
1114// Delete the local `b` only if it still points at `oid` and no worktree has it checked out now,
1115// after saving it under the backup refs. Only refs/heads changes, a remote is never touched
1116fn 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    // git branch -D drops these too
1140    let _ = run(
1141        repo,
1142        &["config", "--remove-section", &format!("branch.{b}")],
1143    );
1144    Ok(backup)
1145}
1146
1147/// What [`execute`] did
1148#[derive(Debug)]
1149#[non_exhaustive]
1150pub enum Done {
1151    /// Removed this worktree
1152    Removed(PathBuf),
1153    /// Deleted this local branch, after saving it as `backup`
1154    Deleted {
1155        /// The branch
1156        branch: String,
1157        /// The commit it pointed at
1158        oid: String,
1159        /// The ref that keeps it, `git branch <branch> <backup>` restores it
1160        backup: String,
1161    },
1162    /// Left this worktree or branch, for this reason
1163    Failed {
1164        /// The worktree path or branch name
1165        what: String,
1166        /// Why
1167        why: String,
1168    },
1169}
1170
1171/**
1172 * Remove every worktree and delete every branch the plan marks [`Action::Remove`]. Each commit
1173 * it lets go of is saved under `refs/git-cow/deleted/<seconds>-<pid>-<call>/` first, and an item that moved since
1174 * the plan stays
1175 **/
1176pub 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
1237/// Whether this git can tell a squash merge: it needs `patch-id --verbatim` and `--attr-source`,
1238/// both in git 2.40. Without them squash-merged branches show as active and stay
1239pub 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/// A linked worktree and how far its work landed, None when no base branch resolves
1250#[derive(Debug)]
1251pub struct Surveyed {
1252    /// The worktree
1253    pub path: PathBuf,
1254    /// Its branch, or None when detached
1255    pub branch: Option<String>,
1256    /// How far its work landed
1257    pub state: Option<State>,
1258}
1259
1260/**
1261 * Every linked worktree of the repository at `dir` but the extra checkouts, with how far its work
1262 * landed. It reads only commits and refs, never a worktree's files, so no filter or hook a
1263 * repository sets can run, which makes it fit for repositories you did not make
1264 *
1265 * # Errors
1266 *
1267 * When `dir` is not in a repository
1268 **/
1269pub 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
1296/**
1297 * Whether `path` is a git-cow extra checkout of the repository at `repo`: under a `.git-cow`
1298 * folder, at `cow.base`, or with the lock file git-cow keeps beside each one. git lists real
1299 * paths while `cow.base` may go through a symlink, so both sides are resolved
1300 **/
1301pub 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}