Decide whether ``wt`` is safe to delete. A worktree is safe iff: - It is a real git working tree (has a ``.git`` file/dir) - ``git status --porcelain`` is empty (no uncommitted changes) - ``git log @{upstream}.. --oneline`` is empty (no unpushed commits), OR there is n
(wt: Path)
| 99 | |
| 100 | |
| 101 | def classify_worktree(wt: Path) -> WorktreeStatus: |
| 102 | """Decide whether ``wt`` is safe to delete. |
| 103 | |
| 104 | A worktree is safe iff: |
| 105 | - It is a real git working tree (has a ``.git`` file/dir) |
| 106 | - ``git status --porcelain`` is empty (no uncommitted changes) |
| 107 | - ``git log @{upstream}.. --oneline`` is empty (no unpushed commits), |
| 108 | OR there is no upstream and the branch has no commits beyond |
| 109 | ``origin/master``. |
| 110 | |
| 111 | A worktree is treated as safe (no work to lose) if it's an orphan |
| 112 | directory with no ``.git`` link — those are leftover empty dirs from |
| 113 | failed prior cleanups. |
| 114 | """ |
| 115 | if not (wt / ".git").exists(): |
| 116 | return WorktreeStatus(path=wt, safe=True, reason="orphan directory (no .git)") |
| 117 | |
| 118 | status = run_git(["status", "--porcelain"], cwd=wt) |
| 119 | if status.returncode != 0: |
| 120 | return WorktreeStatus( |
| 121 | path=wt, |
| 122 | safe=False, |
| 123 | reason=f"git status failed: {status.stderr.strip() or status.stdout.strip()}", |
| 124 | ) |
| 125 | if status.stdout.strip(): |
| 126 | return WorktreeStatus(path=wt, safe=False, reason="uncommitted changes") |
| 127 | |
| 128 | # Check unpushed commits. Try upstream first. |
| 129 | upstream = run_git(["log", "@{upstream}..", "--oneline"], cwd=wt) |
| 130 | if upstream.returncode == 0: |
| 131 | if upstream.stdout.strip(): |
| 132 | return WorktreeStatus( |
| 133 | path=wt, safe=False, reason="unpushed commits vs upstream" |
| 134 | ) |
| 135 | return WorktreeStatus(path=wt, safe=True, reason="clean, in sync with upstream") |
| 136 | |
| 137 | # No upstream — compare against origin/master. |
| 138 | fallback = run_git(["log", "origin/master..", "--oneline"], cwd=wt) |
| 139 | if fallback.returncode != 0: |
| 140 | return WorktreeStatus( |
| 141 | path=wt, |
| 142 | safe=False, |
| 143 | reason="no upstream and cannot compare to origin/master", |
| 144 | ) |
| 145 | if fallback.stdout.strip(): |
| 146 | return WorktreeStatus( |
| 147 | path=wt, |
| 148 | safe=False, |
| 149 | reason="no upstream and has commits beyond origin/master", |
| 150 | ) |
| 151 | return WorktreeStatus( |
| 152 | path=wt, safe=True, reason="clean, no commits beyond origin/master" |
| 153 | ) |
| 154 | |
| 155 | |
| 156 | def clear_readonly(path: Path) -> None: |
no test coverage detected