iannucci@chromium.org | 405b87e | 2015-11-12 18:08:34 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
Andrii Shyshkalov | 0d2dea0 | 2017-07-17 15:17:55 +0200 | [diff] [blame] | 2 | # Copyright (c) 2013 The Chromium Authors. All rights reserved. |
maruel@chromium.org | 725f1c3 | 2011-04-01 20:24:54 +0000 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 6 | # Copyright (C) 2008 Evan Martin <martine@danga.com> |
| 7 | |
Andrii Shyshkalov | 03da150 | 2018-10-15 03:42:34 +0000 | [diff] [blame] | 8 | """A git-command for integrating reviews on Gerrit.""" |
maruel@chromium.org | 725f1c3 | 2011-04-01 20:24:54 +0000 | [diff] [blame] | 9 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 10 | from __future__ import print_function |
| 11 | |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 12 | from distutils.version import LooseVersion |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 13 | from multiprocessing.pool import ThreadPool |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 14 | import base64 |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 15 | import collections |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 16 | import contextlib |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 17 | import datetime |
Andrii Shyshkalov | cd6a936 | 2016-12-07 12:04:12 +0100 | [diff] [blame] | 18 | import fnmatch |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 19 | import httplib |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 20 | import itertools |
maruel@chromium.org | 4f6852c | 2012-04-20 20:39:20 +0000 | [diff] [blame] | 21 | import json |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 22 | import logging |
calamity@chromium.org | cf19748 | 2016-04-29 20:15:53 +0000 | [diff] [blame] | 23 | import multiprocessing |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 24 | import optparse |
| 25 | import os |
| 26 | import re |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 27 | import shutil |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 28 | import stat |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 29 | import sys |
Aaron Gable | 9a03ae0 | 2017-11-03 11:31:07 -0700 | [diff] [blame] | 30 | import tempfile |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 31 | import textwrap |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 32 | import urllib |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 33 | import urllib2 |
maruel@chromium.org | 967c0a8 | 2013-06-17 22:52:24 +0000 | [diff] [blame] | 34 | import urlparse |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 35 | import uuid |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 36 | import webbrowser |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 37 | import zlib |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 38 | |
| 39 | try: |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 40 | import readline # pylint: disable=import-error,W0611 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 41 | except ImportError: |
| 42 | pass |
| 43 | |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 44 | from third_party import colorama |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 45 | from third_party import httplib2 |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 46 | from third_party import upload |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 47 | import auth |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 48 | import checkout |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 49 | import clang_format |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 50 | import dart_format |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 51 | import setup_color |
maruel@chromium.org | 6f09cd9 | 2011-04-01 16:38:12 +0000 | [diff] [blame] | 52 | import fix_encoding |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 53 | import gclient_utils |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 54 | import gerrit_util |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 55 | import git_cache |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 56 | import git_common |
tandrii@chromium.org | 09d7a6a | 2016-03-04 15:44:48 +0000 | [diff] [blame] | 57 | import git_footers |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 58 | import metrics |
Edward Lesmes | 93277a7 | 2018-10-18 22:04:26 +0000 | [diff] [blame] | 59 | import metrics_utils |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 60 | import owners |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 61 | import owners_finder |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 62 | import presubmit_support |
maruel@chromium.org | cab38e9 | 2011-04-09 00:30:51 +0000 | [diff] [blame] | 63 | import rietveld |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 64 | import scm |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 65 | import split_cl |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 66 | import subcommand |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 67 | import subprocess2 |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 68 | import watchlists |
| 69 | |
tandrii | 7400cf0 | 2016-06-21 08:48:07 -0700 | [diff] [blame] | 70 | __version__ = '2.0' |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 71 | |
tandrii | 9d2c7a3 | 2016-06-22 03:42:45 -0700 | [diff] [blame] | 72 | COMMIT_BOT_EMAIL = 'commit-bot@chromium.org' |
iannucci | e7f6895 | 2016-08-15 17:45:29 -0700 | [diff] [blame] | 73 | DEFAULT_SERVER = 'https://codereview.chromium.org' |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 74 | POSTUPSTREAM_HOOK = '.git/hooks/post-cl-land' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 75 | DESCRIPTION_BACKUP_FILE = '~/.git_cl_description_backup' |
rmistry@google.com | c68112d | 2015-03-03 12:48:06 +0000 | [diff] [blame] | 76 | REFS_THAT_ALIAS_TO_OTHER_REFS = { |
| 77 | 'refs/remotes/origin/lkgr': 'refs/remotes/origin/master', |
| 78 | 'refs/remotes/origin/lkcr': 'refs/remotes/origin/master', |
| 79 | } |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 80 | |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 81 | # Valid extensions for files we want to lint. |
| 82 | DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)" |
| 83 | DEFAULT_LINT_IGNORE_REGEX = r"$^" |
| 84 | |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 85 | # File name for yapf style config files. |
| 86 | YAPF_CONFIG_FILENAME = '.style.yapf' |
| 87 | |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 88 | # Buildbucket master name prefix. |
| 89 | MASTER_PREFIX = 'master.' |
| 90 | |
Edward Lemur | 83bd7f4 | 2018-10-10 00:14:21 +0000 | [diff] [blame] | 91 | # TODO(crbug.com/881860): Remove |
| 92 | # Log gerrit failures to a gerrit_util.GERRIT_ERR_LOG_FILE. |
| 93 | GERRIT_ERR_LOGGER = logging.getLogger('GerritErrorLogs') |
| 94 | |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 95 | # Shortcut since it quickly becomes redundant. |
| 96 | Fore = colorama.Fore |
maruel@chromium.org | 9054173 | 2011-04-01 17:54:18 +0000 | [diff] [blame] | 97 | |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 98 | # Initialized in main() |
| 99 | settings = None |
| 100 | |
Andrii Shyshkalov | 768f1d8 | 2016-12-08 15:10:13 +0100 | [diff] [blame] | 101 | # Used by tests/git_cl_test.py to add extra logging. |
| 102 | # Inside the weirdly failing test, add this: |
| 103 | # >>> self.mock(git_cl, '_IS_BEING_TESTED', True) |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 104 | # And scroll up to see the stack trace printed. |
Andrii Shyshkalov | 768f1d8 | 2016-12-08 15:10:13 +0100 | [diff] [blame] | 105 | _IS_BEING_TESTED = False |
| 106 | |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 107 | |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 108 | def DieWithError(message, change_desc=None): |
| 109 | if change_desc: |
| 110 | SaveDescriptionBackup(change_desc) |
| 111 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 112 | print(message, file=sys.stderr) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 113 | sys.exit(1) |
| 114 | |
| 115 | |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 116 | def SaveDescriptionBackup(change_desc): |
| 117 | backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE) |
Andrii Shyshkalov | d9fdc1f | 2018-09-27 02:13:09 +0000 | [diff] [blame] | 118 | print('\nsaving CL description to %s\n' % backup_path) |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 119 | backup_file = open(backup_path, 'w') |
| 120 | backup_file.write(change_desc.description) |
| 121 | backup_file.close() |
| 122 | |
| 123 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 124 | def GetNoGitPagerEnv(): |
| 125 | env = os.environ.copy() |
| 126 | # 'cat' is a magical git string that disables pagers on all platforms. |
| 127 | env['GIT_PAGER'] = 'cat' |
| 128 | return env |
| 129 | |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 130 | |
bsep@chromium.org | 627d900 | 2016-04-29 00:00:52 +0000 | [diff] [blame] | 131 | def RunCommand(args, error_ok=False, error_message=None, shell=False, **kwargs): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 132 | try: |
bsep@chromium.org | 627d900 | 2016-04-29 00:00:52 +0000 | [diff] [blame] | 133 | return subprocess2.check_output(args, shell=shell, **kwargs) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 134 | except subprocess2.CalledProcessError as e: |
| 135 | logging.debug('Failed running %s', args) |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 136 | if not error_ok: |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 137 | DieWithError( |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 138 | 'Command "%s" failed.\n%s' % ( |
| 139 | ' '.join(args), error_message or e.stdout or '')) |
| 140 | return e.stdout |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 141 | |
| 142 | |
| 143 | def RunGit(args, **kwargs): |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 144 | """Returns stdout.""" |
bratell@opera.com | 82b91cd | 2013-07-09 06:33:41 +0000 | [diff] [blame] | 145 | return RunCommand(['git'] + args, **kwargs) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 146 | |
| 147 | |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 148 | def RunGitWithCode(args, suppress_stderr=False): |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 149 | """Returns return code and stdout.""" |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 150 | if suppress_stderr: |
| 151 | stderr = subprocess2.VOID |
| 152 | else: |
| 153 | stderr = sys.stderr |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 154 | try: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 155 | (out, _), code = subprocess2.communicate(['git'] + args, |
| 156 | env=GetNoGitPagerEnv(), |
| 157 | stdout=subprocess2.PIPE, |
| 158 | stderr=stderr) |
| 159 | return code, out |
| 160 | except subprocess2.CalledProcessError as e: |
Yoshisato Yanagisawa | 81e3ff5 | 2017-09-26 15:33:34 +0900 | [diff] [blame] | 161 | logging.debug('Failed running %s', ['git'] + args) |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 162 | return e.returncode, e.stdout |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 163 | |
| 164 | |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 165 | def RunGitSilent(args): |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 166 | """Returns stdout, suppresses stderr and ignores the return code.""" |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 167 | return RunGitWithCode(args, suppress_stderr=True)[1] |
| 168 | |
| 169 | |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 170 | def IsGitVersionAtLeast(min_version): |
ilevy@chromium.org | cc56ee4 | 2013-07-10 22:16:29 +0000 | [diff] [blame] | 171 | prefix = 'git version ' |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 172 | version = RunGit(['--version']).strip() |
ilevy@chromium.org | cc56ee4 | 2013-07-10 22:16:29 +0000 | [diff] [blame] | 173 | return (version.startswith(prefix) and |
| 174 | LooseVersion(version[len(prefix):]) >= LooseVersion(min_version)) |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 175 | |
| 176 | |
pgervais@chromium.org | 8ba38ff | 2015-06-11 21:41:25 +0000 | [diff] [blame] | 177 | def BranchExists(branch): |
| 178 | """Return True if specified branch exists.""" |
| 179 | code, _ = RunGitWithCode(['rev-parse', '--verify', branch], |
| 180 | suppress_stderr=True) |
| 181 | return not code |
| 182 | |
| 183 | |
tandrii | 2a16b95 | 2016-10-19 07:09:44 -0700 | [diff] [blame] | 184 | def time_sleep(seconds): |
| 185 | # Use this so that it can be mocked in tests without interfering with python |
| 186 | # system machinery. |
| 187 | import time # Local import to discourage others from importing time globally. |
| 188 | return time.sleep(seconds) |
| 189 | |
| 190 | |
maruel@chromium.org | 9054173 | 2011-04-01 17:54:18 +0000 | [diff] [blame] | 191 | def ask_for_data(prompt): |
| 192 | try: |
| 193 | return raw_input(prompt) |
| 194 | except KeyboardInterrupt: |
| 195 | # Hide the exception. |
| 196 | sys.exit(1) |
| 197 | |
| 198 | |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 199 | def confirm_or_exit(prefix='', action='confirm'): |
| 200 | """Asks user to press enter to continue or press Ctrl+C to abort.""" |
| 201 | if not prefix or prefix.endswith('\n'): |
| 202 | mid = 'Press' |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 203 | elif prefix.endswith('.') or prefix.endswith('?'): |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 204 | mid = ' Press' |
| 205 | elif prefix.endswith(' '): |
| 206 | mid = 'press' |
| 207 | else: |
| 208 | mid = ' press' |
| 209 | ask_for_data('%s%s Enter to %s, or Ctrl+C to abort' % (prefix, mid, action)) |
| 210 | |
| 211 | |
| 212 | def ask_for_explicit_yes(prompt): |
| 213 | """Returns whether user typed 'y' or 'yes' to confirm the given prompt""" |
| 214 | result = ask_for_data(prompt + ' [Yes/No]: ').lower() |
| 215 | while True: |
| 216 | if 'yes'.startswith(result): |
| 217 | return True |
| 218 | if 'no'.startswith(result): |
| 219 | return False |
| 220 | result = ask_for_data('Please, type yes or no: ').lower() |
| 221 | |
| 222 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 223 | def _git_branch_config_key(branch, key): |
| 224 | """Helper method to return Git config key for a branch.""" |
| 225 | assert branch, 'branch name is required to set git config for it' |
| 226 | return 'branch.%s.%s' % (branch, key) |
| 227 | |
| 228 | |
| 229 | def _git_get_branch_config_value(key, default=None, value_type=str, |
| 230 | branch=False): |
| 231 | """Returns git config value of given or current branch if any. |
| 232 | |
| 233 | Returns default in all other cases. |
| 234 | """ |
| 235 | assert value_type in (int, str, bool) |
| 236 | if branch is False: # Distinguishing default arg value from None. |
| 237 | branch = GetCurrentBranch() |
| 238 | |
rogerta@chromium.org | caa1655 | 2013-03-18 20:45:05 +0000 | [diff] [blame] | 239 | if not branch: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 240 | return default |
rogerta@chromium.org | caa1655 | 2013-03-18 20:45:05 +0000 | [diff] [blame] | 241 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 242 | args = ['config'] |
tandrii | 33a46ff | 2016-08-23 05:53:40 -0700 | [diff] [blame] | 243 | if value_type == bool: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 244 | args.append('--bool') |
tandrii | 33a46ff | 2016-08-23 05:53:40 -0700 | [diff] [blame] | 245 | # git config also has --int, but apparently git config suffers from integer |
| 246 | # overflows (http://crbug.com/640115), so don't use it. |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 247 | args.append(_git_branch_config_key(branch, key)) |
| 248 | code, out = RunGitWithCode(args) |
| 249 | if code == 0: |
| 250 | value = out.strip() |
| 251 | if value_type == int: |
| 252 | return int(value) |
| 253 | if value_type == bool: |
| 254 | return bool(value.lower() == 'true') |
| 255 | return value |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 256 | return default |
| 257 | |
| 258 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 259 | def _git_set_branch_config_value(key, value, branch=None, **kwargs): |
| 260 | """Sets the value or unsets if it's None of a git branch config. |
| 261 | |
| 262 | Valid, though not necessarily existing, branch must be provided, |
| 263 | otherwise currently checked out branch is used. |
| 264 | """ |
| 265 | if not branch: |
| 266 | branch = GetCurrentBranch() |
| 267 | assert branch, 'a branch name OR currently checked out branch is required' |
| 268 | args = ['config'] |
qyearsley | 12fa6ff | 2016-08-24 09:18:40 -0700 | [diff] [blame] | 269 | # Check for boolean first, because bool is int, but int is not bool. |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 270 | if value is None: |
| 271 | args.append('--unset') |
| 272 | elif isinstance(value, bool): |
| 273 | args.append('--bool') |
| 274 | value = str(value).lower() |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 275 | else: |
tandrii | 33a46ff | 2016-08-23 05:53:40 -0700 | [diff] [blame] | 276 | # git config also has --int, but apparently git config suffers from integer |
| 277 | # overflows (http://crbug.com/640115), so don't use it. |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 278 | value = str(value) |
| 279 | args.append(_git_branch_config_key(branch, key)) |
| 280 | if value is not None: |
| 281 | args.append(value) |
| 282 | RunGit(args, **kwargs) |
| 283 | |
| 284 | |
Andrii Shyshkalov | a669581 | 2016-12-06 17:47:09 +0100 | [diff] [blame] | 285 | def _get_committer_timestamp(commit): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 286 | """Returns Unix timestamp as integer of a committer in a commit. |
Andrii Shyshkalov | a669581 | 2016-12-06 17:47:09 +0100 | [diff] [blame] | 287 | |
| 288 | Commit can be whatever git show would recognize, such as HEAD, sha1 or ref. |
| 289 | """ |
| 290 | # Git also stores timezone offset, but it only affects visual display, |
| 291 | # actual point in time is defined by this timestamp only. |
| 292 | return int(RunGit(['show', '-s', '--format=%ct', commit]).strip()) |
| 293 | |
| 294 | |
| 295 | def _git_amend_head(message, committer_timestamp): |
| 296 | """Amends commit with new message and desired committer_timestamp. |
| 297 | |
| 298 | Sets committer timezone to UTC. |
| 299 | """ |
| 300 | env = os.environ.copy() |
| 301 | env['GIT_COMMITTER_DATE'] = '%d+0000' % committer_timestamp |
| 302 | return RunGit(['commit', '--amend', '-m', message], env=env) |
| 303 | |
| 304 | |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 305 | def _get_properties_from_options(options): |
| 306 | properties = dict(x.split('=', 1) for x in options.properties) |
| 307 | for key, val in properties.iteritems(): |
| 308 | try: |
| 309 | properties[key] = json.loads(val) |
| 310 | except ValueError: |
| 311 | pass # If a value couldn't be evaluated, treat it as a string. |
| 312 | return properties |
| 313 | |
| 314 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 315 | def _prefix_master(master): |
| 316 | """Convert user-specified master name to full master name. |
| 317 | |
| 318 | Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket |
| 319 | name, while the developers always use shortened master name |
| 320 | (tryserver.chromium.linux) by stripping off the prefix 'master.'. This |
| 321 | function does the conversion for buildbucket migration. |
| 322 | """ |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 323 | if master.startswith(MASTER_PREFIX): |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 324 | return master |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 325 | return '%s%s' % (MASTER_PREFIX, master) |
| 326 | |
| 327 | |
| 328 | def _unprefix_master(bucket): |
| 329 | """Convert bucket name to shortened master name. |
| 330 | |
| 331 | Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket |
| 332 | name, while the developers always use shortened master name |
| 333 | (tryserver.chromium.linux) by stripping off the prefix 'master.'. This |
| 334 | function does the conversion for buildbucket migration. |
| 335 | """ |
| 336 | if bucket.startswith(MASTER_PREFIX): |
| 337 | return bucket[len(MASTER_PREFIX):] |
| 338 | return bucket |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 339 | |
| 340 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 341 | def _buildbucket_retry(operation_name, http, *args, **kwargs): |
| 342 | """Retries requests to buildbucket service and returns parsed json content.""" |
| 343 | try_count = 0 |
| 344 | while True: |
| 345 | response, content = http.request(*args, **kwargs) |
| 346 | try: |
| 347 | content_json = json.loads(content) |
| 348 | except ValueError: |
| 349 | content_json = None |
| 350 | |
| 351 | # Buildbucket could return an error even if status==200. |
| 352 | if content_json and content_json.get('error'): |
nodir@chromium.org | baff4e1 | 2016-03-08 00:33:57 +0000 | [diff] [blame] | 353 | error = content_json.get('error') |
| 354 | if error.get('code') == 403: |
| 355 | raise BuildbucketResponseException( |
| 356 | 'Access denied: %s' % error.get('message', '')) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 357 | msg = 'Error in response. Reason: %s. Message: %s.' % ( |
nodir@chromium.org | baff4e1 | 2016-03-08 00:33:57 +0000 | [diff] [blame] | 358 | error.get('reason', ''), error.get('message', '')) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 359 | raise BuildbucketResponseException(msg) |
| 360 | |
| 361 | if response.status == 200: |
Nodir Turakulov | 23d75d2 | 2018-06-04 12:37:32 -0700 | [diff] [blame] | 362 | if content_json is None: |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 363 | raise BuildbucketResponseException( |
| 364 | 'Buildbucket returns invalid json content: %s.\n' |
Nodir Turakulov | 9ac5979 | 2018-06-04 12:34:14 -0700 | [diff] [blame] | 365 | 'Please file bugs at http://crbug.com, ' |
| 366 | 'component "Infra>Platform>BuildBucket".' % |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 367 | content) |
| 368 | return content_json |
| 369 | if response.status < 500 or try_count >= 2: |
| 370 | raise httplib2.HttpLib2Error(content) |
| 371 | |
| 372 | # status >= 500 means transient failures. |
| 373 | logging.debug('Transient errors when %s. Will retry.', operation_name) |
tandrii | 2a16b95 | 2016-10-19 07:09:44 -0700 | [diff] [blame] | 374 | time_sleep(0.5 + 1.5*try_count) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 375 | try_count += 1 |
| 376 | assert False, 'unreachable' |
| 377 | |
| 378 | |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 379 | def _get_bucket_map(changelist, options, option_parser): |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 380 | """Returns a dict mapping bucket names to builders and tests, |
| 381 | for triggering try jobs. |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 382 | """ |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 383 | # If no bots are listed, we try to get a set of builders and tests based |
| 384 | # on GetPreferredTryMasters functions in PRESUBMIT.py files. |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 385 | if not options.bot: |
| 386 | change = changelist.GetChange( |
| 387 | changelist.GetCommonAncestorWithUpstream(), None) |
qyearsley | 136b49f | 2016-10-31 09:02:26 -0700 | [diff] [blame] | 388 | # Get try masters from PRESUBMIT.py files. |
nodir | e4f0fe0 | 2016-11-04 16:23:30 -0700 | [diff] [blame] | 389 | masters = presubmit_support.DoGetTryMasters( |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 390 | change=change, |
| 391 | changed_files=change.LocalPaths(), |
| 392 | repository_root=settings.GetRoot(), |
| 393 | default_presubmit=None, |
| 394 | project=None, |
| 395 | verbose=options.verbose, |
| 396 | output_stream=sys.stdout) |
nodir | e4f0fe0 | 2016-11-04 16:23:30 -0700 | [diff] [blame] | 397 | if masters is None: |
| 398 | return None |
Sergiy Byelozyorov | 935b93f | 2016-11-28 20:41:56 +0100 | [diff] [blame] | 399 | return {_prefix_master(m): b for m, b in masters.iteritems()} |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 400 | |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 401 | if options.bucket: |
| 402 | return {options.bucket: {b: [] for b in options.bot}} |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 403 | if options.master: |
| 404 | return {_prefix_master(options.master): {b: [] for b in options.bot}} |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 405 | |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 406 | # If bots are listed but no master or bucket, then we need to find out |
| 407 | # the corresponding master for each bot. |
| 408 | bucket_map, error_message = _get_bucket_map_for_builders(options.bot) |
| 409 | if error_message: |
| 410 | option_parser.error( |
| 411 | 'Tryserver master cannot be found because: %s\n' |
| 412 | 'Please manually specify the tryserver master, e.g. ' |
| 413 | '"-m tryserver.chromium.linux".' % error_message) |
| 414 | return bucket_map |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 415 | |
| 416 | |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 417 | def _get_bucket_map_for_builders(builders): |
| 418 | """Returns a map of buckets to builders for the given builders.""" |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 419 | map_url = 'https://builders-map.appspot.com/' |
| 420 | try: |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 421 | builders_map = json.load(urllib2.urlopen(map_url)) |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 422 | except urllib2.URLError as e: |
| 423 | return None, ('Failed to fetch builder-to-master map from %s. Error: %s.' % |
| 424 | (map_url, e)) |
| 425 | except ValueError as e: |
| 426 | return None, ('Invalid json string from %s. Error: %s.' % (map_url, e)) |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 427 | if not builders_map: |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 428 | return None, 'Failed to build master map.' |
| 429 | |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 430 | bucket_map = {} |
| 431 | for builder in builders: |
Nodir Turakulov | b422e68 | 2018-02-20 22:51:30 -0800 | [diff] [blame] | 432 | bucket = builders_map.get(builder, {}).get('bucket') |
| 433 | if bucket: |
| 434 | bucket_map.setdefault(bucket, {})[builder] = [] |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 435 | return bucket_map, None |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 436 | |
| 437 | |
Andrii Shyshkalov | f9648b5 | 2018-02-21 22:32:42 -0800 | [diff] [blame] | 438 | def _trigger_try_jobs(auth_config, changelist, buckets, options, patchset): |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 439 | """Sends a request to Buildbucket to trigger try jobs for a changelist. |
| 440 | |
| 441 | Args: |
Aaron Gable | fb28d48 | 2018-04-02 13:08:06 -0700 | [diff] [blame] | 442 | auth_config: AuthConfig for Buildbucket. |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 443 | changelist: Changelist that the try jobs are associated with. |
| 444 | buckets: A nested dict mapping bucket names to builders to tests. |
| 445 | options: Command-line options. |
| 446 | """ |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 447 | assert changelist.GetIssue(), 'CL must be uploaded first' |
| 448 | codereview_url = changelist.GetCodereviewServer() |
| 449 | assert codereview_url, 'CL must be uploaded first' |
| 450 | patchset = patchset or changelist.GetMostRecentPatchset() |
| 451 | assert patchset, 'CL must be uploaded first' |
| 452 | |
| 453 | codereview_host = urlparse.urlparse(codereview_url).hostname |
Aaron Gable | fb28d48 | 2018-04-02 13:08:06 -0700 | [diff] [blame] | 454 | # Cache the buildbucket credentials under the codereview host key, so that |
| 455 | # users can use different credentials for different buckets. |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 456 | authenticator = auth.get_authenticator_for_host(codereview_host, auth_config) |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 457 | http = authenticator.authorize(httplib2.Http()) |
| 458 | http.force_exception_to_status_code = True |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 459 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 460 | buildbucket_put_url = ( |
| 461 | 'https://{hostname}/_ah/api/buildbucket/v1/builds/batch'.format( |
sheyang@chromium.org | db37557 | 2015-08-17 19:22:23 +0000 | [diff] [blame] | 462 | hostname=options.buildbucket_host)) |
Andrii Shyshkalov | 03da150 | 2018-10-15 03:42:34 +0000 | [diff] [blame] | 463 | buildset = 'patch/gerrit/{hostname}/{issue}/{patch}'.format( |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 464 | hostname=codereview_host, |
| 465 | issue=changelist.GetIssue(), |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 466 | patch=patchset) |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 467 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 468 | shared_parameters_properties = changelist.GetTryJobProperties(patchset) |
Andrii Shyshkalov | f9648b5 | 2018-02-21 22:32:42 -0800 | [diff] [blame] | 469 | shared_parameters_properties['category'] = options.category |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 470 | if options.clobber: |
| 471 | shared_parameters_properties['clobber'] = True |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 472 | extra_properties = _get_properties_from_options(options) |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 473 | if extra_properties: |
| 474 | shared_parameters_properties.update(extra_properties) |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 475 | |
| 476 | batch_req_body = {'builds': []} |
| 477 | print_text = [] |
| 478 | print_text.append('Tried jobs on:') |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 479 | for bucket, builders_and_tests in sorted(buckets.iteritems()): |
| 480 | print_text.append('Bucket: %s' % bucket) |
| 481 | master = None |
| 482 | if bucket.startswith(MASTER_PREFIX): |
| 483 | master = _unprefix_master(bucket) |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 484 | for builder, tests in sorted(builders_and_tests.iteritems()): |
| 485 | print_text.append(' %s: %s' % (builder, tests)) |
| 486 | parameters = { |
| 487 | 'builder_name': builder, |
nodir@chromium.org | d221731 | 2015-09-21 15:51:21 +0000 | [diff] [blame] | 488 | 'changes': [{ |
Andrii Shyshkalov | eadad92 | 2017-01-26 09:38:30 +0100 | [diff] [blame] | 489 | 'author': {'email': changelist.GetIssueOwner()}, |
nodir@chromium.org | d221731 | 2015-09-21 15:51:21 +0000 | [diff] [blame] | 490 | 'revision': options.revision, |
| 491 | }], |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 492 | 'properties': shared_parameters_properties.copy(), |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 493 | } |
machenbach@chromium.org | 2403e80 | 2016-04-29 12:34:42 +0000 | [diff] [blame] | 494 | if 'presubmit' in builder.lower(): |
| 495 | parameters['properties']['dry_run'] = 'true' |
tandrii@chromium.org | 3764fa2 | 2015-10-21 16:40:40 +0000 | [diff] [blame] | 496 | if tests: |
| 497 | parameters['properties']['testfilter'] = tests |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 498 | |
| 499 | tags = [ |
| 500 | 'builder:%s' % builder, |
| 501 | 'buildset:%s' % buildset, |
| 502 | 'user_agent:git_cl_try', |
| 503 | ] |
| 504 | if master: |
| 505 | parameters['properties']['master'] = master |
| 506 | tags.append('master:%s' % master) |
| 507 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 508 | batch_req_body['builds'].append( |
| 509 | { |
| 510 | 'bucket': bucket, |
| 511 | 'parameters_json': json.dumps(parameters), |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 512 | 'client_operation_id': str(uuid.uuid4()), |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 513 | 'tags': tags, |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 514 | } |
| 515 | ) |
| 516 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 517 | _buildbucket_retry( |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 518 | 'triggering try jobs', |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 519 | http, |
| 520 | buildbucket_put_url, |
| 521 | 'PUT', |
| 522 | body=json.dumps(batch_req_body), |
| 523 | headers={'Content-Type': 'application/json'} |
| 524 | ) |
tandrii@chromium.org | 35c6145 | 2016-02-26 15:24:57 +0000 | [diff] [blame] | 525 | print_text.append('To see results here, run: git cl try-results') |
| 526 | print_text.append('To see results in browser, run: git cl web') |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 527 | print('\n'.join(print_text)) |
kjellander@chromium.org | 4442454 | 2015-06-02 18:35:29 +0000 | [diff] [blame] | 528 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 529 | |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 530 | def fetch_try_jobs(auth_config, changelist, buildbucket_host, |
| 531 | patchset=None): |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 532 | """Fetches try jobs from buildbucket. |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 533 | |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 534 | Returns a map from build id to build info as a dictionary. |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 535 | """ |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 536 | assert buildbucket_host |
| 537 | assert changelist.GetIssue(), 'CL must be uploaded first' |
| 538 | assert changelist.GetCodereviewServer(), 'CL must be uploaded first' |
| 539 | patchset = patchset or changelist.GetMostRecentPatchset() |
| 540 | assert patchset, 'CL must be uploaded first' |
| 541 | |
| 542 | codereview_url = changelist.GetCodereviewServer() |
| 543 | codereview_host = urlparse.urlparse(codereview_url).hostname |
| 544 | authenticator = auth.get_authenticator_for_host(codereview_host, auth_config) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 545 | if authenticator.has_cached_credentials(): |
| 546 | http = authenticator.authorize(httplib2.Http()) |
| 547 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 548 | print('Warning: Some results might be missing because %s' % |
| 549 | # Get the message on how to login. |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 550 | (auth.LoginRequiredError(codereview_host).message,)) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 551 | http = httplib2.Http() |
| 552 | |
| 553 | http.force_exception_to_status_code = True |
| 554 | |
Andrii Shyshkalov | 03da150 | 2018-10-15 03:42:34 +0000 | [diff] [blame] | 555 | buildset = 'patch/gerrit/{hostname}/{issue}/{patch}'.format( |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 556 | hostname=codereview_host, |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 557 | issue=changelist.GetIssue(), |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 558 | patch=patchset) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 559 | params = {'tag': 'buildset:%s' % buildset} |
| 560 | |
| 561 | builds = {} |
| 562 | while True: |
| 563 | url = 'https://{hostname}/_ah/api/buildbucket/v1/search?{params}'.format( |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 564 | hostname=buildbucket_host, |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 565 | params=urllib.urlencode(params)) |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 566 | content = _buildbucket_retry('fetching try jobs', http, url, 'GET') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 567 | for build in content.get('builds', []): |
| 568 | builds[build['id']] = build |
| 569 | if 'next_cursor' in content: |
| 570 | params['start_cursor'] = content['next_cursor'] |
| 571 | else: |
| 572 | break |
| 573 | return builds |
| 574 | |
| 575 | |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 576 | def print_try_jobs(options, builds): |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 577 | """Prints nicely result of fetch_try_jobs.""" |
| 578 | if not builds: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 579 | print('No try jobs scheduled.') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 580 | return |
| 581 | |
| 582 | # Make a copy, because we'll be modifying builds dictionary. |
| 583 | builds = builds.copy() |
| 584 | builder_names_cache = {} |
| 585 | |
| 586 | def get_builder(b): |
| 587 | try: |
| 588 | return builder_names_cache[b['id']] |
| 589 | except KeyError: |
| 590 | try: |
| 591 | parameters = json.loads(b['parameters_json']) |
| 592 | name = parameters['builder_name'] |
| 593 | except (ValueError, KeyError) as error: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 594 | print('WARNING: Failed to get builder name for build %s: %s' % ( |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 595 | b['id'], error)) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 596 | name = None |
| 597 | builder_names_cache[b['id']] = name |
| 598 | return name |
| 599 | |
| 600 | def get_bucket(b): |
| 601 | bucket = b['bucket'] |
| 602 | if bucket.startswith('master.'): |
| 603 | return bucket[len('master.'):] |
| 604 | return bucket |
| 605 | |
| 606 | if options.print_master: |
| 607 | name_fmt = '%%-%ds %%-%ds' % ( |
| 608 | max(len(str(get_bucket(b))) for b in builds.itervalues()), |
| 609 | max(len(str(get_builder(b))) for b in builds.itervalues())) |
| 610 | def get_name(b): |
| 611 | return name_fmt % (get_bucket(b), get_builder(b)) |
| 612 | else: |
| 613 | name_fmt = '%%-%ds' % ( |
| 614 | max(len(str(get_builder(b))) for b in builds.itervalues())) |
| 615 | def get_name(b): |
| 616 | return name_fmt % get_builder(b) |
| 617 | |
| 618 | def sort_key(b): |
| 619 | return b['status'], b.get('result'), get_name(b), b.get('url') |
| 620 | |
| 621 | def pop(title, f, color=None, **kwargs): |
| 622 | """Pop matching builds from `builds` dict and print them.""" |
| 623 | |
tandrii@chromium.org | 6cf98c8 | 2016-03-15 11:56:00 +0000 | [diff] [blame] | 624 | if not options.color or color is None: |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 625 | colorize = str |
| 626 | else: |
| 627 | colorize = lambda x: '%s%s%s' % (color, x, Fore.RESET) |
| 628 | |
| 629 | result = [] |
| 630 | for b in builds.values(): |
| 631 | if all(b.get(k) == v for k, v in kwargs.iteritems()): |
| 632 | builds.pop(b['id']) |
| 633 | result.append(b) |
| 634 | if result: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 635 | print(colorize(title)) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 636 | for b in sorted(result, key=sort_key): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 637 | print(' ', colorize('\t'.join(map(str, f(b))))) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 638 | |
| 639 | total = len(builds) |
| 640 | pop(status='COMPLETED', result='SUCCESS', |
| 641 | title='Successes:', color=Fore.GREEN, |
| 642 | f=lambda b: (get_name(b), b.get('url'))) |
| 643 | pop(status='COMPLETED', result='FAILURE', failure_reason='INFRA_FAILURE', |
| 644 | title='Infra Failures:', color=Fore.MAGENTA, |
| 645 | f=lambda b: (get_name(b), b.get('url'))) |
| 646 | pop(status='COMPLETED', result='FAILURE', failure_reason='BUILD_FAILURE', |
| 647 | title='Failures:', color=Fore.RED, |
| 648 | f=lambda b: (get_name(b), b.get('url'))) |
| 649 | pop(status='COMPLETED', result='CANCELED', |
| 650 | title='Canceled:', color=Fore.MAGENTA, |
| 651 | f=lambda b: (get_name(b),)) |
| 652 | pop(status='COMPLETED', result='FAILURE', |
| 653 | failure_reason='INVALID_BUILD_DEFINITION', |
| 654 | title='Wrong master/builder name:', color=Fore.MAGENTA, |
| 655 | f=lambda b: (get_name(b),)) |
| 656 | pop(status='COMPLETED', result='FAILURE', |
| 657 | title='Other failures:', |
| 658 | f=lambda b: (get_name(b), b.get('failure_reason'), b.get('url'))) |
| 659 | pop(status='COMPLETED', |
| 660 | title='Other finished:', |
| 661 | f=lambda b: (get_name(b), b.get('result'), b.get('url'))) |
| 662 | pop(status='STARTED', |
| 663 | title='Started:', color=Fore.YELLOW, |
| 664 | f=lambda b: (get_name(b), b.get('url'))) |
| 665 | pop(status='SCHEDULED', |
| 666 | title='Scheduled:', |
| 667 | f=lambda b: (get_name(b), 'id=%s' % b['id'])) |
| 668 | # The last section is just in case buildbucket API changes OR there is a bug. |
| 669 | pop(title='Other:', |
| 670 | f=lambda b: (get_name(b), 'id=%s' % b['id'])) |
| 671 | assert len(builds) == 0 |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 672 | print('Total: %d try jobs' % total) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 673 | |
| 674 | |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 675 | def _ComputeDiffLineRanges(files, upstream_commit): |
| 676 | """Gets the changed line ranges for each file since upstream_commit. |
| 677 | |
| 678 | Parses a git diff on provided files and returns a dict that maps a file name |
| 679 | to an ordered list of range tuples in the form (start_line, count). |
| 680 | Ranges are in the same format as a git diff. |
| 681 | """ |
| 682 | # If files is empty then diff_output will be a full diff. |
| 683 | if len(files) == 0: |
| 684 | return {} |
| 685 | |
| 686 | # Take diff and find the line ranges where there are changes. |
| 687 | diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, files, allow_prefix=True) |
| 688 | diff_output = RunGit(diff_cmd) |
| 689 | |
| 690 | pattern = r'(?:^diff --git a/(?:.*) b/(.*))|(?:^@@.*\+(.*) @@)' |
| 691 | # 2 capture groups |
| 692 | # 0 == fname of diff file |
| 693 | # 1 == 'diff_start,diff_count' or 'diff_start' |
| 694 | # will match each of |
| 695 | # diff --git a/foo.foo b/foo.py |
| 696 | # @@ -12,2 +14,3 @@ |
| 697 | # @@ -12,2 +17 @@ |
| 698 | # running re.findall on the above string with pattern will give |
| 699 | # [('foo.py', ''), ('', '14,3'), ('', '17')] |
| 700 | |
| 701 | curr_file = None |
| 702 | line_diffs = {} |
| 703 | for match in re.findall(pattern, diff_output, flags=re.MULTILINE): |
| 704 | if match[0] != '': |
| 705 | # Will match the second filename in diff --git a/a.py b/b.py. |
| 706 | curr_file = match[0] |
| 707 | line_diffs[curr_file] = [] |
| 708 | else: |
| 709 | # Matches +14,3 |
| 710 | if ',' in match[1]: |
| 711 | diff_start, diff_count = match[1].split(',') |
| 712 | else: |
| 713 | # Single line changes are of the form +12 instead of +12,1. |
| 714 | diff_start = match[1] |
| 715 | diff_count = 1 |
| 716 | |
| 717 | diff_start = int(diff_start) |
| 718 | diff_count = int(diff_count) |
| 719 | |
| 720 | # If diff_count == 0 this is a removal we can ignore. |
| 721 | line_diffs[curr_file].append((diff_start, diff_count)) |
| 722 | |
| 723 | return line_diffs |
| 724 | |
| 725 | |
| 726 | def _FindYapfConfigFile(fpath, |
| 727 | yapf_config_cache, |
| 728 | top_dir=None, |
| 729 | default_style=None): |
| 730 | """Checks if a yapf file is in any parent directory of fpath until top_dir. |
| 731 | |
| 732 | Recursively checks parent directories to find yapf file |
| 733 | and if no yapf file is found returns default_style. |
| 734 | Uses yapf_config_cache as a cache for previously found files. |
| 735 | """ |
| 736 | # Return result if we've already computed it. |
| 737 | if fpath in yapf_config_cache: |
| 738 | return yapf_config_cache[fpath] |
| 739 | |
| 740 | # Check if there is a style file in the current directory. |
| 741 | yapf_file = os.path.join(fpath, YAPF_CONFIG_FILENAME) |
| 742 | dirname = os.path.dirname(fpath) |
| 743 | if os.path.isfile(yapf_file): |
| 744 | ret = yapf_file |
| 745 | elif fpath == top_dir or dirname == fpath: |
| 746 | # If we're at the top level directory, or if we're at root |
| 747 | # use the chromium default yapf style. |
| 748 | ret = default_style |
| 749 | else: |
| 750 | # Otherwise recurse on the current directory. |
| 751 | ret = _FindYapfConfigFile(dirname, yapf_config_cache, top_dir, |
| 752 | default_style) |
| 753 | yapf_config_cache[fpath] = ret |
| 754 | return ret |
| 755 | |
| 756 | |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 757 | def write_try_results_json(output_file, builds): |
| 758 | """Writes a subset of the data from fetch_try_jobs to a file as JSON. |
| 759 | |
| 760 | The input |builds| dict is assumed to be generated by Buildbucket. |
| 761 | Buildbucket documentation: http://goo.gl/G0s101 |
| 762 | """ |
| 763 | |
| 764 | def convert_build_dict(build): |
Quinten Yearsley | a563d72 | 2017-12-11 16:36:54 -0800 | [diff] [blame] | 765 | """Extracts some of the information from one build dict.""" |
| 766 | parameters = json.loads(build.get('parameters_json', '{}')) or {} |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 767 | return { |
| 768 | 'buildbucket_id': build.get('id'), |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 769 | 'bucket': build.get('bucket'), |
Quinten Yearsley | a563d72 | 2017-12-11 16:36:54 -0800 | [diff] [blame] | 770 | 'builder_name': parameters.get('builder_name'), |
| 771 | 'created_ts': build.get('created_ts'), |
| 772 | 'experimental': build.get('experimental'), |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 773 | 'failure_reason': build.get('failure_reason'), |
Quinten Yearsley | a563d72 | 2017-12-11 16:36:54 -0800 | [diff] [blame] | 774 | 'result': build.get('result'), |
| 775 | 'status': build.get('status'), |
| 776 | 'tags': build.get('tags'), |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 777 | 'url': build.get('url'), |
| 778 | } |
| 779 | |
| 780 | converted = [] |
| 781 | for _, build in sorted(builds.items()): |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 782 | converted.append(convert_build_dict(build)) |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 783 | write_json(output_file, converted) |
| 784 | |
| 785 | |
Aaron Gable | 13101a6 | 2018-02-09 13:20:41 -0800 | [diff] [blame] | 786 | def print_stats(args): |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 787 | """Prints statistics about the change to the user.""" |
| 788 | # --no-ext-diff is broken in some versions of Git, so try to work around |
| 789 | # this by overriding the environment (but there is still a problem if the |
| 790 | # git config key "diff.external" is used). |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 791 | env = GetNoGitPagerEnv() |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 792 | if 'GIT_EXTERNAL_DIFF' in env: |
| 793 | del env['GIT_EXTERNAL_DIFF'] |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 794 | |
szager@chromium.org | d057f9a | 2014-05-29 21:09:36 +0000 | [diff] [blame] | 795 | try: |
| 796 | stdout = sys.stdout.fileno() |
| 797 | except AttributeError: |
| 798 | stdout = None |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 799 | return subprocess2.call( |
Aaron Gable | 13101a6 | 2018-02-09 13:20:41 -0800 | [diff] [blame] | 800 | ['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] + args, |
szager@chromium.org | d057f9a | 2014-05-29 21:09:36 +0000 | [diff] [blame] | 801 | stdout=stdout, env=env) |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 802 | |
| 803 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 804 | class BuildbucketResponseException(Exception): |
| 805 | pass |
| 806 | |
| 807 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 808 | class Settings(object): |
| 809 | def __init__(self): |
| 810 | self.default_server = None |
| 811 | self.cc = None |
thestig@chromium.org | 7a54e81 | 2014-02-11 19:57:22 +0000 | [diff] [blame] | 812 | self.root = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 813 | self.tree_status_url = None |
| 814 | self.viewvc_url = None |
| 815 | self.updated = False |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 816 | self.is_gerrit = None |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 817 | self.squash_gerrit_uploads = None |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 818 | self.gerrit_skip_ensure_authenticated = None |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 819 | self.git_editor = None |
sheyang@chromium.org | 152cf83 | 2014-06-11 21:37:49 +0000 | [diff] [blame] | 820 | self.project = None |
kjellander@chromium.org | 6abc652 | 2014-12-02 07:34:49 +0000 | [diff] [blame] | 821 | self.force_https_commit_url = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 822 | |
| 823 | def LazyUpdateIfNeeded(self): |
| 824 | """Updates the settings from a codereview.settings file, if available.""" |
| 825 | if not self.updated: |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 826 | # The only value that actually changes the behavior is |
| 827 | # autoupdate = "false". Everything else means "true". |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 828 | autoupdate = RunGit(['config', 'rietveld.autoupdate'], |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 829 | error_ok=True |
| 830 | ).strip().lower() |
| 831 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 832 | cr_settings_file = FindCodereviewSettingsFile() |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 833 | if autoupdate != 'false' and cr_settings_file: |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 834 | LoadCodereviewSettingsFromFile(cr_settings_file) |
| 835 | self.updated = True |
| 836 | |
| 837 | def GetDefaultServerUrl(self, error_ok=False): |
| 838 | if not self.default_server: |
| 839 | self.LazyUpdateIfNeeded() |
maruel@chromium.org | eb5edbc | 2012-01-16 17:03:28 +0000 | [diff] [blame] | 840 | self.default_server = gclient_utils.UpgradeToHttps( |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 841 | self._GetRietveldConfig('server', error_ok=True)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 842 | if error_ok: |
| 843 | return self.default_server |
| 844 | if not self.default_server: |
| 845 | error_message = ('Could not find settings file. You must configure ' |
| 846 | 'your review setup by running "git cl config".') |
maruel@chromium.org | eb5edbc | 2012-01-16 17:03:28 +0000 | [diff] [blame] | 847 | self.default_server = gclient_utils.UpgradeToHttps( |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 848 | self._GetRietveldConfig('server', error_message=error_message)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 849 | return self.default_server |
| 850 | |
thestig@chromium.org | 7a54e81 | 2014-02-11 19:57:22 +0000 | [diff] [blame] | 851 | @staticmethod |
| 852 | def GetRelativeRoot(): |
| 853 | return RunGit(['rev-parse', '--show-cdup']).strip() |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 854 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 855 | def GetRoot(self): |
thestig@chromium.org | 7a54e81 | 2014-02-11 19:57:22 +0000 | [diff] [blame] | 856 | if self.root is None: |
| 857 | self.root = os.path.abspath(self.GetRelativeRoot()) |
| 858 | return self.root |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 859 | |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 860 | def GetGitMirror(self, remote='origin'): |
| 861 | """If this checkout is from a local git mirror, return a Mirror object.""" |
szager@chromium.org | 8159374 | 2016-03-09 20:27:58 +0000 | [diff] [blame] | 862 | local_url = RunGit(['config', '--get', 'remote.%s.url' % remote]).strip() |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 863 | if not os.path.isdir(local_url): |
| 864 | return None |
| 865 | git_cache.Mirror.SetCachePath(os.path.dirname(local_url)) |
| 866 | remote_url = git_cache.Mirror.CacheDirToUrl(local_url) |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 867 | # Use the /dev/null print_func to avoid terminal spew. |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 868 | mirror = git_cache.Mirror(remote_url, print_func=lambda *args: None) |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 869 | if mirror.exists(): |
| 870 | return mirror |
| 871 | return None |
| 872 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 873 | def GetTreeStatusUrl(self, error_ok=False): |
| 874 | if not self.tree_status_url: |
| 875 | error_message = ('You must configure your tree status URL by running ' |
| 876 | '"git cl config".') |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 877 | self.tree_status_url = self._GetRietveldConfig( |
| 878 | 'tree-status-url', error_ok=error_ok, error_message=error_message) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 879 | return self.tree_status_url |
| 880 | |
| 881 | def GetViewVCUrl(self): |
| 882 | if not self.viewvc_url: |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 883 | self.viewvc_url = self._GetRietveldConfig('viewvc-url', error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 884 | return self.viewvc_url |
| 885 | |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 886 | def GetBugPrefix(self): |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 887 | return self._GetRietveldConfig('bug-prefix', error_ok=True) |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 888 | |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 889 | def GetIsSkipDependencyUpload(self, branch_name): |
| 890 | """Returns true if specified branch should skip dep uploads.""" |
| 891 | return self._GetBranchConfig(branch_name, 'skip-deps-uploads', |
| 892 | error_ok=True) |
| 893 | |
rmistry@google.com | 5626a92 | 2015-02-26 14:03:30 +0000 | [diff] [blame] | 894 | def GetRunPostUploadHook(self): |
| 895 | run_post_upload_hook = self._GetRietveldConfig( |
| 896 | 'run-post-upload-hook', error_ok=True) |
| 897 | return run_post_upload_hook == "True" |
| 898 | |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 899 | def GetDefaultCCList(self): |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 900 | return self._GetRietveldConfig('cc', error_ok=True) |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 901 | |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 902 | def GetDefaultPrivateFlag(self): |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 903 | return self._GetRietveldConfig('private', error_ok=True) |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 904 | |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 905 | def GetIsGerrit(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 906 | """Return true if this repo is associated with gerrit code review system.""" |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 907 | if self.is_gerrit is None: |
Aaron Gable | 9b46527 | 2017-05-12 10:53:51 -0700 | [diff] [blame] | 908 | self.is_gerrit = ( |
| 909 | self._GetConfig('gerrit.host', error_ok=True).lower() == 'true') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 910 | return self.is_gerrit |
| 911 | |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 912 | def GetSquashGerritUploads(self): |
| 913 | """Return true if uploads to Gerrit should be squashed by default.""" |
| 914 | if self.squash_gerrit_uploads is None: |
tandrii | a60502f | 2016-06-20 02:01:53 -0700 | [diff] [blame] | 915 | self.squash_gerrit_uploads = self.GetSquashGerritUploadsOverride() |
| 916 | if self.squash_gerrit_uploads is None: |
| 917 | # Default is squash now (http://crbug.com/611892#c23). |
| 918 | self.squash_gerrit_uploads = not ( |
| 919 | RunGit(['config', '--bool', 'gerrit.squash-uploads'], |
| 920 | error_ok=True).strip() == 'false') |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 921 | return self.squash_gerrit_uploads |
| 922 | |
tandrii | a60502f | 2016-06-20 02:01:53 -0700 | [diff] [blame] | 923 | def GetSquashGerritUploadsOverride(self): |
| 924 | """Return True or False if codereview.settings should be overridden. |
| 925 | |
| 926 | Returns None if no override has been defined. |
| 927 | """ |
| 928 | # See also http://crbug.com/611892#c23 |
| 929 | result = RunGit(['config', '--bool', 'gerrit.override-squash-uploads'], |
| 930 | error_ok=True).strip() |
| 931 | if result == 'true': |
| 932 | return True |
| 933 | if result == 'false': |
| 934 | return False |
| 935 | return None |
| 936 | |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 937 | def GetGerritSkipEnsureAuthenticated(self): |
| 938 | """Return True if EnsureAuthenticated should not be done for Gerrit |
| 939 | uploads.""" |
| 940 | if self.gerrit_skip_ensure_authenticated is None: |
| 941 | self.gerrit_skip_ensure_authenticated = ( |
shinyak@chromium.org | 00dbccd | 2016-04-15 07:24:43 +0000 | [diff] [blame] | 942 | RunGit(['config', '--bool', 'gerrit.skip-ensure-authenticated'], |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 943 | error_ok=True).strip() == 'true') |
| 944 | return self.gerrit_skip_ensure_authenticated |
| 945 | |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 946 | def GetGitEditor(self): |
| 947 | """Return the editor specified in the git config, or None if none is.""" |
| 948 | if self.git_editor is None: |
| 949 | self.git_editor = self._GetConfig('core.editor', error_ok=True) |
| 950 | return self.git_editor or None |
| 951 | |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 952 | def GetLintRegex(self): |
| 953 | return (self._GetRietveldConfig('cpplint-regex', error_ok=True) or |
| 954 | DEFAULT_LINT_REGEX) |
| 955 | |
| 956 | def GetLintIgnoreRegex(self): |
| 957 | return (self._GetRietveldConfig('cpplint-ignore-regex', error_ok=True) or |
| 958 | DEFAULT_LINT_IGNORE_REGEX) |
| 959 | |
sheyang@chromium.org | 152cf83 | 2014-06-11 21:37:49 +0000 | [diff] [blame] | 960 | def GetProject(self): |
| 961 | if not self.project: |
| 962 | self.project = self._GetRietveldConfig('project', error_ok=True) |
| 963 | return self.project |
| 964 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 965 | def _GetRietveldConfig(self, param, **kwargs): |
| 966 | return self._GetConfig('rietveld.' + param, **kwargs) |
| 967 | |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 968 | def _GetBranchConfig(self, branch_name, param, **kwargs): |
| 969 | return self._GetConfig('branch.' + branch_name + '.' + param, **kwargs) |
| 970 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 971 | def _GetConfig(self, param, **kwargs): |
| 972 | self.LazyUpdateIfNeeded() |
| 973 | return RunGit(['config', param], **kwargs).strip() |
| 974 | |
| 975 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 976 | @contextlib.contextmanager |
| 977 | def _get_gerrit_project_config_file(remote_url): |
| 978 | """Context manager to fetch and store Gerrit's project.config from |
| 979 | refs/meta/config branch and store it in temp file. |
| 980 | |
| 981 | Provides a temporary filename or None if there was error. |
| 982 | """ |
| 983 | error, _ = RunGitWithCode([ |
| 984 | 'fetch', remote_url, |
| 985 | '+refs/meta/config:refs/git_cl/meta/config']) |
| 986 | if error: |
| 987 | # Ref doesn't exist or isn't accessible to current user. |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 988 | print('WARNING: Failed to fetch project config for %s: %s' % |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 989 | (remote_url, error)) |
| 990 | yield None |
| 991 | return |
| 992 | |
| 993 | error, project_config_data = RunGitWithCode( |
| 994 | ['show', 'refs/git_cl/meta/config:project.config']) |
| 995 | if error: |
| 996 | print('WARNING: project.config file not found') |
| 997 | yield None |
| 998 | return |
| 999 | |
| 1000 | with gclient_utils.temporary_directory() as tempdir: |
| 1001 | project_config_file = os.path.join(tempdir, 'project.config') |
| 1002 | gclient_utils.FileWrite(project_config_file, project_config_data) |
| 1003 | yield project_config_file |
| 1004 | |
| 1005 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1006 | def ShortBranchName(branch): |
| 1007 | """Convert a name like 'refs/heads/foo' to just 'foo'.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1008 | return branch.replace('refs/heads/', '', 1) |
| 1009 | |
| 1010 | |
| 1011 | def GetCurrentBranchRef(): |
| 1012 | """Returns branch ref (e.g., refs/heads/master) or None.""" |
| 1013 | return RunGit(['symbolic-ref', 'HEAD'], |
| 1014 | stderr=subprocess2.VOID, error_ok=True).strip() or None |
| 1015 | |
| 1016 | |
| 1017 | def GetCurrentBranch(): |
| 1018 | """Returns current branch or None. |
| 1019 | |
| 1020 | For refs/heads/* branches, returns just last part. For others, full ref. |
| 1021 | """ |
| 1022 | branchref = GetCurrentBranchRef() |
| 1023 | if branchref: |
| 1024 | return ShortBranchName(branchref) |
| 1025 | return None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1026 | |
| 1027 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1028 | class _CQState(object): |
| 1029 | """Enum for states of CL with respect to Commit Queue.""" |
| 1030 | NONE = 'none' |
| 1031 | DRY_RUN = 'dry_run' |
| 1032 | COMMIT = 'commit' |
| 1033 | |
| 1034 | ALL_STATES = [NONE, DRY_RUN, COMMIT] |
| 1035 | |
| 1036 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1037 | class _ParsedIssueNumberArgument(object): |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 1038 | def __init__(self, issue=None, patchset=None, hostname=None, codereview=None): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1039 | self.issue = issue |
| 1040 | self.patchset = patchset |
| 1041 | self.hostname = hostname |
Andrii Shyshkalov | f5569d2 | 2018-10-15 03:35:23 +0000 | [diff] [blame] | 1042 | assert codereview in (None, 'gerrit', 'rietveld') |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 1043 | self.codereview = codereview |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1044 | |
| 1045 | @property |
| 1046 | def valid(self): |
| 1047 | return self.issue is not None |
| 1048 | |
| 1049 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 1050 | def ParseIssueNumberArgument(arg, codereview=None): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1051 | """Parses the issue argument and returns _ParsedIssueNumberArgument.""" |
| 1052 | fail_result = _ParsedIssueNumberArgument() |
| 1053 | |
| 1054 | if arg.isdigit(): |
Aaron Gable | aee6c85 | 2017-06-26 12:49:01 -0700 | [diff] [blame] | 1055 | return _ParsedIssueNumberArgument(issue=int(arg), codereview=codereview) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1056 | if not arg.startswith('http'): |
| 1057 | return fail_result |
Aaron Gable | aee6c85 | 2017-06-26 12:49:01 -0700 | [diff] [blame] | 1058 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1059 | url = gclient_utils.UpgradeToHttps(arg) |
| 1060 | try: |
| 1061 | parsed_url = urlparse.urlparse(url) |
| 1062 | except ValueError: |
| 1063 | return fail_result |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 1064 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 1065 | if codereview is not None: |
| 1066 | parsed = _CODEREVIEW_IMPLEMENTATIONS[codereview].ParseIssueURL(parsed_url) |
| 1067 | return parsed or fail_result |
| 1068 | |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 1069 | results = {} |
| 1070 | for name, cls in _CODEREVIEW_IMPLEMENTATIONS.iteritems(): |
| 1071 | parsed = cls.ParseIssueURL(parsed_url) |
| 1072 | if parsed is not None: |
| 1073 | results[name] = parsed |
| 1074 | |
| 1075 | if not results: |
| 1076 | return fail_result |
| 1077 | if len(results) == 1: |
| 1078 | return results.values()[0] |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 1079 | |
Andrii Shyshkalov | f5569d2 | 2018-10-15 03:35:23 +0000 | [diff] [blame] | 1080 | return results['gerrit'] |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1081 | |
| 1082 | |
Andrii Shyshkalov | b07575f | 2018-10-16 06:16:21 +0000 | [diff] [blame] | 1083 | def _create_description_from_log(args): |
| 1084 | """Pulls out the commit log to use as a base for the CL description.""" |
| 1085 | log_args = [] |
| 1086 | if len(args) == 1 and not args[0].endswith('.'): |
| 1087 | log_args = [args[0] + '..'] |
| 1088 | elif len(args) == 1 and args[0].endswith('...'): |
| 1089 | log_args = [args[0][:-1]] |
| 1090 | elif len(args) == 2: |
| 1091 | log_args = [args[0] + '..' + args[1]] |
| 1092 | else: |
| 1093 | log_args = args[:] # Hope for the best! |
| 1094 | return RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args) |
| 1095 | |
| 1096 | |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 1097 | class GerritChangeNotExists(Exception): |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 1098 | def __init__(self, issue, url): |
| 1099 | self.issue = issue |
| 1100 | self.url = url |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 1101 | super(GerritChangeNotExists, self).__init__() |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 1102 | |
| 1103 | def __str__(self): |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 1104 | return 'change %s at %s does not exist or you have no access to it' % ( |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 1105 | self.issue, self.url) |
| 1106 | |
| 1107 | |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1108 | _CommentSummary = collections.namedtuple( |
| 1109 | '_CommentSummary', ['date', 'message', 'sender', |
| 1110 | # TODO(tandrii): these two aren't known in Gerrit. |
| 1111 | 'approval', 'disapproval']) |
| 1112 | |
| 1113 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1114 | class Changelist(object): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1115 | """Changelist works with one changelist in local branch. |
| 1116 | |
| 1117 | Supports two codereview backends: Rietveld or Gerrit, selected at object |
| 1118 | creation. |
| 1119 | |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 1120 | Notes: |
| 1121 | * Not safe for concurrent multi-{thread,process} use. |
| 1122 | * Caches values from current branch. Therefore, re-use after branch change |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1123 | with great care. |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1124 | """ |
| 1125 | |
| 1126 | def __init__(self, branchref=None, issue=None, codereview=None, **kwargs): |
| 1127 | """Create a new ChangeList instance. |
| 1128 | |
| 1129 | If issue is given, the codereview must be given too. |
| 1130 | |
| 1131 | If `codereview` is given, it must be 'rietveld' or 'gerrit'. |
| 1132 | Otherwise, it's decided based on current configuration of the local branch, |
| 1133 | with default being 'rietveld' for backwards compatibility. |
| 1134 | See _load_codereview_impl for more details. |
| 1135 | |
| 1136 | **kwargs will be passed directly to codereview implementation. |
| 1137 | """ |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1138 | # Poke settings so we get the "configure your server" message if necessary. |
maruel@chromium.org | 379d07a | 2011-11-30 14:58:10 +0000 | [diff] [blame] | 1139 | global settings |
| 1140 | if not settings: |
| 1141 | # Happens when git_cl.py is used as a utility library. |
| 1142 | settings = Settings() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1143 | |
| 1144 | if issue: |
| 1145 | assert codereview, 'codereview must be known, if issue is known' |
| 1146 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1147 | self.branchref = branchref |
| 1148 | if self.branchref: |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 1149 | assert branchref.startswith('refs/heads/') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1150 | self.branch = ShortBranchName(self.branchref) |
| 1151 | else: |
| 1152 | self.branch = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1153 | self.upstream_branch = None |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1154 | self.lookedup_issue = False |
| 1155 | self.issue = issue or None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1156 | self.has_description = False |
| 1157 | self.description = None |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1158 | self.lookedup_patchset = False |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1159 | self.patchset = None |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1160 | self.cc = None |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1161 | self.more_cc = [] |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 1162 | self._remote = None |
Andrii Shyshkalov | 81db1d5 | 2018-08-23 02:17:41 +0000 | [diff] [blame] | 1163 | self._cached_remote_url = (False, None) # (is_cached, value) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 1164 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1165 | self._codereview_impl = None |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 1166 | self._codereview = None |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1167 | self._load_codereview_impl(codereview, **kwargs) |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 1168 | assert self._codereview_impl |
| 1169 | assert self._codereview in _CODEREVIEW_IMPLEMENTATIONS |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1170 | |
| 1171 | def _load_codereview_impl(self, codereview=None, **kwargs): |
| 1172 | if codereview: |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 1173 | assert codereview in _CODEREVIEW_IMPLEMENTATIONS |
| 1174 | cls = _CODEREVIEW_IMPLEMENTATIONS[codereview] |
| 1175 | self._codereview = codereview |
| 1176 | self._codereview_impl = cls(self, **kwargs) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1177 | return |
| 1178 | |
| 1179 | # Automatic selection based on issue number set for a current branch. |
| 1180 | # Rietveld takes precedence over Gerrit. |
| 1181 | assert not self.issue |
| 1182 | # Whether we find issue or not, we are doing the lookup. |
| 1183 | self.lookedup_issue = True |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1184 | if self.GetBranch(): |
| 1185 | for codereview, cls in _CODEREVIEW_IMPLEMENTATIONS.iteritems(): |
| 1186 | issue = _git_get_branch_config_value( |
| 1187 | cls.IssueConfigKey(), value_type=int, branch=self.GetBranch()) |
| 1188 | if issue: |
| 1189 | self._codereview = codereview |
| 1190 | self._codereview_impl = cls(self, **kwargs) |
| 1191 | self.issue = int(issue) |
| 1192 | return |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1193 | |
| 1194 | # No issue is set for this branch, so decide based on repo-wide settings. |
| 1195 | return self._load_codereview_impl( |
| 1196 | codereview='gerrit' if settings.GetIsGerrit() else 'rietveld', |
| 1197 | **kwargs) |
| 1198 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 1199 | def IsGerrit(self): |
| 1200 | return self._codereview == 'gerrit' |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1201 | |
| 1202 | def GetCCList(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1203 | """Returns the users cc'd on this CL. |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1204 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1205 | The return value is a string suitable for passing to git cl with the --cc |
| 1206 | flag. |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1207 | """ |
| 1208 | if self.cc is None: |
tyoshino@chromium.org | 99918ab | 2013-09-30 06:17:28 +0000 | [diff] [blame] | 1209 | base_cc = settings.GetDefaultCCList() |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1210 | more_cc = ','.join(self.more_cc) |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1211 | self.cc = ','.join(filter(None, (base_cc, more_cc))) or '' |
| 1212 | return self.cc |
| 1213 | |
tyoshino@chromium.org | 99918ab | 2013-09-30 06:17:28 +0000 | [diff] [blame] | 1214 | def GetCCListWithoutDefault(self): |
| 1215 | """Return the users cc'd on this CL excluding default ones.""" |
| 1216 | if self.cc is None: |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1217 | self.cc = ','.join(self.more_cc) |
tyoshino@chromium.org | 99918ab | 2013-09-30 06:17:28 +0000 | [diff] [blame] | 1218 | return self.cc |
| 1219 | |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1220 | def ExtendCC(self, more_cc): |
| 1221 | """Extends the list of users to cc on this CL based on the changed files.""" |
| 1222 | self.more_cc.extend(more_cc) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1223 | |
| 1224 | def GetBranch(self): |
| 1225 | """Returns the short branch name, e.g. 'master'.""" |
| 1226 | if not self.branch: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1227 | branchref = GetCurrentBranchRef() |
szager@chromium.org | d62c61f | 2014-10-20 22:33:21 +0000 | [diff] [blame] | 1228 | if not branchref: |
| 1229 | return None |
| 1230 | self.branchref = branchref |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1231 | self.branch = ShortBranchName(self.branchref) |
| 1232 | return self.branch |
| 1233 | |
| 1234 | def GetBranchRef(self): |
| 1235 | """Returns the full branch name, e.g. 'refs/heads/master'.""" |
| 1236 | self.GetBranch() # Poke the lazy loader. |
| 1237 | return self.branchref |
| 1238 | |
tandrii@chromium.org | 534f67a | 2016-04-07 18:47:05 +0000 | [diff] [blame] | 1239 | def ClearBranch(self): |
| 1240 | """Clears cached branch data of this object.""" |
| 1241 | self.branch = self.branchref = None |
| 1242 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1243 | def _GitGetBranchConfigValue(self, key, default=None, **kwargs): |
| 1244 | assert 'branch' not in kwargs, 'this CL branch is used automatically' |
| 1245 | kwargs['branch'] = self.GetBranch() |
| 1246 | return _git_get_branch_config_value(key, default, **kwargs) |
| 1247 | |
| 1248 | def _GitSetBranchConfigValue(self, key, value, **kwargs): |
| 1249 | assert 'branch' not in kwargs, 'this CL branch is used automatically' |
| 1250 | assert self.GetBranch(), ( |
| 1251 | 'this CL must have an associated branch to %sset %s%s' % |
| 1252 | ('un' if value is None else '', |
| 1253 | key, |
| 1254 | '' if value is None else ' to %r' % value)) |
| 1255 | kwargs['branch'] = self.GetBranch() |
| 1256 | return _git_set_branch_config_value(key, value, **kwargs) |
| 1257 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1258 | @staticmethod |
| 1259 | def FetchUpstreamTuple(branch): |
pgervais@chromium.org | d6617f3 | 2013-11-19 00:34:54 +0000 | [diff] [blame] | 1260 | """Returns a tuple containing remote and remote ref, |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1261 | e.g. 'origin', 'refs/heads/master' |
| 1262 | """ |
| 1263 | remote = '.' |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1264 | upstream_branch = _git_get_branch_config_value('merge', branch=branch) |
| 1265 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1266 | if upstream_branch: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1267 | remote = _git_get_branch_config_value('remote', branch=branch) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1268 | else: |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 1269 | upstream_branch = RunGit(['config', 'rietveld.upstream-branch'], |
| 1270 | error_ok=True).strip() |
| 1271 | if upstream_branch: |
| 1272 | remote = RunGit(['config', 'rietveld.upstream-remote']).strip() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1273 | else: |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 1274 | # Else, try to guess the origin remote. |
| 1275 | remote_branches = RunGit(['branch', '-r']).split() |
| 1276 | if 'origin/master' in remote_branches: |
| 1277 | # Fall back on origin/master if it exits. |
| 1278 | remote = 'origin' |
| 1279 | upstream_branch = 'refs/heads/master' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1280 | else: |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 1281 | DieWithError( |
| 1282 | 'Unable to determine default branch to diff against.\n' |
| 1283 | 'Either pass complete "git diff"-style arguments, like\n' |
| 1284 | ' git cl upload origin/master\n' |
| 1285 | 'or verify this branch is set up to track another \n' |
| 1286 | '(via the --track argument to "git checkout -b ...").') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1287 | |
| 1288 | return remote, upstream_branch |
| 1289 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1290 | def GetCommonAncestorWithUpstream(self): |
pgervais@chromium.org | 8ba38ff | 2015-06-11 21:41:25 +0000 | [diff] [blame] | 1291 | upstream_branch = self.GetUpstreamBranch() |
| 1292 | if not BranchExists(upstream_branch): |
| 1293 | DieWithError('The upstream for the current branch (%s) does not exist ' |
| 1294 | 'anymore.\nPlease fix it and try again.' % self.GetBranch()) |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 1295 | return git_common.get_or_create_merge_base(self.GetBranch(), |
pgervais@chromium.org | 8ba38ff | 2015-06-11 21:41:25 +0000 | [diff] [blame] | 1296 | upstream_branch) |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1297 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1298 | def GetUpstreamBranch(self): |
| 1299 | if self.upstream_branch is None: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1300 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1301 | if remote is not '.': |
mmoss@chromium.org | e758545 | 2014-08-24 01:41:11 +0000 | [diff] [blame] | 1302 | upstream_branch = upstream_branch.replace('refs/heads/', |
| 1303 | 'refs/remotes/%s/' % remote) |
| 1304 | upstream_branch = upstream_branch.replace('refs/branch-heads/', |
| 1305 | 'refs/remotes/branch-heads/') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1306 | self.upstream_branch = upstream_branch |
| 1307 | return self.upstream_branch |
| 1308 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1309 | def GetRemoteBranch(self): |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1310 | if not self._remote: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1311 | remote, branch = None, self.GetBranch() |
| 1312 | seen_branches = set() |
| 1313 | while branch not in seen_branches: |
| 1314 | seen_branches.add(branch) |
| 1315 | remote, branch = self.FetchUpstreamTuple(branch) |
| 1316 | branch = ShortBranchName(branch) |
| 1317 | if remote != '.' or branch.startswith('refs/remotes'): |
| 1318 | break |
| 1319 | else: |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1320 | remotes = RunGit(['remote'], error_ok=True).split() |
| 1321 | if len(remotes) == 1: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1322 | remote, = remotes |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1323 | elif 'origin' in remotes: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1324 | remote = 'origin' |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 1325 | logging.warn('Could not determine which remote this change is ' |
| 1326 | 'associated with, so defaulting to "%s".' % self._remote) |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1327 | else: |
| 1328 | logging.warn('Could not determine which remote this change is ' |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 1329 | 'associated with.') |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1330 | branch = 'HEAD' |
| 1331 | if branch.startswith('refs/remotes'): |
| 1332 | self._remote = (remote, branch) |
mmoss@chromium.org | e758545 | 2014-08-24 01:41:11 +0000 | [diff] [blame] | 1333 | elif branch.startswith('refs/branch-heads/'): |
| 1334 | self._remote = (remote, branch.replace('refs/', 'refs/remotes/')) |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1335 | else: |
| 1336 | self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch)) |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1337 | return self._remote |
| 1338 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1339 | def GitSanityChecks(self, upstream_git_obj): |
| 1340 | """Checks git repo status and ensures diff is from local commits.""" |
| 1341 | |
sbc@chromium.org | 7970606 | 2015-01-14 21:18:12 +0000 | [diff] [blame] | 1342 | if upstream_git_obj is None: |
| 1343 | if self.GetBranch() is None: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1344 | print('ERROR: Unable to determine current branch (detached HEAD?)', |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1345 | file=sys.stderr) |
sbc@chromium.org | 7970606 | 2015-01-14 21:18:12 +0000 | [diff] [blame] | 1346 | else: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1347 | print('ERROR: No upstream branch.', file=sys.stderr) |
sbc@chromium.org | 7970606 | 2015-01-14 21:18:12 +0000 | [diff] [blame] | 1348 | return False |
| 1349 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1350 | # Verify the commit we're diffing against is in our current branch. |
| 1351 | upstream_sha = RunGit(['rev-parse', '--verify', upstream_git_obj]).strip() |
| 1352 | common_ancestor = RunGit(['merge-base', upstream_sha, 'HEAD']).strip() |
| 1353 | if upstream_sha != common_ancestor: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1354 | print('ERROR: %s is not in the current branch. You may need to rebase ' |
| 1355 | 'your tracking branch' % upstream_sha, file=sys.stderr) |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1356 | return False |
| 1357 | |
| 1358 | # List the commits inside the diff, and verify they are all local. |
| 1359 | commits_in_diff = RunGit( |
| 1360 | ['rev-list', '^%s' % upstream_sha, 'HEAD']).splitlines() |
| 1361 | code, remote_branch = RunGitWithCode(['config', 'gitcl.remotebranch']) |
| 1362 | remote_branch = remote_branch.strip() |
| 1363 | if code != 0: |
| 1364 | _, remote_branch = self.GetRemoteBranch() |
| 1365 | |
| 1366 | commits_in_remote = RunGit( |
| 1367 | ['rev-list', '^%s' % upstream_sha, remote_branch]).splitlines() |
| 1368 | |
| 1369 | common_commits = set(commits_in_diff) & set(commits_in_remote) |
| 1370 | if common_commits: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1371 | print('ERROR: Your diff contains %d commits already in %s.\n' |
| 1372 | 'Run "git log --oneline %s..HEAD" to get a list of commits in ' |
| 1373 | 'the diff. If you are using a custom git flow, you can override' |
| 1374 | ' the reference used for this check with "git config ' |
| 1375 | 'gitcl.remotebranch <git-ref>".' % ( |
| 1376 | len(common_commits), remote_branch, upstream_git_obj), |
| 1377 | file=sys.stderr) |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1378 | return False |
| 1379 | return True |
| 1380 | |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 1381 | def GetGitBaseUrlFromConfig(self): |
sheyang@chromium.org | a656e70 | 2014-05-15 20:43:05 +0000 | [diff] [blame] | 1382 | """Return the configured base URL from branch.<branchname>.baseurl. |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 1383 | |
| 1384 | Returns None if it is not set. |
| 1385 | """ |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1386 | return self._GitGetBranchConfigValue('base-url') |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1387 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1388 | def GetRemoteUrl(self): |
| 1389 | """Return the configured remote URL, e.g. 'git://example.org/foo.git/'. |
| 1390 | |
| 1391 | Returns None if there is no remote. |
| 1392 | """ |
Andrii Shyshkalov | 81db1d5 | 2018-08-23 02:17:41 +0000 | [diff] [blame] | 1393 | is_cached, value = self._cached_remote_url |
| 1394 | if is_cached: |
| 1395 | return value |
| 1396 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1397 | remote, _ = self.GetRemoteBranch() |
dyen@chromium.org | 2a13d4f | 2014-06-13 00:06:37 +0000 | [diff] [blame] | 1398 | url = RunGit(['config', 'remote.%s.url' % remote], error_ok=True).strip() |
| 1399 | |
| 1400 | # If URL is pointing to a local directory, it is probably a git cache. |
| 1401 | if os.path.isdir(url): |
| 1402 | url = RunGit(['config', 'remote.%s.url' % remote], |
| 1403 | error_ok=True, |
| 1404 | cwd=url).strip() |
Andrii Shyshkalov | 81db1d5 | 2018-08-23 02:17:41 +0000 | [diff] [blame] | 1405 | self._cached_remote_url = (True, url) |
dyen@chromium.org | 2a13d4f | 2014-06-13 00:06:37 +0000 | [diff] [blame] | 1406 | return url |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1407 | |
tandrii@chromium.org | 87985d2 | 2016-03-24 17:33:33 +0000 | [diff] [blame] | 1408 | def GetIssue(self): |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1409 | """Returns the issue number as a int or None if not set.""" |
tandrii@chromium.org | 87985d2 | 2016-03-24 17:33:33 +0000 | [diff] [blame] | 1410 | if self.issue is None and not self.lookedup_issue: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1411 | self.issue = self._GitGetBranchConfigValue( |
| 1412 | self._codereview_impl.IssueConfigKey(), value_type=int) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1413 | self.lookedup_issue = True |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1414 | return self.issue |
| 1415 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1416 | def GetIssueURL(self): |
| 1417 | """Get the URL for a particular issue.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1418 | issue = self.GetIssue() |
| 1419 | if not issue: |
dbeam@chromium.org | 015fd3d | 2013-06-18 19:02:50 +0000 | [diff] [blame] | 1420 | return None |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1421 | return '%s/%s' % (self._codereview_impl.GetCodereviewServer(), issue) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1422 | |
Andrii Shyshkalov | 3186301 | 2017-02-08 11:35:12 +0100 | [diff] [blame] | 1423 | def GetDescription(self, pretty=False, force=False): |
| 1424 | if not self.has_description or force: |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1425 | if self.GetIssue(): |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 1426 | self.description = self._codereview_impl.FetchDescription(force=force) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1427 | self.has_description = True |
| 1428 | if pretty: |
Asanka Herath | 7c61dcb | 2016-12-14 13:01:58 -0500 | [diff] [blame] | 1429 | # Set width to 72 columns + 2 space indent. |
| 1430 | wrapper = textwrap.TextWrapper(width=74, replace_whitespace=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1431 | wrapper.initial_indent = wrapper.subsequent_indent = ' ' |
Asanka Herath | 7c61dcb | 2016-12-14 13:01:58 -0500 | [diff] [blame] | 1432 | lines = self.description.splitlines() |
| 1433 | return '\n'.join([wrapper.fill(line) for line in lines]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1434 | return self.description |
| 1435 | |
Robert Iannucci | 09f1f3d | 2017-03-28 16:54:32 -0700 | [diff] [blame] | 1436 | def GetDescriptionFooters(self): |
| 1437 | """Returns (non_footer_lines, footers) for the commit message. |
| 1438 | |
| 1439 | Returns: |
| 1440 | non_footer_lines (list(str)) - Simple list of description lines without |
| 1441 | any footer. The lines do not contain newlines, nor does the list contain |
| 1442 | the empty line between the message and the footers. |
| 1443 | footers (list(tuple(KEY, VALUE))) - List of parsed footers, e.g. |
| 1444 | [("Change-Id", "Ideadbeef...."), ...] |
| 1445 | """ |
| 1446 | raw_description = self.GetDescription() |
| 1447 | msg_lines, _, footers = git_footers.split_footers(raw_description) |
| 1448 | if footers: |
| 1449 | msg_lines = msg_lines[:len(msg_lines)-1] |
| 1450 | return msg_lines, footers |
| 1451 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1452 | def GetPatchset(self): |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1453 | """Returns the patchset number as a int or None if not set.""" |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1454 | if self.patchset is None and not self.lookedup_patchset: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1455 | self.patchset = self._GitGetBranchConfigValue( |
| 1456 | self._codereview_impl.PatchsetConfigKey(), value_type=int) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1457 | self.lookedup_patchset = True |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1458 | return self.patchset |
| 1459 | |
| 1460 | def SetPatchset(self, patchset): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1461 | """Set this branch's patchset. If patchset=0, clears the patchset.""" |
| 1462 | assert self.GetBranch() |
| 1463 | if not patchset: |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1464 | self.patchset = None |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1465 | else: |
| 1466 | self.patchset = int(patchset) |
| 1467 | self._GitSetBranchConfigValue( |
| 1468 | self._codereview_impl.PatchsetConfigKey(), self.patchset) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1469 | |
tandrii@chromium.org | a342c92 | 2016-03-16 07:08:25 +0000 | [diff] [blame] | 1470 | def SetIssue(self, issue=None): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1471 | """Set this branch's issue. If issue isn't given, clears the issue.""" |
| 1472 | assert self.GetBranch() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1473 | if issue: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1474 | issue = int(issue) |
| 1475 | self._GitSetBranchConfigValue( |
| 1476 | self._codereview_impl.IssueConfigKey(), issue) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1477 | self.issue = issue |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1478 | codereview_server = self._codereview_impl.GetCodereviewServer() |
| 1479 | if codereview_server: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1480 | self._GitSetBranchConfigValue( |
| 1481 | self._codereview_impl.CodereviewServerConfigKey(), |
| 1482 | codereview_server) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1483 | else: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1484 | # Reset all of these just to be clean. |
| 1485 | reset_suffixes = [ |
| 1486 | 'last-upload-hash', |
| 1487 | self._codereview_impl.IssueConfigKey(), |
| 1488 | self._codereview_impl.PatchsetConfigKey(), |
| 1489 | self._codereview_impl.CodereviewServerConfigKey(), |
| 1490 | ] + self._PostUnsetIssueProperties() |
| 1491 | for prop in reset_suffixes: |
| 1492 | self._GitSetBranchConfigValue(prop, None, error_ok=True) |
Aaron Gable | ca01e2c | 2017-07-19 11:16:02 -0700 | [diff] [blame] | 1493 | msg = RunGit(['log', '-1', '--format=%B']).strip() |
| 1494 | if msg and git_footers.get_footer_change_id(msg): |
| 1495 | print('WARNING: The change patched into this branch has a Change-Id. ' |
| 1496 | 'Removing it.') |
| 1497 | RunGit(['commit', '--amend', '-m', |
| 1498 | git_footers.remove_footer(msg, 'Change-Id')]) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1499 | self.issue = None |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 1500 | self.patchset = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1501 | |
dnj | ba1b0f3 | 2016-09-02 12:37:42 -0700 | [diff] [blame] | 1502 | def GetChange(self, upstream_branch, author, local_description=False): |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1503 | if not self.GitSanityChecks(upstream_branch): |
| 1504 | DieWithError('\nGit sanity check failure') |
| 1505 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1506 | root = settings.GetRelativeRoot() |
bratell@opera.com | f267b0e | 2013-05-02 09:11:43 +0000 | [diff] [blame] | 1507 | if not root: |
| 1508 | root = '.' |
bauerb@chromium.org | 512f1ef | 2011-04-20 15:17:57 +0000 | [diff] [blame] | 1509 | absroot = os.path.abspath(root) |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1510 | |
| 1511 | # We use the sha1 of HEAD as a name of this change. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1512 | name = RunGitWithCode(['rev-parse', 'HEAD'])[1].strip() |
bauerb@chromium.org | 512f1ef | 2011-04-20 15:17:57 +0000 | [diff] [blame] | 1513 | # Need to pass a relative path for msysgit. |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1514 | try: |
maruel@chromium.org | 80a9ef1 | 2011-12-13 20:44:10 +0000 | [diff] [blame] | 1515 | files = scm.GIT.CaptureStatus([root], '.', upstream_branch) |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1516 | except subprocess2.CalledProcessError: |
| 1517 | DieWithError( |
pgervais@chromium.org | d6617f3 | 2013-11-19 00:34:54 +0000 | [diff] [blame] | 1518 | ('\nFailed to diff against upstream branch %s\n\n' |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1519 | 'This branch probably doesn\'t exist anymore. To reset the\n' |
| 1520 | 'tracking branch, please run\n' |
stip | 7a3dd35 | 2016-09-22 17:32:28 -0700 | [diff] [blame] | 1521 | ' git branch --set-upstream-to origin/master %s\n' |
| 1522 | 'or replace origin/master with the relevant branch') % |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1523 | (upstream_branch, self.GetBranch())) |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1524 | |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1525 | issue = self.GetIssue() |
| 1526 | patchset = self.GetPatchset() |
dnj | ba1b0f3 | 2016-09-02 12:37:42 -0700 | [diff] [blame] | 1527 | if issue and not local_description: |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1528 | description = self.GetDescription() |
| 1529 | else: |
| 1530 | # If the change was never uploaded, use the log messages of all commits |
| 1531 | # up to the branch point, as git cl upload will prefill the description |
| 1532 | # with these log messages. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1533 | args = ['log', '--pretty=format:%s%n%n%b', '%s...' % (upstream_branch)] |
| 1534 | description = RunGitWithCode(args)[1].strip() |
maruel@chromium.org | 03b3bdc | 2011-06-14 13:04:12 +0000 | [diff] [blame] | 1535 | |
| 1536 | if not author: |
maruel@chromium.org | 13f623c | 2011-07-22 16:02:23 +0000 | [diff] [blame] | 1537 | author = RunGit(['config', 'user.email']).strip() or None |
asvitkine@chromium.org | 1516995 | 2011-09-27 14:30:53 +0000 | [diff] [blame] | 1538 | return presubmit_support.GitChange( |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1539 | name, |
| 1540 | description, |
| 1541 | absroot, |
| 1542 | files, |
| 1543 | issue, |
| 1544 | patchset, |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 1545 | author, |
| 1546 | upstream=upstream_branch) |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1547 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 1548 | def UpdateDescription(self, description, force=False): |
Andrii Shyshkalov | 8305115 | 2017-02-07 23:47:29 +0100 | [diff] [blame] | 1549 | self._codereview_impl.UpdateDescriptionRemote(description, force=force) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1550 | self.description = description |
Andrii Shyshkalov | 8305115 | 2017-02-07 23:47:29 +0100 | [diff] [blame] | 1551 | self.has_description = True |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1552 | |
Robert Iannucci | 09f1f3d | 2017-03-28 16:54:32 -0700 | [diff] [blame] | 1553 | def UpdateDescriptionFooters(self, description_lines, footers, force=False): |
| 1554 | """Sets the description for this CL remotely. |
| 1555 | |
| 1556 | You can get description_lines and footers with GetDescriptionFooters. |
| 1557 | |
| 1558 | Args: |
| 1559 | description_lines (list(str)) - List of CL description lines without |
| 1560 | newline characters. |
| 1561 | footers (list(tuple(KEY, VALUE))) - List of footers, as returned by |
| 1562 | GetDescriptionFooters. Key must conform to the git footers format (i.e. |
| 1563 | `List-Of-Tokens`). It will be case-normalized so that each token is |
| 1564 | title-cased. |
| 1565 | """ |
| 1566 | new_description = '\n'.join(description_lines) |
| 1567 | if footers: |
| 1568 | new_description += '\n' |
| 1569 | for k, v in footers: |
| 1570 | foot = '%s: %s' % (git_footers.normalize_name(k), v) |
| 1571 | if not git_footers.FOOTER_PATTERN.match(foot): |
| 1572 | raise ValueError('Invalid footer %r' % foot) |
| 1573 | new_description += foot + '\n' |
| 1574 | self.UpdateDescription(new_description, force) |
| 1575 | |
Edward Lesmes | 8e28279 | 2018-04-03 18:50:29 -0400 | [diff] [blame] | 1576 | def RunHook(self, committing, may_prompt, verbose, change, parallel): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1577 | """Calls sys.exit() if the hook fails; returns a HookResults otherwise.""" |
| 1578 | try: |
| 1579 | return presubmit_support.DoPresubmitChecks(change, committing, |
| 1580 | verbose=verbose, output_stream=sys.stdout, input_stream=sys.stdin, |
| 1581 | default_presubmit=None, may_prompt=may_prompt, |
Edward Lesmes | 8e28279 | 2018-04-03 18:50:29 -0400 | [diff] [blame] | 1582 | gerrit_obj=self._codereview_impl.GetGerritObjForPresubmit(), |
| 1583 | parallel=parallel) |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 1584 | except presubmit_support.PresubmitFailure as e: |
Aaron Gable | 5d5f22c | 2018-02-02 09:12:41 -0800 | [diff] [blame] | 1585 | DieWithError('%s\nMaybe your depot_tools is out of date?' % e) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1586 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1587 | def CMDPatchIssue(self, issue_arg, reject, nocommit, directory): |
| 1588 | """Fetches and applies the issue patch from codereview to local branch.""" |
tandrii@chromium.org | ef7c68c | 2016-04-07 09:39:39 +0000 | [diff] [blame] | 1589 | if isinstance(issue_arg, (int, long)) or issue_arg.isdigit(): |
| 1590 | parsed_issue_arg = _ParsedIssueNumberArgument(int(issue_arg)) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1591 | else: |
| 1592 | # Assume url. |
| 1593 | parsed_issue_arg = self._codereview_impl.ParseIssueURL( |
| 1594 | urlparse.urlparse(issue_arg)) |
| 1595 | if not parsed_issue_arg or not parsed_issue_arg.valid: |
| 1596 | DieWithError('Failed to parse issue argument "%s". ' |
| 1597 | 'Must be an issue number or a valid URL.' % issue_arg) |
| 1598 | return self._codereview_impl.CMDPatchWithParsedIssue( |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 1599 | parsed_issue_arg, reject, nocommit, directory, False) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1600 | |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1601 | def CMDUpload(self, options, git_diff_args, orig_args): |
| 1602 | """Uploads a change to codereview.""" |
Andrii Shyshkalov | 9f27443 | 2018-10-15 16:40:23 +0000 | [diff] [blame] | 1603 | assert self.IsGerrit() |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 1604 | custom_cl_base = None |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1605 | if git_diff_args: |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 1606 | custom_cl_base = base_branch = git_diff_args[0] |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1607 | else: |
| 1608 | if self.GetBranch() is None: |
| 1609 | DieWithError('Can\'t upload from detached HEAD state. Get on a branch!') |
| 1610 | |
| 1611 | # Default to diffing against common ancestor of upstream branch |
| 1612 | base_branch = self.GetCommonAncestorWithUpstream() |
| 1613 | git_diff_args = [base_branch, 'HEAD'] |
| 1614 | |
Aaron Gable | c4c40d1 | 2017-05-22 11:49:53 -0700 | [diff] [blame] | 1615 | |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 1616 | # Fast best-effort checks to abort before running potentially |
| 1617 | # expensive hooks if uploading is likely to fail anyway. Passing these |
| 1618 | # checks does not guarantee that uploading will not fail. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1619 | self._codereview_impl.EnsureAuthenticated(force=options.force) |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1620 | self._codereview_impl.EnsureCanUploadPatchset(force=options.force) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1621 | |
| 1622 | # Apply watchlists on upload. |
| 1623 | change = self.GetChange(base_branch, None) |
| 1624 | watchlist = watchlists.Watchlists(change.RepositoryRoot()) |
| 1625 | files = [f.LocalPath() for f in change.AffectedFiles()] |
| 1626 | if not options.bypass_watchlists: |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1627 | self.ExtendCC(watchlist.GetWatchersForPaths(files)) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1628 | |
| 1629 | if not options.bypass_hooks: |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 1630 | if options.reviewers or options.tbrs or options.add_owners_to: |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1631 | # Set the reviewer list now so that presubmit checks can access it. |
| 1632 | change_description = ChangeDescription(change.FullDescriptionText()) |
| 1633 | change_description.update_reviewers(options.reviewers, |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 1634 | options.tbrs, |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 1635 | options.add_owners_to, |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1636 | change) |
| 1637 | change.SetDescriptionText(change_description.description) |
| 1638 | hook_results = self.RunHook(committing=False, |
Edward Lesmes | 8e28279 | 2018-04-03 18:50:29 -0400 | [diff] [blame] | 1639 | may_prompt=not options.force, |
| 1640 | verbose=options.verbose, |
| 1641 | change=change, parallel=options.parallel) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1642 | if not hook_results.should_continue(): |
| 1643 | return 1 |
| 1644 | if not options.reviewers and hook_results.reviewers: |
| 1645 | options.reviewers = hook_results.reviewers.split(',') |
Daniel Cheng | 7227d21 | 2017-11-17 08:12:37 -0800 | [diff] [blame] | 1646 | self.ExtendCC(hook_results.more_cc) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1647 | |
Aaron Gable | 13101a6 | 2018-02-09 13:20:41 -0800 | [diff] [blame] | 1648 | print_stats(git_diff_args) |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 1649 | ret = self.CMDUploadChange(options, git_diff_args, custom_cl_base, change) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1650 | if not ret: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1651 | _git_set_branch_config_value('last-upload-hash', |
| 1652 | RunGit(['rev-parse', 'HEAD']).strip()) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1653 | # Run post upload hooks, if specified. |
| 1654 | if settings.GetRunPostUploadHook(): |
| 1655 | presubmit_support.DoPostUploadExecuter( |
| 1656 | change, |
| 1657 | self, |
| 1658 | settings.GetRoot(), |
| 1659 | options.verbose, |
| 1660 | sys.stdout) |
| 1661 | |
| 1662 | # Upload all dependencies if specified. |
| 1663 | if options.dependencies: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1664 | print() |
| 1665 | print('--dependencies has been specified.') |
| 1666 | print('All dependent local branches will be re-uploaded.') |
| 1667 | print() |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1668 | # Remove the dependencies flag from args so that we do not end up in a |
| 1669 | # loop. |
| 1670 | orig_args.remove('--dependencies') |
| 1671 | ret = upload_branch_deps(self, orig_args) |
| 1672 | return ret |
| 1673 | |
Ravi Mistry | 31e7d56 | 2018-04-02 12:53:57 -0400 | [diff] [blame] | 1674 | def SetLabels(self, enable_auto_submit, use_commit_queue, cq_dry_run): |
| 1675 | """Sets labels on the change based on the provided flags. |
| 1676 | |
| 1677 | Sets labels if issue is already uploaded and known, else returns without |
| 1678 | doing anything. |
| 1679 | |
| 1680 | Args: |
| 1681 | enable_auto_submit: Sets Auto-Submit+1 on the change. |
| 1682 | use_commit_queue: Sets Commit-Queue+2 on the change. |
| 1683 | cq_dry_run: Sets Commit-Queue+1 on the change. Overrides Commit-Queue+2 if |
| 1684 | both use_commit_queue and cq_dry_run are true. |
| 1685 | """ |
| 1686 | if not self.GetIssue(): |
| 1687 | return |
| 1688 | try: |
| 1689 | self._codereview_impl.SetLabels(enable_auto_submit, use_commit_queue, |
| 1690 | cq_dry_run) |
| 1691 | return 0 |
| 1692 | except KeyboardInterrupt: |
| 1693 | raise |
| 1694 | except: |
| 1695 | labels = [] |
| 1696 | if enable_auto_submit: |
| 1697 | labels.append('Auto-Submit') |
| 1698 | if use_commit_queue or cq_dry_run: |
| 1699 | labels.append('Commit-Queue') |
| 1700 | print('WARNING: Failed to set label(s) on your change: %s\n' |
| 1701 | 'Either:\n' |
| 1702 | ' * Your project does not have the above label(s),\n' |
| 1703 | ' * You don\'t have permission to set the above label(s),\n' |
| 1704 | ' * There\'s a bug in this code (see stack trace below).\n' % |
| 1705 | (', '.join(labels))) |
| 1706 | # Still raise exception so that stack trace is printed. |
| 1707 | raise |
| 1708 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1709 | def SetCQState(self, new_state): |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 1710 | """Updates the CQ state for the latest patchset. |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1711 | |
| 1712 | Issue must have been already uploaded and known. |
| 1713 | """ |
| 1714 | assert new_state in _CQState.ALL_STATES |
| 1715 | assert self.GetIssue() |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 1716 | try: |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 1717 | self._codereview_impl.SetCQState(new_state) |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 1718 | return 0 |
| 1719 | except KeyboardInterrupt: |
| 1720 | raise |
| 1721 | except: |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 1722 | print('WARNING: Failed to %s.\n' |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 1723 | 'Either:\n' |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 1724 | ' * Your project has no CQ,\n' |
| 1725 | ' * You don\'t have permission to change the CQ state,\n' |
| 1726 | ' * There\'s a bug in this code (see stack trace below).\n' |
| 1727 | 'Consider specifying which bots to trigger manually or asking your ' |
| 1728 | 'project owners for permissions or contacting Chrome Infra at:\n' |
| 1729 | 'https://www.chromium.org/infra\n\n' % |
| 1730 | ('cancel CQ' if new_state == _CQState.NONE else 'trigger CQ')) |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 1731 | # Still raise exception so that stack trace is printed. |
| 1732 | raise |
| 1733 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1734 | # Forward methods to codereview specific implementation. |
| 1735 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 1736 | def AddComment(self, message, publish=None): |
| 1737 | return self._codereview_impl.AddComment(message, publish=publish) |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 1738 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 1739 | def GetCommentsSummary(self, readable=True): |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1740 | """Returns list of _CommentSummary for each comment. |
| 1741 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 1742 | args: |
| 1743 | readable: determines whether the output is designed for a human or a machine |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1744 | """ |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 1745 | return self._codereview_impl.GetCommentsSummary(readable) |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1746 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1747 | def CloseIssue(self): |
| 1748 | return self._codereview_impl.CloseIssue() |
| 1749 | |
| 1750 | def GetStatus(self): |
| 1751 | return self._codereview_impl.GetStatus() |
| 1752 | |
| 1753 | def GetCodereviewServer(self): |
| 1754 | return self._codereview_impl.GetCodereviewServer() |
| 1755 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1756 | def GetIssueOwner(self): |
| 1757 | """Get owner from codereview, which may differ from this checkout.""" |
| 1758 | return self._codereview_impl.GetIssueOwner() |
| 1759 | |
Edward Lemur | 707d70b | 2018-02-07 00:50:14 +0100 | [diff] [blame] | 1760 | def GetReviewers(self): |
| 1761 | return self._codereview_impl.GetReviewers() |
| 1762 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1763 | def GetMostRecentPatchset(self): |
| 1764 | return self._codereview_impl.GetMostRecentPatchset() |
| 1765 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1766 | def CannotTriggerTryJobReason(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1767 | """Returns reason (str) if unable trigger try jobs on this CL or None.""" |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1768 | return self._codereview_impl.CannotTriggerTryJobReason() |
| 1769 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1770 | def GetTryJobProperties(self, patchset=None): |
| 1771 | """Returns dictionary of properties to launch try job.""" |
| 1772 | return self._codereview_impl.GetTryJobProperties(patchset=patchset) |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 1773 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1774 | def __getattr__(self, attr): |
| 1775 | # This is because lots of untested code accesses Rietveld-specific stuff |
| 1776 | # directly, and it's hard to fix for sure. So, just let it work, and fix |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 1777 | # on a case by case basis. |
tandrii | 4d89550 | 2016-08-18 08:26:19 -0700 | [diff] [blame] | 1778 | # Note that child method defines __getattr__ as well, and forwards it here, |
| 1779 | # because _RietveldChangelistImpl is not cleaned up yet, and given |
| 1780 | # deprecation of Rietveld, it should probably be just removed. |
| 1781 | # Until that time, avoid infinite recursion by bypassing __getattr__ |
| 1782 | # of implementation class. |
| 1783 | return self._codereview_impl.__getattribute__(attr) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1784 | |
| 1785 | |
| 1786 | class _ChangelistCodereviewBase(object): |
| 1787 | """Abstract base class encapsulating codereview specifics of a changelist.""" |
| 1788 | def __init__(self, changelist): |
| 1789 | self._changelist = changelist # instance of Changelist |
| 1790 | |
| 1791 | def __getattr__(self, attr): |
| 1792 | # Forward methods to changelist. |
| 1793 | # TODO(tandrii): maybe clean up _GerritChangelistImpl and |
| 1794 | # _RietveldChangelistImpl to avoid this hack? |
| 1795 | return getattr(self._changelist, attr) |
| 1796 | |
| 1797 | def GetStatus(self): |
| 1798 | """Apply a rough heuristic to give a simple summary of an issue's review |
| 1799 | or CQ status, assuming adherence to a common workflow. |
| 1800 | |
| 1801 | Returns None if no issue for this branch, or specific string keywords. |
| 1802 | """ |
| 1803 | raise NotImplementedError() |
| 1804 | |
| 1805 | def GetCodereviewServer(self): |
| 1806 | """Returns server URL without end slash, like "https://codereview.com".""" |
| 1807 | raise NotImplementedError() |
| 1808 | |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 1809 | def FetchDescription(self, force=False): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1810 | """Fetches and returns description from the codereview server.""" |
| 1811 | raise NotImplementedError() |
| 1812 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1813 | @classmethod |
| 1814 | def IssueConfigKey(cls): |
| 1815 | """Returns branch setting storing issue number.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1816 | raise NotImplementedError() |
| 1817 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 1818 | @classmethod |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1819 | def PatchsetConfigKey(cls): |
| 1820 | """Returns branch setting storing patchset number.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1821 | raise NotImplementedError() |
| 1822 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1823 | @classmethod |
| 1824 | def CodereviewServerConfigKey(cls): |
| 1825 | """Returns branch setting storing codereview server.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1826 | raise NotImplementedError() |
| 1827 | |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 1828 | def _PostUnsetIssueProperties(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1829 | """Which branch-specific properties to erase when unsetting issue.""" |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1830 | return [] |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 1831 | |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 1832 | def GetGerritObjForPresubmit(self): |
| 1833 | # None is valid return value, otherwise presubmit_support.GerritAccessor. |
| 1834 | return None |
| 1835 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 1836 | def UpdateDescriptionRemote(self, description, force=False): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1837 | """Update the description on codereview site.""" |
| 1838 | raise NotImplementedError() |
| 1839 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 1840 | def AddComment(self, message, publish=None): |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 1841 | """Posts a comment to the codereview site.""" |
| 1842 | raise NotImplementedError() |
| 1843 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 1844 | def GetCommentsSummary(self, readable=True): |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1845 | raise NotImplementedError() |
| 1846 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1847 | def CloseIssue(self): |
| 1848 | """Closes the issue.""" |
| 1849 | raise NotImplementedError() |
| 1850 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1851 | def GetMostRecentPatchset(self): |
| 1852 | """Returns the most recent patchset number from the codereview site.""" |
| 1853 | raise NotImplementedError() |
| 1854 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1855 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 1856 | directory, force): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1857 | """Fetches and applies the issue. |
| 1858 | |
| 1859 | Arguments: |
| 1860 | parsed_issue_arg: instance of _ParsedIssueNumberArgument. |
| 1861 | reject: if True, reject the failed patch instead of switching to 3-way |
| 1862 | merge. Rietveld only. |
| 1863 | nocommit: do not commit the patch, thus leave the tree dirty. Rietveld |
| 1864 | only. |
| 1865 | directory: switch to directory before applying the patch. Rietveld only. |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 1866 | force: if true, overwrites existing local state. |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1867 | """ |
| 1868 | raise NotImplementedError() |
| 1869 | |
| 1870 | @staticmethod |
| 1871 | def ParseIssueURL(parsed_url): |
| 1872 | """Parses url and returns instance of _ParsedIssueNumberArgument or None if |
| 1873 | failed.""" |
| 1874 | raise NotImplementedError() |
| 1875 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 1876 | def EnsureAuthenticated(self, force, refresh=False): |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1877 | """Best effort check that user is authenticated with codereview server. |
| 1878 | |
| 1879 | Arguments: |
| 1880 | force: whether to skip confirmation questions. |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 1881 | refresh: whether to attempt to refresh credentials. Ignored if not |
| 1882 | applicable. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1883 | """ |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1884 | raise NotImplementedError() |
| 1885 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1886 | def EnsureCanUploadPatchset(self, force): |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 1887 | """Best effort check that uploading isn't supposed to fail for predictable |
| 1888 | reasons. |
| 1889 | |
| 1890 | This method should raise informative exception if uploading shouldn't |
| 1891 | proceed. |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1892 | |
| 1893 | Arguments: |
| 1894 | force: whether to skip confirmation questions. |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 1895 | """ |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1896 | raise NotImplementedError() |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 1897 | |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 1898 | def CMDUploadChange(self, options, git_diff_args, custom_cl_base, change): |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 1899 | """Uploads a change to codereview.""" |
| 1900 | raise NotImplementedError() |
| 1901 | |
Ravi Mistry | 31e7d56 | 2018-04-02 12:53:57 -0400 | [diff] [blame] | 1902 | def SetLabels(self, enable_auto_submit, use_commit_queue, cq_dry_run): |
| 1903 | """Sets labels on the change based on the provided flags. |
| 1904 | |
| 1905 | Issue must have been already uploaded and known. |
| 1906 | """ |
| 1907 | raise NotImplementedError() |
| 1908 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1909 | def SetCQState(self, new_state): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1910 | """Updates the CQ state for the latest patchset. |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1911 | |
| 1912 | Issue must have been already uploaded and known. |
| 1913 | """ |
| 1914 | raise NotImplementedError() |
| 1915 | |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 1916 | def CannotTriggerTryJobReason(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1917 | """Returns reason (str) if unable trigger try jobs on this CL or None.""" |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 1918 | raise NotImplementedError() |
| 1919 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1920 | def GetIssueOwner(self): |
| 1921 | raise NotImplementedError() |
| 1922 | |
Edward Lemur | 707d70b | 2018-02-07 00:50:14 +0100 | [diff] [blame] | 1923 | def GetReviewers(self): |
| 1924 | raise NotImplementedError() |
| 1925 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1926 | def GetTryJobProperties(self, patchset=None): |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1927 | raise NotImplementedError() |
| 1928 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1929 | |
| 1930 | class _RietveldChangelistImpl(_ChangelistCodereviewBase): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1931 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 1932 | def __init__(self, changelist, auth_config=None, codereview_host=None): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1933 | super(_RietveldChangelistImpl, self).__init__(changelist) |
| 1934 | assert settings, 'must be initialized in _ChangelistCodereviewBase' |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 1935 | if not codereview_host: |
martiniss | 6eda05f | 2016-06-30 10:18:35 -0700 | [diff] [blame] | 1936 | settings.GetDefaultServerUrl() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1937 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 1938 | self._rietveld_server = codereview_host |
Andrii Shyshkalov | 98cef57 | 2017-01-25 13:57:52 +0100 | [diff] [blame] | 1939 | self._auth_config = auth_config or auth.make_auth_config() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1940 | self._props = None |
| 1941 | self._rpc_server = None |
| 1942 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1943 | def GetCodereviewServer(self): |
| 1944 | if not self._rietveld_server: |
| 1945 | # If we're on a branch then get the server potentially associated |
| 1946 | # with that branch. |
| 1947 | if self.GetIssue(): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1948 | self._rietveld_server = gclient_utils.UpgradeToHttps( |
| 1949 | self._GitGetBranchConfigValue(self.CodereviewServerConfigKey())) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1950 | if not self._rietveld_server: |
| 1951 | self._rietveld_server = settings.GetDefaultServerUrl() |
| 1952 | return self._rietveld_server |
| 1953 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 1954 | def EnsureAuthenticated(self, force, refresh=False): |
Andrii Shyshkalov | 51bdf8c | 2018-10-18 01:07:58 +0000 | [diff] [blame] | 1955 | # No checks for Rietveld because we are deprecating Rietveld. |
| 1956 | pass |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1957 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1958 | def EnsureCanUploadPatchset(self, force): |
| 1959 | # No checks for Rietveld because we are deprecating Rietveld. |
| 1960 | pass |
| 1961 | |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 1962 | def FetchDescription(self, force=False): |
Andrii Shyshkalov | 642641d | 2018-10-16 05:54:41 +0000 | [diff] [blame] | 1963 | raise NotImplementedError() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1964 | |
| 1965 | def GetMostRecentPatchset(self): |
Andrii Shyshkalov | 642641d | 2018-10-16 05:54:41 +0000 | [diff] [blame] | 1966 | raise NotImplementedError() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1967 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1968 | def GetIssueProperties(self): |
Andrii Shyshkalov | 642641d | 2018-10-16 05:54:41 +0000 | [diff] [blame] | 1969 | raise NotImplementedError() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1970 | |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 1971 | def CannotTriggerTryJobReason(self): |
Andrii Shyshkalov | 03da150 | 2018-10-15 03:42:34 +0000 | [diff] [blame] | 1972 | raise NotImplementedError() |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 1973 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1974 | def GetTryJobProperties(self, patchset=None): |
Andrii Shyshkalov | 03da150 | 2018-10-15 03:42:34 +0000 | [diff] [blame] | 1975 | raise NotImplementedError() |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 1976 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1977 | def GetIssueOwner(self): |
Andrii Shyshkalov | 51bdf8c | 2018-10-18 01:07:58 +0000 | [diff] [blame] | 1978 | raise NotImplementedError() |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1979 | |
Edward Lemur | 707d70b | 2018-02-07 00:50:14 +0100 | [diff] [blame] | 1980 | def GetReviewers(self): |
Andrii Shyshkalov | 51bdf8c | 2018-10-18 01:07:58 +0000 | [diff] [blame] | 1981 | raise NotImplementedError() |
Edward Lemur | 707d70b | 2018-02-07 00:50:14 +0100 | [diff] [blame] | 1982 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 1983 | def AddComment(self, message, publish=None): |
Andrii Shyshkalov | 51bdf8c | 2018-10-18 01:07:58 +0000 | [diff] [blame] | 1984 | raise NotImplementedError() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1985 | |
Andrii Shyshkalov | 51bdf8c | 2018-10-18 01:07:58 +0000 | [diff] [blame] | 1986 | def GetCommentsSummary(self, readable=True): |
| 1987 | raise NotImplementedError() |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1988 | |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 1989 | def GetStatus(self): |
Andrii Shyshkalov | 51bdf8c | 2018-10-18 01:07:58 +0000 | [diff] [blame] | 1990 | print( |
| 1991 | 'WARNING! Rietveld is no longer supported.\n' |
| 1992 | '\n' |
| 1993 | 'If you have old branches in your checkout, please archive/delete them.\n' |
| 1994 | ' $ git cl archive --help\n' |
| 1995 | '\n' |
| 1996 | 'See also PSA https://groups.google.com/a/chromium.org/' |
| 1997 | 'forum/#!topic/infra-dev/2DIVzM2wseo\n') |
| 1998 | return 'rietveld-not-supported' |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 1999 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 2000 | def UpdateDescriptionRemote(self, description, force=False): |
Andrii Shyshkalov | 51bdf8c | 2018-10-18 01:07:58 +0000 | [diff] [blame] | 2001 | raise NotImplementedError() |
maruel@chromium.org | b021b32 | 2013-04-08 17:57:29 +0000 | [diff] [blame] | 2002 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2003 | def CloseIssue(self): |
Andrii Shyshkalov | 51bdf8c | 2018-10-18 01:07:58 +0000 | [diff] [blame] | 2004 | raise NotImplementedError() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2005 | |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 2006 | def SetFlag(self, flag, value): |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2007 | return self.SetFlags({flag: value}) |
| 2008 | |
| 2009 | def SetFlags(self, flags): |
| 2010 | """Sets flags on this CL/patchset in Rietveld. |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2011 | """ |
phajdan.jr | 6859823 | 2016-08-10 03:28:28 -0700 | [diff] [blame] | 2012 | patchset = self.GetPatchset() or self.GetMostRecentPatchset() |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 2013 | try: |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2014 | return self.RpcServer().set_flags( |
phajdan.jr | 6859823 | 2016-08-10 03:28:28 -0700 | [diff] [blame] | 2015 | self.GetIssue(), patchset, flags) |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 2016 | except urllib2.HTTPError as e: |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 2017 | if e.code == 404: |
| 2018 | DieWithError('The issue %s doesn\'t exist.' % self.GetIssue()) |
| 2019 | if e.code == 403: |
| 2020 | DieWithError( |
| 2021 | ('Access denied to issue %s. Maybe the patchset %s doesn\'t ' |
phajdan.jr | 6859823 | 2016-08-10 03:28:28 -0700 | [diff] [blame] | 2022 | 'match?') % (self.GetIssue(), patchset)) |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 2023 | raise |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2024 | |
maruel@chromium.org | cab38e9 | 2011-04-09 00:30:51 +0000 | [diff] [blame] | 2025 | def RpcServer(self): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2026 | """Returns an upload.RpcServer() to access this review's rietveld instance. |
| 2027 | """ |
maruel@chromium.org | e77ebbf | 2011-03-29 20:35:38 +0000 | [diff] [blame] | 2028 | if not self._rpc_server: |
maruel@chromium.org | 4bac4b5 | 2012-11-27 20:33:52 +0000 | [diff] [blame] | 2029 | self._rpc_server = rietveld.CachingRietveld( |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2030 | self.GetCodereviewServer(), |
Andrii Shyshkalov | 98cef57 | 2017-01-25 13:57:52 +0100 | [diff] [blame] | 2031 | self._auth_config) |
maruel@chromium.org | e77ebbf | 2011-03-29 20:35:38 +0000 | [diff] [blame] | 2032 | return self._rpc_server |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2033 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2034 | @classmethod |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2035 | def IssueConfigKey(cls): |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2036 | return 'rietveldissue' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2037 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2038 | @classmethod |
| 2039 | def PatchsetConfigKey(cls): |
| 2040 | return 'rietveldpatchset' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2041 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2042 | @classmethod |
| 2043 | def CodereviewServerConfigKey(cls): |
| 2044 | return 'rietveldserver' |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 2045 | |
Ravi Mistry | 31e7d56 | 2018-04-02 12:53:57 -0400 | [diff] [blame] | 2046 | def SetLabels(self, enable_auto_submit, use_commit_queue, cq_dry_run): |
| 2047 | raise NotImplementedError() |
| 2048 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2049 | def SetCQState(self, new_state): |
| 2050 | props = self.GetIssueProperties() |
| 2051 | if props.get('private'): |
| 2052 | DieWithError('Cannot set-commit on private issue') |
| 2053 | |
| 2054 | if new_state == _CQState.COMMIT: |
tandrii | 4d84359 | 2016-07-27 08:22:56 -0700 | [diff] [blame] | 2055 | self.SetFlags({'commit': '1', 'cq_dry_run': '0'}) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2056 | elif new_state == _CQState.NONE: |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2057 | self.SetFlags({'commit': '0', 'cq_dry_run': '0'}) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2058 | else: |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2059 | assert new_state == _CQState.DRY_RUN |
| 2060 | self.SetFlags({'commit': '1', 'cq_dry_run': '1'}) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2061 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2062 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 2063 | directory, force): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2064 | # PatchIssue should never be called with a dirty tree. It is up to the |
| 2065 | # caller to check this, but just in case we assert here since the |
| 2066 | # consequences of the caller not checking this could be dire. |
| 2067 | assert(not git_common.is_dirty_git_tree('apply')) |
| 2068 | assert(parsed_issue_arg.valid) |
| 2069 | self._changelist.issue = parsed_issue_arg.issue |
| 2070 | if parsed_issue_arg.hostname: |
| 2071 | self._rietveld_server = 'https://%s' % parsed_issue_arg.hostname |
| 2072 | |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2073 | patchset = parsed_issue_arg.patchset or self.GetMostRecentPatchset() |
| 2074 | patchset_object = self.RpcServer().get_patch(self.GetIssue(), patchset) |
| 2075 | scm_obj = checkout.GitCheckout(settings.GetRoot(), None, None, None, None) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2076 | try: |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2077 | scm_obj.apply_patch(patchset_object) |
| 2078 | except Exception as e: |
| 2079 | print(str(e)) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2080 | return 1 |
| 2081 | |
| 2082 | # If we had an issue, commit the current state and register the issue. |
| 2083 | if not nocommit: |
Aaron Gable | d343c63 | 2017-03-15 11:02:26 -0700 | [diff] [blame] | 2084 | self.SetIssue(self.GetIssue()) |
| 2085 | self.SetPatchset(patchset) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2086 | RunGit(['commit', '-m', (self.GetDescription() + '\n\n' + |
| 2087 | 'patch from issue %(i)s at patchset ' |
| 2088 | '%(p)s (http://crrev.com/%(i)s#ps%(p)s)' |
| 2089 | % {'i': self.GetIssue(), 'p': patchset})]) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 2090 | print('Committed patch locally.') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2091 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 2092 | print('Patch applied to index.') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2093 | return 0 |
| 2094 | |
| 2095 | @staticmethod |
| 2096 | def ParseIssueURL(parsed_url): |
| 2097 | if not parsed_url.scheme or not parsed_url.scheme.startswith('http'): |
| 2098 | return None |
wychen | 3c1c172 | 2016-08-04 11:46:36 -0700 | [diff] [blame] | 2099 | # Rietveld patch: https://domain/<number>/#ps<patchset> |
| 2100 | match = re.match(r'/(\d+)/$', parsed_url.path) |
| 2101 | match2 = re.match(r'ps(\d+)$', parsed_url.fragment) |
| 2102 | if match and match2: |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2103 | return _ParsedIssueNumberArgument( |
wychen | 3c1c172 | 2016-08-04 11:46:36 -0700 | [diff] [blame] | 2104 | issue=int(match.group(1)), |
| 2105 | patchset=int(match2.group(1)), |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 2106 | hostname=parsed_url.netloc, |
| 2107 | codereview='rietveld') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2108 | # Typical url: https://domain/<issue_number>[/[other]] |
| 2109 | match = re.match('/(\d+)(/.*)?$', parsed_url.path) |
| 2110 | if match: |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2111 | return _ParsedIssueNumberArgument( |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2112 | issue=int(match.group(1)), |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 2113 | hostname=parsed_url.netloc, |
| 2114 | codereview='rietveld') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2115 | # Rietveld patch: https://domain/download/issue<number>_<patchset>.diff |
| 2116 | match = re.match(r'/download/issue(\d+)_(\d+).diff$', parsed_url.path) |
| 2117 | if match: |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2118 | return _ParsedIssueNumberArgument( |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2119 | issue=int(match.group(1)), |
| 2120 | patchset=int(match.group(2)), |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 2121 | hostname=parsed_url.netloc, |
| 2122 | codereview='rietveld') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2123 | return None |
| 2124 | |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2125 | def CMDUploadChange(self, options, args, custom_cl_base, change): |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2126 | """Upload the patch to Rietveld.""" |
Andrii Shyshkalov | 9f27443 | 2018-10-15 16:40:23 +0000 | [diff] [blame] | 2127 | raise NotImplementedError |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2128 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 2129 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2130 | class _GerritChangelistImpl(_ChangelistCodereviewBase): |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 2131 | def __init__(self, changelist, auth_config=None, codereview_host=None): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2132 | # auth_config is Rietveld thing, kept here to preserve interface only. |
| 2133 | super(_GerritChangelistImpl, self).__init__(changelist) |
| 2134 | self._change_id = None |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2135 | # Lazily cached values. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2136 | self._gerrit_host = None # e.g. chromium-review.googlesource.com |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 2137 | self._gerrit_server = None # e.g. https://chromium-review.googlesource.com |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2138 | # Map from change number (issue) to its detail cache. |
| 2139 | self._detail_cache = {} |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2140 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 2141 | if codereview_host is not None: |
| 2142 | assert not codereview_host.startswith('https://'), codereview_host |
| 2143 | self._gerrit_host = codereview_host |
| 2144 | self._gerrit_server = 'https://%s' % codereview_host |
| 2145 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2146 | def _GetGerritHost(self): |
| 2147 | # Lazy load of configs. |
| 2148 | self.GetCodereviewServer() |
tandrii | e32e3ea | 2016-06-22 02:52:48 -0700 | [diff] [blame] | 2149 | if self._gerrit_host and '.' not in self._gerrit_host: |
| 2150 | # Abbreviated domain like "chromium" instead of chromium.googlesource.com. |
| 2151 | # This happens for internal stuff http://crbug.com/614312. |
| 2152 | parsed = urlparse.urlparse(self.GetRemoteUrl()) |
| 2153 | if parsed.scheme == 'sso': |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2154 | print('WARNING: using non-https URLs for remote is likely broken\n' |
tandrii | e32e3ea | 2016-06-22 02:52:48 -0700 | [diff] [blame] | 2155 | ' Your current remote is: %s' % self.GetRemoteUrl()) |
| 2156 | self._gerrit_host = '%s.googlesource.com' % self._gerrit_host |
| 2157 | self._gerrit_server = 'https://%s' % self._gerrit_host |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2158 | return self._gerrit_host |
| 2159 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2160 | def _GetGitHost(self): |
| 2161 | """Returns git host to be used when uploading change to Gerrit.""" |
| 2162 | return urlparse.urlparse(self.GetRemoteUrl()).netloc |
| 2163 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2164 | def GetCodereviewServer(self): |
| 2165 | if not self._gerrit_server: |
| 2166 | # If we're on a branch then get the server potentially associated |
| 2167 | # with that branch. |
| 2168 | if self.GetIssue(): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2169 | self._gerrit_server = self._GitGetBranchConfigValue( |
| 2170 | self.CodereviewServerConfigKey()) |
| 2171 | if self._gerrit_server: |
| 2172 | self._gerrit_host = urlparse.urlparse(self._gerrit_server).netloc |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2173 | if not self._gerrit_server: |
| 2174 | # We assume repo to be hosted on Gerrit, and hence Gerrit server |
| 2175 | # has "-review" suffix for lowest level subdomain. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2176 | parts = self._GetGitHost().split('.') |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2177 | parts[0] = parts[0] + '-review' |
| 2178 | self._gerrit_host = '.'.join(parts) |
| 2179 | self._gerrit_server = 'https://%s' % self._gerrit_host |
| 2180 | return self._gerrit_server |
| 2181 | |
Andrii Shyshkalov | 2d0e03c | 2018-08-25 04:18:09 +0000 | [diff] [blame] | 2182 | def _GetGerritProject(self): |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 2183 | """Returns Gerrit project name based on remote git URL.""" |
Andrii Shyshkalov | 2d0e03c | 2018-08-25 04:18:09 +0000 | [diff] [blame] | 2184 | remote_url = self.GetRemoteUrl() |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 2185 | if remote_url is None: |
Andrii Shyshkalov | 2d0e03c | 2018-08-25 04:18:09 +0000 | [diff] [blame] | 2186 | logging.warn('can\'t detect Gerrit project.') |
| 2187 | return None |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 2188 | project = urlparse.urlparse(remote_url).path.strip('/') |
| 2189 | if project.endswith('.git'): |
| 2190 | project = project[:-len('.git')] |
Andrii Shyshkalov | 1e82867 | 2018-08-23 22:34:37 +0000 | [diff] [blame] | 2191 | # *.googlesource.com hosts ensure that Git/Gerrit projects don't start with |
| 2192 | # 'a/' prefix, because 'a/' prefix is used to force authentication in |
| 2193 | # gitiles/git-over-https protocol. E.g., |
| 2194 | # https://chromium.googlesource.com/a/v8/v8 refers to the same repo/project |
| 2195 | # as |
| 2196 | # https://chromium.googlesource.com/v8/v8 |
| 2197 | if project.startswith('a/'): |
| 2198 | project = project[len('a/'):] |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 2199 | return project |
| 2200 | |
Andrii Shyshkalov | d06cc78 | 2018-08-23 17:24:19 +0000 | [diff] [blame] | 2201 | def _GerritChangeIdentifier(self): |
| 2202 | """Handy method for gerrit_util.ChangeIdentifier for a given CL. |
| 2203 | |
| 2204 | Not to be confused by value of "Change-Id:" footer. |
Andrii Shyshkalov | 2d0e03c | 2018-08-25 04:18:09 +0000 | [diff] [blame] | 2205 | If Gerrit project can be determined, this will speed up Gerrit HTTP API RPC. |
Andrii Shyshkalov | d06cc78 | 2018-08-23 17:24:19 +0000 | [diff] [blame] | 2206 | """ |
Andrii Shyshkalov | 2d0e03c | 2018-08-25 04:18:09 +0000 | [diff] [blame] | 2207 | project = self._GetGerritProject() |
| 2208 | if project: |
| 2209 | return gerrit_util.ChangeIdentifier(project, self.GetIssue()) |
| 2210 | # Fall back on still unique, but less efficient change number. |
| 2211 | return str(self.GetIssue()) |
Andrii Shyshkalov | d06cc78 | 2018-08-23 17:24:19 +0000 | [diff] [blame] | 2212 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2213 | @classmethod |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2214 | def IssueConfigKey(cls): |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2215 | return 'gerritissue' |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2216 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2217 | @classmethod |
| 2218 | def PatchsetConfigKey(cls): |
| 2219 | return 'gerritpatchset' |
| 2220 | |
| 2221 | @classmethod |
| 2222 | def CodereviewServerConfigKey(cls): |
| 2223 | return 'gerritserver' |
| 2224 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 2225 | def EnsureAuthenticated(self, force, refresh=None): |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2226 | """Best effort check that user is authenticated with Gerrit server.""" |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 2227 | if settings.GetGerritSkipEnsureAuthenticated(): |
| 2228 | # For projects with unusual authentication schemes. |
| 2229 | # See http://crbug.com/603378. |
| 2230 | return |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 2231 | |
| 2232 | # Check presence of cookies only if using cookies-based auth method. |
| 2233 | cookie_auth = gerrit_util.Authenticator.get() |
| 2234 | if not isinstance(cookie_auth, gerrit_util.CookiesAuthenticator): |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2235 | return |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 2236 | |
| 2237 | # Lazy-loader to identify Gerrit and Git hosts. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2238 | self.GetCodereviewServer() |
| 2239 | git_host = self._GetGitHost() |
| 2240 | assert self._gerrit_server and self._gerrit_host |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2241 | |
| 2242 | gerrit_auth = cookie_auth.get_auth_header(self._gerrit_host) |
| 2243 | git_auth = cookie_auth.get_auth_header(git_host) |
| 2244 | if gerrit_auth and git_auth: |
| 2245 | if gerrit_auth == git_auth: |
| 2246 | return |
Andrii Shyshkalov | 354e1d2 | 2017-06-09 19:31:33 +0200 | [diff] [blame] | 2247 | all_gsrc = cookie_auth.get_auth_header('d0esN0tEx1st.googlesource.com') |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2248 | print(( |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2249 | 'WARNING: You have different credentials for Gerrit and git hosts:\n' |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2250 | ' %s\n' |
| 2251 | ' %s\n' |
Andrii Shyshkalov | 51acef9 | 2017-04-11 17:19:59 +0200 | [diff] [blame] | 2252 | ' Consider running the following command:\n' |
| 2253 | ' git cl creds-check\n' |
Andrii Shyshkalov | 354e1d2 | 2017-06-09 19:31:33 +0200 | [diff] [blame] | 2254 | ' %s\n' |
Andrii Shyshkalov | 8e4576f | 2017-05-10 15:46:53 +0200 | [diff] [blame] | 2255 | ' %s') % |
Andrii Shyshkalov | 51acef9 | 2017-04-11 17:19:59 +0200 | [diff] [blame] | 2256 | (git_host, self._gerrit_host, |
Andrii Shyshkalov | 354e1d2 | 2017-06-09 19:31:33 +0200 | [diff] [blame] | 2257 | ('Hint: delete creds for .googlesource.com' if all_gsrc else ''), |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2258 | cookie_auth.get_new_password_message(git_host))) |
| 2259 | if not force: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2260 | confirm_or_exit('If you know what you are doing', action='continue') |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2261 | return |
| 2262 | else: |
| 2263 | missing = ( |
Anna Henningsen | 4e89144 | 2017-07-06 21:40:58 +0200 | [diff] [blame] | 2264 | ([] if gerrit_auth else [self._gerrit_host]) + |
| 2265 | ([] if git_auth else [git_host])) |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2266 | DieWithError('Credentials for the following hosts are required:\n' |
| 2267 | ' %s\n' |
| 2268 | 'These are read from %s (or legacy %s)\n' |
| 2269 | '%s' % ( |
| 2270 | '\n '.join(missing), |
| 2271 | cookie_auth.get_gitcookies_path(), |
| 2272 | cookie_auth.get_netrc_path(), |
| 2273 | cookie_auth.get_new_password_message(git_host))) |
| 2274 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2275 | def EnsureCanUploadPatchset(self, force): |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 2276 | if not self.GetIssue(): |
| 2277 | return |
| 2278 | |
| 2279 | # Warm change details cache now to avoid RPCs later, reducing latency for |
| 2280 | # developers. |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2281 | self._GetChangeDetail( |
Andrii Shyshkalov | c4a7356 | 2018-09-25 18:40:17 +0000 | [diff] [blame] | 2282 | ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS']) |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 2283 | |
| 2284 | status = self._GetChangeDetail()['status'] |
| 2285 | if status in ('MERGED', 'ABANDONED'): |
| 2286 | DieWithError('Change %s has been %s, new uploads are not allowed' % |
| 2287 | (self.GetIssueURL(), |
| 2288 | 'submitted' if status == 'MERGED' else 'abandoned')) |
| 2289 | |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 2290 | # TODO(vadimsh): For some reason the chunk of code below was skipped if |
| 2291 | # 'is_gce' is True. I'm just refactoring it to be 'skip if not cookies'. |
| 2292 | # Apparently this check is not very important? Otherwise get_auth_email |
| 2293 | # could have been added to other implementations of Authenticator. |
| 2294 | cookies_auth = gerrit_util.Authenticator.get() |
| 2295 | if not isinstance(cookies_auth, gerrit_util.CookiesAuthenticator): |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2296 | return |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 2297 | |
| 2298 | cookies_user = cookies_auth.get_auth_email(self._GetGerritHost()) |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2299 | if self.GetIssueOwner() == cookies_user: |
| 2300 | return |
| 2301 | logging.debug('change %s owner is %s, cookies user is %s', |
| 2302 | self.GetIssue(), self.GetIssueOwner(), cookies_user) |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2303 | # Maybe user has linked accounts or something like that, |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2304 | # so ask what Gerrit thinks of this user. |
| 2305 | details = gerrit_util.GetAccountDetails(self._GetGerritHost(), 'self') |
| 2306 | if details['email'] == self.GetIssueOwner(): |
| 2307 | return |
| 2308 | if not force: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2309 | print('WARNING: Change %s is owned by %s, but you authenticate to Gerrit ' |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2310 | 'as %s.\n' |
| 2311 | 'Uploading may fail due to lack of permissions.' % |
| 2312 | (self.GetIssue(), self.GetIssueOwner(), details['email'])) |
| 2313 | confirm_or_exit(action='upload') |
| 2314 | |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 2315 | def _PostUnsetIssueProperties(self): |
| 2316 | """Which branch-specific properties to erase when unsetting issue.""" |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2317 | return ['gerritsquashhash'] |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 2318 | |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 2319 | def GetGerritObjForPresubmit(self): |
| 2320 | return presubmit_support.GerritAccessor(self._GetGerritHost()) |
| 2321 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2322 | def GetStatus(self): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2323 | """Apply a rough heuristic to give a simple summary of an issue's review |
| 2324 | or CQ status, assuming adherence to a common workflow. |
| 2325 | |
| 2326 | Returns None if no issue for this branch, or one of the following keywords: |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2327 | * 'error' - error from review tool (including deleted issues) |
| 2328 | * 'unsent' - no reviewers added |
| 2329 | * 'waiting' - waiting for review |
| 2330 | * 'reply' - waiting for uploader to reply to review |
| 2331 | * 'lgtm' - Code-Review label has been set |
| 2332 | * 'commit' - in the commit queue |
| 2333 | * 'closed' - successfully submitted or abandoned |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2334 | """ |
| 2335 | if not self.GetIssue(): |
| 2336 | return None |
| 2337 | |
| 2338 | try: |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2339 | data = self._GetChangeDetail([ |
| 2340 | 'DETAILED_LABELS', 'CURRENT_REVISION', 'SUBMITTABLE']) |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2341 | except (httplib.HTTPException, GerritChangeNotExists): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2342 | return 'error' |
| 2343 | |
tandrii@chromium.org | 5e1bf38 | 2016-05-17 08:43:24 +0000 | [diff] [blame] | 2344 | if data['status'] in ('ABANDONED', 'MERGED'): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2345 | return 'closed' |
| 2346 | |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2347 | if data['labels'].get('Commit-Queue', {}).get('approved'): |
| 2348 | # The section will have an "approved" subsection if anyone has voted |
| 2349 | # the maximum value on the label. |
| 2350 | return 'commit' |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2351 | |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2352 | if data['labels'].get('Code-Review', {}).get('approved'): |
| 2353 | return 'lgtm' |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2354 | |
| 2355 | if not data.get('reviewers', {}).get('REVIEWER', []): |
| 2356 | return 'unsent' |
| 2357 | |
Andrii Shyshkalov | 33e88a4 | 2017-01-27 14:45:30 +0100 | [diff] [blame] | 2358 | owner = data['owner'].get('_account_id') |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2359 | messages = sorted(data.get('messages', []), key=lambda m: m.get('updated')) |
| 2360 | last_message_author = messages.pop().get('author', {}) |
| 2361 | while last_message_author: |
Andrii Shyshkalov | 33e88a4 | 2017-01-27 14:45:30 +0100 | [diff] [blame] | 2362 | if last_message_author.get('email') == COMMIT_BOT_EMAIL: |
| 2363 | # Ignore replies from CQ. |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2364 | last_message_author = messages.pop().get('author', {}) |
Andrii Shyshkalov | 33e88a4 | 2017-01-27 14:45:30 +0100 | [diff] [blame] | 2365 | continue |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2366 | if last_message_author.get('_account_id') == owner: |
| 2367 | # Most recent message was by owner. |
| 2368 | return 'waiting' |
| 2369 | else: |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2370 | # Some reply from non-owner. |
| 2371 | return 'reply' |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2372 | |
| 2373 | # Somehow there are no messages even though there are reviewers. |
| 2374 | return 'unsent' |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2375 | |
| 2376 | def GetMostRecentPatchset(self): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2377 | data = self._GetChangeDetail(['CURRENT_REVISION']) |
Aaron Gable | e8856ee | 2017-12-07 12:41:46 -0800 | [diff] [blame] | 2378 | patchset = data['revisions'][data['current_revision']]['_number'] |
| 2379 | self.SetPatchset(patchset) |
| 2380 | return patchset |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2381 | |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 2382 | def FetchDescription(self, force=False): |
| 2383 | data = self._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'], |
| 2384 | no_cache=force) |
tandrii@chromium.org | 2d3da63 | 2016-04-25 19:23:27 +0000 | [diff] [blame] | 2385 | current_rev = data['current_revision'] |
Andrii Shyshkalov | 9c3a464 | 2017-01-24 17:41:22 +0100 | [diff] [blame] | 2386 | return data['revisions'][current_rev]['commit']['message'] |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2387 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 2388 | def UpdateDescriptionRemote(self, description, force=False): |
Andrii Shyshkalov | 889677c | 2018-08-28 20:43:06 +0000 | [diff] [blame] | 2389 | if gerrit_util.HasPendingChangeEdit( |
| 2390 | self._GetGerritHost(), self._GerritChangeIdentifier()): |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 2391 | if not force: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2392 | confirm_or_exit( |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 2393 | 'The description cannot be modified while the issue has a pending ' |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2394 | 'unpublished edit. Either publish the edit in the Gerrit web UI ' |
| 2395 | 'or delete it.\n\n', action='delete the unpublished edit') |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 2396 | |
Andrii Shyshkalov | 889677c | 2018-08-28 20:43:06 +0000 | [diff] [blame] | 2397 | gerrit_util.DeletePendingChangeEdit( |
| 2398 | self._GetGerritHost(), self._GerritChangeIdentifier()) |
| 2399 | gerrit_util.SetCommitMessage( |
| 2400 | self._GetGerritHost(), self._GerritChangeIdentifier(), |
| 2401 | description, notify='NONE') |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2402 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 2403 | def AddComment(self, message, publish=None): |
Andrii Shyshkalov | 889677c | 2018-08-28 20:43:06 +0000 | [diff] [blame] | 2404 | gerrit_util.SetReview( |
| 2405 | self._GetGerritHost(), self._GerritChangeIdentifier(), |
| 2406 | msg=message, ready=publish) |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 2407 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2408 | def GetCommentsSummary(self, readable=True): |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2409 | # DETAILED_ACCOUNTS is to get emails in accounts. |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2410 | messages = self._GetChangeDetail( |
| 2411 | options=['MESSAGES', 'DETAILED_ACCOUNTS']).get('messages', []) |
| 2412 | file_comments = gerrit_util.GetChangeComments( |
Andrii Shyshkalov | 889677c | 2018-08-28 20:43:06 +0000 | [diff] [blame] | 2413 | self._GetGerritHost(), self._GerritChangeIdentifier()) |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2414 | |
| 2415 | # Build dictionary of file comments for easy access and sorting later. |
| 2416 | # {author+date: {path: {patchset: {line: url+message}}}} |
| 2417 | comments = collections.defaultdict( |
| 2418 | lambda: collections.defaultdict(lambda: collections.defaultdict(dict))) |
| 2419 | for path, line_comments in file_comments.iteritems(): |
| 2420 | for comment in line_comments: |
| 2421 | if comment.get('tag', '').startswith('autogenerated'): |
| 2422 | continue |
| 2423 | key = (comment['author']['email'], comment['updated']) |
| 2424 | if comment.get('side', 'REVISION') == 'PARENT': |
| 2425 | patchset = 'Base' |
| 2426 | else: |
| 2427 | patchset = 'PS%d' % comment['patch_set'] |
| 2428 | line = comment.get('line', 0) |
| 2429 | url = ('https://%s/c/%s/%s/%s#%s%s' % |
| 2430 | (self._GetGerritHost(), self.GetIssue(), comment['patch_set'], path, |
| 2431 | 'b' if comment.get('side') == 'PARENT' else '', |
| 2432 | str(line) if line else '')) |
| 2433 | comments[key][path][patchset][line] = (url, comment['message']) |
| 2434 | |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2435 | summary = [] |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2436 | for msg in messages: |
| 2437 | # Don't bother showing autogenerated messages. |
| 2438 | if msg.get('tag') and msg.get('tag').startswith('autogenerated'): |
| 2439 | continue |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2440 | # Gerrit spits out nanoseconds. |
| 2441 | assert len(msg['date'].split('.')[-1]) == 9 |
| 2442 | date = datetime.datetime.strptime(msg['date'][:-3], |
| 2443 | '%Y-%m-%d %H:%M:%S.%f') |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2444 | message = msg['message'] |
| 2445 | key = (msg['author']['email'], msg['date']) |
| 2446 | if key in comments: |
| 2447 | message += '\n' |
| 2448 | for path, patchsets in sorted(comments.get(key, {}).items()): |
| 2449 | if readable: |
| 2450 | message += '\n%s' % path |
| 2451 | for patchset, lines in sorted(patchsets.items()): |
| 2452 | for line, (url, content) in sorted(lines.items()): |
| 2453 | if line: |
| 2454 | line_str = 'Line %d' % line |
| 2455 | path_str = '%s:%d:' % (path, line) |
| 2456 | else: |
| 2457 | line_str = 'File comment' |
| 2458 | path_str = '%s:0:' % path |
| 2459 | if readable: |
| 2460 | message += '\n %s, %s: %s' % (patchset, line_str, url) |
| 2461 | message += '\n %s\n' % content |
| 2462 | else: |
| 2463 | message += '\n%s ' % path_str |
| 2464 | message += '\n%s\n' % content |
| 2465 | |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2466 | summary.append(_CommentSummary( |
| 2467 | date=date, |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2468 | message=message, |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2469 | sender=msg['author']['email'], |
| 2470 | # These could be inferred from the text messages and correlated with |
| 2471 | # Code-Review label maximum, however this is not reliable. |
| 2472 | # Leaving as is until the need arises. |
| 2473 | approval=False, |
| 2474 | disapproval=False, |
| 2475 | )) |
| 2476 | return summary |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 2477 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2478 | def CloseIssue(self): |
Andrii Shyshkalov | 889677c | 2018-08-28 20:43:06 +0000 | [diff] [blame] | 2479 | gerrit_util.AbandonChange( |
| 2480 | self._GetGerritHost(), self._GerritChangeIdentifier(), msg='') |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2481 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2482 | def SubmitIssue(self, wait_for_merge=True): |
Andrii Shyshkalov | 889677c | 2018-08-28 20:43:06 +0000 | [diff] [blame] | 2483 | gerrit_util.SubmitChange( |
| 2484 | self._GetGerritHost(), self._GerritChangeIdentifier(), |
| 2485 | wait_for_merge=wait_for_merge) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2486 | |
Andrii Shyshkalov | b721460 | 2018-08-22 23:20:26 +0000 | [diff] [blame] | 2487 | def _GetChangeDetail(self, options=None, no_cache=False): |
| 2488 | """Returns details of associated Gerrit change and caching results. |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2489 | |
| 2490 | If fresh data is needed, set no_cache=True which will clear cache and |
| 2491 | thus new data will be fetched from Gerrit. |
| 2492 | """ |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2493 | options = options or [] |
Andrii Shyshkalov | 03e0ed2 | 2018-08-28 19:39:30 +0000 | [diff] [blame] | 2494 | assert self.GetIssue(), 'issue is required to query Gerrit' |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2495 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 2496 | # Optimization to avoid multiple RPCs: |
| 2497 | if (('CURRENT_REVISION' in options or 'ALL_REVISIONS' in options) and |
| 2498 | 'CURRENT_COMMIT' not in options): |
| 2499 | options.append('CURRENT_COMMIT') |
| 2500 | |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2501 | # Normalize issue and options for consistent keys in cache. |
Andrii Shyshkalov | 03e0ed2 | 2018-08-28 19:39:30 +0000 | [diff] [blame] | 2502 | cache_key = str(self.GetIssue()) |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2503 | options = [o.upper() for o in options] |
| 2504 | |
| 2505 | # Check in cache first unless no_cache is True. |
| 2506 | if no_cache: |
Andrii Shyshkalov | 03e0ed2 | 2018-08-28 19:39:30 +0000 | [diff] [blame] | 2507 | self._detail_cache.pop(cache_key, None) |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2508 | else: |
| 2509 | options_set = frozenset(options) |
Andrii Shyshkalov | 03e0ed2 | 2018-08-28 19:39:30 +0000 | [diff] [blame] | 2510 | for cached_options_set, data in self._detail_cache.get(cache_key, []): |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2511 | # Assumption: data fetched before with extra options is suitable |
| 2512 | # for return for a smaller set of options. |
| 2513 | # For example, if we cached data for |
| 2514 | # options=[CURRENT_REVISION, DETAILED_FOOTERS] |
| 2515 | # and request is for options=[CURRENT_REVISION], |
| 2516 | # THEN we can return prior cached data. |
| 2517 | if options_set.issubset(cached_options_set): |
| 2518 | return data |
| 2519 | |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 20:51:20 +0100 | [diff] [blame] | 2520 | try: |
Andrii Shyshkalov | 03e0ed2 | 2018-08-28 19:39:30 +0000 | [diff] [blame] | 2521 | data = gerrit_util.GetChangeDetail( |
| 2522 | self._GetGerritHost(), self._GerritChangeIdentifier(), options) |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 20:51:20 +0100 | [diff] [blame] | 2523 | except gerrit_util.GerritError as e: |
| 2524 | if e.http_status == 404: |
Andrii Shyshkalov | 03e0ed2 | 2018-08-28 19:39:30 +0000 | [diff] [blame] | 2525 | raise GerritChangeNotExists(self.GetIssue(), self.GetCodereviewServer()) |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 20:51:20 +0100 | [diff] [blame] | 2526 | raise |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2527 | |
Andrii Shyshkalov | 03e0ed2 | 2018-08-28 19:39:30 +0000 | [diff] [blame] | 2528 | self._detail_cache.setdefault(cache_key, []).append( |
| 2529 | (frozenset(options), data)) |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 2530 | return data |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2531 | |
Andrii Shyshkalov | cc5f17e | 2018-08-22 23:35:59 +0000 | [diff] [blame] | 2532 | def _GetChangeCommit(self): |
Andrii Shyshkalov | e263316 | 2018-08-27 23:50:31 +0000 | [diff] [blame] | 2533 | assert self.GetIssue(), 'issue must be set to query Gerrit' |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 2534 | try: |
Andrii Shyshkalov | e263316 | 2018-08-27 23:50:31 +0000 | [diff] [blame] | 2535 | data = gerrit_util.GetChangeCommit( |
| 2536 | self._GetGerritHost(), self._GerritChangeIdentifier()) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 2537 | except gerrit_util.GerritError as e: |
| 2538 | if e.http_status == 404: |
Andrii Shyshkalov | e263316 | 2018-08-27 23:50:31 +0000 | [diff] [blame] | 2539 | raise GerritChangeNotExists(self.GetIssue(), self.GetCodereviewServer()) |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 2540 | raise |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 2541 | return data |
| 2542 | |
Olivier Robin | 75ee725 | 2018-04-13 10:02:56 +0200 | [diff] [blame] | 2543 | def CMDLand(self, force, bypass_hooks, verbose, parallel): |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2544 | if git_common.is_dirty_git_tree('land'): |
| 2545 | return 1 |
tandrii | d60367b | 2016-06-22 05:25:12 -0700 | [diff] [blame] | 2546 | detail = self._GetChangeDetail(['CURRENT_REVISION', 'LABELS']) |
| 2547 | if u'Commit-Queue' in detail.get('labels', {}): |
| 2548 | if not force: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2549 | confirm_or_exit('\nIt seems this repository has a Commit Queue, ' |
| 2550 | 'which can test and land changes for you. ' |
| 2551 | 'Are you sure you wish to bypass it?\n', |
| 2552 | action='bypass CQ') |
tandrii | d60367b | 2016-06-22 05:25:12 -0700 | [diff] [blame] | 2553 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2554 | differs = True |
tandrii | c4344b5 | 2016-08-29 06:04:54 -0700 | [diff] [blame] | 2555 | last_upload = self._GitGetBranchConfigValue('gerritsquashhash') |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2556 | # Note: git diff outputs nothing if there is no diff. |
| 2557 | if not last_upload or RunGit(['diff', last_upload]).strip(): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2558 | print('WARNING: Some changes from local branch haven\'t been uploaded.') |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2559 | else: |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2560 | if detail['current_revision'] == last_upload: |
| 2561 | differs = False |
| 2562 | else: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2563 | print('WARNING: Local branch contents differ from latest uploaded ' |
| 2564 | 'patchset.') |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2565 | if differs: |
| 2566 | if not force: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2567 | confirm_or_exit( |
| 2568 | 'Do you want to submit latest Gerrit patchset and bypass hooks?\n', |
| 2569 | action='submit') |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2570 | print('WARNING: Bypassing hooks and submitting latest uploaded patchset.') |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2571 | elif not bypass_hooks: |
| 2572 | hook_results = self.RunHook( |
| 2573 | committing=True, |
| 2574 | may_prompt=not force, |
| 2575 | verbose=verbose, |
Olivier Robin | 75ee725 | 2018-04-13 10:02:56 +0200 | [diff] [blame] | 2576 | change=self.GetChange(self.GetCommonAncestorWithUpstream(), None), |
| 2577 | parallel=parallel) |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2578 | if not hook_results.should_continue(): |
| 2579 | return 1 |
| 2580 | |
| 2581 | self.SubmitIssue(wait_for_merge=True) |
| 2582 | print('Issue %s has been submitted.' % self.GetIssueURL()) |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 2583 | links = self._GetChangeCommit().get('web_links', []) |
| 2584 | for link in links: |
Aaron Gable | 02cdbb4 | 2016-12-13 16:24:25 -0800 | [diff] [blame] | 2585 | if link.get('name') == 'gitiles' and link.get('url'): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2586 | print('Landed as: %s' % link.get('url')) |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 2587 | break |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2588 | return 0 |
| 2589 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2590 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 2591 | directory, force): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2592 | assert not reject |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2593 | assert not directory |
| 2594 | assert parsed_issue_arg.valid |
| 2595 | |
| 2596 | self._changelist.issue = parsed_issue_arg.issue |
| 2597 | |
| 2598 | if parsed_issue_arg.hostname: |
| 2599 | self._gerrit_host = parsed_issue_arg.hostname |
| 2600 | self._gerrit_server = 'https://%s' % self._gerrit_host |
| 2601 | |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 2602 | try: |
| 2603 | detail = self._GetChangeDetail(['ALL_REVISIONS']) |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2604 | except GerritChangeNotExists as e: |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 2605 | DieWithError(str(e)) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2606 | |
| 2607 | if not parsed_issue_arg.patchset: |
| 2608 | # Use current revision by default. |
| 2609 | revision_info = detail['revisions'][detail['current_revision']] |
| 2610 | patchset = int(revision_info['_number']) |
| 2611 | else: |
| 2612 | patchset = parsed_issue_arg.patchset |
| 2613 | for revision_info in detail['revisions'].itervalues(): |
| 2614 | if int(revision_info['_number']) == parsed_issue_arg.patchset: |
| 2615 | break |
| 2616 | else: |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2617 | DieWithError('Couldn\'t find patchset %i in change %i' % |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2618 | (parsed_issue_arg.patchset, self.GetIssue())) |
| 2619 | |
Aaron Gable | 697a91b | 2018-01-19 15:20:15 -0800 | [diff] [blame] | 2620 | remote_url = self._changelist.GetRemoteUrl() |
| 2621 | if remote_url.endswith('.git'): |
| 2622 | remote_url = remote_url[:-len('.git')] |
erikchen | 0d14d0d | 2018-08-28 18:57:09 +0000 | [diff] [blame] | 2623 | remote_url = remote_url.rstrip('/') |
| 2624 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2625 | fetch_info = revision_info['fetch']['http'] |
erikchen | 0d14d0d | 2018-08-28 18:57:09 +0000 | [diff] [blame] | 2626 | fetch_info['url'] = fetch_info['url'].rstrip('/') |
Aaron Gable | 697a91b | 2018-01-19 15:20:15 -0800 | [diff] [blame] | 2627 | |
| 2628 | if remote_url != fetch_info['url']: |
| 2629 | DieWithError('Trying to patch a change from %s but this repo appears ' |
| 2630 | 'to be %s.' % (fetch_info['url'], remote_url)) |
| 2631 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2632 | RunGit(['fetch', fetch_info['url'], fetch_info['ref']]) |
Aaron Gable | 9387b4f | 2017-06-08 10:50:03 -0700 | [diff] [blame] | 2633 | |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 2634 | if force: |
| 2635 | RunGit(['reset', '--hard', 'FETCH_HEAD']) |
| 2636 | print('Checked out commit for change %i patchset %i locally' % |
| 2637 | (parsed_issue_arg.issue, patchset)) |
Stefan Zager | 2d5f039 | 2017-10-10 15:17:53 -0700 | [diff] [blame] | 2638 | elif nocommit: |
| 2639 | RunGit(['cherry-pick', '--no-commit', 'FETCH_HEAD']) |
| 2640 | print('Patch applied to index.') |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 2641 | else: |
Aaron Gable | 9387b4f | 2017-06-08 10:50:03 -0700 | [diff] [blame] | 2642 | RunGit(['cherry-pick', 'FETCH_HEAD']) |
| 2643 | print('Committed patch for change %i patchset %i locally.' % |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 2644 | (parsed_issue_arg.issue, patchset)) |
| 2645 | print('Note: this created a local commit which does not have ' |
| 2646 | 'the same hash as the one uploaded for review. This will make ' |
| 2647 | 'uploading changes based on top of this branch difficult.\n' |
| 2648 | 'If you want to do that, use "git cl patch --force" instead.') |
| 2649 | |
Stefan Zager | d08043c | 2017-10-12 12:07:02 -0700 | [diff] [blame] | 2650 | if self.GetBranch(): |
| 2651 | self.SetIssue(parsed_issue_arg.issue) |
| 2652 | self.SetPatchset(patchset) |
| 2653 | fetched_hash = RunGit(['rev-parse', 'FETCH_HEAD']).strip() |
| 2654 | self._GitSetBranchConfigValue('last-upload-hash', fetched_hash) |
| 2655 | self._GitSetBranchConfigValue('gerritsquashhash', fetched_hash) |
| 2656 | else: |
| 2657 | print('WARNING: You are in detached HEAD state.\n' |
| 2658 | 'The patch has been applied to your checkout, but you will not be ' |
| 2659 | 'able to upload a new patch set to the gerrit issue.\n' |
| 2660 | 'Try using the \'-b\' option if you would like to work on a ' |
| 2661 | 'branch and/or upload a new patch set.') |
| 2662 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2663 | return 0 |
| 2664 | |
| 2665 | @staticmethod |
| 2666 | def ParseIssueURL(parsed_url): |
| 2667 | if not parsed_url.scheme or not parsed_url.scheme.startswith('http'): |
| 2668 | return None |
Aaron Gable | 01b9106 | 2017-08-24 17:48:40 -0700 | [diff] [blame] | 2669 | # Gerrit's new UI is https://domain/c/project/+/<issue_number>[/[patchset]] |
| 2670 | # But old GWT UI is https://domain/#/c/project/+/<issue_number>[/[patchset]] |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2671 | # Short urls like https://domain/<issue_number> can be used, but don't allow |
| 2672 | # specifying the patchset (you'd 404), but we allow that here. |
| 2673 | if parsed_url.path == '/': |
| 2674 | part = parsed_url.fragment |
| 2675 | else: |
| 2676 | part = parsed_url.path |
Aaron Gable | 01b9106 | 2017-08-24 17:48:40 -0700 | [diff] [blame] | 2677 | match = re.match('(/c(/.*/\+)?)?/(\d+)(/(\d+)?/?)?$', part) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2678 | if match: |
| 2679 | return _ParsedIssueNumberArgument( |
Aaron Gable | 01b9106 | 2017-08-24 17:48:40 -0700 | [diff] [blame] | 2680 | issue=int(match.group(3)), |
| 2681 | patchset=int(match.group(5)) if match.group(5) else None, |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 2682 | hostname=parsed_url.netloc, |
| 2683 | codereview='gerrit') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2684 | return None |
| 2685 | |
tandrii | 16e0b4e | 2016-06-07 10:34:28 -0700 | [diff] [blame] | 2686 | def _GerritCommitMsgHookCheck(self, offer_removal): |
| 2687 | hook = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg') |
| 2688 | if not os.path.exists(hook): |
| 2689 | return |
| 2690 | # Crude attempt to distinguish Gerrit Codereview hook from potentially |
| 2691 | # custom developer made one. |
| 2692 | data = gclient_utils.FileRead(hook) |
| 2693 | if not('From Gerrit Code Review' in data and 'add_ChangeId()' in data): |
| 2694 | return |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2695 | print('WARNING: You have Gerrit commit-msg hook installed.\n' |
qyearsley | 12fa6ff | 2016-08-24 09:18:40 -0700 | [diff] [blame] | 2696 | 'It is not necessary for uploading with git cl in squash mode, ' |
tandrii | 16e0b4e | 2016-06-07 10:34:28 -0700 | [diff] [blame] | 2697 | 'and may interfere with it in subtle ways.\n' |
| 2698 | 'We recommend you remove the commit-msg hook.') |
| 2699 | if offer_removal: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2700 | if ask_for_explicit_yes('Do you want to remove it now?'): |
tandrii | 16e0b4e | 2016-06-07 10:34:28 -0700 | [diff] [blame] | 2701 | gclient_utils.rm_file_or_tree(hook) |
| 2702 | print('Gerrit commit-msg hook removed.') |
| 2703 | else: |
| 2704 | print('OK, will keep Gerrit commit-msg hook in place.') |
| 2705 | |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2706 | def CMDUploadChange(self, options, git_diff_args, custom_cl_base, change): |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2707 | """Upload the current branch to Gerrit.""" |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2708 | if options.squash and options.no_squash: |
| 2709 | DieWithError('Can only use one of --squash or --no-squash') |
tandrii | a60502f | 2016-06-20 02:01:53 -0700 | [diff] [blame] | 2710 | |
| 2711 | if not options.squash and not options.no_squash: |
| 2712 | # Load default for user, repo, squash=true, in this order. |
| 2713 | options.squash = settings.GetSquashGerritUploads() |
| 2714 | elif options.no_squash: |
| 2715 | options.squash = False |
tandrii | 26f3e4e | 2016-06-10 08:37:04 -0700 | [diff] [blame] | 2716 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2717 | remote, remote_branch = self.GetRemoteBranch() |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 2718 | branch = GetTargetRef(remote, remote_branch, options.target_branch) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2719 | |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2720 | # This may be None; default fallback value is determined in logic below. |
| 2721 | title = options.title |
| 2722 | |
Dominic Battre | 7d1c484 | 2017-10-27 09:17:28 +0200 | [diff] [blame] | 2723 | # Extract bug number from branch name. |
| 2724 | bug = options.bug |
| 2725 | match = re.match(r'(?:bug|fix)[_-]?(\d+)', self.GetBranch()) |
| 2726 | if not bug and match: |
| 2727 | bug = match.group(1) |
| 2728 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2729 | if options.squash: |
tandrii | 16e0b4e | 2016-06-07 10:34:28 -0700 | [diff] [blame] | 2730 | self._GerritCommitMsgHookCheck(offer_removal=not options.force) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2731 | if self.GetIssue(): |
| 2732 | # Try to get the message from a previous upload. |
| 2733 | message = self.GetDescription() |
| 2734 | if not message: |
| 2735 | DieWithError( |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2736 | 'failed to fetch description from current Gerrit change %d\n' |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2737 | '%s' % (self.GetIssue(), self.GetIssueURL())) |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2738 | if not title: |
Andrii Shyshkalov | 2d8a207 | 2017-04-10 15:02:18 +0200 | [diff] [blame] | 2739 | if options.message: |
Aaron Gable | 7303dcb | 2017-06-07 14:17:32 -0700 | [diff] [blame] | 2740 | # When uploading a subsequent patchset, -m|--message is taken |
| 2741 | # as the patchset title if --title was not provided. |
| 2742 | title = options.message.strip() |
Andrii Shyshkalov | 2d8a207 | 2017-04-10 15:02:18 +0200 | [diff] [blame] | 2743 | else: |
| 2744 | default_title = RunGit( |
| 2745 | ['show', '-s', '--format=%s', 'HEAD']).strip() |
Aaron Gable | 7303dcb | 2017-06-07 14:17:32 -0700 | [diff] [blame] | 2746 | if options.force: |
| 2747 | title = default_title |
| 2748 | else: |
| 2749 | title = ask_for_data( |
| 2750 | 'Title for patchset [%s]: ' % default_title) or default_title |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2751 | change_id = self._GetChangeDetail()['change_id'] |
| 2752 | while True: |
| 2753 | footer_change_ids = git_footers.get_footer_change_id(message) |
| 2754 | if footer_change_ids == [change_id]: |
| 2755 | break |
| 2756 | if not footer_change_ids: |
| 2757 | message = git_footers.add_footer_change_id(message, change_id) |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2758 | print('WARNING: appended missing Change-Id to change description.') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2759 | continue |
| 2760 | # There is already a valid footer but with different or several ids. |
| 2761 | # Doing this automatically is non-trivial as we don't want to lose |
| 2762 | # existing other footers, yet we want to append just 1 desired |
| 2763 | # Change-Id. Thus, just create a new footer, but let user verify the |
| 2764 | # new description. |
| 2765 | message = '%s\n\nChange-Id: %s' % (message, change_id) |
| 2766 | print( |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2767 | 'WARNING: change %s has Change-Id footer(s):\n' |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2768 | ' %s\n' |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2769 | 'but change has Change-Id %s, according to Gerrit.\n' |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2770 | 'Please, check the proposed correction to the description, ' |
| 2771 | 'and edit it if necessary but keep the "Change-Id: %s" footer\n' |
| 2772 | % (self.GetIssue(), '\n '.join(footer_change_ids), change_id, |
| 2773 | change_id)) |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2774 | confirm_or_exit(action='edit') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2775 | if not options.force: |
| 2776 | change_desc = ChangeDescription(message) |
Dominic Battre | 7d1c484 | 2017-10-27 09:17:28 +0200 | [diff] [blame] | 2777 | change_desc.prompt(bug=bug) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2778 | message = change_desc.description |
| 2779 | if not message: |
| 2780 | DieWithError("Description is empty. Aborting...") |
| 2781 | # Continue the while loop. |
| 2782 | # Sanity check of this code - we should end up with proper message |
| 2783 | # footer. |
| 2784 | assert [change_id] == git_footers.get_footer_change_id(message) |
| 2785 | change_desc = ChangeDescription(message) |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2786 | else: # if not self.GetIssue() |
| 2787 | if options.message: |
| 2788 | message = options.message |
| 2789 | else: |
Andrii Shyshkalov | b07575f | 2018-10-16 06:16:21 +0000 | [diff] [blame] | 2790 | message = _create_description_from_log(git_diff_args) |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2791 | if options.title: |
| 2792 | message = options.title + '\n\n' + message |
| 2793 | change_desc = ChangeDescription(message) |
Andrii Shyshkalov | 8c90d03 | 2017-04-19 21:27:26 +0200 | [diff] [blame] | 2794 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2795 | if not options.force: |
Dominic Battre | 7d1c484 | 2017-10-27 09:17:28 +0200 | [diff] [blame] | 2796 | change_desc.prompt(bug=bug) |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2797 | # On first upload, patchset title is always this string, while |
| 2798 | # --title flag gets converted to first line of message. |
| 2799 | title = 'Initial upload' |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2800 | if not change_desc.description: |
| 2801 | DieWithError("Description is empty. Aborting...") |
Andrii Shyshkalov | 8c90d03 | 2017-04-19 21:27:26 +0200 | [diff] [blame] | 2802 | change_ids = git_footers.get_footer_change_id(change_desc.description) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2803 | if len(change_ids) > 1: |
| 2804 | DieWithError('too many Change-Id footers, at most 1 allowed.') |
| 2805 | if not change_ids: |
| 2806 | # Generate the Change-Id automatically. |
Andrii Shyshkalov | 8c90d03 | 2017-04-19 21:27:26 +0200 | [diff] [blame] | 2807 | change_desc.set_description(git_footers.add_footer_change_id( |
| 2808 | change_desc.description, |
| 2809 | GenerateGerritChangeId(change_desc.description))) |
| 2810 | change_ids = git_footers.get_footer_change_id(change_desc.description) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2811 | assert len(change_ids) == 1 |
| 2812 | change_id = change_ids[0] |
| 2813 | |
Robert Iannucci | db02dd0 | 2017-04-19 12:18:20 -0700 | [diff] [blame] | 2814 | if options.reviewers or options.tbrs or options.add_owners_to: |
| 2815 | change_desc.update_reviewers(options.reviewers, options.tbrs, |
| 2816 | options.add_owners_to, change) |
| 2817 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2818 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2819 | parent = self._ComputeParent(remote, upstream_branch, custom_cl_base, |
| 2820 | options.force, change_desc) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2821 | tree = RunGit(['rev-parse', 'HEAD:']).strip() |
Aaron Gable | 9a03ae0 | 2017-11-03 11:31:07 -0700 | [diff] [blame] | 2822 | with tempfile.NamedTemporaryFile(delete=False) as desc_tempfile: |
| 2823 | desc_tempfile.write(change_desc.description) |
| 2824 | desc_tempfile.close() |
| 2825 | ref_to_push = RunGit(['commit-tree', tree, '-p', parent, |
| 2826 | '-F', desc_tempfile.name]).strip() |
| 2827 | os.remove(desc_tempfile.name) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2828 | else: |
| 2829 | change_desc = ChangeDescription( |
Andrii Shyshkalov | b07575f | 2018-10-16 06:16:21 +0000 | [diff] [blame] | 2830 | options.message or _create_description_from_log(git_diff_args)) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2831 | if not change_desc.description: |
| 2832 | DieWithError("Description is empty. Aborting...") |
| 2833 | |
| 2834 | if not git_footers.get_footer_change_id(change_desc.description): |
| 2835 | DownloadGerritHook(False) |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2836 | change_desc.set_description( |
| 2837 | self._AddChangeIdToCommitMessage(options, git_diff_args)) |
Robert Iannucci | db02dd0 | 2017-04-19 12:18:20 -0700 | [diff] [blame] | 2838 | if options.reviewers or options.tbrs or options.add_owners_to: |
| 2839 | change_desc.update_reviewers(options.reviewers, options.tbrs, |
| 2840 | options.add_owners_to, change) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2841 | ref_to_push = 'HEAD' |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2842 | # For no-squash mode, we assume the remote called "origin" is the one we |
| 2843 | # want. It is not worthwhile to support different workflows for |
| 2844 | # no-squash mode. |
| 2845 | parent = 'origin/%s' % branch |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2846 | change_id = git_footers.get_footer_change_id(change_desc.description)[0] |
| 2847 | |
| 2848 | assert change_desc |
Andrii Shyshkalov | d9fdc1f | 2018-09-27 02:13:09 +0000 | [diff] [blame] | 2849 | SaveDescriptionBackup(change_desc) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2850 | commits = RunGitSilent(['rev-list', '%s..%s' % (parent, |
| 2851 | ref_to_push)]).splitlines() |
| 2852 | if len(commits) > 1: |
| 2853 | print('WARNING: This will upload %d commits. Run the following command ' |
| 2854 | 'to see which commits will be uploaded: ' % len(commits)) |
| 2855 | print('git log %s..%s' % (parent, ref_to_push)) |
| 2856 | print('You can also use `git squash-branch` to squash these into a ' |
| 2857 | 'single commit.') |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2858 | confirm_or_exit(action='upload') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2859 | |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 2860 | if options.reviewers or options.tbrs or options.add_owners_to: |
| 2861 | change_desc.update_reviewers(options.reviewers, options.tbrs, |
| 2862 | options.add_owners_to, change) |
| 2863 | |
Andrii Shyshkalov | 76988a8 | 2018-10-15 03:12:25 +0000 | [diff] [blame] | 2864 | reviewers = sorted(change_desc.get_reviewers()) |
| 2865 | # Add cc's from the CC_LIST and --cc flag (if any). |
| 2866 | if not options.private and not options.no_autocc: |
| 2867 | cc = self.GetCCList().split(',') |
| 2868 | else: |
| 2869 | cc = [] |
| 2870 | if options.cc: |
| 2871 | cc.extend(options.cc) |
| 2872 | cc = filter(None, [email.strip() for email in cc]) |
| 2873 | if change_desc.get_cced(): |
| 2874 | cc.extend(change_desc.get_cced()) |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 2875 | valid_accounts = gerrit_util.ValidAccounts( |
| 2876 | self._GetGerritHost(), reviewers + cc) |
| 2877 | logging.debug('accounts %s are valid, %s invalid', sorted(valid_accounts), |
| 2878 | set(reviewers + cc).difference(set(valid_accounts))) |
Andrii Shyshkalov | 76988a8 | 2018-10-15 03:12:25 +0000 | [diff] [blame] | 2879 | |
tandrii@chromium.org | bf766ba | 2016-04-13 12:51:23 +0000 | [diff] [blame] | 2880 | # Extra options that can be specified at push time. Doc: |
| 2881 | # https://gerrit-review.googlesource.com/Documentation/user-upload.html |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 2882 | refspec_opts = [] |
Andrii Shyshkalov | 2d8a207 | 2017-04-10 15:02:18 +0200 | [diff] [blame] | 2883 | |
Aaron Gable | 844cf29 | 2017-06-28 11:32:59 -0700 | [diff] [blame] | 2884 | # By default, new changes are started in WIP mode, and subsequent patchsets |
| 2885 | # don't send email. At any time, passing --send-mail will mark the change |
| 2886 | # ready and send email for that particular patch. |
Aaron Gable | afd5277 | 2017-06-27 16:40:10 -0700 | [diff] [blame] | 2887 | if options.send_mail: |
| 2888 | refspec_opts.append('ready') |
Aaron Gable | 844cf29 | 2017-06-28 11:32:59 -0700 | [diff] [blame] | 2889 | refspec_opts.append('notify=ALL') |
Jamie Madill | 276da0b | 2018-04-27 14:41:20 -0400 | [diff] [blame] | 2890 | elif not self.GetIssue() and options.squash: |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 2891 | refspec_opts.append('wip') |
Aaron Gable | afd5277 | 2017-06-27 16:40:10 -0700 | [diff] [blame] | 2892 | else: |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 2893 | refspec_opts.append('notify=NONE') |
Aaron Gable | 70f4e24 | 2017-06-26 10:45:59 -0700 | [diff] [blame] | 2894 | |
Andrii Shyshkalov | 2d8a207 | 2017-04-10 15:02:18 +0200 | [diff] [blame] | 2895 | # TODO(tandrii): options.message should be posted as a comment |
Aaron Gable | e5adf61 | 2017-07-14 10:43:58 -0700 | [diff] [blame] | 2896 | # if --send-mail is set on non-initial upload as Rietveld used to do it. |
Andrii Shyshkalov | 2d8a207 | 2017-04-10 15:02:18 +0200 | [diff] [blame] | 2897 | |
Aaron Gable | 9b713dd | 2016-12-14 16:04:21 -0800 | [diff] [blame] | 2898 | if title: |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame] | 2899 | # Punctuation and whitespace in |title| must be percent-encoded. |
| 2900 | refspec_opts.append('m=' + gerrit_util.PercentEncodeForGitRef(title)) |
tandrii@chromium.org | bf766ba | 2016-04-13 12:51:23 +0000 | [diff] [blame] | 2901 | |
agable | c678797 | 2016-09-09 16:13:34 -0700 | [diff] [blame] | 2902 | if options.private: |
Aaron Gable | b02daf0 | 2017-05-23 11:53:46 -0700 | [diff] [blame] | 2903 | refspec_opts.append('private') |
agable | c678797 | 2016-09-09 16:13:34 -0700 | [diff] [blame] | 2904 | |
Andrii Shyshkalov | 2f72791 | 2018-10-15 17:02:33 +0000 | [diff] [blame] | 2905 | for r in sorted(reviewers): |
| 2906 | if r in valid_accounts: |
| 2907 | refspec_opts.append('r=%s' % r) |
| 2908 | reviewers.remove(r) |
| 2909 | else: |
| 2910 | # TODO(tandrii): this should probably be a hard failure. |
| 2911 | print('WARNING: reviewer %s doesn\'t have a Gerrit account, skipping' |
| 2912 | % r) |
| 2913 | for c in sorted(cc): |
| 2914 | # refspec option will be rejected if cc doesn't correspond to an |
| 2915 | # account, even though REST call to add such arbitrary cc may succeed. |
| 2916 | if c in valid_accounts: |
| 2917 | refspec_opts.append('cc=%s' % c) |
| 2918 | cc.remove(c) |
| 2919 | |
| 2920 | |
rmistry | 9eadede | 2016-09-19 11:22:43 -0700 | [diff] [blame] | 2921 | if options.topic: |
| 2922 | # Documentation on Gerrit topics is here: |
| 2923 | # https://gerrit-review.googlesource.com/Documentation/user-upload.html#topic |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 2924 | refspec_opts.append('topic=%s' % options.topic) |
rmistry | 9eadede | 2016-09-19 11:22:43 -0700 | [diff] [blame] | 2925 | |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 2926 | # Gerrit sorts hashtags, so order is not important. |
Nodir Turakulov | 23b8214 | 2017-11-16 11:04:25 -0800 | [diff] [blame] | 2927 | hashtags = {change_desc.sanitize_hash_tag(t) for t in options.hashtags} |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 2928 | if not self.GetIssue(): |
Nodir Turakulov | 23b8214 | 2017-11-16 11:04:25 -0800 | [diff] [blame] | 2929 | hashtags.update(change_desc.get_hash_tags()) |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 2930 | refspec_opts += ['hashtag=%s' % t for t in sorted(hashtags)] |
| 2931 | |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 2932 | refspec_suffix = '' |
| 2933 | if refspec_opts: |
| 2934 | refspec_suffix = '%' + ','.join(refspec_opts) |
| 2935 | assert ' ' not in refspec_suffix, ( |
| 2936 | 'spaces not allowed in refspec: "%s"' % refspec_suffix) |
| 2937 | refspec = '%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix) |
| 2938 | |
Andrii Shyshkalov | 7d51883 | 2016-12-15 20:48:21 +0100 | [diff] [blame] | 2939 | try: |
Edward Lemur | 83bd7f4 | 2018-10-10 00:14:21 +0000 | [diff] [blame] | 2940 | # TODO(crbug.com/881860): Remove. |
Edward Lemur | 47faa06 | 2018-10-11 19:46:02 +0000 | [diff] [blame] | 2941 | # Clear the log after each git-cl upload run by setting mode='w'. |
| 2942 | handler = logging.FileHandler(gerrit_util.GERRIT_ERR_LOG_FILE, mode='w') |
| 2943 | handler.setFormatter(logging.Formatter('%(asctime)s %(message)s')) |
| 2944 | |
| 2945 | GERRIT_ERR_LOGGER.addHandler(handler) |
| 2946 | GERRIT_ERR_LOGGER.setLevel(logging.INFO) |
| 2947 | # Don't propagate to root logger, so that logs are not printed. |
| 2948 | GERRIT_ERR_LOGGER.propagate = 0 |
| 2949 | |
Edward Lemur | 83bd7f4 | 2018-10-10 00:14:21 +0000 | [diff] [blame] | 2950 | # Get interesting headers from git push, to be displayed to the user if |
| 2951 | # subsequent Gerrit RPC calls fail. |
| 2952 | env = os.environ.copy() |
| 2953 | env['GIT_CURL_VERBOSE'] = '1' |
| 2954 | class FilterHeaders(object): |
| 2955 | """Filter git push headers and store them in a file. |
| 2956 | |
| 2957 | Regular git push output is printed directly. |
| 2958 | """ |
| 2959 | |
| 2960 | def __init__(self): |
| 2961 | # The output from git push that we want to store in a file. |
| 2962 | self._output = '' |
| 2963 | # Keeps track of whether the current line is part of a request header. |
| 2964 | self._on_header = False |
| 2965 | # Keeps track of repeated empty lines, which mark the end of a request |
| 2966 | # header. |
| 2967 | self._last_line_empty = False |
| 2968 | |
| 2969 | def __call__(self, line): |
| 2970 | """Handle a single line of git push output.""" |
| 2971 | if not line: |
| 2972 | # Two consecutive empty lines mark the end of a header. |
| 2973 | if self._last_line_empty: |
| 2974 | self._on_header = False |
| 2975 | self._last_line_empty = True |
| 2976 | return |
| 2977 | |
| 2978 | self._last_line_empty = False |
| 2979 | # A line starting with '>' marks the beggining of a request header. |
| 2980 | if line[0] == '>': |
| 2981 | self._on_header = True |
| 2982 | GERRIT_ERR_LOGGER.info(line) |
| 2983 | # Lines not starting with '*' or '<', and not part of a request header |
| 2984 | # should be displayed to the user. |
| 2985 | elif line[0] not in '*<' and not self._on_header: |
| 2986 | print(line) |
| 2987 | # Flush after every line: useful for seeing progress when running as |
| 2988 | # recipe. |
| 2989 | sys.stdout.flush() |
| 2990 | # Filter out the cookie and authorization headers. |
| 2991 | elif ('cookie: ' not in line.lower() |
| 2992 | and 'authorization: ' not in line.lower()): |
| 2993 | GERRIT_ERR_LOGGER.info(line) |
| 2994 | |
| 2995 | filter_fn = FilterHeaders() |
Andrii Shyshkalov | 7d51883 | 2016-12-15 20:48:21 +0100 | [diff] [blame] | 2996 | push_stdout = gclient_utils.CheckCallAndFilter( |
Andrii Shyshkalov | 81db1d5 | 2018-08-23 02:17:41 +0000 | [diff] [blame] | 2997 | ['git', 'push', self.GetRemoteUrl(), refspec], |
Edward Lemur | 83bd7f4 | 2018-10-10 00:14:21 +0000 | [diff] [blame] | 2998 | print_stdout=False, |
| 2999 | filter_fn=filter_fn, |
| 3000 | env=env) |
Andrii Shyshkalov | 7d51883 | 2016-12-15 20:48:21 +0100 | [diff] [blame] | 3001 | except subprocess2.CalledProcessError: |
| 3002 | DieWithError('Failed to create a change. Please examine output above ' |
Andrii Shyshkalov | 9d93221 | 2017-04-10 14:28:23 +0200 | [diff] [blame] | 3003 | 'for the reason of the failure.\n' |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3004 | 'Hint: run command below to diagnose common Git/Gerrit ' |
Andrii Shyshkalov | 9d93221 | 2017-04-10 14:28:23 +0200 | [diff] [blame] | 3005 | 'credential problems:\n' |
| 3006 | ' git cl creds-check\n', |
| 3007 | change_desc) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3008 | |
| 3009 | if options.squash: |
Aaron Gable | 289b431 | 2017-09-13 14:06:16 -0700 | [diff] [blame] | 3010 | regex = re.compile(r'remote:\s+https?://[\w\-\.\+\/#]*/(\d+)\s.*') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3011 | change_numbers = [m.group(1) |
| 3012 | for m in map(regex.match, push_stdout.splitlines()) |
| 3013 | if m] |
| 3014 | if len(change_numbers) != 1: |
| 3015 | DieWithError( |
| 3016 | ('Created|Updated %d issues on Gerrit, but only 1 expected.\n' |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 3017 | 'Change-Id: %s') % (len(change_numbers), change_id), change_desc) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3018 | self.SetIssue(change_numbers[0]) |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 3019 | self._GitSetBranchConfigValue('gerritsquashhash', ref_to_push) |
tandrii | 8818977 | 2016-09-29 04:29:57 -0700 | [diff] [blame] | 3020 | |
Andrii Shyshkalov | 2f72791 | 2018-10-15 17:02:33 +0000 | [diff] [blame] | 3021 | if self.GetIssue() and (reviewers or cc): |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 3022 | # GetIssue() is not set in case of non-squash uploads according to tests. |
| 3023 | # TODO(agable): non-squash uploads in git cl should be removed. |
| 3024 | gerrit_util.AddReviewers( |
| 3025 | self._GetGerritHost(), |
Andrii Shyshkalov | d06cc78 | 2018-08-23 17:24:19 +0000 | [diff] [blame] | 3026 | self._GerritChangeIdentifier(), |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 3027 | reviewers, cc, |
| 3028 | notify=bool(options.send_mail)) |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 3029 | |
Aaron Gable | fd23808 | 2017-06-07 13:42:34 -0700 | [diff] [blame] | 3030 | if change_desc.get_reviewers(tbr_only=True): |
Yoshisato Yanagisawa | 81e3ff5 | 2017-09-26 15:33:34 +0900 | [diff] [blame] | 3031 | labels = self._GetChangeDetail(['LABELS']).get('labels', {}) |
| 3032 | score = 1 |
| 3033 | if 'Code-Review' in labels and 'values' in labels['Code-Review']: |
| 3034 | score = max([int(x) for x in labels['Code-Review']['values'].keys()]) |
| 3035 | print('Adding self-LGTM (Code-Review +%d) because of TBRs.' % score) |
Aaron Gable | fd23808 | 2017-06-07 13:42:34 -0700 | [diff] [blame] | 3036 | gerrit_util.SetReview( |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 3037 | self._GetGerritHost(), |
Andrii Shyshkalov | d06cc78 | 2018-08-23 17:24:19 +0000 | [diff] [blame] | 3038 | self._GerritChangeIdentifier(), |
Yoshisato Yanagisawa | 81e3ff5 | 2017-09-26 15:33:34 +0900 | [diff] [blame] | 3039 | msg='Self-approving for TBR', |
| 3040 | labels={'Code-Review': score}) |
Aaron Gable | fd23808 | 2017-06-07 13:42:34 -0700 | [diff] [blame] | 3041 | |
Andrii Shyshkalov | dd78844 | 2018-10-13 17:55:29 +0000 | [diff] [blame] | 3042 | self.SetLabels(options.enable_auto_submit, options.use_commit_queue, |
| 3043 | options.cq_dry_run) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3044 | return 0 |
| 3045 | |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 3046 | def _ComputeParent(self, remote, upstream_branch, custom_cl_base, force, |
| 3047 | change_desc): |
| 3048 | """Computes parent of the generated commit to be uploaded to Gerrit. |
| 3049 | |
| 3050 | Returns revision or a ref name. |
| 3051 | """ |
| 3052 | if custom_cl_base: |
| 3053 | # Try to avoid creating additional unintended CLs when uploading, unless |
| 3054 | # user wants to take this risk. |
| 3055 | local_ref_of_target_remote = self.GetRemoteBranch()[1] |
| 3056 | code, _ = RunGitWithCode(['merge-base', '--is-ancestor', custom_cl_base, |
| 3057 | local_ref_of_target_remote]) |
| 3058 | if code == 1: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3059 | print('\nWARNING: Manually specified base of this CL `%s` ' |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 3060 | 'doesn\'t seem to belong to target remote branch `%s`.\n\n' |
| 3061 | 'If you proceed with upload, more than 1 CL may be created by ' |
| 3062 | 'Gerrit as a result, in turn confusing or crashing git cl.\n\n' |
| 3063 | 'If you are certain that specified base `%s` has already been ' |
| 3064 | 'uploaded to Gerrit as another CL, you may proceed.\n' % |
| 3065 | (custom_cl_base, local_ref_of_target_remote, custom_cl_base)) |
| 3066 | if not force: |
| 3067 | confirm_or_exit( |
| 3068 | 'Do you take responsibility for cleaning up potential mess ' |
| 3069 | 'resulting from proceeding with upload?', |
| 3070 | action='upload') |
| 3071 | return custom_cl_base |
| 3072 | |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3073 | if remote != '.': |
| 3074 | return self.GetCommonAncestorWithUpstream() |
| 3075 | |
| 3076 | # If our upstream branch is local, we base our squashed commit on its |
| 3077 | # squashed version. |
| 3078 | upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch) |
| 3079 | |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3080 | if upstream_branch_name == 'master': |
Aaron Gable | 0bbd1c2 | 2017-05-08 14:37:08 -0700 | [diff] [blame] | 3081 | return self.GetCommonAncestorWithUpstream() |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3082 | |
| 3083 | # Check the squashed hash of the parent. |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 3084 | # TODO(tandrii): consider checking parent change in Gerrit and using its |
| 3085 | # hash if tree hash of latest parent revision (patchset) in Gerrit matches |
| 3086 | # the tree hash of the parent branch. The upside is less likely bogus |
| 3087 | # requests to reupload parent change just because it's uploadhash is |
| 3088 | # missing, yet the downside likely exists, too (albeit unknown to me yet). |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3089 | parent = RunGit(['config', |
| 3090 | 'branch.%s.gerritsquashhash' % upstream_branch_name], |
| 3091 | error_ok=True).strip() |
| 3092 | # Verify that the upstream branch has been uploaded too, otherwise |
| 3093 | # Gerrit will create additional CLs when uploading. |
| 3094 | if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) != |
| 3095 | RunGitSilent(['rev-parse', parent + ':'])): |
| 3096 | DieWithError( |
| 3097 | '\nUpload upstream branch %s first.\n' |
| 3098 | 'It is likely that this branch has been rebased since its last ' |
| 3099 | 'upload, so you just need to upload it again.\n' |
| 3100 | '(If you uploaded it with --no-squash, then branch dependencies ' |
| 3101 | 'are not supported, and you should reupload with --squash.)' |
| 3102 | % upstream_branch_name, |
| 3103 | change_desc) |
| 3104 | return parent |
| 3105 | |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 3106 | def _AddChangeIdToCommitMessage(self, options, args): |
| 3107 | """Re-commits using the current message, assumes the commit hook is in |
| 3108 | place. |
| 3109 | """ |
Andrii Shyshkalov | b07575f | 2018-10-16 06:16:21 +0000 | [diff] [blame] | 3110 | log_desc = options.message or _create_description_from_log(args) |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 3111 | git_command = ['commit', '--amend', '-m', log_desc] |
| 3112 | RunGit(git_command) |
Andrii Shyshkalov | b07575f | 2018-10-16 06:16:21 +0000 | [diff] [blame] | 3113 | new_log_desc = _create_description_from_log(args) |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 3114 | if git_footers.get_footer_change_id(new_log_desc): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 3115 | print('git-cl: Added Change-Id to commit message.') |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 3116 | return new_log_desc |
| 3117 | else: |
tandrii@chromium.org | b067ec5 | 2016-05-31 15:24:44 +0000 | [diff] [blame] | 3118 | DieWithError('ERROR: Gerrit commit-msg hook not installed.') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3119 | |
Ravi Mistry | 31e7d56 | 2018-04-02 12:53:57 -0400 | [diff] [blame] | 3120 | def SetLabels(self, enable_auto_submit, use_commit_queue, cq_dry_run): |
| 3121 | """Sets labels on the change based on the provided flags.""" |
| 3122 | labels = {} |
| 3123 | notify = None; |
| 3124 | if enable_auto_submit: |
| 3125 | labels['Auto-Submit'] = 1 |
| 3126 | if use_commit_queue: |
| 3127 | labels['Commit-Queue'] = 2 |
| 3128 | elif cq_dry_run: |
| 3129 | labels['Commit-Queue'] = 1 |
| 3130 | notify = False |
| 3131 | if labels: |
Andrii Shyshkalov | d06cc78 | 2018-08-23 17:24:19 +0000 | [diff] [blame] | 3132 | gerrit_util.SetReview( |
| 3133 | self._GetGerritHost(), |
| 3134 | self._GerritChangeIdentifier(), |
| 3135 | labels=labels, notify=notify) |
Ravi Mistry | 31e7d56 | 2018-04-02 12:53:57 -0400 | [diff] [blame] | 3136 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 3137 | def SetCQState(self, new_state): |
| 3138 | """Sets the Commit-Queue label assuming canonical CQ config for Gerrit.""" |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 3139 | vote_map = { |
| 3140 | _CQState.NONE: 0, |
| 3141 | _CQState.DRY_RUN: 1, |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 3142 | _CQState.COMMIT: 2, |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 3143 | } |
Aaron Gable | fc62f76 | 2017-07-17 11:12:07 -0700 | [diff] [blame] | 3144 | labels = {'Commit-Queue': vote_map[new_state]} |
| 3145 | notify = False if new_state == _CQState.DRY_RUN else None |
Andrii Shyshkalov | 889677c | 2018-08-28 20:43:06 +0000 | [diff] [blame] | 3146 | gerrit_util.SetReview( |
| 3147 | self._GetGerritHost(), self._GerritChangeIdentifier(), |
| 3148 | labels=labels, notify=notify) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 3149 | |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 3150 | def CannotTriggerTryJobReason(self): |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3151 | try: |
| 3152 | data = self._GetChangeDetail() |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 3153 | except GerritChangeNotExists: |
| 3154 | return 'Gerrit doesn\'t know about your change %s' % self.GetIssue() |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3155 | |
| 3156 | if data['status'] in ('ABANDONED', 'MERGED'): |
| 3157 | return 'CL %s is closed' % self.GetIssue() |
| 3158 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3159 | def GetTryJobProperties(self, patchset=None): |
| 3160 | """Returns dictionary of properties to launch try job.""" |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3161 | data = self._GetChangeDetail(['ALL_REVISIONS']) |
| 3162 | patchset = int(patchset or self.GetPatchset()) |
| 3163 | assert patchset |
| 3164 | revision_data = None # Pylint wants it to be defined. |
| 3165 | for revision_data in data['revisions'].itervalues(): |
| 3166 | if int(revision_data['_number']) == patchset: |
| 3167 | break |
| 3168 | else: |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 3169 | raise Exception('Patchset %d is not known in Gerrit change %d' % |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3170 | (patchset, self.GetIssue())) |
| 3171 | return { |
| 3172 | 'patch_issue': self.GetIssue(), |
| 3173 | 'patch_set': patchset or self.GetPatchset(), |
| 3174 | 'patch_project': data['project'], |
| 3175 | 'patch_storage': 'gerrit', |
| 3176 | 'patch_ref': revision_data['fetch']['http']['ref'], |
| 3177 | 'patch_repository_url': revision_data['fetch']['http']['url'], |
| 3178 | 'patch_gerrit_url': self.GetCodereviewServer(), |
| 3179 | } |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 3180 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 3181 | def GetIssueOwner(self): |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3182 | return self._GetChangeDetail(['DETAILED_ACCOUNTS'])['owner']['email'] |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 3183 | |
Edward Lemur | 707d70b | 2018-02-07 00:50:14 +0100 | [diff] [blame] | 3184 | def GetReviewers(self): |
| 3185 | details = self._GetChangeDetail(['DETAILED_ACCOUNTS']) |
| 3186 | return [reviewer['email'] for reviewer in details['reviewers']['REVIEWER']] |
| 3187 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 3188 | |
| 3189 | _CODEREVIEW_IMPLEMENTATIONS = { |
| 3190 | 'rietveld': _RietveldChangelistImpl, |
| 3191 | 'gerrit': _GerritChangelistImpl, |
| 3192 | } |
| 3193 | |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 3194 | |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 3195 | def _add_codereview_issue_select_options(parser, extra=""): |
| 3196 | _add_codereview_select_options(parser) |
| 3197 | |
| 3198 | text = ('Operate on this issue number instead of the current branch\'s ' |
| 3199 | 'implicit issue.') |
| 3200 | if extra: |
| 3201 | text += ' '+extra |
| 3202 | parser.add_option('-i', '--issue', type=int, help=text) |
| 3203 | |
| 3204 | |
| 3205 | def _process_codereview_issue_select_options(parser, options): |
| 3206 | _process_codereview_select_options(parser, options) |
| 3207 | if options.issue is not None and not options.forced_codereview: |
| 3208 | parser.error('--issue must be specified with either --rietveld or --gerrit') |
| 3209 | |
| 3210 | |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3211 | def _add_codereview_select_options(parser): |
| 3212 | """Appends --gerrit and --rietveld options to force specific codereview.""" |
| 3213 | parser.codereview_group = optparse.OptionGroup( |
| 3214 | parser, 'EXPERIMENTAL! Codereview override options') |
| 3215 | parser.add_option_group(parser.codereview_group) |
| 3216 | parser.codereview_group.add_option( |
| 3217 | '--gerrit', action='store_true', |
| 3218 | help='Force the use of Gerrit for codereview') |
| 3219 | parser.codereview_group.add_option( |
| 3220 | '--rietveld', action='store_true', |
| 3221 | help='Force the use of Rietveld for codereview') |
| 3222 | |
| 3223 | |
| 3224 | def _process_codereview_select_options(parser, options): |
Andrii Shyshkalov | feec80e | 2018-10-16 01:00:47 +0000 | [diff] [blame] | 3225 | if options.rietveld: |
| 3226 | parser.error('--rietveld is no longer supported') |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3227 | options.forced_codereview = None |
| 3228 | if options.gerrit: |
| 3229 | options.forced_codereview = 'gerrit' |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3230 | |
| 3231 | |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3232 | def _get_bug_line_values(default_project, bugs): |
| 3233 | """Given default_project and comma separated list of bugs, yields bug line |
| 3234 | values. |
| 3235 | |
| 3236 | Each bug can be either: |
| 3237 | * a number, which is combined with default_project |
| 3238 | * string, which is left as is. |
| 3239 | |
| 3240 | This function may produce more than one line, because bugdroid expects one |
| 3241 | project per line. |
| 3242 | |
| 3243 | >>> list(_get_bug_line_values('v8', '123,chromium:789')) |
| 3244 | ['v8:123', 'chromium:789'] |
| 3245 | """ |
| 3246 | default_bugs = [] |
| 3247 | others = [] |
| 3248 | for bug in bugs.split(','): |
| 3249 | bug = bug.strip() |
| 3250 | if bug: |
| 3251 | try: |
| 3252 | default_bugs.append(int(bug)) |
| 3253 | except ValueError: |
| 3254 | others.append(bug) |
| 3255 | |
| 3256 | if default_bugs: |
| 3257 | default_bugs = ','.join(map(str, default_bugs)) |
| 3258 | if default_project: |
| 3259 | yield '%s:%s' % (default_project, default_bugs) |
| 3260 | else: |
| 3261 | yield default_bugs |
| 3262 | for other in sorted(others): |
| 3263 | # Don't bother finding common prefixes, CLs with >2 bugs are very very rare. |
| 3264 | yield other |
| 3265 | |
| 3266 | |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3267 | class ChangeDescription(object): |
| 3268 | """Contains a parsed form of the change description.""" |
maruel@chromium.org | c6f60e8 | 2013-04-19 17:01:57 +0000 | [diff] [blame] | 3269 | R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$' |
bradnelson | d975b30 | 2016-10-23 12:20:23 -0700 | [diff] [blame] | 3270 | CC_LINE = r'^[ \t]*(CC)[ \t]*=[ \t]*(.*?)[ \t]*$' |
Aaron Gable | 3a16ed1 | 2017-03-23 10:51:55 -0700 | [diff] [blame] | 3271 | BUG_LINE = r'^[ \t]*(?:(BUG)[ \t]*=|Bug:)[ \t]*(.*?)[ \t]*$' |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3272 | CHERRY_PICK_LINE = r'^\(cherry picked from commit [a-fA-F0-9]{40}\)$' |
Nodir Turakulov | 23b8214 | 2017-11-16 11:04:25 -0800 | [diff] [blame] | 3273 | STRIP_HASH_TAG_PREFIX = r'^(\s*(revert|reland)( "|:)?\s*)*' |
| 3274 | BRACKET_HASH_TAG = r'\s*\[([^\[\]]+)\]' |
| 3275 | COLON_SEPARATED_HASH_TAG = r'^([a-zA-Z0-9_\- ]+):' |
| 3276 | BAD_HASH_TAG_CHUNK = r'[^a-zA-Z0-9]+' |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3277 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3278 | def __init__(self, description): |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3279 | self._description_lines = (description or '').strip().splitlines() |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3280 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3281 | @property # www.logilab.org/ticket/89786 |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 3282 | def description(self): # pylint: disable=method-hidden |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3283 | return '\n'.join(self._description_lines) |
| 3284 | |
| 3285 | def set_description(self, desc): |
| 3286 | if isinstance(desc, basestring): |
| 3287 | lines = desc.splitlines() |
| 3288 | else: |
| 3289 | lines = [line.rstrip() for line in desc] |
| 3290 | while lines and not lines[0]: |
| 3291 | lines.pop(0) |
| 3292 | while lines and not lines[-1]: |
| 3293 | lines.pop(-1) |
| 3294 | self._description_lines = lines |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3295 | |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3296 | def update_reviewers(self, reviewers, tbrs, add_owners_to=None, change=None): |
| 3297 | """Rewrites the R=/TBR= line(s) as a single line each. |
| 3298 | |
| 3299 | Args: |
| 3300 | reviewers (list(str)) - list of additional emails to use for reviewers. |
| 3301 | tbrs (list(str)) - list of additional emails to use for TBRs. |
| 3302 | add_owners_to (None|'R'|'TBR') - Pass to do an OWNERS lookup for files in |
| 3303 | the change that are missing OWNER coverage. If this is not None, you |
| 3304 | must also pass a value for `change`. |
| 3305 | change (Change) - The Change that should be used for OWNERS lookups. |
| 3306 | """ |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3307 | assert isinstance(reviewers, list), reviewers |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3308 | assert isinstance(tbrs, list), tbrs |
| 3309 | |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 3310 | assert add_owners_to in (None, 'TBR', 'R'), add_owners_to |
Robert Iannucci | a28592e | 2017-04-18 13:14:49 -0700 | [diff] [blame] | 3311 | assert not add_owners_to or change, add_owners_to |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3312 | |
| 3313 | if not reviewers and not tbrs and not add_owners_to: |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3314 | return |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3315 | |
| 3316 | reviewers = set(reviewers) |
| 3317 | tbrs = set(tbrs) |
| 3318 | LOOKUP = { |
| 3319 | 'TBR': tbrs, |
| 3320 | 'R': reviewers, |
| 3321 | } |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3322 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3323 | # Get the set of R= and TBR= lines and remove them from the description. |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3324 | regexp = re.compile(self.R_LINE) |
| 3325 | matches = [regexp.match(line) for line in self._description_lines] |
| 3326 | new_desc = [l for i, l in enumerate(self._description_lines) |
| 3327 | if not matches[i]] |
| 3328 | self.set_description(new_desc) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3329 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3330 | # Construct new unified R= and TBR= lines. |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3331 | |
| 3332 | # First, update tbrs/reviewers with names from the R=/TBR= lines (if any). |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3333 | for match in matches: |
| 3334 | if not match: |
| 3335 | continue |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3336 | LOOKUP[match.group(1)].update(cleanup_list([match.group(2).strip()])) |
| 3337 | |
| 3338 | # Next, maybe fill in OWNERS coverage gaps to either tbrs/reviewers. |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 3339 | if add_owners_to: |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 3340 | owners_db = owners.Database(change.RepositoryRoot(), |
Jochen Eisinger | 72606f8 | 2017-04-04 10:44:18 +0200 | [diff] [blame] | 3341 | fopen=file, os_path=os.path) |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 3342 | missing_files = owners_db.files_not_covered_by(change.LocalPaths(), |
Robert Iannucci | 100aa21 | 2017-04-18 17:28:26 -0700 | [diff] [blame] | 3343 | (tbrs | reviewers)) |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3344 | LOOKUP[add_owners_to].update( |
| 3345 | owners_db.reviewers_for(missing_files, change.author_email)) |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 3346 | |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3347 | # If any folks ended up in both groups, remove them from tbrs. |
| 3348 | tbrs -= reviewers |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 3349 | |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3350 | new_r_line = 'R=' + ', '.join(sorted(reviewers)) if reviewers else None |
| 3351 | new_tbr_line = 'TBR=' + ', '.join(sorted(tbrs)) if tbrs else None |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3352 | |
| 3353 | # Put the new lines in the description where the old first R= line was. |
| 3354 | line_loc = next((i for i, match in enumerate(matches) if match), -1) |
| 3355 | if 0 <= line_loc < len(self._description_lines): |
| 3356 | if new_tbr_line: |
| 3357 | self._description_lines.insert(line_loc, new_tbr_line) |
| 3358 | if new_r_line: |
| 3359 | self._description_lines.insert(line_loc, new_r_line) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3360 | else: |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3361 | if new_r_line: |
| 3362 | self.append_footer(new_r_line) |
| 3363 | if new_tbr_line: |
| 3364 | self.append_footer(new_tbr_line) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3365 | |
Aaron Gable | 3a16ed1 | 2017-03-23 10:51:55 -0700 | [diff] [blame] | 3366 | def prompt(self, bug=None, git_footer=True): |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3367 | """Asks the user to update the description.""" |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3368 | self.set_description([ |
| 3369 | '# Enter a description of the change.', |
| 3370 | '# This will be displayed on the codereview site.', |
| 3371 | '# The first line will also be used as the subject of the review.', |
alancutter@chromium.org | bd1073e | 2013-06-01 00:34:38 +0000 | [diff] [blame] | 3372 | '#--------------------This line is 72 characters long' |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3373 | '--------------------', |
| 3374 | ] + self._description_lines) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3375 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3376 | regexp = re.compile(self.BUG_LINE) |
| 3377 | if not any((regexp.match(line) for line in self._description_lines)): |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3378 | prefix = settings.GetBugPrefix() |
| 3379 | values = list(_get_bug_line_values(prefix, bug or '')) or [prefix] |
Aaron Gable | 3a16ed1 | 2017-03-23 10:51:55 -0700 | [diff] [blame] | 3380 | if git_footer: |
| 3381 | self.append_footer('Bug: %s' % ', '.join(values)) |
| 3382 | else: |
| 3383 | for value in values: |
| 3384 | self.append_footer('BUG=%s' % value) |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3385 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3386 | content = gclient_utils.RunEditor(self.description, True, |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 3387 | git_editor=settings.GetGitEditor()) |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 3388 | if not content: |
| 3389 | DieWithError('Running editor failed') |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3390 | lines = content.splitlines() |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3391 | |
Bruce Dawson | 2377b01 | 2018-01-11 16:46:49 -0800 | [diff] [blame] | 3392 | # Strip off comments and default inserted "Bug:" line. |
| 3393 | clean_lines = [line.rstrip() for line in lines if not |
| 3394 | (line.startswith('#') or line.rstrip() == "Bug:")] |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3395 | if not clean_lines: |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 3396 | DieWithError('No CL description, aborting') |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3397 | self.set_description(clean_lines) |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3398 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3399 | def append_footer(self, line): |
tandrii@chromium.org | 601e1d1 | 2016-06-03 13:03:54 +0000 | [diff] [blame] | 3400 | """Adds a footer line to the description. |
| 3401 | |
| 3402 | Differentiates legacy "KEY=xxx" footers (used to be called tags) and |
| 3403 | Gerrit's footers in the form of "Footer-Key: footer any value" and ensures |
| 3404 | that Gerrit footers are always at the end. |
| 3405 | """ |
| 3406 | parsed_footer_line = git_footers.parse_footer(line) |
| 3407 | if parsed_footer_line: |
| 3408 | # Line is a gerrit footer in the form: Footer-Key: any value. |
| 3409 | # Thus, must be appended observing Gerrit footer rules. |
| 3410 | self.set_description( |
| 3411 | git_footers.add_footer(self.description, |
| 3412 | key=parsed_footer_line[0], |
| 3413 | value=parsed_footer_line[1])) |
| 3414 | return |
| 3415 | |
| 3416 | if not self._description_lines: |
| 3417 | self._description_lines.append(line) |
| 3418 | return |
| 3419 | |
| 3420 | top_lines, gerrit_footers, _ = git_footers.split_footers(self.description) |
| 3421 | if gerrit_footers: |
| 3422 | # git_footers.split_footers ensures that there is an empty line before |
| 3423 | # actual (gerrit) footers, if any. We have to keep it that way. |
| 3424 | assert top_lines and top_lines[-1] == '' |
| 3425 | top_lines, separator = top_lines[:-1], top_lines[-1:] |
| 3426 | else: |
| 3427 | separator = [] # No need for separator if there are no gerrit_footers. |
| 3428 | |
| 3429 | prev_line = top_lines[-1] if top_lines else '' |
| 3430 | if (not presubmit_support.Change.TAG_LINE_RE.match(prev_line) or |
| 3431 | not presubmit_support.Change.TAG_LINE_RE.match(line)): |
| 3432 | top_lines.append('') |
| 3433 | top_lines.append(line) |
| 3434 | self._description_lines = top_lines + separator + gerrit_footers |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3435 | |
tandrii | 99a72f2 | 2016-08-17 14:33:24 -0700 | [diff] [blame] | 3436 | def get_reviewers(self, tbr_only=False): |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3437 | """Retrieves the list of reviewers.""" |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3438 | matches = [re.match(self.R_LINE, line) for line in self._description_lines] |
tandrii | 99a72f2 | 2016-08-17 14:33:24 -0700 | [diff] [blame] | 3439 | reviewers = [match.group(2).strip() |
| 3440 | for match in matches |
| 3441 | if match and (not tbr_only or match.group(1).upper() == 'TBR')] |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3442 | return cleanup_list(reviewers) |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3443 | |
bradnelson | d975b30 | 2016-10-23 12:20:23 -0700 | [diff] [blame] | 3444 | def get_cced(self): |
| 3445 | """Retrieves the list of reviewers.""" |
| 3446 | matches = [re.match(self.CC_LINE, line) for line in self._description_lines] |
| 3447 | cced = [match.group(2).strip() for match in matches if match] |
| 3448 | return cleanup_list(cced) |
| 3449 | |
Nodir Turakulov | 23b8214 | 2017-11-16 11:04:25 -0800 | [diff] [blame] | 3450 | def get_hash_tags(self): |
| 3451 | """Extracts and sanitizes a list of Gerrit hashtags.""" |
| 3452 | subject = (self._description_lines or ('',))[0] |
| 3453 | subject = re.sub( |
| 3454 | self.STRIP_HASH_TAG_PREFIX, '', subject, flags=re.IGNORECASE) |
| 3455 | |
| 3456 | tags = [] |
| 3457 | start = 0 |
| 3458 | bracket_exp = re.compile(self.BRACKET_HASH_TAG) |
| 3459 | while True: |
| 3460 | m = bracket_exp.match(subject, start) |
| 3461 | if not m: |
| 3462 | break |
| 3463 | tags.append(self.sanitize_hash_tag(m.group(1))) |
| 3464 | start = m.end() |
| 3465 | |
| 3466 | if not tags: |
| 3467 | # Try "Tag: " prefix. |
| 3468 | m = re.match(self.COLON_SEPARATED_HASH_TAG, subject) |
| 3469 | if m: |
| 3470 | tags.append(self.sanitize_hash_tag(m.group(1))) |
| 3471 | return tags |
| 3472 | |
| 3473 | @classmethod |
| 3474 | def sanitize_hash_tag(cls, tag): |
| 3475 | """Returns a sanitized Gerrit hash tag. |
| 3476 | |
| 3477 | A sanitized hashtag can be used as a git push refspec parameter value. |
| 3478 | """ |
| 3479 | return re.sub(cls.BAD_HASH_TAG_CHUNK, '-', tag).strip('-').lower() |
| 3480 | |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3481 | def update_with_git_number_footers(self, parent_hash, parent_msg, dest_ref): |
| 3482 | """Updates this commit description given the parent. |
| 3483 | |
| 3484 | This is essentially what Gnumbd used to do. |
| 3485 | Consult https://goo.gl/WMmpDe for more details. |
| 3486 | """ |
| 3487 | assert parent_msg # No, orphan branch creation isn't supported. |
| 3488 | assert parent_hash |
| 3489 | assert dest_ref |
| 3490 | parent_footer_map = git_footers.parse_footers(parent_msg) |
| 3491 | # This will also happily parse svn-position, which GnumbD is no longer |
| 3492 | # supporting. While we'd generate correct footers, the verifier plugin |
| 3493 | # installed in Gerrit will block such commit (ie git push below will fail). |
| 3494 | parent_position = git_footers.get_position(parent_footer_map) |
| 3495 | |
| 3496 | # Cherry-picks may have last line obscuring their prior footers, |
| 3497 | # from git_footers perspective. This is also what Gnumbd did. |
| 3498 | cp_line = None |
| 3499 | if (self._description_lines and |
| 3500 | re.match(self.CHERRY_PICK_LINE, self._description_lines[-1])): |
| 3501 | cp_line = self._description_lines.pop() |
| 3502 | |
Andrii Shyshkalov | de37c01 | 2017-07-06 21:06:50 +0200 | [diff] [blame] | 3503 | top_lines, footer_lines, _ = git_footers.split_footers(self.description) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3504 | |
| 3505 | # Original-ify all Cr- footers, to avoid re-lands, cherry-picks, or just |
| 3506 | # user interference with actual footers we'd insert below. |
Andrii Shyshkalov | de37c01 | 2017-07-06 21:06:50 +0200 | [diff] [blame] | 3507 | for i, line in enumerate(footer_lines): |
| 3508 | k, v = git_footers.parse_footer(line) or (None, None) |
| 3509 | if k and k.startswith('Cr-'): |
| 3510 | footer_lines[i] = '%s: %s' % ('Cr-Original-' + k[len('Cr-'):], v) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3511 | |
| 3512 | # Add Position and Lineage footers based on the parent. |
Andrii Shyshkalov | b5effa1 | 2016-12-14 19:35:12 +0100 | [diff] [blame] | 3513 | lineage = list(reversed(parent_footer_map.get('Cr-Branched-From', []))) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3514 | if parent_position[0] == dest_ref: |
| 3515 | # Same branch as parent. |
| 3516 | number = int(parent_position[1]) + 1 |
| 3517 | else: |
| 3518 | number = 1 # New branch, and extra lineage. |
| 3519 | lineage.insert(0, '%s-%s@{#%d}' % (parent_hash, parent_position[0], |
| 3520 | int(parent_position[1]))) |
| 3521 | |
Andrii Shyshkalov | de37c01 | 2017-07-06 21:06:50 +0200 | [diff] [blame] | 3522 | footer_lines.append('Cr-Commit-Position: %s@{#%d}' % (dest_ref, number)) |
| 3523 | footer_lines.extend('Cr-Branched-From: %s' % v for v in lineage) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3524 | |
| 3525 | self._description_lines = top_lines |
| 3526 | if cp_line: |
| 3527 | self._description_lines.append(cp_line) |
| 3528 | if self._description_lines[-1] != '': |
| 3529 | self._description_lines.append('') # Ensure footer separator. |
Andrii Shyshkalov | de37c01 | 2017-07-06 21:06:50 +0200 | [diff] [blame] | 3530 | self._description_lines.extend(footer_lines) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3531 | |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3532 | |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 3533 | def get_approving_reviewers(props, disapproval=False): |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 3534 | """Retrieves the reviewers that approved a CL from the issue properties with |
| 3535 | messages. |
| 3536 | |
| 3537 | Note that the list may contain reviewers that are not committer, thus are not |
| 3538 | considered by the CQ. |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 3539 | |
| 3540 | If disapproval is True, instead returns reviewers who 'not lgtm'd the CL. |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 3541 | """ |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 3542 | approval_type = 'disapproval' if disapproval else 'approval' |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 3543 | return sorted( |
| 3544 | set( |
| 3545 | message['sender'] |
| 3546 | for message in props['messages'] |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 3547 | if message[approval_type] and message['sender'] in props['reviewers'] |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 3548 | ) |
| 3549 | ) |
| 3550 | |
| 3551 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3552 | def FindCodereviewSettingsFile(filename='codereview.settings'): |
| 3553 | """Finds the given file starting in the cwd and going up. |
| 3554 | |
| 3555 | Only looks up to the top of the repository unless an |
| 3556 | 'inherit-review-settings-ok' file exists in the root of the repository. |
| 3557 | """ |
| 3558 | inherit_ok_file = 'inherit-review-settings-ok' |
| 3559 | cwd = os.getcwd() |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 3560 | root = settings.GetRoot() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3561 | if os.path.isfile(os.path.join(root, inherit_ok_file)): |
| 3562 | root = '/' |
| 3563 | while True: |
| 3564 | if filename in os.listdir(cwd): |
| 3565 | if os.path.isfile(os.path.join(cwd, filename)): |
| 3566 | return open(os.path.join(cwd, filename)) |
| 3567 | if cwd == root: |
| 3568 | break |
| 3569 | cwd = os.path.dirname(cwd) |
| 3570 | |
| 3571 | |
| 3572 | def LoadCodereviewSettingsFromFile(fileobj): |
| 3573 | """Parse a codereview.settings file and updates hooks.""" |
maruel@chromium.org | 99ac1c5 | 2012-01-16 14:52:12 +0000 | [diff] [blame] | 3574 | keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3575 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3576 | def SetProperty(name, setting, unset_error_ok=False): |
| 3577 | fullname = 'rietveld.' + name |
| 3578 | if setting in keyvals: |
| 3579 | RunGit(['config', fullname, keyvals[setting]]) |
| 3580 | else: |
| 3581 | RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok) |
| 3582 | |
tandrii | 48df581 | 2016-10-17 03:55:37 -0700 | [diff] [blame] | 3583 | if not keyvals.get('GERRIT_HOST', False): |
| 3584 | SetProperty('server', 'CODE_REVIEW_SERVER') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3585 | # Only server setting is required. Other settings can be absent. |
| 3586 | # In that case, we ignore errors raised during option deletion attempt. |
| 3587 | SetProperty('cc', 'CC_LIST', unset_error_ok=True) |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 3588 | SetProperty('private', 'PRIVATE', unset_error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3589 | SetProperty('tree-status-url', 'STATUS', unset_error_ok=True) |
| 3590 | SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True) |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 3591 | SetProperty('bug-prefix', 'BUG_PREFIX', unset_error_ok=True) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 3592 | SetProperty('cpplint-regex', 'LINT_REGEX', unset_error_ok=True) |
| 3593 | SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX', unset_error_ok=True) |
sheyang@chromium.org | 152cf83 | 2014-06-11 21:37:49 +0000 | [diff] [blame] | 3594 | SetProperty('project', 'PROJECT', unset_error_ok=True) |
rmistry@google.com | 5626a92 | 2015-02-26 14:03:30 +0000 | [diff] [blame] | 3595 | SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK', |
| 3596 | unset_error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3597 | |
ukai@chromium.org | 7044efc | 2013-11-28 01:51:21 +0000 | [diff] [blame] | 3598 | if 'GERRIT_HOST' in keyvals: |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3599 | RunGit(['config', 'gerrit.host', keyvals['GERRIT_HOST']]) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3600 | |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 3601 | if 'GERRIT_SQUASH_UPLOADS' in keyvals: |
tandrii | 8dd81ea | 2016-06-16 13:24:23 -0700 | [diff] [blame] | 3602 | RunGit(['config', 'gerrit.squash-uploads', |
| 3603 | keyvals['GERRIT_SQUASH_UPLOADS']]) |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 3604 | |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 3605 | if 'GERRIT_SKIP_ENSURE_AUTHENTICATED' in keyvals: |
shinyak@chromium.org | 00dbccd | 2016-04-15 07:24:43 +0000 | [diff] [blame] | 3606 | RunGit(['config', 'gerrit.skip-ensure-authenticated', |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 3607 | keyvals['GERRIT_SKIP_ENSURE_AUTHENTICATED']]) |
| 3608 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3609 | if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals: |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 3610 | # should be of the form |
| 3611 | # PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof |
| 3612 | # ORIGIN_URL_CONFIG: http://src.chromium.org/git |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3613 | RunGit(['config', keyvals['PUSH_URL_CONFIG'], |
| 3614 | keyvals['ORIGIN_URL_CONFIG']]) |
| 3615 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3616 | |
joshua.lock@intel.com | 426f69b | 2012-08-02 23:41:49 +0000 | [diff] [blame] | 3617 | def urlretrieve(source, destination): |
| 3618 | """urllib is broken for SSL connections via a proxy therefore we |
| 3619 | can't use urllib.urlretrieve().""" |
| 3620 | with open(destination, 'w') as f: |
| 3621 | f.write(urllib2.urlopen(source).read()) |
| 3622 | |
| 3623 | |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3624 | def hasSheBang(fname): |
| 3625 | """Checks fname is a #! script.""" |
| 3626 | with open(fname) as f: |
| 3627 | return f.read(2).startswith('#!') |
| 3628 | |
| 3629 | |
bpastene@chromium.org | 917f0ff | 2016-04-05 00:45:30 +0000 | [diff] [blame] | 3630 | # TODO(bpastene) Remove once a cleaner fix to crbug.com/600473 presents itself. |
| 3631 | def DownloadHooks(*args, **kwargs): |
| 3632 | pass |
| 3633 | |
| 3634 | |
tandrii@chromium.org | 18630d6 | 2016-03-04 12:06:02 +0000 | [diff] [blame] | 3635 | def DownloadGerritHook(force): |
| 3636 | """Download and install Gerrit commit-msg hook. |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3637 | |
| 3638 | Args: |
| 3639 | force: True to update hooks. False to install hooks if not present. |
| 3640 | """ |
| 3641 | if not settings.GetIsGerrit(): |
| 3642 | return |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3643 | src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg' |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3644 | dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg') |
| 3645 | if not os.access(dst, os.X_OK): |
| 3646 | if os.path.exists(dst): |
| 3647 | if not force: |
| 3648 | return |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3649 | try: |
joshua.lock@intel.com | 426f69b | 2012-08-02 23:41:49 +0000 | [diff] [blame] | 3650 | urlretrieve(src, dst) |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3651 | if not hasSheBang(dst): |
| 3652 | DieWithError('Not a script: %s\n' |
| 3653 | 'You need to download from\n%s\n' |
| 3654 | 'into .git/hooks/commit-msg and ' |
| 3655 | 'chmod +x .git/hooks/commit-msg' % (dst, src)) |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3656 | os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) |
| 3657 | except Exception: |
| 3658 | if os.path.exists(dst): |
| 3659 | os.remove(dst) |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3660 | DieWithError('\nFailed to download hooks.\n' |
| 3661 | 'You need to download from\n%s\n' |
| 3662 | 'into .git/hooks/commit-msg and ' |
| 3663 | 'chmod +x .git/hooks/commit-msg' % src) |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3664 | |
| 3665 | |
tandrii@chromium.org | e7d3d16 | 2016-03-15 14:15:57 +0000 | [diff] [blame] | 3666 | def GetRietveldCodereviewSettingsInteractively(): |
| 3667 | """Prompt the user for settings.""" |
| 3668 | server = settings.GetDefaultServerUrl(error_ok=True) |
| 3669 | prompt = 'Rietveld server (host[:port])' |
| 3670 | prompt += ' [%s]' % (server or DEFAULT_SERVER) |
| 3671 | newserver = ask_for_data(prompt + ':') |
| 3672 | if not server and not newserver: |
| 3673 | newserver = DEFAULT_SERVER |
| 3674 | if newserver: |
| 3675 | newserver = gclient_utils.UpgradeToHttps(newserver) |
| 3676 | if newserver != server: |
| 3677 | RunGit(['config', 'rietveld.server', newserver]) |
| 3678 | |
| 3679 | def SetProperty(initial, caption, name, is_url): |
| 3680 | prompt = caption |
| 3681 | if initial: |
| 3682 | prompt += ' ("x" to clear) [%s]' % initial |
| 3683 | new_val = ask_for_data(prompt + ':') |
| 3684 | if new_val == 'x': |
| 3685 | RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True) |
| 3686 | elif new_val: |
| 3687 | if is_url: |
| 3688 | new_val = gclient_utils.UpgradeToHttps(new_val) |
| 3689 | if new_val != initial: |
| 3690 | RunGit(['config', 'rietveld.' + name, new_val]) |
| 3691 | |
| 3692 | SetProperty(settings.GetDefaultCCList(), 'CC list', 'cc', False) |
| 3693 | SetProperty(settings.GetDefaultPrivateFlag(), |
| 3694 | 'Private flag (rietveld only)', 'private', False) |
| 3695 | SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL', |
| 3696 | 'tree-status-url', False) |
| 3697 | SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url', True) |
| 3698 | SetProperty(settings.GetBugPrefix(), 'Bug Prefix', 'bug-prefix', False) |
| 3699 | SetProperty(settings.GetRunPostUploadHook(), 'Run Post Upload Hook', |
| 3700 | 'run-post-upload-hook', False) |
| 3701 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 3702 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3703 | class _GitCookiesChecker(object): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3704 | """Provides facilities for validating and suggesting fixes to .gitcookies.""" |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3705 | |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 3706 | _GOOGLESOURCE = 'googlesource.com' |
| 3707 | |
| 3708 | def __init__(self): |
| 3709 | # Cached list of [host, identity, source], where source is either |
| 3710 | # .gitcookies or .netrc. |
| 3711 | self._all_hosts = None |
| 3712 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3713 | def ensure_configured_gitcookies(self): |
| 3714 | """Runs checks and suggests fixes to make git use .gitcookies from default |
| 3715 | path.""" |
| 3716 | default = gerrit_util.CookiesAuthenticator.get_gitcookies_path() |
| 3717 | configured_path = RunGitSilent( |
| 3718 | ['config', '--global', 'http.cookiefile']).strip() |
Andrii Shyshkalov | 1e250cd | 2017-05-10 15:39:31 +0200 | [diff] [blame] | 3719 | configured_path = os.path.expanduser(configured_path) |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3720 | if configured_path: |
| 3721 | self._ensure_default_gitcookies_path(configured_path, default) |
| 3722 | else: |
| 3723 | self._configure_gitcookies_path(default) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3724 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3725 | @staticmethod |
| 3726 | def _ensure_default_gitcookies_path(configured_path, default_path): |
| 3727 | assert configured_path |
| 3728 | if configured_path == default_path: |
| 3729 | print('git is already configured to use your .gitcookies from %s' % |
| 3730 | configured_path) |
| 3731 | return |
| 3732 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3733 | print('WARNING: You have configured custom path to .gitcookies: %s\n' |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3734 | 'Gerrit and other depot_tools expect .gitcookies at %s\n' % |
| 3735 | (configured_path, default_path)) |
| 3736 | |
| 3737 | if not os.path.exists(configured_path): |
| 3738 | print('However, your configured .gitcookies file is missing.') |
| 3739 | confirm_or_exit('Reconfigure git to use default .gitcookies?', |
| 3740 | action='reconfigure') |
| 3741 | RunGit(['config', '--global', 'http.cookiefile', default_path]) |
| 3742 | return |
| 3743 | |
| 3744 | if os.path.exists(default_path): |
| 3745 | print('WARNING: default .gitcookies file already exists %s' % |
| 3746 | default_path) |
| 3747 | DieWithError('Please delete %s manually and re-run git cl creds-check' % |
| 3748 | default_path) |
| 3749 | |
| 3750 | confirm_or_exit('Move existing .gitcookies to default location?', |
| 3751 | action='move') |
| 3752 | shutil.move(configured_path, default_path) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3753 | RunGit(['config', '--global', 'http.cookiefile', default_path]) |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3754 | print('Moved and reconfigured git to use .gitcookies from %s' % |
| 3755 | default_path) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3756 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3757 | @staticmethod |
| 3758 | def _configure_gitcookies_path(default_path): |
| 3759 | netrc_path = gerrit_util.CookiesAuthenticator.get_netrc_path() |
| 3760 | if os.path.exists(netrc_path): |
| 3761 | print('You seem to be using outdated .netrc for git credentials: %s' % |
| 3762 | netrc_path) |
| 3763 | print('This tool will guide you through setting up recommended ' |
| 3764 | '.gitcookies store for git credentials.\n' |
| 3765 | '\n' |
| 3766 | 'IMPORTANT: If something goes wrong and you decide to go back, do:\n' |
| 3767 | ' git config --global --unset http.cookiefile\n' |
| 3768 | ' mv %s %s.backup\n\n' % (default_path, default_path)) |
| 3769 | confirm_or_exit(action='setup .gitcookies') |
| 3770 | RunGit(['config', '--global', 'http.cookiefile', default_path]) |
| 3771 | print('Configured git to use .gitcookies from %s' % default_path) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3772 | |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 3773 | def get_hosts_with_creds(self, include_netrc=False): |
| 3774 | if self._all_hosts is None: |
| 3775 | a = gerrit_util.CookiesAuthenticator() |
| 3776 | self._all_hosts = [ |
| 3777 | (h, u, s) |
| 3778 | for h, u, s in itertools.chain( |
| 3779 | ((h, u, '.netrc') for h, (u, _, _) in a.netrc.hosts.iteritems()), |
| 3780 | ((h, u, '.gitcookies') for h, (u, _) in a.gitcookies.iteritems()) |
| 3781 | ) |
| 3782 | if h.endswith(self._GOOGLESOURCE) |
| 3783 | ] |
| 3784 | |
| 3785 | if include_netrc: |
| 3786 | return self._all_hosts |
| 3787 | return [(h, u, s) for h, u, s in self._all_hosts if s != '.netrc'] |
| 3788 | |
| 3789 | def print_current_creds(self, include_netrc=False): |
| 3790 | hosts = sorted(self.get_hosts_with_creds(include_netrc=include_netrc)) |
| 3791 | if not hosts: |
| 3792 | print('No Git/Gerrit credentials found') |
| 3793 | return |
| 3794 | lengths = [max(map(len, (row[i] for row in hosts))) for i in xrange(3)] |
| 3795 | header = [('Host', 'User', 'Which file'), |
| 3796 | ['=' * l for l in lengths]] |
| 3797 | for row in (header + hosts): |
| 3798 | print('\t'.join((('%%+%ds' % l) % s) |
| 3799 | for l, s in zip(lengths, row))) |
| 3800 | |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3801 | @staticmethod |
| 3802 | def _parse_identity(identity): |
Lei Zhang | d3f769a | 2017-12-15 15:16:14 -0800 | [diff] [blame] | 3803 | """Parses identity "git-<username>.domain" into <username> and domain.""" |
| 3804 | # Special case: usernames that contain ".", which are generally not |
Andrii Shyshkalov | 0d2dea0 | 2017-07-17 15:17:55 +0200 | [diff] [blame] | 3805 | # distinguishable from sub-domains. But we do know typical domains: |
| 3806 | if identity.endswith('.chromium.org'): |
| 3807 | domain = 'chromium.org' |
| 3808 | username = identity[:-len('.chromium.org')] |
| 3809 | else: |
| 3810 | username, domain = identity.split('.', 1) |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3811 | if username.startswith('git-'): |
| 3812 | username = username[len('git-'):] |
| 3813 | return username, domain |
| 3814 | |
| 3815 | def _get_usernames_of_domain(self, domain): |
| 3816 | """Returns list of usernames referenced by .gitcookies in a given domain.""" |
| 3817 | identities_by_domain = {} |
| 3818 | for _, identity, _ in self.get_hosts_with_creds(): |
| 3819 | username, domain = self._parse_identity(identity) |
| 3820 | identities_by_domain.setdefault(domain, []).append(username) |
| 3821 | return identities_by_domain.get(domain) |
| 3822 | |
| 3823 | def _canonical_git_googlesource_host(self, host): |
| 3824 | """Normalizes Gerrit hosts (with '-review') to Git host.""" |
| 3825 | assert host.endswith(self._GOOGLESOURCE) |
| 3826 | # Prefix doesn't include '.' at the end. |
| 3827 | prefix = host[:-(1 + len(self._GOOGLESOURCE))] |
| 3828 | if prefix.endswith('-review'): |
| 3829 | prefix = prefix[:-len('-review')] |
| 3830 | return prefix + '.' + self._GOOGLESOURCE |
| 3831 | |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3832 | def _canonical_gerrit_googlesource_host(self, host): |
| 3833 | git_host = self._canonical_git_googlesource_host(host) |
| 3834 | prefix = git_host.split('.', 1)[0] |
| 3835 | return prefix + '-review.' + self._GOOGLESOURCE |
| 3836 | |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3837 | def _get_counterpart_host(self, host): |
| 3838 | assert host.endswith(self._GOOGLESOURCE) |
| 3839 | git = self._canonical_git_googlesource_host(host) |
| 3840 | gerrit = self._canonical_gerrit_googlesource_host(git) |
| 3841 | return git if gerrit == host else gerrit |
| 3842 | |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3843 | def has_generic_host(self): |
| 3844 | """Returns whether generic .googlesource.com has been configured. |
| 3845 | |
| 3846 | Chrome Infra recommends to use explicit ${host}.googlesource.com instead. |
| 3847 | """ |
| 3848 | for host, _, _ in self.get_hosts_with_creds(include_netrc=False): |
| 3849 | if host == '.' + self._GOOGLESOURCE: |
| 3850 | return True |
| 3851 | return False |
| 3852 | |
| 3853 | def _get_git_gerrit_identity_pairs(self): |
| 3854 | """Returns map from canonic host to pair of identities (Git, Gerrit). |
| 3855 | |
| 3856 | One of identities might be None, meaning not configured. |
| 3857 | """ |
| 3858 | host_to_identity_pairs = {} |
| 3859 | for host, identity, _ in self.get_hosts_with_creds(): |
| 3860 | canonical = self._canonical_git_googlesource_host(host) |
| 3861 | pair = host_to_identity_pairs.setdefault(canonical, [None, None]) |
| 3862 | idx = 0 if canonical == host else 1 |
| 3863 | pair[idx] = identity |
| 3864 | return host_to_identity_pairs |
| 3865 | |
| 3866 | def get_partially_configured_hosts(self): |
| 3867 | return set( |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3868 | (host if i1 else self._canonical_gerrit_googlesource_host(host)) |
| 3869 | for host, (i1, i2) in self._get_git_gerrit_identity_pairs().iteritems() |
| 3870 | if None in (i1, i2) and host != '.' + self._GOOGLESOURCE) |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3871 | |
| 3872 | def get_conflicting_hosts(self): |
| 3873 | return set( |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3874 | host |
| 3875 | for host, (i1, i2) in self._get_git_gerrit_identity_pairs().iteritems() |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3876 | if None not in (i1, i2) and i1 != i2) |
| 3877 | |
| 3878 | def get_duplicated_hosts(self): |
| 3879 | counters = collections.Counter(h for h, _, _ in self.get_hosts_with_creds()) |
| 3880 | return set(host for host, count in counters.iteritems() if count > 1) |
| 3881 | |
| 3882 | _EXPECTED_HOST_IDENTITY_DOMAINS = { |
| 3883 | 'chromium.googlesource.com': 'chromium.org', |
| 3884 | 'chrome-internal.googlesource.com': 'google.com', |
| 3885 | } |
| 3886 | |
| 3887 | def get_hosts_with_wrong_identities(self): |
| 3888 | """Finds hosts which **likely** reference wrong identities. |
| 3889 | |
| 3890 | Note: skips hosts which have conflicting identities for Git and Gerrit. |
| 3891 | """ |
| 3892 | hosts = set() |
| 3893 | for host, expected in self._EXPECTED_HOST_IDENTITY_DOMAINS.iteritems(): |
| 3894 | pair = self._get_git_gerrit_identity_pairs().get(host) |
| 3895 | if pair and pair[0] == pair[1]: |
| 3896 | _, domain = self._parse_identity(pair[0]) |
| 3897 | if domain != expected: |
| 3898 | hosts.add(host) |
| 3899 | return hosts |
| 3900 | |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3901 | @staticmethod |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3902 | def _format_hosts(hosts, extra_column_func=None): |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3903 | hosts = sorted(hosts) |
| 3904 | assert hosts |
| 3905 | if extra_column_func is None: |
| 3906 | extras = [''] * len(hosts) |
| 3907 | else: |
| 3908 | extras = [extra_column_func(host) for host in hosts] |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3909 | tmpl = '%%-%ds %%-%ds' % (max(map(len, hosts)), max(map(len, extras))) |
| 3910 | lines = [] |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3911 | for he in zip(hosts, extras): |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3912 | lines.append(tmpl % he) |
| 3913 | return lines |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3914 | |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3915 | def _find_problems(self): |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3916 | if self.has_generic_host(): |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3917 | yield ('.googlesource.com wildcard record detected', |
| 3918 | ['Chrome Infrastructure team recommends to list full host names ' |
| 3919 | 'explicitly.'], |
| 3920 | None) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3921 | |
| 3922 | dups = self.get_duplicated_hosts() |
| 3923 | if dups: |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3924 | yield ('The following hosts were defined twice', |
| 3925 | self._format_hosts(dups), |
| 3926 | None) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3927 | |
| 3928 | partial = self.get_partially_configured_hosts() |
| 3929 | if partial: |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3930 | yield ('Credentials should come in pairs for Git and Gerrit hosts. ' |
| 3931 | 'These hosts are missing', |
| 3932 | self._format_hosts(partial, lambda host: 'but %s defined' % |
| 3933 | self._get_counterpart_host(host)), |
| 3934 | partial) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3935 | |
| 3936 | conflicting = self.get_conflicting_hosts() |
| 3937 | if conflicting: |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3938 | yield ('The following Git hosts have differing credentials from their ' |
| 3939 | 'Gerrit counterparts', |
| 3940 | self._format_hosts(conflicting, lambda host: '%s vs %s' % |
| 3941 | tuple(self._get_git_gerrit_identity_pairs()[host])), |
| 3942 | conflicting) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3943 | |
| 3944 | wrong = self.get_hosts_with_wrong_identities() |
| 3945 | if wrong: |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3946 | yield ('These hosts likely use wrong identity', |
| 3947 | self._format_hosts(wrong, lambda host: '%s but %s recommended' % |
| 3948 | (self._get_git_gerrit_identity_pairs()[host][0], |
| 3949 | self._EXPECTED_HOST_IDENTITY_DOMAINS[host])), |
| 3950 | wrong) |
| 3951 | |
| 3952 | def find_and_report_problems(self): |
| 3953 | """Returns True if there was at least one problem, else False.""" |
| 3954 | found = False |
| 3955 | bad_hosts = set() |
| 3956 | for title, sublines, hosts in self._find_problems(): |
| 3957 | if not found: |
| 3958 | found = True |
| 3959 | print('\n\n.gitcookies problem report:\n') |
| 3960 | bad_hosts.update(hosts or []) |
| 3961 | print(' %s%s' % (title , (':' if sublines else ''))) |
| 3962 | if sublines: |
| 3963 | print() |
| 3964 | print(' %s' % '\n '.join(sublines)) |
| 3965 | print() |
| 3966 | |
| 3967 | if bad_hosts: |
| 3968 | assert found |
| 3969 | print(' You can manually remove corresponding lines in your %s file and ' |
| 3970 | 'visit the following URLs with correct account to generate ' |
| 3971 | 'correct credential lines:\n' % |
| 3972 | gerrit_util.CookiesAuthenticator.get_gitcookies_path()) |
| 3973 | print(' %s' % '\n '.join(sorted(set( |
| 3974 | gerrit_util.CookiesAuthenticator().get_new_password_url( |
| 3975 | self._canonical_git_googlesource_host(host)) |
| 3976 | for host in bad_hosts |
| 3977 | )))) |
| 3978 | return found |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3979 | |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3980 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 3981 | @metrics.collector.collect_metrics('git cl creds-check') |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3982 | def CMDcreds_check(parser, args): |
| 3983 | """Checks credentials and suggests changes.""" |
| 3984 | _, _ = parser.parse_args(args) |
| 3985 | |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 3986 | # Code below checks .gitcookies. Abort if using something else. |
| 3987 | authn = gerrit_util.Authenticator.get() |
| 3988 | if not isinstance(authn, gerrit_util.CookiesAuthenticator): |
| 3989 | if isinstance(authn, gerrit_util.GceAuthenticator): |
| 3990 | DieWithError( |
| 3991 | 'This command is not designed for GCE, are you on a bot?\n' |
| 3992 | 'If you need to run this on GCE, export SKIP_GCE_AUTH_FOR_GIT=1 ' |
| 3993 | 'in your env.') |
Aaron Gable | d10ca0e | 2017-09-11 11:24:10 -0700 | [diff] [blame] | 3994 | DieWithError( |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 3995 | 'This command is not designed for bot environment. It checks ' |
| 3996 | '~/.gitcookies file not generally used on bots.') |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3997 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3998 | checker = _GitCookiesChecker() |
| 3999 | checker.ensure_configured_gitcookies() |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 4000 | |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 4001 | print('Your .netrc and .gitcookies have credentials for these hosts:') |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 4002 | checker.print_current_creds(include_netrc=True) |
| 4003 | |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 4004 | if not checker.find_and_report_problems(): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 4005 | print('\nNo problems detected in your .gitcookies file.') |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 4006 | return 0 |
| 4007 | return 1 |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 4008 | |
| 4009 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4010 | @subcommand.usage('[repo root containing codereview.settings]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4011 | @metrics.collector.collect_metrics('git cl config') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4012 | def CMDconfig(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4013 | """Edits configuration for this tree.""" |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4014 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 4015 | print('WARNING: git cl config works for Rietveld only.') |
tandrii | 5d0a042 | 2016-09-14 06:24:35 -0700 | [diff] [blame] | 4016 | # TODO(tandrii): remove this once we switch to Gerrit. |
| 4017 | # See bugs http://crbug.com/637561 and http://crbug.com/600469. |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 4018 | parser.add_option('--activate-update', action='store_true', |
| 4019 | help='activate auto-updating [rietveld] section in ' |
| 4020 | '.git/config') |
| 4021 | parser.add_option('--deactivate-update', action='store_true', |
| 4022 | help='deactivate auto-updating [rietveld] section in ' |
| 4023 | '.git/config') |
| 4024 | options, args = parser.parse_args(args) |
| 4025 | |
| 4026 | if options.deactivate_update: |
| 4027 | RunGit(['config', 'rietveld.autoupdate', 'false']) |
| 4028 | return |
| 4029 | |
| 4030 | if options.activate_update: |
| 4031 | RunGit(['config', '--unset', 'rietveld.autoupdate']) |
| 4032 | return |
| 4033 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4034 | if len(args) == 0: |
tandrii@chromium.org | e7d3d16 | 2016-03-15 14:15:57 +0000 | [diff] [blame] | 4035 | GetRietveldCodereviewSettingsInteractively() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4036 | return 0 |
| 4037 | |
| 4038 | url = args[0] |
| 4039 | if not url.endswith('codereview.settings'): |
| 4040 | url = os.path.join(url, 'codereview.settings') |
| 4041 | |
| 4042 | # Load code review settings and download hooks (if available). |
| 4043 | LoadCodereviewSettingsFromFile(urllib2.urlopen(url)) |
| 4044 | return 0 |
| 4045 | |
| 4046 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4047 | @metrics.collector.collect_metrics('git cl baseurl') |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 4048 | def CMDbaseurl(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4049 | """Gets or sets base-url for this branch.""" |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 4050 | branchref = RunGit(['symbolic-ref', 'HEAD']).strip() |
| 4051 | branch = ShortBranchName(branchref) |
| 4052 | _, args = parser.parse_args(args) |
| 4053 | if not args: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4054 | print('Current base-url:') |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 4055 | return RunGit(['config', 'branch.%s.base-url' % branch], |
| 4056 | error_ok=False).strip() |
| 4057 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4058 | print('Setting base-url to %s' % args[0]) |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 4059 | return RunGit(['config', 'branch.%s.base-url' % branch, args[0]], |
| 4060 | error_ok=False).strip() |
| 4061 | |
| 4062 | |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 4063 | def color_for_status(status): |
| 4064 | """Maps a Changelist status to color, for CMDstatus and other tools.""" |
| 4065 | return { |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4066 | 'unsent': Fore.YELLOW, |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 4067 | 'waiting': Fore.BLUE, |
| 4068 | 'reply': Fore.YELLOW, |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4069 | 'not lgtm': Fore.RED, |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 4070 | 'lgtm': Fore.GREEN, |
| 4071 | 'commit': Fore.MAGENTA, |
| 4072 | 'closed': Fore.CYAN, |
| 4073 | 'error': Fore.WHITE, |
| 4074 | }.get(status, Fore.WHITE) |
| 4075 | |
tandrii@chromium.org | 04ea846 | 2016-04-25 19:51:21 +0000 | [diff] [blame] | 4076 | |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4077 | def get_cl_statuses(changes, fine_grained, max_processes=None): |
| 4078 | """Returns a blocking iterable of (cl, status) for given branches. |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4079 | |
| 4080 | If fine_grained is true, this will fetch CL statuses from the server. |
| 4081 | Otherwise, simply indicate if there's a matching url for the given branches. |
| 4082 | |
| 4083 | If max_processes is specified, it is used as the maximum number of processes |
| 4084 | to spawn to fetch CL status from the server. Otherwise 1 process per branch is |
| 4085 | spawned. |
calamity@chromium.org | cf19748 | 2016-04-29 20:15:53 +0000 | [diff] [blame] | 4086 | |
| 4087 | See GetStatus() for a list of possible statuses. |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4088 | """ |
qyearsley | 12fa6ff | 2016-08-24 09:18:40 -0700 | [diff] [blame] | 4089 | # Silence upload.py otherwise it becomes unwieldy. |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4090 | upload.verbosity = 0 |
| 4091 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 4092 | if not changes: |
| 4093 | raise StopIteration() |
calamity@chromium.org | cf19748 | 2016-04-29 20:15:53 +0000 | [diff] [blame] | 4094 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 4095 | if not fine_grained: |
| 4096 | # Fast path which doesn't involve querying codereview servers. |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 4097 | # Do not use get_approving_reviewers(), since it requires an HTTP request. |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4098 | for cl in changes: |
| 4099 | yield (cl, 'waiting' if cl.GetIssueURL() else 'error') |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 4100 | return |
| 4101 | |
| 4102 | # First, sort out authentication issues. |
| 4103 | logging.debug('ensuring credentials exist') |
| 4104 | for cl in changes: |
| 4105 | cl.EnsureAuthenticated(force=False, refresh=True) |
| 4106 | |
| 4107 | def fetch(cl): |
| 4108 | try: |
| 4109 | return (cl, cl.GetStatus()) |
| 4110 | except: |
| 4111 | # See http://crbug.com/629863. |
Andrii Shyshkalov | 9882423 | 2018-04-19 11:37:15 -0700 | [diff] [blame] | 4112 | logging.exception('failed to fetch status for cl %s:', cl.GetIssue()) |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 4113 | raise |
| 4114 | |
| 4115 | threads_count = len(changes) |
| 4116 | if max_processes: |
| 4117 | threads_count = max(1, min(threads_count, max_processes)) |
| 4118 | logging.debug('querying %d CLs using %d threads', len(changes), threads_count) |
| 4119 | |
| 4120 | pool = ThreadPool(threads_count) |
| 4121 | fetched_cls = set() |
| 4122 | try: |
| 4123 | it = pool.imap_unordered(fetch, changes).__iter__() |
| 4124 | while True: |
| 4125 | try: |
| 4126 | cl, status = it.next(timeout=5) |
| 4127 | except multiprocessing.TimeoutError: |
| 4128 | break |
| 4129 | fetched_cls.add(cl) |
| 4130 | yield cl, status |
| 4131 | finally: |
| 4132 | pool.close() |
| 4133 | |
| 4134 | # Add any branches that failed to fetch. |
| 4135 | for cl in set(changes) - fetched_cls: |
| 4136 | yield (cl, 'error') |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 4137 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4138 | |
| 4139 | def upload_branch_deps(cl, args): |
| 4140 | """Uploads CLs of local branches that are dependents of the current branch. |
| 4141 | |
| 4142 | If the local branch dependency tree looks like: |
| 4143 | test1 -> test2.1 -> test3.1 |
| 4144 | -> test3.2 |
| 4145 | -> test2.2 -> test3.3 |
| 4146 | |
| 4147 | and you run "git cl upload --dependencies" from test1 then "git cl upload" is |
| 4148 | run on the dependent branches in this order: |
| 4149 | test2.1, test3.1, test3.2, test2.2, test3.3 |
| 4150 | |
| 4151 | Note: This function does not rebase your local dependent branches. Use it when |
| 4152 | you make a change to the parent branch that will not conflict with its |
| 4153 | dependent branches, and you would like their dependencies updated in |
| 4154 | Rietveld. |
| 4155 | """ |
| 4156 | if git_common.is_dirty_git_tree('upload-branch-deps'): |
| 4157 | return 1 |
| 4158 | |
| 4159 | root_branch = cl.GetBranch() |
| 4160 | if root_branch is None: |
| 4161 | DieWithError('Can\'t find dependent branches from detached HEAD state. ' |
| 4162 | 'Get on a branch!') |
Andrii Shyshkalov | 9f27443 | 2018-10-15 16:40:23 +0000 | [diff] [blame] | 4163 | if not cl.GetIssue(): |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4164 | DieWithError('Current branch does not have an uploaded CL. We cannot set ' |
| 4165 | 'patchset dependencies without an uploaded CL.') |
| 4166 | |
| 4167 | branches = RunGit(['for-each-ref', |
| 4168 | '--format=%(refname:short) %(upstream:short)', |
| 4169 | 'refs/heads']) |
| 4170 | if not branches: |
| 4171 | print('No local branches found.') |
| 4172 | return 0 |
| 4173 | |
| 4174 | # Create a dictionary of all local branches to the branches that are dependent |
| 4175 | # on it. |
| 4176 | tracked_to_dependents = collections.defaultdict(list) |
| 4177 | for b in branches.splitlines(): |
| 4178 | tokens = b.split() |
| 4179 | if len(tokens) == 2: |
| 4180 | branch_name, tracked = tokens |
| 4181 | tracked_to_dependents[tracked].append(branch_name) |
| 4182 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4183 | print() |
| 4184 | print('The dependent local branches of %s are:' % root_branch) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4185 | dependents = [] |
| 4186 | def traverse_dependents_preorder(branch, padding=''): |
| 4187 | dependents_to_process = tracked_to_dependents.get(branch, []) |
| 4188 | padding += ' ' |
| 4189 | for dependent in dependents_to_process: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4190 | print('%s%s' % (padding, dependent)) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4191 | dependents.append(dependent) |
| 4192 | traverse_dependents_preorder(dependent, padding) |
| 4193 | traverse_dependents_preorder(root_branch) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4194 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4195 | |
| 4196 | if not dependents: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4197 | print('There are no dependent local branches for %s' % root_branch) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4198 | return 0 |
| 4199 | |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 4200 | confirm_or_exit('This command will checkout all dependent branches and run ' |
| 4201 | '"git cl upload".', action='continue') |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4202 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4203 | # Record all dependents that failed to upload. |
| 4204 | failures = {} |
| 4205 | # Go through all dependents, checkout the branch and upload. |
| 4206 | try: |
| 4207 | for dependent_branch in dependents: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4208 | print() |
| 4209 | print('--------------------------------------') |
| 4210 | print('Running "git cl upload" from %s:' % dependent_branch) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4211 | RunGit(['checkout', '-q', dependent_branch]) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4212 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4213 | try: |
| 4214 | if CMDupload(OptionParser(), args) != 0: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4215 | print('Upload failed for %s!' % dependent_branch) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4216 | failures[dependent_branch] = 1 |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 4217 | except: # pylint: disable=bare-except |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4218 | failures[dependent_branch] = 1 |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4219 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4220 | finally: |
| 4221 | # Swap back to the original root branch. |
| 4222 | RunGit(['checkout', '-q', root_branch]) |
| 4223 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4224 | print() |
| 4225 | print('Upload complete for dependent branches!') |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4226 | for dependent_branch in dependents: |
| 4227 | upload_status = 'failed' if failures.get(dependent_branch) else 'succeeded' |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4228 | print(' %s : %s' % (dependent_branch, upload_status)) |
| 4229 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4230 | |
| 4231 | return 0 |
| 4232 | |
| 4233 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4234 | @metrics.collector.collect_metrics('git cl archive') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4235 | def CMDarchive(parser, args): |
| 4236 | """Archives and deletes branches associated with closed changelists.""" |
| 4237 | parser.add_option( |
| 4238 | '-j', '--maxjobs', action='store', type=int, |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4239 | help='The maximum number of jobs to use when retrieving review status.') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4240 | parser.add_option( |
| 4241 | '-f', '--force', action='store_true', |
| 4242 | help='Bypasses the confirmation prompt.') |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4243 | parser.add_option( |
| 4244 | '-d', '--dry-run', action='store_true', |
| 4245 | help='Skip the branch tagging and removal steps.') |
| 4246 | parser.add_option( |
| 4247 | '-t', '--notags', action='store_true', |
| 4248 | help='Do not tag archived branches. ' |
| 4249 | 'Note: local commit history may be lost.') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4250 | |
| 4251 | auth.add_auth_options(parser) |
| 4252 | options, args = parser.parse_args(args) |
| 4253 | if args: |
| 4254 | parser.error('Unsupported args: %s' % ' '.join(args)) |
| 4255 | auth_config = auth.extract_auth_config_from_options(options) |
| 4256 | |
| 4257 | branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads']) |
| 4258 | if not branches: |
| 4259 | return 0 |
| 4260 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4261 | print('Finding all branches associated with closed issues...') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4262 | changes = [Changelist(branchref=b, auth_config=auth_config) |
| 4263 | for b in branches.splitlines()] |
| 4264 | alignment = max(5, max(len(c.GetBranch()) for c in changes)) |
| 4265 | statuses = get_cl_statuses(changes, |
| 4266 | fine_grained=True, |
| 4267 | max_processes=options.maxjobs) |
| 4268 | proposal = [(cl.GetBranch(), |
| 4269 | 'git-cl-archived-%s-%s' % (cl.GetIssue(), cl.GetBranch())) |
| 4270 | for cl, status in statuses |
Andrii Shyshkalov | 51bdf8c | 2018-10-18 01:07:58 +0000 | [diff] [blame] | 4271 | if status in ('closed', 'rietveld-not-supported')] |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4272 | proposal.sort() |
| 4273 | |
| 4274 | if not proposal: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4275 | print('No branches with closed codereview issues found.') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4276 | return 0 |
| 4277 | |
| 4278 | current_branch = GetCurrentBranch() |
| 4279 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4280 | print('\nBranches with closed issues that will be archived:\n') |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4281 | if options.notags: |
| 4282 | for next_item in proposal: |
| 4283 | print(' ' + next_item[0]) |
| 4284 | else: |
| 4285 | print('%*s | %s' % (alignment, 'Branch name', 'Archival tag name')) |
| 4286 | for next_item in proposal: |
| 4287 | print('%*s %s' % (alignment, next_item[0], next_item[1])) |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4288 | |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4289 | # Quit now on precondition failure or if instructed by the user, either |
| 4290 | # via an interactive prompt or by command line flags. |
| 4291 | if options.dry_run: |
| 4292 | print('\nNo changes were made (dry run).\n') |
| 4293 | return 0 |
| 4294 | elif any(branch == current_branch for branch, _ in proposal): |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4295 | print('You are currently on a branch \'%s\' which is associated with a ' |
| 4296 | 'closed codereview issue, so archive cannot proceed. Please ' |
| 4297 | 'checkout another branch and run this command again.' % |
| 4298 | current_branch) |
| 4299 | return 1 |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4300 | elif not options.force: |
sergiyb | 4a5ecbe | 2016-06-20 09:46:00 -0700 | [diff] [blame] | 4301 | answer = ask_for_data('\nProceed with deletion (Y/n)? ').lower() |
| 4302 | if answer not in ('y', ''): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4303 | print('Aborted.') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4304 | return 1 |
| 4305 | |
| 4306 | for branch, tagname in proposal: |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4307 | if not options.notags: |
| 4308 | RunGit(['tag', tagname, branch]) |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4309 | RunGit(['branch', '-D', branch]) |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4310 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4311 | print('\nJob\'s done!') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4312 | |
| 4313 | return 0 |
| 4314 | |
| 4315 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4316 | @metrics.collector.collect_metrics('git cl status') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4317 | def CMDstatus(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4318 | """Show status of changelists. |
| 4319 | |
| 4320 | Colors are used to tell the state of the CL unless --fast is used: |
jsbell@chromium.org | aeab41a | 2013-12-10 20:01:22 +0000 | [diff] [blame] | 4321 | - Blue waiting for review |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4322 | - Yellow waiting for you to reply to review, or not yet sent |
jsbell@chromium.org | aeab41a | 2013-12-10 20:01:22 +0000 | [diff] [blame] | 4323 | - Green LGTM'ed |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4324 | - Red 'not LGTM'ed |
jsbell@chromium.org | aeab41a | 2013-12-10 20:01:22 +0000 | [diff] [blame] | 4325 | - Magenta in the commit queue |
| 4326 | - Cyan was committed, branch can be deleted |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4327 | - White error, or unknown status |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4328 | |
| 4329 | Also see 'git cl comments'. |
| 4330 | """ |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4331 | parser.add_option('--field', |
phajdan.jr | 289d03e | 2016-08-16 08:21:06 -0700 | [diff] [blame] | 4332 | help='print only specific field (desc|id|patch|status|url)') |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 4333 | parser.add_option('-f', '--fast', action='store_true', |
| 4334 | help='Do not retrieve review status') |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4335 | parser.add_option( |
| 4336 | '-j', '--maxjobs', action='store', type=int, |
| 4337 | help='The maximum number of jobs to use when retrieving review status') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4338 | |
| 4339 | auth.add_auth_options(parser) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 4340 | _add_codereview_issue_select_options( |
| 4341 | parser, 'Must be in conjunction with --field.') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4342 | options, args = parser.parse_args(args) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 4343 | _process_codereview_issue_select_options(parser, options) |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4344 | if args: |
| 4345 | parser.error('Unsupported args: %s' % args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4346 | auth_config = auth.extract_auth_config_from_options(options) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4347 | |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 4348 | if options.issue is not None and not options.field: |
| 4349 | parser.error('--field must be specified with --issue') |
iannucci | 3c972b9 | 2016-08-17 13:24:10 -0700 | [diff] [blame] | 4350 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4351 | if options.field: |
iannucci | 3c972b9 | 2016-08-17 13:24:10 -0700 | [diff] [blame] | 4352 | cl = Changelist(auth_config=auth_config, issue=options.issue, |
| 4353 | codereview=options.forced_codereview) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4354 | if options.field.startswith('desc'): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4355 | print(cl.GetDescription()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4356 | elif options.field == 'id': |
| 4357 | issueid = cl.GetIssue() |
| 4358 | if issueid: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4359 | print(issueid) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4360 | elif options.field == 'patch': |
Aaron Gable | e8856ee | 2017-12-07 12:41:46 -0800 | [diff] [blame] | 4361 | patchset = cl.GetMostRecentPatchset() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4362 | if patchset: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4363 | print(patchset) |
phajdan.jr | 289d03e | 2016-08-16 08:21:06 -0700 | [diff] [blame] | 4364 | elif options.field == 'status': |
| 4365 | print(cl.GetStatus()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4366 | elif options.field == 'url': |
| 4367 | url = cl.GetIssueURL() |
| 4368 | if url: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4369 | print(url) |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 4370 | return 0 |
| 4371 | |
| 4372 | branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads']) |
| 4373 | if not branches: |
| 4374 | print('No local branch found.') |
| 4375 | return 0 |
| 4376 | |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4377 | changes = [ |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4378 | Changelist(branchref=b, auth_config=auth_config) |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4379 | for b in branches.splitlines()] |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4380 | print('Branches associated with reviews:') |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4381 | output = get_cl_statuses(changes, |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4382 | fine_grained=not options.fast, |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4383 | max_processes=options.maxjobs) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 4384 | |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4385 | branch_statuses = {} |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4386 | alignment = max(5, max(len(ShortBranchName(c.GetBranch())) for c in changes)) |
| 4387 | for cl in sorted(changes, key=lambda c: c.GetBranch()): |
| 4388 | branch = cl.GetBranch() |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4389 | while branch not in branch_statuses: |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4390 | c, status = output.next() |
| 4391 | branch_statuses[c.GetBranch()] = status |
| 4392 | status = branch_statuses.pop(branch) |
| 4393 | url = cl.GetIssueURL() |
| 4394 | if url and (not status or status == 'error'): |
| 4395 | # The issue probably doesn't exist anymore. |
| 4396 | url += ' (broken)' |
| 4397 | |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 4398 | color = color_for_status(status) |
maruel@chromium.org | 885f651 | 2013-07-27 02:17:26 +0000 | [diff] [blame] | 4399 | reset = Fore.RESET |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 4400 | if not setup_color.IS_TTY: |
maruel@chromium.org | 885f651 | 2013-07-27 02:17:26 +0000 | [diff] [blame] | 4401 | color = '' |
| 4402 | reset = '' |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 4403 | status_str = '(%s)' % status if status else '' |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4404 | print(' %*s : %s%s %s%s' % ( |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4405 | alignment, ShortBranchName(branch), color, url, |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4406 | status_str, reset)) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 4407 | |
Andrii Shyshkalov | d0e1d9d | 2017-01-24 17:10:51 +0100 | [diff] [blame] | 4408 | |
| 4409 | branch = GetCurrentBranch() |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4410 | print() |
Andrii Shyshkalov | d0e1d9d | 2017-01-24 17:10:51 +0100 | [diff] [blame] | 4411 | print('Current branch: %s' % branch) |
| 4412 | for cl in changes: |
| 4413 | if cl.GetBranch() == branch: |
| 4414 | break |
dpranke@chromium.org | ee87f58 | 2015-07-31 18:46:25 +0000 | [diff] [blame] | 4415 | if not cl.GetIssue(): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4416 | print('No issue assigned.') |
dpranke@chromium.org | ee87f58 | 2015-07-31 18:46:25 +0000 | [diff] [blame] | 4417 | return 0 |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4418 | print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())) |
maruel@chromium.org | 85616e0 | 2014-07-28 15:37:55 +0000 | [diff] [blame] | 4419 | if not options.fast: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4420 | print('Issue description:') |
| 4421 | print(cl.GetDescription(pretty=True)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4422 | return 0 |
| 4423 | |
| 4424 | |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4425 | def colorize_CMDstatus_doc(): |
| 4426 | """To be called once in main() to add colors to git cl status help.""" |
| 4427 | colors = [i for i in dir(Fore) if i[0].isupper()] |
| 4428 | |
| 4429 | def colorize_line(line): |
| 4430 | for color in colors: |
| 4431 | if color in line.upper(): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 4432 | # Extract whitespace first and the leading '-'. |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4433 | indent = len(line) - len(line.lstrip(' ')) + 1 |
| 4434 | return line[:indent] + getattr(Fore, color) + line[indent:] + Fore.RESET |
| 4435 | return line |
| 4436 | |
| 4437 | lines = CMDstatus.__doc__.splitlines() |
| 4438 | CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines) |
| 4439 | |
| 4440 | |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4441 | def write_json(path, contents): |
Stefan Zager | 1306bd0 | 2017-06-22 19:26:46 -0700 | [diff] [blame] | 4442 | if path == '-': |
| 4443 | json.dump(contents, sys.stdout) |
| 4444 | else: |
| 4445 | with open(path, 'w') as f: |
| 4446 | json.dump(contents, f) |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4447 | |
| 4448 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4449 | @subcommand.usage('[issue_number]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4450 | @metrics.collector.collect_metrics('git cl issue') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4451 | def CMDissue(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4452 | """Sets or displays the current code review issue number. |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4453 | |
| 4454 | Pass issue number 0 to clear the current issue. |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4455 | """ |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4456 | parser.add_option('-r', '--reverse', action='store_true', |
| 4457 | help='Lookup the branch(es) for the specified issues. If ' |
| 4458 | 'no issues are specified, all branches with mapped ' |
| 4459 | 'issues will be listed.') |
Stefan Zager | 1306bd0 | 2017-06-22 19:26:46 -0700 | [diff] [blame] | 4460 | parser.add_option('--json', |
| 4461 | help='Path to JSON output file, or "-" for stdout.') |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4462 | _add_codereview_select_options(parser) |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4463 | options, args = parser.parse_args(args) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4464 | _process_codereview_select_options(parser, options) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4465 | |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4466 | if options.reverse: |
| 4467 | branches = RunGit(['for-each-ref', 'refs/heads', |
Aaron Gable | ad64abd | 2017-12-04 09:49:13 -0800 | [diff] [blame] | 4468 | '--format=%(refname)']).splitlines() |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4469 | # Reverse issue lookup. |
| 4470 | issue_branch_map = {} |
Daniel Bratell | b56a43a | 2018-09-06 15:49:03 +0000 | [diff] [blame] | 4471 | |
| 4472 | git_config = {} |
| 4473 | for config in RunGit(['config', '--get-regexp', |
| 4474 | r'branch\..*issue']).splitlines(): |
| 4475 | name, _space, val = config.partition(' ') |
| 4476 | git_config[name] = val |
| 4477 | |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4478 | for branch in branches: |
Daniel Bratell | b56a43a | 2018-09-06 15:49:03 +0000 | [diff] [blame] | 4479 | for cls in _CODEREVIEW_IMPLEMENTATIONS.values(): |
| 4480 | config_key = _git_branch_config_key(ShortBranchName(branch), |
| 4481 | cls.IssueConfigKey()) |
| 4482 | issue = git_config.get(config_key) |
| 4483 | if issue: |
| 4484 | issue_branch_map.setdefault(int(issue), []).append(branch) |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4485 | if not args: |
| 4486 | args = sorted(issue_branch_map.iterkeys()) |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4487 | result = {} |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4488 | for issue in args: |
| 4489 | if not issue: |
| 4490 | continue |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4491 | result[int(issue)] = issue_branch_map.get(int(issue)) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4492 | print('Branch for issue number %s: %s' % ( |
| 4493 | issue, ', '.join(issue_branch_map.get(int(issue)) or ('None',)))) |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4494 | if options.json: |
| 4495 | write_json(options.json, result) |
Aaron Gable | 78753da | 2017-06-15 10:35:49 -0700 | [diff] [blame] | 4496 | return 0 |
| 4497 | |
| 4498 | if len(args) > 0: |
| 4499 | issue = ParseIssueNumberArgument(args[0], options.forced_codereview) |
| 4500 | if not issue.valid: |
| 4501 | DieWithError('Pass a url or number to set the issue, 0 to unset it, ' |
| 4502 | 'or no argument to list it.\n' |
| 4503 | 'Maybe you want to run git cl status?') |
| 4504 | cl = Changelist(codereview=issue.codereview) |
| 4505 | cl.SetIssue(issue.issue) |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4506 | else: |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4507 | cl = Changelist(codereview=options.forced_codereview) |
Aaron Gable | 78753da | 2017-06-15 10:35:49 -0700 | [diff] [blame] | 4508 | print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())) |
| 4509 | if options.json: |
| 4510 | write_json(options.json, { |
| 4511 | 'issue': cl.GetIssue(), |
| 4512 | 'issue_url': cl.GetIssueURL(), |
| 4513 | }) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4514 | return 0 |
| 4515 | |
| 4516 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4517 | @metrics.collector.collect_metrics('git cl comments') |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 4518 | def CMDcomments(parser, args): |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4519 | """Shows or posts review comments for any changelist.""" |
| 4520 | parser.add_option('-a', '--add-comment', dest='comment', |
| 4521 | help='comment to add to an issue') |
Sergiy Byelozyorov | cb629a4 | 2018-10-28 19:20:39 +0000 | [diff] [blame^] | 4522 | parser.add_option('-p', '--publish', action='store_true', |
| 4523 | help='marks CL as ready and sends comment to reviewers') |
Andrii Shyshkalov | 0d6b46e | 2017-03-17 22:23:22 +0100 | [diff] [blame] | 4524 | parser.add_option('-i', '--issue', dest='issue', |
| 4525 | help='review issue id (defaults to current issue). ' |
| 4526 | 'If given, requires --rietveld or --gerrit') |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 4527 | parser.add_option('-m', '--machine-readable', dest='readable', |
| 4528 | action='store_false', default=True, |
| 4529 | help='output comments in a format compatible with ' |
| 4530 | 'editor parsing') |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 4531 | parser.add_option('-j', '--json-file', |
Stefan Zager | 1306bd0 | 2017-06-22 19:26:46 -0700 | [diff] [blame] | 4532 | help='File to write JSON summary to, or "-" for stdout') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4533 | auth.add_auth_options(parser) |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 4534 | _add_codereview_select_options(parser) |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4535 | options, args = parser.parse_args(args) |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 4536 | _process_codereview_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4537 | auth_config = auth.extract_auth_config_from_options(options) |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 4538 | |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4539 | issue = None |
| 4540 | if options.issue: |
| 4541 | try: |
| 4542 | issue = int(options.issue) |
| 4543 | except ValueError: |
| 4544 | DieWithError('A review issue id is expected to be a number') |
| 4545 | |
Andrii Shyshkalov | 642641d | 2018-10-16 05:54:41 +0000 | [diff] [blame] | 4546 | cl = Changelist(issue=issue, codereview='gerrit', auth_config=auth_config) |
| 4547 | |
| 4548 | if not cl.IsGerrit(): |
| 4549 | parser.error('rietveld is not supported') |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4550 | |
| 4551 | if options.comment: |
Sergiy Byelozyorov | cb629a4 | 2018-10-28 19:20:39 +0000 | [diff] [blame^] | 4552 | cl.AddComment(options.comment, options.publish) |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4553 | return 0 |
| 4554 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 4555 | summary = sorted(cl.GetCommentsSummary(readable=options.readable), |
| 4556 | key=lambda c: c.date) |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4557 | for comment in summary: |
| 4558 | if comment.disapproval: |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4559 | color = Fore.RED |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4560 | elif comment.approval: |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4561 | color = Fore.GREEN |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4562 | elif comment.sender == cl.GetIssueOwner(): |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4563 | color = Fore.MAGENTA |
| 4564 | else: |
| 4565 | color = Fore.BLUE |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4566 | print('\n%s%s %s%s\n%s' % ( |
| 4567 | color, |
| 4568 | comment.date.strftime('%Y-%m-%d %H:%M:%S UTC'), |
| 4569 | comment.sender, |
| 4570 | Fore.RESET, |
| 4571 | '\n'.join(' ' + l for l in comment.message.strip().splitlines()))) |
| 4572 | |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 4573 | if options.json_file: |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4574 | def pre_serialize(c): |
| 4575 | dct = c.__dict__.copy() |
| 4576 | dct['date'] = dct['date'].strftime('%Y-%m-%d %H:%M:%S.%f') |
| 4577 | return dct |
Leszek Swirski | 45b20c4 | 2018-09-17 17:05:26 +0000 | [diff] [blame] | 4578 | write_json(options.json_file, map(pre_serialize, summary)) |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 4579 | return 0 |
| 4580 | |
| 4581 | |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4582 | @subcommand.usage('[codereview url or issue id]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4583 | @metrics.collector.collect_metrics('git cl description') |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4584 | def CMDdescription(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4585 | """Brings up the editor for the current CL's description.""" |
smut@google.com | 34fb6b1 | 2015-07-13 20:03:26 +0000 | [diff] [blame] | 4586 | parser.add_option('-d', '--display', action='store_true', |
| 4587 | help='Display the description instead of opening an editor') |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4588 | parser.add_option('-n', '--new-description', |
dnj | ba1b0f3 | 2016-09-02 12:37:42 -0700 | [diff] [blame] | 4589 | help='New description to set for this issue (- for stdin, ' |
| 4590 | '+ to load from local commit HEAD)') |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 4591 | parser.add_option('-f', '--force', action='store_true', |
| 4592 | help='Delete any unpublished Gerrit edits for this issue ' |
| 4593 | 'without prompting') |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4594 | |
| 4595 | _add_codereview_select_options(parser) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4596 | auth.add_auth_options(parser) |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4597 | options, args = parser.parse_args(args) |
| 4598 | _process_codereview_select_options(parser, options) |
| 4599 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 4600 | target_issue_arg = None |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4601 | if len(args) > 0: |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4602 | target_issue_arg = ParseIssueNumberArgument(args[0], |
| 4603 | options.forced_codereview) |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 4604 | if not target_issue_arg.valid: |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 4605 | parser.error('invalid codereview url or CL id') |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4606 | |
martiniss | 6eda05f | 2016-06-30 10:18:35 -0700 | [diff] [blame] | 4607 | kwargs = { |
Andrii Shyshkalov | dd672fb | 2018-10-16 06:09:51 +0000 | [diff] [blame] | 4608 | 'auth_config': auth.extract_auth_config_from_options(options), |
| 4609 | 'codereview': options.forced_codereview, |
martiniss | 6eda05f | 2016-06-30 10:18:35 -0700 | [diff] [blame] | 4610 | } |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4611 | detected_codereview_from_url = False |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 4612 | if target_issue_arg: |
| 4613 | kwargs['issue'] = target_issue_arg.issue |
| 4614 | kwargs['codereview_host'] = target_issue_arg.hostname |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4615 | if target_issue_arg.codereview and not options.forced_codereview: |
| 4616 | detected_codereview_from_url = True |
| 4617 | kwargs['codereview'] = target_issue_arg.codereview |
martiniss | 6eda05f | 2016-06-30 10:18:35 -0700 | [diff] [blame] | 4618 | |
| 4619 | cl = Changelist(**kwargs) |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4620 | if not cl.GetIssue(): |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4621 | assert not detected_codereview_from_url |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4622 | DieWithError('This branch has no associated changelist.') |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4623 | |
| 4624 | if detected_codereview_from_url: |
| 4625 | logging.info('canonical issue/change URL: %s (type: %s)\n', |
| 4626 | cl.GetIssueURL(), target_issue_arg.codereview) |
| 4627 | |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4628 | description = ChangeDescription(cl.GetDescription()) |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4629 | |
smut@google.com | 34fb6b1 | 2015-07-13 20:03:26 +0000 | [diff] [blame] | 4630 | if options.display: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4631 | print(description.description) |
smut@google.com | 34fb6b1 | 2015-07-13 20:03:26 +0000 | [diff] [blame] | 4632 | return 0 |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4633 | |
| 4634 | if options.new_description: |
| 4635 | text = options.new_description |
| 4636 | if text == '-': |
| 4637 | text = '\n'.join(l.rstrip() for l in sys.stdin) |
dnj | ba1b0f3 | 2016-09-02 12:37:42 -0700 | [diff] [blame] | 4638 | elif text == '+': |
| 4639 | base_branch = cl.GetCommonAncestorWithUpstream() |
| 4640 | change = cl.GetChange(base_branch, None, local_description=True) |
| 4641 | text = change.FullDescriptionText() |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4642 | |
| 4643 | description.set_description(text) |
| 4644 | else: |
Aaron Gable | 3a16ed1 | 2017-03-23 10:51:55 -0700 | [diff] [blame] | 4645 | description.prompt(git_footer=cl.IsGerrit()) |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4646 | |
Andrii Shyshkalov | 680253d | 2017-03-15 21:07:36 +0100 | [diff] [blame] | 4647 | if cl.GetDescription().strip() != description.description: |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 4648 | cl.UpdateDescription(description.description, force=options.force) |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4649 | return 0 |
| 4650 | |
| 4651 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4652 | @metrics.collector.collect_metrics('git cl lint') |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4653 | def CMDlint(parser, args): |
| 4654 | """Runs cpplint on the current changelist.""" |
tzik@chromium.org | f204d4b | 2014-03-13 07:40:55 +0000 | [diff] [blame] | 4655 | parser.add_option('--filter', action='append', metavar='-x,+y', |
| 4656 | help='Comma-separated list of cpplint\'s category-filters') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4657 | auth.add_auth_options(parser) |
| 4658 | options, args = parser.parse_args(args) |
| 4659 | auth_config = auth.extract_auth_config_from_options(options) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4660 | |
| 4661 | # Access to a protected member _XX of a client class |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 4662 | # pylint: disable=protected-access |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4663 | try: |
| 4664 | import cpplint |
| 4665 | import cpplint_chromium |
| 4666 | except ImportError: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4667 | print('Your depot_tools is missing cpplint.py and/or cpplint_chromium.py.') |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4668 | return 1 |
| 4669 | |
| 4670 | # Change the current working directory before calling lint so that it |
| 4671 | # shows the correct base. |
| 4672 | previous_cwd = os.getcwd() |
| 4673 | os.chdir(settings.GetRoot()) |
| 4674 | try: |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4675 | cl = Changelist(auth_config=auth_config) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4676 | change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None) |
| 4677 | files = [f.LocalPath() for f in change.AffectedFiles()] |
thestig@chromium.org | 5839eb5 | 2014-05-30 16:20:51 +0000 | [diff] [blame] | 4678 | if not files: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4679 | print('Cannot lint an empty CL') |
thestig@chromium.org | 5839eb5 | 2014-05-30 16:20:51 +0000 | [diff] [blame] | 4680 | return 1 |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4681 | |
| 4682 | # Process cpplints arguments if any. |
tzik@chromium.org | f204d4b | 2014-03-13 07:40:55 +0000 | [diff] [blame] | 4683 | command = args + files |
| 4684 | if options.filter: |
| 4685 | command = ['--filter=' + ','.join(options.filter)] + command |
| 4686 | filenames = cpplint.ParseArguments(command) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4687 | |
| 4688 | white_regex = re.compile(settings.GetLintRegex()) |
| 4689 | black_regex = re.compile(settings.GetLintIgnoreRegex()) |
| 4690 | extra_check_functions = [cpplint_chromium.CheckPointerDeclarationWhitespace] |
| 4691 | for filename in filenames: |
| 4692 | if white_regex.match(filename): |
| 4693 | if black_regex.match(filename): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4694 | print('Ignoring file %s' % filename) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4695 | else: |
| 4696 | cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level, |
| 4697 | extra_check_functions) |
| 4698 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4699 | print('Skipping file %s' % filename) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4700 | finally: |
| 4701 | os.chdir(previous_cwd) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4702 | print('Total errors found: %d\n' % cpplint._cpplint_state.error_count) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4703 | if cpplint._cpplint_state.error_count != 0: |
| 4704 | return 1 |
| 4705 | return 0 |
| 4706 | |
| 4707 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4708 | @metrics.collector.collect_metrics('git cl presubmit') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4709 | def CMDpresubmit(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4710 | """Runs presubmit tests on the current changelist.""" |
ilevy@chromium.org | 375a902 | 2013-01-07 01:12:05 +0000 | [diff] [blame] | 4711 | parser.add_option('-u', '--upload', action='store_true', |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 4712 | help='Run upload hook instead of the push hook') |
ilevy@chromium.org | 375a902 | 2013-01-07 01:12:05 +0000 | [diff] [blame] | 4713 | parser.add_option('-f', '--force', action='store_true', |
sbc@chromium.org | 495ad15 | 2012-09-04 23:07:42 +0000 | [diff] [blame] | 4714 | help='Run checks even if tree is dirty') |
Aaron Gable | 8076c28 | 2017-11-29 14:39:41 -0800 | [diff] [blame] | 4715 | parser.add_option('--all', action='store_true', |
| 4716 | help='Run checks against all files, not just modified ones') |
Edward Lesmes | 8e28279 | 2018-04-03 18:50:29 -0400 | [diff] [blame] | 4717 | parser.add_option('--parallel', action='store_true', |
| 4718 | help='Run all tests specified by input_api.RunTests in all ' |
| 4719 | 'PRESUBMIT files in parallel.') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4720 | auth.add_auth_options(parser) |
| 4721 | options, args = parser.parse_args(args) |
| 4722 | auth_config = auth.extract_auth_config_from_options(options) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4723 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 4724 | if not options.force and git_common.is_dirty_git_tree('presubmit'): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4725 | print('use --force to check even if tree is dirty.') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4726 | return 1 |
| 4727 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4728 | cl = Changelist(auth_config=auth_config) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4729 | if args: |
| 4730 | base_branch = args[0] |
| 4731 | else: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 4732 | # Default to diffing against the common ancestor of the upstream branch. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 4733 | base_branch = cl.GetCommonAncestorWithUpstream() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4734 | |
Aaron Gable | 8076c28 | 2017-11-29 14:39:41 -0800 | [diff] [blame] | 4735 | if options.all: |
| 4736 | base_change = cl.GetChange(base_branch, None) |
| 4737 | files = [('M', f) for f in base_change.AllFiles()] |
| 4738 | change = presubmit_support.GitChange( |
| 4739 | base_change.Name(), |
| 4740 | base_change.FullDescriptionText(), |
| 4741 | base_change.RepositoryRoot(), |
| 4742 | files, |
| 4743 | base_change.issue, |
| 4744 | base_change.patchset, |
| 4745 | base_change.author_email, |
| 4746 | base_change._upstream) |
| 4747 | else: |
| 4748 | change = cl.GetChange(base_branch, None) |
| 4749 | |
ilevy@chromium.org | 051ad0e | 2013-03-04 21:57:34 +0000 | [diff] [blame] | 4750 | cl.RunHook( |
| 4751 | committing=not options.upload, |
| 4752 | may_prompt=False, |
| 4753 | verbose=options.verbose, |
Edward Lesmes | 8e28279 | 2018-04-03 18:50:29 -0400 | [diff] [blame] | 4754 | change=change, |
| 4755 | parallel=options.parallel) |
dpranke@chromium.org | 0a2bb37 | 2011-03-25 01:16:22 +0000 | [diff] [blame] | 4756 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4757 | |
| 4758 | |
tandrii@chromium.org | 65874e1 | 2016-03-04 12:03:02 +0000 | [diff] [blame] | 4759 | def GenerateGerritChangeId(message): |
| 4760 | """Returns Ixxxxxx...xxx change id. |
| 4761 | |
| 4762 | Works the same way as |
| 4763 | https://gerrit-review.googlesource.com/tools/hooks/commit-msg |
| 4764 | but can be called on demand on all platforms. |
| 4765 | |
| 4766 | The basic idea is to generate git hash of a state of the tree, original commit |
| 4767 | message, author/committer info and timestamps. |
| 4768 | """ |
| 4769 | lines = [] |
| 4770 | tree_hash = RunGitSilent(['write-tree']) |
| 4771 | lines.append('tree %s' % tree_hash.strip()) |
| 4772 | code, parent = RunGitWithCode(['rev-parse', 'HEAD~0'], suppress_stderr=False) |
| 4773 | if code == 0: |
| 4774 | lines.append('parent %s' % parent.strip()) |
| 4775 | author = RunGitSilent(['var', 'GIT_AUTHOR_IDENT']) |
| 4776 | lines.append('author %s' % author.strip()) |
| 4777 | committer = RunGitSilent(['var', 'GIT_COMMITTER_IDENT']) |
| 4778 | lines.append('committer %s' % committer.strip()) |
| 4779 | lines.append('') |
| 4780 | # Note: Gerrit's commit-hook actually cleans message of some lines and |
| 4781 | # whitespace. This code is not doing this, but it clearly won't decrease |
| 4782 | # entropy. |
| 4783 | lines.append(message) |
| 4784 | change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'], |
| 4785 | stdin='\n'.join(lines)) |
| 4786 | return 'I%s' % change_hash.strip() |
| 4787 | |
| 4788 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 4789 | def GetTargetRef(remote, remote_branch, target_branch): |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4790 | """Computes the remote branch ref to use for the CL. |
| 4791 | |
| 4792 | Args: |
| 4793 | remote (str): The git remote for the CL. |
| 4794 | remote_branch (str): The git remote branch for the CL. |
| 4795 | target_branch (str): The target branch specified by the user. |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4796 | """ |
| 4797 | if not (remote and remote_branch): |
| 4798 | return None |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 4799 | |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4800 | if target_branch: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 4801 | # Canonicalize branch references to the equivalent local full symbolic |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4802 | # refs, which are then translated into the remote full symbolic refs |
| 4803 | # below. |
| 4804 | if '/' not in target_branch: |
| 4805 | remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch) |
| 4806 | else: |
| 4807 | prefix_replacements = ( |
| 4808 | ('^((refs/)?remotes/)?branch-heads/', 'refs/remotes/branch-heads/'), |
| 4809 | ('^((refs/)?remotes/)?%s/' % remote, 'refs/remotes/%s/' % remote), |
| 4810 | ('^(refs/)?heads/', 'refs/remotes/%s/' % remote), |
| 4811 | ) |
| 4812 | match = None |
| 4813 | for regex, replacement in prefix_replacements: |
| 4814 | match = re.search(regex, target_branch) |
| 4815 | if match: |
| 4816 | remote_branch = target_branch.replace(match.group(0), replacement) |
| 4817 | break |
| 4818 | if not match: |
| 4819 | # This is a branch path but not one we recognize; use as-is. |
| 4820 | remote_branch = target_branch |
rmistry@google.com | c68112d | 2015-03-03 12:48:06 +0000 | [diff] [blame] | 4821 | elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS: |
| 4822 | # Handle the refs that need to land in different refs. |
| 4823 | remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch] |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 4824 | |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4825 | # Create the true path to the remote branch. |
| 4826 | # Does the following translation: |
| 4827 | # * refs/remotes/origin/refs/diff/test -> refs/diff/test |
| 4828 | # * refs/remotes/origin/master -> refs/heads/master |
| 4829 | # * refs/remotes/branch-heads/test -> refs/branch-heads/test |
| 4830 | if remote_branch.startswith('refs/remotes/%s/refs/' % remote): |
| 4831 | remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '') |
| 4832 | elif remote_branch.startswith('refs/remotes/%s/' % remote): |
| 4833 | remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, |
| 4834 | 'refs/heads/') |
| 4835 | elif remote_branch.startswith('refs/remotes/branch-heads'): |
| 4836 | remote_branch = remote_branch.replace('refs/remotes/', 'refs/') |
Andrii Shyshkalov | 768f1d8 | 2016-12-08 15:10:13 +0100 | [diff] [blame] | 4837 | |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4838 | return remote_branch |
| 4839 | |
| 4840 | |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4841 | def cleanup_list(l): |
| 4842 | """Fixes a list so that comma separated items are put as individual items. |
| 4843 | |
| 4844 | So that "--reviewers joe@c,john@c --reviewers joa@c" results in |
| 4845 | options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']). |
| 4846 | """ |
| 4847 | items = sum((i.split(',') for i in l), []) |
| 4848 | stripped_items = (i.strip() for i in items) |
| 4849 | return sorted(filter(None, stripped_items)) |
| 4850 | |
| 4851 | |
Aaron Gable | 4db38df | 2017-11-03 14:59:07 -0700 | [diff] [blame] | 4852 | @subcommand.usage('[flags]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4853 | @metrics.collector.collect_metrics('git cl upload') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4854 | def CMDupload(parser, args): |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 4855 | """Uploads the current changelist to codereview. |
| 4856 | |
| 4857 | Can skip dependency patchset uploads for a branch by running: |
| 4858 | git config branch.branch_name.skip-deps-uploads True |
| 4859 | To unset run: |
| 4860 | git config --unset branch.branch_name.skip-deps-uploads |
| 4861 | Can also set the above globally by using the --global flag. |
Dominic Battre | 7d1c484 | 2017-10-27 09:17:28 +0200 | [diff] [blame] | 4862 | |
| 4863 | If the name of the checked out branch starts with "bug-" or "fix-" followed by |
| 4864 | a bug number, this bug number is automatically populated in the CL |
| 4865 | description. |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 4866 | |
| 4867 | If subject contains text in square brackets or has "<text>: " prefix, such |
| 4868 | text(s) is treated as Gerrit hashtags. For example, CLs with subjects |
| 4869 | [git-cl] add support for hashtags |
| 4870 | Foo bar: implement foo |
| 4871 | will be hashtagged with "git-cl" and "foo-bar" respectively. |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 4872 | """ |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4873 | parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 4874 | help='bypass upload presubmit hook') |
brettw@chromium.org | b65c43c | 2013-06-10 22:04:49 +0000 | [diff] [blame] | 4875 | parser.add_option('--bypass-watchlists', action='store_true', |
| 4876 | dest='bypass_watchlists', |
| 4877 | help='bypass watchlists auto CC-ing reviewers') |
Aaron Gable | f7543cd | 2017-07-20 14:26:31 -0700 | [diff] [blame] | 4878 | parser.add_option('-f', '--force', action='store_true', dest='force', |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4879 | help="force yes to questions (don't prompt)") |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 4880 | parser.add_option('--message', '-m', dest='message', |
| 4881 | help='message for patchset') |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 4882 | parser.add_option('-b', '--bug', |
| 4883 | help='pre-populate the bug number(s) for this issue. ' |
| 4884 | 'If several, separate with commas') |
tandrii | b80458a | 2016-06-23 12:20:07 -0700 | [diff] [blame] | 4885 | parser.add_option('--message-file', dest='message_file', |
| 4886 | help='file which contains message for patchset') |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 4887 | parser.add_option('--title', '-t', dest='title', |
| 4888 | help='title for patchset') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4889 | parser.add_option('-r', '--reviewers', |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4890 | action='append', default=[], |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4891 | help='reviewer email addresses') |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 4892 | parser.add_option('--tbrs', |
| 4893 | action='append', default=[], |
| 4894 | help='TBR email addresses') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4895 | parser.add_option('--cc', |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4896 | action='append', default=[], |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4897 | help='cc email addresses') |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 4898 | parser.add_option('--hashtag', dest='hashtags', |
| 4899 | action='append', default=[], |
| 4900 | help=('Gerrit hashtag for new CL; ' |
| 4901 | 'can be applied multiple times')) |
adamk@chromium.org | 36f4730 | 2013-04-05 01:08:31 +0000 | [diff] [blame] | 4902 | parser.add_option('-s', '--send-mail', action='store_true', |
Aaron Gable | 59f4851 | 2017-01-12 10:54:46 -0800 | [diff] [blame] | 4903 | help='send email to reviewer(s) and cc(s) immediately') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4904 | parser.add_option('-c', '--use-commit-queue', action='store_true', |
Aaron Gable | edbc413 | 2017-09-11 13:22:28 -0700 | [diff] [blame] | 4905 | help='tell the commit queue to commit this patchset; ' |
| 4906 | 'implies --send-mail') |
ukai@chromium.org | 8ef7ab2 | 2012-11-28 04:24:52 +0000 | [diff] [blame] | 4907 | parser.add_option('--target_branch', |
pgervais@chromium.org | b9f2751 | 2014-08-08 15:52:33 +0000 | [diff] [blame] | 4908 | '--target-branch', |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4909 | metavar='TARGET', |
| 4910 | help='Apply CL to remote ref TARGET. ' + |
| 4911 | 'Default: remote branch head, or master') |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 4912 | parser.add_option('--squash', action='store_true', |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 4913 | help='Squash multiple commits into one') |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 4914 | parser.add_option('--no-squash', action='store_true', |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 4915 | help='Don\'t squash multiple commits into one') |
rmistry | 9eadede | 2016-09-19 11:22:43 -0700 | [diff] [blame] | 4916 | parser.add_option('--topic', default=None, |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 4917 | help='Topic to specify when uploading') |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 4918 | parser.add_option('--tbr-owners', dest='add_owners_to', action='store_const', |
| 4919 | const='TBR', help='add a set of OWNERS to TBR') |
| 4920 | parser.add_option('--r-owners', dest='add_owners_to', action='store_const', |
| 4921 | const='R', help='add a set of OWNERS to R') |
tandrii@chromium.org | d50452a | 2015-11-23 16:38:15 +0000 | [diff] [blame] | 4922 | parser.add_option('-d', '--cq-dry-run', dest='cq_dry_run', |
| 4923 | action='store_true', |
rmistry@google.com | ef96622 | 2015-04-07 11:15:01 +0000 | [diff] [blame] | 4924 | help='Send the patchset to do a CQ dry run right after ' |
| 4925 | 'upload.') |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4926 | parser.add_option('--dependencies', action='store_true', |
| 4927 | help='Uploads CLs of all the local branches that depend on ' |
| 4928 | 'the current branch') |
Ravi Mistry | 31e7d56 | 2018-04-02 12:53:57 -0400 | [diff] [blame] | 4929 | parser.add_option('-a', '--enable-auto-submit', action='store_true', |
| 4930 | help='Sends your change to the CQ after an approval. Only ' |
| 4931 | 'works on repos that have the Auto-Submit label ' |
| 4932 | 'enabled') |
Edward Lesmes | 8e28279 | 2018-04-03 18:50:29 -0400 | [diff] [blame] | 4933 | parser.add_option('--parallel', action='store_true', |
| 4934 | help='Run all tests specified by input_api.RunTests in all ' |
| 4935 | 'PRESUBMIT files in parallel.') |
pgervais@chromium.org | 9114137 | 2014-01-09 23:27:20 +0000 | [diff] [blame] | 4936 | |
Sergiy Byelozyorov | 1aa405f | 2018-09-18 17:38:43 +0000 | [diff] [blame] | 4937 | parser.add_option('--no-autocc', action='store_true', |
| 4938 | help='Disables automatic addition of CC emails') |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 4939 | parser.add_option('--private', action='store_true', |
Sergiy Byelozyorov | 1aa405f | 2018-09-18 17:38:43 +0000 | [diff] [blame] | 4940 | help='Set the review private. This implies --no-autocc.') |
| 4941 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4942 | orig_args = args |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4943 | auth.add_auth_options(parser) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4944 | _add_codereview_select_options(parser) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4945 | (options, args) = parser.parse_args(args) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4946 | _process_codereview_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4947 | auth_config = auth.extract_auth_config_from_options(options) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4948 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 4949 | if git_common.is_dirty_git_tree('upload'): |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4950 | return 1 |
| 4951 | |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4952 | options.reviewers = cleanup_list(options.reviewers) |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 4953 | options.tbrs = cleanup_list(options.tbrs) |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4954 | options.cc = cleanup_list(options.cc) |
| 4955 | |
tandrii | b80458a | 2016-06-23 12:20:07 -0700 | [diff] [blame] | 4956 | if options.message_file: |
| 4957 | if options.message: |
| 4958 | parser.error('only one of --message and --message-file allowed.') |
| 4959 | options.message = gclient_utils.FileRead(options.message_file) |
| 4960 | options.message_file = None |
| 4961 | |
tandrii | 4d0545a | 2016-07-06 03:56:49 -0700 | [diff] [blame] | 4962 | if options.cq_dry_run and options.use_commit_queue: |
| 4963 | parser.error('only one of --use-commit-queue and --cq-dry-run allowed.') |
| 4964 | |
Aaron Gable | edbc413 | 2017-09-11 13:22:28 -0700 | [diff] [blame] | 4965 | if options.use_commit_queue: |
| 4966 | options.send_mail = True |
| 4967 | |
tandrii@chromium.org | 512d79c | 2016-03-31 12:55:28 +0000 | [diff] [blame] | 4968 | # For sanity of test expectations, do this otherwise lazy-loading *now*. |
| 4969 | settings.GetIsGerrit() |
| 4970 | |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4971 | cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview) |
Andrii Shyshkalov | 9f27443 | 2018-10-15 16:40:23 +0000 | [diff] [blame] | 4972 | if not cl.IsGerrit(): |
| 4973 | # Error out with instructions for repos not yet configured for Gerrit. |
| 4974 | print('=====================================') |
| 4975 | print('NOTICE: Rietveld is no longer supported. ' |
| 4976 | 'You can upload changes to Gerrit with') |
| 4977 | print(' git cl upload --gerrit') |
| 4978 | print('or set Gerrit to be your default code review tool with') |
| 4979 | print(' git config gerrit.host true') |
| 4980 | print('=====================================') |
| 4981 | return 1 |
| 4982 | |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 4983 | return cl.CMDUpload(options, args, orig_args) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4984 | |
| 4985 | |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 4986 | @subcommand.usage('--description=<description file>') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4987 | @metrics.collector.collect_metrics('git cl split') |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 4988 | def CMDsplit(parser, args): |
| 4989 | """Splits a branch into smaller branches and uploads CLs. |
| 4990 | |
| 4991 | Creates a branch and uploads a CL for each group of files modified in the |
| 4992 | current branch that share a common OWNERS file. In the CL description and |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 4993 | comment, the string '$directory', is replaced with the directory containing |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 4994 | the shared OWNERS file. |
| 4995 | """ |
| 4996 | parser.add_option("-d", "--description", dest="description_file", |
Gabriel Charette | 02b5ee8 | 2017-11-08 16:36:05 -0500 | [diff] [blame] | 4997 | help="A text file containing a CL description in which " |
| 4998 | "$directory will be replaced by each CL's directory.") |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 4999 | parser.add_option("-c", "--comment", dest="comment_file", |
| 5000 | help="A text file containing a CL comment.") |
Chris Watkins | ba28e46 | 2017-12-13 11:22:17 +1100 | [diff] [blame] | 5001 | parser.add_option("-n", "--dry-run", dest="dry_run", action='store_true', |
| 5002 | default=False, |
| 5003 | help="List the files and reviewers for each CL that would " |
| 5004 | "be created, but don't create branches or CLs.") |
Stephen Martinis | cb32668 | 2018-08-29 21:06:30 +0000 | [diff] [blame] | 5005 | parser.add_option("--cq-dry-run", action='store_true', |
| 5006 | help="If set, will do a cq dry run for each uploaded CL. " |
| 5007 | "Please be careful when doing this; more than ~10 CLs " |
| 5008 | "has the potential to overload our build " |
| 5009 | "infrastructure. Try to upload these not during high " |
| 5010 | "load times (usually 11-3 Mountain View time). Email " |
| 5011 | "infra-dev@chromium.org with any questions.") |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5012 | options, _ = parser.parse_args(args) |
| 5013 | |
| 5014 | if not options.description_file: |
| 5015 | parser.error('No --description flag specified.') |
| 5016 | |
| 5017 | def WrappedCMDupload(args): |
| 5018 | return CMDupload(OptionParser(), args) |
| 5019 | |
| 5020 | return split_cl.SplitCl(options.description_file, options.comment_file, |
Stephen Martinis | cb32668 | 2018-08-29 21:06:30 +0000 | [diff] [blame] | 5021 | Changelist, WrappedCMDupload, options.dry_run, |
| 5022 | options.cq_dry_run) |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5023 | |
| 5024 | |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5025 | @subcommand.usage('DEPRECATED') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5026 | @metrics.collector.collect_metrics('git cl commit') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5027 | def CMDdcommit(parser, args): |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5028 | """DEPRECATED: Used to commit the current changelist via git-svn.""" |
| 5029 | message = ('git-cl no longer supports committing to SVN repositories via ' |
| 5030 | 'git-svn. You probably want to use `git cl land` instead.') |
| 5031 | print(message) |
| 5032 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5033 | |
| 5034 | |
Andrii Shyshkalov | aa31b97 | 2017-03-24 16:16:33 +0100 | [diff] [blame] | 5035 | # Two special branches used by git cl land. |
| 5036 | MERGE_BRANCH = 'git-cl-commit' |
| 5037 | CHERRY_PICK_BRANCH = 'git-cl-cherry-pick' |
| 5038 | |
| 5039 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 5040 | @subcommand.usage('[upstream branch to apply against]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5041 | @metrics.collector.collect_metrics('git cl land') |
pgervais@chromium.org | cee6dc4 | 2014-05-07 17:04:03 +0000 | [diff] [blame] | 5042 | def CMDland(parser, args): |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5043 | """Commits the current changelist via git. |
| 5044 | |
| 5045 | In case of Gerrit, uses Gerrit REST api to "submit" the issue, which pushes |
| 5046 | upstream and closes the issue automatically and atomically. |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5047 | """ |
| 5048 | parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 5049 | help='bypass upload presubmit hook') |
Aaron Gable | f7543cd | 2017-07-20 14:26:31 -0700 | [diff] [blame] | 5050 | parser.add_option('-f', '--force', action='store_true', dest='force', |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5051 | help="force yes to questions (don't prompt)") |
Edward Lesmes | 67b3faa | 2018-04-13 17:50:52 -0400 | [diff] [blame] | 5052 | parser.add_option('--parallel', action='store_true', |
| 5053 | help='Run all tests specified by input_api.RunTests in all ' |
| 5054 | 'PRESUBMIT files in parallel.') |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5055 | auth.add_auth_options(parser) |
| 5056 | (options, args) = parser.parse_args(args) |
| 5057 | auth_config = auth.extract_auth_config_from_options(options) |
| 5058 | |
| 5059 | cl = Changelist(auth_config=auth_config) |
| 5060 | |
Robert Iannucci | 2e73d43 | 2018-03-14 01:10:47 -0700 | [diff] [blame] | 5061 | if not cl.IsGerrit(): |
| 5062 | parser.error('rietveld is not supported') |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5063 | |
Robert Iannucci | 2e73d43 | 2018-03-14 01:10:47 -0700 | [diff] [blame] | 5064 | if not cl.GetIssue(): |
| 5065 | DieWithError('You must upload the change first to Gerrit.\n' |
| 5066 | ' If you would rather have `git cl land` upload ' |
| 5067 | 'automatically for you, see http://crbug.com/642759') |
| 5068 | return cl._codereview_impl.CMDLand(options.force, options.bypass_hooks, |
Olivier Robin | 75ee725 | 2018-04-13 10:02:56 +0200 | [diff] [blame] | 5069 | options.verbose, options.parallel) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5070 | |
| 5071 | |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 5072 | @subcommand.usage('<patch url or issue id or issue url>') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5073 | @metrics.collector.collect_metrics('git cl patch') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5074 | def CMDpatch(parser, args): |
marq@chromium.org | e5e5900 | 2013-10-02 23:21:25 +0000 | [diff] [blame] | 5075 | """Patches in a code review.""" |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5076 | parser.add_option('-b', dest='newbranch', |
| 5077 | help='create a new branch off trunk for the patch') |
qsr@chromium.org | 1ef44af | 2013-10-16 16:24:32 +0000 | [diff] [blame] | 5078 | parser.add_option('-f', '--force', action='store_true', |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 5079 | help='overwrite state on the current or chosen branch') |
qsr@chromium.org | 1ef44af | 2013-10-16 16:24:32 +0000 | [diff] [blame] | 5080 | parser.add_option('-d', '--directory', action='store', metavar='DIR', |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 5081 | help='change to the directory DIR immediately, ' |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5082 | 'before doing anything else. Rietveld only.') |
qsr@chromium.org | 1ef44af | 2013-10-16 16:24:32 +0000 | [diff] [blame] | 5083 | parser.add_option('--reject', action='store_true', |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 5084 | help='failed patches spew .rej files rather than ' |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5085 | 'attempting a 3-way merge. Rietveld only.') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5086 | parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit', |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5087 | help='don\'t commit after patch applies. Rietveld only.') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5088 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5089 | |
| 5090 | group = optparse.OptionGroup( |
| 5091 | parser, |
| 5092 | 'Options for continuing work on the current issue uploaded from a ' |
| 5093 | 'different clone (e.g. different machine). Must be used independently ' |
| 5094 | 'from the other options. No issue number should be specified, and the ' |
| 5095 | 'branch must have an issue number associated with it') |
| 5096 | group.add_option('--reapply', action='store_true', dest='reapply', |
| 5097 | help='Reset the branch and reapply the issue.\n' |
| 5098 | 'CAUTION: This will undo any local changes in this ' |
| 5099 | 'branch') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5100 | |
| 5101 | group.add_option('--pull', action='store_true', dest='pull', |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5102 | help='Performs a pull before reapplying.') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5103 | parser.add_option_group(group) |
| 5104 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5105 | auth.add_auth_options(parser) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 5106 | _add_codereview_select_options(parser) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5107 | (options, args) = parser.parse_args(args) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 5108 | _process_codereview_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5109 | auth_config = auth.extract_auth_config_from_options(options) |
| 5110 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5111 | if options.reapply: |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5112 | if options.newbranch: |
| 5113 | parser.error('--reapply works on the current branch only') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5114 | if len(args) > 0: |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5115 | parser.error('--reapply implies no additional arguments') |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 5116 | |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5117 | cl = Changelist(auth_config=auth_config, |
| 5118 | codereview=options.forced_codereview) |
| 5119 | if not cl.GetIssue(): |
| 5120 | parser.error('current branch must have an associated issue') |
| 5121 | |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5122 | upstream = cl.GetUpstreamBranch() |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5123 | if upstream is None: |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5124 | parser.error('No upstream branch specified. Cannot reset branch') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5125 | |
| 5126 | RunGit(['reset', '--hard', upstream]) |
| 5127 | if options.pull: |
| 5128 | RunGit(['pull']) |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5129 | |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5130 | return cl.CMDPatchIssue(cl.GetIssue(), options.reject, options.nocommit, |
| 5131 | options.directory) |
| 5132 | |
| 5133 | if len(args) != 1 or not args[0]: |
| 5134 | parser.error('Must specify issue number or url') |
| 5135 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 5136 | target_issue_arg = ParseIssueNumberArgument(args[0], |
| 5137 | options.forced_codereview) |
| 5138 | if not target_issue_arg.valid: |
| 5139 | parser.error('invalid codereview url or CL id') |
| 5140 | |
| 5141 | cl_kwargs = { |
| 5142 | 'auth_config': auth_config, |
| 5143 | 'codereview_host': target_issue_arg.hostname, |
| 5144 | 'codereview': options.forced_codereview, |
| 5145 | } |
| 5146 | detected_codereview_from_url = False |
| 5147 | if target_issue_arg.codereview and not options.forced_codereview: |
| 5148 | detected_codereview_from_url = True |
| 5149 | cl_kwargs['codereview'] = target_issue_arg.codereview |
| 5150 | cl_kwargs['issue'] = target_issue_arg.issue |
| 5151 | |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5152 | # We don't want uncommitted changes mixed up with the patch. |
| 5153 | if git_common.is_dirty_git_tree('patch'): |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 5154 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5155 | |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5156 | if options.newbranch: |
| 5157 | if options.force: |
| 5158 | RunGit(['branch', '-D', options.newbranch], |
| 5159 | stderr=subprocess2.PIPE, error_ok=True) |
| 5160 | RunGit(['new-branch', options.newbranch]) |
| 5161 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 5162 | cl = Changelist(**cl_kwargs) |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5163 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5164 | if cl.IsGerrit(): |
| 5165 | if options.reject: |
| 5166 | parser.error('--reject is not supported with Gerrit codereview.') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5167 | if options.directory: |
| 5168 | parser.error('--directory is not supported with Gerrit codereview.') |
| 5169 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 5170 | if detected_codereview_from_url: |
| 5171 | print('canonical issue/change URL: %s (type: %s)\n' % |
| 5172 | (cl.GetIssueURL(), target_issue_arg.codereview)) |
| 5173 | |
| 5174 | return cl.CMDPatchWithParsedIssue(target_issue_arg, options.reject, |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 5175 | options.nocommit, options.directory, |
| 5176 | options.force) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5177 | |
| 5178 | |
jochen@chromium.org | 3ec0d54 | 2014-01-14 20:00:03 +0000 | [diff] [blame] | 5179 | def GetTreeStatus(url=None): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5180 | """Fetches the tree status and returns either 'open', 'closed', |
| 5181 | 'unknown' or 'unset'.""" |
jochen@chromium.org | 3ec0d54 | 2014-01-14 20:00:03 +0000 | [diff] [blame] | 5182 | url = url or settings.GetTreeStatusUrl(error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5183 | if url: |
| 5184 | status = urllib2.urlopen(url).read().lower() |
| 5185 | if status.find('closed') != -1 or status == '0': |
| 5186 | return 'closed' |
| 5187 | elif status.find('open') != -1 or status == '1': |
| 5188 | return 'open' |
| 5189 | return 'unknown' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5190 | return 'unset' |
| 5191 | |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 5192 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5193 | def GetTreeStatusReason(): |
| 5194 | """Fetches the tree status from a json url and returns the message |
| 5195 | with the reason for the tree to be opened or closed.""" |
msb@chromium.org | bf1a7ba | 2011-02-01 16:21:46 +0000 | [diff] [blame] | 5196 | url = settings.GetTreeStatusUrl() |
| 5197 | json_url = urlparse.urljoin(url, '/current?format=json') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5198 | connection = urllib2.urlopen(json_url) |
| 5199 | status = json.loads(connection.read()) |
| 5200 | connection.close() |
| 5201 | return status['message'] |
| 5202 | |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 5203 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5204 | @metrics.collector.collect_metrics('git cl tree') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5205 | def CMDtree(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5206 | """Shows the status of the tree.""" |
dpranke@chromium.org | 97ae58e | 2011-03-18 00:29:20 +0000 | [diff] [blame] | 5207 | _, args = parser.parse_args(args) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5208 | status = GetTreeStatus() |
| 5209 | if 'unset' == status: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5210 | print('You must configure your tree status URL by running "git cl config".') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5211 | return 2 |
| 5212 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5213 | print('The tree is %s' % status) |
| 5214 | print() |
| 5215 | print(GetTreeStatusReason()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5216 | if status != 'open': |
| 5217 | return 1 |
| 5218 | return 0 |
| 5219 | |
| 5220 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5221 | @metrics.collector.collect_metrics('git cl try') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5222 | def CMDtry(parser, args): |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 5223 | """Triggers try jobs using either BuildBucket or CQ dry run.""" |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5224 | group = optparse.OptionGroup(parser, 'Try job options') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5225 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5226 | '-b', '--bot', action='append', |
| 5227 | help=('IMPORTANT: specify ONE builder per --bot flag. Use it multiple ' |
| 5228 | 'times to specify multiple builders. ex: ' |
| 5229 | '"-b win_rel -b win_layout". See ' |
| 5230 | 'the try server waterfall for the builders name and the tests ' |
| 5231 | 'available.')) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5232 | group.add_option( |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 5233 | '-B', '--bucket', default='', |
| 5234 | help=('Buildbucket bucket to send the try requests.')) |
| 5235 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5236 | '-m', '--master', default='', |
Nodir Turakulov | f6929a1 | 2017-10-09 12:34:44 -0700 | [diff] [blame] | 5237 | help=('DEPRECATED, use -B. The try master where to run the builds.')) |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 5238 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5239 | '-r', '--revision', |
tandrii | f7b29d4 | 2016-10-07 08:45:41 -0700 | [diff] [blame] | 5240 | help='Revision to use for the try job; default: the revision will ' |
| 5241 | 'be determined by the try recipe that builder runs, which usually ' |
| 5242 | 'defaults to HEAD of origin/master') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5243 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5244 | '-c', '--clobber', action='store_true', default=False, |
tandrii | f7b29d4 | 2016-10-07 08:45:41 -0700 | [diff] [blame] | 5245 | help='Force a clobber before building; that is don\'t do an ' |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5246 | 'incremental build') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5247 | group.add_option( |
Andrii Shyshkalov | f9648b5 | 2018-02-21 22:32:42 -0800 | [diff] [blame] | 5248 | '--category', default='git_cl_try', help='Specify custom build category.') |
| 5249 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5250 | '--project', |
| 5251 | help='Override which project to use. Projects are defined ' |
tandrii | f7b29d4 | 2016-10-07 08:45:41 -0700 | [diff] [blame] | 5252 | 'in recipe to determine to which repository or directory to ' |
| 5253 | 'apply the patch') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5254 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5255 | '-p', '--property', dest='properties', action='append', default=[], |
| 5256 | help='Specify generic properties in the form -p key1=value1 -p ' |
tandrii | f7b29d4 | 2016-10-07 08:45:41 -0700 | [diff] [blame] | 5257 | 'key2=value2 etc. The value will be treated as ' |
| 5258 | 'json if decodable, or as string otherwise. ' |
| 5259 | 'NOTE: using this may make your try job not usable for CQ, ' |
| 5260 | 'which will then schedule another try job with default properties') |
sheyang@chromium.org | db37557 | 2015-08-17 19:22:23 +0000 | [diff] [blame] | 5261 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5262 | '--buildbucket-host', default='cr-buildbucket.appspot.com', |
| 5263 | help='Host of buildbucket. The default host is %default.') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5264 | parser.add_option_group(group) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5265 | auth.add_auth_options(parser) |
Koji Ishii | 31c1478 | 2018-01-08 17:17:33 +0900 | [diff] [blame] | 5266 | _add_codereview_issue_select_options(parser) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5267 | options, args = parser.parse_args(args) |
Koji Ishii | 31c1478 | 2018-01-08 17:17:33 +0900 | [diff] [blame] | 5268 | _process_codereview_issue_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5269 | auth_config = auth.extract_auth_config_from_options(options) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5270 | |
Nodir Turakulov | f6929a1 | 2017-10-09 12:34:44 -0700 | [diff] [blame] | 5271 | if options.master and options.master.startswith('luci.'): |
| 5272 | parser.error( |
| 5273 | '-m option does not support LUCI. Please pass -B %s' % options.master) |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 5274 | # Make sure that all properties are prop=value pairs. |
| 5275 | bad_params = [x for x in options.properties if '=' not in x] |
| 5276 | if bad_params: |
| 5277 | parser.error('Got properties with missing "=": %s' % bad_params) |
| 5278 | |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5279 | if args: |
| 5280 | parser.error('Unknown arguments: %s' % args) |
| 5281 | |
Koji Ishii | 31c1478 | 2018-01-08 17:17:33 +0900 | [diff] [blame] | 5282 | cl = Changelist(auth_config=auth_config, issue=options.issue, |
| 5283 | codereview=options.forced_codereview) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5284 | if not cl.GetIssue(): |
| 5285 | parser.error('Need to upload first') |
| 5286 | |
Andrii Shyshkalov | eadad92 | 2017-01-26 09:38:30 +0100 | [diff] [blame] | 5287 | if cl.IsGerrit(): |
| 5288 | # HACK: warm up Gerrit change detail cache to save on RPCs. |
| 5289 | cl._codereview_impl._GetChangeDetail(['DETAILED_ACCOUNTS', 'ALL_REVISIONS']) |
| 5290 | |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 5291 | error_message = cl.CannotTriggerTryJobReason() |
| 5292 | if error_message: |
qyearsley | 99e2cdf | 2016-10-23 12:51:41 -0700 | [diff] [blame] | 5293 | parser.error('Can\'t trigger try jobs: %s' % error_message) |
jrobbins@chromium.org | 16f10f7 | 2014-06-24 22:14:36 +0000 | [diff] [blame] | 5294 | |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 5295 | if options.bucket and options.master: |
| 5296 | parser.error('Only one of --bucket and --master may be used.') |
| 5297 | |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 5298 | buckets = _get_bucket_map(cl, options, parser) |
phajdan.jr@chromium.org | 8da7f27 | 2014-03-14 01:28:39 +0000 | [diff] [blame] | 5299 | |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 5300 | # If no bots are listed and we couldn't get a list based on PRESUBMIT files, |
| 5301 | # then we default to triggering a CQ dry run (see http://crbug.com/625697). |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 5302 | if not buckets: |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 5303 | if options.verbose: |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 5304 | print('git cl try with no bots now defaults to CQ dry run.') |
| 5305 | print('Scheduling CQ dry run on: %s' % cl.GetIssueURL()) |
| 5306 | return cl.SetCQState(_CQState.DRY_RUN) |
stip@chromium.org | 43064fd | 2013-12-18 20:07:44 +0000 | [diff] [blame] | 5307 | |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 5308 | for builders in buckets.itervalues(): |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 5309 | if any('triggered' in b for b in builders): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5310 | print('ERROR You are trying to send a job to a triggered bot. This type ' |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 5311 | 'of bot requires an initial job from a parent (usually a builder). ' |
| 5312 | 'Instead send your job to the parent.\n' |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5313 | 'Bot list: %s' % builders, file=sys.stderr) |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 5314 | return 1 |
ilevy@chromium.org | f3b2123 | 2012-09-24 20:48:55 +0000 | [diff] [blame] | 5315 | |
ilevy@chromium.org | 36e420b | 2013-08-06 23:21:12 +0000 | [diff] [blame] | 5316 | patchset = cl.GetMostRecentPatchset() |
tandrii | 568043b | 2016-10-11 07:49:18 -0700 | [diff] [blame] | 5317 | try: |
Andrii Shyshkalov | f9648b5 | 2018-02-21 22:32:42 -0800 | [diff] [blame] | 5318 | _trigger_try_jobs(auth_config, cl, buckets, options, patchset) |
tandrii | 568043b | 2016-10-11 07:49:18 -0700 | [diff] [blame] | 5319 | except BuildbucketResponseException as ex: |
| 5320 | print('ERROR: %s' % ex) |
| 5321 | return 1 |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5322 | return 0 |
| 5323 | |
| 5324 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5325 | @metrics.collector.collect_metrics('git cl try-results') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5326 | def CMDtry_results(parser, args): |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5327 | """Prints info about try jobs associated with current CL.""" |
| 5328 | group = optparse.OptionGroup(parser, 'Try job results options') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5329 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5330 | '-p', '--patchset', type=int, help='patchset number if not current.') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5331 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5332 | '--print-master', action='store_true', help='print master name as well.') |
tandrii@chromium.org | 6cf98c8 | 2016-03-15 11:56:00 +0000 | [diff] [blame] | 5333 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5334 | '--color', action='store_true', default=setup_color.IS_TTY, |
| 5335 | help='force color output, useful when piping output.') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5336 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5337 | '--buildbucket-host', default='cr-buildbucket.appspot.com', |
| 5338 | help='Host of buildbucket. The default host is %default.') |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 5339 | group.add_option( |
Stefan Zager | 1306bd0 | 2017-06-22 19:26:46 -0700 | [diff] [blame] | 5340 | '--json', help=('Path of JSON output file to write try job results to,' |
| 5341 | 'or "-" for stdout.')) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5342 | parser.add_option_group(group) |
| 5343 | auth.add_auth_options(parser) |
Stefan Zager | 27db3f2 | 2017-10-10 15:15:01 -0700 | [diff] [blame] | 5344 | _add_codereview_issue_select_options(parser) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5345 | options, args = parser.parse_args(args) |
Stefan Zager | 27db3f2 | 2017-10-10 15:15:01 -0700 | [diff] [blame] | 5346 | _process_codereview_issue_select_options(parser, options) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5347 | if args: |
| 5348 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
| 5349 | |
| 5350 | auth_config = auth.extract_auth_config_from_options(options) |
Stefan Zager | 27db3f2 | 2017-10-10 15:15:01 -0700 | [diff] [blame] | 5351 | cl = Changelist( |
| 5352 | issue=options.issue, codereview=options.forced_codereview, |
| 5353 | auth_config=auth_config) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5354 | if not cl.GetIssue(): |
| 5355 | parser.error('Need to upload first') |
| 5356 | |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 5357 | patchset = options.patchset |
| 5358 | if not patchset: |
| 5359 | patchset = cl.GetMostRecentPatchset() |
| 5360 | if not patchset: |
| 5361 | parser.error('Codereview doesn\'t know about issue %s. ' |
| 5362 | 'No access to issue or wrong issue number?\n' |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 5363 | 'Either upload first, or pass --patchset explicitly' % |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 5364 | cl.GetIssue()) |
| 5365 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5366 | try: |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 5367 | jobs = fetch_try_jobs(auth_config, cl, options.buildbucket_host, patchset) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5368 | except BuildbucketResponseException as ex: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5369 | print('Buildbucket error: %s' % ex) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5370 | return 1 |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 5371 | if options.json: |
| 5372 | write_try_results_json(options.json, jobs) |
| 5373 | else: |
| 5374 | print_try_jobs(options, jobs) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5375 | return 0 |
| 5376 | |
| 5377 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 5378 | @subcommand.usage('[new upstream branch]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5379 | @metrics.collector.collect_metrics('git cl upstream') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5380 | def CMDupstream(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5381 | """Prints or sets the name of the upstream branch, if any.""" |
dpranke@chromium.org | 97ae58e | 2011-03-18 00:29:20 +0000 | [diff] [blame] | 5382 | _, args = parser.parse_args(args) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5383 | if len(args) > 1: |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5384 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5385 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5386 | cl = Changelist() |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5387 | if args: |
| 5388 | # One arg means set upstream branch. |
bauerb@chromium.org | c9cf90a | 2014-04-28 20:32:31 +0000 | [diff] [blame] | 5389 | branch = cl.GetBranch() |
stip | 7a3dd35 | 2016-09-22 17:32:28 -0700 | [diff] [blame] | 5390 | RunGit(['branch', '--set-upstream-to', args[0], branch]) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5391 | cl = Changelist() |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5392 | print('Upstream branch set to %s' % (cl.GetUpstreamBranch(),)) |
bauerb@chromium.org | c9cf90a | 2014-04-28 20:32:31 +0000 | [diff] [blame] | 5393 | |
| 5394 | # Clear configured merge-base, if there is one. |
| 5395 | git_common.remove_merge_base(branch) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5396 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5397 | print(cl.GetUpstreamBranch()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5398 | return 0 |
| 5399 | |
| 5400 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5401 | @metrics.collector.collect_metrics('git cl web') |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 5402 | def CMDweb(parser, args): |
| 5403 | """Opens the current CL in the web browser.""" |
| 5404 | _, args = parser.parse_args(args) |
| 5405 | if args: |
| 5406 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
| 5407 | |
| 5408 | issue_url = Changelist().GetIssueURL() |
| 5409 | if not issue_url: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5410 | print('ERROR No issue to open', file=sys.stderr) |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 5411 | return 1 |
| 5412 | |
Sergiy Byelozyorov | 2b71832 | 2018-10-24 17:43:31 +0000 | [diff] [blame] | 5413 | # Redirect I/O before invoking browser to hide its output. For example, this |
| 5414 | # allows to hide "Created new window in existing browser session." message |
| 5415 | # from Chrome. Based on https://stackoverflow.com/a/2323563. |
| 5416 | saved_stdout = os.dup(1) |
| 5417 | os.close(1) |
| 5418 | os.open(os.devnull, os.O_RDWR) |
| 5419 | try: |
| 5420 | webbrowser.open(issue_url) |
| 5421 | finally: |
| 5422 | os.dup2(saved_stdout, 1) |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 5423 | return 0 |
| 5424 | |
| 5425 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5426 | @metrics.collector.collect_metrics('git cl set-commit') |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5427 | def CMDset_commit(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5428 | """Sets the commit bit to trigger the Commit Queue.""" |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 5429 | parser.add_option('-d', '--dry-run', action='store_true', |
| 5430 | help='trigger in dry run mode') |
| 5431 | parser.add_option('-c', '--clear', action='store_true', |
| 5432 | help='stop CQ run, if any') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5433 | auth.add_auth_options(parser) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5434 | _add_codereview_issue_select_options(parser) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5435 | options, args = parser.parse_args(args) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5436 | _process_codereview_issue_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5437 | auth_config = auth.extract_auth_config_from_options(options) |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5438 | if args: |
| 5439 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 5440 | if options.dry_run and options.clear: |
| 5441 | parser.error('Make up your mind: both --dry-run and --clear not allowed') |
| 5442 | |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5443 | cl = Changelist(auth_config=auth_config, issue=options.issue, |
| 5444 | codereview=options.forced_codereview) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 5445 | if options.clear: |
tandrii | d9e5ce5 | 2016-07-13 02:32:59 -0700 | [diff] [blame] | 5446 | state = _CQState.NONE |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 5447 | elif options.dry_run: |
| 5448 | state = _CQState.DRY_RUN |
| 5449 | else: |
| 5450 | state = _CQState.COMMIT |
| 5451 | if not cl.GetIssue(): |
| 5452 | parser.error('Must upload the issue first') |
tandrii | 9de9ec6 | 2016-07-13 03:01:59 -0700 | [diff] [blame] | 5453 | cl.SetCQState(state) |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5454 | return 0 |
| 5455 | |
| 5456 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5457 | @metrics.collector.collect_metrics('git cl set-close') |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 5458 | def CMDset_close(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5459 | """Closes the issue.""" |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5460 | _add_codereview_issue_select_options(parser) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5461 | auth.add_auth_options(parser) |
| 5462 | options, args = parser.parse_args(args) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5463 | _process_codereview_issue_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5464 | auth_config = auth.extract_auth_config_from_options(options) |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 5465 | if args: |
| 5466 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5467 | cl = Changelist(auth_config=auth_config, issue=options.issue, |
| 5468 | codereview=options.forced_codereview) |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 5469 | # Ensure there actually is an issue to close. |
Aaron Gable | 7139a4e | 2017-09-05 17:53:09 -0700 | [diff] [blame] | 5470 | if not cl.GetIssue(): |
| 5471 | DieWithError('ERROR No issue to close') |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 5472 | cl.CloseIssue() |
| 5473 | return 0 |
| 5474 | |
| 5475 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5476 | @metrics.collector.collect_metrics('git cl diff') |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5477 | def CMDdiff(parser, args): |
wychen@chromium.org | 37b2ec0 | 2015-04-03 00:49:15 +0000 | [diff] [blame] | 5478 | """Shows differences between local tree and last upload.""" |
thomasanderson | 074beb2 | 2016-08-29 14:03:20 -0700 | [diff] [blame] | 5479 | parser.add_option( |
| 5480 | '--stat', |
| 5481 | action='store_true', |
| 5482 | dest='stat', |
| 5483 | help='Generate a diffstat') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5484 | auth.add_auth_options(parser) |
| 5485 | options, args = parser.parse_args(args) |
| 5486 | auth_config = auth.extract_auth_config_from_options(options) |
| 5487 | if args: |
| 5488 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 5489 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5490 | cl = Changelist(auth_config=auth_config) |
sbc@chromium.org | 78dc984 | 2013-11-25 18:43:44 +0000 | [diff] [blame] | 5491 | issue = cl.GetIssue() |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5492 | branch = cl.GetBranch() |
sbc@chromium.org | 78dc984 | 2013-11-25 18:43:44 +0000 | [diff] [blame] | 5493 | if not issue: |
| 5494 | DieWithError('No issue found for current branch (%s)' % branch) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5495 | |
Aaron Gable | a718c3e | 2017-08-28 17:47:28 -0700 | [diff] [blame] | 5496 | base = cl._GitGetBranchConfigValue('last-upload-hash') |
| 5497 | if not base: |
| 5498 | base = cl._GitGetBranchConfigValue('gerritsquashhash') |
| 5499 | if not base: |
| 5500 | detail = cl._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT']) |
| 5501 | revision_info = detail['revisions'][detail['current_revision']] |
| 5502 | fetch_info = revision_info['fetch']['http'] |
| 5503 | RunGit(['fetch', fetch_info['url'], fetch_info['ref']]) |
| 5504 | base = 'FETCH_HEAD' |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5505 | |
Aaron Gable | a718c3e | 2017-08-28 17:47:28 -0700 | [diff] [blame] | 5506 | cmd = ['git', 'diff'] |
| 5507 | if options.stat: |
| 5508 | cmd.append('--stat') |
| 5509 | cmd.append(base) |
| 5510 | subprocess2.check_call(cmd) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5511 | |
| 5512 | return 0 |
| 5513 | |
| 5514 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5515 | @metrics.collector.collect_metrics('git cl owners') |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5516 | def CMDowners(parser, args): |
Dirk Pranke | bf98088 | 2017-09-02 15:08:00 -0700 | [diff] [blame] | 5517 | """Finds potential owners for reviewing.""" |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5518 | parser.add_option( |
Sidney San MartÃn | 8e6f58c | 2018-06-08 01:02:56 +0000 | [diff] [blame] | 5519 | '--ignore-current', |
| 5520 | action='store_true', |
| 5521 | help='Ignore the CL\'s current reviewers and start from scratch.') |
| 5522 | parser.add_option( |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5523 | '--no-color', |
| 5524 | action='store_true', |
| 5525 | help='Use this option to disable color output') |
Dirk Pranke | bf98088 | 2017-09-02 15:08:00 -0700 | [diff] [blame] | 5526 | parser.add_option( |
| 5527 | '--batch', |
| 5528 | action='store_true', |
| 5529 | help='Do not run interactively, just suggest some') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5530 | auth.add_auth_options(parser) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5531 | options, args = parser.parse_args(args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5532 | auth_config = auth.extract_auth_config_from_options(options) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5533 | |
| 5534 | author = RunGit(['config', 'user.email']).strip() or None |
| 5535 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5536 | cl = Changelist(auth_config=auth_config) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5537 | |
| 5538 | if args: |
| 5539 | if len(args) > 1: |
| 5540 | parser.error('Unknown args') |
| 5541 | base_branch = args[0] |
| 5542 | else: |
| 5543 | # Default to diffing against the common ancestor of the upstream branch. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 5544 | base_branch = cl.GetCommonAncestorWithUpstream() |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5545 | |
| 5546 | change = cl.GetChange(base_branch, None) |
Dirk Pranke | bf98088 | 2017-09-02 15:08:00 -0700 | [diff] [blame] | 5547 | affected_files = [f.LocalPath() for f in change.AffectedFiles()] |
| 5548 | |
| 5549 | if options.batch: |
| 5550 | db = owners.Database(change.RepositoryRoot(), file, os.path) |
| 5551 | print('\n'.join(db.reviewers_for(affected_files, author))) |
| 5552 | return 0 |
| 5553 | |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5554 | return owners_finder.OwnersFinder( |
Dirk Pranke | bf98088 | 2017-09-02 15:08:00 -0700 | [diff] [blame] | 5555 | affected_files, |
Jochen Eisinger | 72606f8 | 2017-04-04 10:44:18 +0200 | [diff] [blame] | 5556 | change.RepositoryRoot(), |
Edward Lemur | 707d70b | 2018-02-07 00:50:14 +0100 | [diff] [blame] | 5557 | author, |
Sidney San MartÃn | 8e6f58c | 2018-06-08 01:02:56 +0000 | [diff] [blame] | 5558 | [] if options.ignore_current else cl.GetReviewers(), |
Edward Lemur | 707d70b | 2018-02-07 00:50:14 +0100 | [diff] [blame] | 5559 | fopen=file, os_path=os.path, |
Jochen Eisinger | d0573ec | 2017-04-13 10:55:06 +0200 | [diff] [blame] | 5560 | disable_color=options.no_color, |
| 5561 | override_files=change.OriginalOwnersFiles()).run() |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5562 | |
| 5563 | |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 5564 | def BuildGitDiffCmd(diff_type, upstream_commit, args, allow_prefix=False): |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5565 | """Generates a diff command.""" |
| 5566 | # Generate diff for the current branch's changes. |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 5567 | diff_cmd = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff'] |
| 5568 | |
| 5569 | if not allow_prefix: |
| 5570 | diff_cmd += ['--no-prefix'] |
| 5571 | |
| 5572 | diff_cmd += [diff_type, upstream_commit, '--'] |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5573 | |
| 5574 | if args: |
| 5575 | for arg in args: |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5576 | if os.path.isdir(arg) or os.path.isfile(arg): |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5577 | diff_cmd.append(arg) |
| 5578 | else: |
| 5579 | DieWithError('Argument "%s" is not a file or a directory' % arg) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5580 | |
| 5581 | return diff_cmd |
| 5582 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5583 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5584 | def MatchingFileType(file_name, extensions): |
| 5585 | """Returns true if the file name ends with one of the given extensions.""" |
| 5586 | return bool([ext for ext in extensions if file_name.lower().endswith(ext)]) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5587 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5588 | |
enne@chromium.org | 555cfe4 | 2014-01-29 18:21:39 +0000 | [diff] [blame] | 5589 | @subcommand.usage('[files or directories to diff]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5590 | @metrics.collector.collect_metrics('git cl format') |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5591 | def CMDformat(parser, args): |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5592 | """Runs auto-formatting tools (clang-format etc.) on the diff.""" |
Christopher Lam | c5ba692 | 2017-01-24 11:19:14 +1100 | [diff] [blame] | 5593 | CLANG_EXTS = ['.cc', '.cpp', '.h', '.m', '.mm', '.proto', '.java'] |
kylechar | 58edce2 | 2016-06-17 06:07:51 -0700 | [diff] [blame] | 5594 | GN_EXTS = ['.gn', '.gni', '.typemap'] |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 5595 | parser.add_option('--full', action='store_true', |
| 5596 | help='Reformat the full content of all touched files') |
| 5597 | parser.add_option('--dry-run', action='store_true', |
| 5598 | help='Don\'t modify any file on disk.') |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5599 | parser.add_option('--python', action='store_true', |
| 5600 | help='Format python code with yapf (experimental).') |
Christopher Lam | c5ba692 | 2017-01-24 11:19:14 +1100 | [diff] [blame] | 5601 | parser.add_option('--js', action='store_true', |
| 5602 | help='Format javascript code with clang-format.') |
wittman@chromium.org | 04d5a22 | 2014-03-07 18:30:42 +0000 | [diff] [blame] | 5603 | parser.add_option('--diff', action='store_true', |
| 5604 | help='Print diff to stdout rather than modifying files.') |
Ilya Sherman | e081cbe | 2017-08-15 17:51:04 -0700 | [diff] [blame] | 5605 | parser.add_option('--presubmit', action='store_true', |
| 5606 | help='Used when running the script from a presubmit.') |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5607 | opts, args = parser.parse_args(args) |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5608 | |
Daniel Cheng | c55eecf | 2016-12-30 03:11:02 -0800 | [diff] [blame] | 5609 | # Normalize any remaining args against the current path, so paths relative to |
| 5610 | # the current directory are still resolved as expected. |
| 5611 | args = [os.path.join(os.getcwd(), arg) for arg in args] |
| 5612 | |
enne@chromium.org | ff7a1fb | 2013-12-10 19:21:41 +0000 | [diff] [blame] | 5613 | # git diff generates paths against the root of the repository. Change |
| 5614 | # to that directory so clang-format can find files even within subdirs. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 5615 | rel_base_path = settings.GetRelativeRoot() |
enne@chromium.org | ff7a1fb | 2013-12-10 19:21:41 +0000 | [diff] [blame] | 5616 | if rel_base_path: |
| 5617 | os.chdir(rel_base_path) |
| 5618 | |
digit@chromium.org | 29e4727 | 2013-05-17 17:01:46 +0000 | [diff] [blame] | 5619 | # Grab the merge-base commit, i.e. the upstream commit of the current |
| 5620 | # branch when it was created or the last time it was rebased. This is |
| 5621 | # to cover the case where the user may have called "git fetch origin", |
| 5622 | # moving the origin branch to a newer commit, but hasn't rebased yet. |
| 5623 | upstream_commit = None |
| 5624 | cl = Changelist() |
| 5625 | upstream_branch = cl.GetUpstreamBranch() |
| 5626 | if upstream_branch: |
| 5627 | upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch]) |
| 5628 | upstream_commit = upstream_commit.strip() |
| 5629 | |
| 5630 | if not upstream_commit: |
| 5631 | DieWithError('Could not find base commit for this branch. ' |
| 5632 | 'Are you in detached state?') |
| 5633 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5634 | changed_files_cmd = BuildGitDiffCmd('--name-only', upstream_commit, args) |
| 5635 | diff_output = RunGit(changed_files_cmd) |
| 5636 | diff_files = diff_output.splitlines() |
jkarlin@chromium.org | ad21b92 | 2016-01-28 17:48:42 +0000 | [diff] [blame] | 5637 | # Filter out files deleted by this CL |
| 5638 | diff_files = [x for x in diff_files if os.path.isfile(x)] |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5639 | |
Christopher Lam | c5ba692 | 2017-01-24 11:19:14 +1100 | [diff] [blame] | 5640 | if opts.js: |
Deepanjan Roy | 605dd31 | 2018-07-02 17:48:54 +0000 | [diff] [blame] | 5641 | CLANG_EXTS.extend(['.js', '.ts']) |
Christopher Lam | c5ba692 | 2017-01-24 11:19:14 +1100 | [diff] [blame] | 5642 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5643 | clang_diff_files = [x for x in diff_files if MatchingFileType(x, CLANG_EXTS)] |
| 5644 | python_diff_files = [x for x in diff_files if MatchingFileType(x, ['.py'])] |
| 5645 | dart_diff_files = [x for x in diff_files if MatchingFileType(x, ['.dart'])] |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 5646 | gn_diff_files = [x for x in diff_files if MatchingFileType(x, GN_EXTS)] |
digit@chromium.org | 29e4727 | 2013-05-17 17:01:46 +0000 | [diff] [blame] | 5647 | |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 5648 | top_dir = os.path.normpath( |
| 5649 | RunGit(["rev-parse", "--show-toplevel"]).rstrip('\n')) |
| 5650 | |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5651 | # Set to 2 to signal to CheckPatchFormatted() that this patch isn't |
| 5652 | # formatted. This is used to block during the presubmit. |
| 5653 | return_value = 0 |
| 5654 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5655 | if clang_diff_files: |
techtonik@gmail.com | 5573df1 | 2016-04-12 18:34:10 +0000 | [diff] [blame] | 5656 | # Locate the clang-format binary in the checkout |
| 5657 | try: |
| 5658 | clang_format_tool = clang_format.FindClangFormatToolInChromiumTree() |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 5659 | except clang_format.NotFoundError as e: |
techtonik@gmail.com | 5573df1 | 2016-04-12 18:34:10 +0000 | [diff] [blame] | 5660 | DieWithError(e) |
| 5661 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5662 | if opts.full: |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5663 | cmd = [clang_format_tool] |
| 5664 | if not opts.dry_run and not opts.diff: |
| 5665 | cmd.append('-i') |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5666 | stdout = RunCommand(cmd + clang_diff_files, cwd=top_dir) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5667 | if opts.diff: |
| 5668 | sys.stdout.write(stdout) |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5669 | else: |
| 5670 | env = os.environ.copy() |
| 5671 | env['PATH'] = str(os.path.dirname(clang_format_tool)) |
| 5672 | try: |
| 5673 | script = clang_format.FindClangFormatScriptInChromiumTree( |
| 5674 | 'clang-format-diff.py') |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 5675 | except clang_format.NotFoundError as e: |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5676 | DieWithError(e) |
digit@chromium.org | d6ddc1c | 2013-10-25 15:36:32 +0000 | [diff] [blame] | 5677 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5678 | cmd = [sys.executable, script, '-p0'] |
| 5679 | if not opts.dry_run and not opts.diff: |
| 5680 | cmd.append('-i') |
digit@chromium.org | d6ddc1c | 2013-10-25 15:36:32 +0000 | [diff] [blame] | 5681 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5682 | diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, clang_diff_files) |
| 5683 | diff_output = RunGit(diff_cmd) |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5684 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5685 | stdout = RunCommand(cmd, stdin=diff_output, cwd=top_dir, env=env) |
| 5686 | if opts.diff: |
| 5687 | sys.stdout.write(stdout) |
| 5688 | if opts.dry_run and len(stdout) > 0: |
| 5689 | return_value = 2 |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5690 | |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5691 | # Similar code to above, but using yapf on .py files rather than clang-format |
| 5692 | # on C/C++ files |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 5693 | if opts.python and python_diff_files: |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5694 | yapf_tool = gclient_utils.FindExecutable('yapf') |
| 5695 | if yapf_tool is None: |
| 5696 | DieWithError('yapf not found in PATH') |
| 5697 | |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 5698 | # If we couldn't find a yapf file we'll default to the chromium style |
| 5699 | # specified in depot_tools. |
| 5700 | depot_tools_path = os.path.dirname(os.path.abspath(__file__)) |
| 5701 | chromium_default_yapf_style = os.path.join(depot_tools_path, |
| 5702 | YAPF_CONFIG_FILENAME) |
| 5703 | |
| 5704 | # Note: yapf still seems to fix indentation of the entire file |
| 5705 | # even if line ranges are specified. |
| 5706 | # See https://github.com/google/yapf/issues/499 |
| 5707 | if not opts.full: |
| 5708 | py_line_diffs = _ComputeDiffLineRanges(python_diff_files, upstream_commit) |
| 5709 | |
| 5710 | # Used for caching. |
| 5711 | yapf_configs = {} |
| 5712 | for f in python_diff_files: |
| 5713 | # Find the yapf style config for the current file, defaults to depot |
| 5714 | # tools default. |
| 5715 | yapf_config = _FindYapfConfigFile( |
| 5716 | os.path.abspath(f), yapf_configs, top_dir, |
| 5717 | chromium_default_yapf_style) |
| 5718 | |
| 5719 | cmd = [yapf_tool, '--style', yapf_config, f] |
| 5720 | |
| 5721 | has_formattable_lines = False |
| 5722 | if not opts.full: |
| 5723 | # Only run yapf over changed line ranges. |
| 5724 | for diff_start, diff_len in py_line_diffs[f]: |
| 5725 | diff_end = diff_start + diff_len - 1 |
| 5726 | # Yapf errors out if diff_end < diff_start but this |
| 5727 | # is a valid line range diff for a removal. |
| 5728 | if diff_end >= diff_start: |
| 5729 | has_formattable_lines = True |
| 5730 | cmd += ['-l', '{}-{}'.format(diff_start, diff_end)] |
| 5731 | # If all line diffs were removals we have nothing to format. |
| 5732 | if not has_formattable_lines: |
| 5733 | continue |
| 5734 | |
| 5735 | if opts.diff or opts.dry_run: |
| 5736 | cmd += ['--diff'] |
| 5737 | # Will return non-zero exit code if non-empty diff. |
| 5738 | stdout = RunCommand(cmd, error_ok=True, cwd=top_dir) |
| 5739 | if opts.diff: |
| 5740 | sys.stdout.write(stdout) |
| 5741 | elif len(stdout) > 0: |
| 5742 | return_value = 2 |
| 5743 | else: |
| 5744 | cmd += ['-i'] |
| 5745 | RunCommand(cmd, cwd=top_dir) |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5746 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5747 | # Dart's formatter does not have the nice property of only operating on |
| 5748 | # modified chunks, so hard code full. |
| 5749 | if dart_diff_files: |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5750 | try: |
| 5751 | command = [dart_format.FindDartFmtToolInChromiumTree()] |
| 5752 | if not opts.dry_run and not opts.diff: |
| 5753 | command.append('-w') |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5754 | command.extend(dart_diff_files) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5755 | |
ppi@chromium.org | 6593d93 | 2016-03-03 15:41:15 +0000 | [diff] [blame] | 5756 | stdout = RunCommand(command, cwd=top_dir) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5757 | if opts.dry_run and stdout: |
| 5758 | return_value = 2 |
| 5759 | except dart_format.NotFoundError as e: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5760 | print('Warning: Unable to check Dart code formatting. Dart SDK not ' |
| 5761 | 'found in this checkout. Files in other languages are still ' |
| 5762 | 'formatted.') |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5763 | |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 5764 | # Format GN build files. Always run on full build files for canonical form. |
| 5765 | if gn_diff_files: |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5766 | cmd = ['gn', 'format'] |
brettw | 4b8ed59 | 2016-08-05 16:19:12 -0700 | [diff] [blame] | 5767 | if opts.dry_run or opts.diff: |
| 5768 | cmd.append('--dry-run') |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 5769 | for gn_diff_file in gn_diff_files: |
brettw | 4b8ed59 | 2016-08-05 16:19:12 -0700 | [diff] [blame] | 5770 | gn_ret = subprocess2.call(cmd + [gn_diff_file], |
| 5771 | shell=sys.platform == 'win32', |
| 5772 | cwd=top_dir) |
| 5773 | if opts.dry_run and gn_ret == 2: |
| 5774 | return_value = 2 # Not formatted. |
| 5775 | elif opts.diff and gn_ret == 2: |
| 5776 | # TODO this should compute and print the actual diff. |
| 5777 | print("This change has GN build file diff for " + gn_diff_file) |
| 5778 | elif gn_ret != 0: |
| 5779 | # For non-dry run cases (and non-2 return values for dry-run), a |
| 5780 | # nonzero error code indicates a failure, probably because the file |
| 5781 | # doesn't parse. |
| 5782 | DieWithError("gn format failed on " + gn_diff_file + |
| 5783 | "\nTry running 'gn format' on this file manually.") |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 5784 | |
Ilya Sherman | e081cbe | 2017-08-15 17:51:04 -0700 | [diff] [blame] | 5785 | # Skip the metrics formatting from the global presubmit hook. These files have |
| 5786 | # a separate presubmit hook that issues an error if the files need formatting, |
| 5787 | # whereas the top-level presubmit script merely issues a warning. Formatting |
| 5788 | # these files is somewhat slow, so it's important not to duplicate the work. |
| 5789 | if not opts.presubmit: |
| 5790 | for xml_dir in GetDirtyMetricsDirs(diff_files): |
| 5791 | tool_dir = os.path.join(top_dir, xml_dir) |
| 5792 | cmd = [os.path.join(tool_dir, 'pretty_print.py'), '--non-interactive'] |
| 5793 | if opts.dry_run or opts.diff: |
| 5794 | cmd.append('--diff') |
Ilya Sherman | 235b70d | 2017-08-22 17:46:38 -0700 | [diff] [blame] | 5795 | stdout = RunCommand(cmd, cwd=top_dir) |
Ilya Sherman | e081cbe | 2017-08-15 17:51:04 -0700 | [diff] [blame] | 5796 | if opts.diff: |
| 5797 | sys.stdout.write(stdout) |
| 5798 | if opts.dry_run and stdout: |
| 5799 | return_value = 2 # Not formatted. |
Alexei Svitkine | f3cac41 | 2017-02-06 11:08:50 -0500 | [diff] [blame] | 5800 | |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5801 | return return_value |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5802 | |
Steven Holte | 2e664bf | 2017-04-21 13:10:47 -0700 | [diff] [blame] | 5803 | def GetDirtyMetricsDirs(diff_files): |
| 5804 | xml_diff_files = [x for x in diff_files if MatchingFileType(x, ['.xml'])] |
| 5805 | metrics_xml_dirs = [ |
| 5806 | os.path.join('tools', 'metrics', 'actions'), |
| 5807 | os.path.join('tools', 'metrics', 'histograms'), |
| 5808 | os.path.join('tools', 'metrics', 'rappor'), |
| 5809 | os.path.join('tools', 'metrics', 'ukm')] |
| 5810 | for xml_dir in metrics_xml_dirs: |
| 5811 | if any(file.startswith(xml_dir) for file in xml_diff_files): |
| 5812 | yield xml_dir |
| 5813 | |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5814 | |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5815 | @subcommand.usage('<codereview url or issue id>') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5816 | @metrics.collector.collect_metrics('git cl checkout') |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5817 | def CMDcheckout(parser, args): |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 5818 | """Checks out a branch associated with a given Rietveld or Gerrit issue.""" |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5819 | _, args = parser.parse_args(args) |
| 5820 | |
| 5821 | if len(args) != 1: |
| 5822 | parser.print_help() |
| 5823 | return 1 |
| 5824 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5825 | issue_arg = ParseIssueNumberArgument(args[0]) |
tandrii@chromium.org | de6c9a1 | 2016-04-11 15:33:53 +0000 | [diff] [blame] | 5826 | if not issue_arg.valid: |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 5827 | parser.error('invalid codereview url or CL id') |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 5828 | |
tandrii@chromium.org | abd27e5 | 2016-04-11 15:43:32 +0000 | [diff] [blame] | 5829 | target_issue = str(issue_arg.issue) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5830 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 5831 | def find_issues(issueprefix): |
tandrii@chromium.org | 26c8fd2 | 2016-04-11 21:33:21 +0000 | [diff] [blame] | 5832 | output = RunGit(['config', '--local', '--get-regexp', |
| 5833 | r'branch\..*\.%s' % issueprefix], |
| 5834 | error_ok=True) |
| 5835 | for key, issue in [x.split() for x in output.splitlines()]: |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 5836 | if issue == target_issue: |
| 5837 | yield re.sub(r'branch\.(.*)\.%s' % issueprefix, r'\1', key) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5838 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 5839 | branches = [] |
| 5840 | for cls in _CODEREVIEW_IMPLEMENTATIONS.values(): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 5841 | branches.extend(find_issues(cls.IssueConfigKey())) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5842 | if len(branches) == 0: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5843 | print('No branch found for issue %s.' % target_issue) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5844 | return 1 |
| 5845 | if len(branches) == 1: |
| 5846 | RunGit(['checkout', branches[0]]) |
| 5847 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5848 | print('Multiple branches match issue %s:' % target_issue) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5849 | for i in range(len(branches)): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5850 | print('%d: %s' % (i, branches[i])) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5851 | which = raw_input('Choose by index: ') |
| 5852 | try: |
| 5853 | RunGit(['checkout', branches[int(which)]]) |
| 5854 | except (IndexError, ValueError): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5855 | print('Invalid selection, not checking out any branch.') |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5856 | return 1 |
| 5857 | |
| 5858 | return 0 |
| 5859 | |
| 5860 | |
maruel@chromium.org | 29404b5 | 2014-09-08 22:58:00 +0000 | [diff] [blame] | 5861 | def CMDlol(parser, args): |
| 5862 | # This command is intentionally undocumented. |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5863 | print(zlib.decompress(base64.b64decode( |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 5864 | 'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE' |
| 5865 | 'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9' |
| 5866 | 'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W' |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5867 | 'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY'))) |
maruel@chromium.org | 29404b5 | 2014-09-08 22:58:00 +0000 | [diff] [blame] | 5868 | return 0 |
| 5869 | |
| 5870 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5871 | class OptionParser(optparse.OptionParser): |
| 5872 | """Creates the option parse and add --verbose support.""" |
| 5873 | def __init__(self, *args, **kwargs): |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 5874 | optparse.OptionParser.__init__( |
| 5875 | self, *args, prog='git cl', version=__version__, **kwargs) |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5876 | self.add_option( |
| 5877 | '-v', '--verbose', action='count', default=0, |
| 5878 | help='Use 2 times for more debugging info') |
| 5879 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5880 | def parse_args(self, args=None, _values=None): |
| 5881 | # Create an optparse.Values object that will store only the actual passed |
| 5882 | # options, without the defaults. |
| 5883 | actual_options = optparse.Values() |
| 5884 | _, args = optparse.OptionParser.parse_args(self, args, actual_options) |
| 5885 | # Create an optparse.Values object with the default options. |
| 5886 | options = optparse.Values(self.get_default_values().__dict__) |
| 5887 | # Update it with the options passed by the user. |
| 5888 | options._update_careful(actual_options.__dict__) |
| 5889 | # Store the options passed by the user in an _actual_options attribute. |
| 5890 | # We store only the keys, and not the values, since the values can contain |
| 5891 | # arbitrary information, which might be PII. |
| 5892 | metrics.collector.add('arguments', actual_options.__dict__.keys()) |
| 5893 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5894 | levels = [logging.WARNING, logging.INFO, logging.DEBUG] |
Andrii Shyshkalov | 5b04a57 | 2017-01-23 17:44:41 +0100 | [diff] [blame] | 5895 | logging.basicConfig( |
| 5896 | level=levels[min(options.verbose, len(levels) - 1)], |
| 5897 | format='[%(levelname).1s%(asctime)s %(process)d %(thread)d ' |
| 5898 | '%(filename)s] %(message)s') |
Edward Lemur | 83bd7f4 | 2018-10-10 00:14:21 +0000 | [diff] [blame] | 5899 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5900 | return options, args |
| 5901 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5902 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5903 | def main(argv): |
maruel@chromium.org | 82798cb | 2012-02-23 18:16:12 +0000 | [diff] [blame] | 5904 | if sys.hexversion < 0x02060000: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5905 | print('\nYour python version %s is unsupported, please upgrade.\n' % |
| 5906 | (sys.version.split(' ', 1)[0],), file=sys.stderr) |
maruel@chromium.org | 82798cb | 2012-02-23 18:16:12 +0000 | [diff] [blame] | 5907 | return 2 |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 5908 | |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 5909 | # Reload settings. |
| 5910 | global settings |
| 5911 | settings = Settings() |
| 5912 | |
Edward Lemur | ad463c9 | 2018-07-25 21:31:23 +0000 | [diff] [blame] | 5913 | if not metrics.DISABLE_METRICS_COLLECTION: |
Edward Lesmes | 93277a7 | 2018-10-18 22:04:26 +0000 | [diff] [blame] | 5914 | project_url = settings.GetViewVCUrl().strip('/+') |
| 5915 | if project_url in metrics_utils.KNOWN_PROJECT_URLS: |
| 5916 | metrics.collector.add('project_urls', [project_url]) |
| 5917 | |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 5918 | colorize_CMDstatus_doc() |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 5919 | dispatcher = subcommand.CommandDispatcher(__name__) |
| 5920 | try: |
| 5921 | return dispatcher.execute(OptionParser(), argv) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 5922 | except auth.AuthenticationError as e: |
| 5923 | DieWithError(str(e)) |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 5924 | except urllib2.HTTPError as e: |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 5925 | if e.code != 500: |
| 5926 | raise |
| 5927 | DieWithError( |
| 5928 | ('AppEngine is misbehaving and returned HTTP %d, again. Keep faith ' |
| 5929 | 'and retry or visit go/isgaeup.\n%s') % (e.code, str(e))) |
sbc@chromium.org | 013731e | 2015-02-26 18:28:43 +0000 | [diff] [blame] | 5930 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5931 | |
| 5932 | |
| 5933 | if __name__ == '__main__': |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 5934 | # These affect sys.stdout so do it outside of main() to simplify mocks in |
| 5935 | # unit testing. |
maruel@chromium.org | 6f09cd9 | 2011-04-01 16:38:12 +0000 | [diff] [blame] | 5936 | fix_encoding.fix_encoding() |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 5937 | setup_color.init() |
Edward Lemur | 6f812e1 | 2018-07-31 22:45:57 +0000 | [diff] [blame] | 5938 | with metrics.collector.print_notice_and_exit(): |
sbc@chromium.org | 013731e | 2015-02-26 18:28:43 +0000 | [diff] [blame] | 5939 | sys.exit(main(sys.argv[1:])) |