Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/scripts/check-version-change.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
"""
Expand Down
26 changes: 14 additions & 12 deletions git_sync/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
get_remotes,
in_git_repo,
update_merged_prs,
update_rebased_prs,
)
from .github import fetch_pull_requests, repos_by_domain

Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down
81 changes: 66 additions & 15 deletions git_sync/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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"
Expand All @@ -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(
Expand Down Expand Up @@ -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]
)
24 changes: 23 additions & 1 deletion git_sync/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}}
}}
}}
}}
}}
}}
}}
Expand Down Expand Up @@ -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)
Expand All @@ -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"],
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
26 changes: 26 additions & 0 deletions tests/integration/test_fast_forward_merged_prs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
116 changes: 116 additions & 0 deletions tests/integration/test_update_rebased_prs.py
Original file line number Diff line number Diff line change
@@ -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,
}
Loading
Loading