diff --git a/.github/scripts/check-version-change.py b/.github/scripts/check-version-change.py index 7b59d44..b758fdd 100755 --- a/.github/scripts/check-version-change.py +++ b/.github/scripts/check-version-change.py @@ -32,7 +32,7 @@ def fetch_pr_labels() -> set[str]: url=os.environ["GITHUB_GRAPHQL_URL"], headers={"Authorization": f"Bearer {GITHUB_TOKEN}"}, ) - client = Client(transport=transport, fetch_schema_from_transport=True) + client = Client(transport=transport, fetch_schema_from_transport=False) result = client.execute( gql( """ diff --git a/git_sync/__init__.py b/git_sync/__init__.py index de4ea17..982f621 100644 --- a/git_sync/__init__.py +++ b/git_sync/__init__.py @@ -14,6 +14,7 @@ get_remotes, in_git_repo, update_merged_prs, + update_rebased_prs, ) from .github import fetch_pull_requests, repos_by_domain @@ -52,6 +53,7 @@ def get_description( "\nMerged PR branches will be fast-forwarded or, if safe, deleted." f"\nMerged fork branches will be deleted from {push_remote.decode()}" " if unchanged since the merge." + "\nPR branches rebased on GitHub will be updated to the new PR head." ) if domains_without_tokens: description += "\n" @@ -115,20 +117,20 @@ async def git_sync() -> None: await fetch_and_fast_forward_to_upstream(branches) if push_remote: - await fast_forward_to_downstream(push_remote, branches) + push_remote_url = next( + remote.url for remote in remotes if remote.name == push_remote + ) + pull_requests = await pull_request_task if pull_request_task else [] - if pull_request_task is not None: - pull_requests = await pull_request_task - push_remote_url = next( - remote.url for remote in remotes if remote.name == push_remote - ) - await update_merged_prs( - push_remote_url, pull_requests, allow_delete=args.allow_delete + await update_rebased_prs(push_remote_url, pull_requests) + await fast_forward_to_downstream(push_remote, branches) + await update_merged_prs( + push_remote_url, pull_requests, allow_delete=args.allow_delete + ) + if args.allow_delete: + await delete_merged_remote_branches( + push_remote, push_remote_url, pull_requests ) - if args.allow_delete: - await delete_merged_remote_branches( - push_remote, push_remote_url, pull_requests - ) def main() -> None: diff --git a/git_sync/git.py b/git_sync/git.py index 0751112..7df334e 100644 --- a/git_sync/git.py +++ b/git_sync/git.py @@ -150,6 +150,28 @@ async def branch_is_an_upstream(branch_name: bytes) -> bool: return branch_name in upstream_heads +async def has_uncommitted_changes(branch_name: bytes) -> bool: + """Return true, and print why, if there are staged or unstaged changes.""" + any_staged_changes = await git_output( + "diff", "--cached", "--exit-code", check_return=False + ) + if any_staged_changes: + print(f"Staged changes on {branch_name.decode()}, skipping fast-forward") + return True + any_unstaged_changes_to_committed_files = await git_output( + "diff", "--exit-code", check_return=False + ) + if any_unstaged_changes_to_committed_files: + print(f"Unstaged changes on {branch_name.decode()}, skipping fast-forward") + return True + return False + + +async def get_current_branch_name() -> bytes | None: + current_branch = await get_current_branch() + return current_branch and current_branch[11:] + + async def update_merged_pr_branch( branch_name: bytes, merged_hash: str, @@ -161,20 +183,8 @@ async def update_merged_pr_branch( If there are any uncommitted changes on the branch, it will be skipped. If the branch is not an upstream of any other branch, it will be deleted. """ - current_branch = await get_current_branch() - current_branch = current_branch and current_branch[11:] - if current_branch == branch_name: - any_staged_changes = await git_output( - "diff", "--cached", "--exit-code", check_return=False - ) - if any_staged_changes: - print(f"Staged changes on {branch_name.decode()}, skipping fast-forward") - return - any_unstaged_changes_to_committed_files = await git_output( - "diff", "--exit-code", check_return=False - ) - if any_unstaged_changes_to_committed_files: - print(f"Unstaged changes on {branch_name.decode()}, skipping fast-forward") + if await get_current_branch_name() == branch_name: + if await has_uncommitted_changes(branch_name): return if allow_delete and not await branch_is_an_upstream(branch_name): upstream = (await get_upstream_branch(branch_name)) or b"main" @@ -200,7 +210,10 @@ async def update_merged_prs( if ( merged_hash and branch_name in branch_hashes - and branch_hashes[branch_name] in pr.hashes + and ( + branch_hashes[branch_name] in pr.hashes + or branch_hashes[branch_name] in pr.superseded_heads + ) and push_remote_url in pr.repo_urls ): await update_merged_pr_branch( @@ -244,3 +257,41 @@ async def delete_merged_remote_branches( # A branch may have been deleted since we queried the API; git will report # any failures itself, and the rest of the deletions still apply await git("push", push_remote, "--delete", *branch_names, check_return=False) + + +async def commit_exists(commit_hash: str) -> bool: + proc = await create_subprocess_exec( + "git", "cat-file", "-e", commit_hash + "^{commit}", stderr=DEVNULL + ) + return await proc.wait() == 0 + + +async def update_rebased_pr_branch(branch_name: bytes, head_hash: str) -> None: + """Move a branch from a superseded PR head to the current PR head. + + If there are any uncommitted changes on the branch, it will be skipped. + """ + if not await commit_exists(head_hash): + return + if await get_current_branch_name() == branch_name: + if await has_uncommitted_changes(branch_name): + return + await git("reset", "--hard", head_hash) + else: + await git("branch", "--force", branch_name, head_hash) + print(f"Update rebased {branch_name.decode()} to {head_hash}") + + +async def update_rebased_prs(push_remote_url: str, prs: Iterable[PullRequest]) -> None: + branch_hashes = await get_branch_hashes() + for pr in prs: + branch_name = pr.branch_name.encode("utf-8") + if ( + pr.hashes + and branch_name in branch_hashes + and branch_hashes[branch_name] in pr.superseded_heads + and push_remote_url in pr.repo_urls + ): + await update_rebased_pr_branch( + branch_name=branch_name, head_hash=pr.hashes[0] + ) diff --git a/git_sync/github.py b/git_sync/github.py index e2bddca..4c75766 100644 --- a/git_sync/github.py +++ b/git_sync/github.py @@ -57,13 +57,15 @@ class PullRequest: repo_urls: frozenset[str] """Git and SSH URLs of the repository where the PR is located.""" hashes: tuple[str, ...] - """All commits pushed to the PR, newest first.""" + """Commits in the current PR head, newest first.""" merged_hash: str | None """The commit hash of the PR merge commit, if it exists.""" head_hash: str | None = None """The current commit hash of the PR branch, or None if it has been deleted.""" is_cross_repository: bool = False """Whether the PR branch is in a different repository to the PR target.""" + superseded_heads: frozenset[str] = frozenset() + """Previous PR heads, replaced by force-pushes (e.g. rebasing onto main).""" COMMITS_PAGE_SIZE = 100 @@ -108,6 +110,17 @@ def pr_query(owner: str, name: str) -> str: mergeCommit {{ oid }} + timelineItems( + itemTypes: [HEAD_REF_FORCE_PUSHED_EVENT], last: 100 + ) {{ + nodes {{ + ... on HeadRefForcePushedEvent {{ + beforeCommit {{ + oid + }} + }} + }} + }} }} }} }} @@ -184,6 +197,7 @@ class PartialPullRequest: branch_name: str repo_urls: frozenset[str] merged_hash: str | None + superseded_heads: frozenset[str] head_hash: str | None = None is_cross_repository: bool = False oids: list[str] = field(default_factory=list) @@ -209,9 +223,16 @@ def to_pull_request(self) -> PullRequest: merged_hash=self.merged_hash, head_hash=self.head_hash, is_cross_repository=self.is_cross_repository, + superseded_heads=self.superseded_heads, ) +def superseded_heads(pr_data: dict[str, Any]) -> Iterator[str]: + for event in pr_data["timelineItems"]["nodes"]: + if before_commit := event.get("beforeCommit"): + yield before_commit["oid"] + + def partial_pull_request(pr_data: dict[str, Any]) -> PartialPullRequest: pr = PartialPullRequest( node_id=pr_data["id"], @@ -220,6 +241,7 @@ def partial_pull_request(pr_data: dict[str, Any]) -> PartialPullRequest: merged_hash=(pr_data.get("mergeCommit") or {}).get("oid"), head_hash=((pr_data.get("headRef") or {}).get("target") or {}).get("oid"), is_cross_repository=bool(pr_data.get("isCrossRepository")), + superseded_heads=frozenset(superseded_heads(pr_data)), ) pr.add_page(pr_data["commits"]) return pr diff --git a/pyproject.toml b/pyproject.toml index 67be574..b6e6867 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "git-sync" -version = "0.6.0" +version = "0.7.0" description = "Synchronize local git repo with remotes" authors = [{ name = "Alice Purcell", email = "alicederyn@gmail.com" }] requires-python = ">= 3.12" diff --git a/tests/integration/test_fast_forward_merged_prs.py b/tests/integration/test_fast_forward_merged_prs.py index e3df031..c513bff 100644 --- a/tests/integration/test_fast_forward_merged_prs.py +++ b/tests/integration/test_fast_forward_merged_prs.py @@ -288,3 +288,29 @@ async def test_no_fastforward_when_branch_has_additional_commits() -> None: "main": commit_d, "my_pr": commit_c, } + + +async def test_fastforward_when_branch_is_at_superseded_pr_head() -> None: + # Given a merged PR that was rebased on GitHub before merging + commit_a = create_commit("main", file="A\n") + commit_b = create_commit(commit_a, file="B\n") + commit_c = create_commit(commit_a, other="C\n") + commit_d = create_commit(commit_c, file="B\n") + commit_e = squash_merge(commit_c, commit_d) + setup_branches(main=commit_e, my_pr=commit_b, active_branch="main") + pr = PullRequest( + branch_name="my_pr", + repo_urls=frozenset([REPO_URL]), + hashes=(commit_d,), + merged_hash=commit_e, + superseded_heads=frozenset([commit_b]), + ) + + # When we update merged PRs + await update_merged_prs(REPO_URL, [pr], allow_delete=False) + + # Then the PR branch is fast-forwarded to the merged commit + assert all_branches() == { + "main": commit_e, + "my_pr": commit_e, + } diff --git a/tests/integration/test_update_rebased_prs.py b/tests/integration/test_update_rebased_prs.py new file mode 100644 index 0000000..845d6f8 --- /dev/null +++ b/tests/integration/test_update_rebased_prs.py @@ -0,0 +1,116 @@ +from git_sync.git import update_rebased_prs +from git_sync.github import PullRequest + +from .gitutils import ( + all_branches, + all_staged_changes, + create_commit, + setup_branches, + stage_changes, +) + +REPO_URL = "https://github.com/example/example.git" # Dummy URL for test + + +async def test_update_inactive_branch_to_rebased_pr_head() -> None: + # Given an open PR rebased onto main on GitHub + commit_a = create_commit("main", file="A\n") + commit_b = create_commit(commit_a, file="B\n") + commit_c = create_commit(commit_a, other="C\n") + commit_d = create_commit(commit_c, file="B\n") + setup_branches(main=commit_c, my_pr=commit_b, active_branch="main") + pr = PullRequest( + branch_name="my_pr", + repo_urls=frozenset([REPO_URL]), + hashes=(commit_d,), + merged_hash=None, + superseded_heads=frozenset([commit_b]), + ) + + # When we update rebased PRs + await update_rebased_prs(REPO_URL, [pr]) + + # Then the PR branch is moved to the rebased PR head + assert all_branches() == { + "main": commit_c, + "my_pr": commit_d, + } + + +async def test_update_active_branch_to_rebased_pr_head() -> None: + # Given an open PR rebased onto main on GitHub, checked out locally + commit_a = create_commit("main", file="A\n") + commit_b = create_commit(commit_a, file="B\n") + commit_c = create_commit(commit_a, other="C\n") + commit_d = create_commit(commit_c, file="B\n") + setup_branches(main=commit_c, my_pr=commit_b, active_branch="my_pr") + pr = PullRequest( + branch_name="my_pr", + repo_urls=frozenset([REPO_URL]), + hashes=(commit_d,), + merged_hash=None, + superseded_heads=frozenset([commit_b]), + ) + + # When we update rebased PRs + await update_rebased_prs(REPO_URL, [pr]) + + # Then the PR branch is moved to the rebased PR head + assert all_branches() == { + "main": commit_c, + "my_pr": commit_d, + } + + +async def test_staged_changes_not_lost() -> None: + # Given staged changes over an open PR rebased onto main on GitHub + commit_a = create_commit("main", file="A\n") + commit_b = create_commit(commit_a, file="B\n") + commit_c = create_commit(commit_a, other="C\n") + commit_d = create_commit(commit_c, file="B\n") + setup_branches(main=commit_c, my_pr=commit_b, active_branch="my_pr") + stage_changes(file="D\n") + pr = PullRequest( + branch_name="my_pr", + repo_urls=frozenset([REPO_URL]), + hashes=(commit_d,), + merged_hash=None, + superseded_heads=frozenset([commit_b]), + ) + + # When we update rebased PRs + await update_rebased_prs(REPO_URL, [pr]) + + # Then the active branch is unaffected + assert all_branches() == { + "main": commit_c, + "my_pr": commit_b, + } + # And the staged changes are preserved + assert all_staged_changes() == {"file": "D\n"} + + +async def test_no_update_when_branch_has_additional_commits() -> None: + # Given a local branch with commits not in any PR head + commit_a = create_commit("main", file="A\n") + commit_b = create_commit(commit_a, file="B\n") + commit_c = create_commit(commit_a, other="C\n") + commit_d = create_commit(commit_c, file="B\n") + commit_e = create_commit(commit_b, file="E\n") + setup_branches(main=commit_c, my_pr=commit_e, active_branch="main") + pr = PullRequest( + branch_name="my_pr", + repo_urls=frozenset([REPO_URL]), + hashes=(commit_d,), + merged_hash=None, + superseded_heads=frozenset([commit_b]), + ) + + # When we update rebased PRs + await update_rebased_prs(REPO_URL, [pr]) + + # Then the PR branch is unaffected + assert all_branches() == { + "main": commit_c, + "my_pr": commit_e, + } diff --git a/tests/test_github.py b/tests/test_github.py index 721a9e8..6a990bf 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -59,6 +59,14 @@ def commits(*oids: str, has_previous_page: bool = False) -> dict[str, object]: } +def force_pushes(*before_oids: str | None) -> dict[str, object]: + return { + "nodes": [ + {"beforeCommit": {"oid": oid} if oid else None} for oid in before_oids + ] + } + + async def test_successful_fetch_with_multiple_repos_and_prs( graphql_client: Mock, ) -> None: @@ -78,6 +86,7 @@ async def test_successful_fetch_with_multiple_repos_and_prs( "isCrossRepository": True, "commits": commits("commit1", "commit2", "commit3"), "mergeCommit": {"oid": "merge1"}, + "timelineItems": force_pushes(), }, { "id": "pr2", @@ -90,6 +99,7 @@ async def test_successful_fetch_with_multiple_repos_and_prs( "isCrossRepository": False, "commits": commits("commit4"), "mergeCommit": None, + "timelineItems": force_pushes(), }, ] } @@ -108,6 +118,7 @@ async def test_successful_fetch_with_multiple_repos_and_prs( "isCrossRepository": True, "commits": commits("commit5", "commit6"), "mergeCommit": {"oid": "merge2"}, + "timelineItems": force_pushes(), }, ] } @@ -227,6 +238,7 @@ async def test_pr_without_head_repository(graphql_client: Mock) -> None: "headRepository": None, # Deleted repository "commits": commits("commit1"), "mergeCommit": None, + "timelineItems": force_pushes(), }, ] } @@ -245,7 +257,11 @@ async def test_pr_without_head_repository(graphql_client: Mock) -> None: assert result[0].branch_name == "feature-branch" -def one_pr_with_commits(commits: dict[str, object]) -> dict[str, object]: +def one_pr_with_commits( + commits: dict[str, object], + *, + timeline_items: dict[str, object] | None = None, +) -> dict[str, object]: return { "q0": { "pullRequests": { @@ -256,6 +272,7 @@ def one_pr_with_commits(commits: dict[str, object]) -> dict[str, object]: "headRepository": None, "commits": commits, "mergeCommit": {"oid": "merge1"}, + "timelineItems": timeline_items or force_pushes(), }, ] } @@ -263,6 +280,21 @@ def one_pr_with_commits(commits: dict[str, object]) -> dict[str, object]: } +async def test_pr_superseded_heads(graphql_client: Mock) -> None: + pr_data = one_pr_with_commits( + commits("commit3"), + timeline_items=force_pushes("commit1", None, "commit2"), + ) + graphql_client.return_value.query.return_value = Mock(data=pr_data, errors=None) + + result = [ + pr + async for pr in fetch_pull_requests_from_domain(Mock(), Mock(), [TWO_REPOS[0]]) + ] + + assert result[0].superseded_heads == frozenset(["commit1", "commit2"]) + + async def test_commits_paginated_over_multiple_pages(graphql_client: Mock) -> None: graphql_client.return_value.query.side_effect = [ Mock(