Skip to content

Commit

Permalink
Refactor Branch Creation Logic and Update Tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sentry-autofix[bot] authored Jan 9, 2025
1 parent 18749fc commit 0c9b344
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 13 deletions.
20 changes: 7 additions & 13 deletions src/seer/automation/codebase/repo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,18 +322,12 @@ def get_valid_file_paths(self, sha: str | None = None) -> set[str]:
return valid_file_paths

def _create_branch(self, branch_name):
try:
ref = self.repo.create_git_ref(
ref=f"refs/heads/{branch_name}", sha=self.get_default_branch_head_sha()
)
return ref
except GithubException as e:
# if reference already exists (422), just fetch and return it
if e.status == 422:
return self.repo.get_git_ref(f"heads/{branch_name}")
raise e
ref = self.repo.create_git_ref(
ref=f"refs/heads/{branch_name}", sha=self.get_default_branch_head_sha()
)
return ref

def process_one_file_for_git_commit(
def create_branch_from_changes(
self, *, branch_ref: str, patch: FilePatch | None = None, change: FileChange | None = None
) -> InputGitTreeElement | None:
"""
Expand Down Expand Up @@ -393,8 +387,8 @@ def create_branch_from_changes(
try:
branch_ref = self._create_branch(new_branch_name)
except GithubException as e:
# only use the random suffix if the branch already exists
if e.status == 409:
# Handle both 409 (conflict) and 422 (reference already exists) by generating a new name
if e.status in (409, 422):
new_branch_name = f"{new_branch_name}/{generate_random_string(n=6)}"
branch_ref = self._create_branch(new_branch_name)
else:
Expand Down
19 changes: 19 additions & 0 deletions tests/automation/codebase/test_repo_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,25 @@ def test_create_branch_from_changes_branch_already_exists(
)
assert result is not None
assert mock_create_branch.calls[0].args[0].startswith("autofix/test-pr/")

@patch("seer.automation.codebase.repo_client.RepoClient._create_branch")
def test_create_branch_from_changes_reference_already_exists(
self, mock_create_branch, repo_client, mock_github
):
mock_github.get_repo.return_value.compare.return_value = MagicMock(ahead_by=1)
# First call raises 422, second call succeeds with random suffix
mock_create_branch.side_effect = [
GithubException(422, "Reference already exists", None),
MagicMock(ref="autofix/test-pr/123456")
]

result = repo_client.create_branch_from_changes(
pr_title="autofix/Test PR",
file_patches=[next(generate(FileChange))],
file_changes=[]
)
assert result is not None
assert mock_create_branch.call_args_list[1][0][0].startswith("autofix/test-pr/")

@pytest.mark.parametrize(
"input_type,input_data",
Expand Down

0 comments on commit 0c9b344

Please sign in to comment.