Allow 409 error from Gerrit when creating the branch

Gerrit may return 409 error to us even if the branch was created.
We should ignore this error if the branch head is the commit we
requested.

Also pre-check the branch status before creating it.
If an existing branch is expected by the caller, simply return
the branch info without sending the creation request.

BUG=1433047
TEST=local run
Change-Id: Ic6184705579f1410cb9c54843cc0bbb4c4ad61b1
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/tools/depot_tools/+/4436317
Reviewed-by: Gavin Mak <gavinmak@google.com>
Reviewed-by: Garrett Beaty <gbeaty@google.com>
Commit-Queue: Xinan Lin <linxinan@chromium.org>
changes/17/4436317/16
Xinan Lin 2 years ago committed by LUCI CQ
parent 68ec7822b8
commit dbcecc9017

@ -112,6 +112,10 @@ def CMDbranch(parser, args):
"""Create a branch in a gerrit project."""
parser.add_option('--branch', dest='branch', help='branch name')
parser.add_option('--commit', dest='commit', help='commit hash')
parser.add_option('--allow-existent-branch',
action='store_true',
help=('Accept that the branch alread exists as long as the'
' branch head points the given commit'))
(opt, args) = parser.parse_args(args)
assert opt.project, "--project not defined"
@ -121,7 +125,27 @@ def CMDbranch(parser, args):
project = quote_plus(opt.project)
host = urlparse.urlparse(opt.host).netloc
branch = quote_plus(opt.branch)
result = gerrit_util.CreateGerritBranch(host, project, branch, opt.commit)
result = gerrit_util.GetGerritBranch(host, project, branch)
if result:
if not opt.allow_existent_branch:
raise gerrit_util.GerritError(200, 'Branch already exists')
if result.get('revision') != opt.commit:
raise gerrit_util.GerritError(
200, ('Branch already exists but '
'the branch head is not at the given commit'))
else:
try:
result = gerrit_util.CreateGerritBranch(host, project, branch, opt.commit)
except gerrit_util.GerritError as e:
result = gerrit_util.GetGerritBranch(host, project, branch)
if not result:
raise e
# If reached here, we hit a real conflict error, because the
# branch just created is pointing a different commit.
if result.get('revision') != opt.commit:
raise gerrit_util.GerritError(
200, ('Conflict: branch was created but '
'the branch head is not at the given commit'))
logging.info(result)
write_result(result, opt)

@ -1077,7 +1077,7 @@ def CreateGerritBranch(host, project, branch, commit):
path = 'projects/%s/branches/%s' % (project, branch)
body = {'revision': commit}
conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
response = ReadHttpJsonResponse(conn, accept_statuses=[201])
response = ReadHttpJsonResponse(conn, accept_statuses=[201, 409])
if response:
return response
raise GerritError(200, 'Unable to create gerrit branch')

Loading…
Cancel
Save