From 23175d9c1c44e8b49ab05af618d810bca6f44c2e Mon Sep 17 00:00:00 2001 From: Bay Gaillard Date: Mon, 10 Oct 2022 10:40:44 -0400 Subject: [PATCH] add delete of existing branch --- gh-code-scanning | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/gh-code-scanning b/gh-code-scanning index 5f22bbc..c658591 100755 --- a/gh-code-scanning +++ b/gh-code-scanning @@ -59,11 +59,28 @@ class GitHeadRef: def branch(self, new_branch_name): """Create a new branch from the HEAD of this branch.""" log.info('%s: Creating branch "%s"', self.repository, new_branch_name) - self.repository.api( - f'repos/{self.repository}/git/refs', - method='POST', - params={'ref': f'refs/heads/{new_branch_name}', 'sha': self.head()}, - ) + try: + self.repository.api( + f'repos/{self.repository}/git/refs', + method='POST', + params={'ref': f'refs/heads/{new_branch_name}', 'sha': self.head()}, + ) + except GithubError as error: + if error.http_status == 422: + # Try again, but delete the branch first + self.repository.api( + f'repos/{self.repository}/git/refs/heads/{new_branch_name}', + method='DELETE', + params={'ref': f'refs/heads/{new_branch_name}', 'sha': self.head()}, + ) + self.repository.api( + f'repos/{self.repository}/git/refs', + method='POST', + params={'ref': f'refs/heads/{new_branch_name}', 'sha': self.head()}, + ) + + else: + raise return GitHeadRef(new_branch_name, self.repository) def create_file(self, name, content): @@ -195,7 +212,7 @@ class GithubRepository: if raw_output: return buffer.read() - else: + elif method != 'DELETE': return json.load(buffer) def analyses(self, ref=None):