git-janitor 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,382 @@
1
+ from datetime import UTC, datetime, timedelta
2
+ from pathlib import Path
3
+
4
+ from git_janitor import git
5
+ from git_janitor.github import GitHubClient
6
+ from git_janitor.model import (
7
+ Action,
8
+ Blocker,
9
+ Branch,
10
+ Candidate,
11
+ DeleteBranch,
12
+ DirtyBlocker,
13
+ ErrorBlocker,
14
+ Evidence,
15
+ ExtraCommits,
16
+ InProgressOpBlocker,
17
+ IsCurrentBlocker,
18
+ IsMainBlocker,
19
+ LockedBlocker,
20
+ NestedRepositoryBlocker,
21
+ PreciousFilesBlocker,
22
+ PullRequest,
23
+ PullRequestEvidence,
24
+ PullRequestState,
25
+ RecentActivityBlocker,
26
+ RemoveWorktree,
27
+ Report,
28
+ SameTree,
29
+ Status,
30
+ SubmodulesBlocker,
31
+ UnreadableBlocker,
32
+ UntrackedBlocker,
33
+ Worktree,
34
+ parse_duration,
35
+ )
36
+ from git_janitor.precious import scan_ignored
37
+
38
+ REMOTE = "origin"
39
+ MIN_AGE_CONFIG_KEY = "janitor.minAge"
40
+ DEFAULT_MIN_AGE = timedelta(days=7)
41
+ SAME_TREE_REPLACES = frozenset(
42
+ {
43
+ Status.PR_CLOSED,
44
+ Status.MERGED_INTO_OTHER_BASE,
45
+ Status.MERGED_PLUS_LOCAL,
46
+ Status.NO_PR,
47
+ }
48
+ )
49
+ """Statuses that a same-tree match replaces with `merged_same_tree`."""
50
+
51
+
52
+ def analyze(
53
+ repo: Path,
54
+ github: GitHubClient,
55
+ *,
56
+ fetch: bool = True,
57
+ cwd: Path | None = None,
58
+ now: datetime | None = None,
59
+ ) -> Report:
60
+ """Analyze the local branches and worktrees of `repo`.
61
+
62
+ `cwd` is the caller's current directory, used to detect worktrees that are in use. `now` is
63
+ the time that activity ages are measured against.
64
+ """
65
+ cwd = (cwd or Path.cwd()).resolve()
66
+ now = now or datetime.now(UTC)
67
+ min_age = _min_age(repo)
68
+ if fetch:
69
+ git.fetch(REMOTE, cwd=repo)
70
+ branches = git.list_branches(repo)
71
+ worktrees = git.list_worktrees(repo)
72
+ worktrees_by_branch: dict[str, Worktree] = {}
73
+ for worktree in worktrees:
74
+ if worktree.branch:
75
+ worktrees_by_branch.setdefault(worktree.branch, worktree)
76
+ head_names = sorted({name for branch in branches for name in _head_names(branch)})
77
+ detached_heads = sorted(
78
+ {wt.head for wt in worktrees if wt.branch is None and not wt.is_main and wt.head}
79
+ )
80
+ data = github.fetch(git.remote_url(REMOTE, cwd=repo), head_names, detached_heads)
81
+ default_branch = data.default_branch
82
+ default_ref = f"refs/remotes/{REMOTE}/{default_branch}"
83
+ if not git.ref_exists(default_ref, cwd=repo):
84
+ raise git.GitError(
85
+ f"{default_ref} doesn't exist. git-janitor needs {REMOTE}'s default branch "
86
+ f"({default_branch}) to be fetched."
87
+ )
88
+
89
+ candidates = []
90
+ for branch in branches:
91
+ if branch.name == default_branch:
92
+ status, evidence = Status.DEFAULT_BRANCH, ()
93
+ else:
94
+ prs = [
95
+ pr
96
+ for name in _head_names(branch) - {default_branch}
97
+ for pr in data.pull_requests.get(name, [])
98
+ ]
99
+ status, evidence = _classify_tip(branch.tip, prs, default_ref, default_branch, repo)
100
+ worktree = worktrees_by_branch.get(branch.name)
101
+ blockers = _branch_blockers(status, worktree, cwd)
102
+ linked = worktree if worktree and not worktree.is_main else None
103
+ last_activity = _latest(
104
+ git.reflog_time(f"refs/heads/{branch.name}", cwd=repo),
105
+ git.worktree_activity(linked, repo) if linked else None,
106
+ )
107
+ if linked:
108
+ blockers = (
109
+ *blockers,
110
+ *_recent_activity(status, last_activity, now, min_age),
111
+ )
112
+ candidates.append(
113
+ Candidate(
114
+ id=branch.name,
115
+ status=status,
116
+ branch=branch,
117
+ worktree=worktree,
118
+ blockers=blockers,
119
+ evidence=evidence,
120
+ actions=_branch_actions(branch, status, worktree),
121
+ last_activity=last_activity,
122
+ )
123
+ )
124
+
125
+ branch_names = {branch.name for branch in branches}
126
+ for worktree in worktrees:
127
+ if worktree.is_main or worktree.branch in branch_names:
128
+ continue
129
+ if worktree.branch is None:
130
+ prs = data.pull_requests_by_commit.get(worktree.head, [])
131
+ status, evidence = _classify_tip(worktree.head, prs, default_ref, default_branch, repo)
132
+ else:
133
+ status, evidence = Status.BRANCH_MISSING, ()
134
+ last_activity = git.worktree_activity(worktree, repo)
135
+ candidates.append(
136
+ Candidate(
137
+ id=str(worktree.path),
138
+ status=status,
139
+ branch=None,
140
+ worktree=worktree,
141
+ blockers=(
142
+ *worktree_blockers(worktree, cwd),
143
+ *_recent_activity(status, last_activity, now, min_age),
144
+ ),
145
+ evidence=evidence,
146
+ actions=(RemoveWorktree(path=worktree.path),),
147
+ last_activity=last_activity,
148
+ )
149
+ )
150
+
151
+ return Report(
152
+ repo=next(wt.path for wt in worktrees if wt.is_main),
153
+ github_repo=data.name_with_owner,
154
+ default_branch=default_branch,
155
+ fetched=fetch,
156
+ candidates=tuple(candidates),
157
+ )
158
+
159
+
160
+ def _min_age(repo: Path) -> timedelta:
161
+ values = git.config_get_all(MIN_AGE_CONFIG_KEY, repo)
162
+ if not values:
163
+ return DEFAULT_MIN_AGE
164
+ try:
165
+ return parse_duration(values[-1])
166
+ except ValueError as exc:
167
+ raise ValueError(f"{MIN_AGE_CONFIG_KEY}: {exc}") from exc
168
+
169
+
170
+ def _latest(*times: datetime | None) -> datetime | None:
171
+ return max((t for t in times if t is not None), default=None)
172
+
173
+
174
+ def _recent_activity(
175
+ status: Status,
176
+ last_activity: datetime | None,
177
+ now: datetime,
178
+ min_age: timedelta,
179
+ ) -> tuple[Blocker, ...]:
180
+ """Protects linked worktrees with no commits of their own that may be in use, such as one
181
+ an agent has just created.
182
+ """
183
+ if status is not Status.NO_UNIQUE_COMMITS:
184
+ return ()
185
+ if last_activity is not None and now - last_activity >= min_age:
186
+ return ()
187
+ return (RecentActivityBlocker(min_age=min_age),)
188
+
189
+
190
+ def _branch_actions(
191
+ branch: Branch, status: Status, worktree: Worktree | None
192
+ ) -> tuple[Action, ...]:
193
+ if status is Status.DEFAULT_BRANCH:
194
+ return ()
195
+ actions: list[Action] = []
196
+ if worktree and not worktree.is_main:
197
+ actions.append(RemoveWorktree(path=worktree.path))
198
+ actions.append(DeleteBranch(name=branch.name, tip=branch.tip))
199
+ return tuple(actions)
200
+
201
+
202
+ def _branch_blockers(status: Status, worktree: Worktree | None, cwd: Path) -> tuple[Blocker, ...]:
203
+ if worktree is None or status is Status.DEFAULT_BRANCH:
204
+ return ()
205
+ if worktree.is_main:
206
+ return (IsMainBlocker(),)
207
+ return worktree_blockers(worktree, cwd)
208
+
209
+
210
+ def worktree_blockers(worktree: Worktree, cwd: Path) -> tuple[Blocker, ...]:
211
+ """Blockers for removing a linked worktree.
212
+
213
+ A failure while checking becomes an error blocker rather than stopping the analysis.
214
+ """
215
+ try:
216
+ return _worktree_blockers(worktree, cwd)
217
+ except (git.GitError, OSError, ValueError) as exc:
218
+ return (ErrorBlocker(detail=str(exc)),)
219
+
220
+
221
+ def _worktree_blockers(worktree: Worktree, cwd: Path) -> tuple[Blocker, ...]:
222
+ if not worktree.path.exists():
223
+ missing: list[Blocker] = [LockedBlocker()] if worktree.locked else []
224
+ if git.has_submodule_git_dirs(worktree):
225
+ missing.append(SubmodulesBlocker(paths=()))
226
+ return tuple(missing)
227
+ blockers: list[Blocker] = []
228
+ if cwd.is_relative_to(worktree.path.resolve()):
229
+ blockers.append(IsCurrentBlocker())
230
+ if worktree.locked:
231
+ blockers.append(LockedBlocker())
232
+ for operation in git.operations_in_progress(worktree.path):
233
+ blockers.append(InProgressOpBlocker(operation=operation))
234
+ status = git.worktree_status(worktree.path)
235
+ changed = tuple(sorted({*status.changed, *git.skipped_changes(worktree.path)}))
236
+ if changed:
237
+ blockers.append(DirtyBlocker(paths=changed))
238
+ if status.untracked:
239
+ blockers.append(UntrackedBlocker(paths=status.untracked))
240
+ submodules = git.populated_submodules(worktree.path)
241
+ if submodules or git.has_submodule_git_dirs(worktree):
242
+ blockers.append(SubmodulesBlocker(paths=tuple(submodules)))
243
+ scan = scan_ignored(worktree.path, status.ignored)
244
+ if scan.nested_repositories:
245
+ blockers.append(NestedRepositoryBlocker(paths=scan.nested_repositories))
246
+ if scan.precious:
247
+ blockers.append(PreciousFilesBlocker(entries=scan.precious))
248
+ if scan.unreadable:
249
+ blockers.append(UnreadableBlocker(paths=scan.unreadable))
250
+ return tuple(blockers)
251
+
252
+
253
+ def _head_names(branch: Branch) -> set[str]:
254
+ """Names a pull request's head branch could have: the local name and the upstream's name."""
255
+ names = {branch.name}
256
+ if branch.upstream_remote == REMOTE and branch.upstream_branch:
257
+ names.add(branch.upstream_branch)
258
+ return names
259
+
260
+
261
+ def _classify_tip(
262
+ tip: str,
263
+ prs: list[PullRequest],
264
+ default_ref: str,
265
+ default_branch: str,
266
+ repo: Path,
267
+ ) -> tuple[Status, tuple[Evidence, ...]]:
268
+ """Classify a branch tip or detached HEAD against the pull requests that might contain it."""
269
+ status, evidence = _classify_by_head(tip, prs, default_ref, default_branch, repo)
270
+ if status in SAME_TREE_REPLACES:
271
+ same_tree = _same_tree(tip, prs, default_ref, repo)
272
+ if same_tree:
273
+ pr_evidence = tuple(e for e in evidence if isinstance(e, PullRequestEvidence))
274
+ return Status.MERGED_SAME_TREE, (*pr_evidence, same_tree)
275
+ return status, evidence
276
+
277
+
278
+ def _classify_by_head(
279
+ tip: str,
280
+ prs: list[PullRequest],
281
+ default_ref: str,
282
+ default_branch: str,
283
+ repo: Path,
284
+ ) -> tuple[Status, tuple[Evidence, ...]]:
285
+ """Classify a tip by whether pull requests' heads contain it."""
286
+ in_default = git.is_ancestor(tip, default_ref, cwd=repo)
287
+ matched = {pr.number for pr in prs if _contains(pr, tip, in_default, repo)}
288
+ pr_evidence = tuple(
289
+ PullRequestEvidence(pull_request=pr, matched=pr.number in matched)
290
+ for pr in sorted(prs, key=lambda pr: pr.number, reverse=True)
291
+ )
292
+ matching = [pr for pr in prs if pr.number in matched]
293
+ if any(pr.state is PullRequestState.OPEN for pr in matching):
294
+ return Status.PR_OPEN, pr_evidence
295
+ if matching:
296
+ pr = max(matching, key=lambda pr: pr.number)
297
+ if _merged_into_default(pr, default_ref, default_branch, repo):
298
+ return Status.MERGED, pr_evidence
299
+ if pr.state is PullRequestState.MERGED:
300
+ return Status.MERGED_INTO_OTHER_BASE, pr_evidence
301
+ return Status.PR_CLOSED, pr_evidence
302
+ if in_default:
303
+ return Status.NO_UNIQUE_COMMITS, pr_evidence
304
+
305
+ # Pull requests whose head the tip has moved beyond
306
+ behind = [
307
+ pr
308
+ for pr in prs
309
+ if (
310
+ pr.state is PullRequestState.OPEN
311
+ or _merged_into_default(pr, default_ref, default_branch, repo)
312
+ )
313
+ and git.has_commit(pr.head_oid, cwd=repo)
314
+ and git.is_ancestor(pr.head_oid, tip, cwd=repo)
315
+ ]
316
+ if behind:
317
+ open_prs = [pr for pr in behind if pr.state is PullRequestState.OPEN]
318
+ pr = max(open_prs or behind, key=lambda pr: pr.number)
319
+ extra = ExtraCommits(
320
+ pull_request=pr.number,
321
+ commits=tuple(git.commits_between(pr.head_oid, tip, cwd=repo, exclude=default_ref)),
322
+ )
323
+ status = Status.PR_OPEN if open_prs else Status.MERGED_PLUS_LOCAL
324
+ return status, (*pr_evidence, extra)
325
+
326
+ return Status.NO_PR, pr_evidence
327
+
328
+
329
+ def _same_tree(tip: str, prs: list[PullRequest], default_ref: str, repo: Path) -> SameTree | None:
330
+ """The highest-numbered merged pull request whose merge commit is in the default branch and
331
+ has the identical tree as `tip`.
332
+ """
333
+ tip_tree = None
334
+ for pr in sorted(prs, key=lambda pr: pr.number, reverse=True):
335
+ if (
336
+ pr.state is not PullRequestState.MERGED
337
+ or pr.merge_oid is None
338
+ or not git.has_commit(pr.merge_oid, cwd=repo)
339
+ or not git.is_ancestor(pr.merge_oid, default_ref, cwd=repo)
340
+ ):
341
+ continue
342
+ tip_tree = tip_tree or git.tree_id(tip, cwd=repo)
343
+ if git.tree_id(pr.merge_oid, cwd=repo) == tip_tree:
344
+ return SameTree(pull_request=pr.number, merge_oid=pr.merge_oid)
345
+ return None
346
+
347
+
348
+ def _merged_into_default(
349
+ pr: PullRequest, default_ref: str, default_branch: str, repo: Path
350
+ ) -> bool:
351
+ """Whether a pull request was merged into the default branch, or into another branch with
352
+ its merge commit in the default branch, as when GitHub merges a stack of pull requests.
353
+ """
354
+ if pr.state is not PullRequestState.MERGED:
355
+ return False
356
+ if pr.base == default_branch:
357
+ return True
358
+ return (
359
+ pr.merge_oid is not None
360
+ and git.has_commit(pr.merge_oid, cwd=repo)
361
+ and git.is_ancestor(pr.merge_oid, default_ref, cwd=repo)
362
+ )
363
+
364
+
365
+ def _contains(pr: PullRequest, tip: str, in_default: bool, repo: Path) -> bool:
366
+ """Whether `tip` is the pull request's head commit or one of the pull request's own commits.
367
+
368
+ A tip already in the default branch only matches the head exactly. Otherwise, a branch
369
+ created from history that predates the pull request would match it.
370
+ """
371
+ if pr.head_oid == tip:
372
+ return True
373
+ if in_default:
374
+ return False
375
+ if not git.has_commit(pr.head_oid, cwd=repo):
376
+ try:
377
+ git.fetch_objects(REMOTE, f"refs/pull/{pr.number}/head", cwd=repo)
378
+ except git.GitError:
379
+ return False
380
+ if not git.has_commit(pr.head_oid, cwd=repo):
381
+ return False
382
+ return git.is_ancestor(tip, pr.head_oid, cwd=repo)
git_janitor/clean.py ADDED
@@ -0,0 +1,142 @@
1
+ from collections.abc import Collection, Sequence
2
+ from datetime import datetime
3
+ from pathlib import Path
4
+ import shlex
5
+
6
+ from git_janitor import git
7
+ from git_janitor.analysis import analyze, worktree_blockers
8
+ from git_janitor.github import GitHubClient
9
+ from git_janitor.model import (
10
+ ACCEPTABLE_BLOCKERS,
11
+ Action,
12
+ BlockerCode,
13
+ Candidate,
14
+ CleanResult,
15
+ DeleteBranch,
16
+ Outcome,
17
+ RemoveWorktree,
18
+ TargetOutcome,
19
+ Verdict,
20
+ )
21
+
22
+
23
+ def clean(
24
+ repo: Path,
25
+ github: GitHubClient,
26
+ *,
27
+ targets: Sequence[str] = (),
28
+ all: bool = False,
29
+ dry_run: bool = False,
30
+ fetch: bool = True,
31
+ cwd: Path | None = None,
32
+ now: datetime | None = None,
33
+ accept: Collection[BlockerCode] = (),
34
+ ) -> CleanResult:
35
+ """Re-analyze `repo` and carry out the actions of targets with a delete verdict.
36
+
37
+ Each action first checks that its target hasn't changed since the analysis. Blockers with
38
+ codes in `accept` are ignored for explicit targets.
39
+ """
40
+ if bool(targets) == all:
41
+ raise ValueError("Pass candidate ids to clean, or --all, but not both.")
42
+ accept = frozenset(accept)
43
+ if not_acceptable := accept - ACCEPTABLE_BLOCKERS:
44
+ codes = ", ".join(sorted(not_acceptable))
45
+ raise ValueError(f"{codes} can't be accepted")
46
+ if accept and all:
47
+ raise ValueError("Accepting blockers requires explicit targets.")
48
+ cwd = (cwd or Path.cwd()).resolve()
49
+ report = analyze(repo, github, fetch=fetch, cwd=cwd, now=now)
50
+
51
+ if all:
52
+ selected: list[Candidate | str] = [
53
+ c for c in report.candidates if c.verdict is Verdict.DELETE
54
+ ]
55
+ else:
56
+ selected = []
57
+ for target in targets:
58
+ candidate = report.find(target, cwd=cwd)
59
+ if candidate is None:
60
+ selected.append(target)
61
+ elif candidate not in selected:
62
+ selected.append(candidate)
63
+
64
+ outcomes = [
65
+ TargetOutcome(id=item, outcome=Outcome.NOT_FOUND, detail="no such candidate")
66
+ if isinstance(item, str)
67
+ else _clean_candidate(item, repo, cwd, accept, dry_run=dry_run)
68
+ for item in selected
69
+ ]
70
+ return CleanResult(report=report, outcomes=tuple(outcomes))
71
+
72
+
73
+ class ChangedSinceAnalysisError(Exception):
74
+ pass
75
+
76
+
77
+ def _clean_candidate(
78
+ candidate: Candidate,
79
+ repo: Path,
80
+ cwd: Path,
81
+ accept: frozenset[BlockerCode],
82
+ *,
83
+ dry_run: bool,
84
+ ) -> TargetOutcome:
85
+ accepted = tuple(b for b in candidate.blockers if b.code in accept)
86
+
87
+ def outcome(outcome: Outcome, detail: str = "", done: Sequence[Action] = ()) -> TargetOutcome:
88
+ return TargetOutcome(
89
+ id=candidate.id,
90
+ outcome=outcome,
91
+ verdict=candidate.verdict,
92
+ detail=detail,
93
+ actions=candidate.actions,
94
+ recovery=_recovery(done),
95
+ accepted=accepted if outcome is not Outcome.REFUSED else (),
96
+ )
97
+
98
+ verdict = candidate.verdict_accepting(accept)
99
+ if verdict is not Verdict.DELETE:
100
+ detail = f"verdict is {verdict}, not delete"
101
+ if blockers := candidate.unaccepted_blockers(accept):
102
+ detail += f"; blockers: {', '.join(str(b.code) for b in blockers)}"
103
+ return outcome(Outcome.REFUSED, detail)
104
+ if dry_run:
105
+ return outcome(Outcome.WOULD_DELETE, done=candidate.actions)
106
+
107
+ done: list[Action] = []
108
+ for action in candidate.actions:
109
+ try:
110
+ _execute(action, repo, cwd, accept)
111
+ except Exception as exc: # Keep going, so earlier targets' recovery commands are reported
112
+ return outcome(Outcome.FAILED, f"{type(exc).__name__}: {exc}", done)
113
+ done.append(action)
114
+ return outcome(Outcome.DELETED, done=done)
115
+
116
+
117
+ def _execute(action: Action, repo: Path, cwd: Path, accept: frozenset[BlockerCode]) -> None:
118
+ worktrees = git.list_worktrees(repo)
119
+ match action:
120
+ case RemoveWorktree(path=path):
121
+ current = next((wt for wt in worktrees if wt.path == path), None)
122
+ if current is None:
123
+ raise ChangedSinceAnalysisError(f"{path} is no longer a worktree")
124
+ blockers = worktree_blockers(current, cwd)
125
+ if unaccepted := [b for b in blockers if b.code not in accept]:
126
+ found = "; ".join(f"{b.code} ({b.detail})" for b in unaccepted)
127
+ raise ChangedSinceAnalysisError(f"{path} has new blockers: {found}")
128
+ git.run_git("worktree", "remove", str(path), cwd=repo)
129
+ case DeleteBranch(name=name, tip=tip):
130
+ if any(wt.branch == name for wt in worktrees):
131
+ raise ChangedSinceAnalysisError(f"{name} is now checked out in a worktree")
132
+ git.run_git("update-ref", "-d", f"refs/heads/{name}", tip, cwd=repo)
133
+ git.succeeds("config", "--remove-section", f"branch.{name}", cwd=repo)
134
+
135
+
136
+ def _recovery(done: Sequence[Action]) -> tuple[str, ...]:
137
+ """Commands that recreate the branches deleted by `done`."""
138
+ return tuple(
139
+ f"git branch {shlex.quote(action.name)} {action.tip}"
140
+ for action in done
141
+ if isinstance(action, DeleteBranch)
142
+ )
git_janitor/cli.py ADDED
@@ -0,0 +1,176 @@
1
+ from collections.abc import Sequence
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Annotated
6
+
7
+ from rich.console import Console
8
+ from rich.markup import escape
9
+ from rich.table import Table
10
+ import typer
11
+
12
+ from git_janitor import git
13
+ from git_janitor.analysis import analyze
14
+ from git_janitor.clean import clean
15
+ from git_janitor.github import GhGitHubClient, GitHubClient, GitHubError
16
+ from git_janitor.model import (
17
+ ACCEPTABLE_BLOCKERS,
18
+ BlockerCode,
19
+ Candidate,
20
+ CleanResult,
21
+ PullRequestEvidence,
22
+ SameTree,
23
+ Verdict,
24
+ )
25
+ from git_janitor.serialize import clean_result_to_dict, report_to_dict
26
+
27
+ app = typer.Typer(
28
+ no_args_is_help=True,
29
+ add_completion=False,
30
+ context_settings={"help_option_names": ["-h", "--help"]},
31
+ help="Find local branches and worktrees whose work is merged on GitHub, and clean them up.",
32
+ )
33
+ console = Console()
34
+ err_console = Console(stderr=True)
35
+
36
+ VERDICT_STYLES = {Verdict.DELETE: "green", Verdict.KEEP: "blue", Verdict.REVIEW: "yellow"}
37
+
38
+ Targets = Annotated[
39
+ list[str] | None, typer.Argument(help="Candidate ids: branch names or worktree paths.")
40
+ ]
41
+ JsonOption = Annotated[bool, typer.Option("--json", help="Print machine-readable JSON.")]
42
+ NoFetchOption = Annotated[
43
+ bool, typer.Option("--no-fetch", help="Skip `git fetch origin --prune`.")
44
+ ]
45
+
46
+
47
+ def github_client() -> GitHubClient:
48
+ return GhGitHubClient()
49
+
50
+
51
+ def fail(message: str) -> typer.Exit:
52
+ err_console.print(f"[red]Error:[/red] {escape(message)}", highlight=False)
53
+ return typer.Exit(code=1)
54
+
55
+
56
+ def repo_root() -> Path:
57
+ try:
58
+ return Path(git.run_git("rev-parse", "--show-toplevel", cwd=Path.cwd()).strip())
59
+ except git.GitError as exc:
60
+ raise fail(str(exc)) from exc
61
+
62
+
63
+ @app.command()
64
+ def report(
65
+ targets: Targets = None,
66
+ as_json: JsonOption = False,
67
+ no_fetch: NoFetchOption = False,
68
+ ) -> None:
69
+ """Report the merge status and verdict of local branches and worktrees."""
70
+ repo = repo_root()
71
+ try:
72
+ result = analyze(repo, github_client(), fetch=not no_fetch)
73
+ except (git.GitError, GitHubError, OSError, ValueError) as exc:
74
+ raise fail(str(exc)) from exc
75
+
76
+ candidates = result.candidates
77
+ if targets:
78
+ found = {target: result.find(target, cwd=Path.cwd()) for target in targets}
79
+ missing = [target for target, candidate in found.items() if candidate is None]
80
+ if missing:
81
+ raise fail(f"No such candidates: {', '.join(missing)}")
82
+ candidates = list(dict.fromkeys(c for c in found.values() if c is not None))
83
+
84
+ if as_json:
85
+ print(json.dumps(report_to_dict(result, candidates), indent=2))
86
+ else:
87
+ console.print(candidates_table(candidates))
88
+
89
+
90
+ @app.command(name="clean")
91
+ def clean_command(
92
+ targets: Targets = None,
93
+ all: Annotated[
94
+ bool, typer.Option("--all", help="Clean every candidate whose verdict is delete.")
95
+ ] = False,
96
+ dry_run: Annotated[
97
+ bool, typer.Option("--dry-run", help="Show what would be deleted.")
98
+ ] = False,
99
+ accept: Annotated[
100
+ list[str] | None,
101
+ typer.Option(
102
+ "--accept",
103
+ help=(
104
+ "Blocker codes to accept for the given targets, comma-separated: "
105
+ + ", ".join(sorted(ACCEPTABLE_BLOCKERS))
106
+ + "."
107
+ ),
108
+ ),
109
+ ] = None,
110
+ as_json: JsonOption = False,
111
+ no_fetch: NoFetchOption = False,
112
+ ) -> None:
113
+ """Delete candidates whose verdict is delete. Anything else is refused."""
114
+ try:
115
+ codes = [
116
+ BlockerCode(code.strip())
117
+ for value in accept or []
118
+ for code in value.split(",")
119
+ if code.strip()
120
+ ]
121
+ except ValueError as exc:
122
+ raise fail(str(exc)) from exc
123
+ repo = repo_root()
124
+ try:
125
+ result = clean(
126
+ repo,
127
+ github_client(),
128
+ targets=targets or [],
129
+ all=all,
130
+ dry_run=dry_run,
131
+ fetch=not no_fetch,
132
+ accept=codes,
133
+ )
134
+ except (git.GitError, GitHubError, OSError, ValueError) as exc:
135
+ raise fail(str(exc)) from exc
136
+
137
+ if as_json:
138
+ print(json.dumps(clean_result_to_dict(result, dry_run=dry_run), indent=2))
139
+ else:
140
+ print_clean_result(result)
141
+ if not result.ok:
142
+ raise typer.Exit(code=1)
143
+
144
+
145
+ def candidates_table(candidates: Sequence[Candidate]) -> Table:
146
+ table = Table()
147
+ for column in ("Candidate", "Verdict", "Status", "Worktree", "Blockers", "Pull request"):
148
+ table.add_column(column, overflow="fold")
149
+ for candidate in candidates:
150
+ style = VERDICT_STYLES[candidate.verdict]
151
+ numbers = [e.pull_request for e in candidate.evidence if isinstance(e, SameTree)] + [
152
+ e.pull_request.number
153
+ for e in candidate.evidence
154
+ if isinstance(e, PullRequestEvidence) and e.matched
155
+ ]
156
+ table.add_row(
157
+ escape(candidate.id),
158
+ f"[{style}]{candidate.verdict}[/{style}]",
159
+ str(candidate.status),
160
+ escape(os.path.relpath(candidate.worktree.path)) if candidate.worktree else "",
161
+ ", ".join(str(b.code) for b in candidate.blockers),
162
+ f"#{numbers[0]}" if numbers else "",
163
+ )
164
+ return table
165
+
166
+
167
+ def print_clean_result(result: CleanResult) -> None:
168
+ for outcome in result.outcomes:
169
+ line = f"{outcome.id}: {outcome.outcome}"
170
+ if outcome.detail:
171
+ line += f" ({outcome.detail})"
172
+ console.print(escape(line), highlight=False)
173
+ for command in outcome.recovery:
174
+ console.print(f" to recover: {escape(command)}", highlight=False)
175
+ if not result.outcomes:
176
+ console.print("Nothing to clean.")