blob: 2f28fe3f58e151e11c50267df3b76640f528c38f [file] [log] [blame]
Edward Lemur1f3bafb2019-10-08 17:56:33 +00001#!/usr/bin/env vpython
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +02002# Copyright (c) 2013 The Chromium Authors. All rights reserved.
maruel@chromium.org725f1c32011-04-01 20:24:54 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00006# Copyright (C) 2008 Evan Martin <martine@danga.com>
7
Andrii Shyshkalov03da1502018-10-15 03:42:34 +00008"""A git-command for integrating reviews on Gerrit."""
maruel@chromium.org725f1c32011-04-01 20:24:54 +00009
vapiera7fbd5a2016-06-16 09:17:49 -070010from __future__ import print_function
11
Edward Lesmescba46082020-03-25 00:29:06 +000012from distutils.version import LooseVersion
thakis@chromium.org3421c992014-11-02 02:20:32 +000013import base64
rmistry@google.com2dd99862015-06-22 12:22:18 +000014import collections
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +010015import datetime
Brian Sheedyb4307d52019-12-02 19:18:17 +000016import fnmatch
Edward Lemur202c5592019-10-21 22:44:52 +000017import httplib2
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +010018import itertools
maruel@chromium.org4f6852c2012-04-20 20:39:20 +000019import json
chase@chromium.orgcc51cd02010-12-23 00:48:39 +000020import logging
calamity@chromium.orgcf197482016-04-29 20:15:53 +000021import multiprocessing
chase@chromium.orgcc51cd02010-12-23 00:48:39 +000022import optparse
23import os
24import re
Andrii Shyshkalov353637c2017-03-14 16:52:18 +010025import shutil
ukai@chromium.org78c4b982012-02-14 02:20:26 +000026import stat
chase@chromium.orgcc51cd02010-12-23 00:48:39 +000027import sys
Aaron Gable9a03ae02017-11-03 11:31:07 -070028import tempfile
chase@chromium.orgcc51cd02010-12-23 00:48:39 +000029import textwrap
Edward Lemurfec80c42018-11-01 23:14:14 +000030import time
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +000031import uuid
thestig@chromium.org00858c82013-12-02 23:08:03 +000032import webbrowser
thakis@chromium.org3421c992014-11-02 02:20:32 +000033import zlib
chase@chromium.orgcc51cd02010-12-23 00:48:39 +000034
maruel@chromium.org2e23ce32013-05-07 12:42:28 +000035from third_party import colorama
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +000036import auth
nick@chromium.org3ac1c4e2014-01-16 02:44:42 +000037import clang_format
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +000038import dart_format
maruel@chromium.org6f09cd92011-04-01 16:38:12 +000039import fix_encoding
maruel@chromium.org0e0436a2011-10-25 13:32:41 +000040import gclient_utils
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +000041import gerrit_util
iannucci@chromium.org9e849272014-04-04 00:31:55 +000042import git_common
tandrii@chromium.org09d7a6a2016-03-04 15:44:48 +000043import git_footers
Edward Lemur85153282020-02-14 22:06:29 +000044import git_new_branch
Edward Lemur5ba1e9c2018-07-23 18:19:02 +000045import metrics
Edward Lesmes93277a72018-10-18 22:04:26 +000046import metrics_utils
piman@chromium.org336f9122014-09-04 02:16:55 +000047import owners
iannucci@chromium.org9e849272014-04-04 00:31:55 +000048import owners_finder
maruel@chromium.org2a74d372011-03-29 19:05:50 +000049import presubmit_support
50import scm
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000051import setup_color
Francois Dorayd42c6812017-05-30 15:10:20 -040052import split_cl
maruel@chromium.org0633fb42013-08-16 20:06:14 +000053import subcommand
maruel@chromium.org32f9f5e2011-09-14 13:41:47 +000054import subprocess2
maruel@chromium.org2a74d372011-03-29 19:05:50 +000055import watchlists
56
Edward Lemur79d4f992019-11-11 23:49:02 +000057from third_party import six
58from six.moves import urllib
59
60
61if sys.version_info.major == 3:
62 basestring = (str,) # pylint: disable=redefined-builtin
63
Edward Lemurb9830242019-10-30 22:19:20 +000064
tandrii7400cf02016-06-21 08:48:07 -070065__version__ = '2.0'
maruel@chromium.org2a74d372011-03-29 19:05:50 +000066
Edward Lemur0f58ae42019-04-30 17:24:12 +000067# Traces for git push will be stored in a traces directory inside the
68# depot_tools checkout.
69DEPOT_TOOLS = os.path.dirname(os.path.abspath(__file__))
70TRACES_DIR = os.path.join(DEPOT_TOOLS, 'traces')
Edward Lemur227d5102020-02-25 23:45:35 +000071PRESUBMIT_SUPPORT = os.path.join(DEPOT_TOOLS, 'presubmit_support.py')
Edward Lemur0f58ae42019-04-30 17:24:12 +000072
73# When collecting traces, Git hashes will be reduced to 6 characters to reduce
74# the size after compression.
75GIT_HASH_RE = re.compile(r'\b([a-f0-9]{6})[a-f0-9]{34}\b', flags=re.I)
76# Used to redact the cookies from the gitcookies file.
77GITCOOKIES_REDACT_RE = re.compile(r'1/.*')
78
Edward Lemurd4d1ba42019-09-20 21:46:37 +000079MAX_ATTEMPTS = 3
80
Edward Lemur1b52d872019-05-09 21:12:12 +000081# The maximum number of traces we will keep. Multiplied by 3 since we store
82# 3 files per trace.
83MAX_TRACES = 3 * 10
Edward Lemur5737f022019-05-17 01:24:00 +000084# Message to be displayed to the user to inform where to find the traces for a
85# git-cl upload execution.
Edward Lemur0f58ae42019-04-30 17:24:12 +000086TRACES_MESSAGE = (
Edward Lemur1b52d872019-05-09 21:12:12 +000087'\n'
Edward Lemur5737f022019-05-17 01:24:00 +000088'The traces of this git-cl execution have been recorded at:\n'
Edward Lemur1b52d872019-05-09 21:12:12 +000089' %(trace_name)s-traces.zip\n'
Edward Lemur5737f022019-05-17 01:24:00 +000090'Copies of your gitcookies file and git config have been recorded at:\n'
91' %(trace_name)s-git-info.zip\n')
Edward Lemur1b52d872019-05-09 21:12:12 +000092# Format of the message to be stored as part of the traces to give developers a
93# better context when they go through traces.
94TRACES_README_FORMAT = (
95'Date: %(now)s\n'
96'\n'
97'Change: https://%(gerrit_host)s/q/%(change_id)s\n'
98'Title: %(title)s\n'
99'\n'
100'%(description)s\n'
101'\n'
102'Execution time: %(execution_time)s\n'
103'Exit code: %(exit_code)s\n') + TRACES_MESSAGE
Edward Lemur0f58ae42019-04-30 17:24:12 +0000104
Aaron Gable1bc7bfe2016-12-19 10:08:14 -0800105POSTUPSTREAM_HOOK = '.git/hooks/post-cl-land'
Henrique Ferreiroff249622019-11-28 23:19:29 +0000106DESCRIPTION_BACKUP_FILE = '.git_cl_description_backup'
rmistry@google.comc68112d2015-03-03 12:48:06 +0000107REFS_THAT_ALIAS_TO_OTHER_REFS = {
108 'refs/remotes/origin/lkgr': 'refs/remotes/origin/master',
109 'refs/remotes/origin/lkcr': 'refs/remotes/origin/master',
110}
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000111
thestig@chromium.org44202a22014-03-11 19:22:18 +0000112# Valid extensions for files we want to lint.
113DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)"
114DEFAULT_LINT_IGNORE_REGEX = r"$^"
115
Aiden Bennerc08566e2018-10-03 17:52:42 +0000116# File name for yapf style config files.
117YAPF_CONFIG_FILENAME = '.style.yapf'
118
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000119# Shortcut since it quickly becomes repetitive.
maruel@chromium.org2e23ce32013-05-07 12:42:28 +0000120Fore = colorama.Fore
maruel@chromium.org90541732011-04-01 17:54:18 +0000121
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000122# Initialized in main()
123settings = None
124
Andrii Shyshkalov768f1d82016-12-08 15:10:13 +0100125# Used by tests/git_cl_test.py to add extra logging.
126# Inside the weirdly failing test, add this:
127# >>> self.mock(git_cl, '_IS_BEING_TESTED', True)
Quinten Yearsley0c62da92017-05-31 13:39:42 -0700128# And scroll up to see the stack trace printed.
Andrii Shyshkalov768f1d82016-12-08 15:10:13 +0100129_IS_BEING_TESTED = False
130
maruel@chromium.orgddd59412011-11-30 14:20:38 +0000131
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +0000132_KNOWN_GERRIT_TO_SHORT_URLS = {
133 'https://chrome-internal-review.googlesource.com': 'https://crrev.com/i',
134 'https://chromium-review.googlesource.com': 'https://crrev.com/c',
135}
136
137
Christopher Lamf732cd52017-01-24 12:40:11 +1100138def DieWithError(message, change_desc=None):
139 if change_desc:
140 SaveDescriptionBackup(change_desc)
Josip Sokcevic953278a2020-02-28 19:46:36 +0000141 print('\n ** Content of CL description **\n' +
142 '='*72 + '\n' +
143 change_desc.description + '\n' +
144 '='*72 + '\n')
Christopher Lamf732cd52017-01-24 12:40:11 +1100145
vapiera7fbd5a2016-06-16 09:17:49 -0700146 print(message, file=sys.stderr)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000147 sys.exit(1)
148
149
Christopher Lamf732cd52017-01-24 12:40:11 +1100150def SaveDescriptionBackup(change_desc):
Henrique Ferreiro5ae48172019-11-29 16:14:42 +0000151 backup_path = os.path.join(DEPOT_TOOLS, DESCRIPTION_BACKUP_FILE)
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +0000152 print('\nsaving CL description to %s\n' % backup_path)
Josip906bfde2020-01-31 22:38:49 +0000153 with open(backup_path, 'w') as backup_file:
154 backup_file.write(change_desc.description)
Christopher Lamf732cd52017-01-24 12:40:11 +1100155
156
thestig@chromium.org8b0553c2014-02-11 00:33:37 +0000157def GetNoGitPagerEnv():
158 env = os.environ.copy()
159 # 'cat' is a magical git string that disables pagers on all platforms.
160 env['GIT_PAGER'] = 'cat'
161 return env
162
vadimsh@chromium.org566a02a2014-08-22 01:34:13 +0000163
bsep@chromium.org627d9002016-04-29 00:00:52 +0000164def RunCommand(args, error_ok=False, error_message=None, shell=False, **kwargs):
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000165 try:
Edward Lemur79d4f992019-11-11 23:49:02 +0000166 stdout = subprocess2.check_output(args, shell=shell, **kwargs)
167 return stdout.decode('utf-8', 'replace')
maruel@chromium.org78936cb2013-04-11 00:17:52 +0000168 except subprocess2.CalledProcessError as e:
169 logging.debug('Failed running %s', args)
maruel@chromium.org32f9f5e2011-09-14 13:41:47 +0000170 if not error_ok:
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000171 DieWithError(
maruel@chromium.org32f9f5e2011-09-14 13:41:47 +0000172 'Command "%s" failed.\n%s' % (
173 ' '.join(args), error_message or e.stdout or ''))
Edward Lemur79d4f992019-11-11 23:49:02 +0000174 return e.stdout.decode('utf-8', 'replace')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000175
176
177def RunGit(args, **kwargs):
maruel@chromium.org32f9f5e2011-09-14 13:41:47 +0000178 """Returns stdout."""
bratell@opera.com82b91cd2013-07-09 06:33:41 +0000179 return RunCommand(['git'] + args, **kwargs)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000180
181
enne@chromium.org3b7e15c2014-01-21 17:44:47 +0000182def RunGitWithCode(args, suppress_stderr=False):
maruel@chromium.org32f9f5e2011-09-14 13:41:47 +0000183 """Returns return code and stdout."""
tandrii5d48c322016-08-18 16:19:37 -0700184 if suppress_stderr:
185 stderr = subprocess2.VOID
186 else:
187 stderr = sys.stderr
szager@chromium.org9bb85e22012-06-13 20:28:23 +0000188 try:
tandrii5d48c322016-08-18 16:19:37 -0700189 (out, _), code = subprocess2.communicate(['git'] + args,
190 env=GetNoGitPagerEnv(),
191 stdout=subprocess2.PIPE,
192 stderr=stderr)
Edward Lemur79d4f992019-11-11 23:49:02 +0000193 return code, out.decode('utf-8', 'replace')
tandrii5d48c322016-08-18 16:19:37 -0700194 except subprocess2.CalledProcessError as e:
Yoshisato Yanagisawa81e3ff52017-09-26 15:33:34 +0900195 logging.debug('Failed running %s', ['git'] + args)
Edward Lemur79d4f992019-11-11 23:49:02 +0000196 return e.returncode, e.stdout.decode('utf-8', 'replace')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000197
198
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000199def RunGitSilent(args):
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000200 """Returns stdout, suppresses stderr and ignores the return code."""
bauerb@chromium.org27386dd2015-02-16 10:45:39 +0000201 return RunGitWithCode(args, suppress_stderr=True)[1]
202
203
Edward Lesmescba46082020-03-25 00:29:06 +0000204def IsGitVersionAtLeast(min_version):
205 prefix = 'git version '
206 version = RunGit(['--version']).strip()
207 return (version.startswith(prefix) and
208 LooseVersion(version[len(prefix):]) >= LooseVersion(min_version))
209
210
211def BranchExists(branch):
212 """Return True if specified branch exists."""
213 code, _ = RunGitWithCode(['rev-parse', '--verify', branch],
214 suppress_stderr=True)
215 return not code
216
217
tandrii2a16b952016-10-19 07:09:44 -0700218def time_sleep(seconds):
219 # Use this so that it can be mocked in tests without interfering with python
220 # system machinery.
tandrii2a16b952016-10-19 07:09:44 -0700221 return time.sleep(seconds)
222
223
Edward Lemur01f4a4f2018-11-03 00:40:38 +0000224def time_time():
225 # Use this so that it can be mocked in tests without interfering with python
226 # system machinery.
227 return time.time()
228
229
Edward Lemur1b52d872019-05-09 21:12:12 +0000230def datetime_now():
231 # Use this so that it can be mocked in tests without interfering with python
232 # system machinery.
233 return datetime.datetime.now()
234
235
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100236def confirm_or_exit(prefix='', action='confirm'):
237 """Asks user to press enter to continue or press Ctrl+C to abort."""
238 if not prefix or prefix.endswith('\n'):
239 mid = 'Press'
Andrii Shyshkalov353637c2017-03-14 16:52:18 +0100240 elif prefix.endswith('.') or prefix.endswith('?'):
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100241 mid = ' Press'
242 elif prefix.endswith(' '):
243 mid = 'press'
244 else:
245 mid = ' press'
Edward Lesmesae3586b2020-03-23 21:21:14 +0000246 gclient_utils.AskForData(
247 '%s%s Enter to %s, or Ctrl+C to abort' % (prefix, mid, action))
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100248
249
250def ask_for_explicit_yes(prompt):
Quinten Yearsleyd242ed72019-07-25 17:17:55 +0000251 """Returns whether user typed 'y' or 'yes' to confirm the given prompt."""
Edward Lesmesae3586b2020-03-23 21:21:14 +0000252 result = gclient_utils.AskForData(prompt + ' [Yes/No]: ').lower()
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100253 while True:
254 if 'yes'.startswith(result):
255 return True
256 if 'no'.startswith(result):
257 return False
Edward Lesmesae3586b2020-03-23 21:21:14 +0000258 result = gclient_utils.AskForData('Please, type yes or no: ').lower()
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +0100259
260
Edward Lesmescba46082020-03-25 00:29:06 +0000261def _git_branch_config_key(branch, key):
262 """Helper method to return Git config key for a branch."""
263 assert branch, 'branch name is required to set git config for it'
264 return 'branch.%s.%s' % (branch, key)
265
266
machenbach@chromium.org45453142015-09-15 08:45:22 +0000267def _get_properties_from_options(options):
Quinten Yearsleya19d3532019-09-30 21:54:39 +0000268 prop_list = getattr(options, 'properties', [])
269 properties = dict(x.split('=', 1) for x in prop_list)
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000270 for key, val in properties.items():
machenbach@chromium.org45453142015-09-15 08:45:22 +0000271 try:
272 properties[key] = json.loads(val)
273 except ValueError:
274 pass # If a value couldn't be evaluated, treat it as a string.
275 return properties
276
277
Edward Lesmescba46082020-03-25 00:29:06 +0000278# TODO(crbug.com/976104): Remove this function once git-cl try-results has
279# migrated to use buildbucket v2
280def _buildbucket_retry(operation_name, http, *args, **kwargs):
281 """Retries requests to buildbucket service and returns parsed json content."""
282 try_count = 0
283 while True:
284 response, content = http.request(*args, **kwargs)
285 try:
286 content_json = json.loads(content)
287 except ValueError:
288 content_json = None
289
290 # Buildbucket could return an error even if status==200.
291 if content_json and content_json.get('error'):
292 error = content_json.get('error')
293 if error.get('code') == 403:
294 raise BuildbucketResponseException(
295 'Access denied: %s' % error.get('message', ''))
296 msg = 'Error in response. Reason: %s. Message: %s.' % (
297 error.get('reason', ''), error.get('message', ''))
298 raise BuildbucketResponseException(msg)
299
300 if response.status == 200:
301 if content_json is None:
302 raise BuildbucketResponseException(
303 'Buildbucket returned invalid JSON content: %s.\n'
304 'Please file bugs at http://crbug.com, '
305 'component "Infra>Platform>Buildbucket".' %
306 content)
307 return content_json
308 if response.status < 500 or try_count >= 2:
309 raise httplib2.HttpLib2Error(content)
310
311 # status >= 500 means transient failures.
312 logging.debug('Transient errors when %s. Will retry.', operation_name)
313 time_sleep(0.5 + (1.5 * try_count))
314 try_count += 1
315 assert False, 'unreachable'
316
317
Edward Lemur4c707a22019-09-24 21:13:43 +0000318def _call_buildbucket(http, buildbucket_host, method, request):
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000319 """Calls a buildbucket v2 method and returns the parsed json response."""
320 headers = {
321 'Accept': 'application/json',
322 'Content-Type': 'application/json',
323 }
324 request = json.dumps(request)
325 url = 'https://%s/prpc/buildbucket.v2.Builds/%s' % (buildbucket_host, method)
326
327 logging.info('POST %s with %s' % (url, request))
328
329 attempts = 1
330 time_to_sleep = 1
331 while True:
332 response, content = http.request(url, 'POST', body=request, headers=headers)
333 if response.status == 200:
334 return json.loads(content[4:])
335 if attempts >= MAX_ATTEMPTS or 400 <= response.status < 500:
336 msg = '%s error when calling POST %s with %s: %s' % (
337 response.status, url, request, content)
338 raise BuildbucketResponseException(msg)
339 logging.debug(
340 '%s error when calling POST %s with %s. '
341 'Sleeping for %d seconds and retrying...' % (
342 response.status, url, request, time_to_sleep))
343 time.sleep(time_to_sleep)
344 time_to_sleep *= 2
345 attempts += 1
346
347 assert False, 'unreachable'
348
349
Edward Lemur6215c792019-10-03 21:59:05 +0000350def _parse_bucket(raw_bucket):
351 legacy = True
352 project = bucket = None
353 if '/' in raw_bucket:
354 legacy = False
355 project, bucket = raw_bucket.split('/', 1)
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000356 # Assume luci.<project>.<bucket>.
Edward Lemur6215c792019-10-03 21:59:05 +0000357 elif raw_bucket.startswith('luci.'):
358 project, bucket = raw_bucket[len('luci.'):].split('.', 1)
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000359 # Otherwise, assume prefix is also the project name.
Edward Lemur6215c792019-10-03 21:59:05 +0000360 elif '.' in raw_bucket:
361 project = raw_bucket.split('.')[0]
362 bucket = raw_bucket
363 # Legacy buckets.
Edward Lemur45768512020-03-02 19:03:14 +0000364 if legacy and project and bucket:
Edward Lemur6215c792019-10-03 21:59:05 +0000365 print('WARNING Please use %s/%s to specify the bucket.' % (project, bucket))
366 return project, bucket
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000367
368
Quinten Yearsley777660f2020-03-04 23:37:06 +0000369def _trigger_tryjobs(changelist, jobs, options, patchset):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000370 """Sends a request to Buildbucket to trigger tryjobs for a changelist.
qyearsley1fdfcb62016-10-24 13:22:03 -0700371
372 Args:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000373 changelist: Changelist that the tryjobs are associated with.
Edward Lemur45768512020-03-02 19:03:14 +0000374 jobs: A list of (project, bucket, builder).
qyearsley1fdfcb62016-10-24 13:22:03 -0700375 options: Command-line options.
376 """
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000377 print('Scheduling jobs on:')
Edward Lemur45768512020-03-02 19:03:14 +0000378 for project, bucket, builder in jobs:
379 print(' %s/%s: %s' % (project, bucket, builder))
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000380 print('To see results here, run: git cl try-results')
381 print('To see results in browser, run: git cl web')
tandriide281ae2016-10-12 06:02:30 -0700382
Quinten Yearsley777660f2020-03-04 23:37:06 +0000383 requests = _make_tryjob_schedule_requests(changelist, jobs, options, patchset)
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +0000384 if not requests:
385 return
386
Edward Lemur5b929a42019-10-21 17:57:39 +0000387 http = auth.Authenticator().authorize(httplib2.Http())
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +0000388 http.force_exception_to_status_code = True
389
390 batch_request = {'requests': requests}
391 batch_response = _call_buildbucket(
392 http, options.buildbucket_host, 'Batch', batch_request)
393
394 errors = [
395 ' ' + response['error']['message']
396 for response in batch_response.get('responses', [])
397 if 'error' in response
398 ]
399 if errors:
400 raise BuildbucketResponseException(
401 'Failed to schedule builds for some bots:\n%s' % '\n'.join(errors))
402
403
Quinten Yearsley777660f2020-03-04 23:37:06 +0000404def _make_tryjob_schedule_requests(changelist, jobs, options, patchset):
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +0000405 """Constructs requests for Buildbucket to trigger tryjobs."""
Edward Lemurf0faf482019-09-25 20:40:17 +0000406 gerrit_changes = [changelist.GetGerritChange(patchset)]
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +0000407 shared_properties = {
408 'category': options.ensure_value('category', 'git_cl_try')
409 }
410 if options.ensure_value('clobber', False):
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000411 shared_properties['clobber'] = True
412 shared_properties.update(_get_properties_from_options(options) or {})
413
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +0000414 shared_tags = [{'key': 'user_agent', 'value': 'git_cl_try'}]
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +0000415 if options.ensure_value('retry_failed', False):
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +0000416 shared_tags.append({'key': 'retry_failed',
417 'value': '1'})
418
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000419 requests = []
Edward Lemur45768512020-03-02 19:03:14 +0000420 for (project, bucket, builder) in jobs:
421 properties = shared_properties.copy()
422 if 'presubmit' in builder.lower():
423 properties['dry_run'] = 'true'
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000424
Edward Lemur45768512020-03-02 19:03:14 +0000425 requests.append({
426 'scheduleBuild': {
427 'requestId': str(uuid.uuid4()),
428 'builder': {
429 'project': getattr(options, 'project', None) or project,
430 'bucket': bucket,
431 'builder': builder,
432 },
433 'gerritChanges': gerrit_changes,
434 'properties': properties,
435 'tags': [
436 {'key': 'builder', 'value': builder},
437 ] + shared_tags,
438 }
439 })
Edward Lemurd4d1ba42019-09-20 21:46:37 +0000440
Quinten Yearsleyee8be8a2020-03-05 21:48:32 +0000441 if options.ensure_value('revision', None):
Edward Lemur45768512020-03-02 19:03:14 +0000442 requests[-1]['scheduleBuild']['gitilesCommit'] = {
443 'host': gerrit_changes[0]['host'],
444 'project': gerrit_changes[0]['project'],
445 'id': options.revision
446 }
Anthony Polito1a5fe232020-01-24 23:17:52 +0000447
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +0000448 return requests
kjellander@chromium.org44424542015-06-02 18:35:29 +0000449
sheyang@google.com6ebaf782015-05-12 19:17:54 +0000450
Quinten Yearsley777660f2020-03-04 23:37:06 +0000451def _fetch_tryjobs(changelist, buildbucket_host, patchset=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000452 """Fetches tryjobs from buildbucket.
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000453
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000454 Returns list of buildbucket.v2.Build with the try jobs for the changelist.
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000455 """
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +0000456 fields = ['id', 'builder', 'status', 'createTime', 'tags']
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000457 request = {
458 'predicate': {
459 'gerritChanges': [changelist.GetGerritChange(patchset)],
460 },
461 'fields': ','.join('builds.*.' + field for field in fields),
462 }
tandrii221ab252016-10-06 08:12:04 -0700463
Edward Lemur5b929a42019-10-21 17:57:39 +0000464 authenticator = auth.Authenticator()
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000465 if authenticator.has_cached_credentials():
466 http = authenticator.authorize(httplib2.Http())
467 else:
vapiera7fbd5a2016-06-16 09:17:49 -0700468 print('Warning: Some results might be missing because %s' %
469 # Get the message on how to login.
Edward Lemurba5bc992019-09-23 22:59:17 +0000470 (auth.LoginRequiredError().message,))
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000471 http = httplib2.Http()
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000472 http.force_exception_to_status_code = True
473
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000474 response = _call_buildbucket(http, buildbucket_host, 'SearchBuilds', request)
475 return response.get('builds', [])
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000476
Edward Lemur45768512020-03-02 19:03:14 +0000477
Edward Lemur5b929a42019-10-21 17:57:39 +0000478def _fetch_latest_builds(changelist, buildbucket_host, latest_patchset=None):
Quinten Yearsley983111f2019-09-26 17:18:48 +0000479 """Fetches builds from the latest patchset that has builds (within
480 the last few patchsets).
481
482 Args:
Quinten Yearsley983111f2019-09-26 17:18:48 +0000483 changelist (Changelist): The CL to fetch builds for
484 buildbucket_host (str): Buildbucket host, e.g. "cr-buildbucket.appspot.com"
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +0000485 lastest_patchset(int|NoneType): the patchset to start fetching builds from.
486 If None (default), starts with the latest available patchset.
Quinten Yearsley983111f2019-09-26 17:18:48 +0000487 Returns:
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000488 A tuple (builds, patchset) where builds is a list of buildbucket.v2.Build,
489 and patchset is the patchset number where those builds came from.
Quinten Yearsley983111f2019-09-26 17:18:48 +0000490 """
491 assert buildbucket_host
492 assert changelist.GetIssue(), 'CL must be uploaded first'
493 assert changelist.GetCodereviewServer(), 'CL must be uploaded first'
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +0000494 if latest_patchset is None:
495 assert changelist.GetMostRecentPatchset()
496 ps = changelist.GetMostRecentPatchset()
497 else:
498 assert latest_patchset > 0, latest_patchset
499 ps = latest_patchset
500
Quinten Yearsley983111f2019-09-26 17:18:48 +0000501 min_ps = max(1, ps - 5)
502 while ps >= min_ps:
Quinten Yearsley777660f2020-03-04 23:37:06 +0000503 builds = _fetch_tryjobs(changelist, buildbucket_host, patchset=ps)
Quinten Yearsley983111f2019-09-26 17:18:48 +0000504 if len(builds):
505 return builds, ps
506 ps -= 1
507 return [], 0
508
509
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +0000510def _filter_failed_for_retry(all_builds):
511 """Returns a list of buckets/builders that are worth retrying.
Quinten Yearsley983111f2019-09-26 17:18:48 +0000512
513 Args:
Quinten Yearsley777660f2020-03-04 23:37:06 +0000514 all_builds (list): Builds, in the format returned by _fetch_tryjobs,
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000515 i.e. a list of buildbucket.v2.Builds which includes status and builder
516 info.
Quinten Yearsley983111f2019-09-26 17:18:48 +0000517
518 Returns:
Edward Lemur45768512020-03-02 19:03:14 +0000519 A dict {(proj, bucket): [builders]}. This is the same format accepted by
Quinten Yearsley777660f2020-03-04 23:37:06 +0000520 _trigger_tryjobs.
Quinten Yearsley983111f2019-09-26 17:18:48 +0000521 """
Edward Lemur45768512020-03-02 19:03:14 +0000522 grouped = {}
523 for build in all_builds:
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +0000524 builder = build['builder']
Edward Lemur45768512020-03-02 19:03:14 +0000525 key = (builder['project'], builder['bucket'], builder['builder'])
526 grouped.setdefault(key, []).append(build)
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +0000527
Edward Lemur45768512020-03-02 19:03:14 +0000528 jobs = []
529 for (project, bucket, builder), builds in grouped.items():
530 if 'triggered' in builder:
531 print('WARNING: Not scheduling %s. Triggered bots require an initial job '
532 'from a parent. Please schedule a manual job for the parent '
533 'instead.')
Andrii Shyshkalov2cbae8a2019-10-11 21:30:27 +0000534 continue
535 if any(b['status'] in ('STARTED', 'SCHEDULED') for b in builds):
536 # Don't retry if any are running.
537 continue
Edward Lemur45768512020-03-02 19:03:14 +0000538 # If builder had several builds, retry only if the last one failed.
539 # This is a bit different from CQ, which would re-use *any* SUCCESS-full
540 # build, but in case of retrying failed jobs retrying a flaky one makes
541 # sense.
542 builds = sorted(builds, key=lambda b: b['createTime'])
543 if builds[-1]['status'] not in ('FAILURE', 'INFRA_FAILURE'):
544 continue
545 # Don't retry experimental build previously triggered by CQ.
546 if any(t['key'] == 'cq_experimental' and t['value'] == 'true'
547 for t in builds[-1]['tags']):
548 continue
549 jobs.append((project, bucket, builder))
550
551 # Sort the jobs to make testing easier.
552 return sorted(jobs)
Quinten Yearsley983111f2019-09-26 17:18:48 +0000553
554
Quinten Yearsley777660f2020-03-04 23:37:06 +0000555def _print_tryjobs(options, builds):
556 """Prints nicely result of _fetch_tryjobs."""
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000557 if not builds:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000558 print('No tryjobs scheduled.')
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000559 return
560
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000561 longest_builder = max(len(b['builder']['builder']) for b in builds)
562 name_fmt = '{builder:<%d}' % longest_builder
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000563 if options.print_master:
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000564 longest_bucket = max(len(b['builder']['bucket']) for b in builds)
565 name_fmt = ('{bucket:>%d} ' % longest_bucket) + name_fmt
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000566
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000567 builds_by_status = {}
568 for b in builds:
569 builds_by_status.setdefault(b['status'], []).append({
570 'id': b['id'],
571 'name': name_fmt.format(
572 builder=b['builder']['builder'], bucket=b['builder']['bucket']),
573 })
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000574
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000575 sort_key = lambda b: (b['name'], b['id'])
576
577 def print_builds(title, builds, fmt=None, color=None):
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000578 """Pop matching builds from `builds` dict and print them."""
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000579 if not builds:
580 return
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000581
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000582 fmt = fmt or '{name} https://ci.chromium.org/b/{id}'
tandrii@chromium.org6cf98c82016-03-15 11:56:00 +0000583 if not options.color or color is None:
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000584 colorize = lambda x: x
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000585 else:
586 colorize = lambda x: '%s%s%s' % (color, x, Fore.RESET)
587
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000588 print(colorize(title))
589 for b in sorted(builds, key=sort_key):
590 print(' ', colorize(fmt.format(**b)))
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000591
592 total = len(builds)
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000593 print_builds(
594 'Successes:', builds_by_status.pop('SUCCESS', []), color=Fore.GREEN)
595 print_builds(
596 'Infra Failures:', builds_by_status.pop('INFRA_FAILURE', []),
597 color=Fore.MAGENTA)
598 print_builds('Failures:', builds_by_status.pop('FAILURE', []), color=Fore.RED)
599 print_builds('Canceled:', builds_by_status.pop('CANCELED', []), fmt='{name}',
600 color=Fore.MAGENTA)
601 print_builds('Started:', builds_by_status.pop('STARTED', []))
602 print_builds(
603 'Scheduled:', builds_by_status.pop('SCHEDULED', []), fmt='{name} id={id}')
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000604 # The last section is just in case buildbucket API changes OR there is a bug.
Edward Lemurbaaf6be2019-10-09 18:00:44 +0000605 print_builds(
606 'Other:', sum(builds_by_status.values(), []), fmt='{name} id={id}')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000607 print('Total: %d tryjobs' % total)
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +0000608
609
Aiden Bennerc08566e2018-10-03 17:52:42 +0000610def _ComputeDiffLineRanges(files, upstream_commit):
611 """Gets the changed line ranges for each file since upstream_commit.
612
613 Parses a git diff on provided files and returns a dict that maps a file name
614 to an ordered list of range tuples in the form (start_line, count).
615 Ranges are in the same format as a git diff.
616 """
617 # If files is empty then diff_output will be a full diff.
618 if len(files) == 0:
619 return {}
620
Aiden Benner6c18a1a2018-11-23 20:18:23 +0000621 # Take the git diff and find the line ranges where there are changes.
Jamie Madill3671a6a2019-10-24 15:13:21 +0000622 diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, files, allow_prefix=True)
Aiden Bennerc08566e2018-10-03 17:52:42 +0000623 diff_output = RunGit(diff_cmd)
624
625 pattern = r'(?:^diff --git a/(?:.*) b/(.*))|(?:^@@.*\+(.*) @@)'
626 # 2 capture groups
627 # 0 == fname of diff file
628 # 1 == 'diff_start,diff_count' or 'diff_start'
629 # will match each of
630 # diff --git a/foo.foo b/foo.py
631 # @@ -12,2 +14,3 @@
632 # @@ -12,2 +17 @@
633 # running re.findall on the above string with pattern will give
634 # [('foo.py', ''), ('', '14,3'), ('', '17')]
635
636 curr_file = None
637 line_diffs = {}
638 for match in re.findall(pattern, diff_output, flags=re.MULTILINE):
639 if match[0] != '':
640 # Will match the second filename in diff --git a/a.py b/b.py.
641 curr_file = match[0]
642 line_diffs[curr_file] = []
643 else:
644 # Matches +14,3
645 if ',' in match[1]:
646 diff_start, diff_count = match[1].split(',')
647 else:
648 # Single line changes are of the form +12 instead of +12,1.
649 diff_start = match[1]
650 diff_count = 1
651
652 diff_start = int(diff_start)
653 diff_count = int(diff_count)
654
655 # If diff_count == 0 this is a removal we can ignore.
656 line_diffs[curr_file].append((diff_start, diff_count))
657
658 return line_diffs
659
660
Aiden Benner99b0ccb2018-11-20 19:53:31 +0000661def _FindYapfConfigFile(fpath, yapf_config_cache, top_dir=None):
Aiden Bennerc08566e2018-10-03 17:52:42 +0000662 """Checks if a yapf file is in any parent directory of fpath until top_dir.
663
Aiden Benner99b0ccb2018-11-20 19:53:31 +0000664 Recursively checks parent directories to find yapf file and if no yapf file
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000665 is found returns None. Uses yapf_config_cache as a cache for previously found
666 configs.
Aiden Bennerc08566e2018-10-03 17:52:42 +0000667 """
Aiden Benner99b0ccb2018-11-20 19:53:31 +0000668 fpath = os.path.abspath(fpath)
Aiden Bennerc08566e2018-10-03 17:52:42 +0000669 # Return result if we've already computed it.
670 if fpath in yapf_config_cache:
671 return yapf_config_cache[fpath]
672
Aiden Benner99b0ccb2018-11-20 19:53:31 +0000673 parent_dir = os.path.dirname(fpath)
674 if os.path.isfile(fpath):
675 ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir)
Aiden Bennerc08566e2018-10-03 17:52:42 +0000676 else:
Aiden Benner99b0ccb2018-11-20 19:53:31 +0000677 # Otherwise fpath is a directory
678 yapf_file = os.path.join(fpath, YAPF_CONFIG_FILENAME)
679 if os.path.isfile(yapf_file):
680 ret = yapf_file
681 elif fpath == top_dir or parent_dir == fpath:
682 # If we're at the top level directory, or if we're at root
683 # there is no provided style.
684 ret = None
685 else:
686 # Otherwise recurse on the current directory.
687 ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir)
Aiden Bennerc08566e2018-10-03 17:52:42 +0000688 yapf_config_cache[fpath] = ret
689 return ret
690
691
Brian Sheedyb4307d52019-12-02 19:18:17 +0000692def _GetYapfIgnorePatterns(top_dir):
693 """Returns all patterns in the .yapfignore file.
Brian Sheedy59b06a82019-10-14 17:03:29 +0000694
695 yapf is supposed to handle the ignoring of files listed in .yapfignore itself,
696 but this functionality appears to break when explicitly passing files to
697 yapf for formatting. According to
698 https://github.com/google/yapf/blob/master/README.rst#excluding-files-from-formatting-yapfignore,
699 the .yapfignore file should be in the directory that yapf is invoked from,
700 which we assume to be the top level directory in this case.
701
702 Args:
703 top_dir: The top level directory for the repository being formatted.
704
705 Returns:
Brian Sheedyb4307d52019-12-02 19:18:17 +0000706 A set of all fnmatch patterns to be ignored.
Brian Sheedy59b06a82019-10-14 17:03:29 +0000707 """
708 yapfignore_file = os.path.join(top_dir, '.yapfignore')
Brian Sheedyb4307d52019-12-02 19:18:17 +0000709 ignore_patterns = set()
Brian Sheedy59b06a82019-10-14 17:03:29 +0000710 if not os.path.exists(yapfignore_file):
Brian Sheedyb4307d52019-12-02 19:18:17 +0000711 return ignore_patterns
Brian Sheedy59b06a82019-10-14 17:03:29 +0000712
Brian Sheedyb4307d52019-12-02 19:18:17 +0000713 with open(yapfignore_file) as f:
714 for line in f.readlines():
715 stripped_line = line.strip()
716 # Comments and blank lines should be ignored.
717 if stripped_line.startswith('#') or stripped_line == '':
718 continue
719 ignore_patterns.add(stripped_line)
720 return ignore_patterns
721
722
723def _FilterYapfIgnoredFiles(filepaths, patterns):
724 """Filters out any filepaths that match any of the given patterns.
725
726 Args:
727 filepaths: An iterable of strings containing filepaths to filter.
728 patterns: An iterable of strings containing fnmatch patterns to filter on.
729
730 Returns:
731 A list of strings containing all the elements of |filepaths| that did not
732 match any of the patterns in |patterns|.
733 """
734 # Not inlined so that tests can use the same implementation.
735 return [f for f in filepaths
736 if not any(fnmatch.fnmatch(f, p) for p in patterns)]
Brian Sheedy59b06a82019-10-14 17:03:29 +0000737
738
Aaron Gable13101a62018-02-09 13:20:41 -0800739def print_stats(args):
maruel@chromium.org49e3d802012-07-18 23:54:45 +0000740 """Prints statistics about the change to the user."""
741 # --no-ext-diff is broken in some versions of Git, so try to work around
742 # this by overriding the environment (but there is still a problem if the
743 # git config key "diff.external" is used).
thestig@chromium.org8b0553c2014-02-11 00:33:37 +0000744 env = GetNoGitPagerEnv()
maruel@chromium.org49e3d802012-07-18 23:54:45 +0000745 if 'GIT_EXTERNAL_DIFF' in env:
746 del env['GIT_EXTERNAL_DIFF']
iannucci@chromium.org79540052012-10-19 23:15:26 +0000747
maruel@chromium.org49e3d802012-07-18 23:54:45 +0000748 return subprocess2.call(
Aaron Gable13101a62018-02-09 13:20:41 -0800749 ['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] + args,
Edward Lemur0db01f02019-11-12 22:01:51 +0000750 env=env)
maruel@chromium.org49e3d802012-07-18 23:54:45 +0000751
752
sheyang@google.com6ebaf782015-05-12 19:17:54 +0000753class BuildbucketResponseException(Exception):
754 pass
755
756
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000757class Settings(object):
758 def __init__(self):
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000759 self.cc = None
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000760 self.root = None
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000761 self.tree_status_url = None
762 self.viewvc_url = None
763 self.updated = False
ukai@chromium.orge8077812012-02-03 03:41:46 +0000764 self.is_gerrit = None
bauerb@chromium.org54b400c2016-01-14 10:08:25 +0000765 self.squash_gerrit_uploads = None
tandrii@chromium.org28253532016-04-14 13:46:56 +0000766 self.gerrit_skip_ensure_authenticated = None
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000767 self.git_editor = None
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000768 self.format_full_by_default = None
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000769
Edward Lemur26964072020-02-19 19:18:51 +0000770 def _LazyUpdateIfNeeded(self):
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000771 """Updates the settings from a codereview.settings file, if available."""
Edward Lemur26964072020-02-19 19:18:51 +0000772 if self.updated:
773 return
pgervais@chromium.org87884cc2014-01-03 22:23:41 +0000774
Edward Lemur26964072020-02-19 19:18:51 +0000775 # The only value that actually changes the behavior is
776 # autoupdate = "false". Everything else means "true".
777 autoupdate = (
778 scm.GIT.GetConfig(self.GetRoot(), 'rietveld.autoupdate', '').lower())
779
780 cr_settings_file = FindCodereviewSettingsFile()
781 if autoupdate != 'false' and cr_settings_file:
782 LoadCodereviewSettingsFromFile(cr_settings_file)
783 cr_settings_file.close()
784
785 self.updated = True
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000786
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000787 @staticmethod
788 def GetRelativeRoot():
Edward Lesmescba46082020-03-25 00:29:06 +0000789 return RunGit(['rev-parse', '--show-cdup']).strip()
thestig@chromium.org8b0553c2014-02-11 00:33:37 +0000790
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000791 def GetRoot(self):
thestig@chromium.org7a54e812014-02-11 19:57:22 +0000792 if self.root is None:
793 self.root = os.path.abspath(self.GetRelativeRoot())
794 return self.root
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000795
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000796 def GetTreeStatusUrl(self, error_ok=False):
797 if not self.tree_status_url:
Edward Lemur26964072020-02-19 19:18:51 +0000798 self.tree_status_url = self._GetConfig('rietveld.tree-status-url')
799 if self.tree_status_url is None and not error_ok:
800 DieWithError(
801 'You must configure your tree status URL by running '
802 '"git cl config".')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000803 return self.tree_status_url
804
805 def GetViewVCUrl(self):
806 if not self.viewvc_url:
Edward Lemur26964072020-02-19 19:18:51 +0000807 self.viewvc_url = self._GetConfig('rietveld.viewvc-url')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000808 return self.viewvc_url
809
rmistry@google.com90752582014-01-14 21:04:50 +0000810 def GetBugPrefix(self):
Edward Lemur26964072020-02-19 19:18:51 +0000811 return self._GetConfig('rietveld.bug-prefix')
rmistry@google.com78948ed2015-07-08 23:09:57 +0000812
rmistry@google.com5626a922015-02-26 14:03:30 +0000813 def GetRunPostUploadHook(self):
Edward Lemur61ea3072018-12-01 00:34:36 +0000814 run_post_upload_hook = self._GetConfig(
Edward Lemur26964072020-02-19 19:18:51 +0000815 'rietveld.run-post-upload-hook')
rmistry@google.com5626a922015-02-26 14:03:30 +0000816 return run_post_upload_hook == "True"
817
bauerb@chromium.orgae6df352011-04-06 17:40:39 +0000818 def GetDefaultCCList(self):
Edward Lemur26964072020-02-19 19:18:51 +0000819 return self._GetConfig('rietveld.cc')
tyoshino@chromium.orgc1737d02013-05-29 14:17:28 +0000820
bauerb@chromium.org54b400c2016-01-14 10:08:25 +0000821 def GetSquashGerritUploads(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000822 """Returns True if uploads to Gerrit should be squashed by default."""
bauerb@chromium.org54b400c2016-01-14 10:08:25 +0000823 if self.squash_gerrit_uploads is None:
tandriia60502f2016-06-20 02:01:53 -0700824 self.squash_gerrit_uploads = self.GetSquashGerritUploadsOverride()
Edward Lemur26964072020-02-19 19:18:51 +0000825 if self.squash_gerrit_uploads is None:
826 # Default is squash now (http://crbug.com/611892#c23).
827 self.squash_gerrit_uploads = self._GetConfig(
828 'gerrit.squash-uploads').lower() != 'false'
bauerb@chromium.org54b400c2016-01-14 10:08:25 +0000829 return self.squash_gerrit_uploads
830
tandriia60502f2016-06-20 02:01:53 -0700831 def GetSquashGerritUploadsOverride(self):
832 """Return True or False if codereview.settings should be overridden.
833
834 Returns None if no override has been defined.
835 """
836 # See also http://crbug.com/611892#c23
Edward Lemur26964072020-02-19 19:18:51 +0000837 result = self._GetConfig('gerrit.override-squash-uploads').lower()
tandriia60502f2016-06-20 02:01:53 -0700838 if result == 'true':
839 return True
840 if result == 'false':
841 return False
842 return None
843
tandrii@chromium.org28253532016-04-14 13:46:56 +0000844 def GetGerritSkipEnsureAuthenticated(self):
845 """Return True if EnsureAuthenticated should not be done for Gerrit
846 uploads."""
847 if self.gerrit_skip_ensure_authenticated is None:
Edward Lemur26964072020-02-19 19:18:51 +0000848 self.gerrit_skip_ensure_authenticated = self._GetConfig(
849 'gerrit.skip-ensure-authenticated').lower() == 'true'
tandrii@chromium.org28253532016-04-14 13:46:56 +0000850 return self.gerrit_skip_ensure_authenticated
851
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000852 def GetGitEditor(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000853 """Returns the editor specified in the git config, or None if none is."""
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000854 if self.git_editor is None:
Raul Tambre5a525872019-02-12 19:08:08 +0000855 # Git requires single quotes for paths with spaces. We need to replace
856 # them with double quotes for Windows to treat such paths as a single
857 # path.
Edward Lemur26964072020-02-19 19:18:51 +0000858 self.git_editor = self._GetConfig('core.editor').replace('\'', '"')
jbroman@chromium.org615a2622013-05-03 13:20:14 +0000859 return self.git_editor or None
860
thestig@chromium.org44202a22014-03-11 19:22:18 +0000861 def GetLintRegex(self):
Edward Lemur26964072020-02-19 19:18:51 +0000862 return self._GetConfig('rietveld.cpplint-regex', DEFAULT_LINT_REGEX)
thestig@chromium.org44202a22014-03-11 19:22:18 +0000863
864 def GetLintIgnoreRegex(self):
Edward Lemur26964072020-02-19 19:18:51 +0000865 return self._GetConfig(
866 'rietveld.cpplint-ignore-regex', DEFAULT_LINT_IGNORE_REGEX)
thestig@chromium.org44202a22014-03-11 19:22:18 +0000867
Jamie Madilldc4d19e2019-10-24 21:50:02 +0000868 def GetFormatFullByDefault(self):
869 if self.format_full_by_default is None:
870 result = (
871 RunGit(['config', '--bool', 'rietveld.format-full-by-default'],
872 error_ok=True).strip())
873 self.format_full_by_default = (result == 'true')
874 return self.format_full_by_default
875
Edward Lemur26964072020-02-19 19:18:51 +0000876 def _GetConfig(self, key, default=''):
877 self._LazyUpdateIfNeeded()
878 return scm.GIT.GetConfig(self.GetRoot(), key, default)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000879
880
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +0000881class _CQState(object):
Andrii Shyshkalov0e889b72019-07-15 22:28:48 +0000882 """Enum for states of CL with respect to CQ."""
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +0000883 NONE = 'none'
884 DRY_RUN = 'dry_run'
885 COMMIT = 'commit'
886
887 ALL_STATES = [NONE, DRY_RUN, COMMIT]
888
889
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000890class _ParsedIssueNumberArgument(object):
Edward Lemurf38bc172019-09-03 21:02:13 +0000891 def __init__(self, issue=None, patchset=None, hostname=None):
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000892 self.issue = issue
893 self.patchset = patchset
894 self.hostname = hostname
895
896 @property
897 def valid(self):
898 return self.issue is not None
899
900
Edward Lemurf38bc172019-09-03 21:02:13 +0000901def ParseIssueNumberArgument(arg):
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000902 """Parses the issue argument and returns _ParsedIssueNumberArgument."""
903 fail_result = _ParsedIssueNumberArgument()
904
Edward Lemur678a6842019-10-03 22:25:05 +0000905 if isinstance(arg, int):
906 return _ParsedIssueNumberArgument(issue=arg)
907 if not isinstance(arg, basestring):
908 return fail_result
909
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000910 if arg.isdigit():
Edward Lemurf38bc172019-09-03 21:02:13 +0000911 return _ParsedIssueNumberArgument(issue=int(arg))
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000912 if not arg.startswith('http'):
913 return fail_result
Aaron Gableaee6c852017-06-26 12:49:01 -0700914
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000915 url = gclient_utils.UpgradeToHttps(arg)
916 try:
Edward Lemur79d4f992019-11-11 23:49:02 +0000917 parsed_url = urllib.parse.urlparse(url)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000918 except ValueError:
919 return fail_result
Andrii Shyshkalov28d840e2017-04-10 15:45:09 +0200920
Edward Lemur678a6842019-10-03 22:25:05 +0000921 # Gerrit's new UI is https://domain/c/project/+/<issue_number>[/[patchset]]
922 # But old GWT UI is https://domain/#/c/project/+/<issue_number>[/[patchset]]
923 # Short urls like https://domain/<issue_number> can be used, but don't allow
924 # specifying the patchset (you'd 404), but we allow that here.
925 if parsed_url.path == '/':
926 part = parsed_url.fragment
927 else:
928 part = parsed_url.path
929
930 match = re.match(
931 r'(/c(/.*/\+)?)?/(?P<issue>\d+)(/(?P<patchset>\d+)?/?)?$', part)
932 if not match:
933 return fail_result
934
935 issue = int(match.group('issue'))
936 patchset = match.group('patchset')
937 return _ParsedIssueNumberArgument(
938 issue=issue,
939 patchset=int(patchset) if patchset else None,
940 hostname=parsed_url.netloc)
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +0000941
942
Andrii Shyshkalovb07575f2018-10-16 06:16:21 +0000943def _create_description_from_log(args):
944 """Pulls out the commit log to use as a base for the CL description."""
945 log_args = []
946 if len(args) == 1 and not args[0].endswith('.'):
947 log_args = [args[0] + '..']
948 elif len(args) == 1 and args[0].endswith('...'):
949 log_args = [args[0][:-1]]
950 elif len(args) == 2:
951 log_args = [args[0] + '..' + args[1]]
952 else:
953 log_args = args[:] # Hope for the best!
Edward Lemura12175c2020-03-09 16:58:26 +0000954 return RunGit(['log', '--pretty=format:%s%n%n%b'] + log_args)
Andrii Shyshkalovb07575f2018-10-16 06:16:21 +0000955
956
Aaron Gablea45ee112016-11-22 15:14:38 -0800957class GerritChangeNotExists(Exception):
tandriic2405f52016-10-10 08:13:15 -0700958 def __init__(self, issue, url):
959 self.issue = issue
960 self.url = url
Aaron Gablea45ee112016-11-22 15:14:38 -0800961 super(GerritChangeNotExists, self).__init__()
tandriic2405f52016-10-10 08:13:15 -0700962
963 def __str__(self):
Aaron Gablea45ee112016-11-22 15:14:38 -0800964 return 'change %s at %s does not exist or you have no access to it' % (
tandriic2405f52016-10-10 08:13:15 -0700965 self.issue, self.url)
966
967
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +0100968_CommentSummary = collections.namedtuple(
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000969 '_CommentSummary', ['date', 'message', 'sender', 'autogenerated',
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +0100970 # TODO(tandrii): these two aren't known in Gerrit.
971 'approval', 'disapproval'])
972
973
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000974class Changelist(object):
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000975 """Changelist works with one changelist in local branch.
976
tandrii@chromium.org8930b3d2016-04-13 14:47:02 +0000977 Notes:
978 * Not safe for concurrent multi-{thread,process} use.
979 * Caches values from current branch. Therefore, re-use after branch change
tandrii5d48c322016-08-18 16:19:37 -0700980 with great care.
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000981 """
982
Edward Lemur125d60a2019-09-13 18:25:41 +0000983 def __init__(self, branchref=None, issue=None, codereview_host=None):
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000984 """Create a new ChangeList instance.
985
Edward Lemurf38bc172019-09-03 21:02:13 +0000986 **kwargs will be passed directly to Gerrit implementation.
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000987 """
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000988 # Poke settings so we get the "configure your server" message if necessary.
maruel@chromium.org379d07a2011-11-30 14:58:10 +0000989 global settings
990 if not settings:
991 # Happens when git_cl.py is used as a utility library.
992 settings = Settings()
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +0000993
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000994 self.branchref = branchref
995 if self.branchref:
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +0000996 assert branchref.startswith('refs/heads/')
Edward Lemur85153282020-02-14 22:06:29 +0000997 self.branch = scm.GIT.ShortBranchName(self.branchref)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +0000998 else:
999 self.branch = None
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001000 self.upstream_branch = None
maruel@chromium.org1033efd2013-07-23 23:25:09 +00001001 self.lookedup_issue = False
1002 self.issue = issue or None
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001003 self.description = None
maruel@chromium.org1033efd2013-07-23 23:25:09 +00001004 self.lookedup_patchset = False
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001005 self.patchset = None
bauerb@chromium.orgae6df352011-04-06 17:40:39 +00001006 self.cc = None
Daniel Cheng7227d212017-11-17 08:12:37 -08001007 self.more_cc = []
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001008 self._remote = None
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001009 self._cached_remote_url = (False, None) # (is_cached, value)
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00001010
Edward Lemur125d60a2019-09-13 18:25:41 +00001011 # Lazily cached values.
1012 self._gerrit_host = None # e.g. chromium-review.googlesource.com
1013 self._gerrit_server = None # e.g. https://chromium-review.googlesource.com
1014 # Map from change number (issue) to its detail cache.
1015 self._detail_cache = {}
1016
1017 if codereview_host is not None:
1018 assert not codereview_host.startswith('https://'), codereview_host
1019 self._gerrit_host = codereview_host
1020 self._gerrit_server = 'https://%s' % codereview_host
bauerb@chromium.orgae6df352011-04-06 17:40:39 +00001021
1022 def GetCCList(self):
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001023 """Returns the users cc'd on this CL.
bauerb@chromium.orgae6df352011-04-06 17:40:39 +00001024
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001025 The return value is a string suitable for passing to git cl with the --cc
1026 flag.
bauerb@chromium.orgae6df352011-04-06 17:40:39 +00001027 """
1028 if self.cc is None:
tyoshino@chromium.org99918ab2013-09-30 06:17:28 +00001029 base_cc = settings.GetDefaultCCList()
Daniel Cheng7227d212017-11-17 08:12:37 -08001030 more_cc = ','.join(self.more_cc)
bauerb@chromium.orgae6df352011-04-06 17:40:39 +00001031 self.cc = ','.join(filter(None, (base_cc, more_cc))) or ''
1032 return self.cc
1033
Edward Lesmescba46082020-03-25 00:29:06 +00001034 def GetCCListWithoutDefault(self):
1035 """Return the users cc'd on this CL excluding default ones."""
1036 if self.cc is None:
1037 self.cc = ','.join(self.more_cc)
1038 return self.cc
1039
Daniel Cheng7227d212017-11-17 08:12:37 -08001040 def ExtendCC(self, more_cc):
1041 """Extends the list of users to cc on this CL based on the changed files."""
1042 self.more_cc.extend(more_cc)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001043
1044 def GetBranch(self):
1045 """Returns the short branch name, e.g. 'master'."""
1046 if not self.branch:
Edward Lemur85153282020-02-14 22:06:29 +00001047 branchref = scm.GIT.GetBranchRef(settings.GetRoot())
szager@chromium.orgd62c61f2014-10-20 22:33:21 +00001048 if not branchref:
1049 return None
1050 self.branchref = branchref
Edward Lemur85153282020-02-14 22:06:29 +00001051 self.branch = scm.GIT.ShortBranchName(self.branchref)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001052 return self.branch
1053
1054 def GetBranchRef(self):
1055 """Returns the full branch name, e.g. 'refs/heads/master'."""
1056 self.GetBranch() # Poke the lazy loader.
1057 return self.branchref
1058
Edward Lesmescba46082020-03-25 00:29:06 +00001059 def ClearBranch(self):
1060 """Clears cached branch data of this object."""
1061 self.branch = self.branchref = None
1062
Edward Lemur85153282020-02-14 22:06:29 +00001063 def _GitGetBranchConfigValue(self, key, default=None):
1064 return scm.GIT.GetBranchConfig(
1065 settings.GetRoot(), self.GetBranch(), key, default)
tandrii5d48c322016-08-18 16:19:37 -07001066
Edward Lemur85153282020-02-14 22:06:29 +00001067 def _GitSetBranchConfigValue(self, key, value):
1068 action = 'set %s to %r' % (key, value)
1069 if not value:
1070 action = 'unset %s' % key
1071 assert self.GetBranch(), 'a branch is needed to ' + action
1072 return scm.GIT.SetBranchConfig(
1073 settings.GetRoot(), self.GetBranch(), key, value)
tandrii5d48c322016-08-18 16:19:37 -07001074
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001075 @staticmethod
1076 def FetchUpstreamTuple(branch):
pgervais@chromium.orgd6617f32013-11-19 00:34:54 +00001077 """Returns a tuple containing remote and remote ref,
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001078 e.g. 'origin', 'refs/heads/master'
1079 """
Edward Lemur15a9b8c2020-02-13 00:52:30 +00001080 remote, upstream_branch = scm.GIT.FetchUpstreamTuple(
1081 settings.GetRoot(), branch)
1082 if not remote or not upstream_branch:
1083 DieWithError(
1084 'Unable to determine default branch to diff against.\n'
1085 'Either pass complete "git diff"-style arguments, like\n'
1086 ' git cl upload origin/master\n'
1087 'or verify this branch is set up to track another \n'
1088 '(via the --track argument to "git checkout -b ...").')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001089
1090 return remote, upstream_branch
1091
thestig@chromium.org8b0553c2014-02-11 00:33:37 +00001092 def GetCommonAncestorWithUpstream(self):
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +00001093 upstream_branch = self.GetUpstreamBranch()
Edward Lesmescba46082020-03-25 00:29:06 +00001094 if not BranchExists(upstream_branch):
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +00001095 DieWithError('The upstream for the current branch (%s) does not exist '
1096 'anymore.\nPlease fix it and try again.' % self.GetBranch())
iannucci@chromium.org9e849272014-04-04 00:31:55 +00001097 return git_common.get_or_create_merge_base(self.GetBranch(),
pgervais@chromium.org8ba38ff2015-06-11 21:41:25 +00001098 upstream_branch)
thestig@chromium.org8b0553c2014-02-11 00:33:37 +00001099
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001100 def GetUpstreamBranch(self):
1101 if self.upstream_branch is None:
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001102 remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
Raul Tambrefe1dbe12019-05-02 04:43:57 +00001103 if remote != '.':
mmoss@chromium.orge7585452014-08-24 01:41:11 +00001104 upstream_branch = upstream_branch.replace('refs/heads/',
1105 'refs/remotes/%s/' % remote)
1106 upstream_branch = upstream_branch.replace('refs/branch-heads/',
1107 'refs/remotes/branch-heads/')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001108 self.upstream_branch = upstream_branch
1109 return self.upstream_branch
1110
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001111 def GetRemoteBranch(self):
jmbaker@chromium.orga2cbbbb2012-03-22 20:40:40 +00001112 if not self._remote:
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001113 remote, branch = None, self.GetBranch()
1114 seen_branches = set()
1115 while branch not in seen_branches:
1116 seen_branches.add(branch)
1117 remote, branch = self.FetchUpstreamTuple(branch)
Edward Lemur85153282020-02-14 22:06:29 +00001118 branch = scm.GIT.ShortBranchName(branch)
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001119 if remote != '.' or branch.startswith('refs/remotes'):
1120 break
1121 else:
jmbaker@chromium.orga2cbbbb2012-03-22 20:40:40 +00001122 remotes = RunGit(['remote'], error_ok=True).split()
1123 if len(remotes) == 1:
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001124 remote, = remotes
jmbaker@chromium.orga2cbbbb2012-03-22 20:40:40 +00001125 elif 'origin' in remotes:
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001126 remote = 'origin'
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08001127 logging.warn('Could not determine which remote this change is '
1128 'associated with, so defaulting to "%s".' % self._remote)
jmbaker@chromium.orga2cbbbb2012-03-22 20:40:40 +00001129 else:
1130 logging.warn('Could not determine which remote this change is '
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08001131 'associated with.')
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001132 branch = 'HEAD'
1133 if branch.startswith('refs/remotes'):
1134 self._remote = (remote, branch)
mmoss@chromium.orge7585452014-08-24 01:41:11 +00001135 elif branch.startswith('refs/branch-heads/'):
1136 self._remote = (remote, branch.replace('refs/', 'refs/remotes/'))
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001137 else:
1138 self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch))
jmbaker@chromium.orga2cbbbb2012-03-22 20:40:40 +00001139 return self._remote
1140
Edward Lesmescba46082020-03-25 00:29:06 +00001141 def GitSanityChecks(self, upstream_git_obj):
1142 """Checks git repo status and ensures diff is from local commits."""
1143
1144 if upstream_git_obj is None:
1145 if self.GetBranch() is None:
1146 print('ERROR: Unable to determine current branch (detached HEAD?)',
1147 file=sys.stderr)
1148 else:
1149 print('ERROR: No upstream branch.', file=sys.stderr)
1150 return False
1151
1152 # Verify the commit we're diffing against is in our current branch.
1153 upstream_sha = RunGit(['rev-parse', '--verify', upstream_git_obj]).strip()
1154 common_ancestor = RunGit(['merge-base', upstream_sha, 'HEAD']).strip()
1155 if upstream_sha != common_ancestor:
1156 print('ERROR: %s is not in the current branch. You may need to rebase '
1157 'your tracking branch' % upstream_sha, file=sys.stderr)
1158 return False
1159
1160 # List the commits inside the diff, and verify they are all local.
1161 commits_in_diff = RunGit(
1162 ['rev-list', '^%s' % upstream_sha, 'HEAD']).splitlines()
1163 code, remote_branch = RunGitWithCode(['config', 'gitcl.remotebranch'])
1164 remote_branch = remote_branch.strip()
1165 if code != 0:
1166 _, remote_branch = self.GetRemoteBranch()
1167
1168 commits_in_remote = RunGit(
1169 ['rev-list', '^%s' % upstream_sha, remote_branch]).splitlines()
1170
1171 common_commits = set(commits_in_diff) & set(commits_in_remote)
1172 if common_commits:
1173 print('ERROR: Your diff contains %d commits already in %s.\n'
1174 'Run "git log --oneline %s..HEAD" to get a list of commits in '
1175 'the diff. If you are using a custom git flow, you can override'
1176 ' the reference used for this check with "git config '
1177 'gitcl.remotebranch <git-ref>".' % (
1178 len(common_commits), remote_branch, upstream_git_obj),
1179 file=sys.stderr)
1180 return False
1181 return True
1182
1183 def GetGitBaseUrlFromConfig(self):
1184 """Return the configured base URL from branch.<branchname>.baseurl.
1185
1186 Returns None if it is not set.
1187 """
1188 return self._GitGetBranchConfigValue('base-url')
1189
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001190 def GetRemoteUrl(self):
1191 """Return the configured remote URL, e.g. 'git://example.org/foo.git/'.
1192
1193 Returns None if there is no remote.
1194 """
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001195 is_cached, value = self._cached_remote_url
1196 if is_cached:
1197 return value
1198
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00001199 remote, _ = self.GetRemoteBranch()
Edward Lemur26964072020-02-19 19:18:51 +00001200 url = scm.GIT.GetConfig(settings.GetRoot(), 'remote.%s.url' % remote, '')
dyen@chromium.org2a13d4f2014-06-13 00:06:37 +00001201
Edward Lemur298f2cf2019-02-22 21:40:39 +00001202 # Check if the remote url can be parsed as an URL.
Edward Lemur79d4f992019-11-11 23:49:02 +00001203 host = urllib.parse.urlparse(url).netloc
Edward Lemur298f2cf2019-02-22 21:40:39 +00001204 if host:
1205 self._cached_remote_url = (True, url)
1206 return url
1207
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001208 # If it cannot be parsed as an url, assume it is a local directory,
1209 # probably a git cache.
Edward Lemur298f2cf2019-02-22 21:40:39 +00001210 logging.warning('"%s" doesn\'t appear to point to a git host. '
1211 'Interpreting it as a local directory.', url)
1212 if not os.path.isdir(url):
1213 logging.error(
Josip906bfde2020-01-31 22:38:49 +00001214 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
1215 'but it doesn\'t exist.',
1216 {'remote': remote, 'branch': self.GetBranch(), 'url': url})
Edward Lemur298f2cf2019-02-22 21:40:39 +00001217 return None
1218
1219 cache_path = url
Edward Lemur26964072020-02-19 19:18:51 +00001220 url = scm.GIT.GetConfig(url, 'remote.%s.url' % remote, '')
Edward Lemur298f2cf2019-02-22 21:40:39 +00001221
Edward Lemur79d4f992019-11-11 23:49:02 +00001222 host = urllib.parse.urlparse(url).netloc
Edward Lemur298f2cf2019-02-22 21:40:39 +00001223 if not host:
1224 logging.error(
1225 'Remote "%(remote)s" for branch "%(branch)s" points to '
1226 '"%(cache_path)s", but it is misconfigured.\n'
1227 '"%(cache_path)s" must be a git repo and must have a remote named '
1228 '"%(remote)s" pointing to the git host.', {
1229 'remote': remote,
1230 'cache_path': cache_path,
1231 'branch': self.GetBranch()})
1232 return None
1233
Andrii Shyshkalov81db1d52018-08-23 02:17:41 +00001234 self._cached_remote_url = (True, url)
dyen@chromium.org2a13d4f2014-06-13 00:06:37 +00001235 return url
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001236
tandrii@chromium.org87985d22016-03-24 17:33:33 +00001237 def GetIssue(self):
maruel@chromium.org52424302012-08-29 15:14:30 +00001238 """Returns the issue number as a int or None if not set."""
tandrii@chromium.org87985d22016-03-24 17:33:33 +00001239 if self.issue is None and not self.lookedup_issue:
Edward Lesmescba46082020-03-25 00:29:06 +00001240 self.issue = self._GitGetBranchConfigValue(self.IssueConfigKey())
Edward Lemur85153282020-02-14 22:06:29 +00001241 if self.issue is not None:
1242 self.issue = int(self.issue)
maruel@chromium.org1033efd2013-07-23 23:25:09 +00001243 self.lookedup_issue = True
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001244 return self.issue
1245
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +00001246 def GetIssueURL(self, short=False):
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001247 """Get the URL for a particular issue."""
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001248 issue = self.GetIssue()
1249 if not issue:
dbeam@chromium.org015fd3d2013-06-18 19:02:50 +00001250 return None
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +00001251 server = self.GetCodereviewServer()
1252 if short:
1253 server = _KNOWN_GERRIT_TO_SHORT_URLS.get(server, server)
1254 return '%s/%s' % (server, issue)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001255
Edward Lemur6c6827c2020-02-06 21:15:18 +00001256 def FetchDescription(self, pretty=False):
1257 assert self.GetIssue(), 'issue is required to query Gerrit'
1258
Edward Lemur9aa1a962020-02-25 00:58:38 +00001259 if self.description is None:
Edward Lemur6c6827c2020-02-06 21:15:18 +00001260 data = self._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'])
1261 current_rev = data['current_revision']
1262 self.description = data['revisions'][current_rev]['commit']['message']
Edward Lemur6c6827c2020-02-06 21:15:18 +00001263
1264 if not pretty:
1265 return self.description
1266
1267 # Set width to 72 columns + 2 space indent.
1268 wrapper = textwrap.TextWrapper(width=74, replace_whitespace=True)
1269 wrapper.initial_indent = wrapper.subsequent_indent = ' '
1270 lines = self.description.splitlines()
1271 return '\n'.join([wrapper.fill(line) for line in lines])
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001272
1273 def GetPatchset(self):
maruel@chromium.org52424302012-08-29 15:14:30 +00001274 """Returns the patchset number as a int or None if not set."""
maruel@chromium.org1033efd2013-07-23 23:25:09 +00001275 if self.patchset is None and not self.lookedup_patchset:
Edward Lesmescba46082020-03-25 00:29:06 +00001276 self.patchset = self._GitGetBranchConfigValue(self.PatchsetConfigKey())
Edward Lemur85153282020-02-14 22:06:29 +00001277 if self.patchset is not None:
1278 self.patchset = int(self.patchset)
maruel@chromium.org1033efd2013-07-23 23:25:09 +00001279 self.lookedup_patchset = True
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001280 return self.patchset
1281
Edward Lemur9aa1a962020-02-25 00:58:38 +00001282 def GetAuthor(self):
1283 return scm.GIT.GetConfig(settings.GetRoot(), 'user.email')
1284
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001285 def SetPatchset(self, patchset):
tandrii5d48c322016-08-18 16:19:37 -07001286 """Set this branch's patchset. If patchset=0, clears the patchset."""
1287 assert self.GetBranch()
1288 if not patchset:
maruel@chromium.org1033efd2013-07-23 23:25:09 +00001289 self.patchset = None
tandrii5d48c322016-08-18 16:19:37 -07001290 else:
1291 self.patchset = int(patchset)
Edward Lesmescba46082020-03-25 00:29:06 +00001292 self._GitSetBranchConfigValue(
1293 self.PatchsetConfigKey(), str(self.patchset))
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001294
tandrii@chromium.orga342c922016-03-16 07:08:25 +00001295 def SetIssue(self, issue=None):
tandrii5d48c322016-08-18 16:19:37 -07001296 """Set this branch's issue. If issue isn't given, clears the issue."""
1297 assert self.GetBranch()
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001298 if issue:
tandrii5d48c322016-08-18 16:19:37 -07001299 issue = int(issue)
Edward Lesmescba46082020-03-25 00:29:06 +00001300 self._GitSetBranchConfigValue(
1301 self.IssueConfigKey(), str(issue))
maruel@chromium.org1033efd2013-07-23 23:25:09 +00001302 self.issue = issue
Edward Lemur125d60a2019-09-13 18:25:41 +00001303 codereview_server = self.GetCodereviewServer()
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001304 if codereview_server:
tandrii5d48c322016-08-18 16:19:37 -07001305 self._GitSetBranchConfigValue(
Edward Lesmescba46082020-03-25 00:29:06 +00001306 self.CodereviewServerConfigKey(),
1307 codereview_server)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001308 else:
tandrii5d48c322016-08-18 16:19:37 -07001309 # Reset all of these just to be clean.
1310 reset_suffixes = [
1311 'last-upload-hash',
Edward Lesmescba46082020-03-25 00:29:06 +00001312 self.IssueConfigKey(),
1313 self.PatchsetConfigKey(),
1314 self.CodereviewServerConfigKey(),
1315 ] + self._PostUnsetIssueProperties()
tandrii5d48c322016-08-18 16:19:37 -07001316 for prop in reset_suffixes:
Edward Lemur85153282020-02-14 22:06:29 +00001317 try:
1318 self._GitSetBranchConfigValue(prop, None)
1319 except subprocess2.CalledProcessError:
1320 pass
Aaron Gableca01e2c2017-07-19 11:16:02 -07001321 msg = RunGit(['log', '-1', '--format=%B']).strip()
1322 if msg and git_footers.get_footer_change_id(msg):
1323 print('WARNING: The change patched into this branch has a Change-Id. '
1324 'Removing it.')
1325 RunGit(['commit', '--amend', '-m',
1326 git_footers.remove_footer(msg, 'Change-Id')])
Edward Lemurf38bc172019-09-03 21:02:13 +00001327 self.lookedup_issue = True
maruel@chromium.org1033efd2013-07-23 23:25:09 +00001328 self.issue = None
tandrii@chromium.org9b7fd712016-06-01 13:45:20 +00001329 self.patchset = None
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001330
Edward Lemur2c62b332020-03-12 22:12:33 +00001331 def GetAffectedFiles(self, upstream):
maruel@chromium.org2b38e9c2011-10-19 00:04:35 +00001332 try:
Edward Lemur2c62b332020-03-12 22:12:33 +00001333 return [f for _, f in scm.GIT.CaptureStatus(settings.GetRoot(), upstream)]
maruel@chromium.org2b38e9c2011-10-19 00:04:35 +00001334 except subprocess2.CalledProcessError:
1335 DieWithError(
pgervais@chromium.orgd6617f32013-11-19 00:34:54 +00001336 ('\nFailed to diff against upstream branch %s\n\n'
maruel@chromium.org2b38e9c2011-10-19 00:04:35 +00001337 'This branch probably doesn\'t exist anymore. To reset the\n'
1338 'tracking branch, please run\n'
stip7a3dd352016-09-22 17:32:28 -07001339 ' git branch --set-upstream-to origin/master %s\n'
1340 'or replace origin/master with the relevant branch') %
Edward Lemur2c62b332020-03-12 22:12:33 +00001341 (upstream, self.GetBranch()))
bauerb@chromium.org6fb99c62011-04-18 15:57:28 +00001342
dsansomee2d6fd92016-09-08 00:10:47 -07001343 def UpdateDescription(self, description, force=False):
Edward Lemur6c6827c2020-02-06 21:15:18 +00001344 assert self.GetIssue(), 'issue is required to update description'
1345
1346 if gerrit_util.HasPendingChangeEdit(
1347 self._GetGerritHost(), self._GerritChangeIdentifier()):
1348 if not force:
1349 confirm_or_exit(
1350 'The description cannot be modified while the issue has a pending '
1351 'unpublished edit. Either publish the edit in the Gerrit web UI '
1352 'or delete it.\n\n', action='delete the unpublished edit')
1353
1354 gerrit_util.DeletePendingChangeEdit(
1355 self._GetGerritHost(), self._GerritChangeIdentifier())
1356 gerrit_util.SetCommitMessage(
1357 self._GetGerritHost(), self._GerritChangeIdentifier(),
1358 description, notify='NONE')
1359
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001360 self.description = description
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001361
Edward Lemur75526302020-02-27 22:31:05 +00001362 def _GetCommonPresubmitArgs(self, verbose, upstream):
Edward Lemur227d5102020-02-25 23:45:35 +00001363 args = [
Edward Lemur227d5102020-02-25 23:45:35 +00001364 '--root', settings.GetRoot(),
1365 '--upstream', upstream,
1366 ]
1367
1368 args.extend(['--verbose'] * verbose)
1369
Edward Lemur99df04e2020-03-05 19:39:43 +00001370 author = self.GetAuthor()
1371 gerrit_url = self.GetCodereviewServer()
Edward Lemur227d5102020-02-25 23:45:35 +00001372 issue = self.GetIssue()
1373 patchset = self.GetPatchset()
Edward Lemur99df04e2020-03-05 19:39:43 +00001374 if author:
1375 args.extend(['--author', author])
1376 if gerrit_url:
1377 args.extend(['--gerrit_url', gerrit_url])
Edward Lemur227d5102020-02-25 23:45:35 +00001378 if issue:
1379 args.extend(['--issue', str(issue)])
1380 if patchset:
1381 args.extend(['--patchset', str(patchset)])
Edward Lemur227d5102020-02-25 23:45:35 +00001382
Edward Lemur75526302020-02-27 22:31:05 +00001383 return args
1384
1385 def RunHook(
1386 self, committing, may_prompt, verbose, parallel, upstream, description,
1387 all_files):
1388 """Calls sys.exit() if the hook fails; returns a HookResults otherwise."""
1389 args = self._GetCommonPresubmitArgs(verbose, upstream)
1390 args.append('--commit' if committing else '--upload')
Edward Lemur227d5102020-02-25 23:45:35 +00001391 if may_prompt:
1392 args.append('--may_prompt')
1393 if parallel:
1394 args.append('--parallel')
1395 if all_files:
1396 args.append('--all_files')
1397
1398 with gclient_utils.temporary_file() as description_file:
1399 with gclient_utils.temporary_file() as json_output:
Edward Lemur1a83da12020-03-04 21:18:36 +00001400
1401 gclient_utils.FileWrite(description_file, description)
Edward Lemur227d5102020-02-25 23:45:35 +00001402 args.extend(['--json_output', json_output])
1403 args.extend(['--description_file', description_file])
1404
1405 start = time_time()
1406 p = subprocess2.Popen(['vpython', PRESUBMIT_SUPPORT] + args)
1407 exit_code = p.wait()
1408 metrics.collector.add_repeated('sub_commands', {
1409 'command': 'presubmit',
1410 'execution_time': time_time() - start,
1411 'exit_code': exit_code,
1412 })
1413
1414 if exit_code:
1415 sys.exit(exit_code)
1416
1417 json_results = gclient_utils.FileRead(json_output)
1418 return json.loads(json_results)
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001419
Edward Lemur75526302020-02-27 22:31:05 +00001420 def RunPostUploadHook(self, verbose, upstream, description):
1421 args = self._GetCommonPresubmitArgs(verbose, upstream)
1422 args.append('--post_upload')
1423
1424 with gclient_utils.temporary_file() as description_file:
Edward Lemur1a83da12020-03-04 21:18:36 +00001425 gclient_utils.FileWrite(description_file, description)
Edward Lemur75526302020-02-27 22:31:05 +00001426 args.extend(['--description_file', description_file])
1427 p = subprocess2.Popen(['vpython', PRESUBMIT_SUPPORT] + args)
1428 p.wait()
1429
Edward Lemur5a644f82020-03-18 16:44:57 +00001430 def _GetDescriptionForUpload(self, options, git_diff_args, files):
1431 # Get description message for upload.
1432 if self.GetIssue():
1433 description = self.FetchDescription()
1434 elif options.message:
1435 description = options.message
1436 else:
1437 description = _create_description_from_log(git_diff_args)
1438 if options.title and options.squash:
Edward Lesmes0dd54822020-03-26 18:24:25 +00001439 description = options.title + '\n\n' + description
Edward Lemur5a644f82020-03-18 16:44:57 +00001440
1441 # Extract bug number from branch name.
1442 bug = options.bug
1443 fixed = options.fixed
1444 match = re.match(r'(?P<type>bug|fix(?:e[sd])?)[_-]?(?P<bugnum>\d+)',
1445 self.GetBranch())
1446 if not bug and not fixed and match:
1447 if match.group('type') == 'bug':
1448 bug = match.group('bugnum')
1449 else:
1450 fixed = match.group('bugnum')
1451
1452 change_description = ChangeDescription(description, bug, fixed)
1453
1454 # Set the reviewer list now so that presubmit checks can access it.
1455 if options.reviewers or options.tbrs or options.add_owners_to:
1456 change_description.update_reviewers(
1457 options.reviewers, options.tbrs, options.add_owners_to, files,
1458 self.GetAuthor())
1459
1460 return change_description
1461
1462 def _GetTitleForUpload(self, options):
1463 # When not squashing, just return options.title.
1464 if not options.squash:
1465 return options.title
1466
1467 # On first upload, patchset title is always this string, while options.title
1468 # gets converted to first line of message.
1469 if not self.GetIssue():
1470 return 'Initial upload'
1471
1472 # When uploading subsequent patchsets, options.message is taken as the title
1473 # if options.title is not provided.
1474 if options.title:
1475 return options.title
1476 if options.message:
1477 return options.message.strip()
1478
1479 # Use the subject of the last commit as title by default.
Edward Lesmescba46082020-03-25 00:29:06 +00001480 title = RunGit(
1481 ['show', '-s', '--format=%s', 'HEAD']).strip()
Edward Lemur5a644f82020-03-18 16:44:57 +00001482 if options.force:
1483 return title
Edward Lesmesae3586b2020-03-23 21:21:14 +00001484 user_title = gclient_utils.AskForData('Title for patchset [%s]: ' % title)
1485 return user_title or title
Edward Lemur5a644f82020-03-18 16:44:57 +00001486
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001487 def CMDUpload(self, options, git_diff_args, orig_args):
1488 """Uploads a change to codereview."""
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001489 custom_cl_base = None
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001490 if git_diff_args:
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02001491 custom_cl_base = base_branch = git_diff_args[0]
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001492 else:
1493 if self.GetBranch() is None:
1494 DieWithError('Can\'t upload from detached HEAD state. Get on a branch!')
1495
1496 # Default to diffing against common ancestor of upstream branch
1497 base_branch = self.GetCommonAncestorWithUpstream()
1498 git_diff_args = [base_branch, 'HEAD']
1499
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001500 # Fast best-effort checks to abort before running potentially expensive
1501 # hooks if uploading is likely to fail anyway. Passing these checks does
1502 # not guarantee that uploading will not fail.
Edward Lemur125d60a2019-09-13 18:25:41 +00001503 self.EnsureAuthenticated(force=options.force)
1504 self.EnsureCanUploadPatchset(force=options.force)
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001505
1506 # Apply watchlists on upload.
Edward Lemur2c62b332020-03-12 22:12:33 +00001507 watchlist = watchlists.Watchlists(settings.GetRoot())
1508 files = self.GetAffectedFiles(base_branch)
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001509 if not options.bypass_watchlists:
Daniel Cheng7227d212017-11-17 08:12:37 -08001510 self.ExtendCC(watchlist.GetWatchersForPaths(files))
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001511
Edward Lemur5a644f82020-03-18 16:44:57 +00001512 change_desc = self._GetDescriptionForUpload(options, git_diff_args, files)
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001513 if not options.bypass_hooks:
Edward Lemur2c62b332020-03-12 22:12:33 +00001514 hook_results = self.RunHook(
1515 committing=False,
1516 may_prompt=not options.force,
1517 verbose=options.verbose,
1518 parallel=options.parallel,
1519 upstream=base_branch,
Edward Lemur5a644f82020-03-18 16:44:57 +00001520 description=change_desc.description,
Edward Lemur2c62b332020-03-12 22:12:33 +00001521 all_files=False)
Edward Lemur227d5102020-02-25 23:45:35 +00001522 self.ExtendCC(hook_results['more_cc'])
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001523
Aaron Gable13101a62018-02-09 13:20:41 -08001524 print_stats(git_diff_args)
Edward Lemura12175c2020-03-09 16:58:26 +00001525 ret = self.CMDUploadChange(
Edward Lemur5a644f82020-03-18 16:44:57 +00001526 options, git_diff_args, custom_cl_base, change_desc)
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001527 if not ret:
Edward Lemur85153282020-02-14 22:06:29 +00001528 self._GitSetBranchConfigValue(
Edward Lesmescba46082020-03-25 00:29:06 +00001529 'last-upload-hash', RunGit(['rev-parse', 'HEAD']).strip())
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001530 # Run post upload hooks, if specified.
1531 if settings.GetRunPostUploadHook():
Edward Lemur5a644f82020-03-18 16:44:57 +00001532 self.RunPostUploadHook(
1533 options.verbose, base_branch, change_desc.description)
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001534
1535 # Upload all dependencies if specified.
1536 if options.dependencies:
vapiera7fbd5a2016-06-16 09:17:49 -07001537 print()
1538 print('--dependencies has been specified.')
1539 print('All dependent local branches will be re-uploaded.')
1540 print()
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001541 # Remove the dependencies flag from args so that we do not end up in a
1542 # loop.
1543 orig_args.remove('--dependencies')
1544 ret = upload_branch_deps(self, orig_args)
1545 return ret
1546
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001547 def SetCQState(self, new_state):
Quinten Yearsleyfc5fd922017-05-31 11:50:52 -07001548 """Updates the CQ state for the latest patchset.
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00001549
1550 Issue must have been already uploaded and known.
1551 """
1552 assert new_state in _CQState.ALL_STATES
1553 assert self.GetIssue()
qyearsley1fdfcb62016-10-24 13:22:03 -07001554 try:
Edward Lemur125d60a2019-09-13 18:25:41 +00001555 vote_map = {
1556 _CQState.NONE: 0,
1557 _CQState.DRY_RUN: 1,
1558 _CQState.COMMIT: 2,
1559 }
1560 labels = {'Commit-Queue': vote_map[new_state]}
1561 notify = False if new_state == _CQState.DRY_RUN else None
1562 gerrit_util.SetReview(
1563 self._GetGerritHost(), self._GerritChangeIdentifier(),
1564 labels=labels, notify=notify)
qyearsley1fdfcb62016-10-24 13:22:03 -07001565 return 0
1566 except KeyboardInterrupt:
1567 raise
1568 except:
Quinten Yearsleyfc5fd922017-05-31 11:50:52 -07001569 print('WARNING: Failed to %s.\n'
qyearsley1fdfcb62016-10-24 13:22:03 -07001570 'Either:\n'
Quinten Yearsleyfc5fd922017-05-31 11:50:52 -07001571 ' * Your project has no CQ,\n'
1572 ' * You don\'t have permission to change the CQ state,\n'
1573 ' * There\'s a bug in this code (see stack trace below).\n'
1574 'Consider specifying which bots to trigger manually or asking your '
1575 'project owners for permissions or contacting Chrome Infra at:\n'
1576 'https://www.chromium.org/infra\n\n' %
1577 ('cancel CQ' if new_state == _CQState.NONE else 'trigger CQ'))
qyearsley1fdfcb62016-10-24 13:22:03 -07001578 # Still raise exception so that stack trace is printed.
1579 raise
1580
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001581 def _GetGerritHost(self):
1582 # Lazy load of configs.
1583 self.GetCodereviewServer()
tandriie32e3ea2016-06-22 02:52:48 -07001584 if self._gerrit_host and '.' not in self._gerrit_host:
1585 # Abbreviated domain like "chromium" instead of chromium.googlesource.com.
1586 # This happens for internal stuff http://crbug.com/614312.
Edward Lemur79d4f992019-11-11 23:49:02 +00001587 parsed = urllib.parse.urlparse(self.GetRemoteUrl())
tandriie32e3ea2016-06-22 02:52:48 -07001588 if parsed.scheme == 'sso':
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001589 print('WARNING: using non-https URLs for remote is likely broken\n'
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001590 ' Your current remote is: %s' % self.GetRemoteUrl())
tandriie32e3ea2016-06-22 02:52:48 -07001591 self._gerrit_host = '%s.googlesource.com' % self._gerrit_host
1592 self._gerrit_server = 'https://%s' % self._gerrit_host
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001593 return self._gerrit_host
1594
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001595 def _GetGitHost(self):
1596 """Returns git host to be used when uploading change to Gerrit."""
Edward Lemur298f2cf2019-02-22 21:40:39 +00001597 remote_url = self.GetRemoteUrl()
1598 if not remote_url:
1599 return None
Edward Lemur79d4f992019-11-11 23:49:02 +00001600 return urllib.parse.urlparse(remote_url).netloc
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001601
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001602 def GetCodereviewServer(self):
1603 if not self._gerrit_server:
1604 # If we're on a branch then get the server potentially associated
1605 # with that branch.
Edward Lemur85153282020-02-14 22:06:29 +00001606 if self.GetIssue() and self.GetBranch():
tandrii5d48c322016-08-18 16:19:37 -07001607 self._gerrit_server = self._GitGetBranchConfigValue(
Edward Lesmescba46082020-03-25 00:29:06 +00001608 self.CodereviewServerConfigKey())
tandrii5d48c322016-08-18 16:19:37 -07001609 if self._gerrit_server:
Edward Lemur79d4f992019-11-11 23:49:02 +00001610 self._gerrit_host = urllib.parse.urlparse(self._gerrit_server).netloc
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001611 if not self._gerrit_server:
1612 # We assume repo to be hosted on Gerrit, and hence Gerrit server
1613 # has "-review" suffix for lowest level subdomain.
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001614 parts = self._GetGitHost().split('.')
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001615 parts[0] = parts[0] + '-review'
1616 self._gerrit_host = '.'.join(parts)
1617 self._gerrit_server = 'https://%s' % self._gerrit_host
1618 return self._gerrit_server
1619
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00001620 def _GetGerritProject(self):
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001621 """Returns Gerrit project name based on remote git URL."""
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00001622 remote_url = self.GetRemoteUrl()
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001623 if remote_url is None:
Josip906bfde2020-01-31 22:38:49 +00001624 logging.warning('can\'t detect Gerrit project.')
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00001625 return None
Edward Lemur79d4f992019-11-11 23:49:02 +00001626 project = urllib.parse.urlparse(remote_url).path.strip('/')
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001627 if project.endswith('.git'):
1628 project = project[:-len('.git')]
Andrii Shyshkalov1e828672018-08-23 22:34:37 +00001629 # *.googlesource.com hosts ensure that Git/Gerrit projects don't start with
1630 # 'a/' prefix, because 'a/' prefix is used to force authentication in
1631 # gitiles/git-over-https protocol. E.g.,
1632 # https://chromium.googlesource.com/a/v8/v8 refers to the same repo/project
1633 # as
1634 # https://chromium.googlesource.com/v8/v8
1635 if project.startswith('a/'):
1636 project = project[len('a/'):]
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001637 return project
1638
Andrii Shyshkalovd06cc782018-08-23 17:24:19 +00001639 def _GerritChangeIdentifier(self):
1640 """Handy method for gerrit_util.ChangeIdentifier for a given CL.
1641
1642 Not to be confused by value of "Change-Id:" footer.
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00001643 If Gerrit project can be determined, this will speed up Gerrit HTTP API RPC.
Andrii Shyshkalovd06cc782018-08-23 17:24:19 +00001644 """
Andrii Shyshkalov2d0e03c2018-08-25 04:18:09 +00001645 project = self._GetGerritProject()
1646 if project:
1647 return gerrit_util.ChangeIdentifier(project, self.GetIssue())
1648 # Fall back on still unique, but less efficient change number.
1649 return str(self.GetIssue())
Andrii Shyshkalovd06cc782018-08-23 17:24:19 +00001650
Edward Lesmescba46082020-03-25 00:29:06 +00001651 @classmethod
1652 def IssueConfigKey(cls):
1653 return 'gerritissue'
1654
1655 @classmethod
1656 def PatchsetConfigKey(cls):
1657 return 'gerritpatchset'
1658
1659 @classmethod
1660 def CodereviewServerConfigKey(cls):
1661 return 'gerritserver'
1662
Andrii Shyshkalov2f8e9242017-01-23 19:20:19 +01001663 def EnsureAuthenticated(self, force, refresh=None):
tandrii@chromium.org9e6c3a52016-04-12 14:13:08 +00001664 """Best effort check that user is authenticated with Gerrit server."""
tandrii@chromium.org28253532016-04-14 13:46:56 +00001665 if settings.GetGerritSkipEnsureAuthenticated():
1666 # For projects with unusual authentication schemes.
1667 # See http://crbug.com/603378.
1668 return
Vadim Shtayurab250ec12018-10-04 00:21:08 +00001669
1670 # Check presence of cookies only if using cookies-based auth method.
1671 cookie_auth = gerrit_util.Authenticator.get()
1672 if not isinstance(cookie_auth, gerrit_util.CookiesAuthenticator):
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001673 return
Vadim Shtayurab250ec12018-10-04 00:21:08 +00001674
Florian Mayerae510e82020-01-30 21:04:48 +00001675 remote_url = self.GetRemoteUrl()
1676 if remote_url is None:
Josip906bfde2020-01-31 22:38:49 +00001677 logging.warning('invalid remote')
Florian Mayerae510e82020-01-30 21:04:48 +00001678 return
1679 if urllib.parse.urlparse(remote_url).scheme != 'https':
Josip906bfde2020-01-31 22:38:49 +00001680 logging.warning('Ignoring branch %(branch)s with non-https remote '
1681 '%(remote)s', {
1682 'branch': self.branch,
1683 'remote': self.GetRemoteUrl()
1684 })
Daniel Chengcf6269b2019-05-18 01:02:12 +00001685 return
1686
Vadim Shtayurab250ec12018-10-04 00:21:08 +00001687 # Lazy-loader to identify Gerrit and Git hosts.
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001688 self.GetCodereviewServer()
1689 git_host = self._GetGitHost()
Edward Lemur298f2cf2019-02-22 21:40:39 +00001690 assert self._gerrit_server and self._gerrit_host and git_host
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001691
1692 gerrit_auth = cookie_auth.get_auth_header(self._gerrit_host)
1693 git_auth = cookie_auth.get_auth_header(git_host)
1694 if gerrit_auth and git_auth:
1695 if gerrit_auth == git_auth:
1696 return
Andrii Shyshkalov354e1d22017-06-09 19:31:33 +02001697 all_gsrc = cookie_auth.get_auth_header('d0esN0tEx1st.googlesource.com')
Raul Tambre80ee78e2019-05-06 22:41:05 +00001698 print(
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001699 'WARNING: You have different credentials for Gerrit and git hosts:\n'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001700 ' %s\n'
1701 ' %s\n'
Andrii Shyshkalov51acef92017-04-11 17:19:59 +02001702 ' Consider running the following command:\n'
1703 ' git cl creds-check\n'
Andrii Shyshkalov354e1d22017-06-09 19:31:33 +02001704 ' %s\n'
Raul Tambre80ee78e2019-05-06 22:41:05 +00001705 ' %s' %
Andrii Shyshkalov51acef92017-04-11 17:19:59 +02001706 (git_host, self._gerrit_host,
Andrii Shyshkalov354e1d22017-06-09 19:31:33 +02001707 ('Hint: delete creds for .googlesource.com' if all_gsrc else ''),
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001708 cookie_auth.get_new_password_message(git_host)))
1709 if not force:
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001710 confirm_or_exit('If you know what you are doing', action='continue')
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001711 return
1712 else:
1713 missing = (
Anna Henningsen4e891442017-07-06 21:40:58 +02001714 ([] if gerrit_auth else [self._gerrit_host]) +
1715 ([] if git_auth else [git_host]))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +00001716 DieWithError('Credentials for the following hosts are required:\n'
1717 ' %s\n'
1718 'These are read from %s (or legacy %s)\n'
1719 '%s' % (
1720 '\n '.join(missing),
1721 cookie_auth.get_gitcookies_path(),
1722 cookie_auth.get_netrc_path(),
1723 cookie_auth.get_new_password_message(git_host)))
1724
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001725 def EnsureCanUploadPatchset(self, force):
Andrii Shyshkalov3e631422017-02-16 17:46:44 +01001726 if not self.GetIssue():
1727 return
1728
Andrii Shyshkalov3e631422017-02-16 17:46:44 +01001729 status = self._GetChangeDetail()['status']
1730 if status in ('MERGED', 'ABANDONED'):
1731 DieWithError('Change %s has been %s, new uploads are not allowed' %
1732 (self.GetIssueURL(),
1733 'submitted' if status == 'MERGED' else 'abandoned'))
1734
Vadim Shtayurab250ec12018-10-04 00:21:08 +00001735 # TODO(vadimsh): For some reason the chunk of code below was skipped if
1736 # 'is_gce' is True. I'm just refactoring it to be 'skip if not cookies'.
1737 # Apparently this check is not very important? Otherwise get_auth_email
1738 # could have been added to other implementations of Authenticator.
1739 cookies_auth = gerrit_util.Authenticator.get()
1740 if not isinstance(cookies_auth, gerrit_util.CookiesAuthenticator):
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001741 return
Vadim Shtayurab250ec12018-10-04 00:21:08 +00001742
1743 cookies_user = cookies_auth.get_auth_email(self._GetGerritHost())
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001744 if self.GetIssueOwner() == cookies_user:
1745 return
1746 logging.debug('change %s owner is %s, cookies user is %s',
1747 self.GetIssue(), self.GetIssueOwner(), cookies_user)
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001748 # Maybe user has linked accounts or something like that,
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001749 # so ask what Gerrit thinks of this user.
1750 details = gerrit_util.GetAccountDetails(self._GetGerritHost(), 'self')
1751 if details['email'] == self.GetIssueOwner():
1752 return
1753 if not force:
Quinten Yearsley0c62da92017-05-31 13:39:42 -07001754 print('WARNING: Change %s is owned by %s, but you authenticate to Gerrit '
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001755 'as %s.\n'
1756 'Uploading may fail due to lack of permissions.' %
1757 (self.GetIssue(), self.GetIssueOwner(), details['email']))
1758 confirm_or_exit(action='upload')
1759
Edward Lesmescba46082020-03-25 00:29:06 +00001760 def _PostUnsetIssueProperties(self):
1761 """Which branch-specific properties to erase when unsetting issue."""
1762 return ['gerritsquashhash']
1763
1764 def GetGerritObjForPresubmit(self):
1765 return presubmit_support.GerritAccessor(self._GetGerritHost())
1766
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001767 def GetStatus(self):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001768 """Applies a rough heuristic to give a simple summary of an issue's review
tandrii@chromium.org013a2802016-03-29 09:52:33 +00001769 or CQ status, assuming adherence to a common workflow.
1770
1771 Returns None if no issue for this branch, or one of the following keywords:
Aaron Gable9ab38c62017-04-06 14:36:33 -07001772 * 'error' - error from review tool (including deleted issues)
1773 * 'unsent' - no reviewers added
1774 * 'waiting' - waiting for review
1775 * 'reply' - waiting for uploader to reply to review
1776 * 'lgtm' - Code-Review label has been set
Andrii Shyshkalov0e889b72019-07-15 22:28:48 +00001777 * 'dry-run' - dry-running in the CQ
1778 * 'commit' - in the CQ
Aaron Gable9ab38c62017-04-06 14:36:33 -07001779 * 'closed' - successfully submitted or abandoned
tandrii@chromium.org013a2802016-03-29 09:52:33 +00001780 """
1781 if not self.GetIssue():
1782 return None
1783
1784 try:
Aaron Gable9ab38c62017-04-06 14:36:33 -07001785 data = self._GetChangeDetail([
1786 'DETAILED_LABELS', 'CURRENT_REVISION', 'SUBMITTABLE'])
Edward Lemur79d4f992019-11-11 23:49:02 +00001787 except GerritChangeNotExists:
tandrii@chromium.org013a2802016-03-29 09:52:33 +00001788 return 'error'
1789
tandrii@chromium.org5e1bf382016-05-17 08:43:24 +00001790 if data['status'] in ('ABANDONED', 'MERGED'):
tandrii@chromium.org013a2802016-03-29 09:52:33 +00001791 return 'closed'
1792
Andrii Shyshkalovb8268ca2019-04-03 23:33:44 +00001793 cq_label = data['labels'].get('Commit-Queue', {})
1794 max_cq_vote = 0
1795 for vote in cq_label.get('all', []):
1796 max_cq_vote = max(max_cq_vote, vote.get('value', 0))
1797 if max_cq_vote == 2:
Aaron Gable9ab38c62017-04-06 14:36:33 -07001798 return 'commit'
Andrii Shyshkalovb8268ca2019-04-03 23:33:44 +00001799 if max_cq_vote == 1:
1800 return 'dry-run'
tandrii@chromium.org013a2802016-03-29 09:52:33 +00001801
Aaron Gable9ab38c62017-04-06 14:36:33 -07001802 if data['labels'].get('Code-Review', {}).get('approved'):
1803 return 'lgtm'
tandrii@chromium.org013a2802016-03-29 09:52:33 +00001804
1805 if not data.get('reviewers', {}).get('REVIEWER', []):
1806 return 'unsent'
1807
Andrii Shyshkalov33e88a42017-01-27 14:45:30 +01001808 owner = data['owner'].get('_account_id')
Edward Lemur79d4f992019-11-11 23:49:02 +00001809 messages = sorted(data.get('messages', []), key=lambda m: m.get('date'))
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00001810 while messages:
1811 m = messages.pop()
1812 if m.get('tag', '').startswith('autogenerated:cq:'):
Andrii Shyshkalov33e88a42017-01-27 14:45:30 +01001813 # Ignore replies from CQ.
1814 continue
Andrii Shyshkalov8aa9d622020-03-10 19:15:35 +00001815 if m.get('author', {}).get('_account_id') == owner:
Aaron Gable9ab38c62017-04-06 14:36:33 -07001816 # Most recent message was by owner.
1817 return 'waiting'
1818 else:
tandrii@chromium.org013a2802016-03-29 09:52:33 +00001819 # Some reply from non-owner.
1820 return 'reply'
Aaron Gable9ab38c62017-04-06 14:36:33 -07001821
1822 # Somehow there are no messages even though there are reviewers.
1823 return 'unsent'
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001824
1825 def GetMostRecentPatchset(self):
Edward Lemur6c6827c2020-02-06 21:15:18 +00001826 if not self.GetIssue():
1827 return None
1828
tandrii@chromium.org013a2802016-03-29 09:52:33 +00001829 data = self._GetChangeDetail(['CURRENT_REVISION'])
Aaron Gablee8856ee2017-12-07 12:41:46 -08001830 patchset = data['revisions'][data['current_revision']]['_number']
1831 self.SetPatchset(patchset)
1832 return patchset
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001833
Aaron Gable636b13f2017-07-14 10:42:48 -07001834 def AddComment(self, message, publish=None):
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00001835 gerrit_util.SetReview(
1836 self._GetGerritHost(), self._GerritChangeIdentifier(),
1837 msg=message, ready=publish)
Andrii Shyshkalov625986d2017-03-16 00:24:37 +01001838
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07001839 def GetCommentsSummary(self, readable=True):
Andrii Shyshkalov5a0cf202017-03-17 16:14:59 +01001840 # DETAILED_ACCOUNTS is to get emails in accounts.
Quinten Yearsley0e617c02019-02-20 00:37:03 +00001841 # CURRENT_REVISION is included to get the latest patchset so that
1842 # only the robot comments from the latest patchset can be shown.
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07001843 messages = self._GetChangeDetail(
Quinten Yearsley0e617c02019-02-20 00:37:03 +00001844 options=['MESSAGES', 'DETAILED_ACCOUNTS',
1845 'CURRENT_REVISION']).get('messages', [])
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07001846 file_comments = gerrit_util.GetChangeComments(
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00001847 self._GetGerritHost(), self._GerritChangeIdentifier())
Quinten Yearsley0e617c02019-02-20 00:37:03 +00001848 robot_file_comments = gerrit_util.GetChangeRobotComments(
1849 self._GetGerritHost(), self._GerritChangeIdentifier())
1850
1851 # Add the robot comments onto the list of comments, but only
Andrii Shyshkalovaeee6a82019-10-09 21:56:25 +00001852 # keep those that are from the latest patchset.
Quinten Yearsley0e617c02019-02-20 00:37:03 +00001853 latest_patch_set = self.GetMostRecentPatchset()
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001854 for path, robot_comments in robot_file_comments.items():
Quinten Yearsley0e617c02019-02-20 00:37:03 +00001855 line_comments = file_comments.setdefault(path, [])
1856 line_comments.extend(
1857 [c for c in robot_comments if c['patch_set'] == latest_patch_set])
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07001858
1859 # Build dictionary of file comments for easy access and sorting later.
1860 # {author+date: {path: {patchset: {line: url+message}}}}
1861 comments = collections.defaultdict(
1862 lambda: collections.defaultdict(lambda: collections.defaultdict(dict)))
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00001863 for path, line_comments in file_comments.items():
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07001864 for comment in line_comments:
Quinten Yearsley0e617c02019-02-20 00:37:03 +00001865 tag = comment.get('tag', '')
1866 if tag.startswith('autogenerated') and 'robot_id' not in comment:
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07001867 continue
1868 key = (comment['author']['email'], comment['updated'])
1869 if comment.get('side', 'REVISION') == 'PARENT':
1870 patchset = 'Base'
1871 else:
1872 patchset = 'PS%d' % comment['patch_set']
1873 line = comment.get('line', 0)
1874 url = ('https://%s/c/%s/%s/%s#%s%s' %
1875 (self._GetGerritHost(), self.GetIssue(), comment['patch_set'], path,
1876 'b' if comment.get('side') == 'PARENT' else '',
1877 str(line) if line else ''))
1878 comments[key][path][patchset][line] = (url, comment['message'])
1879
Quinten Yearsley0e617c02019-02-20 00:37:03 +00001880 summaries = []
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07001881 for msg in messages:
Quinten Yearsley0e617c02019-02-20 00:37:03 +00001882 summary = self._BuildCommentSummary(msg, comments, readable)
1883 if summary:
1884 summaries.append(summary)
1885 return summaries
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07001886
Quinten Yearsley0e617c02019-02-20 00:37:03 +00001887 @staticmethod
1888 def _BuildCommentSummary(msg, comments, readable):
1889 key = (msg['author']['email'], msg['date'])
1890 # Don't bother showing autogenerated messages that don't have associated
1891 # file or line comments. this will filter out most autogenerated
1892 # messages, but will keep robot comments like those from Tricium.
1893 is_autogenerated = msg.get('tag', '').startswith('autogenerated')
1894 if is_autogenerated and not comments.get(key):
1895 return None
1896 message = msg['message']
1897 # Gerrit spits out nanoseconds.
1898 assert len(msg['date'].split('.')[-1]) == 9
1899 date = datetime.datetime.strptime(msg['date'][:-3],
1900 '%Y-%m-%d %H:%M:%S.%f')
1901 if key in comments:
1902 message += '\n'
1903 for path, patchsets in sorted(comments.get(key, {}).items()):
1904 if readable:
1905 message += '\n%s' % path
1906 for patchset, lines in sorted(patchsets.items()):
1907 for line, (url, content) in sorted(lines.items()):
1908 if line:
1909 line_str = 'Line %d' % line
1910 path_str = '%s:%d:' % (path, line)
1911 else:
1912 line_str = 'File comment'
1913 path_str = '%s:0:' % path
1914 if readable:
1915 message += '\n %s, %s: %s' % (patchset, line_str, url)
1916 message += '\n %s\n' % content
1917 else:
1918 message += '\n%s ' % path_str
1919 message += '\n%s\n' % content
1920
1921 return _CommentSummary(
1922 date=date,
1923 message=message,
1924 sender=msg['author']['email'],
1925 autogenerated=is_autogenerated,
1926 # These could be inferred from the text messages and correlated with
1927 # Code-Review label maximum, however this is not reliable.
1928 # Leaving as is until the need arises.
1929 approval=False,
1930 disapproval=False,
1931 )
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01001932
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001933 def CloseIssue(self):
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00001934 gerrit_util.AbandonChange(
1935 self._GetGerritHost(), self._GerritChangeIdentifier(), msg='')
tandrii@chromium.orgaa5ced12016-03-29 09:41:14 +00001936
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00001937 def SubmitIssue(self, wait_for_merge=True):
Andrii Shyshkalov889677c2018-08-28 20:43:06 +00001938 gerrit_util.SubmitChange(
1939 self._GetGerritHost(), self._GerritChangeIdentifier(),
1940 wait_for_merge=wait_for_merge)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00001941
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001942 def _GetChangeDetail(self, options=None):
1943 """Returns details of associated Gerrit change and caching results."""
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00001944 options = options or []
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001945 assert self.GetIssue(), 'issue is required to query Gerrit'
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01001946
Andrii Shyshkalov8039be72017-01-26 09:38:18 +01001947 # Optimization to avoid multiple RPCs:
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001948 if 'CURRENT_REVISION' in options or 'ALL_REVISIONS' in options:
Andrii Shyshkalov8039be72017-01-26 09:38:18 +01001949 options.append('CURRENT_COMMIT')
1950
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01001951 # Normalize issue and options for consistent keys in cache.
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001952 cache_key = str(self.GetIssue())
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001953 options_set = frozenset(o.upper() for o in options)
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01001954
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001955 for cached_options_set, data in self._detail_cache.get(cache_key, []):
1956 # Assumption: data fetched before with extra options is suitable
1957 # for return for a smaller set of options.
1958 # For example, if we cached data for
1959 # options=[CURRENT_REVISION, DETAILED_FOOTERS]
1960 # and request is for options=[CURRENT_REVISION],
1961 # THEN we can return prior cached data.
1962 if options_set.issubset(cached_options_set):
1963 return data
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01001964
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001965 try:
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001966 data = gerrit_util.GetChangeDetail(
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001967 self._GetGerritHost(), self._GerritChangeIdentifier(), options_set)
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001968 except gerrit_util.GerritError as e:
1969 if e.http_status == 404:
Andrii Shyshkalov03e0ed22018-08-28 19:39:30 +00001970 raise GerritChangeNotExists(self.GetIssue(), self.GetCodereviewServer())
Andrii Shyshkalovc6c8b4c2016-11-09 20:51:20 +01001971 raise
Andrii Shyshkalov258e0a62017-01-24 16:50:57 +01001972
Edward Lesmes7677e5c2020-02-19 20:39:03 +00001973 self._detail_cache.setdefault(cache_key, []).append((options_set, data))
tandriic2405f52016-10-10 08:13:15 -07001974 return data
tandrii@chromium.org013a2802016-03-29 09:52:33 +00001975
Andrii Shyshkalovcc5f17e2018-08-22 23:35:59 +00001976 def _GetChangeCommit(self):
Andrii Shyshkalove2633162018-08-27 23:50:31 +00001977 assert self.GetIssue(), 'issue must be set to query Gerrit'
Aaron Gable6f5a8d92017-04-18 14:49:05 -07001978 try:
Andrii Shyshkalove2633162018-08-27 23:50:31 +00001979 data = gerrit_util.GetChangeCommit(
1980 self._GetGerritHost(), self._GerritChangeIdentifier())
Aaron Gable6f5a8d92017-04-18 14:49:05 -07001981 except gerrit_util.GerritError as e:
1982 if e.http_status == 404:
Andrii Shyshkalove2633162018-08-27 23:50:31 +00001983 raise GerritChangeNotExists(self.GetIssue(), self.GetCodereviewServer())
Aaron Gable6f5a8d92017-04-18 14:49:05 -07001984 raise
agable32978d92016-11-01 12:55:02 -07001985 return data
1986
Karen Qian40c19422019-03-13 21:28:29 +00001987 def _IsCqConfigured(self):
1988 detail = self._GetChangeDetail(['LABELS'])
Andrii Shyshkalov8effa4d2020-01-21 13:23:36 +00001989 return u'Commit-Queue' in detail.get('labels', {})
Karen Qian40c19422019-03-13 21:28:29 +00001990
Olivier Robin75ee7252018-04-13 10:02:56 +02001991 def CMDLand(self, force, bypass_hooks, verbose, parallel):
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00001992 if git_common.is_dirty_git_tree('land'):
1993 return 1
Karen Qian40c19422019-03-13 21:28:29 +00001994
tandriid60367b2016-06-22 05:25:12 -07001995 detail = self._GetChangeDetail(['CURRENT_REVISION', 'LABELS'])
Karen Qian40c19422019-03-13 21:28:29 +00001996 if not force and self._IsCqConfigured():
Andrii Shyshkalov0e889b72019-07-15 22:28:48 +00001997 confirm_or_exit('\nIt seems this repository has a CQ, '
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01001998 'which can test and land changes for you. '
1999 'Are you sure you wish to bypass it?\n',
2000 action='bypass CQ')
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002001 differs = True
tandriic4344b52016-08-29 06:04:54 -07002002 last_upload = self._GitGetBranchConfigValue('gerritsquashhash')
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002003 # Note: git diff outputs nothing if there is no diff.
2004 if not last_upload or RunGit(['diff', last_upload]).strip():
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002005 print('WARNING: Some changes from local branch haven\'t been uploaded.')
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002006 else:
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002007 if detail['current_revision'] == last_upload:
2008 differs = False
2009 else:
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002010 print('WARNING: Local branch contents differ from latest uploaded '
2011 'patchset.')
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002012 if differs:
2013 if not force:
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002014 confirm_or_exit(
2015 'Do you want to submit latest Gerrit patchset and bypass hooks?\n',
2016 action='submit')
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002017 print('WARNING: Bypassing hooks and submitting latest uploaded patchset.')
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002018 elif not bypass_hooks:
Edward Lemur227d5102020-02-25 23:45:35 +00002019 upstream = self.GetCommonAncestorWithUpstream()
2020 if self.GetIssue():
2021 description = self.FetchDescription()
2022 else:
Edward Lemura12175c2020-03-09 16:58:26 +00002023 description = _create_description_from_log([upstream])
Edward Lemur227d5102020-02-25 23:45:35 +00002024 self.RunHook(
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002025 committing=True,
2026 may_prompt=not force,
2027 verbose=verbose,
Edward Lemur227d5102020-02-25 23:45:35 +00002028 parallel=parallel,
2029 upstream=upstream,
2030 description=description,
2031 all_files=False)
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002032
2033 self.SubmitIssue(wait_for_merge=True)
2034 print('Issue %s has been submitted.' % self.GetIssueURL())
agable32978d92016-11-01 12:55:02 -07002035 links = self._GetChangeCommit().get('web_links', [])
2036 for link in links:
Aaron Gable02cdbb42016-12-13 16:24:25 -08002037 if link.get('name') == 'gitiles' and link.get('url'):
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002038 print('Landed as: %s' % link.get('url'))
agable32978d92016-11-01 12:55:02 -07002039 break
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002040 return 0
2041
Edward Lemurf38bc172019-09-03 21:02:13 +00002042 def CMDPatchWithParsedIssue(self, parsed_issue_arg, nocommit, force):
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002043 assert parsed_issue_arg.valid
2044
Edward Lemur125d60a2019-09-13 18:25:41 +00002045 self.issue = parsed_issue_arg.issue
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002046
2047 if parsed_issue_arg.hostname:
2048 self._gerrit_host = parsed_issue_arg.hostname
2049 self._gerrit_server = 'https://%s' % self._gerrit_host
2050
tandriic2405f52016-10-10 08:13:15 -07002051 try:
2052 detail = self._GetChangeDetail(['ALL_REVISIONS'])
Aaron Gablea45ee112016-11-22 15:14:38 -08002053 except GerritChangeNotExists as e:
tandriic2405f52016-10-10 08:13:15 -07002054 DieWithError(str(e))
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002055
2056 if not parsed_issue_arg.patchset:
2057 # Use current revision by default.
2058 revision_info = detail['revisions'][detail['current_revision']]
2059 patchset = int(revision_info['_number'])
2060 else:
2061 patchset = parsed_issue_arg.patchset
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00002062 for revision_info in detail['revisions'].values():
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002063 if int(revision_info['_number']) == parsed_issue_arg.patchset:
2064 break
2065 else:
Aaron Gablea45ee112016-11-22 15:14:38 -08002066 DieWithError('Couldn\'t find patchset %i in change %i' %
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002067 (parsed_issue_arg.patchset, self.GetIssue()))
2068
Edward Lemur125d60a2019-09-13 18:25:41 +00002069 remote_url = self.GetRemoteUrl()
Aaron Gable697a91b2018-01-19 15:20:15 -08002070 if remote_url.endswith('.git'):
2071 remote_url = remote_url[:-len('.git')]
erikchen0d14d0d2018-08-28 18:57:09 +00002072 remote_url = remote_url.rstrip('/')
2073
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002074 fetch_info = revision_info['fetch']['http']
erikchen0d14d0d2018-08-28 18:57:09 +00002075 fetch_info['url'] = fetch_info['url'].rstrip('/')
Aaron Gable697a91b2018-01-19 15:20:15 -08002076
2077 if remote_url != fetch_info['url']:
2078 DieWithError('Trying to patch a change from %s but this repo appears '
2079 'to be %s.' % (fetch_info['url'], remote_url))
2080
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002081 RunGit(['fetch', fetch_info['url'], fetch_info['ref']])
Aaron Gable9387b4f2017-06-08 10:50:03 -07002082
Aaron Gable62619a32017-06-16 08:22:09 -07002083 if force:
2084 RunGit(['reset', '--hard', 'FETCH_HEAD'])
2085 print('Checked out commit for change %i patchset %i locally' %
2086 (parsed_issue_arg.issue, patchset))
Stefan Zager2d5f0392017-10-10 15:17:53 -07002087 elif nocommit:
2088 RunGit(['cherry-pick', '--no-commit', 'FETCH_HEAD'])
2089 print('Patch applied to index.')
Aaron Gable62619a32017-06-16 08:22:09 -07002090 else:
Aaron Gable9387b4f2017-06-08 10:50:03 -07002091 RunGit(['cherry-pick', 'FETCH_HEAD'])
2092 print('Committed patch for change %i patchset %i locally.' %
Aaron Gable62619a32017-06-16 08:22:09 -07002093 (parsed_issue_arg.issue, patchset))
2094 print('Note: this created a local commit which does not have '
2095 'the same hash as the one uploaded for review. This will make '
2096 'uploading changes based on top of this branch difficult.\n'
2097 'If you want to do that, use "git cl patch --force" instead.')
2098
Stefan Zagerd08043c2017-10-12 12:07:02 -07002099 if self.GetBranch():
2100 self.SetIssue(parsed_issue_arg.issue)
2101 self.SetPatchset(patchset)
Edward Lesmescba46082020-03-25 00:29:06 +00002102 fetched_hash = RunGit(['rev-parse', 'FETCH_HEAD']).strip()
Stefan Zagerd08043c2017-10-12 12:07:02 -07002103 self._GitSetBranchConfigValue('last-upload-hash', fetched_hash)
2104 self._GitSetBranchConfigValue('gerritsquashhash', fetched_hash)
2105 else:
2106 print('WARNING: You are in detached HEAD state.\n'
2107 'The patch has been applied to your checkout, but you will not be '
2108 'able to upload a new patch set to the gerrit issue.\n'
2109 'Try using the \'-b\' option if you would like to work on a '
2110 'branch and/or upload a new patch set.')
2111
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00002112 return 0
2113
tandrii16e0b4e2016-06-07 10:34:28 -07002114 def _GerritCommitMsgHookCheck(self, offer_removal):
2115 hook = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
2116 if not os.path.exists(hook):
2117 return
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002118 # Crude attempt to distinguish Gerrit Codereview hook from a potentially
2119 # custom developer-made one.
tandrii16e0b4e2016-06-07 10:34:28 -07002120 data = gclient_utils.FileRead(hook)
2121 if not('From Gerrit Code Review' in data and 'add_ChangeId()' in data):
2122 return
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002123 print('WARNING: You have Gerrit commit-msg hook installed.\n'
qyearsley12fa6ff2016-08-24 09:18:40 -07002124 'It is not necessary for uploading with git cl in squash mode, '
tandrii16e0b4e2016-06-07 10:34:28 -07002125 'and may interfere with it in subtle ways.\n'
2126 'We recommend you remove the commit-msg hook.')
2127 if offer_removal:
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002128 if ask_for_explicit_yes('Do you want to remove it now?'):
tandrii16e0b4e2016-06-07 10:34:28 -07002129 gclient_utils.rm_file_or_tree(hook)
2130 print('Gerrit commit-msg hook removed.')
2131 else:
2132 print('OK, will keep Gerrit commit-msg hook in place.')
2133
Edward Lemur1b52d872019-05-09 21:12:12 +00002134 def _CleanUpOldTraces(self):
2135 """Keep only the last |MAX_TRACES| traces."""
2136 try:
2137 traces = sorted([
2138 os.path.join(TRACES_DIR, f)
2139 for f in os.listdir(TRACES_DIR)
2140 if (os.path.isfile(os.path.join(TRACES_DIR, f))
2141 and not f.startswith('tmp'))
2142 ])
2143 traces_to_delete = traces[:-MAX_TRACES]
2144 for trace in traces_to_delete:
Daniel Chengcf6269b2019-05-18 01:02:12 +00002145 os.remove(trace)
Edward Lemur1b52d872019-05-09 21:12:12 +00002146 except OSError:
2147 print('WARNING: Failed to remove old git traces from\n'
2148 ' %s'
2149 'Consider removing them manually.' % TRACES_DIR)
Edward Lemurdc8e23d2019-05-07 00:45:48 +00002150
Edward Lemur5737f022019-05-17 01:24:00 +00002151 def _WriteGitPushTraces(self, trace_name, traces_dir, git_push_metadata):
Edward Lemur1b52d872019-05-09 21:12:12 +00002152 """Zip and write the git push traces stored in traces_dir."""
2153 gclient_utils.safe_makedirs(TRACES_DIR)
Edward Lemur1b52d872019-05-09 21:12:12 +00002154 traces_zip = trace_name + '-traces'
2155 traces_readme = trace_name + '-README'
Michael Mosse7f0b4c2019-05-08 04:36:24 +00002156 # Create a temporary dir to store git config and gitcookies in. It will be
2157 # compressed and stored next to the traces.
2158 git_info_dir = tempfile.mkdtemp()
Edward Lemur1b52d872019-05-09 21:12:12 +00002159 git_info_zip = trace_name + '-git-info'
2160
Edward Lemur5737f022019-05-17 01:24:00 +00002161 git_push_metadata['now'] = datetime_now().strftime('%c')
Eric Boren67c48202019-05-30 16:52:51 +00002162 if sys.stdin.encoding and sys.stdin.encoding != 'utf-8':
sangwoo.ko7a614332019-05-22 02:46:19 +00002163 git_push_metadata['now'] = git_push_metadata['now'].decode(
2164 sys.stdin.encoding)
2165
Edward Lemur1b52d872019-05-09 21:12:12 +00002166 git_push_metadata['trace_name'] = trace_name
2167 gclient_utils.FileWrite(
2168 traces_readme, TRACES_README_FORMAT % git_push_metadata)
2169
2170 # Keep only the first 6 characters of the git hashes on the packet
2171 # trace. This greatly decreases size after compression.
2172 packet_traces = os.path.join(traces_dir, 'trace-packet')
2173 if os.path.isfile(packet_traces):
2174 contents = gclient_utils.FileRead(packet_traces)
2175 gclient_utils.FileWrite(
2176 packet_traces, GIT_HASH_RE.sub(r'\1', contents))
2177 shutil.make_archive(traces_zip, 'zip', traces_dir)
2178
2179 # Collect and compress the git config and gitcookies.
2180 git_config = RunGit(['config', '-l'])
2181 gclient_utils.FileWrite(
2182 os.path.join(git_info_dir, 'git-config'),
2183 git_config)
2184
2185 cookie_auth = gerrit_util.Authenticator.get()
2186 if isinstance(cookie_auth, gerrit_util.CookiesAuthenticator):
2187 gitcookies_path = cookie_auth.get_gitcookies_path()
2188 if os.path.isfile(gitcookies_path):
2189 gitcookies = gclient_utils.FileRead(gitcookies_path)
2190 gclient_utils.FileWrite(
2191 os.path.join(git_info_dir, 'gitcookies'),
2192 GITCOOKIES_REDACT_RE.sub('REDACTED', gitcookies))
2193 shutil.make_archive(git_info_zip, 'zip', git_info_dir)
2194
Edward Lemur1b52d872019-05-09 21:12:12 +00002195 gclient_utils.rmtree(git_info_dir)
2196
2197 def _RunGitPushWithTraces(
2198 self, change_desc, refspec, refspec_opts, git_push_metadata):
2199 """Run git push and collect the traces resulting from the execution."""
2200 # Create a temporary directory to store traces in. Traces will be compressed
2201 # and stored in a 'traces' dir inside depot_tools.
2202 traces_dir = tempfile.mkdtemp()
Edward Lemur5737f022019-05-17 01:24:00 +00002203 trace_name = os.path.join(
2204 TRACES_DIR, datetime_now().strftime('%Y%m%dT%H%M%S.%f'))
Edward Lemur0f58ae42019-04-30 17:24:12 +00002205
2206 env = os.environ.copy()
2207 env['GIT_REDACT_COOKIES'] = 'o,SSO,GSSO_Uberproxy'
2208 env['GIT_TR2_EVENT'] = os.path.join(traces_dir, 'tr2-event')
Jonathan Nieder9779b142019-05-29 23:19:29 +00002209 env['GIT_TRACE2_EVENT'] = os.path.join(traces_dir, 'tr2-event')
Edward Lemur0f58ae42019-04-30 17:24:12 +00002210 env['GIT_TRACE_CURL'] = os.path.join(traces_dir, 'trace-curl')
2211 env['GIT_TRACE_CURL_NO_DATA'] = '1'
2212 env['GIT_TRACE_PACKET'] = os.path.join(traces_dir, 'trace-packet')
2213
2214 try:
2215 push_returncode = 0
Edward Lemur1b52d872019-05-09 21:12:12 +00002216 remote_url = self.GetRemoteUrl()
Edward Lemur0f58ae42019-04-30 17:24:12 +00002217 before_push = time_time()
2218 push_stdout = gclient_utils.CheckCallAndFilter(
Edward Lemur1b52d872019-05-09 21:12:12 +00002219 ['git', 'push', remote_url, refspec],
Edward Lemur0f58ae42019-04-30 17:24:12 +00002220 env=env,
2221 print_stdout=True,
2222 # Flush after every line: useful for seeing progress when running as
2223 # recipe.
2224 filter_fn=lambda _: sys.stdout.flush())
Edward Lemur79d4f992019-11-11 23:49:02 +00002225 push_stdout = push_stdout.decode('utf-8', 'replace')
Edward Lemur0f58ae42019-04-30 17:24:12 +00002226 except subprocess2.CalledProcessError as e:
2227 push_returncode = e.returncode
2228 DieWithError('Failed to create a change. Please examine output above '
2229 'for the reason of the failure.\n'
2230 'Hint: run command below to diagnose common Git/Gerrit '
2231 'credential problems:\n'
Edward Lemur5737f022019-05-17 01:24:00 +00002232 ' git cl creds-check\n'
2233 '\n'
2234 'If git-cl is not working correctly, file a bug under the '
2235 'Infra>SDK component including the files below.\n'
2236 'Review the files before upload, since they might contain '
2237 'sensitive information.\n'
2238 'Set the Restrict-View-Google label so that they are not '
2239 'publicly accessible.\n'
2240 + TRACES_MESSAGE % {'trace_name': trace_name},
Edward Lemur0f58ae42019-04-30 17:24:12 +00002241 change_desc)
2242 finally:
2243 execution_time = time_time() - before_push
2244 metrics.collector.add_repeated('sub_commands', {
2245 'command': 'git push',
2246 'execution_time': execution_time,
2247 'exit_code': push_returncode,
2248 'arguments': metrics_utils.extract_known_subcommand_args(refspec_opts),
2249 })
2250
Edward Lemur1b52d872019-05-09 21:12:12 +00002251 git_push_metadata['execution_time'] = execution_time
2252 git_push_metadata['exit_code'] = push_returncode
Edward Lemur5737f022019-05-17 01:24:00 +00002253 self._WriteGitPushTraces(trace_name, traces_dir, git_push_metadata)
Edward Lemur0f58ae42019-04-30 17:24:12 +00002254
Edward Lemur1b52d872019-05-09 21:12:12 +00002255 self._CleanUpOldTraces()
Edward Lemur0f58ae42019-04-30 17:24:12 +00002256 gclient_utils.rmtree(traces_dir)
2257
2258 return push_stdout
2259
Edward Lemura12175c2020-03-09 16:58:26 +00002260 def CMDUploadChange(
Edward Lemur5a644f82020-03-18 16:44:57 +00002261 self, options, git_diff_args, custom_cl_base, change_desc):
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002262 """Upload the current branch to Gerrit."""
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002263 remote, remote_branch = self.GetRemoteBranch()
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01002264 branch = GetTargetRef(remote, remote_branch, options.target_branch)
Dominic Battre7d1c4842017-10-27 09:17:28 +02002265
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002266 if options.squash:
tandrii16e0b4e2016-06-07 10:34:28 -07002267 self._GerritCommitMsgHookCheck(offer_removal=not options.force)
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002268 if self.GetIssue():
Josipe827b0f2020-01-30 00:07:20 +00002269 # User requested to change description
2270 if options.edit_description:
Josipe827b0f2020-01-30 00:07:20 +00002271 change_desc.prompt()
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002272 change_id = self._GetChangeDetail()['change_id']
Edward Lemur5a644f82020-03-18 16:44:57 +00002273 change_desc.ensure_change_id(change_id)
Aaron Gableb56ad332017-01-06 15:24:31 -08002274 else: # if not self.GetIssue()
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002275 if not options.force:
Anthony Polito8b955342019-09-24 19:01:36 +00002276 change_desc.prompt()
Andrii Shyshkalov8c90d032017-04-19 21:27:26 +02002277 change_ids = git_footers.get_footer_change_id(change_desc.description)
Edward Lemur5a644f82020-03-18 16:44:57 +00002278 if len(change_ids) == 1:
2279 change_id = change_ids[0]
2280 else:
2281 change_id = GenerateGerritChangeId(change_desc.description)
2282 change_desc.ensure_change_id(change_id)
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002283
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +00002284 if options.preserve_tryjobs:
2285 change_desc.set_preserve_tryjobs()
Robert Iannuccidb02dd02017-04-19 12:18:20 -07002286
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002287 remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
Edward Lemur5a644f82020-03-18 16:44:57 +00002288 parent = self._ComputeParent(
2289 remote, upstream_branch, custom_cl_base, options.force, change_desc)
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002290 tree = RunGit(['rev-parse', 'HEAD:']).strip()
Edward Lemur1773f372020-02-22 00:27:14 +00002291 with gclient_utils.temporary_file() as desc_tempfile:
2292 gclient_utils.FileWrite(desc_tempfile, change_desc.description)
2293 ref_to_push = RunGit(
2294 ['commit-tree', tree, '-p', parent, '-F', desc_tempfile]).strip()
Anthony Polito8b955342019-09-24 19:01:36 +00002295 else: # if not options.squash
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002296 if not git_footers.get_footer_change_id(change_desc.description):
2297 DownloadGerritHook(False)
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02002298 change_desc.set_description(
Edward Lemur5a644f82020-03-18 16:44:57 +00002299 self._AddChangeIdToCommitMessage(
2300 change_desc.description, git_diff_args))
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002301 ref_to_push = 'HEAD'
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02002302 # For no-squash mode, we assume the remote called "origin" is the one we
2303 # want. It is not worthwhile to support different workflows for
2304 # no-squash mode.
2305 parent = 'origin/%s' % branch
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002306 change_id = git_footers.get_footer_change_id(change_desc.description)[0]
2307
Andrii Shyshkalovd9fdc1f2018-09-27 02:13:09 +00002308 SaveDescriptionBackup(change_desc)
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002309 commits = RunGitSilent(['rev-list', '%s..%s' % (parent,
2310 ref_to_push)]).splitlines()
2311 if len(commits) > 1:
2312 print('WARNING: This will upload %d commits. Run the following command '
2313 'to see which commits will be uploaded: ' % len(commits))
2314 print('git log %s..%s' % (parent, ref_to_push))
2315 print('You can also use `git squash-branch` to squash these into a '
2316 'single commit.')
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01002317 confirm_or_exit(action='upload')
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002318
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00002319 reviewers = sorted(change_desc.get_reviewers())
Edward Lemur4508b422019-10-03 21:56:35 +00002320 cc = []
2321 # Add CCs from WATCHLISTS and rietveld.cc git config unless this is
2322 # the initial upload, the CL is private, or auto-CCing has ben disabled.
2323 if not (self.GetIssue() or options.private or options.no_autocc):
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00002324 cc = self.GetCCList().split(',')
Edward Lemur4508b422019-10-03 21:56:35 +00002325 # Add cc's from the --cc flag.
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00002326 if options.cc:
2327 cc.extend(options.cc)
Edward Lemur79d4f992019-11-11 23:49:02 +00002328 cc = [email.strip() for email in cc if email.strip()]
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00002329 if change_desc.get_cced():
2330 cc.extend(change_desc.get_cced())
Andrii Shyshkalov0da5e8f2018-10-30 17:29:18 +00002331 if self._GetGerritHost() == 'chromium-review.googlesource.com':
2332 valid_accounts = set(reviewers + cc)
2333 # TODO(crbug/877717): relax this for all hosts.
2334 else:
2335 valid_accounts = gerrit_util.ValidAccounts(
2336 self._GetGerritHost(), reviewers + cc)
Andrii Shyshkalovf170af42018-10-30 07:00:44 +00002337 logging.info('accounts %s are recognized, %s invalid',
2338 sorted(valid_accounts),
2339 set(reviewers + cc).difference(set(valid_accounts)))
Andrii Shyshkalov76988a82018-10-15 03:12:25 +00002340
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00002341 # Extra options that can be specified at push time. Doc:
2342 # https://gerrit-review.googlesource.com/Documentation/user-upload.html
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00002343 refspec_opts = []
Andrii Shyshkalov2d8a2072017-04-10 15:02:18 +02002344
Aaron Gable844cf292017-06-28 11:32:59 -07002345 # By default, new changes are started in WIP mode, and subsequent patchsets
2346 # don't send email. At any time, passing --send-mail will mark the change
2347 # ready and send email for that particular patch.
Aaron Gableafd52772017-06-27 16:40:10 -07002348 if options.send_mail:
2349 refspec_opts.append('ready')
Aaron Gable844cf292017-06-28 11:32:59 -07002350 refspec_opts.append('notify=ALL')
Jamie Madill276da0b2018-04-27 14:41:20 -04002351 elif not self.GetIssue() and options.squash:
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08002352 refspec_opts.append('wip')
Aaron Gableafd52772017-06-27 16:40:10 -07002353 else:
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08002354 refspec_opts.append('notify=NONE')
Aaron Gable70f4e242017-06-26 10:45:59 -07002355
Andrii Shyshkalov2d8a2072017-04-10 15:02:18 +02002356 # TODO(tandrii): options.message should be posted as a comment
Aaron Gablee5adf612017-07-14 10:43:58 -07002357 # if --send-mail is set on non-initial upload as Rietveld used to do it.
Andrii Shyshkalov2d8a2072017-04-10 15:02:18 +02002358
Edward Lemur5a644f82020-03-18 16:44:57 +00002359 title = self._GetTitleForUpload(options)
Aaron Gable9b713dd2016-12-14 16:04:21 -08002360 if title:
Nick Carter8692b182017-11-06 16:30:38 -08002361 # Punctuation and whitespace in |title| must be percent-encoded.
2362 refspec_opts.append('m=' + gerrit_util.PercentEncodeForGitRef(title))
tandrii@chromium.orgbf766ba2016-04-13 12:51:23 +00002363
agablec6787972016-09-09 16:13:34 -07002364 if options.private:
Aaron Gableb02daf02017-05-23 11:53:46 -07002365 refspec_opts.append('private')
agablec6787972016-09-09 16:13:34 -07002366
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00002367 for r in sorted(reviewers):
2368 if r in valid_accounts:
2369 refspec_opts.append('r=%s' % r)
2370 reviewers.remove(r)
2371 else:
2372 # TODO(tandrii): this should probably be a hard failure.
2373 print('WARNING: reviewer %s doesn\'t have a Gerrit account, skipping'
2374 % r)
2375 for c in sorted(cc):
2376 # refspec option will be rejected if cc doesn't correspond to an
2377 # account, even though REST call to add such arbitrary cc may succeed.
2378 if c in valid_accounts:
2379 refspec_opts.append('cc=%s' % c)
2380 cc.remove(c)
2381
rmistry9eadede2016-09-19 11:22:43 -07002382 if options.topic:
2383 # Documentation on Gerrit topics is here:
2384 # https://gerrit-review.googlesource.com/Documentation/user-upload.html#topic
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00002385 refspec_opts.append('topic=%s' % options.topic)
rmistry9eadede2016-09-19 11:22:43 -07002386
Edward Lemur687ca902018-12-05 02:30:30 +00002387 if options.enable_auto_submit:
2388 refspec_opts.append('l=Auto-Submit+1')
2389 if options.use_commit_queue:
2390 refspec_opts.append('l=Commit-Queue+2')
2391 elif options.cq_dry_run:
2392 refspec_opts.append('l=Commit-Queue+1')
2393
2394 if change_desc.get_reviewers(tbr_only=True):
2395 score = gerrit_util.GetCodeReviewTbrScore(
2396 self._GetGerritHost(),
2397 self._GetGerritProject())
2398 refspec_opts.append('l=Code-Review+%s' % score)
Andrii Shyshkalove7a7fc42018-10-30 17:35:09 +00002399
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08002400 # Gerrit sorts hashtags, so order is not important.
Nodir Turakulov23b82142017-11-16 11:04:25 -08002401 hashtags = {change_desc.sanitize_hash_tag(t) for t in options.hashtags}
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08002402 if not self.GetIssue():
Nodir Turakulov23b82142017-11-16 11:04:25 -08002403 hashtags.update(change_desc.get_hash_tags())
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08002404 refspec_opts += ['hashtag=%s' % t for t in sorted(hashtags)]
2405
Andrii Shyshkalovfebbae92017-04-05 15:05:20 +00002406 refspec_suffix = ''
2407 if refspec_opts:
2408 refspec_suffix = '%' + ','.join(refspec_opts)
2409 assert ' ' not in refspec_suffix, (
2410 'spaces not allowed in refspec: "%s"' % refspec_suffix)
2411 refspec = '%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix)
2412
Edward Lemur1b52d872019-05-09 21:12:12 +00002413 git_push_metadata = {
2414 'gerrit_host': self._GetGerritHost(),
2415 'title': title or '<untitled>',
2416 'change_id': change_id,
2417 'description': change_desc.description,
2418 }
2419 push_stdout = self._RunGitPushWithTraces(
2420 change_desc, refspec, refspec_opts, git_push_metadata)
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002421
2422 if options.squash:
Aaron Gable289b4312017-09-13 14:06:16 -07002423 regex = re.compile(r'remote:\s+https?://[\w\-\.\+\/#]*/(\d+)\s.*')
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002424 change_numbers = [m.group(1)
2425 for m in map(regex.match, push_stdout.splitlines())
2426 if m]
2427 if len(change_numbers) != 1:
2428 DieWithError(
2429 ('Created|Updated %d issues on Gerrit, but only 1 expected.\n'
Christopher Lamf732cd52017-01-24 12:40:11 +11002430 'Change-Id: %s') % (len(change_numbers), change_id), change_desc)
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002431 self.SetIssue(change_numbers[0])
tandrii5d48c322016-08-18 16:19:37 -07002432 self._GitSetBranchConfigValue('gerritsquashhash', ref_to_push)
tandrii88189772016-09-29 04:29:57 -07002433
Andrii Shyshkalov2f727912018-10-15 17:02:33 +00002434 if self.GetIssue() and (reviewers or cc):
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00002435 # GetIssue() is not set in case of non-squash uploads according to tests.
2436 # TODO(agable): non-squash uploads in git cl should be removed.
2437 gerrit_util.AddReviewers(
2438 self._GetGerritHost(),
Andrii Shyshkalovd06cc782018-08-23 17:24:19 +00002439 self._GerritChangeIdentifier(),
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00002440 reviewers, cc,
2441 notify=bool(options.send_mail))
Aaron Gable6dadfbf2017-05-09 14:27:58 -07002442
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002443 return 0
2444
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02002445 def _ComputeParent(self, remote, upstream_branch, custom_cl_base, force,
2446 change_desc):
2447 """Computes parent of the generated commit to be uploaded to Gerrit.
2448
2449 Returns revision or a ref name.
2450 """
2451 if custom_cl_base:
2452 # Try to avoid creating additional unintended CLs when uploading, unless
2453 # user wants to take this risk.
2454 local_ref_of_target_remote = self.GetRemoteBranch()[1]
2455 code, _ = RunGitWithCode(['merge-base', '--is-ancestor', custom_cl_base,
2456 local_ref_of_target_remote])
2457 if code == 1:
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002458 print('\nWARNING: Manually specified base of this CL `%s` '
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02002459 'doesn\'t seem to belong to target remote branch `%s`.\n\n'
2460 'If you proceed with upload, more than 1 CL may be created by '
2461 'Gerrit as a result, in turn confusing or crashing git cl.\n\n'
2462 'If you are certain that specified base `%s` has already been '
2463 'uploaded to Gerrit as another CL, you may proceed.\n' %
2464 (custom_cl_base, local_ref_of_target_remote, custom_cl_base))
2465 if not force:
2466 confirm_or_exit(
2467 'Do you take responsibility for cleaning up potential mess '
2468 'resulting from proceeding with upload?',
2469 action='upload')
2470 return custom_cl_base
2471
Aaron Gablef97e33d2017-03-30 15:44:27 -07002472 if remote != '.':
2473 return self.GetCommonAncestorWithUpstream()
2474
2475 # If our upstream branch is local, we base our squashed commit on its
2476 # squashed version.
2477 upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch)
2478
Aaron Gablef97e33d2017-03-30 15:44:27 -07002479 if upstream_branch_name == 'master':
Aaron Gable0bbd1c22017-05-08 14:37:08 -07002480 return self.GetCommonAncestorWithUpstream()
Aaron Gablef97e33d2017-03-30 15:44:27 -07002481
2482 # Check the squashed hash of the parent.
Andrii Shyshkalov550e9242017-04-12 17:14:49 +02002483 # TODO(tandrii): consider checking parent change in Gerrit and using its
2484 # hash if tree hash of latest parent revision (patchset) in Gerrit matches
2485 # the tree hash of the parent branch. The upside is less likely bogus
2486 # requests to reupload parent change just because it's uploadhash is
2487 # missing, yet the downside likely exists, too (albeit unknown to me yet).
Edward Lesmescba46082020-03-25 00:29:06 +00002488 parent = RunGit(['config',
2489 'branch.%s.gerritsquashhash' % upstream_branch_name],
2490 error_ok=True).strip()
Aaron Gablef97e33d2017-03-30 15:44:27 -07002491 # Verify that the upstream branch has been uploaded too, otherwise
2492 # Gerrit will create additional CLs when uploading.
2493 if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) !=
2494 RunGitSilent(['rev-parse', parent + ':'])):
2495 DieWithError(
2496 '\nUpload upstream branch %s first.\n'
2497 'It is likely that this branch has been rebased since its last '
2498 'upload, so you just need to upload it again.\n'
2499 '(If you uploaded it with --no-squash, then branch dependencies '
2500 'are not supported, and you should reupload with --squash.)'
2501 % upstream_branch_name,
2502 change_desc)
2503 return parent
2504
Edward Lemura12175c2020-03-09 16:58:26 +00002505 def _AddChangeIdToCommitMessage(self, log_desc, args):
tandrii@chromium.org8930b3d2016-04-13 14:47:02 +00002506 """Re-commits using the current message, assumes the commit hook is in
2507 place.
2508 """
Edward Lemura12175c2020-03-09 16:58:26 +00002509 RunGit(['commit', '--amend', '-m', log_desc])
Andrii Shyshkalovb07575f2018-10-16 06:16:21 +00002510 new_log_desc = _create_description_from_log(args)
tandrii@chromium.org8930b3d2016-04-13 14:47:02 +00002511 if git_footers.get_footer_change_id(new_log_desc):
vapiera7fbd5a2016-06-16 09:17:49 -07002512 print('git-cl: Added Change-Id to commit message.')
tandrii@chromium.org8930b3d2016-04-13 14:47:02 +00002513 return new_log_desc
2514 else:
tandrii@chromium.orgb067ec52016-05-31 15:24:44 +00002515 DieWithError('ERROR: Gerrit commit-msg hook not installed.')
tandrii@chromium.orgaa6235b2016-04-11 21:35:29 +00002516
tandriie113dfd2016-10-11 10:20:12 -07002517 def CannotTriggerTryJobReason(self):
tandrii8c5a3532016-11-04 07:52:02 -07002518 try:
2519 data = self._GetChangeDetail()
Aaron Gablea45ee112016-11-22 15:14:38 -08002520 except GerritChangeNotExists:
2521 return 'Gerrit doesn\'t know about your change %s' % self.GetIssue()
tandrii8c5a3532016-11-04 07:52:02 -07002522
2523 if data['status'] in ('ABANDONED', 'MERGED'):
2524 return 'CL %s is closed' % self.GetIssue()
2525
Edward Lemurd4d1ba42019-09-20 21:46:37 +00002526 def GetGerritChange(self, patchset=None):
2527 """Returns a buildbucket.v2.GerritChange message for the current issue."""
Edward Lemur79d4f992019-11-11 23:49:02 +00002528 host = urllib.parse.urlparse(self.GetCodereviewServer()).hostname
Edward Lemurd4d1ba42019-09-20 21:46:37 +00002529 issue = self.GetIssue()
Edward Lemur2c210a42019-09-16 23:58:35 +00002530 patchset = int(patchset or self.GetPatchset())
Edward Lemurd4d1ba42019-09-20 21:46:37 +00002531 data = self._GetChangeDetail(['ALL_REVISIONS'])
2532
2533 assert host and issue and patchset, 'CL must be uploaded first'
2534
2535 has_patchset = any(
2536 int(revision_data['_number']) == patchset
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00002537 for revision_data in data['revisions'].values())
Edward Lemurd4d1ba42019-09-20 21:46:37 +00002538 if not has_patchset:
Aaron Gablea45ee112016-11-22 15:14:38 -08002539 raise Exception('Patchset %d is not known in Gerrit change %d' %
tandrii8c5a3532016-11-04 07:52:02 -07002540 (patchset, self.GetIssue()))
Edward Lemurd4d1ba42019-09-20 21:46:37 +00002541
tandrii8c5a3532016-11-04 07:52:02 -07002542 return {
Edward Lemurd4d1ba42019-09-20 21:46:37 +00002543 'host': host,
2544 'change': issue,
2545 'project': data['project'],
2546 'patchset': patchset,
tandrii8c5a3532016-11-04 07:52:02 -07002547 }
tandriie113dfd2016-10-11 10:20:12 -07002548
tandriide281ae2016-10-12 06:02:30 -07002549 def GetIssueOwner(self):
tandrii8c5a3532016-11-04 07:52:02 -07002550 return self._GetChangeDetail(['DETAILED_ACCOUNTS'])['owner']['email']
tandriide281ae2016-10-12 06:02:30 -07002551
Edward Lemur707d70b2018-02-07 00:50:14 +01002552 def GetReviewers(self):
2553 details = self._GetChangeDetail(['DETAILED_ACCOUNTS'])
Mohamed Heikal171c0742018-11-09 20:38:51 +00002554 return [r['email'] for r in details['reviewers'].get('REVIEWER', [])]
Edward Lemur707d70b2018-02-07 00:50:14 +01002555
tandrii@chromium.orgd68b62b2016-03-31 16:09:29 +00002556
tandriif9aefb72016-07-01 09:06:51 -07002557def _get_bug_line_values(default_project, bugs):
2558 """Given default_project and comma separated list of bugs, yields bug line
2559 values.
2560
2561 Each bug can be either:
2562 * a number, which is combined with default_project
2563 * string, which is left as is.
2564
2565 This function may produce more than one line, because bugdroid expects one
2566 project per line.
2567
2568 >>> list(_get_bug_line_values('v8', '123,chromium:789'))
2569 ['v8:123', 'chromium:789']
2570 """
2571 default_bugs = []
2572 others = []
2573 for bug in bugs.split(','):
2574 bug = bug.strip()
2575 if bug:
2576 try:
2577 default_bugs.append(int(bug))
2578 except ValueError:
2579 others.append(bug)
2580
2581 if default_bugs:
2582 default_bugs = ','.join(map(str, default_bugs))
2583 if default_project:
2584 yield '%s:%s' % (default_project, default_bugs)
2585 else:
2586 yield default_bugs
2587 for other in sorted(others):
2588 # Don't bother finding common prefixes, CLs with >2 bugs are very very rare.
2589 yield other
2590
2591
dpranke@chromium.org20254fc2011-03-22 18:28:59 +00002592class ChangeDescription(object):
2593 """Contains a parsed form of the change description."""
maruel@chromium.orgc6f60e82013-04-19 17:01:57 +00002594 R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$'
bradnelsond975b302016-10-23 12:20:23 -07002595 CC_LINE = r'^[ \t]*(CC)[ \t]*=[ \t]*(.*?)[ \t]*$'
Aaron Gable3a16ed12017-03-23 10:51:55 -07002596 BUG_LINE = r'^[ \t]*(?:(BUG)[ \t]*=|Bug:)[ \t]*(.*?)[ \t]*$'
Dan Beamd8b04ca2019-10-10 21:23:26 +00002597 FIXED_LINE = r'^[ \t]*Fixed[ \t]*:[ \t]*(.*?)[ \t]*$'
Andrii Shyshkalov15e50cc2016-12-02 14:34:08 +01002598 CHERRY_PICK_LINE = r'^\(cherry picked from commit [a-fA-F0-9]{40}\)$'
Nodir Turakulov23b82142017-11-16 11:04:25 -08002599 STRIP_HASH_TAG_PREFIX = r'^(\s*(revert|reland)( "|:)?\s*)*'
2600 BRACKET_HASH_TAG = r'\s*\[([^\[\]]+)\]'
Anthony Polito02b5af32019-12-02 19:49:47 +00002601 COLON_SEPARATED_HASH_TAG = r'^([a-zA-Z0-9_\- ]+):($|[^:])'
Nodir Turakulov23b82142017-11-16 11:04:25 -08002602 BAD_HASH_TAG_CHUNK = r'[^a-zA-Z0-9]+'
dpranke@chromium.org20254fc2011-03-22 18:28:59 +00002603
Dan Beamd8b04ca2019-10-10 21:23:26 +00002604 def __init__(self, description, bug=None, fixed=None):
agable@chromium.org42c20792013-09-12 17:34:49 +00002605 self._description_lines = (description or '').strip().splitlines()
Anthony Polito8b955342019-09-24 19:01:36 +00002606 if bug:
2607 regexp = re.compile(self.BUG_LINE)
2608 prefix = settings.GetBugPrefix()
2609 if not any((regexp.match(line) for line in self._description_lines)):
2610 values = list(_get_bug_line_values(prefix, bug))
2611 self.append_footer('Bug: %s' % ', '.join(values))
Dan Beamd8b04ca2019-10-10 21:23:26 +00002612 if fixed:
2613 regexp = re.compile(self.FIXED_LINE)
2614 prefix = settings.GetBugPrefix()
2615 if not any((regexp.match(line) for line in self._description_lines)):
2616 values = list(_get_bug_line_values(prefix, fixed))
2617 self.append_footer('Fixed: %s' % ', '.join(values))
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002618
agable@chromium.org42c20792013-09-12 17:34:49 +00002619 @property # www.logilab.org/ticket/89786
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -08002620 def description(self): # pylint: disable=method-hidden
agable@chromium.org42c20792013-09-12 17:34:49 +00002621 return '\n'.join(self._description_lines)
2622
2623 def set_description(self, desc):
2624 if isinstance(desc, basestring):
2625 lines = desc.splitlines()
2626 else:
2627 lines = [line.rstrip() for line in desc]
2628 while lines and not lines[0]:
2629 lines.pop(0)
2630 while lines and not lines[-1]:
2631 lines.pop(-1)
2632 self._description_lines = lines
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002633
Edward Lemur5a644f82020-03-18 16:44:57 +00002634 def ensure_change_id(self, change_id):
2635 description = self.description
2636 footer_change_ids = git_footers.get_footer_change_id(description)
2637 # Make sure that the Change-Id in the description matches the given one.
2638 if footer_change_ids != [change_id]:
2639 if footer_change_ids:
2640 # Remove any existing Change-Id footers since they don't match the
2641 # expected change_id footer.
2642 description = git_footers.remove_footer(description, 'Change-Id')
2643 print('WARNING: Change-Id has been set to %s. Use `git cl issue 0` '
2644 'if you want to set a new one.')
2645 # Add the expected Change-Id footer.
2646 description = git_footers.add_footer_change_id(description, change_id)
2647 self.set_description(description)
2648
Edward Lemur2c62b332020-03-12 22:12:33 +00002649 def update_reviewers(
2650 self, reviewers, tbrs, add_owners_to, affected_files, author_email):
Robert Iannucci6c98dc62017-04-18 11:38:00 -07002651 """Rewrites the R=/TBR= line(s) as a single line each.
2652
2653 Args:
2654 reviewers (list(str)) - list of additional emails to use for reviewers.
2655 tbrs (list(str)) - list of additional emails to use for TBRs.
2656 add_owners_to (None|'R'|'TBR') - Pass to do an OWNERS lookup for files in
2657 the change that are missing OWNER coverage. If this is not None, you
2658 must also pass a value for `change`.
2659 change (Change) - The Change that should be used for OWNERS lookups.
2660 """
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002661 assert isinstance(reviewers, list), reviewers
Robert Iannucci6c98dc62017-04-18 11:38:00 -07002662 assert isinstance(tbrs, list), tbrs
2663
Robert Iannuccif2708bd2017-04-17 15:49:02 -07002664 assert add_owners_to in (None, 'TBR', 'R'), add_owners_to
Edward Lemur2c62b332020-03-12 22:12:33 +00002665 assert not add_owners_to or affected_files, add_owners_to
Robert Iannucci6c98dc62017-04-18 11:38:00 -07002666
2667 if not reviewers and not tbrs and not add_owners_to:
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002668 return
Robert Iannucci6c98dc62017-04-18 11:38:00 -07002669
2670 reviewers = set(reviewers)
2671 tbrs = set(tbrs)
2672 LOOKUP = {
2673 'TBR': tbrs,
2674 'R': reviewers,
2675 }
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002676
Quinten Yearsley0c62da92017-05-31 13:39:42 -07002677 # Get the set of R= and TBR= lines and remove them from the description.
agable@chromium.org42c20792013-09-12 17:34:49 +00002678 regexp = re.compile(self.R_LINE)
2679 matches = [regexp.match(line) for line in self._description_lines]
2680 new_desc = [l for i, l in enumerate(self._description_lines)
2681 if not matches[i]]
2682 self.set_description(new_desc)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002683
agable@chromium.org42c20792013-09-12 17:34:49 +00002684 # Construct new unified R= and TBR= lines.
Robert Iannucci6c98dc62017-04-18 11:38:00 -07002685
2686 # First, update tbrs/reviewers with names from the R=/TBR= lines (if any).
agable@chromium.org42c20792013-09-12 17:34:49 +00002687 for match in matches:
2688 if not match:
2689 continue
Robert Iannucci6c98dc62017-04-18 11:38:00 -07002690 LOOKUP[match.group(1)].update(cleanup_list([match.group(2).strip()]))
2691
2692 # Next, maybe fill in OWNERS coverage gaps to either tbrs/reviewers.
Robert Iannuccif2708bd2017-04-17 15:49:02 -07002693 if add_owners_to:
Edward Lemur2c62b332020-03-12 22:12:33 +00002694 owners_db = owners.Database(settings.GetRoot(),
Edward Lemurb7f759f2020-03-04 21:20:56 +00002695 fopen=open, os_path=os.path)
Edward Lemur2c62b332020-03-12 22:12:33 +00002696 missing_files = owners_db.files_not_covered_by(affected_files,
Robert Iannucci100aa212017-04-18 17:28:26 -07002697 (tbrs | reviewers))
Robert Iannucci6c98dc62017-04-18 11:38:00 -07002698 LOOKUP[add_owners_to].update(
Edward Lemur2c62b332020-03-12 22:12:33 +00002699 owners_db.reviewers_for(missing_files, author_email))
Robert Iannuccif2708bd2017-04-17 15:49:02 -07002700
Robert Iannucci6c98dc62017-04-18 11:38:00 -07002701 # If any folks ended up in both groups, remove them from tbrs.
2702 tbrs -= reviewers
Robert Iannuccif2708bd2017-04-17 15:49:02 -07002703
Robert Iannucci6c98dc62017-04-18 11:38:00 -07002704 new_r_line = 'R=' + ', '.join(sorted(reviewers)) if reviewers else None
2705 new_tbr_line = 'TBR=' + ', '.join(sorted(tbrs)) if tbrs else None
agable@chromium.org42c20792013-09-12 17:34:49 +00002706
2707 # Put the new lines in the description where the old first R= line was.
2708 line_loc = next((i for i, match in enumerate(matches) if match), -1)
2709 if 0 <= line_loc < len(self._description_lines):
2710 if new_tbr_line:
2711 self._description_lines.insert(line_loc, new_tbr_line)
2712 if new_r_line:
2713 self._description_lines.insert(line_loc, new_r_line)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002714 else:
agable@chromium.org42c20792013-09-12 17:34:49 +00002715 if new_r_line:
2716 self.append_footer(new_r_line)
2717 if new_tbr_line:
2718 self.append_footer(new_tbr_line)
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002719
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +00002720 def set_preserve_tryjobs(self):
2721 """Ensures description footer contains 'Cq-Do-Not-Cancel-Tryjobs: true'."""
2722 footers = git_footers.parse_footers(self.description)
2723 for v in footers.get('Cq-Do-Not-Cancel-Tryjobs', []):
2724 if v.lower() == 'true':
2725 return
2726 self.append_footer('Cq-Do-Not-Cancel-Tryjobs: true')
2727
Anthony Polito8b955342019-09-24 19:01:36 +00002728 def prompt(self):
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002729 """Asks the user to update the description."""
agable@chromium.org42c20792013-09-12 17:34:49 +00002730 self.set_description([
2731 '# Enter a description of the change.',
2732 '# This will be displayed on the codereview site.',
2733 '# The first line will also be used as the subject of the review.',
alancutter@chromium.orgbd1073e2013-06-01 00:34:38 +00002734 '#--------------------This line is 72 characters long'
agable@chromium.org42c20792013-09-12 17:34:49 +00002735 '--------------------',
2736 ] + self._description_lines)
Dan Beamd8b04ca2019-10-10 21:23:26 +00002737 bug_regexp = re.compile(self.BUG_LINE)
2738 fixed_regexp = re.compile(self.FIXED_LINE)
Jonas Termansend0f79112019-03-22 15:28:26 +00002739 prefix = settings.GetBugPrefix()
Dan Beamd8b04ca2019-10-10 21:23:26 +00002740 has_issue = lambda l: bug_regexp.match(l) or fixed_regexp.match(l)
2741 if not any((has_issue(line) for line in self._description_lines)):
Anthony Polito8b955342019-09-24 19:01:36 +00002742 self.append_footer('Bug: %s' % prefix)
tandriif9aefb72016-07-01 09:06:51 -07002743
agable@chromium.org42c20792013-09-12 17:34:49 +00002744 content = gclient_utils.RunEditor(self.description, True,
Edward Lemur79d4f992019-11-11 23:49:02 +00002745 git_editor=settings.GetGitEditor())
maruel@chromium.org0e0436a2011-10-25 13:32:41 +00002746 if not content:
2747 DieWithError('Running editor failed')
agable@chromium.org42c20792013-09-12 17:34:49 +00002748 lines = content.splitlines()
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002749
Bruce Dawson2377b012018-01-11 16:46:49 -08002750 # Strip off comments and default inserted "Bug:" line.
2751 clean_lines = [line.rstrip() for line in lines if not
Jonas Termansend0f79112019-03-22 15:28:26 +00002752 (line.startswith('#') or
2753 line.rstrip() == "Bug:" or
2754 line.rstrip() == "Bug: " + prefix)]
agable@chromium.org42c20792013-09-12 17:34:49 +00002755 if not clean_lines:
maruel@chromium.org0e0436a2011-10-25 13:32:41 +00002756 DieWithError('No CL description, aborting')
agable@chromium.org42c20792013-09-12 17:34:49 +00002757 self.set_description(clean_lines)
dpranke@chromium.org20254fc2011-03-22 18:28:59 +00002758
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002759 def append_footer(self, line):
tandrii@chromium.org601e1d12016-06-03 13:03:54 +00002760 """Adds a footer line to the description.
2761
2762 Differentiates legacy "KEY=xxx" footers (used to be called tags) and
2763 Gerrit's footers in the form of "Footer-Key: footer any value" and ensures
2764 that Gerrit footers are always at the end.
2765 """
2766 parsed_footer_line = git_footers.parse_footer(line)
2767 if parsed_footer_line:
2768 # Line is a gerrit footer in the form: Footer-Key: any value.
2769 # Thus, must be appended observing Gerrit footer rules.
2770 self.set_description(
2771 git_footers.add_footer(self.description,
2772 key=parsed_footer_line[0],
2773 value=parsed_footer_line[1]))
2774 return
2775
2776 if not self._description_lines:
2777 self._description_lines.append(line)
2778 return
2779
2780 top_lines, gerrit_footers, _ = git_footers.split_footers(self.description)
2781 if gerrit_footers:
2782 # git_footers.split_footers ensures that there is an empty line before
2783 # actual (gerrit) footers, if any. We have to keep it that way.
2784 assert top_lines and top_lines[-1] == ''
2785 top_lines, separator = top_lines[:-1], top_lines[-1:]
2786 else:
2787 separator = [] # No need for separator if there are no gerrit_footers.
2788
2789 prev_line = top_lines[-1] if top_lines else ''
2790 if (not presubmit_support.Change.TAG_LINE_RE.match(prev_line) or
2791 not presubmit_support.Change.TAG_LINE_RE.match(line)):
2792 top_lines.append('')
2793 top_lines.append(line)
2794 self._description_lines = top_lines + separator + gerrit_footers
dpranke@chromium.org20254fc2011-03-22 18:28:59 +00002795
tandrii99a72f22016-08-17 14:33:24 -07002796 def get_reviewers(self, tbr_only=False):
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002797 """Retrieves the list of reviewers."""
agable@chromium.org42c20792013-09-12 17:34:49 +00002798 matches = [re.match(self.R_LINE, line) for line in self._description_lines]
tandrii99a72f22016-08-17 14:33:24 -07002799 reviewers = [match.group(2).strip()
2800 for match in matches
2801 if match and (not tbr_only or match.group(1).upper() == 'TBR')]
maruel@chromium.org78936cb2013-04-11 00:17:52 +00002802 return cleanup_list(reviewers)
dpranke@chromium.org20254fc2011-03-22 18:28:59 +00002803
bradnelsond975b302016-10-23 12:20:23 -07002804 def get_cced(self):
2805 """Retrieves the list of reviewers."""
2806 matches = [re.match(self.CC_LINE, line) for line in self._description_lines]
2807 cced = [match.group(2).strip() for match in matches if match]
2808 return cleanup_list(cced)
2809
Nodir Turakulov23b82142017-11-16 11:04:25 -08002810 def get_hash_tags(self):
2811 """Extracts and sanitizes a list of Gerrit hashtags."""
2812 subject = (self._description_lines or ('',))[0]
2813 subject = re.sub(
2814 self.STRIP_HASH_TAG_PREFIX, '', subject, flags=re.IGNORECASE)
2815
2816 tags = []
2817 start = 0
2818 bracket_exp = re.compile(self.BRACKET_HASH_TAG)
2819 while True:
2820 m = bracket_exp.match(subject, start)
2821 if not m:
2822 break
2823 tags.append(self.sanitize_hash_tag(m.group(1)))
2824 start = m.end()
2825
2826 if not tags:
2827 # Try "Tag: " prefix.
2828 m = re.match(self.COLON_SEPARATED_HASH_TAG, subject)
2829 if m:
2830 tags.append(self.sanitize_hash_tag(m.group(1)))
2831 return tags
2832
2833 @classmethod
2834 def sanitize_hash_tag(cls, tag):
2835 """Returns a sanitized Gerrit hash tag.
2836
2837 A sanitized hashtag can be used as a git push refspec parameter value.
2838 """
2839 return re.sub(cls.BAD_HASH_TAG_CHUNK, '-', tag).strip('-').lower()
2840
Edward Lesmescba46082020-03-25 00:29:06 +00002841 def update_with_git_number_footers(self, parent_hash, parent_msg, dest_ref):
2842 """Updates this commit description given the parent.
2843
2844 This is essentially what Gnumbd used to do.
2845 Consult https://goo.gl/WMmpDe for more details.
2846 """
2847 assert parent_msg # No, orphan branch creation isn't supported.
2848 assert parent_hash
2849 assert dest_ref
2850 parent_footer_map = git_footers.parse_footers(parent_msg)
2851 # This will also happily parse svn-position, which GnumbD is no longer
2852 # supporting. While we'd generate correct footers, the verifier plugin
2853 # installed in Gerrit will block such commit (ie git push below will fail).
2854 parent_position = git_footers.get_position(parent_footer_map)
2855
2856 # Cherry-picks may have last line obscuring their prior footers,
2857 # from git_footers perspective. This is also what Gnumbd did.
2858 cp_line = None
2859 if (self._description_lines and
2860 re.match(self.CHERRY_PICK_LINE, self._description_lines[-1])):
2861 cp_line = self._description_lines.pop()
2862
2863 top_lines, footer_lines, _ = git_footers.split_footers(self.description)
2864
2865 # Original-ify all Cr- footers, to avoid re-lands, cherry-picks, or just
2866 # user interference with actual footers we'd insert below.
2867 for i, line in enumerate(footer_lines):
2868 k, v = git_footers.parse_footer(line) or (None, None)
2869 if k and k.startswith('Cr-'):
2870 footer_lines[i] = '%s: %s' % ('Cr-Original-' + k[len('Cr-'):], v)
2871
2872 # Add Position and Lineage footers based on the parent.
2873 lineage = list(reversed(parent_footer_map.get('Cr-Branched-From', [])))
2874 if parent_position[0] == dest_ref:
2875 # Same branch as parent.
2876 number = int(parent_position[1]) + 1
2877 else:
2878 number = 1 # New branch, and extra lineage.
2879 lineage.insert(0, '%s-%s@{#%d}' % (parent_hash, parent_position[0],
2880 int(parent_position[1])))
2881
2882 footer_lines.append('Cr-Commit-Position: %s@{#%d}' % (dest_ref, number))
2883 footer_lines.extend('Cr-Branched-From: %s' % v for v in lineage)
2884
2885 self._description_lines = top_lines
2886 if cp_line:
2887 self._description_lines.append(cp_line)
2888 if self._description_lines[-1] != '':
2889 self._description_lines.append('') # Ensure footer separator.
2890 self._description_lines.extend(footer_lines)
2891
2892
2893def get_approving_reviewers(props, disapproval=False):
2894 """Retrieves the reviewers that approved a CL from the issue properties with
2895 messages.
2896
2897 Note that the list may contain reviewers that are not committer, thus are not
2898 considered by the CQ.
2899
2900 If disapproval is True, instead returns reviewers who 'not lgtm'd the CL.
2901 """
2902 approval_type = 'disapproval' if disapproval else 'approval'
2903 return sorted(
2904 set(
2905 message['sender']
2906 for message in props['messages']
2907 if message[approval_type] and message['sender'] in props['reviewers']
2908 )
2909 )
2910
maruel@chromium.orge52678e2013-04-26 18:34:44 +00002911
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00002912def FindCodereviewSettingsFile(filename='codereview.settings'):
2913 """Finds the given file starting in the cwd and going up.
2914
2915 Only looks up to the top of the repository unless an
2916 'inherit-review-settings-ok' file exists in the root of the repository.
2917 """
2918 inherit_ok_file = 'inherit-review-settings-ok'
2919 cwd = os.getcwd()
thestig@chromium.org8b0553c2014-02-11 00:33:37 +00002920 root = settings.GetRoot()
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00002921 if os.path.isfile(os.path.join(root, inherit_ok_file)):
2922 root = '/'
2923 while True:
2924 if filename in os.listdir(cwd):
2925 if os.path.isfile(os.path.join(cwd, filename)):
2926 return open(os.path.join(cwd, filename))
2927 if cwd == root:
2928 break
2929 cwd = os.path.dirname(cwd)
2930
2931
2932def LoadCodereviewSettingsFromFile(fileobj):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002933 """Parses a codereview.settings file and updates hooks."""
maruel@chromium.org99ac1c52012-01-16 14:52:12 +00002934 keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read())
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00002935
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00002936 def SetProperty(name, setting, unset_error_ok=False):
2937 fullname = 'rietveld.' + name
2938 if setting in keyvals:
2939 RunGit(['config', fullname, keyvals[setting]])
2940 else:
2941 RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok)
2942
tandrii48df5812016-10-17 03:55:37 -07002943 if not keyvals.get('GERRIT_HOST', False):
2944 SetProperty('server', 'CODE_REVIEW_SERVER')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00002945 # Only server setting is required. Other settings can be absent.
2946 # In that case, we ignore errors raised during option deletion attempt.
2947 SetProperty('cc', 'CC_LIST', unset_error_ok=True)
2948 SetProperty('tree-status-url', 'STATUS', unset_error_ok=True)
2949 SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True)
rmistry@google.com90752582014-01-14 21:04:50 +00002950 SetProperty('bug-prefix', 'BUG_PREFIX', unset_error_ok=True)
thestig@chromium.org44202a22014-03-11 19:22:18 +00002951 SetProperty('cpplint-regex', 'LINT_REGEX', unset_error_ok=True)
2952 SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX', unset_error_ok=True)
rmistry@google.com5626a922015-02-26 14:03:30 +00002953 SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK',
2954 unset_error_ok=True)
Jamie Madilldc4d19e2019-10-24 21:50:02 +00002955 SetProperty(
2956 'format-full-by-default', 'FORMAT_FULL_BY_DEFAULT', unset_error_ok=True)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00002957
ukai@chromium.org7044efc2013-11-28 01:51:21 +00002958 if 'GERRIT_HOST' in keyvals:
ukai@chromium.orge8077812012-02-03 03:41:46 +00002959 RunGit(['config', 'gerrit.host', keyvals['GERRIT_HOST']])
ukai@chromium.orge8077812012-02-03 03:41:46 +00002960
bauerb@chromium.org54b400c2016-01-14 10:08:25 +00002961 if 'GERRIT_SQUASH_UPLOADS' in keyvals:
tandrii8dd81ea2016-06-16 13:24:23 -07002962 RunGit(['config', 'gerrit.squash-uploads',
2963 keyvals['GERRIT_SQUASH_UPLOADS']])
bauerb@chromium.org54b400c2016-01-14 10:08:25 +00002964
tandrii@chromium.org28253532016-04-14 13:46:56 +00002965 if 'GERRIT_SKIP_ENSURE_AUTHENTICATED' in keyvals:
shinyak@chromium.org00dbccd2016-04-15 07:24:43 +00002966 RunGit(['config', 'gerrit.skip-ensure-authenticated',
tandrii@chromium.org28253532016-04-14 13:46:56 +00002967 keyvals['GERRIT_SKIP_ENSURE_AUTHENTICATED']])
2968
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00002969 if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals:
Andrii Shyshkalov18975322017-01-25 16:44:13 +01002970 # should be of the form
2971 # PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof
2972 # ORIGIN_URL_CONFIG: http://src.chromium.org/git
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00002973 RunGit(['config', keyvals['PUSH_URL_CONFIG'],
2974 keyvals['ORIGIN_URL_CONFIG']])
2975
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00002976
joshua.lock@intel.com426f69b2012-08-02 23:41:49 +00002977def urlretrieve(source, destination):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002978 """Downloads a network object to a local file, like urllib.urlretrieve.
2979
2980 This is necessary because urllib is broken for SSL connections via a proxy.
2981 """
joshua.lock@intel.com426f69b2012-08-02 23:41:49 +00002982 with open(destination, 'w') as f:
Edward Lemur79d4f992019-11-11 23:49:02 +00002983 f.write(urllib.request.urlopen(source).read())
joshua.lock@intel.com426f69b2012-08-02 23:41:49 +00002984
2985
ukai@chromium.org712d6102013-11-27 00:52:58 +00002986def hasSheBang(fname):
2987 """Checks fname is a #! script."""
2988 with open(fname) as f:
2989 return f.read(2).startswith('#!')
2990
2991
Edward Lesmescba46082020-03-25 00:29:06 +00002992# TODO(bpastene) Remove once a cleaner fix to crbug.com/600473 presents itself.
2993def DownloadHooks(*args, **kwargs):
2994 pass
2995
2996
tandrii@chromium.org18630d62016-03-04 12:06:02 +00002997def DownloadGerritHook(force):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00002998 """Downloads and installs a Gerrit commit-msg hook.
ukai@chromium.org78c4b982012-02-14 02:20:26 +00002999
3000 Args:
3001 force: True to update hooks. False to install hooks if not present.
3002 """
ukai@chromium.org712d6102013-11-27 00:52:58 +00003003 src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg'
ukai@chromium.org78c4b982012-02-14 02:20:26 +00003004 dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
3005 if not os.access(dst, os.X_OK):
3006 if os.path.exists(dst):
3007 if not force:
3008 return
ukai@chromium.org78c4b982012-02-14 02:20:26 +00003009 try:
joshua.lock@intel.com426f69b2012-08-02 23:41:49 +00003010 urlretrieve(src, dst)
ukai@chromium.org712d6102013-11-27 00:52:58 +00003011 if not hasSheBang(dst):
3012 DieWithError('Not a script: %s\n'
3013 'You need to download from\n%s\n'
3014 'into .git/hooks/commit-msg and '
3015 'chmod +x .git/hooks/commit-msg' % (dst, src))
ukai@chromium.org78c4b982012-02-14 02:20:26 +00003016 os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
3017 except Exception:
3018 if os.path.exists(dst):
3019 os.remove(dst)
ukai@chromium.org712d6102013-11-27 00:52:58 +00003020 DieWithError('\nFailed to download hooks.\n'
3021 'You need to download from\n%s\n'
3022 'into .git/hooks/commit-msg and '
3023 'chmod +x .git/hooks/commit-msg' % src)
ukai@chromium.org78c4b982012-02-14 02:20:26 +00003024
3025
Andrii Shyshkalov517948b2017-03-15 15:51:59 +01003026class _GitCookiesChecker(object):
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003027 """Provides facilities for validating and suggesting fixes to .gitcookies."""
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003028
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003029 _GOOGLESOURCE = 'googlesource.com'
3030
3031 def __init__(self):
3032 # Cached list of [host, identity, source], where source is either
3033 # .gitcookies or .netrc.
3034 self._all_hosts = None
3035
Andrii Shyshkalov517948b2017-03-15 15:51:59 +01003036 def ensure_configured_gitcookies(self):
3037 """Runs checks and suggests fixes to make git use .gitcookies from default
3038 path."""
3039 default = gerrit_util.CookiesAuthenticator.get_gitcookies_path()
3040 configured_path = RunGitSilent(
3041 ['config', '--global', 'http.cookiefile']).strip()
Andrii Shyshkalov1e250cd2017-05-10 15:39:31 +02003042 configured_path = os.path.expanduser(configured_path)
Andrii Shyshkalov517948b2017-03-15 15:51:59 +01003043 if configured_path:
3044 self._ensure_default_gitcookies_path(configured_path, default)
3045 else:
3046 self._configure_gitcookies_path(default)
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003047
Andrii Shyshkalov517948b2017-03-15 15:51:59 +01003048 @staticmethod
3049 def _ensure_default_gitcookies_path(configured_path, default_path):
3050 assert configured_path
3051 if configured_path == default_path:
3052 print('git is already configured to use your .gitcookies from %s' %
3053 configured_path)
3054 return
3055
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003056 print('WARNING: You have configured custom path to .gitcookies: %s\n'
Andrii Shyshkalov517948b2017-03-15 15:51:59 +01003057 'Gerrit and other depot_tools expect .gitcookies at %s\n' %
3058 (configured_path, default_path))
3059
3060 if not os.path.exists(configured_path):
3061 print('However, your configured .gitcookies file is missing.')
3062 confirm_or_exit('Reconfigure git to use default .gitcookies?',
3063 action='reconfigure')
3064 RunGit(['config', '--global', 'http.cookiefile', default_path])
3065 return
3066
3067 if os.path.exists(default_path):
3068 print('WARNING: default .gitcookies file already exists %s' %
3069 default_path)
3070 DieWithError('Please delete %s manually and re-run git cl creds-check' %
3071 default_path)
3072
3073 confirm_or_exit('Move existing .gitcookies to default location?',
3074 action='move')
3075 shutil.move(configured_path, default_path)
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003076 RunGit(['config', '--global', 'http.cookiefile', default_path])
Andrii Shyshkalov517948b2017-03-15 15:51:59 +01003077 print('Moved and reconfigured git to use .gitcookies from %s' %
3078 default_path)
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003079
Andrii Shyshkalov517948b2017-03-15 15:51:59 +01003080 @staticmethod
3081 def _configure_gitcookies_path(default_path):
3082 netrc_path = gerrit_util.CookiesAuthenticator.get_netrc_path()
3083 if os.path.exists(netrc_path):
3084 print('You seem to be using outdated .netrc for git credentials: %s' %
3085 netrc_path)
3086 print('This tool will guide you through setting up recommended '
3087 '.gitcookies store for git credentials.\n'
3088 '\n'
3089 'IMPORTANT: If something goes wrong and you decide to go back, do:\n'
3090 ' git config --global --unset http.cookiefile\n'
3091 ' mv %s %s.backup\n\n' % (default_path, default_path))
3092 confirm_or_exit(action='setup .gitcookies')
3093 RunGit(['config', '--global', 'http.cookiefile', default_path])
3094 print('Configured git to use .gitcookies from %s' % default_path)
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003095
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003096 def get_hosts_with_creds(self, include_netrc=False):
3097 if self._all_hosts is None:
3098 a = gerrit_util.CookiesAuthenticator()
3099 self._all_hosts = [
3100 (h, u, s)
3101 for h, u, s in itertools.chain(
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00003102 ((h, u, '.netrc') for h, (u, _, _) in a.netrc.hosts.items()),
3103 ((h, u, '.gitcookies') for h, (u, _) in a.gitcookies.items())
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003104 )
3105 if h.endswith(self._GOOGLESOURCE)
3106 ]
3107
3108 if include_netrc:
3109 return self._all_hosts
3110 return [(h, u, s) for h, u, s in self._all_hosts if s != '.netrc']
3111
3112 def print_current_creds(self, include_netrc=False):
3113 hosts = sorted(self.get_hosts_with_creds(include_netrc=include_netrc))
3114 if not hosts:
3115 print('No Git/Gerrit credentials found')
3116 return
Edward Lemur79d4f992019-11-11 23:49:02 +00003117 lengths = [max(map(len, (row[i] for row in hosts))) for i in range(3)]
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003118 header = [('Host', 'User', 'Which file'),
3119 ['=' * l for l in lengths]]
3120 for row in (header + hosts):
3121 print('\t'.join((('%%+%ds' % l) % s)
3122 for l, s in zip(lengths, row)))
3123
Andrii Shyshkalov97800502017-03-16 16:04:32 +01003124 @staticmethod
3125 def _parse_identity(identity):
Lei Zhangd3f769a2017-12-15 15:16:14 -08003126 """Parses identity "git-<username>.domain" into <username> and domain."""
3127 # Special case: usernames that contain ".", which are generally not
Andrii Shyshkalov0d2dea02017-07-17 15:17:55 +02003128 # distinguishable from sub-domains. But we do know typical domains:
3129 if identity.endswith('.chromium.org'):
3130 domain = 'chromium.org'
3131 username = identity[:-len('.chromium.org')]
3132 else:
3133 username, domain = identity.split('.', 1)
Andrii Shyshkalov97800502017-03-16 16:04:32 +01003134 if username.startswith('git-'):
3135 username = username[len('git-'):]
3136 return username, domain
3137
Andrii Shyshkalov97800502017-03-16 16:04:32 +01003138 def _canonical_git_googlesource_host(self, host):
3139 """Normalizes Gerrit hosts (with '-review') to Git host."""
3140 assert host.endswith(self._GOOGLESOURCE)
3141 # Prefix doesn't include '.' at the end.
3142 prefix = host[:-(1 + len(self._GOOGLESOURCE))]
3143 if prefix.endswith('-review'):
3144 prefix = prefix[:-len('-review')]
3145 return prefix + '.' + self._GOOGLESOURCE
3146
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003147 def _canonical_gerrit_googlesource_host(self, host):
3148 git_host = self._canonical_git_googlesource_host(host)
3149 prefix = git_host.split('.', 1)[0]
3150 return prefix + '-review.' + self._GOOGLESOURCE
3151
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003152 def _get_counterpart_host(self, host):
3153 assert host.endswith(self._GOOGLESOURCE)
3154 git = self._canonical_git_googlesource_host(host)
3155 gerrit = self._canonical_gerrit_googlesource_host(git)
3156 return git if gerrit == host else gerrit
3157
Andrii Shyshkalov97800502017-03-16 16:04:32 +01003158 def has_generic_host(self):
3159 """Returns whether generic .googlesource.com has been configured.
3160
3161 Chrome Infra recommends to use explicit ${host}.googlesource.com instead.
3162 """
3163 for host, _, _ in self.get_hosts_with_creds(include_netrc=False):
3164 if host == '.' + self._GOOGLESOURCE:
3165 return True
3166 return False
3167
3168 def _get_git_gerrit_identity_pairs(self):
3169 """Returns map from canonic host to pair of identities (Git, Gerrit).
3170
3171 One of identities might be None, meaning not configured.
3172 """
3173 host_to_identity_pairs = {}
3174 for host, identity, _ in self.get_hosts_with_creds():
3175 canonical = self._canonical_git_googlesource_host(host)
3176 pair = host_to_identity_pairs.setdefault(canonical, [None, None])
3177 idx = 0 if canonical == host else 1
3178 pair[idx] = identity
3179 return host_to_identity_pairs
3180
3181 def get_partially_configured_hosts(self):
3182 return set(
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003183 (host if i1 else self._canonical_gerrit_googlesource_host(host))
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00003184 for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items()
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003185 if None in (i1, i2) and host != '.' + self._GOOGLESOURCE)
Andrii Shyshkalov97800502017-03-16 16:04:32 +01003186
3187 def get_conflicting_hosts(self):
3188 return set(
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003189 host
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00003190 for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items()
Andrii Shyshkalov97800502017-03-16 16:04:32 +01003191 if None not in (i1, i2) and i1 != i2)
3192
3193 def get_duplicated_hosts(self):
3194 counters = collections.Counter(h for h, _, _ in self.get_hosts_with_creds())
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00003195 return set(host for host, count in counters.items() if count > 1)
Andrii Shyshkalov97800502017-03-16 16:04:32 +01003196
3197 _EXPECTED_HOST_IDENTITY_DOMAINS = {
3198 'chromium.googlesource.com': 'chromium.org',
3199 'chrome-internal.googlesource.com': 'google.com',
3200 }
3201
3202 def get_hosts_with_wrong_identities(self):
3203 """Finds hosts which **likely** reference wrong identities.
3204
3205 Note: skips hosts which have conflicting identities for Git and Gerrit.
3206 """
3207 hosts = set()
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +00003208 for host, expected in self._EXPECTED_HOST_IDENTITY_DOMAINS.items():
Andrii Shyshkalov97800502017-03-16 16:04:32 +01003209 pair = self._get_git_gerrit_identity_pairs().get(host)
3210 if pair and pair[0] == pair[1]:
3211 _, domain = self._parse_identity(pair[0])
3212 if domain != expected:
3213 hosts.add(host)
3214 return hosts
3215
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003216 @staticmethod
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003217 def _format_hosts(hosts, extra_column_func=None):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003218 hosts = sorted(hosts)
3219 assert hosts
3220 if extra_column_func is None:
3221 extras = [''] * len(hosts)
3222 else:
3223 extras = [extra_column_func(host) for host in hosts]
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003224 tmpl = '%%-%ds %%-%ds' % (max(map(len, hosts)), max(map(len, extras)))
3225 lines = []
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003226 for he in zip(hosts, extras):
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003227 lines.append(tmpl % he)
3228 return lines
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003229
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003230 def _find_problems(self):
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003231 if self.has_generic_host():
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003232 yield ('.googlesource.com wildcard record detected',
3233 ['Chrome Infrastructure team recommends to list full host names '
3234 'explicitly.'],
3235 None)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003236
3237 dups = self.get_duplicated_hosts()
3238 if dups:
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003239 yield ('The following hosts were defined twice',
3240 self._format_hosts(dups),
3241 None)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003242
3243 partial = self.get_partially_configured_hosts()
3244 if partial:
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003245 yield ('Credentials should come in pairs for Git and Gerrit hosts. '
3246 'These hosts are missing',
3247 self._format_hosts(partial, lambda host: 'but %s defined' %
3248 self._get_counterpart_host(host)),
3249 partial)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003250
3251 conflicting = self.get_conflicting_hosts()
3252 if conflicting:
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003253 yield ('The following Git hosts have differing credentials from their '
3254 'Gerrit counterparts',
3255 self._format_hosts(conflicting, lambda host: '%s vs %s' %
3256 tuple(self._get_git_gerrit_identity_pairs()[host])),
3257 conflicting)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003258
3259 wrong = self.get_hosts_with_wrong_identities()
3260 if wrong:
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003261 yield ('These hosts likely use wrong identity',
3262 self._format_hosts(wrong, lambda host: '%s but %s recommended' %
3263 (self._get_git_gerrit_identity_pairs()[host][0],
3264 self._EXPECTED_HOST_IDENTITY_DOMAINS[host])),
3265 wrong)
3266
3267 def find_and_report_problems(self):
3268 """Returns True if there was at least one problem, else False."""
3269 found = False
3270 bad_hosts = set()
3271 for title, sublines, hosts in self._find_problems():
3272 if not found:
3273 found = True
3274 print('\n\n.gitcookies problem report:\n')
3275 bad_hosts.update(hosts or [])
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003276 print(' %s%s' % (title, (':' if sublines else '')))
Andrii Shyshkalovc8173822017-07-10 12:10:53 +02003277 if sublines:
3278 print()
3279 print(' %s' % '\n '.join(sublines))
3280 print()
3281
3282 if bad_hosts:
3283 assert found
3284 print(' You can manually remove corresponding lines in your %s file and '
3285 'visit the following URLs with correct account to generate '
3286 'correct credential lines:\n' %
3287 gerrit_util.CookiesAuthenticator.get_gitcookies_path())
3288 print(' %s' % '\n '.join(sorted(set(
3289 gerrit_util.CookiesAuthenticator().get_new_password_url(
3290 self._canonical_git_googlesource_host(host))
3291 for host in bad_hosts
3292 ))))
3293 return found
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003294
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003295
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00003296@metrics.collector.collect_metrics('git cl creds-check')
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003297def CMDcreds_check(parser, args):
3298 """Checks credentials and suggests changes."""
3299 _, _ = parser.parse_args(args)
3300
Vadim Shtayurab250ec12018-10-04 00:21:08 +00003301 # Code below checks .gitcookies. Abort if using something else.
3302 authn = gerrit_util.Authenticator.get()
3303 if not isinstance(authn, gerrit_util.CookiesAuthenticator):
Edward Lemur57d47422020-03-06 20:43:07 +00003304 message = (
Vadim Shtayurab250ec12018-10-04 00:21:08 +00003305 'This command is not designed for bot environment. It checks '
3306 '~/.gitcookies file not generally used on bots.')
Edward Lemur57d47422020-03-06 20:43:07 +00003307 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop.
3308 if isinstance(authn, gerrit_util.GceAuthenticator):
3309 message += (
3310 '\n'
3311 'If you need to run this on GCE or a cloudtop instance, '
3312 'export SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
3313 DieWithError(message)
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003314
Andrii Shyshkalov517948b2017-03-15 15:51:59 +01003315 checker = _GitCookiesChecker()
3316 checker.ensure_configured_gitcookies()
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003317
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003318 print('Your .netrc and .gitcookies have credentials for these hosts:')
Andrii Shyshkalov34924cd2017-03-15 17:08:32 +01003319 checker.print_current_creds(include_netrc=True)
3320
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003321 if not checker.find_and_report_problems():
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003322 print('\nNo problems detected in your .gitcookies file.')
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +01003323 return 0
3324 return 1
Andrii Shyshkalov353637c2017-03-14 16:52:18 +01003325
3326
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00003327@metrics.collector.collect_metrics('git cl baseurl')
kalmard@homejinni.com6b0051e2012-04-03 15:45:08 +00003328def CMDbaseurl(parser, args):
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00003329 """Gets or sets base-url for this branch."""
Edward Lesmescba46082020-03-25 00:29:06 +00003330 branchref = RunGit(['symbolic-ref', 'HEAD']).strip()
Edward Lemur85153282020-02-14 22:06:29 +00003331 branch = scm.GIT.ShortBranchName(branchref)
kalmard@homejinni.com6b0051e2012-04-03 15:45:08 +00003332 _, args = parser.parse_args(args)
3333 if not args:
vapiera7fbd5a2016-06-16 09:17:49 -07003334 print('Current base-url:')
kalmard@homejinni.com6b0051e2012-04-03 15:45:08 +00003335 return RunGit(['config', 'branch.%s.base-url' % branch],
3336 error_ok=False).strip()
3337 else:
vapiera7fbd5a2016-06-16 09:17:49 -07003338 print('Setting base-url to %s' % args[0])
kalmard@homejinni.com6b0051e2012-04-03 15:45:08 +00003339 return RunGit(['config', 'branch.%s.base-url' % branch, args[0]],
3340 error_ok=False).strip()
3341
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003342
jsbell@chromium.orgb99fbd92014-09-11 17:29:28 +00003343def color_for_status(status):
3344 """Maps a Changelist status to color, for CMDstatus and other tools."""
3345 return {
Aaron Gable9ab38c62017-04-06 14:36:33 -07003346 'unsent': Fore.YELLOW,
jsbell@chromium.orgb99fbd92014-09-11 17:29:28 +00003347 'waiting': Fore.BLUE,
3348 'reply': Fore.YELLOW,
Aaron Gable9ab38c62017-04-06 14:36:33 -07003349 'not lgtm': Fore.RED,
jsbell@chromium.orgb99fbd92014-09-11 17:29:28 +00003350 'lgtm': Fore.GREEN,
3351 'commit': Fore.MAGENTA,
3352 'closed': Fore.CYAN,
3353 'error': Fore.WHITE,
3354 }.get(status, Fore.WHITE)
3355
tandrii@chromium.org04ea8462016-04-25 19:51:21 +00003356
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +00003357def get_cl_statuses(changes, fine_grained, max_processes=None):
3358 """Returns a blocking iterable of (cl, status) for given branches.
calamity@chromium.orgffde55c2015-03-12 00:44:17 +00003359
3360 If fine_grained is true, this will fetch CL statuses from the server.
3361 Otherwise, simply indicate if there's a matching url for the given branches.
3362
3363 If max_processes is specified, it is used as the maximum number of processes
3364 to spawn to fetch CL status from the server. Otherwise 1 process per branch is
3365 spawned.
calamity@chromium.orgcf197482016-04-29 20:15:53 +00003366
3367 See GetStatus() for a list of possible statuses.
calamity@chromium.orgffde55c2015-03-12 00:44:17 +00003368 """
Andrii Shyshkalov2f8e9242017-01-23 19:20:19 +01003369 if not changes:
Edward Lemur61bf4172020-02-24 23:22:37 +00003370 return
calamity@chromium.orgcf197482016-04-29 20:15:53 +00003371
Andrii Shyshkalov2f8e9242017-01-23 19:20:19 +01003372 if not fine_grained:
3373 # Fast path which doesn't involve querying codereview servers.
Aaron Gablea1bab272017-04-11 16:38:18 -07003374 # Do not use get_approving_reviewers(), since it requires an HTTP request.
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +00003375 for cl in changes:
3376 yield (cl, 'waiting' if cl.GetIssueURL() else 'error')
Andrii Shyshkalov2f8e9242017-01-23 19:20:19 +01003377 return
3378
3379 # First, sort out authentication issues.
3380 logging.debug('ensuring credentials exist')
3381 for cl in changes:
3382 cl.EnsureAuthenticated(force=False, refresh=True)
3383
3384 def fetch(cl):
3385 try:
3386 return (cl, cl.GetStatus())
3387 except:
3388 # See http://crbug.com/629863.
Andrii Shyshkalov98824232018-04-19 11:37:15 -07003389 logging.exception('failed to fetch status for cl %s:', cl.GetIssue())
Andrii Shyshkalov2f8e9242017-01-23 19:20:19 +01003390 raise
3391
3392 threads_count = len(changes)
3393 if max_processes:
3394 threads_count = max(1, min(threads_count, max_processes))
3395 logging.debug('querying %d CLs using %d threads', len(changes), threads_count)
3396
Edward Lemur61bf4172020-02-24 23:22:37 +00003397 pool = multiprocessing.pool.ThreadPool(threads_count)
Andrii Shyshkalov2f8e9242017-01-23 19:20:19 +01003398 fetched_cls = set()
3399 try:
3400 it = pool.imap_unordered(fetch, changes).__iter__()
3401 while True:
3402 try:
3403 cl, status = it.next(timeout=5)
Edward Lemur61bf4172020-02-24 23:22:37 +00003404 except (multiprocessing.TimeoutError, StopIteration):
Andrii Shyshkalov2f8e9242017-01-23 19:20:19 +01003405 break
3406 fetched_cls.add(cl)
3407 yield cl, status
3408 finally:
3409 pool.close()
3410
3411 # Add any branches that failed to fetch.
3412 for cl in set(changes) - fetched_cls:
3413 yield (cl, 'error')
jsbell@chromium.orgb99fbd92014-09-11 17:29:28 +00003414
rmistry@google.com2dd99862015-06-22 12:22:18 +00003415
3416def upload_branch_deps(cl, args):
3417 """Uploads CLs of local branches that are dependents of the current branch.
3418
3419 If the local branch dependency tree looks like:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003420
3421 test1 -> test2.1 -> test3.1
3422 -> test3.2
3423 -> test2.2 -> test3.3
rmistry@google.com2dd99862015-06-22 12:22:18 +00003424
3425 and you run "git cl upload --dependencies" from test1 then "git cl upload" is
3426 run on the dependent branches in this order:
3427 test2.1, test3.1, test3.2, test2.2, test3.3
3428
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003429 Note: This function does not rebase your local dependent branches. Use it
3430 when you make a change to the parent branch that will not conflict
3431 with its dependent branches, and you would like their dependencies
3432 updated in Rietveld.
rmistry@google.com2dd99862015-06-22 12:22:18 +00003433 """
3434 if git_common.is_dirty_git_tree('upload-branch-deps'):
3435 return 1
3436
3437 root_branch = cl.GetBranch()
3438 if root_branch is None:
3439 DieWithError('Can\'t find dependent branches from detached HEAD state. '
3440 'Get on a branch!')
Andrii Shyshkalov9f274432018-10-15 16:40:23 +00003441 if not cl.GetIssue():
rmistry@google.com2dd99862015-06-22 12:22:18 +00003442 DieWithError('Current branch does not have an uploaded CL. We cannot set '
3443 'patchset dependencies without an uploaded CL.')
3444
3445 branches = RunGit(['for-each-ref',
3446 '--format=%(refname:short) %(upstream:short)',
3447 'refs/heads'])
3448 if not branches:
3449 print('No local branches found.')
3450 return 0
3451
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003452 # Create a dictionary of all local branches to the branches that are
3453 # dependent on it.
rmistry@google.com2dd99862015-06-22 12:22:18 +00003454 tracked_to_dependents = collections.defaultdict(list)
3455 for b in branches.splitlines():
3456 tokens = b.split()
3457 if len(tokens) == 2:
3458 branch_name, tracked = tokens
3459 tracked_to_dependents[tracked].append(branch_name)
3460
vapiera7fbd5a2016-06-16 09:17:49 -07003461 print()
3462 print('The dependent local branches of %s are:' % root_branch)
rmistry@google.com2dd99862015-06-22 12:22:18 +00003463 dependents = []
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003464
rmistry@google.com2dd99862015-06-22 12:22:18 +00003465 def traverse_dependents_preorder(branch, padding=''):
3466 dependents_to_process = tracked_to_dependents.get(branch, [])
3467 padding += ' '
3468 for dependent in dependents_to_process:
vapiera7fbd5a2016-06-16 09:17:49 -07003469 print('%s%s' % (padding, dependent))
rmistry@google.com2dd99862015-06-22 12:22:18 +00003470 dependents.append(dependent)
3471 traverse_dependents_preorder(dependent, padding)
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00003472
rmistry@google.com2dd99862015-06-22 12:22:18 +00003473 traverse_dependents_preorder(root_branch)
vapiera7fbd5a2016-06-16 09:17:49 -07003474 print()
rmistry@google.com2dd99862015-06-22 12:22:18 +00003475
3476 if not dependents:
vapiera7fbd5a2016-06-16 09:17:49 -07003477 print('There are no dependent local branches for %s' % root_branch)
rmistry@google.com2dd99862015-06-22 12:22:18 +00003478 return 0
3479
Andrii Shyshkalovabc26ac2017-03-14 14:49:38 +01003480 confirm_or_exit('This command will checkout all dependent branches and run '
3481 '"git cl upload".', action='continue')
rmistry@google.com2dd99862015-06-22 12:22:18 +00003482
rmistry@google.com2dd99862015-06-22 12:22:18 +00003483 # Record all dependents that failed to upload.
3484 failures = {}
3485 # Go through all dependents, checkout the branch and upload.
3486 try:
3487 for dependent_branch in dependents:
vapiera7fbd5a2016-06-16 09:17:49 -07003488 print()
3489 print('--------------------------------------')
3490 print('Running "git cl upload" from %s:' % dependent_branch)
rmistry@google.com2dd99862015-06-22 12:22:18 +00003491 RunGit(['checkout', '-q', dependent_branch])
vapiera7fbd5a2016-06-16 09:17:49 -07003492 print()
rmistry@google.com2dd99862015-06-22 12:22:18 +00003493 try:
3494 if CMDupload(OptionParser(), args) != 0:
vapiera7fbd5a2016-06-16 09:17:49 -07003495 print('Upload failed for %s!' % dependent_branch)
rmistry@google.com2dd99862015-06-22 12:22:18 +00003496 failures[dependent_branch] = 1
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -08003497 except: # pylint: disable=bare-except
rmistry@google.com2dd99862015-06-22 12:22:18 +00003498 failures[dependent_branch] = 1
vapiera7fbd5a2016-06-16 09:17:49 -07003499 print()
rmistry@google.com2dd99862015-06-22 12:22:18 +00003500 finally:
3501 # Swap back to the original root branch.
3502 RunGit(['checkout', '-q', root_branch])
3503
vapiera7fbd5a2016-06-16 09:17:49 -07003504 print()
3505 print('Upload complete for dependent branches!')
rmistry@google.com2dd99862015-06-22 12:22:18 +00003506 for dependent_branch in dependents:
3507 upload_status = 'failed' if failures.get(dependent_branch) else 'succeeded'
vapiera7fbd5a2016-06-16 09:17:49 -07003508 print(' %s : %s' % (dependent_branch, upload_status))
3509 print()
rmistry@google.com2dd99862015-06-22 12:22:18 +00003510
3511 return 0
3512
3513
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00003514def GetArchiveTagForBranch(issue_num, branch_name, existing_tags, pattern):
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00003515 """Given a proposed tag name, returns a tag name that is guaranteed to be
3516 unique. If 'foo' is proposed but already exists, then 'foo-2' is used,
3517 or 'foo-3', and so on."""
3518
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00003519 proposed_tag = pattern.format(**{'issue': issue_num, 'branch': branch_name})
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00003520 for suffix_num in itertools.count(1):
3521 if suffix_num == 1:
3522 to_check = proposed_tag
3523 else:
3524 to_check = '%s-%d' % (proposed_tag, suffix_num)
3525
3526 if to_check not in existing_tags:
3527 return to_check
3528
3529
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00003530@metrics.collector.collect_metrics('git cl archive')
kmarshall3bff56b2016-06-06 18:31:47 -07003531def CMDarchive(parser, args):
3532 """Archives and deletes branches associated with closed changelists."""
3533 parser.add_option(
3534 '-j', '--maxjobs', action='store', type=int,
kmarshall9249e012016-08-23 12:02:16 -07003535 help='The maximum number of jobs to use when retrieving review status.')
kmarshall3bff56b2016-06-06 18:31:47 -07003536 parser.add_option(
3537 '-f', '--force', action='store_true',
3538 help='Bypasses the confirmation prompt.')
kmarshall9249e012016-08-23 12:02:16 -07003539 parser.add_option(
3540 '-d', '--dry-run', action='store_true',
3541 help='Skip the branch tagging and removal steps.')
3542 parser.add_option(
3543 '-t', '--notags', action='store_true',
3544 help='Do not tag archived branches. '
3545 'Note: local commit history may be lost.')
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00003546 parser.add_option(
3547 '-p',
3548 '--pattern',
3549 default='git-cl-archived-{issue}-{branch}',
3550 help='Format string for archive tags. '
3551 'E.g. \'archived-{issue}-{branch}\'.')
kmarshall3bff56b2016-06-06 18:31:47 -07003552
kmarshall3bff56b2016-06-06 18:31:47 -07003553 options, args = parser.parse_args(args)
3554 if args:
3555 parser.error('Unsupported args: %s' % ' '.join(args))
kmarshall3bff56b2016-06-06 18:31:47 -07003556
3557 branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
3558 if not branches:
3559 return 0
3560
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00003561 tags = RunGit(['for-each-ref', '--format=%(refname)',
3562 'refs/tags']).splitlines() or []
3563 tags = [t.split('/')[-1] for t in tags]
3564
vapiera7fbd5a2016-06-16 09:17:49 -07003565 print('Finding all branches associated with closed issues...')
Edward Lemur934836a2019-09-09 20:16:54 +00003566 changes = [Changelist(branchref=b)
3567 for b in branches.splitlines()]
kmarshall3bff56b2016-06-06 18:31:47 -07003568 alignment = max(5, max(len(c.GetBranch()) for c in changes))
3569 statuses = get_cl_statuses(changes,
3570 fine_grained=True,
3571 max_processes=options.maxjobs)
3572 proposal = [(cl.GetBranch(),
Tibor Goldschwendt7c5efb22020-03-25 01:23:54 +00003573 GetArchiveTagForBranch(cl.GetIssue(), cl.GetBranch(), tags,
3574 options.pattern))
kmarshall3bff56b2016-06-06 18:31:47 -07003575 for cl, status in statuses
Andrii Shyshkalov51bdf8c2018-10-18 01:07:58 +00003576 if status in ('closed', 'rietveld-not-supported')]
kmarshall3bff56b2016-06-06 18:31:47 -07003577 proposal.sort()
3578
3579 if not proposal:
vapiera7fbd5a2016-06-16 09:17:49 -07003580 print('No branches with closed codereview issues found.')
kmarshall3bff56b2016-06-06 18:31:47 -07003581 return 0
3582
Edward Lemur85153282020-02-14 22:06:29 +00003583 current_branch = scm.GIT.GetBranch(settings.GetRoot())
kmarshall3bff56b2016-06-06 18:31:47 -07003584
vapiera7fbd5a2016-06-16 09:17:49 -07003585 print('\nBranches with closed issues that will be archived:\n')
kmarshall9249e012016-08-23 12:02:16 -07003586 if options.notags:
3587 for next_item in proposal:
3588 print(' ' + next_item[0])
3589 else:
3590 print('%*s | %s' % (alignment, 'Branch name', 'Archival tag name'))
3591 for next_item in proposal:
3592 print('%*s %s' % (alignment, next_item[0], next_item[1]))
kmarshall3bff56b2016-06-06 18:31:47 -07003593
kmarshall9249e012016-08-23 12:02:16 -07003594 # Quit now on precondition failure or if instructed by the user, either
3595 # via an interactive prompt or by command line flags.
3596 if options.dry_run:
3597 print('\nNo changes were made (dry run).\n')
3598 return 0
3599 elif any(branch == current_branch for branch, _ in proposal):
kmarshall3bff56b2016-06-06 18:31:47 -07003600 print('You are currently on a branch \'%s\' which is associated with a '
3601 'closed codereview issue, so archive cannot proceed. Please '
3602 'checkout another branch and run this command again.' %
3603 current_branch)
3604 return 1
kmarshall9249e012016-08-23 12:02:16 -07003605 elif not options.force:
Edward Lesmesae3586b2020-03-23 21:21:14 +00003606 answer = gclient_utils.AskForData('\nProceed with deletion (Y/n)? ').lower()
sergiyb4a5ecbe2016-06-20 09:46:00 -07003607 if answer not in ('y', ''):
vapiera7fbd5a2016-06-16 09:17:49 -07003608 print('Aborted.')
kmarshall3bff56b2016-06-06 18:31:47 -07003609 return 1
3610
3611 for branch, tagname in proposal:
kmarshall9249e012016-08-23 12:02:16 -07003612 if not options.notags:
3613 RunGit(['tag', tagname, branch])
Kevin Marshall0e60ecd2019-12-04 17:44:13 +00003614
3615 if RunGitWithCode(['branch', '-D', branch])[0] != 0:
3616 # Clean up the tag if we failed to delete the branch.
3617 RunGit(['tag', '-d', tagname])
kmarshall9249e012016-08-23 12:02:16 -07003618
vapiera7fbd5a2016-06-16 09:17:49 -07003619 print('\nJob\'s done!')
kmarshall3bff56b2016-06-06 18:31:47 -07003620
3621 return 0
3622
3623
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00003624@metrics.collector.collect_metrics('git cl status')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003625def CMDstatus(parser, args):
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00003626 """Show status of changelists.
3627
3628 Colors are used to tell the state of the CL unless --fast is used:
jsbell@chromium.orgaeab41a2013-12-10 20:01:22 +00003629 - Blue waiting for review
Aaron Gable9ab38c62017-04-06 14:36:33 -07003630 - Yellow waiting for you to reply to review, or not yet sent
jsbell@chromium.orgaeab41a2013-12-10 20:01:22 +00003631 - Green LGTM'ed
Aaron Gable9ab38c62017-04-06 14:36:33 -07003632 - Red 'not LGTM'ed
Andrii Shyshkalov0e889b72019-07-15 22:28:48 +00003633 - Magenta in the CQ
jsbell@chromium.orgaeab41a2013-12-10 20:01:22 +00003634 - Cyan was committed, branch can be deleted
Aaron Gable9ab38c62017-04-06 14:36:33 -07003635 - White error, or unknown status
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00003636
3637 Also see 'git cl comments'.
3638 """
Alan Cuttera3be9a52019-03-04 18:50:33 +00003639 parser.add_option(
3640 '--no-branch-color',
3641 action='store_true',
3642 help='Disable colorized branch names')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003643 parser.add_option('--field',
phajdan.jr289d03e2016-08-16 08:21:06 -07003644 help='print only specific field (desc|id|patch|status|url)')
maruel@chromium.org1033efd2013-07-23 23:25:09 +00003645 parser.add_option('-f', '--fast', action='store_true',
3646 help='Do not retrieve review status')
calamity@chromium.orgffde55c2015-03-12 00:44:17 +00003647 parser.add_option(
3648 '-j', '--maxjobs', action='store', type=int,
3649 help='The maximum number of jobs to use when retrieving review status')
Edward Lemur52969c92020-02-06 18:15:28 +00003650 parser.add_option(
3651 '-i', '--issue', type=int,
3652 help='Operate on this issue instead of the current branch\'s implicit '
3653 'issue. Requires --field to be set.')
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00003654 options, args = parser.parse_args(args)
maruel@chromium.org39c0b222013-08-17 16:57:01 +00003655 if args:
3656 parser.error('Unsupported args: %s' % args)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003657
iannuccie53c9352016-08-17 14:40:40 -07003658 if options.issue is not None and not options.field:
Edward Lemur6c6827c2020-02-06 21:15:18 +00003659 parser.error('--field must be given when --issue is set.')
iannucci3c972b92016-08-17 13:24:10 -07003660
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003661 if options.field:
Edward Lemur934836a2019-09-09 20:16:54 +00003662 cl = Changelist(issue=options.issue)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003663 if options.field.startswith('desc'):
Edward Lemur6c6827c2020-02-06 21:15:18 +00003664 if cl.GetIssue():
3665 print(cl.FetchDescription())
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003666 elif options.field == 'id':
3667 issueid = cl.GetIssue()
3668 if issueid:
vapiera7fbd5a2016-06-16 09:17:49 -07003669 print(issueid)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003670 elif options.field == 'patch':
Aaron Gablee8856ee2017-12-07 12:41:46 -08003671 patchset = cl.GetMostRecentPatchset()
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003672 if patchset:
vapiera7fbd5a2016-06-16 09:17:49 -07003673 print(patchset)
phajdan.jr289d03e2016-08-16 08:21:06 -07003674 elif options.field == 'status':
3675 print(cl.GetStatus())
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003676 elif options.field == 'url':
3677 url = cl.GetIssueURL()
3678 if url:
vapiera7fbd5a2016-06-16 09:17:49 -07003679 print(url)
maruel@chromium.orge25c75b2013-07-23 18:30:56 +00003680 return 0
3681
3682 branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
3683 if not branches:
3684 print('No local branch found.')
3685 return 0
3686
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +00003687 changes = [
Edward Lemur934836a2019-09-09 20:16:54 +00003688 Changelist(branchref=b)
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +00003689 for b in branches.splitlines()]
vapiera7fbd5a2016-06-16 09:17:49 -07003690 print('Branches associated with reviews:')
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +00003691 output = get_cl_statuses(changes,
calamity@chromium.orgffde55c2015-03-12 00:44:17 +00003692 fine_grained=not options.fast,
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +00003693 max_processes=options.maxjobs)
maruel@chromium.org1033efd2013-07-23 23:25:09 +00003694
Edward Lemur85153282020-02-14 22:06:29 +00003695 current_branch = scm.GIT.GetBranch(settings.GetRoot())
Daniel McArdlea23bf592019-02-12 00:25:12 +00003696
3697 def FormatBranchName(branch, colorize=False):
3698 """Simulates 'git branch' behavior. Colorizes and prefixes branch name with
3699 an asterisk when it is the current branch."""
3700
3701 asterisk = ""
3702 color = Fore.RESET
3703 if branch == current_branch:
3704 asterisk = "* "
3705 color = Fore.GREEN
Edward Lemur85153282020-02-14 22:06:29 +00003706 branch_name = scm.GIT.ShortBranchName(branch)
Daniel McArdlea23bf592019-02-12 00:25:12 +00003707
3708 if colorize:
3709 return asterisk + color + branch_name + Fore.RESET
Daniel McArdle452a49f2019-02-14 17:28:31 +00003710 return asterisk + branch_name
3711
calamity@chromium.orgffde55c2015-03-12 00:44:17 +00003712 branch_statuses = {}
Daniel McArdlea23bf592019-02-12 00:25:12 +00003713
3714 alignment = max(5, max(len(FormatBranchName(c.GetBranch())) for c in changes))
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +00003715 for cl in sorted(changes, key=lambda c: c.GetBranch()):
3716 branch = cl.GetBranch()
calamity@chromium.orgffde55c2015-03-12 00:44:17 +00003717 while branch not in branch_statuses:
Edward Lemur79d4f992019-11-11 23:49:02 +00003718 c, status = next(output)
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +00003719 branch_statuses[c.GetBranch()] = status
3720 status = branch_statuses.pop(branch)
Andrii Shyshkalov1ee78cd2020-03-12 01:31:53 +00003721 url = cl.GetIssueURL(short=True)
clemensh@chromium.orgcbd7dc32016-05-31 10:33:50 +00003722 if url and (not status or status == 'error'):
3723 # The issue probably doesn't exist anymore.
3724 url += ' (broken)'
3725
nodir@chromium.orga6de1f42015-06-10 04:23:17 +00003726 color = color_for_status(status)
maruel@chromium.org885f6512013-07-27 02:17:26 +00003727 reset = Fore.RESET
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +00003728 if not setup_color.IS_TTY:
maruel@chromium.org885f6512013-07-27 02:17:26 +00003729 color = ''
3730 reset = ''
nodir@chromium.orga6de1f42015-06-10 04:23:17 +00003731 status_str = '(%s)' % status if status else ''
Daniel McArdle452a49f2019-02-14 17:28:31 +00003732
Alan Cuttera3be9a52019-03-04 18:50:33 +00003733 branch_display = FormatBranchName(branch)
3734 padding = ' ' * (alignment - len(branch_display))
3735 if not options.no_branch_color:
3736 branch_display = FormatBranchName(branch, colorize=True)
Daniel McArdle452a49f2019-02-14 17:28:31 +00003737
Alan Cuttera3be9a52019-03-04 18:50:33 +00003738 print(' %s : %s%s %s%s' % (padding + branch_display, color, url,
3739 status_str, reset))
Andrii Shyshkalovd0e1d9d2017-01-24 17:10:51 +01003740
vapiera7fbd5a2016-06-16 09:17:49 -07003741 print()
Daniel McArdlea23bf592019-02-12 00:25:12 +00003742 print('Current branch: %s' % current_branch)
Andrii Shyshkalovd0e1d9d2017-01-24 17:10:51 +01003743 for cl in changes:
Daniel McArdlea23bf592019-02-12 00:25:12 +00003744 if cl.GetBranch() == current_branch:
Andrii Shyshkalovd0e1d9d2017-01-24 17:10:51 +01003745 break
dpranke@chromium.orgee87f582015-07-31 18:46:25 +00003746 if not cl.GetIssue():
vapiera7fbd5a2016-06-16 09:17:49 -07003747 print('No issue assigned.')
dpranke@chromium.orgee87f582015-07-31 18:46:25 +00003748 return 0
vapiera7fbd5a2016-06-16 09:17:49 -07003749 print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()))
maruel@chromium.org85616e02014-07-28 15:37:55 +00003750 if not options.fast:
vapiera7fbd5a2016-06-16 09:17:49 -07003751 print('Issue description:')
Edward Lemur6c6827c2020-02-06 21:15:18 +00003752 print(cl.FetchDescription(pretty=True))
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003753 return 0
3754
3755
maruel@chromium.org39c0b222013-08-17 16:57:01 +00003756def colorize_CMDstatus_doc():
3757 """To be called once in main() to add colors to git cl status help."""
3758 colors = [i for i in dir(Fore) if i[0].isupper()]
3759
3760 def colorize_line(line):
3761 for color in colors:
3762 if color in line.upper():
Quinten Yearsley0c62da92017-05-31 13:39:42 -07003763 # Extract whitespace first and the leading '-'.
maruel@chromium.org39c0b222013-08-17 16:57:01 +00003764 indent = len(line) - len(line.lstrip(' ')) + 1
3765 return line[:indent] + getattr(Fore, color) + line[indent:] + Fore.RESET
3766 return line
3767
3768 lines = CMDstatus.__doc__.splitlines()
3769 CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines)
3770
3771
phajdan.jre328cf92016-08-22 04:12:17 -07003772def write_json(path, contents):
Stefan Zager1306bd02017-06-22 19:26:46 -07003773 if path == '-':
3774 json.dump(contents, sys.stdout)
3775 else:
3776 with open(path, 'w') as f:
3777 json.dump(contents, f)
phajdan.jre328cf92016-08-22 04:12:17 -07003778
3779
maruel@chromium.org0633fb42013-08-16 20:06:14 +00003780@subcommand.usage('[issue_number]')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00003781@metrics.collector.collect_metrics('git cl issue')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003782def CMDissue(parser, args):
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00003783 """Sets or displays the current code review issue number.
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003784
3785 Pass issue number 0 to clear the current issue.
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00003786 """
dnj@chromium.org406c4402015-03-03 17:22:28 +00003787 parser.add_option('-r', '--reverse', action='store_true',
3788 help='Lookup the branch(es) for the specified issues. If '
3789 'no issues are specified, all branches with mapped '
3790 'issues will be listed.')
Stefan Zager1306bd02017-06-22 19:26:46 -07003791 parser.add_option('--json',
3792 help='Path to JSON output file, or "-" for stdout.')
dnj@chromium.org406c4402015-03-03 17:22:28 +00003793 options, args = parser.parse_args(args)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003794
dnj@chromium.org406c4402015-03-03 17:22:28 +00003795 if options.reverse:
3796 branches = RunGit(['for-each-ref', 'refs/heads',
Aaron Gablead64abd2017-12-04 09:49:13 -08003797 '--format=%(refname)']).splitlines()
dnj@chromium.org406c4402015-03-03 17:22:28 +00003798 # Reverse issue lookup.
3799 issue_branch_map = {}
Daniel Bratellb56a43a2018-09-06 15:49:03 +00003800
3801 git_config = {}
3802 for config in RunGit(['config', '--get-regexp',
3803 r'branch\..*issue']).splitlines():
3804 name, _space, val = config.partition(' ')
3805 git_config[name] = val
3806
dnj@chromium.org406c4402015-03-03 17:22:28 +00003807 for branch in branches:
Edward Lesmescba46082020-03-25 00:29:06 +00003808 config_key = _git_branch_config_key(scm.GIT.ShortBranchName(branch),
3809 Changelist.IssueConfigKey())
3810 issue = git_config.get(config_key)
Edward Lemur52969c92020-02-06 18:15:28 +00003811 if issue:
3812 issue_branch_map.setdefault(int(issue), []).append(branch)
dnj@chromium.org406c4402015-03-03 17:22:28 +00003813 if not args:
3814 args = sorted(issue_branch_map.iterkeys())
phajdan.jre328cf92016-08-22 04:12:17 -07003815 result = {}
dnj@chromium.org406c4402015-03-03 17:22:28 +00003816 for issue in args:
Lei Zhang5a368d42019-03-25 23:18:19 +00003817 try:
3818 issue_num = int(issue)
3819 except ValueError:
3820 print('ERROR cannot parse issue number: %s' % issue, file=sys.stderr)
dnj@chromium.org406c4402015-03-03 17:22:28 +00003821 continue
Lei Zhang5a368d42019-03-25 23:18:19 +00003822 result[issue_num] = issue_branch_map.get(issue_num)
vapiera7fbd5a2016-06-16 09:17:49 -07003823 print('Branch for issue number %s: %s' % (
Lei Zhang5a368d42019-03-25 23:18:19 +00003824 issue, ', '.join(issue_branch_map.get(issue_num) or ('None',))))
phajdan.jre328cf92016-08-22 04:12:17 -07003825 if options.json:
3826 write_json(options.json, result)
Aaron Gable78753da2017-06-15 10:35:49 -07003827 return 0
3828
3829 if len(args) > 0:
Edward Lemurf38bc172019-09-03 21:02:13 +00003830 issue = ParseIssueNumberArgument(args[0])
Aaron Gable78753da2017-06-15 10:35:49 -07003831 if not issue.valid:
3832 DieWithError('Pass a url or number to set the issue, 0 to unset it, '
3833 'or no argument to list it.\n'
3834 'Maybe you want to run git cl status?')
Edward Lemurf38bc172019-09-03 21:02:13 +00003835 cl = Changelist()
Aaron Gable78753da2017-06-15 10:35:49 -07003836 cl.SetIssue(issue.issue)
dnj@chromium.org406c4402015-03-03 17:22:28 +00003837 else:
Edward Lemurf38bc172019-09-03 21:02:13 +00003838 cl = Changelist()
Aaron Gable78753da2017-06-15 10:35:49 -07003839 print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()))
3840 if options.json:
3841 write_json(options.json, {
3842 'issue': cl.GetIssue(),
3843 'issue_url': cl.GetIssueURL(),
3844 })
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00003845 return 0
3846
3847
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00003848@metrics.collector.collect_metrics('git cl comments')
maruel@chromium.org9977a2e2012-06-06 22:30:56 +00003849def CMDcomments(parser, args):
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003850 """Shows or posts review comments for any changelist."""
3851 parser.add_option('-a', '--add-comment', dest='comment',
3852 help='comment to add to an issue')
Sergiy Byelozyorovcb629a42018-10-28 19:20:39 +00003853 parser.add_option('-p', '--publish', action='store_true',
3854 help='marks CL as ready and sends comment to reviewers')
Andrii Shyshkalov0d6b46e2017-03-17 22:23:22 +01003855 parser.add_option('-i', '--issue', dest='issue',
Edward Lemurf38bc172019-09-03 21:02:13 +00003856 help='review issue id (defaults to current issue).')
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07003857 parser.add_option('-m', '--machine-readable', dest='readable',
3858 action='store_false', default=True,
3859 help='output comments in a format compatible with '
3860 'editor parsing')
smut@google.comc85ac942015-09-15 16:34:43 +00003861 parser.add_option('-j', '--json-file',
Stefan Zager1306bd02017-06-22 19:26:46 -07003862 help='File to write JSON summary to, or "-" for stdout')
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003863 options, args = parser.parse_args(args)
maruel@chromium.org9977a2e2012-06-06 22:30:56 +00003864
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003865 issue = None
3866 if options.issue:
3867 try:
3868 issue = int(options.issue)
3869 except ValueError:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00003870 DieWithError('A review issue ID is expected to be a number.')
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003871
Edward Lemur934836a2019-09-09 20:16:54 +00003872 cl = Changelist(issue=issue)
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003873
3874 if options.comment:
Sergiy Byelozyorovcb629a42018-10-28 19:20:39 +00003875 cl.AddComment(options.comment, options.publish)
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003876 return 0
3877
Aaron Gable0ffdf2d2017-06-05 13:01:17 -07003878 summary = sorted(cl.GetCommentsSummary(readable=options.readable),
3879 key=lambda c: c.date)
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01003880 for comment in summary:
3881 if comment.disapproval:
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003882 color = Fore.RED
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01003883 elif comment.approval:
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003884 color = Fore.GREEN
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01003885 elif comment.sender == cl.GetIssueOwner():
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003886 color = Fore.MAGENTA
Quinten Yearsley0e617c02019-02-20 00:37:03 +00003887 elif comment.autogenerated:
3888 color = Fore.CYAN
apavlov@chromium.orge4efd512014-11-05 09:05:29 +00003889 else:
3890 color = Fore.BLUE
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01003891 print('\n%s%s %s%s\n%s' % (
3892 color,
3893 comment.date.strftime('%Y-%m-%d %H:%M:%S UTC'),
3894 comment.sender,
3895 Fore.RESET,
3896 '\n'.join(' ' + l for l in comment.message.strip().splitlines())))
3897
smut@google.comc85ac942015-09-15 16:34:43 +00003898 if options.json_file:
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01003899 def pre_serialize(c):
Edward Lemur79d4f992019-11-11 23:49:02 +00003900 dct = c._asdict().copy()
Andrii Shyshkalovd8aa49f2017-03-17 16:05:49 +01003901 dct['date'] = dct['date'].strftime('%Y-%m-%d %H:%M:%S.%f')
3902 return dct
Edward Lemur79d4f992019-11-11 23:49:02 +00003903 write_json(options.json_file, [pre_serialize(x) for x in summary])
maruel@chromium.org9977a2e2012-06-06 22:30:56 +00003904 return 0
3905
3906
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00003907@subcommand.usage('[codereview url or issue id]')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00003908@metrics.collector.collect_metrics('git cl description')
rsesek@chromium.orgeec76592013-05-20 16:27:57 +00003909def CMDdescription(parser, args):
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00003910 """Brings up the editor for the current CL's description."""
smut@google.com34fb6b12015-07-13 20:03:26 +00003911 parser.add_option('-d', '--display', action='store_true',
3912 help='Display the description instead of opening an editor')
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00003913 parser.add_option('-n', '--new-description',
dnjba1b0f32016-09-02 12:37:42 -07003914 help='New description to set for this issue (- for stdin, '
3915 '+ to load from local commit HEAD)')
dsansomee2d6fd92016-09-08 00:10:47 -07003916 parser.add_option('-f', '--force', action='store_true',
3917 help='Delete any unpublished Gerrit edits for this issue '
3918 'without prompting')
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00003919
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00003920 options, args = parser.parse_args(args)
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00003921
Andrii Shyshkalov8039be72017-01-26 09:38:18 +01003922 target_issue_arg = None
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00003923 if len(args) > 0:
Edward Lemurf38bc172019-09-03 21:02:13 +00003924 target_issue_arg = ParseIssueNumberArgument(args[0])
Andrii Shyshkalov8039be72017-01-26 09:38:18 +01003925 if not target_issue_arg.valid:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00003926 parser.error('Invalid issue ID or URL.')
martiniss@chromium.org2b55fe32016-04-26 20:28:54 +00003927
Edward Lemur934836a2019-09-09 20:16:54 +00003928 kwargs = {}
Andrii Shyshkalov8039be72017-01-26 09:38:18 +01003929 if target_issue_arg:
3930 kwargs['issue'] = target_issue_arg.issue
3931 kwargs['codereview_host'] = target_issue_arg.hostname
martiniss6eda05f2016-06-30 10:18:35 -07003932
3933 cl = Changelist(**kwargs)
rsesek@chromium.orgeec76592013-05-20 16:27:57 +00003934 if not cl.GetIssue():
3935 DieWithError('This branch has no associated changelist.')
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02003936
Edward Lemur678a6842019-10-03 22:25:05 +00003937 if args and not args[0].isdigit():
Edward Lemurf38bc172019-09-03 21:02:13 +00003938 logging.info('canonical issue/change URL: %s\n', cl.GetIssueURL())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02003939
Edward Lemur6c6827c2020-02-06 21:15:18 +00003940 description = ChangeDescription(cl.FetchDescription())
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00003941
smut@google.com34fb6b12015-07-13 20:03:26 +00003942 if options.display:
vapiera7fbd5a2016-06-16 09:17:49 -07003943 print(description.description)
smut@google.com34fb6b12015-07-13 20:03:26 +00003944 return 0
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00003945
3946 if options.new_description:
3947 text = options.new_description
3948 if text == '-':
3949 text = '\n'.join(l.rstrip() for l in sys.stdin)
dnjba1b0f32016-09-02 12:37:42 -07003950 elif text == '+':
3951 base_branch = cl.GetCommonAncestorWithUpstream()
Edward Lemura12175c2020-03-09 16:58:26 +00003952 text = _create_description_from_log([base_branch])
martiniss@chromium.orgd6648e22016-04-29 19:22:16 +00003953
3954 description.set_description(text)
3955 else:
Edward Lemurf38bc172019-09-03 21:02:13 +00003956 description.prompt()
Edward Lemur6c6827c2020-02-06 21:15:18 +00003957 if cl.FetchDescription().strip() != description.description:
dsansomee2d6fd92016-09-08 00:10:47 -07003958 cl.UpdateDescription(description.description, force=options.force)
rsesek@chromium.orgeec76592013-05-20 16:27:57 +00003959 return 0
3960
3961
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00003962@metrics.collector.collect_metrics('git cl lint')
thestig@chromium.org44202a22014-03-11 19:22:18 +00003963def CMDlint(parser, args):
3964 """Runs cpplint on the current changelist."""
tzik@chromium.orgf204d4b2014-03-13 07:40:55 +00003965 parser.add_option('--filter', action='append', metavar='-x,+y',
3966 help='Comma-separated list of cpplint\'s category-filters')
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00003967 options, args = parser.parse_args(args)
thestig@chromium.org44202a22014-03-11 19:22:18 +00003968
3969 # Access to a protected member _XX of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -08003970 # pylint: disable=protected-access
thestig@chromium.org44202a22014-03-11 19:22:18 +00003971 try:
3972 import cpplint
3973 import cpplint_chromium
3974 except ImportError:
vapiera7fbd5a2016-06-16 09:17:49 -07003975 print('Your depot_tools is missing cpplint.py and/or cpplint_chromium.py.')
thestig@chromium.org44202a22014-03-11 19:22:18 +00003976 return 1
3977
3978 # Change the current working directory before calling lint so that it
3979 # shows the correct base.
3980 previous_cwd = os.getcwd()
3981 os.chdir(settings.GetRoot())
3982 try:
Edward Lemur934836a2019-09-09 20:16:54 +00003983 cl = Changelist()
Edward Lemur2c62b332020-03-12 22:12:33 +00003984 files = cl.GetAffectedFiles(cl.GetCommonAncestorWithUpstream())
thestig@chromium.org5839eb52014-05-30 16:20:51 +00003985 if not files:
vapiera7fbd5a2016-06-16 09:17:49 -07003986 print('Cannot lint an empty CL')
thestig@chromium.org5839eb52014-05-30 16:20:51 +00003987 return 1
thestig@chromium.org44202a22014-03-11 19:22:18 +00003988
3989 # Process cpplints arguments if any.
tzik@chromium.orgf204d4b2014-03-13 07:40:55 +00003990 command = args + files
3991 if options.filter:
3992 command = ['--filter=' + ','.join(options.filter)] + command
3993 filenames = cpplint.ParseArguments(command)
thestig@chromium.org44202a22014-03-11 19:22:18 +00003994
3995 white_regex = re.compile(settings.GetLintRegex())
3996 black_regex = re.compile(settings.GetLintIgnoreRegex())
3997 extra_check_functions = [cpplint_chromium.CheckPointerDeclarationWhitespace]
3998 for filename in filenames:
3999 if white_regex.match(filename):
4000 if black_regex.match(filename):
vapiera7fbd5a2016-06-16 09:17:49 -07004001 print('Ignoring file %s' % filename)
thestig@chromium.org44202a22014-03-11 19:22:18 +00004002 else:
4003 cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level,
4004 extra_check_functions)
4005 else:
vapiera7fbd5a2016-06-16 09:17:49 -07004006 print('Skipping file %s' % filename)
thestig@chromium.org44202a22014-03-11 19:22:18 +00004007 finally:
4008 os.chdir(previous_cwd)
vapiera7fbd5a2016-06-16 09:17:49 -07004009 print('Total errors found: %d\n' % cpplint._cpplint_state.error_count)
thestig@chromium.org44202a22014-03-11 19:22:18 +00004010 if cpplint._cpplint_state.error_count != 0:
4011 return 1
4012 return 0
4013
4014
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004015@metrics.collector.collect_metrics('git cl presubmit')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004016def CMDpresubmit(parser, args):
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00004017 """Runs presubmit tests on the current changelist."""
ilevy@chromium.org375a9022013-01-07 01:12:05 +00004018 parser.add_option('-u', '--upload', action='store_true',
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004019 help='Run upload hook instead of the push hook')
ilevy@chromium.org375a9022013-01-07 01:12:05 +00004020 parser.add_option('-f', '--force', action='store_true',
sbc@chromium.org495ad152012-09-04 23:07:42 +00004021 help='Run checks even if tree is dirty')
Aaron Gable8076c282017-11-29 14:39:41 -08004022 parser.add_option('--all', action='store_true',
4023 help='Run checks against all files, not just modified ones')
Edward Lesmes8e282792018-04-03 18:50:29 -04004024 parser.add_option('--parallel', action='store_true',
4025 help='Run all tests specified by input_api.RunTests in all '
4026 'PRESUBMIT files in parallel.')
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00004027 options, args = parser.parse_args(args)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004028
sbc@chromium.org71437c02015-04-09 19:29:40 +00004029 if not options.force and git_common.is_dirty_git_tree('presubmit'):
vapiera7fbd5a2016-06-16 09:17:49 -07004030 print('use --force to check even if tree is dirty.')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004031 return 1
4032
Edward Lemur934836a2019-09-09 20:16:54 +00004033 cl = Changelist()
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004034 if args:
4035 base_branch = args[0]
4036 else:
ilevy@chromium.org0f58fa82012-11-05 01:45:20 +00004037 # Default to diffing against the common ancestor of the upstream branch.
thestig@chromium.org8b0553c2014-02-11 00:33:37 +00004038 base_branch = cl.GetCommonAncestorWithUpstream()
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004039
Gregory Nisbet29d5cf82020-02-27 08:16:58 +00004040 if cl.GetIssue():
4041 description = cl.FetchDescription()
Aaron Gable8076c282017-11-29 14:39:41 -08004042 else:
Edward Lemura12175c2020-03-09 16:58:26 +00004043 description = _create_description_from_log([base_branch])
Aaron Gable8076c282017-11-29 14:39:41 -08004044
ilevy@chromium.org051ad0e2013-03-04 21:57:34 +00004045 cl.RunHook(
4046 committing=not options.upload,
4047 may_prompt=False,
4048 verbose=options.verbose,
Edward Lemur227d5102020-02-25 23:45:35 +00004049 parallel=options.parallel,
4050 upstream=base_branch,
4051 description=description,
4052 all_files=options.all)
dpranke@chromium.org0a2bb372011-03-25 01:16:22 +00004053 return 0
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004054
4055
tandrii@chromium.org65874e12016-03-04 12:03:02 +00004056def GenerateGerritChangeId(message):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004057 """Returns the Change ID footer value (Ixxxxxx...xxx).
tandrii@chromium.org65874e12016-03-04 12:03:02 +00004058
4059 Works the same way as
4060 https://gerrit-review.googlesource.com/tools/hooks/commit-msg
4061 but can be called on demand on all platforms.
4062
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004063 The basic idea is to generate git hash of a state of the tree, original
4064 commit message, author/committer info and timestamps.
tandrii@chromium.org65874e12016-03-04 12:03:02 +00004065 """
4066 lines = []
4067 tree_hash = RunGitSilent(['write-tree'])
4068 lines.append('tree %s' % tree_hash.strip())
4069 code, parent = RunGitWithCode(['rev-parse', 'HEAD~0'], suppress_stderr=False)
4070 if code == 0:
4071 lines.append('parent %s' % parent.strip())
4072 author = RunGitSilent(['var', 'GIT_AUTHOR_IDENT'])
4073 lines.append('author %s' % author.strip())
4074 committer = RunGitSilent(['var', 'GIT_COMMITTER_IDENT'])
4075 lines.append('committer %s' % committer.strip())
4076 lines.append('')
4077 # Note: Gerrit's commit-hook actually cleans message of some lines and
4078 # whitespace. This code is not doing this, but it clearly won't decrease
4079 # entropy.
4080 lines.append(message)
4081 change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'],
Raul Tambreb946b232019-03-26 14:48:46 +00004082 stdin=('\n'.join(lines)).encode())
tandrii@chromium.org65874e12016-03-04 12:03:02 +00004083 return 'I%s' % change_hash.strip()
4084
4085
Andrii Shyshkalovf3a20ae2017-01-24 21:23:57 +01004086def GetTargetRef(remote, remote_branch, target_branch):
wittman@chromium.org455dc922015-01-26 20:15:50 +00004087 """Computes the remote branch ref to use for the CL.
4088
4089 Args:
4090 remote (str): The git remote for the CL.
4091 remote_branch (str): The git remote branch for the CL.
4092 target_branch (str): The target branch specified by the user.
wittman@chromium.org455dc922015-01-26 20:15:50 +00004093 """
4094 if not (remote and remote_branch):
4095 return None
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00004096
wittman@chromium.org455dc922015-01-26 20:15:50 +00004097 if target_branch:
Quinten Yearsley0c62da92017-05-31 13:39:42 -07004098 # Canonicalize branch references to the equivalent local full symbolic
wittman@chromium.org455dc922015-01-26 20:15:50 +00004099 # refs, which are then translated into the remote full symbolic refs
4100 # below.
4101 if '/' not in target_branch:
4102 remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch)
4103 else:
4104 prefix_replacements = (
4105 ('^((refs/)?remotes/)?branch-heads/', 'refs/remotes/branch-heads/'),
4106 ('^((refs/)?remotes/)?%s/' % remote, 'refs/remotes/%s/' % remote),
4107 ('^(refs/)?heads/', 'refs/remotes/%s/' % remote),
4108 )
4109 match = None
4110 for regex, replacement in prefix_replacements:
4111 match = re.search(regex, target_branch)
4112 if match:
4113 remote_branch = target_branch.replace(match.group(0), replacement)
4114 break
4115 if not match:
4116 # This is a branch path but not one we recognize; use as-is.
4117 remote_branch = target_branch
rmistry@google.comc68112d2015-03-03 12:48:06 +00004118 elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS:
4119 # Handle the refs that need to land in different refs.
4120 remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch]
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00004121
wittman@chromium.org455dc922015-01-26 20:15:50 +00004122 # Create the true path to the remote branch.
4123 # Does the following translation:
4124 # * refs/remotes/origin/refs/diff/test -> refs/diff/test
4125 # * refs/remotes/origin/master -> refs/heads/master
4126 # * refs/remotes/branch-heads/test -> refs/branch-heads/test
4127 if remote_branch.startswith('refs/remotes/%s/refs/' % remote):
4128 remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '')
4129 elif remote_branch.startswith('refs/remotes/%s/' % remote):
4130 remote_branch = remote_branch.replace('refs/remotes/%s/' % remote,
4131 'refs/heads/')
4132 elif remote_branch.startswith('refs/remotes/branch-heads'):
4133 remote_branch = remote_branch.replace('refs/remotes/', 'refs/')
Andrii Shyshkalov768f1d82016-12-08 15:10:13 +01004134
wittman@chromium.org455dc922015-01-26 20:15:50 +00004135 return remote_branch
4136
4137
maruel@chromium.orgeb52a5c2013-04-10 23:17:09 +00004138def cleanup_list(l):
4139 """Fixes a list so that comma separated items are put as individual items.
4140
4141 So that "--reviewers joe@c,john@c --reviewers joa@c" results in
4142 options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']).
4143 """
4144 items = sum((i.split(',') for i in l), [])
4145 stripped_items = (i.strip() for i in items)
4146 return sorted(filter(None, stripped_items))
4147
4148
Aaron Gable4db38df2017-11-03 14:59:07 -07004149@subcommand.usage('[flags]')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004150@metrics.collector.collect_metrics('git cl upload')
ukai@chromium.orge8077812012-02-03 03:41:46 +00004151def CMDupload(parser, args):
rmistry@google.com78948ed2015-07-08 23:09:57 +00004152 """Uploads the current changelist to codereview.
4153
4154 Can skip dependency patchset uploads for a branch by running:
4155 git config branch.branch_name.skip-deps-uploads True
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004156 To unset, run:
rmistry@google.com78948ed2015-07-08 23:09:57 +00004157 git config --unset branch.branch_name.skip-deps-uploads
4158 Can also set the above globally by using the --global flag.
Dominic Battre7d1c4842017-10-27 09:17:28 +02004159
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004160 If the name of the checked out branch starts with "bug-" or "fix-" followed
4161 by a bug number, this bug number is automatically populated in the CL
Dominic Battre7d1c4842017-10-27 09:17:28 +02004162 description.
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08004163
4164 If subject contains text in square brackets or has "<text>: " prefix, such
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004165 text(s) is treated as Gerrit hashtags. For example, CLs with subjects:
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08004166 [git-cl] add support for hashtags
4167 Foo bar: implement foo
4168 will be hashtagged with "git-cl" and "foo-bar" respectively.
rmistry@google.com78948ed2015-07-08 23:09:57 +00004169 """
ukai@chromium.orge8077812012-02-03 03:41:46 +00004170 parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
4171 help='bypass upload presubmit hook')
brettw@chromium.orgb65c43c2013-06-10 22:04:49 +00004172 parser.add_option('--bypass-watchlists', action='store_true',
4173 dest='bypass_watchlists',
4174 help='bypass watchlists auto CC-ing reviewers')
Aaron Gablef7543cd2017-07-20 14:26:31 -07004175 parser.add_option('-f', '--force', action='store_true', dest='force',
ukai@chromium.orge8077812012-02-03 03:41:46 +00004176 help="force yes to questions (don't prompt)")
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004177 parser.add_option('--message', '-m', dest='message',
4178 help='message for patchset')
tandriif9aefb72016-07-01 09:06:51 -07004179 parser.add_option('-b', '--bug',
4180 help='pre-populate the bug number(s) for this issue. '
4181 'If several, separate with commas')
tandriib80458a2016-06-23 12:20:07 -07004182 parser.add_option('--message-file', dest='message_file',
4183 help='file which contains message for patchset')
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004184 parser.add_option('--title', '-t', dest='title',
4185 help='title for patchset')
ukai@chromium.orge8077812012-02-03 03:41:46 +00004186 parser.add_option('-r', '--reviewers',
maruel@chromium.orgeb52a5c2013-04-10 23:17:09 +00004187 action='append', default=[],
ukai@chromium.orge8077812012-02-03 03:41:46 +00004188 help='reviewer email addresses')
Robert Iannucci6c98dc62017-04-18 11:38:00 -07004189 parser.add_option('--tbrs',
4190 action='append', default=[],
4191 help='TBR email addresses')
ukai@chromium.orge8077812012-02-03 03:41:46 +00004192 parser.add_option('--cc',
maruel@chromium.orgeb52a5c2013-04-10 23:17:09 +00004193 action='append', default=[],
ukai@chromium.orge8077812012-02-03 03:41:46 +00004194 help='cc email addresses')
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08004195 parser.add_option('--hashtag', dest='hashtags',
4196 action='append', default=[],
4197 help=('Gerrit hashtag for new CL; '
4198 'can be applied multiple times'))
adamk@chromium.org36f47302013-04-05 01:08:31 +00004199 parser.add_option('-s', '--send-mail', action='store_true',
Aaron Gable59f48512017-01-12 10:54:46 -08004200 help='send email to reviewer(s) and cc(s) immediately')
ukai@chromium.org8ef7ab22012-11-28 04:24:52 +00004201 parser.add_option('--target_branch',
pgervais@chromium.orgb9f27512014-08-08 15:52:33 +00004202 '--target-branch',
wittman@chromium.org455dc922015-01-26 20:15:50 +00004203 metavar='TARGET',
4204 help='Apply CL to remote ref TARGET. ' +
4205 'Default: remote branch head, or master')
bauerb@chromium.org27386dd2015-02-16 10:45:39 +00004206 parser.add_option('--squash', action='store_true',
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08004207 help='Squash multiple commits into one')
Mike Frysingera989d552019-08-14 20:51:23 +00004208 parser.add_option('--no-squash', action='store_false', dest='squash',
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08004209 help='Don\'t squash multiple commits into one')
rmistry9eadede2016-09-19 11:22:43 -07004210 parser.add_option('--topic', default=None,
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08004211 help='Topic to specify when uploading')
Robert Iannuccif2708bd2017-04-17 15:49:02 -07004212 parser.add_option('--tbr-owners', dest='add_owners_to', action='store_const',
4213 const='TBR', help='add a set of OWNERS to TBR')
4214 parser.add_option('--r-owners', dest='add_owners_to', action='store_const',
4215 const='R', help='add a set of OWNERS to R')
Andrii Shyshkalov0e889b72019-07-15 22:28:48 +00004216 parser.add_option('-c', '--use-commit-queue', action='store_true',
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004217 default=False,
Andrii Shyshkalov0e889b72019-07-15 22:28:48 +00004218 help='tell the CQ to commit this patchset; '
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004219 'implies --send-mail')
4220 parser.add_option('-d', '--cq-dry-run',
4221 action='store_true', default=False,
rmistry@google.comef966222015-04-07 11:15:01 +00004222 help='Send the patchset to do a CQ dry run right after '
4223 'upload.')
Andrii Shyshkalov71f0da32019-07-15 22:45:18 +00004224 parser.add_option('--preserve-tryjobs', action='store_true',
4225 help='instruct the CQ to let tryjobs running even after '
4226 'new patchsets are uploaded instead of canceling '
4227 'prior patchset\' tryjobs')
rmistry@google.com2dd99862015-06-22 12:22:18 +00004228 parser.add_option('--dependencies', action='store_true',
4229 help='Uploads CLs of all the local branches that depend on '
4230 'the current branch')
Ravi Mistry31e7d562018-04-02 12:53:57 -04004231 parser.add_option('-a', '--enable-auto-submit', action='store_true',
4232 help='Sends your change to the CQ after an approval. Only '
4233 'works on repos that have the Auto-Submit label '
4234 'enabled')
Edward Lesmes8e282792018-04-03 18:50:29 -04004235 parser.add_option('--parallel', action='store_true',
4236 help='Run all tests specified by input_api.RunTests in all '
4237 'PRESUBMIT files in parallel.')
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +00004238 parser.add_option('--no-autocc', action='store_true',
4239 help='Disables automatic addition of CC emails')
Nodir Turakulovd0e2cd22017-11-15 10:22:06 -08004240 parser.add_option('--private', action='store_true',
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +00004241 help='Set the review private. This implies --no-autocc.')
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004242 parser.add_option('-R', '--retry-failed', action='store_true',
4243 help='Retry failed tryjobs from old patchset immediately '
4244 'after uploading new patchset. Cannot be used with '
4245 '--use-commit-queue or --cq-dry-run.')
4246 parser.add_option('--buildbucket-host', default='cr-buildbucket.appspot.com',
4247 help='Host of buildbucket. The default host is %default.')
Dan Beamd8b04ca2019-10-10 21:23:26 +00004248 parser.add_option('--fixed', '-x',
4249 help='List of bugs that will be commented on and marked '
4250 'fixed (pre-populates "Fixed:" tag). Same format as '
4251 '-b option / "Bug:" tag. If fixing several issues, '
4252 'separate with commas.')
Josipe827b0f2020-01-30 00:07:20 +00004253 parser.add_option('--edit-description', action='store_true', default=False,
4254 help='Modify description before upload. Cannot be used '
4255 'with --force. It is a noop when --no-squash is set '
4256 'or a new commit is created.')
Sergiy Byelozyorov1aa405f2018-09-18 17:38:43 +00004257
rmistry@google.com2dd99862015-06-22 12:22:18 +00004258 orig_args = args
ukai@chromium.orge8077812012-02-03 03:41:46 +00004259 (options, args) = parser.parse_args(args)
4260
sbc@chromium.org71437c02015-04-09 19:29:40 +00004261 if git_common.is_dirty_git_tree('upload'):
ukai@chromium.orge8077812012-02-03 03:41:46 +00004262 return 1
4263
maruel@chromium.orgeb52a5c2013-04-10 23:17:09 +00004264 options.reviewers = cleanup_list(options.reviewers)
Robert Iannucci6c98dc62017-04-18 11:38:00 -07004265 options.tbrs = cleanup_list(options.tbrs)
maruel@chromium.orgeb52a5c2013-04-10 23:17:09 +00004266 options.cc = cleanup_list(options.cc)
4267
Josipe827b0f2020-01-30 00:07:20 +00004268 if options.edit_description and options.force:
4269 parser.error('Only one of --force and --edit-description allowed')
4270
tandriib80458a2016-06-23 12:20:07 -07004271 if options.message_file:
4272 if options.message:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004273 parser.error('Only one of --message and --message-file allowed.')
tandriib80458a2016-06-23 12:20:07 -07004274 options.message = gclient_utils.FileRead(options.message_file)
4275 options.message_file = None
4276
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004277 if ([options.cq_dry_run,
4278 options.use_commit_queue,
4279 options.retry_failed].count(True) > 1):
4280 parser.error('Only one of --use-commit-queue, --cq-dry-run, or '
4281 '--retry-failed is allowed.')
tandrii4d0545a2016-07-06 03:56:49 -07004282
Aaron Gableedbc4132017-09-11 13:22:28 -07004283 if options.use_commit_queue:
4284 options.send_mail = True
4285
Edward Lesmes0dd54822020-03-26 18:24:25 +00004286 if options.squash is None:
4287 # Load default for user, repo, squash=true, in this order.
4288 options.squash = settings.GetSquashGerritUploads()
4289
Edward Lemur934836a2019-09-09 20:16:54 +00004290 cl = Changelist()
Edward Lesmes7677e5c2020-02-19 20:39:03 +00004291 # Warm change details cache now to avoid RPCs later, reducing latency for
4292 # developers.
4293 if cl.GetIssue():
4294 cl._GetChangeDetail(
4295 ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS'])
4296
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004297 if options.retry_failed and not cl.GetIssue():
4298 print('No previous patchsets, so --retry-failed has no effect.')
4299 options.retry_failed = False
Edward Lesmes7677e5c2020-02-19 20:39:03 +00004300
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004301 # cl.GetMostRecentPatchset uses cached information, and can return the last
4302 # patchset before upload. Calling it here makes it clear that it's the
4303 # last patchset before upload. Note that GetMostRecentPatchset will fail
4304 # if no CL has been uploaded yet.
4305 if options.retry_failed:
4306 patchset = cl.GetMostRecentPatchset()
Andrii Shyshkalov9f274432018-10-15 16:40:23 +00004307
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004308 ret = cl.CMDUpload(options, args, orig_args)
4309
4310 if options.retry_failed:
4311 if ret != 0:
4312 print('Upload failed, so --retry-failed has no effect.')
4313 return ret
Andrii Shyshkalov1ad58112019-10-08 01:46:14 +00004314 builds, _ = _fetch_latest_builds(
Edward Lemur5b929a42019-10-21 17:57:39 +00004315 cl, options.buildbucket_host, latest_patchset=patchset)
Edward Lemur45768512020-03-02 19:03:14 +00004316 jobs = _filter_failed_for_retry(builds)
4317 if len(jobs) == 0:
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004318 print('No failed tryjobs, so --retry-failed has no effect.')
4319 return ret
Quinten Yearsley777660f2020-03-04 23:37:06 +00004320 _trigger_tryjobs(cl, jobs, options, patchset + 1)
Quinten Yearsleya19d3532019-09-30 21:54:39 +00004321
4322 return ret
ukai@chromium.orge8077812012-02-03 03:41:46 +00004323
4324
Francois Dorayd42c6812017-05-30 15:10:20 -04004325@subcommand.usage('--description=<description file>')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004326@metrics.collector.collect_metrics('git cl split')
Francois Dorayd42c6812017-05-30 15:10:20 -04004327def CMDsplit(parser, args):
4328 """Splits a branch into smaller branches and uploads CLs.
4329
4330 Creates a branch and uploads a CL for each group of files modified in the
4331 current branch that share a common OWNERS file. In the CL description and
Edward Lemurac5c55f2020-02-29 00:17:16 +00004332 comment, the string '$directory', is replaced with the directory containing
4333 the shared OWNERS file.
Francois Dorayd42c6812017-05-30 15:10:20 -04004334 """
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004335 parser.add_option('-d', '--description', dest='description_file',
4336 help='A text file containing a CL description in which '
4337 '$directory will be replaced by each CL\'s directory.')
4338 parser.add_option('-c', '--comment', dest='comment_file',
4339 help='A text file containing a CL comment.')
4340 parser.add_option('-n', '--dry-run', dest='dry_run', action='store_true',
Chris Watkinsba28e462017-12-13 11:22:17 +11004341 default=False,
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004342 help='List the files and reviewers for each CL that would '
4343 'be created, but don\'t create branches or CLs.')
4344 parser.add_option('--cq-dry-run', action='store_true',
4345 help='If set, will do a cq dry run for each uploaded CL. '
4346 'Please be careful when doing this; more than ~10 CLs '
4347 'has the potential to overload our build '
4348 'infrastructure. Try to upload these not during high '
4349 'load times (usually 11-3 Mountain View time). Email '
4350 'infra-dev@chromium.org with any questions.')
Takuto Ikuta51eca592019-02-14 19:40:52 +00004351 parser.add_option('-a', '--enable-auto-submit', action='store_true',
4352 default=True,
4353 help='Sends your change to the CQ after an approval. Only '
4354 'works on repos that have the Auto-Submit label '
4355 'enabled')
Francois Dorayd42c6812017-05-30 15:10:20 -04004356 options, _ = parser.parse_args(args)
4357
4358 if not options.description_file:
4359 parser.error('No --description flag specified.')
4360
4361 def WrappedCMDupload(args):
4362 return CMDupload(OptionParser(), args)
4363
Edward Lemur2c62b332020-03-12 22:12:33 +00004364 return split_cl.SplitCl(
4365 options.description_file, options.comment_file, Changelist,
4366 WrappedCMDupload, options.dry_run, options.cq_dry_run,
4367 options.enable_auto_submit, settings.GetRoot())
Francois Dorayd42c6812017-05-30 15:10:20 -04004368
4369
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004370@subcommand.usage('DEPRECATED')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004371@metrics.collector.collect_metrics('git cl commit')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004372def CMDdcommit(parser, args):
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004373 """DEPRECATED: Used to commit the current changelist via git-svn."""
4374 message = ('git-cl no longer supports committing to SVN repositories via '
4375 'git-svn. You probably want to use `git cl land` instead.')
4376 print(message)
4377 return 1
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004378
4379
maruel@chromium.org0633fb42013-08-16 20:06:14 +00004380@subcommand.usage('[upstream branch to apply against]')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004381@metrics.collector.collect_metrics('git cl land')
pgervais@chromium.orgcee6dc42014-05-07 17:04:03 +00004382def CMDland(parser, args):
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004383 """Commits the current changelist via git.
4384
4385 In case of Gerrit, uses Gerrit REST api to "submit" the issue, which pushes
4386 upstream and closes the issue automatically and atomically.
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004387 """
4388 parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
4389 help='bypass upload presubmit hook')
Aaron Gablef7543cd2017-07-20 14:26:31 -07004390 parser.add_option('-f', '--force', action='store_true', dest='force',
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004391 help="force yes to questions (don't prompt)")
Edward Lesmes67b3faa2018-04-13 17:50:52 -04004392 parser.add_option('--parallel', action='store_true',
4393 help='Run all tests specified by input_api.RunTests in all '
4394 'PRESUBMIT files in parallel.')
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004395 (options, args) = parser.parse_args(args)
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004396
Edward Lemur934836a2019-09-09 20:16:54 +00004397 cl = Changelist()
Aaron Gable1bc7bfe2016-12-19 10:08:14 -08004398
Robert Iannucci2e73d432018-03-14 01:10:47 -07004399 if not cl.GetIssue():
4400 DieWithError('You must upload the change first to Gerrit.\n'
4401 ' If you would rather have `git cl land` upload '
4402 'automatically for you, see http://crbug.com/642759')
Edward Lemur125d60a2019-09-13 18:25:41 +00004403 return cl.CMDLand(options.force, options.bypass_hooks,
Olivier Robin75ee7252018-04-13 10:02:56 +02004404 options.verbose, options.parallel)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004405
4406
dsinclair@chromium.orgfbed6562015-09-25 21:22:36 +00004407@subcommand.usage('<patch url or issue id or issue url>')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004408@metrics.collector.collect_metrics('git cl patch')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004409def CMDpatch(parser, args):
marq@chromium.orge5e59002013-10-02 23:21:25 +00004410 """Patches in a code review."""
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004411 parser.add_option('-b', dest='newbranch',
4412 help='create a new branch off trunk for the patch')
qsr@chromium.org1ef44af2013-10-16 16:24:32 +00004413 parser.add_option('-f', '--force', action='store_true',
Aaron Gable62619a32017-06-16 08:22:09 -07004414 help='overwrite state on the current or chosen branch')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004415 parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit',
Edward Lemurf38bc172019-09-03 21:02:13 +00004416 help='don\'t commit after patch applies.')
mtrofin@chromium.org1d88dd32016-02-04 16:25:12 +00004417
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00004418 group = optparse.OptionGroup(
4419 parser,
4420 'Options for continuing work on the current issue uploaded from a '
4421 'different clone (e.g. different machine). Must be used independently '
4422 'from the other options. No issue number should be specified, and the '
4423 'branch must have an issue number associated with it')
4424 group.add_option('--reapply', action='store_true', dest='reapply',
4425 help='Reset the branch and reapply the issue.\n'
4426 'CAUTION: This will undo any local changes in this '
4427 'branch')
mtrofin@chromium.org1d88dd32016-02-04 16:25:12 +00004428
4429 group.add_option('--pull', action='store_true', dest='pull',
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00004430 help='Performs a pull before reapplying.')
mtrofin@chromium.org1d88dd32016-02-04 16:25:12 +00004431 parser.add_option_group(group)
4432
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004433 (options, args) = parser.parse_args(args)
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00004434
Andrii Shyshkalov18975322017-01-25 16:44:13 +01004435 if options.reapply:
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00004436 if options.newbranch:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004437 parser.error('--reapply works on the current branch only.')
mtrofin@chromium.org1d88dd32016-02-04 16:25:12 +00004438 if len(args) > 0:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004439 parser.error('--reapply implies no additional arguments.')
dsinclair@chromium.orgfbed6562015-09-25 21:22:36 +00004440
Edward Lemur934836a2019-09-09 20:16:54 +00004441 cl = Changelist()
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00004442 if not cl.GetIssue():
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004443 parser.error('Current branch must have an associated issue.')
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00004444
mtrofin@chromium.org1d88dd32016-02-04 16:25:12 +00004445 upstream = cl.GetUpstreamBranch()
Andrii Shyshkalov18975322017-01-25 16:44:13 +01004446 if upstream is None:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004447 parser.error('No upstream branch specified. Cannot reset branch.')
mtrofin@chromium.org1d88dd32016-02-04 16:25:12 +00004448
4449 RunGit(['reset', '--hard', upstream])
4450 if options.pull:
4451 RunGit(['pull'])
mtrofin@chromium.org1d88dd32016-02-04 16:25:12 +00004452
Edward Lemur678a6842019-10-03 22:25:05 +00004453 target_issue_arg = ParseIssueNumberArgument(cl.GetIssue())
4454 return cl.CMDPatchWithParsedIssue(target_issue_arg, options.nocommit, False)
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00004455
4456 if len(args) != 1 or not args[0]:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004457 parser.error('Must specify issue number or URL.')
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00004458
Edward Lemurf38bc172019-09-03 21:02:13 +00004459 target_issue_arg = ParseIssueNumberArgument(args[0])
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02004460 if not target_issue_arg.valid:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004461 parser.error('Invalid issue ID or URL.')
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02004462
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00004463 # We don't want uncommitted changes mixed up with the patch.
4464 if git_common.is_dirty_git_tree('patch'):
dsinclair@chromium.orgfbed6562015-09-25 21:22:36 +00004465 return 1
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004466
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00004467 if options.newbranch:
4468 if options.force:
4469 RunGit(['branch', '-D', options.newbranch],
4470 stderr=subprocess2.PIPE, error_ok=True)
Edward Lemur84101642020-02-21 21:40:34 +00004471 git_new_branch.create_new_branch(options.newbranch)
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00004472
Edward Lemur678a6842019-10-03 22:25:05 +00004473 cl = Changelist(
4474 codereview_host=target_issue_arg.hostname, issue=target_issue_arg.issue)
tandrii@chromium.orgc2786d92016-05-31 19:53:50 +00004475
Edward Lemur678a6842019-10-03 22:25:05 +00004476 if not args[0].isdigit():
Edward Lemurf38bc172019-09-03 21:02:13 +00004477 print('canonical issue/change URL: %s\n' % cl.GetIssueURL())
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02004478
Edward Lemurf38bc172019-09-03 21:02:13 +00004479 return cl.CMDPatchWithParsedIssue(
4480 target_issue_arg, options.nocommit, options.force)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004481
4482
jochen@chromium.org3ec0d542014-01-14 20:00:03 +00004483def GetTreeStatus(url=None):
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004484 """Fetches the tree status and returns either 'open', 'closed',
4485 'unknown' or 'unset'."""
jochen@chromium.org3ec0d542014-01-14 20:00:03 +00004486 url = url or settings.GetTreeStatusUrl(error_ok=True)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004487 if url:
Edward Lemur79d4f992019-11-11 23:49:02 +00004488 status = urllib.request.urlopen(url).read().lower()
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004489 if status.find('closed') != -1 or status == '0':
4490 return 'closed'
4491 elif status.find('open') != -1 or status == '1':
4492 return 'open'
4493 return 'unknown'
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004494 return 'unset'
4495
dpranke@chromium.org970c5222011-03-12 00:32:24 +00004496
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004497def GetTreeStatusReason():
4498 """Fetches the tree status from a json url and returns the message
4499 with the reason for the tree to be opened or closed."""
msb@chromium.orgbf1a7ba2011-02-01 16:21:46 +00004500 url = settings.GetTreeStatusUrl()
4501 json_url = urlparse.urljoin(url, '/current?format=json')
Edward Lemur79d4f992019-11-11 23:49:02 +00004502 connection = urllib.request.urlopen(json_url)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004503 status = json.loads(connection.read())
4504 connection.close()
4505 return status['message']
4506
dpranke@chromium.org970c5222011-03-12 00:32:24 +00004507
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004508@metrics.collector.collect_metrics('git cl tree')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004509def CMDtree(parser, args):
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00004510 """Shows the status of the tree."""
dpranke@chromium.org97ae58e2011-03-18 00:29:20 +00004511 _, args = parser.parse_args(args)
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004512 status = GetTreeStatus()
4513 if 'unset' == status:
vapiera7fbd5a2016-06-16 09:17:49 -07004514 print('You must configure your tree status URL by running "git cl config".')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004515 return 2
4516
vapiera7fbd5a2016-06-16 09:17:49 -07004517 print('The tree is %s' % status)
4518 print()
4519 print(GetTreeStatusReason())
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004520 if status != 'open':
4521 return 1
4522 return 0
4523
4524
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004525@metrics.collector.collect_metrics('git cl try')
maruel@chromium.org15192402012-09-06 12:38:29 +00004526def CMDtry(parser, args):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004527 """Triggers tryjobs using either Buildbucket or CQ dry run."""
4528 group = optparse.OptionGroup(parser, 'Tryjob options')
maruel@chromium.org15192402012-09-06 12:38:29 +00004529 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004530 '-b', '--bot', action='append',
4531 help=('IMPORTANT: specify ONE builder per --bot flag. Use it multiple '
4532 'times to specify multiple builders. ex: '
4533 '"-b win_rel -b win_layout". See '
4534 'the try server waterfall for the builders name and the tests '
4535 'available.'))
maruel@chromium.org15192402012-09-06 12:38:29 +00004536 group.add_option(
borenet6c0efe62016-10-19 08:13:29 -07004537 '-B', '--bucket', default='',
4538 help=('Buildbucket bucket to send the try requests.'))
4539 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004540 '-r', '--revision',
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004541 help='Revision to use for the tryjob; default: the revision will '
tandriif7b29d42016-10-07 08:45:41 -07004542 'be determined by the try recipe that builder runs, which usually '
4543 'defaults to HEAD of origin/master')
maruel@chromium.org15192402012-09-06 12:38:29 +00004544 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004545 '-c', '--clobber', action='store_true', default=False,
tandriif7b29d42016-10-07 08:45:41 -07004546 help='Force a clobber before building; that is don\'t do an '
tandrii1838bad2016-10-06 00:10:52 -07004547 'incremental build')
maruel@chromium.org15192402012-09-06 12:38:29 +00004548 group.add_option(
Andrii Shyshkalovf9648b52018-02-21 22:32:42 -08004549 '--category', default='git_cl_try', help='Specify custom build category.')
4550 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004551 '--project',
4552 help='Override which project to use. Projects are defined '
tandriif7b29d42016-10-07 08:45:41 -07004553 'in recipe to determine to which repository or directory to '
4554 'apply the patch')
maruel@chromium.org15192402012-09-06 12:38:29 +00004555 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004556 '-p', '--property', dest='properties', action='append', default=[],
4557 help='Specify generic properties in the form -p key1=value1 -p '
tandriif7b29d42016-10-07 08:45:41 -07004558 'key2=value2 etc. The value will be treated as '
4559 'json if decodable, or as string otherwise. '
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004560 'NOTE: using this may make your tryjob not usable for CQ, '
4561 'which will then schedule another tryjob with default properties')
sheyang@chromium.orgdb375572015-08-17 19:22:23 +00004562 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004563 '--buildbucket-host', default='cr-buildbucket.appspot.com',
4564 help='Host of buildbucket. The default host is %default.')
maruel@chromium.org15192402012-09-06 12:38:29 +00004565 parser.add_option_group(group)
Quinten Yearsley983111f2019-09-26 17:18:48 +00004566 parser.add_option(
4567 '-R', '--retry-failed', action='store_true', default=False,
4568 help='Retry failed jobs from the latest set of tryjobs. '
4569 'Not allowed with --bucket and --bot options.')
Edward Lemur52969c92020-02-06 18:15:28 +00004570 parser.add_option(
4571 '-i', '--issue', type=int,
4572 help='Operate on this issue instead of the current branch\'s implicit '
4573 'issue.')
maruel@chromium.org15192402012-09-06 12:38:29 +00004574 options, args = parser.parse_args(args)
4575
machenbach@chromium.org45453142015-09-15 08:45:22 +00004576 # Make sure that all properties are prop=value pairs.
4577 bad_params = [x for x in options.properties if '=' not in x]
4578 if bad_params:
4579 parser.error('Got properties with missing "=": %s' % bad_params)
4580
maruel@chromium.org15192402012-09-06 12:38:29 +00004581 if args:
4582 parser.error('Unknown arguments: %s' % args)
4583
Edward Lemur934836a2019-09-09 20:16:54 +00004584 cl = Changelist(issue=options.issue)
maruel@chromium.org15192402012-09-06 12:38:29 +00004585 if not cl.GetIssue():
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004586 parser.error('Need to upload first.')
maruel@chromium.org15192402012-09-06 12:38:29 +00004587
Edward Lemurf38bc172019-09-03 21:02:13 +00004588 # HACK: warm up Gerrit change detail cache to save on RPCs.
Edward Lemur125d60a2019-09-13 18:25:41 +00004589 cl._GetChangeDetail(['DETAILED_ACCOUNTS', 'ALL_REVISIONS'])
Andrii Shyshkaloveadad922017-01-26 09:38:30 +01004590
tandriie113dfd2016-10-11 10:20:12 -07004591 error_message = cl.CannotTriggerTryJobReason()
4592 if error_message:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004593 parser.error('Can\'t trigger tryjobs: %s' % error_message)
jrobbins@chromium.org16f10f72014-06-24 22:14:36 +00004594
Edward Lemur45768512020-03-02 19:03:14 +00004595 if options.bot:
4596 if options.retry_failed:
4597 parser.error('--bot is not compatible with --retry-failed.')
4598 if not options.bucket:
4599 parser.error('A bucket (e.g. "chromium/try") is required.')
4600
4601 triggered = [b for b in options.bot if 'triggered' in b]
4602 if triggered:
4603 parser.error(
4604 'Cannot schedule builds on triggered bots: %s.\n'
4605 'This type of bot requires an initial job from a parent (usually a '
4606 'builder). Schedule a job on the parent instead.\n' % triggered)
4607
4608 if options.bucket.startswith('.master'):
4609 parser.error('Buildbot masters are not supported.')
4610
4611 project, bucket = _parse_bucket(options.bucket)
4612 if project is None or bucket is None:
4613 parser.error('Invalid bucket: %s.' % options.bucket)
4614 jobs = sorted((project, bucket, bot) for bot in options.bot)
4615 elif options.retry_failed:
Quinten Yearsley983111f2019-09-26 17:18:48 +00004616 print('Searching for failed tryjobs...')
Edward Lemur5b929a42019-10-21 17:57:39 +00004617 builds, patchset = _fetch_latest_builds(cl, options.buildbucket_host)
Quinten Yearsley983111f2019-09-26 17:18:48 +00004618 if options.verbose:
4619 print('Got %d builds in patchset #%d' % (len(builds), patchset))
Edward Lemur45768512020-03-02 19:03:14 +00004620 jobs = _filter_failed_for_retry(builds)
4621 if not jobs:
Quinten Yearsley983111f2019-09-26 17:18:48 +00004622 print('There are no failed jobs in the latest set of jobs '
4623 '(patchset #%d), doing nothing.' % patchset)
4624 return 0
Edward Lemur45768512020-03-02 19:03:14 +00004625 num_builders = len(jobs)
Quinten Yearsley983111f2019-09-26 17:18:48 +00004626 if num_builders > 10:
4627 confirm_or_exit('There are %d builders with failed builds.'
4628 % num_builders, action='continue')
4629 else:
qyearsley1fdfcb62016-10-24 13:22:03 -07004630 if options.verbose:
Quinten Yearsleyfc5fd922017-05-31 11:50:52 -07004631 print('git cl try with no bots now defaults to CQ dry run.')
4632 print('Scheduling CQ dry run on: %s' % cl.GetIssueURL())
4633 return cl.SetCQState(_CQState.DRY_RUN)
stip@chromium.org43064fd2013-12-18 20:07:44 +00004634
ilevy@chromium.org36e420b2013-08-06 23:21:12 +00004635 patchset = cl.GetMostRecentPatchset()
Edward Lemur2c210a42019-09-16 23:58:35 +00004636 try:
Quinten Yearsley777660f2020-03-04 23:37:06 +00004637 _trigger_tryjobs(cl, jobs, options, patchset)
Edward Lemur2c210a42019-09-16 23:58:35 +00004638 except BuildbucketResponseException as ex:
4639 print('ERROR: %s' % ex)
4640 return 1
4641 return 0
maruel@chromium.org15192402012-09-06 12:38:29 +00004642
4643
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004644@metrics.collector.collect_metrics('git cl try-results')
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004645def CMDtry_results(parser, args):
Quinten Yearsleyd242ed72019-07-25 17:17:55 +00004646 """Prints info about results for tryjobs associated with the current CL."""
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004647 group = optparse.OptionGroup(parser, 'Tryjob results options')
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004648 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004649 '-p', '--patchset', type=int, help='patchset number if not current.')
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004650 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004651 '--print-master', action='store_true', help='print master name as well.')
tandrii@chromium.org6cf98c82016-03-15 11:56:00 +00004652 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004653 '--color', action='store_true', default=setup_color.IS_TTY,
4654 help='force color output, useful when piping output.')
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004655 group.add_option(
tandrii1838bad2016-10-06 00:10:52 -07004656 '--buildbucket-host', default='cr-buildbucket.appspot.com',
4657 help='Host of buildbucket. The default host is %default.')
qyearsley53f48a12016-09-01 10:45:13 -07004658 group.add_option(
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004659 '--json', help=('Path of JSON output file to write tryjob results to,'
Stefan Zager1306bd02017-06-22 19:26:46 -07004660 'or "-" for stdout.'))
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004661 parser.add_option_group(group)
Edward Lemur52969c92020-02-06 18:15:28 +00004662 parser.add_option(
4663 '-i', '--issue', type=int,
4664 help='Operate on this issue instead of the current branch\'s implicit '
4665 'issue.')
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004666 options, args = parser.parse_args(args)
4667 if args:
4668 parser.error('Unrecognized args: %s' % ' '.join(args))
4669
Edward Lemur934836a2019-09-09 20:16:54 +00004670 cl = Changelist(issue=options.issue)
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004671 if not cl.GetIssue():
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004672 parser.error('Need to upload first.')
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004673
tandrii221ab252016-10-06 08:12:04 -07004674 patchset = options.patchset
4675 if not patchset:
4676 patchset = cl.GetMostRecentPatchset()
4677 if not patchset:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004678 parser.error('Code review host doesn\'t know about issue %s. '
tandrii221ab252016-10-06 08:12:04 -07004679 'No access to issue or wrong issue number?\n'
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004680 'Either upload first, or pass --patchset explicitly.' %
tandrii221ab252016-10-06 08:12:04 -07004681 cl.GetIssue())
4682
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004683 try:
Quinten Yearsley777660f2020-03-04 23:37:06 +00004684 jobs = _fetch_tryjobs(cl, options.buildbucket_host, patchset)
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004685 except BuildbucketResponseException as ex:
vapiera7fbd5a2016-06-16 09:17:49 -07004686 print('Buildbucket error: %s' % ex)
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004687 return 1
qyearsley53f48a12016-09-01 10:45:13 -07004688 if options.json:
Edward Lemurbaaf6be2019-10-09 18:00:44 +00004689 write_json(options.json, jobs)
qyearsley53f48a12016-09-01 10:45:13 -07004690 else:
Quinten Yearsley777660f2020-03-04 23:37:06 +00004691 _print_tryjobs(options, jobs)
tandrii@chromium.orgb015fac2016-02-26 14:52:01 +00004692 return 0
4693
4694
maruel@chromium.org0633fb42013-08-16 20:06:14 +00004695@subcommand.usage('[new upstream branch]')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004696@metrics.collector.collect_metrics('git cl upstream')
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004697def CMDupstream(parser, args):
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00004698 """Prints or sets the name of the upstream branch, if any."""
dpranke@chromium.org97ae58e2011-03-18 00:29:20 +00004699 _, args = parser.parse_args(args)
brettw@chromium.orgac0ba332012-08-09 23:42:53 +00004700 if len(args) > 1:
maruel@chromium.org27bb3872011-05-30 20:33:19 +00004701 parser.error('Unrecognized args: %s' % ' '.join(args))
brettw@chromium.orgac0ba332012-08-09 23:42:53 +00004702
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004703 cl = Changelist()
brettw@chromium.orgac0ba332012-08-09 23:42:53 +00004704 if args:
4705 # One arg means set upstream branch.
bauerb@chromium.orgc9cf90a2014-04-28 20:32:31 +00004706 branch = cl.GetBranch()
stip7a3dd352016-09-22 17:32:28 -07004707 RunGit(['branch', '--set-upstream-to', args[0], branch])
brettw@chromium.orgac0ba332012-08-09 23:42:53 +00004708 cl = Changelist()
vapiera7fbd5a2016-06-16 09:17:49 -07004709 print('Upstream branch set to %s' % (cl.GetUpstreamBranch(),))
bauerb@chromium.orgc9cf90a2014-04-28 20:32:31 +00004710
4711 # Clear configured merge-base, if there is one.
4712 git_common.remove_merge_base(branch)
brettw@chromium.orgac0ba332012-08-09 23:42:53 +00004713 else:
vapiera7fbd5a2016-06-16 09:17:49 -07004714 print(cl.GetUpstreamBranch())
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00004715 return 0
4716
4717
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004718@metrics.collector.collect_metrics('git cl web')
thestig@chromium.org00858c82013-12-02 23:08:03 +00004719def CMDweb(parser, args):
4720 """Opens the current CL in the web browser."""
4721 _, args = parser.parse_args(args)
4722 if args:
4723 parser.error('Unrecognized args: %s' % ' '.join(args))
4724
4725 issue_url = Changelist().GetIssueURL()
4726 if not issue_url:
vapiera7fbd5a2016-06-16 09:17:49 -07004727 print('ERROR No issue to open', file=sys.stderr)
thestig@chromium.org00858c82013-12-02 23:08:03 +00004728 return 1
4729
Sergiy Byelozyorov2b718322018-10-24 17:43:31 +00004730 # Redirect I/O before invoking browser to hide its output. For example, this
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00004731 # allows us to hide the "Created new window in existing browser session."
4732 # message from Chrome. Based on https://stackoverflow.com/a/2323563.
Sergiy Byelozyorov2b718322018-10-24 17:43:31 +00004733 saved_stdout = os.dup(1)
Sergiy Belozorov06684032019-03-06 16:53:08 +00004734 saved_stderr = os.dup(2)
Sergiy Byelozyorov2b718322018-10-24 17:43:31 +00004735 os.close(1)
Sergiy Belozorov06684032019-03-06 16:53:08 +00004736 os.close(2)
Sergiy Byelozyorov2b718322018-10-24 17:43:31 +00004737 os.open(os.devnull, os.O_RDWR)
4738 try:
4739 webbrowser.open(issue_url)
4740 finally:
4741 os.dup2(saved_stdout, 1)
Sergiy Belozorov06684032019-03-06 16:53:08 +00004742 os.dup2(saved_stderr, 2)
thestig@chromium.org00858c82013-12-02 23:08:03 +00004743 return 0
4744
4745
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004746@metrics.collector.collect_metrics('git cl set-commit')
maruel@chromium.org27bb3872011-05-30 20:33:19 +00004747def CMDset_commit(parser, args):
Andrii Shyshkalov0e889b72019-07-15 22:28:48 +00004748 """Sets the commit bit to trigger the CQ."""
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00004749 parser.add_option('-d', '--dry-run', action='store_true',
4750 help='trigger in dry run mode')
4751 parser.add_option('-c', '--clear', action='store_true',
4752 help='stop CQ run, if any')
Edward Lemur52969c92020-02-06 18:15:28 +00004753 parser.add_option(
4754 '-i', '--issue', type=int,
4755 help='Operate on this issue instead of the current branch\'s implicit '
4756 'issue.')
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00004757 options, args = parser.parse_args(args)
maruel@chromium.org27bb3872011-05-30 20:33:19 +00004758 if args:
4759 parser.error('Unrecognized args: %s' % ' '.join(args))
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00004760 if options.dry_run and options.clear:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004761 parser.error('Only one of --dry-run and --clear are allowed.')
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00004762
Edward Lemur934836a2019-09-09 20:16:54 +00004763 cl = Changelist(issue=options.issue)
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00004764 if options.clear:
tandriid9e5ce52016-07-13 02:32:59 -07004765 state = _CQState.NONE
tandrii@chromium.orgfa330e82016-04-13 17:09:52 +00004766 elif options.dry_run:
4767 state = _CQState.DRY_RUN
4768 else:
4769 state = _CQState.COMMIT
4770 if not cl.GetIssue():
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004771 parser.error('Must upload the issue first.')
tandrii9de9ec62016-07-13 03:01:59 -07004772 cl.SetCQState(state)
maruel@chromium.org27bb3872011-05-30 20:33:19 +00004773 return 0
4774
4775
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004776@metrics.collector.collect_metrics('git cl set-close')
groby@chromium.org411034a2013-02-26 15:12:01 +00004777def CMDset_close(parser, args):
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00004778 """Closes the issue."""
Edward Lemur52969c92020-02-06 18:15:28 +00004779 parser.add_option(
4780 '-i', '--issue', type=int,
4781 help='Operate on this issue instead of the current branch\'s implicit '
4782 'issue.')
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00004783 options, args = parser.parse_args(args)
groby@chromium.org411034a2013-02-26 15:12:01 +00004784 if args:
4785 parser.error('Unrecognized args: %s' % ' '.join(args))
Edward Lemur934836a2019-09-09 20:16:54 +00004786 cl = Changelist(issue=options.issue)
groby@chromium.org411034a2013-02-26 15:12:01 +00004787 # Ensure there actually is an issue to close.
Aaron Gable7139a4e2017-09-05 17:53:09 -07004788 if not cl.GetIssue():
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004789 DieWithError('ERROR: No issue to close.')
groby@chromium.org411034a2013-02-26 15:12:01 +00004790 cl.CloseIssue()
4791 return 0
4792
4793
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004794@metrics.collector.collect_metrics('git cl diff')
sbc@chromium.org87b9bf02013-09-26 20:35:15 +00004795def CMDdiff(parser, args):
wychen@chromium.org37b2ec02015-04-03 00:49:15 +00004796 """Shows differences between local tree and last upload."""
thomasanderson074beb22016-08-29 14:03:20 -07004797 parser.add_option(
4798 '--stat',
4799 action='store_true',
4800 dest='stat',
4801 help='Generate a diffstat')
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00004802 options, args = parser.parse_args(args)
vadimsh@chromium.orgcf6a5d22015-04-09 22:02:00 +00004803 if args:
4804 parser.error('Unrecognized args: %s' % ' '.join(args))
wychen@chromium.org46309bf2015-04-03 21:04:49 +00004805
Edward Lemur934836a2019-09-09 20:16:54 +00004806 cl = Changelist()
sbc@chromium.org78dc9842013-11-25 18:43:44 +00004807 issue = cl.GetIssue()
sbc@chromium.org87b9bf02013-09-26 20:35:15 +00004808 branch = cl.GetBranch()
sbc@chromium.org78dc9842013-11-25 18:43:44 +00004809 if not issue:
4810 DieWithError('No issue found for current branch (%s)' % branch)
sbc@chromium.org87b9bf02013-09-26 20:35:15 +00004811
Aaron Gablea718c3e2017-08-28 17:47:28 -07004812 base = cl._GitGetBranchConfigValue('last-upload-hash')
4813 if not base:
4814 base = cl._GitGetBranchConfigValue('gerritsquashhash')
4815 if not base:
4816 detail = cl._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'])
4817 revision_info = detail['revisions'][detail['current_revision']]
4818 fetch_info = revision_info['fetch']['http']
4819 RunGit(['fetch', fetch_info['url'], fetch_info['ref']])
4820 base = 'FETCH_HEAD'
sbc@chromium.org87b9bf02013-09-26 20:35:15 +00004821
Aaron Gablea718c3e2017-08-28 17:47:28 -07004822 cmd = ['git', 'diff']
4823 if options.stat:
4824 cmd.append('--stat')
4825 cmd.append(base)
4826 subprocess2.check_call(cmd)
sbc@chromium.org87b9bf02013-09-26 20:35:15 +00004827
4828 return 0
4829
4830
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004831@metrics.collector.collect_metrics('git cl owners')
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004832def CMDowners(parser, args):
Dirk Prankebf980882017-09-02 15:08:00 -07004833 """Finds potential owners for reviewing."""
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004834 parser.add_option(
Sidney San Martín8e6f58c2018-06-08 01:02:56 +00004835 '--ignore-current',
4836 action='store_true',
4837 help='Ignore the CL\'s current reviewers and start from scratch.')
4838 parser.add_option(
Sylvain Defresneb1f865d2019-02-12 12:38:22 +00004839 '--ignore-self',
4840 action='store_true',
4841 help='Do not consider CL\'s author as an owners.')
4842 parser.add_option(
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004843 '--no-color',
4844 action='store_true',
4845 help='Use this option to disable color output')
Dirk Prankebf980882017-09-02 15:08:00 -07004846 parser.add_option(
4847 '--batch',
4848 action='store_true',
4849 help='Do not run interactively, just suggest some')
Yang Guo6e269a02019-06-26 11:17:02 +00004850 # TODO: Consider moving this to another command, since other
4851 # git-cl owners commands deal with owners for a given CL.
4852 parser.add_option(
4853 '--show-all',
4854 action='store_true',
4855 help='Show all owners for a particular file')
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004856 options, args = parser.parse_args(args)
4857
Edward Lesmescba46082020-03-25 00:29:06 +00004858 author = RunGit(['config', 'user.email']).strip() or None
4859
Edward Lemur934836a2019-09-09 20:16:54 +00004860 cl = Changelist()
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004861
Yang Guo6e269a02019-06-26 11:17:02 +00004862 if options.show_all:
4863 for arg in args:
4864 base_branch = cl.GetCommonAncestorWithUpstream()
Edward Lemurb7f759f2020-03-04 21:20:56 +00004865 database = owners.Database(settings.GetRoot(), open, os.path)
Yang Guo6e269a02019-06-26 11:17:02 +00004866 database.load_data_needed_for([arg])
4867 print('Owners for %s:' % arg)
4868 for owner in sorted(database.all_possible_owners([arg], None)):
4869 print(' - %s' % owner)
4870 return 0
4871
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004872 if args:
4873 if len(args) > 1:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00004874 parser.error('Unknown args.')
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004875 base_branch = args[0]
4876 else:
4877 # Default to diffing against the common ancestor of the upstream branch.
thestig@chromium.org8b0553c2014-02-11 00:33:37 +00004878 base_branch = cl.GetCommonAncestorWithUpstream()
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004879
Edward Lemur2c62b332020-03-12 22:12:33 +00004880 root = settings.GetRoot()
4881 affected_files = cl.GetAffectedFiles(base_branch)
Dirk Prankebf980882017-09-02 15:08:00 -07004882
4883 if options.batch:
Edward Lemur2c62b332020-03-12 22:12:33 +00004884 db = owners.Database(root, open, os.path)
Dirk Prankebf980882017-09-02 15:08:00 -07004885 print('\n'.join(db.reviewers_for(affected_files, author)))
4886 return 0
4887
Edward Lemur2c62b332020-03-12 22:12:33 +00004888 owner_files = [f for f in affected_files if 'OWNERS' in os.path.basename(f)]
4889 original_owner_files = {
4890 f: scm.GIT.GetOldContents(root, f, base_branch).splitlines()
4891 for f in owner_files}
4892
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004893 return owners_finder.OwnersFinder(
Dirk Prankebf980882017-09-02 15:08:00 -07004894 affected_files,
Edward Lemur2c62b332020-03-12 22:12:33 +00004895 root,
Edward Lemur707d70b2018-02-07 00:50:14 +01004896 author,
Sidney San Martín8e6f58c2018-06-08 01:02:56 +00004897 [] if options.ignore_current else cl.GetReviewers(),
Edward Lemur2c62b332020-03-12 22:12:33 +00004898 fopen=open,
4899 os_path=os.path,
Jochen Eisingerd0573ec2017-04-13 10:55:06 +02004900 disable_color=options.no_color,
Edward Lemur2c62b332020-03-12 22:12:33 +00004901 override_files=original_owner_files,
Sylvain Defresneb1f865d2019-02-12 12:38:22 +00004902 ignore_author=options.ignore_self).run()
ikarienator@chromium.orgfaf3fdf2013-09-20 02:11:48 +00004903
4904
Aiden Bennerc08566e2018-10-03 17:52:42 +00004905def BuildGitDiffCmd(diff_type, upstream_commit, args, allow_prefix=False):
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00004906 """Generates a diff command."""
4907 # Generate diff for the current branch's changes.
Aiden Bennerc08566e2018-10-03 17:52:42 +00004908 diff_cmd = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff']
4909
Aiden Benner6c18a1a2018-11-23 20:18:23 +00004910 if allow_prefix:
4911 # explicitly setting --src-prefix and --dst-prefix is necessary in the
4912 # case that diff.noprefix is set in the user's git config.
4913 diff_cmd += ['--src-prefix=a/', '--dst-prefix=b/']
4914 else:
Aiden Bennerc08566e2018-10-03 17:52:42 +00004915 diff_cmd += ['--no-prefix']
4916
4917 diff_cmd += [diff_type, upstream_commit, '--']
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00004918
4919 if args:
4920 for arg in args:
jkarlin@chromium.org6f7fa5e2016-01-20 19:32:21 +00004921 if os.path.isdir(arg) or os.path.isfile(arg):
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00004922 diff_cmd.append(arg)
4923 else:
4924 DieWithError('Argument "%s" is not a file or a directory' % arg)
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00004925
4926 return diff_cmd
4927
Andrii Shyshkalov18975322017-01-25 16:44:13 +01004928
Jamie Madill5e96ad12020-01-13 16:08:35 +00004929def _RunClangFormatDiff(opts, clang_diff_files, top_dir, upstream_commit):
4930 """Runs clang-format-diff and sets a return value if necessary."""
4931
4932 if not clang_diff_files:
4933 return 0
4934
4935 # Set to 2 to signal to CheckPatchFormatted() that this patch isn't
4936 # formatted. This is used to block during the presubmit.
4937 return_value = 0
4938
4939 # Locate the clang-format binary in the checkout
4940 try:
4941 clang_format_tool = clang_format.FindClangFormatToolInChromiumTree()
4942 except clang_format.NotFoundError as e:
4943 DieWithError(e)
4944
4945 if opts.full or settings.GetFormatFullByDefault():
4946 cmd = [clang_format_tool]
4947 if not opts.dry_run and not opts.diff:
4948 cmd.append('-i')
4949 if opts.dry_run:
4950 for diff_file in clang_diff_files:
4951 with open(diff_file, 'r') as myfile:
4952 code = myfile.read().replace('\r\n', '\n')
4953 stdout = RunCommand(cmd + [diff_file], cwd=top_dir)
4954 stdout = stdout.replace('\r\n', '\n')
4955 if opts.diff:
4956 sys.stdout.write(stdout)
4957 if code != stdout:
4958 return_value = 2
4959 else:
4960 stdout = RunCommand(cmd + clang_diff_files, cwd=top_dir)
4961 if opts.diff:
4962 sys.stdout.write(stdout)
4963 else:
4964 env = os.environ.copy()
4965 env['PATH'] = str(os.path.dirname(clang_format_tool))
4966 try:
4967 script = clang_format.FindClangFormatScriptInChromiumTree(
4968 'clang-format-diff.py')
4969 except clang_format.NotFoundError as e:
4970 DieWithError(e)
4971
4972 cmd = [sys.executable, script, '-p0']
4973 if not opts.dry_run and not opts.diff:
4974 cmd.append('-i')
4975
4976 diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, clang_diff_files)
Edward Lemur1a83da12020-03-04 21:18:36 +00004977 diff_output = RunGit(diff_cmd).encode('utf-8')
Jamie Madill5e96ad12020-01-13 16:08:35 +00004978
4979 stdout = RunCommand(cmd, stdin=diff_output, cwd=top_dir, env=env)
4980 if opts.diff:
4981 sys.stdout.write(stdout)
4982 if opts.dry_run and len(stdout) > 0:
4983 return_value = 2
4984
4985 return return_value
4986
4987
jkarlin@chromium.org6f7fa5e2016-01-20 19:32:21 +00004988def MatchingFileType(file_name, extensions):
Quinten Yearsleyd242ed72019-07-25 17:17:55 +00004989 """Returns True if the file name ends with one of the given extensions."""
jkarlin@chromium.org6f7fa5e2016-01-20 19:32:21 +00004990 return bool([ext for ext in extensions if file_name.lower().endswith(ext)])
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00004991
Andrii Shyshkalov18975322017-01-25 16:44:13 +01004992
enne@chromium.org555cfe42014-01-29 18:21:39 +00004993@subcommand.usage('[files or directories to diff]')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00004994@metrics.collector.collect_metrics('git cl format')
agable@chromium.orgfab8f822013-05-06 17:43:09 +00004995def CMDformat(parser, args):
sbc@chromium.org9d0644d2015-06-05 23:16:54 +00004996 """Runs auto-formatting tools (clang-format etc.) on the diff."""
Christopher Lamc5ba6922017-01-24 11:19:14 +11004997 CLANG_EXTS = ['.cc', '.cpp', '.h', '.m', '.mm', '.proto', '.java']
kylechar58edce22016-06-17 06:07:51 -07004998 GN_EXTS = ['.gn', '.gni', '.typemap']
enne@chromium.org3b7e15c2014-01-21 17:44:47 +00004999 parser.add_option('--full', action='store_true',
5000 help='Reformat the full content of all touched files')
5001 parser.add_option('--dry-run', action='store_true',
5002 help='Don\'t modify any file on disk.')
Aiden Benner99b0ccb2018-11-20 19:53:31 +00005003 parser.add_option(
Garrett Beatyed0cc5f2020-01-06 17:26:13 +00005004 '--no-clang-format',
5005 dest='clang_format',
5006 action='store_false',
5007 default=True,
5008 help='Disables formatting of various file types using clang-format.')
5009 parser.add_option(
Aiden Benner99b0ccb2018-11-20 19:53:31 +00005010 '--python',
5011 action='store_true',
5012 default=None,
5013 help='Enables python formatting on all python files.')
5014 parser.add_option(
5015 '--no-python',
5016 action='store_true',
Garrett Beaty91a6f332020-01-06 16:57:24 +00005017 default=False,
Aiden Benner99b0ccb2018-11-20 19:53:31 +00005018 help='Disables python formatting on all python files. '
Garrett Beaty91a6f332020-01-06 16:57:24 +00005019 'If neither --python or --no-python are set, python files that have a '
5020 '.style.yapf file in an ancestor directory will be formatted. '
5021 'It is an error to set both.')
Garrett Beatyed0cc5f2020-01-06 17:26:13 +00005022 parser.add_option(
5023 '--js',
5024 action='store_true',
5025 help='Format javascript code with clang-format. '
5026 'Has no effect if --no-clang-format is set.')
wittman@chromium.org04d5a222014-03-07 18:30:42 +00005027 parser.add_option('--diff', action='store_true',
5028 help='Print diff to stdout rather than modifying files.')
Ilya Shermane081cbe2017-08-15 17:51:04 -07005029 parser.add_option('--presubmit', action='store_true',
5030 help='Used when running the script from a presubmit.')
agable@chromium.orgfab8f822013-05-06 17:43:09 +00005031 opts, args = parser.parse_args(args)
agable@chromium.orgfab8f822013-05-06 17:43:09 +00005032
Garrett Beaty91a6f332020-01-06 16:57:24 +00005033 if opts.python is not None and opts.no_python:
5034 raise parser.error('Cannot set both --python and --no-python')
5035 if opts.no_python:
5036 opts.python = False
5037
Daniel Chengc55eecf2016-12-30 03:11:02 -08005038 # Normalize any remaining args against the current path, so paths relative to
5039 # the current directory are still resolved as expected.
5040 args = [os.path.join(os.getcwd(), arg) for arg in args]
5041
enne@chromium.orgff7a1fb2013-12-10 19:21:41 +00005042 # git diff generates paths against the root of the repository. Change
5043 # to that directory so clang-format can find files even within subdirs.
thestig@chromium.org8b0553c2014-02-11 00:33:37 +00005044 rel_base_path = settings.GetRelativeRoot()
enne@chromium.orgff7a1fb2013-12-10 19:21:41 +00005045 if rel_base_path:
5046 os.chdir(rel_base_path)
5047
digit@chromium.org29e47272013-05-17 17:01:46 +00005048 # Grab the merge-base commit, i.e. the upstream commit of the current
5049 # branch when it was created or the last time it was rebased. This is
5050 # to cover the case where the user may have called "git fetch origin",
5051 # moving the origin branch to a newer commit, but hasn't rebased yet.
5052 upstream_commit = None
5053 cl = Changelist()
5054 upstream_branch = cl.GetUpstreamBranch()
5055 if upstream_branch:
5056 upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch])
5057 upstream_commit = upstream_commit.strip()
5058
5059 if not upstream_commit:
5060 DieWithError('Could not find base commit for this branch. '
5061 'Are you in detached state?')
5062
jkarlin@chromium.org6f7fa5e2016-01-20 19:32:21 +00005063 changed_files_cmd = BuildGitDiffCmd('--name-only', upstream_commit, args)
5064 diff_output = RunGit(changed_files_cmd)
5065 diff_files = diff_output.splitlines()
jkarlin@chromium.orgad21b922016-01-28 17:48:42 +00005066 # Filter out files deleted by this CL
5067 diff_files = [x for x in diff_files if os.path.isfile(x)]
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00005068
Andreas Haas417d89c2020-02-06 10:24:27 +00005069 if opts.js:
Deepanjan Roy605dd312018-07-02 17:48:54 +00005070 CLANG_EXTS.extend(['.js', '.ts'])
Christopher Lamc5ba6922017-01-24 11:19:14 +11005071
Garrett Beatyed0cc5f2020-01-06 17:26:13 +00005072 clang_diff_files = []
5073 if opts.clang_format:
5074 clang_diff_files = [
5075 x for x in diff_files if MatchingFileType(x, CLANG_EXTS)
5076 ]
jkarlin@chromium.org6f7fa5e2016-01-20 19:32:21 +00005077 python_diff_files = [x for x in diff_files if MatchingFileType(x, ['.py'])]
5078 dart_diff_files = [x for x in diff_files if MatchingFileType(x, ['.dart'])]
kylechar@chromium.org8b61f112016-02-05 13:28:58 +00005079 gn_diff_files = [x for x in diff_files if MatchingFileType(x, GN_EXTS)]
digit@chromium.org29e47272013-05-17 17:01:46 +00005080
Edward Lesmescba46082020-03-25 00:29:06 +00005081 top_dir = os.path.normpath(
5082 RunGit(["rev-parse", "--show-toplevel"]).rstrip('\n'))
nick@chromium.org3ac1c4e2014-01-16 02:44:42 +00005083
Jamie Madill5e96ad12020-01-13 16:08:35 +00005084 return_value = _RunClangFormatDiff(opts, clang_diff_files, top_dir,
5085 upstream_commit)
agable@chromium.orgfab8f822013-05-06 17:43:09 +00005086
sbc@chromium.org9d0644d2015-06-05 23:16:54 +00005087 # Similar code to above, but using yapf on .py files rather than clang-format
5088 # on C/C++ files
Aiden Benner99b0ccb2018-11-20 19:53:31 +00005089 py_explicitly_disabled = opts.python is not None and not opts.python
5090 if python_diff_files and not py_explicitly_disabled:
Aiden Bennere47ac152018-11-20 16:44:03 +00005091 depot_tools_path = os.path.dirname(os.path.abspath(__file__))
5092 yapf_tool = os.path.join(depot_tools_path, 'yapf')
5093 if sys.platform.startswith('win'):
5094 yapf_tool += '.bat'
sbc@chromium.org9d0644d2015-06-05 23:16:54 +00005095
Aiden Bennerc08566e2018-10-03 17:52:42 +00005096 # Used for caching.
5097 yapf_configs = {}
5098 for f in python_diff_files:
5099 # Find the yapf style config for the current file, defaults to depot
5100 # tools default.
Aiden Benner99b0ccb2018-11-20 19:53:31 +00005101 _FindYapfConfigFile(f, yapf_configs, top_dir)
5102
5103 # Turn on python formatting by default if a yapf config is specified.
5104 # This breaks in the case of this repo though since the specified
5105 # style file is also the global default.
5106 if opts.python is None:
5107 filtered_py_files = []
5108 for f in python_diff_files:
5109 if _FindYapfConfigFile(f, yapf_configs, top_dir) is not None:
5110 filtered_py_files.append(f)
5111 else:
5112 filtered_py_files = python_diff_files
5113
5114 # Note: yapf still seems to fix indentation of the entire file
5115 # even if line ranges are specified.
5116 # See https://github.com/google/yapf/issues/499
5117 if not opts.full and filtered_py_files:
5118 py_line_diffs = _ComputeDiffLineRanges(filtered_py_files, upstream_commit)
5119
Brian Sheedyb4307d52019-12-02 19:18:17 +00005120 yapfignore_patterns = _GetYapfIgnorePatterns(top_dir)
5121 filtered_py_files = _FilterYapfIgnoredFiles(filtered_py_files,
5122 yapfignore_patterns)
Brian Sheedy59b06a82019-10-14 17:03:29 +00005123
Aiden Benner99b0ccb2018-11-20 19:53:31 +00005124 for f in filtered_py_files:
Andrew Grievefa40bfa2020-01-07 02:32:57 +00005125 yapf_style = _FindYapfConfigFile(f, yapf_configs, top_dir)
5126 # Default to pep8 if not .style.yapf is found.
5127 if not yapf_style:
5128 yapf_style = 'pep8'
Aiden Bennerc08566e2018-10-03 17:52:42 +00005129
Andrew Grievefa40bfa2020-01-07 02:32:57 +00005130 cmd = [yapf_tool, '--style', yapf_style, f]
Aiden Bennerc08566e2018-10-03 17:52:42 +00005131
5132 has_formattable_lines = False
5133 if not opts.full:
5134 # Only run yapf over changed line ranges.
5135 for diff_start, diff_len in py_line_diffs[f]:
5136 diff_end = diff_start + diff_len - 1
5137 # Yapf errors out if diff_end < diff_start but this
5138 # is a valid line range diff for a removal.
5139 if diff_end >= diff_start:
5140 has_formattable_lines = True
5141 cmd += ['-l', '{}-{}'.format(diff_start, diff_end)]
5142 # If all line diffs were removals we have nothing to format.
5143 if not has_formattable_lines:
5144 continue
5145
5146 if opts.diff or opts.dry_run:
5147 cmd += ['--diff']
5148 # Will return non-zero exit code if non-empty diff.
5149 stdout = RunCommand(cmd, error_ok=True, cwd=top_dir)
5150 if opts.diff:
5151 sys.stdout.write(stdout)
5152 elif len(stdout) > 0:
5153 return_value = 2
5154 else:
5155 cmd += ['-i']
5156 RunCommand(cmd, cwd=top_dir)
sbc@chromium.org9d0644d2015-06-05 23:16:54 +00005157
jkarlin@chromium.org6f7fa5e2016-01-20 19:32:21 +00005158 # Dart's formatter does not have the nice property of only operating on
5159 # modified chunks, so hard code full.
5160 if dart_diff_files:
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00005161 try:
5162 command = [dart_format.FindDartFmtToolInChromiumTree()]
5163 if not opts.dry_run and not opts.diff:
5164 command.append('-w')
jkarlin@chromium.org6f7fa5e2016-01-20 19:32:21 +00005165 command.extend(dart_diff_files)
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00005166
ppi@chromium.org6593d932016-03-03 15:41:15 +00005167 stdout = RunCommand(command, cwd=top_dir)
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00005168 if opts.dry_run and stdout:
5169 return_value = 2
Jamie Madill5e96ad12020-01-13 16:08:35 +00005170 except dart_format.NotFoundError:
vapiera7fbd5a2016-06-16 09:17:49 -07005171 print('Warning: Unable to check Dart code formatting. Dart SDK not '
5172 'found in this checkout. Files in other languages are still '
5173 'formatted.')
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00005174
kylechar@chromium.org8b61f112016-02-05 13:28:58 +00005175 # Format GN build files. Always run on full build files for canonical form.
5176 if gn_diff_files:
Andrii Shyshkalov18975322017-01-25 16:44:13 +01005177 cmd = ['gn', 'format']
brettw4b8ed592016-08-05 16:19:12 -07005178 if opts.dry_run or opts.diff:
5179 cmd.append('--dry-run')
kylechar@chromium.org8b61f112016-02-05 13:28:58 +00005180 for gn_diff_file in gn_diff_files:
brettw4b8ed592016-08-05 16:19:12 -07005181 gn_ret = subprocess2.call(cmd + [gn_diff_file],
5182 shell=sys.platform == 'win32',
5183 cwd=top_dir)
5184 if opts.dry_run and gn_ret == 2:
5185 return_value = 2 # Not formatted.
5186 elif opts.diff and gn_ret == 2:
5187 # TODO this should compute and print the actual diff.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00005188 print('This change has GN build file diff for ' + gn_diff_file)
brettw4b8ed592016-08-05 16:19:12 -07005189 elif gn_ret != 0:
5190 # For non-dry run cases (and non-2 return values for dry-run), a
5191 # nonzero error code indicates a failure, probably because the file
5192 # doesn't parse.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00005193 DieWithError('gn format failed on ' + gn_diff_file +
5194 '\nTry running `gn format` on this file manually.')
kylechar@chromium.org8b61f112016-02-05 13:28:58 +00005195
Ilya Shermane081cbe2017-08-15 17:51:04 -07005196 # Skip the metrics formatting from the global presubmit hook. These files have
5197 # a separate presubmit hook that issues an error if the files need formatting,
5198 # whereas the top-level presubmit script merely issues a warning. Formatting
5199 # these files is somewhat slow, so it's important not to duplicate the work.
5200 if not opts.presubmit:
5201 for xml_dir in GetDirtyMetricsDirs(diff_files):
5202 tool_dir = os.path.join(top_dir, xml_dir)
5203 cmd = [os.path.join(tool_dir, 'pretty_print.py'), '--non-interactive']
5204 if opts.dry_run or opts.diff:
5205 cmd.append('--diff')
Ilya Sherman235b70d2017-08-22 17:46:38 -07005206 stdout = RunCommand(cmd, cwd=top_dir)
Ilya Shermane081cbe2017-08-15 17:51:04 -07005207 if opts.diff:
5208 sys.stdout.write(stdout)
5209 if opts.dry_run and stdout:
5210 return_value = 2 # Not formatted.
Alexei Svitkinef3cac412017-02-06 11:08:50 -05005211
erg@chromium.orge0a7c5d2015-02-23 20:30:08 +00005212 return return_value
agable@chromium.orgfab8f822013-05-06 17:43:09 +00005213
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00005214
Steven Holte2e664bf2017-04-21 13:10:47 -07005215def GetDirtyMetricsDirs(diff_files):
5216 xml_diff_files = [x for x in diff_files if MatchingFileType(x, ['.xml'])]
5217 metrics_xml_dirs = [
5218 os.path.join('tools', 'metrics', 'actions'),
5219 os.path.join('tools', 'metrics', 'histograms'),
5220 os.path.join('tools', 'metrics', 'rappor'),
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00005221 os.path.join('tools', 'metrics', 'ukm'),
5222 ]
Steven Holte2e664bf2017-04-21 13:10:47 -07005223 for xml_dir in metrics_xml_dirs:
5224 if any(file.startswith(xml_dir) for file in xml_diff_files):
5225 yield xml_dir
5226
agable@chromium.orgfab8f822013-05-06 17:43:09 +00005227
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005228@subcommand.usage('<codereview url or issue id>')
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00005229@metrics.collector.collect_metrics('git cl checkout')
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005230def CMDcheckout(parser, args):
Edward Lemurf38bc172019-09-03 21:02:13 +00005231 """Checks out a branch associated with a given Gerrit issue."""
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005232 _, args = parser.parse_args(args)
5233
5234 if len(args) != 1:
5235 parser.print_help()
5236 return 1
5237
tandrii@chromium.orgf86c7d32016-04-01 19:27:30 +00005238 issue_arg = ParseIssueNumberArgument(args[0])
tandrii@chromium.orgde6c9a12016-04-11 15:33:53 +00005239 if not issue_arg.valid:
Quinten Yearsleyc4202212019-07-22 23:34:40 +00005240 parser.error('Invalid issue ID or URL.')
Andrii Shyshkalovc9712392017-04-11 13:35:21 +02005241
tandrii@chromium.orgabd27e52016-04-11 15:43:32 +00005242 target_issue = str(issue_arg.issue)
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005243
Edward Lesmescba46082020-03-25 00:29:06 +00005244 issueprefix = Changelist.IssueConfigKey()
Edward Lemur52969c92020-02-06 18:15:28 +00005245 output = RunGit(['config', '--local', '--get-regexp',
Edward Lesmescba46082020-03-25 00:29:06 +00005246 r'branch\..*\.%s' % issueprefix],
Edward Lemur52969c92020-02-06 18:15:28 +00005247 error_ok=True)
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005248
tandrii@chromium.org5df290f2016-04-11 16:12:29 +00005249 branches = []
Edward Lemur52969c92020-02-06 18:15:28 +00005250 for key, issue in [x.split() for x in output.splitlines()]:
5251 if issue == target_issue:
Edward Lesmescba46082020-03-25 00:29:06 +00005252 branches.append(re.sub(r'branch\.(.*)\.%s' % issueprefix, r'\1', key))
Edward Lemur52969c92020-02-06 18:15:28 +00005253
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005254 if len(branches) == 0:
vapiera7fbd5a2016-06-16 09:17:49 -07005255 print('No branch found for issue %s.' % target_issue)
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005256 return 1
5257 if len(branches) == 1:
5258 RunGit(['checkout', branches[0]])
5259 else:
vapiera7fbd5a2016-06-16 09:17:49 -07005260 print('Multiple branches match issue %s:' % target_issue)
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005261 for i in range(len(branches)):
vapiera7fbd5a2016-06-16 09:17:49 -07005262 print('%d: %s' % (i, branches[i]))
Edward Lesmesae3586b2020-03-23 21:21:14 +00005263 which = gclient_utils.AskForData('Choose by index: ')
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005264 try:
5265 RunGit(['checkout', branches[int(which)]])
5266 except (IndexError, ValueError):
vapiera7fbd5a2016-06-16 09:17:49 -07005267 print('Invalid selection, not checking out any branch.')
scottmg@chromium.org84a80c42015-09-22 20:40:37 +00005268 return 1
5269
5270 return 0
5271
5272
maruel@chromium.org29404b52014-09-08 22:58:00 +00005273def CMDlol(parser, args):
5274 # This command is intentionally undocumented.
vapiera7fbd5a2016-06-16 09:17:49 -07005275 print(zlib.decompress(base64.b64decode(
thakis@chromium.org3421c992014-11-02 02:20:32 +00005276 'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE'
5277 'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9'
5278 'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W'
vapiera7fbd5a2016-06-16 09:17:49 -07005279 'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY')))
maruel@chromium.org29404b52014-09-08 22:58:00 +00005280 return 0
5281
5282
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00005283class OptionParser(optparse.OptionParser):
5284 """Creates the option parse and add --verbose support."""
5285 def __init__(self, *args, **kwargs):
maruel@chromium.org0633fb42013-08-16 20:06:14 +00005286 optparse.OptionParser.__init__(
5287 self, *args, prog='git cl', version=__version__, **kwargs)
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00005288 self.add_option(
5289 '-v', '--verbose', action='count', default=0,
5290 help='Use 2 times for more debugging info')
5291
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00005292 def parse_args(self, args=None, _values=None):
Andrii Shyshkalov46f20cd2018-10-30 06:42:54 +00005293 try:
5294 return self._parse_args(args)
5295 finally:
5296 # Regardless of success or failure of args parsing, we want to report
5297 # metrics, but only after logging has been initialized (if parsing
5298 # succeeded).
5299 global settings
5300 settings = Settings()
5301
5302 if not metrics.DISABLE_METRICS_COLLECTION:
5303 # GetViewVCUrl ultimately calls logging method.
5304 project_url = settings.GetViewVCUrl().strip('/+')
5305 if project_url in metrics_utils.KNOWN_PROJECT_URLS:
5306 metrics.collector.add('project_urls', [project_url])
5307
5308 def _parse_args(self, args=None):
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00005309 # Create an optparse.Values object that will store only the actual passed
5310 # options, without the defaults.
5311 actual_options = optparse.Values()
5312 _, args = optparse.OptionParser.parse_args(self, args, actual_options)
5313 # Create an optparse.Values object with the default options.
5314 options = optparse.Values(self.get_default_values().__dict__)
5315 # Update it with the options passed by the user.
5316 options._update_careful(actual_options.__dict__)
5317 # Store the options passed by the user in an _actual_options attribute.
5318 # We store only the keys, and not the values, since the values can contain
5319 # arbitrary information, which might be PII.
Edward Lemur79d4f992019-11-11 23:49:02 +00005320 metrics.collector.add('arguments', list(actual_options.__dict__.keys()))
Edward Lemur5ba1e9c2018-07-23 18:19:02 +00005321
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00005322 levels = [logging.WARNING, logging.INFO, logging.DEBUG]
Andrii Shyshkalov5b04a572017-01-23 17:44:41 +01005323 logging.basicConfig(
5324 level=levels[min(options.verbose, len(levels) - 1)],
5325 format='[%(levelname).1s%(asctime)s %(process)d %(thread)d '
5326 '%(filename)s] %(message)s')
Edward Lemur83bd7f42018-10-10 00:14:21 +00005327
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00005328 return options, args
5329
iannucci@chromium.orgd9c1b202013-07-24 23:52:11 +00005330
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00005331def main(argv):
maruel@chromium.org82798cb2012-02-23 18:16:12 +00005332 if sys.hexversion < 0x02060000:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00005333 print('\nYour Python version %s is unsupported, please upgrade.\n' %
vapiera7fbd5a2016-06-16 09:17:49 -07005334 (sys.version.split(' ', 1)[0],), file=sys.stderr)
maruel@chromium.org82798cb2012-02-23 18:16:12 +00005335 return 2
maruel@chromium.org2e23ce32013-05-07 12:42:28 +00005336
maruel@chromium.org39c0b222013-08-17 16:57:01 +00005337 colorize_CMDstatus_doc()
maruel@chromium.org0633fb42013-08-16 20:06:14 +00005338 dispatcher = subcommand.CommandDispatcher(__name__)
5339 try:
5340 return dispatcher.execute(OptionParser(), argv)
Edward Lemur5b929a42019-10-21 17:57:39 +00005341 except auth.LoginRequiredError as e:
vadimsh@chromium.orgeed4df32015-04-10 21:30:20 +00005342 DieWithError(str(e))
Edward Lemur79d4f992019-11-11 23:49:02 +00005343 except urllib.error.HTTPError as e:
maruel@chromium.org0633fb42013-08-16 20:06:14 +00005344 if e.code != 500:
5345 raise
5346 DieWithError(
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00005347 ('App Engine is misbehaving and returned HTTP %d, again. Keep faith '
Quinten Yearsleyc4202212019-07-22 23:34:40 +00005348 'and retry or visit go/isgaeup.\n%s') % (e.code, str(e)))
sbc@chromium.org013731e2015-02-26 18:28:43 +00005349 return 0
chase@chromium.orgcc51cd02010-12-23 00:48:39 +00005350
5351
5352if __name__ == '__main__':
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00005353 # These affect sys.stdout, so do it outside of main() to simplify mocks in
5354 # the unit tests.
maruel@chromium.org6f09cd92011-04-01 16:38:12 +00005355 fix_encoding.fix_encoding()
iannucci@chromium.org596cd5c2016-04-04 21:34:39 +00005356 setup_color.init()
Edward Lemur6f812e12018-07-31 22:45:57 +00005357 with metrics.collector.print_notice_and_exit():
sbc@chromium.org013731e2015-02-26 18:28:43 +00005358 sys.exit(main(sys.argv[1:]))