Repository navigation
Pin local merge cleanup to the verified PR head #1635
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
1f09c75
a09cdd3
3769eb2
0cb5d94
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,11 +5,15 @@ | |
| import errno | ||
| import re | ||
| import stat | ||
| import subprocess | ||
| import tempfile | ||
| from collections.abc import Iterator | ||
| from contextlib import contextmanager | ||
| from pathlib import Path | ||
| from select import select | ||
| from uuid import uuid4 | ||
|
|
||
| from loopzero._proc import run | ||
| from loopzero._proc import build_env, run | ||
|
|
||
| GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK") | ||
| _ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir") | ||
|
|
@@ -259,13 +263,31 @@ def merges_since(wt: Path, sha: str) -> list[str]: | |
| return _git(Path(wt), "rev-list", "--first-parent", "--reverse", "--merges", f"{sha}..HEAD").split() | ||
|
|
||
|
|
||
| def cleanup(wt: Path) -> None: | ||
| """Remove the worktree and branch if there are no local user files.""" | ||
| wt = Path(wt).absolute() | ||
| if not wt.exists(): | ||
| raise WorktreeError(f"no such worktree: {wt}") | ||
| if is_dirty(wt): | ||
| raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") | ||
| @contextmanager | ||
| def _lock_verified_ref(wt: Path, ref: str, expected_head: str) -> Iterator[None]: | ||
| argv = ("git", "update-ref", "--stdin") | ||
| with subprocess.Popen( | ||
| argv, cwd=wt, env=build_env(GIT_ENV), stdin=subprocess.PIPE, | ||
| stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="surrogateescape", | ||
| ) as transaction: | ||
| assert transaction.stdin is not None and transaction.stdout is not None | ||
| try: | ||
| transaction.stdin.write(f"option no-deref\nverify {ref} {expected_head}\nprepare\n") | ||
| transaction.stdin.flush() | ||
| if not select([transaction.stdout], [], [], 30)[0]: | ||
| raise GitError(argv, "timed out verifying the merged branch") | ||
| response = transaction.stdout.readline() | ||
| if response != "prepare: ok\n": | ||
| raise GitError(argv, response) | ||
| yield | ||
| finally: | ||
| try: | ||
| transaction.communicate("abort\n", timeout=5) | ||
| except subprocess.TimeoutExpired: | ||
| transaction.terminate() | ||
|
|
||
|
|
||
| def _require_no_ignored_user_files(wt: Path) -> None: | ||
| ignored = _git( | ||
| wt, "ls-files", "--others", "--ignored", "--exclude-standard", "-z", preserve_newlines=True | ||
| ) | ||
|
|
@@ -277,10 +299,30 @@ def cleanup(wt: Path) -> None: | |
| ): | ||
| continue | ||
| raise WorktreeError(f"worktree contains ignored file {path!r}, refusing to remove: {wt}") | ||
| name, gd = branch(wt), (wt / _git(wt, "rev-parse", "--git-common-dir")).resolve() | ||
| _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout | ||
|
|
||
|
|
||
| def cleanup(wt: Path, expected_head: str) -> None: | ||
| """Remove a clean merged worktree and its branch if it has no local user files.""" | ||
| wt = Path(wt).absolute() | ||
| if not wt.exists(): | ||
| raise WorktreeError(f"no such worktree: {wt}") | ||
| if head(wt) != expected_head: | ||
| raise WorktreeError("local HEAD differs from merged PR head") | ||
| name = branch(wt) | ||
| gd = Path(_git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)) | ||
| ref = f"refs/heads/{name}" | ||
| with _lock_verified_ref(wt, ref, expected_head): | ||
| if branch(wt) != name: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: The ref lock does not stop HEAD being detached or switched before removal The |
||
| raise WorktreeError("local branch changed during merge cleanup") | ||
| if is_dirty(wt): | ||
| raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}") | ||
| _require_no_ignored_user_files(wt) | ||
| _git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout | ||
| worktrees = _git(gd, f"--git-dir={gd}", "worktree", "list", "--porcelain", "-z") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: The check that the branch is checked out elsewhere can race with branch deletion Before this change, |
||
| if f"branch {ref}" in worktrees.split("\0"): | ||
| raise WorktreeError(f"local branch {name!r} is checked out in another worktree") | ||
| try: | ||
| _git(gd, f"--git-dir={gd}", "branch", "-D", name) | ||
| _git(gd, f"--git-dir={gd}", "update-ref", "--no-deref", "-d", ref, expected_head) | ||
| except GitError: | ||
| if _git(gd, f"--git-dir={gd}", "branch", "--list", "--", name): | ||
| raise | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: Merging stderr into the transaction's stdout turns any Git warning into a refusal
Stderr is merged into stdout, and the code only accepts the first line if it is exactly
prepare: ok\n. If Git prints anything first, such as a config or deprecation warning,responsewill not match and cleanup is refused. That fails safe, but cleanup can never succeed in that environment, and the error shows only the warning line. Also, if Git exits without output,readline()returns""and the error message has no detail. Smallest fix: send stderr to a separate pipe and read stdout untilprepare: ok. On failure, include the stderr output inGitError.