iannucci@chromium.org | 405b87e | 2015-11-12 18:08:34 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
miket@chromium.org | 183df1a | 2012-01-04 19:44:55 +0000 | [diff] [blame] | 2 | # Copyright (c) 2012 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 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 8 | """A git-command for integrating reviews on Rietveld and 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 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 30 | import textwrap |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 31 | import urllib |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 32 | import urllib2 |
maruel@chromium.org | 967c0a8 | 2013-06-17 22:52:24 +0000 | [diff] [blame] | 33 | import urlparse |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 34 | import uuid |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 35 | import webbrowser |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 36 | import zlib |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 37 | |
| 38 | try: |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 39 | import readline # pylint: disable=import-error,W0611 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 40 | except ImportError: |
| 41 | pass |
| 42 | |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 43 | from third_party import colorama |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 44 | from third_party import httplib2 |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 45 | from third_party import upload |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 46 | import auth |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 47 | import checkout |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 48 | import clang_format |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 49 | import dart_format |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 50 | import setup_color |
maruel@chromium.org | 6f09cd9 | 2011-04-01 16:38:12 +0000 | [diff] [blame] | 51 | import fix_encoding |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 52 | import gclient_utils |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 53 | import gerrit_util |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 54 | import git_cache |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 55 | import git_common |
tandrii@chromium.org | 09d7a6a | 2016-03-04 15:44:48 +0000 | [diff] [blame] | 56 | import git_footers |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 57 | import owners |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 58 | import owners_finder |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 59 | import presubmit_support |
maruel@chromium.org | cab38e9 | 2011-04-09 00:30:51 +0000 | [diff] [blame] | 60 | import rietveld |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 61 | import scm |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 62 | import split_cl |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 63 | import subcommand |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 64 | import subprocess2 |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 65 | import watchlists |
| 66 | |
tandrii | 7400cf0 | 2016-06-21 08:48:07 -0700 | [diff] [blame] | 67 | __version__ = '2.0' |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 68 | |
tandrii | 9d2c7a3 | 2016-06-22 03:42:45 -0700 | [diff] [blame] | 69 | COMMIT_BOT_EMAIL = 'commit-bot@chromium.org' |
iannucci | e7f6895 | 2016-08-15 17:45:29 -0700 | [diff] [blame] | 70 | DEFAULT_SERVER = 'https://codereview.chromium.org' |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 71 | POSTUPSTREAM_HOOK = '.git/hooks/post-cl-land' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 72 | DESCRIPTION_BACKUP_FILE = '~/.git_cl_description_backup' |
rmistry@google.com | c68112d | 2015-03-03 12:48:06 +0000 | [diff] [blame] | 73 | REFS_THAT_ALIAS_TO_OTHER_REFS = { |
| 74 | 'refs/remotes/origin/lkgr': 'refs/remotes/origin/master', |
| 75 | 'refs/remotes/origin/lkcr': 'refs/remotes/origin/master', |
| 76 | } |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 77 | |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 78 | # Valid extensions for files we want to lint. |
| 79 | DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)" |
| 80 | DEFAULT_LINT_IGNORE_REGEX = r"$^" |
| 81 | |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 82 | # Buildbucket master name prefix. |
| 83 | MASTER_PREFIX = 'master.' |
| 84 | |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 85 | # Shortcut since it quickly becomes redundant. |
| 86 | Fore = colorama.Fore |
maruel@chromium.org | 9054173 | 2011-04-01 17:54:18 +0000 | [diff] [blame] | 87 | |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 88 | # Initialized in main() |
| 89 | settings = None |
| 90 | |
Andrii Shyshkalov | 768f1d8 | 2016-12-08 15:10:13 +0100 | [diff] [blame] | 91 | # Used by tests/git_cl_test.py to add extra logging. |
| 92 | # Inside the weirdly failing test, add this: |
| 93 | # >>> self.mock(git_cl, '_IS_BEING_TESTED', True) |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 94 | # And scroll up to see the stack trace printed. |
Andrii Shyshkalov | 768f1d8 | 2016-12-08 15:10:13 +0100 | [diff] [blame] | 95 | _IS_BEING_TESTED = False |
| 96 | |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 97 | |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 98 | def DieWithError(message, change_desc=None): |
| 99 | if change_desc: |
| 100 | SaveDescriptionBackup(change_desc) |
| 101 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 102 | print(message, file=sys.stderr) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 103 | sys.exit(1) |
| 104 | |
| 105 | |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 106 | def SaveDescriptionBackup(change_desc): |
| 107 | backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE) |
| 108 | print('\nError after CL description prompt -- saving description to %s\n' % |
| 109 | backup_path) |
| 110 | backup_file = open(backup_path, 'w') |
| 111 | backup_file.write(change_desc.description) |
| 112 | backup_file.close() |
| 113 | |
| 114 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 115 | def GetNoGitPagerEnv(): |
| 116 | env = os.environ.copy() |
| 117 | # 'cat' is a magical git string that disables pagers on all platforms. |
| 118 | env['GIT_PAGER'] = 'cat' |
| 119 | return env |
| 120 | |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 121 | |
bsep@chromium.org | 627d900 | 2016-04-29 00:00:52 +0000 | [diff] [blame] | 122 | 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] | 123 | try: |
bsep@chromium.org | 627d900 | 2016-04-29 00:00:52 +0000 | [diff] [blame] | 124 | return subprocess2.check_output(args, shell=shell, **kwargs) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 125 | except subprocess2.CalledProcessError as e: |
| 126 | logging.debug('Failed running %s', args) |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 127 | if not error_ok: |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 128 | DieWithError( |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 129 | 'Command "%s" failed.\n%s' % ( |
| 130 | ' '.join(args), error_message or e.stdout or '')) |
| 131 | return e.stdout |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 132 | |
| 133 | |
| 134 | def RunGit(args, **kwargs): |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 135 | """Returns stdout.""" |
bratell@opera.com | 82b91cd | 2013-07-09 06:33:41 +0000 | [diff] [blame] | 136 | return RunCommand(['git'] + args, **kwargs) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 137 | |
| 138 | |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 139 | def RunGitWithCode(args, suppress_stderr=False): |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 140 | """Returns return code and stdout.""" |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 141 | if suppress_stderr: |
| 142 | stderr = subprocess2.VOID |
| 143 | else: |
| 144 | stderr = sys.stderr |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 145 | try: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 146 | (out, _), code = subprocess2.communicate(['git'] + args, |
| 147 | env=GetNoGitPagerEnv(), |
| 148 | stdout=subprocess2.PIPE, |
| 149 | stderr=stderr) |
| 150 | return code, out |
| 151 | except subprocess2.CalledProcessError as e: |
| 152 | logging.debug('Failed running %s', args) |
| 153 | return e.returncode, e.stdout |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 154 | |
| 155 | |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 156 | def RunGitSilent(args): |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 157 | """Returns stdout, suppresses stderr and ignores the return code.""" |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 158 | return RunGitWithCode(args, suppress_stderr=True)[1] |
| 159 | |
| 160 | |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 161 | def IsGitVersionAtLeast(min_version): |
ilevy@chromium.org | cc56ee4 | 2013-07-10 22:16:29 +0000 | [diff] [blame] | 162 | prefix = 'git version ' |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 163 | version = RunGit(['--version']).strip() |
ilevy@chromium.org | cc56ee4 | 2013-07-10 22:16:29 +0000 | [diff] [blame] | 164 | return (version.startswith(prefix) and |
| 165 | LooseVersion(version[len(prefix):]) >= LooseVersion(min_version)) |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 166 | |
| 167 | |
pgervais@chromium.org | 8ba38ff | 2015-06-11 21:41:25 +0000 | [diff] [blame] | 168 | def BranchExists(branch): |
| 169 | """Return True if specified branch exists.""" |
| 170 | code, _ = RunGitWithCode(['rev-parse', '--verify', branch], |
| 171 | suppress_stderr=True) |
| 172 | return not code |
| 173 | |
| 174 | |
tandrii | 2a16b95 | 2016-10-19 07:09:44 -0700 | [diff] [blame] | 175 | def time_sleep(seconds): |
| 176 | # Use this so that it can be mocked in tests without interfering with python |
| 177 | # system machinery. |
| 178 | import time # Local import to discourage others from importing time globally. |
| 179 | return time.sleep(seconds) |
| 180 | |
| 181 | |
maruel@chromium.org | 9054173 | 2011-04-01 17:54:18 +0000 | [diff] [blame] | 182 | def ask_for_data(prompt): |
| 183 | try: |
| 184 | return raw_input(prompt) |
| 185 | except KeyboardInterrupt: |
| 186 | # Hide the exception. |
| 187 | sys.exit(1) |
| 188 | |
| 189 | |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 190 | def confirm_or_exit(prefix='', action='confirm'): |
| 191 | """Asks user to press enter to continue or press Ctrl+C to abort.""" |
| 192 | if not prefix or prefix.endswith('\n'): |
| 193 | mid = 'Press' |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 194 | elif prefix.endswith('.') or prefix.endswith('?'): |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 195 | mid = ' Press' |
| 196 | elif prefix.endswith(' '): |
| 197 | mid = 'press' |
| 198 | else: |
| 199 | mid = ' press' |
| 200 | ask_for_data('%s%s Enter to %s, or Ctrl+C to abort' % (prefix, mid, action)) |
| 201 | |
| 202 | |
| 203 | def ask_for_explicit_yes(prompt): |
| 204 | """Returns whether user typed 'y' or 'yes' to confirm the given prompt""" |
| 205 | result = ask_for_data(prompt + ' [Yes/No]: ').lower() |
| 206 | while True: |
| 207 | if 'yes'.startswith(result): |
| 208 | return True |
| 209 | if 'no'.startswith(result): |
| 210 | return False |
| 211 | result = ask_for_data('Please, type yes or no: ').lower() |
| 212 | |
| 213 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 214 | def _git_branch_config_key(branch, key): |
| 215 | """Helper method to return Git config key for a branch.""" |
| 216 | assert branch, 'branch name is required to set git config for it' |
| 217 | return 'branch.%s.%s' % (branch, key) |
| 218 | |
| 219 | |
| 220 | def _git_get_branch_config_value(key, default=None, value_type=str, |
| 221 | branch=False): |
| 222 | """Returns git config value of given or current branch if any. |
| 223 | |
| 224 | Returns default in all other cases. |
| 225 | """ |
| 226 | assert value_type in (int, str, bool) |
| 227 | if branch is False: # Distinguishing default arg value from None. |
| 228 | branch = GetCurrentBranch() |
| 229 | |
rogerta@chromium.org | caa1655 | 2013-03-18 20:45:05 +0000 | [diff] [blame] | 230 | if not branch: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 231 | return default |
rogerta@chromium.org | caa1655 | 2013-03-18 20:45:05 +0000 | [diff] [blame] | 232 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 233 | args = ['config'] |
tandrii | 33a46ff | 2016-08-23 05:53:40 -0700 | [diff] [blame] | 234 | if value_type == bool: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 235 | args.append('--bool') |
tandrii | 33a46ff | 2016-08-23 05:53:40 -0700 | [diff] [blame] | 236 | # git config also has --int, but apparently git config suffers from integer |
| 237 | # overflows (http://crbug.com/640115), so don't use it. |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 238 | args.append(_git_branch_config_key(branch, key)) |
| 239 | code, out = RunGitWithCode(args) |
| 240 | if code == 0: |
| 241 | value = out.strip() |
| 242 | if value_type == int: |
| 243 | return int(value) |
| 244 | if value_type == bool: |
| 245 | return bool(value.lower() == 'true') |
| 246 | return value |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 247 | return default |
| 248 | |
| 249 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 250 | def _git_set_branch_config_value(key, value, branch=None, **kwargs): |
| 251 | """Sets the value or unsets if it's None of a git branch config. |
| 252 | |
| 253 | Valid, though not necessarily existing, branch must be provided, |
| 254 | otherwise currently checked out branch is used. |
| 255 | """ |
| 256 | if not branch: |
| 257 | branch = GetCurrentBranch() |
| 258 | assert branch, 'a branch name OR currently checked out branch is required' |
| 259 | args = ['config'] |
qyearsley | 12fa6ff | 2016-08-24 09:18:40 -0700 | [diff] [blame] | 260 | # Check for boolean first, because bool is int, but int is not bool. |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 261 | if value is None: |
| 262 | args.append('--unset') |
| 263 | elif isinstance(value, bool): |
| 264 | args.append('--bool') |
| 265 | value = str(value).lower() |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 266 | else: |
tandrii | 33a46ff | 2016-08-23 05:53:40 -0700 | [diff] [blame] | 267 | # git config also has --int, but apparently git config suffers from integer |
| 268 | # overflows (http://crbug.com/640115), so don't use it. |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 269 | value = str(value) |
| 270 | args.append(_git_branch_config_key(branch, key)) |
| 271 | if value is not None: |
| 272 | args.append(value) |
| 273 | RunGit(args, **kwargs) |
| 274 | |
| 275 | |
Andrii Shyshkalov | a669581 | 2016-12-06 17:47:09 +0100 | [diff] [blame] | 276 | def _get_committer_timestamp(commit): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 277 | """Returns Unix timestamp as integer of a committer in a commit. |
Andrii Shyshkalov | a669581 | 2016-12-06 17:47:09 +0100 | [diff] [blame] | 278 | |
| 279 | Commit can be whatever git show would recognize, such as HEAD, sha1 or ref. |
| 280 | """ |
| 281 | # Git also stores timezone offset, but it only affects visual display, |
| 282 | # actual point in time is defined by this timestamp only. |
| 283 | return int(RunGit(['show', '-s', '--format=%ct', commit]).strip()) |
| 284 | |
| 285 | |
| 286 | def _git_amend_head(message, committer_timestamp): |
| 287 | """Amends commit with new message and desired committer_timestamp. |
| 288 | |
| 289 | Sets committer timezone to UTC. |
| 290 | """ |
| 291 | env = os.environ.copy() |
| 292 | env['GIT_COMMITTER_DATE'] = '%d+0000' % committer_timestamp |
| 293 | return RunGit(['commit', '--amend', '-m', message], env=env) |
| 294 | |
| 295 | |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 296 | def add_git_similarity(parser): |
| 297 | parser.add_option( |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 298 | '--similarity', metavar='SIM', type=int, action='store', |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 299 | help='Sets the percentage that a pair of files need to match in order to' |
| 300 | ' be considered copies (default 50)') |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 301 | parser.add_option( |
| 302 | '--find-copies', action='store_true', |
| 303 | help='Allows git to look for copies.') |
| 304 | parser.add_option( |
| 305 | '--no-find-copies', action='store_false', dest='find_copies', |
| 306 | help='Disallows git from looking for copies.') |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 307 | |
| 308 | old_parser_args = parser.parse_args |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 309 | |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 310 | def Parse(args): |
| 311 | options, args = old_parser_args(args) |
| 312 | |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 313 | if options.similarity is None: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 314 | options.similarity = _git_get_branch_config_value( |
| 315 | 'git-cl-similarity', default=50, value_type=int) |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 316 | else: |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 317 | print('Note: Saving similarity of %d%% in git config.' |
| 318 | % options.similarity) |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 319 | _git_set_branch_config_value('git-cl-similarity', options.similarity) |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 320 | |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 321 | options.similarity = max(0, min(options.similarity, 100)) |
| 322 | |
| 323 | if options.find_copies is None: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 324 | options.find_copies = _git_get_branch_config_value( |
| 325 | 'git-find-copies', default=True, value_type=bool) |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 326 | else: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 327 | _git_set_branch_config_value('git-find-copies', bool(options.find_copies)) |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 328 | |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 329 | return options, args |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 330 | |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 331 | parser.parse_args = Parse |
| 332 | |
| 333 | |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 334 | def _get_properties_from_options(options): |
| 335 | properties = dict(x.split('=', 1) for x in options.properties) |
| 336 | for key, val in properties.iteritems(): |
| 337 | try: |
| 338 | properties[key] = json.loads(val) |
| 339 | except ValueError: |
| 340 | pass # If a value couldn't be evaluated, treat it as a string. |
| 341 | return properties |
| 342 | |
| 343 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 344 | def _prefix_master(master): |
| 345 | """Convert user-specified master name to full master name. |
| 346 | |
| 347 | Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket |
| 348 | name, while the developers always use shortened master name |
| 349 | (tryserver.chromium.linux) by stripping off the prefix 'master.'. This |
| 350 | function does the conversion for buildbucket migration. |
| 351 | """ |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 352 | if master.startswith(MASTER_PREFIX): |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 353 | return master |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 354 | return '%s%s' % (MASTER_PREFIX, master) |
| 355 | |
| 356 | |
| 357 | def _unprefix_master(bucket): |
| 358 | """Convert bucket name to shortened master name. |
| 359 | |
| 360 | Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket |
| 361 | name, while the developers always use shortened master name |
| 362 | (tryserver.chromium.linux) by stripping off the prefix 'master.'. This |
| 363 | function does the conversion for buildbucket migration. |
| 364 | """ |
| 365 | if bucket.startswith(MASTER_PREFIX): |
| 366 | return bucket[len(MASTER_PREFIX):] |
| 367 | return bucket |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 368 | |
| 369 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 370 | def _buildbucket_retry(operation_name, http, *args, **kwargs): |
| 371 | """Retries requests to buildbucket service and returns parsed json content.""" |
| 372 | try_count = 0 |
| 373 | while True: |
| 374 | response, content = http.request(*args, **kwargs) |
| 375 | try: |
| 376 | content_json = json.loads(content) |
| 377 | except ValueError: |
| 378 | content_json = None |
| 379 | |
| 380 | # Buildbucket could return an error even if status==200. |
| 381 | if content_json and content_json.get('error'): |
nodir@chromium.org | baff4e1 | 2016-03-08 00:33:57 +0000 | [diff] [blame] | 382 | error = content_json.get('error') |
| 383 | if error.get('code') == 403: |
| 384 | raise BuildbucketResponseException( |
| 385 | 'Access denied: %s' % error.get('message', '')) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 386 | msg = 'Error in response. Reason: %s. Message: %s.' % ( |
nodir@chromium.org | baff4e1 | 2016-03-08 00:33:57 +0000 | [diff] [blame] | 387 | error.get('reason', ''), error.get('message', '')) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 388 | raise BuildbucketResponseException(msg) |
| 389 | |
| 390 | if response.status == 200: |
| 391 | if not content_json: |
| 392 | raise BuildbucketResponseException( |
| 393 | 'Buildbucket returns invalid json content: %s.\n' |
| 394 | 'Please file bugs at http://crbug.com, label "Infra-BuildBucket".' % |
| 395 | content) |
| 396 | return content_json |
| 397 | if response.status < 500 or try_count >= 2: |
| 398 | raise httplib2.HttpLib2Error(content) |
| 399 | |
| 400 | # status >= 500 means transient failures. |
| 401 | logging.debug('Transient errors when %s. Will retry.', operation_name) |
tandrii | 2a16b95 | 2016-10-19 07:09:44 -0700 | [diff] [blame] | 402 | time_sleep(0.5 + 1.5*try_count) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 403 | try_count += 1 |
| 404 | assert False, 'unreachable' |
| 405 | |
| 406 | |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 407 | def _get_bucket_map(changelist, options, option_parser): |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 408 | """Returns a dict mapping bucket names to builders and tests, |
| 409 | for triggering try jobs. |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 410 | """ |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 411 | # If no bots are listed, we try to get a set of builders and tests based |
| 412 | # on GetPreferredTryMasters functions in PRESUBMIT.py files. |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 413 | if not options.bot: |
| 414 | change = changelist.GetChange( |
| 415 | changelist.GetCommonAncestorWithUpstream(), None) |
qyearsley | 136b49f | 2016-10-31 09:02:26 -0700 | [diff] [blame] | 416 | # Get try masters from PRESUBMIT.py files. |
nodir | e4f0fe0 | 2016-11-04 16:23:30 -0700 | [diff] [blame] | 417 | masters = presubmit_support.DoGetTryMasters( |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 418 | change=change, |
| 419 | changed_files=change.LocalPaths(), |
| 420 | repository_root=settings.GetRoot(), |
| 421 | default_presubmit=None, |
| 422 | project=None, |
| 423 | verbose=options.verbose, |
| 424 | output_stream=sys.stdout) |
nodir | e4f0fe0 | 2016-11-04 16:23:30 -0700 | [diff] [blame] | 425 | if masters is None: |
| 426 | return None |
Sergiy Byelozyorov | 935b93f | 2016-11-28 20:41:56 +0100 | [diff] [blame] | 427 | return {_prefix_master(m): b for m, b in masters.iteritems()} |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 428 | |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 429 | if options.bucket: |
| 430 | return {options.bucket: {b: [] for b in options.bot}} |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 431 | if options.master: |
| 432 | return {_prefix_master(options.master): {b: [] for b in options.bot}} |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 433 | |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 434 | # If bots are listed but no master or bucket, then we need to find out |
| 435 | # the corresponding master for each bot. |
| 436 | bucket_map, error_message = _get_bucket_map_for_builders(options.bot) |
| 437 | if error_message: |
| 438 | option_parser.error( |
| 439 | 'Tryserver master cannot be found because: %s\n' |
| 440 | 'Please manually specify the tryserver master, e.g. ' |
| 441 | '"-m tryserver.chromium.linux".' % error_message) |
| 442 | return bucket_map |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 443 | |
| 444 | |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 445 | def _get_bucket_map_for_builders(builders): |
| 446 | """Returns a map of buckets to builders for the given builders.""" |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 447 | map_url = 'https://builders-map.appspot.com/' |
| 448 | try: |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 449 | builders_map = json.load(urllib2.urlopen(map_url)) |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 450 | except urllib2.URLError as e: |
| 451 | return None, ('Failed to fetch builder-to-master map from %s. Error: %s.' % |
| 452 | (map_url, e)) |
| 453 | except ValueError as e: |
| 454 | return None, ('Invalid json string from %s. Error: %s.' % (map_url, e)) |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 455 | if not builders_map: |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 456 | return None, 'Failed to build master map.' |
| 457 | |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 458 | bucket_map = {} |
| 459 | for builder in builders: |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 460 | masters = builders_map.get(builder, []) |
| 461 | if not masters: |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 462 | return None, ('No matching master for builder %s.' % builder) |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 463 | if len(masters) > 1: |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 464 | return None, ('The builder name %s exists in multiple masters %s.' % |
qyearsley | 123a468 | 2016-10-26 09:12:17 -0700 | [diff] [blame] | 465 | (builder, masters)) |
| 466 | bucket = _prefix_master(masters[0]) |
| 467 | bucket_map.setdefault(bucket, {})[builder] = [] |
| 468 | |
| 469 | return bucket_map, None |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 470 | |
| 471 | |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 472 | def _trigger_try_jobs(auth_config, changelist, buckets, options, |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 473 | category='git_cl_try', patchset=None): |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 474 | """Sends a request to Buildbucket to trigger try jobs for a changelist. |
| 475 | |
| 476 | Args: |
| 477 | auth_config: AuthConfig for Rietveld. |
| 478 | changelist: Changelist that the try jobs are associated with. |
| 479 | buckets: A nested dict mapping bucket names to builders to tests. |
| 480 | options: Command-line options. |
| 481 | """ |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 482 | assert changelist.GetIssue(), 'CL must be uploaded first' |
| 483 | codereview_url = changelist.GetCodereviewServer() |
| 484 | assert codereview_url, 'CL must be uploaded first' |
| 485 | patchset = patchset or changelist.GetMostRecentPatchset() |
| 486 | assert patchset, 'CL must be uploaded first' |
| 487 | |
| 488 | codereview_host = urlparse.urlparse(codereview_url).hostname |
| 489 | authenticator = auth.get_authenticator_for_host(codereview_host, auth_config) |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 490 | http = authenticator.authorize(httplib2.Http()) |
| 491 | http.force_exception_to_status_code = True |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 492 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 493 | buildbucket_put_url = ( |
| 494 | 'https://{hostname}/_ah/api/buildbucket/v1/builds/batch'.format( |
sheyang@chromium.org | db37557 | 2015-08-17 19:22:23 +0000 | [diff] [blame] | 495 | hostname=options.buildbucket_host)) |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 496 | buildset = 'patch/{codereview}/{hostname}/{issue}/{patch}'.format( |
| 497 | codereview='gerrit' if changelist.IsGerrit() else 'rietveld', |
| 498 | hostname=codereview_host, |
| 499 | issue=changelist.GetIssue(), |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 500 | patch=patchset) |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 501 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 502 | shared_parameters_properties = changelist.GetTryJobProperties(patchset) |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 503 | shared_parameters_properties['category'] = category |
| 504 | if options.clobber: |
| 505 | shared_parameters_properties['clobber'] = True |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 506 | extra_properties = _get_properties_from_options(options) |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 507 | if extra_properties: |
| 508 | shared_parameters_properties.update(extra_properties) |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 509 | |
| 510 | batch_req_body = {'builds': []} |
| 511 | print_text = [] |
| 512 | print_text.append('Tried jobs on:') |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 513 | for bucket, builders_and_tests in sorted(buckets.iteritems()): |
| 514 | print_text.append('Bucket: %s' % bucket) |
| 515 | master = None |
| 516 | if bucket.startswith(MASTER_PREFIX): |
| 517 | master = _unprefix_master(bucket) |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 518 | for builder, tests in sorted(builders_and_tests.iteritems()): |
| 519 | print_text.append(' %s: %s' % (builder, tests)) |
| 520 | parameters = { |
| 521 | 'builder_name': builder, |
nodir@chromium.org | d221731 | 2015-09-21 15:51:21 +0000 | [diff] [blame] | 522 | 'changes': [{ |
Andrii Shyshkalov | eadad92 | 2017-01-26 09:38:30 +0100 | [diff] [blame] | 523 | 'author': {'email': changelist.GetIssueOwner()}, |
nodir@chromium.org | d221731 | 2015-09-21 15:51:21 +0000 | [diff] [blame] | 524 | 'revision': options.revision, |
| 525 | }], |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 526 | 'properties': shared_parameters_properties.copy(), |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 527 | } |
machenbach@chromium.org | 2403e80 | 2016-04-29 12:34:42 +0000 | [diff] [blame] | 528 | if 'presubmit' in builder.lower(): |
| 529 | parameters['properties']['dry_run'] = 'true' |
tandrii@chromium.org | 3764fa2 | 2015-10-21 16:40:40 +0000 | [diff] [blame] | 530 | if tests: |
| 531 | parameters['properties']['testfilter'] = tests |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 532 | |
| 533 | tags = [ |
| 534 | 'builder:%s' % builder, |
| 535 | 'buildset:%s' % buildset, |
| 536 | 'user_agent:git_cl_try', |
| 537 | ] |
| 538 | if master: |
| 539 | parameters['properties']['master'] = master |
| 540 | tags.append('master:%s' % master) |
| 541 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 542 | batch_req_body['builds'].append( |
| 543 | { |
| 544 | 'bucket': bucket, |
| 545 | 'parameters_json': json.dumps(parameters), |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 546 | 'client_operation_id': str(uuid.uuid4()), |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 547 | 'tags': tags, |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 548 | } |
| 549 | ) |
| 550 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 551 | _buildbucket_retry( |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 552 | 'triggering try jobs', |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 553 | http, |
| 554 | buildbucket_put_url, |
| 555 | 'PUT', |
| 556 | body=json.dumps(batch_req_body), |
| 557 | headers={'Content-Type': 'application/json'} |
| 558 | ) |
tandrii@chromium.org | 35c6145 | 2016-02-26 15:24:57 +0000 | [diff] [blame] | 559 | print_text.append('To see results here, run: git cl try-results') |
| 560 | print_text.append('To see results in browser, run: git cl web') |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 561 | print('\n'.join(print_text)) |
kjellander@chromium.org | 4442454 | 2015-06-02 18:35:29 +0000 | [diff] [blame] | 562 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 563 | |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 564 | def fetch_try_jobs(auth_config, changelist, buildbucket_host, |
| 565 | patchset=None): |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 566 | """Fetches try jobs from buildbucket. |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 567 | |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 568 | 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] | 569 | """ |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 570 | assert buildbucket_host |
| 571 | assert changelist.GetIssue(), 'CL must be uploaded first' |
| 572 | assert changelist.GetCodereviewServer(), 'CL must be uploaded first' |
| 573 | patchset = patchset or changelist.GetMostRecentPatchset() |
| 574 | assert patchset, 'CL must be uploaded first' |
| 575 | |
| 576 | codereview_url = changelist.GetCodereviewServer() |
| 577 | codereview_host = urlparse.urlparse(codereview_url).hostname |
| 578 | authenticator = auth.get_authenticator_for_host(codereview_host, auth_config) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 579 | if authenticator.has_cached_credentials(): |
| 580 | http = authenticator.authorize(httplib2.Http()) |
| 581 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 582 | print('Warning: Some results might be missing because %s' % |
| 583 | # Get the message on how to login. |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 584 | (auth.LoginRequiredError(codereview_host).message,)) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 585 | http = httplib2.Http() |
| 586 | |
| 587 | http.force_exception_to_status_code = True |
| 588 | |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 589 | buildset = 'patch/{codereview}/{hostname}/{issue}/{patch}'.format( |
| 590 | codereview='gerrit' if changelist.IsGerrit() else 'rietveld', |
| 591 | hostname=codereview_host, |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 592 | issue=changelist.GetIssue(), |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 593 | patch=patchset) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 594 | params = {'tag': 'buildset:%s' % buildset} |
| 595 | |
| 596 | builds = {} |
| 597 | while True: |
| 598 | url = 'https://{hostname}/_ah/api/buildbucket/v1/search?{params}'.format( |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 599 | hostname=buildbucket_host, |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 600 | params=urllib.urlencode(params)) |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 601 | content = _buildbucket_retry('fetching try jobs', http, url, 'GET') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 602 | for build in content.get('builds', []): |
| 603 | builds[build['id']] = build |
| 604 | if 'next_cursor' in content: |
| 605 | params['start_cursor'] = content['next_cursor'] |
| 606 | else: |
| 607 | break |
| 608 | return builds |
| 609 | |
| 610 | |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 611 | def print_try_jobs(options, builds): |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 612 | """Prints nicely result of fetch_try_jobs.""" |
| 613 | if not builds: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 614 | print('No try jobs scheduled.') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 615 | return |
| 616 | |
| 617 | # Make a copy, because we'll be modifying builds dictionary. |
| 618 | builds = builds.copy() |
| 619 | builder_names_cache = {} |
| 620 | |
| 621 | def get_builder(b): |
| 622 | try: |
| 623 | return builder_names_cache[b['id']] |
| 624 | except KeyError: |
| 625 | try: |
| 626 | parameters = json.loads(b['parameters_json']) |
| 627 | name = parameters['builder_name'] |
| 628 | except (ValueError, KeyError) as error: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 629 | print('WARNING: Failed to get builder name for build %s: %s' % ( |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 630 | b['id'], error)) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 631 | name = None |
| 632 | builder_names_cache[b['id']] = name |
| 633 | return name |
| 634 | |
| 635 | def get_bucket(b): |
| 636 | bucket = b['bucket'] |
| 637 | if bucket.startswith('master.'): |
| 638 | return bucket[len('master.'):] |
| 639 | return bucket |
| 640 | |
| 641 | if options.print_master: |
| 642 | name_fmt = '%%-%ds %%-%ds' % ( |
| 643 | max(len(str(get_bucket(b))) for b in builds.itervalues()), |
| 644 | max(len(str(get_builder(b))) for b in builds.itervalues())) |
| 645 | def get_name(b): |
| 646 | return name_fmt % (get_bucket(b), get_builder(b)) |
| 647 | else: |
| 648 | name_fmt = '%%-%ds' % ( |
| 649 | max(len(str(get_builder(b))) for b in builds.itervalues())) |
| 650 | def get_name(b): |
| 651 | return name_fmt % get_builder(b) |
| 652 | |
| 653 | def sort_key(b): |
| 654 | return b['status'], b.get('result'), get_name(b), b.get('url') |
| 655 | |
| 656 | def pop(title, f, color=None, **kwargs): |
| 657 | """Pop matching builds from `builds` dict and print them.""" |
| 658 | |
tandrii@chromium.org | 6cf98c8 | 2016-03-15 11:56:00 +0000 | [diff] [blame] | 659 | if not options.color or color is None: |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 660 | colorize = str |
| 661 | else: |
| 662 | colorize = lambda x: '%s%s%s' % (color, x, Fore.RESET) |
| 663 | |
| 664 | result = [] |
| 665 | for b in builds.values(): |
| 666 | if all(b.get(k) == v for k, v in kwargs.iteritems()): |
| 667 | builds.pop(b['id']) |
| 668 | result.append(b) |
| 669 | if result: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 670 | print(colorize(title)) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 671 | for b in sorted(result, key=sort_key): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 672 | print(' ', colorize('\t'.join(map(str, f(b))))) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 673 | |
| 674 | total = len(builds) |
| 675 | pop(status='COMPLETED', result='SUCCESS', |
| 676 | title='Successes:', color=Fore.GREEN, |
| 677 | f=lambda b: (get_name(b), b.get('url'))) |
| 678 | pop(status='COMPLETED', result='FAILURE', failure_reason='INFRA_FAILURE', |
| 679 | title='Infra Failures:', color=Fore.MAGENTA, |
| 680 | f=lambda b: (get_name(b), b.get('url'))) |
| 681 | pop(status='COMPLETED', result='FAILURE', failure_reason='BUILD_FAILURE', |
| 682 | title='Failures:', color=Fore.RED, |
| 683 | f=lambda b: (get_name(b), b.get('url'))) |
| 684 | pop(status='COMPLETED', result='CANCELED', |
| 685 | title='Canceled:', color=Fore.MAGENTA, |
| 686 | f=lambda b: (get_name(b),)) |
| 687 | pop(status='COMPLETED', result='FAILURE', |
| 688 | failure_reason='INVALID_BUILD_DEFINITION', |
| 689 | title='Wrong master/builder name:', color=Fore.MAGENTA, |
| 690 | f=lambda b: (get_name(b),)) |
| 691 | pop(status='COMPLETED', result='FAILURE', |
| 692 | title='Other failures:', |
| 693 | f=lambda b: (get_name(b), b.get('failure_reason'), b.get('url'))) |
| 694 | pop(status='COMPLETED', |
| 695 | title='Other finished:', |
| 696 | f=lambda b: (get_name(b), b.get('result'), b.get('url'))) |
| 697 | pop(status='STARTED', |
| 698 | title='Started:', color=Fore.YELLOW, |
| 699 | f=lambda b: (get_name(b), b.get('url'))) |
| 700 | pop(status='SCHEDULED', |
| 701 | title='Scheduled:', |
| 702 | f=lambda b: (get_name(b), 'id=%s' % b['id'])) |
| 703 | # The last section is just in case buildbucket API changes OR there is a bug. |
| 704 | pop(title='Other:', |
| 705 | f=lambda b: (get_name(b), 'id=%s' % b['id'])) |
| 706 | assert len(builds) == 0 |
qyearsley | eab3c04 | 2016-08-24 09:18:28 -0700 | [diff] [blame] | 707 | print('Total: %d try jobs' % total) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 708 | |
| 709 | |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 710 | def write_try_results_json(output_file, builds): |
| 711 | """Writes a subset of the data from fetch_try_jobs to a file as JSON. |
| 712 | |
| 713 | The input |builds| dict is assumed to be generated by Buildbucket. |
| 714 | Buildbucket documentation: http://goo.gl/G0s101 |
| 715 | """ |
| 716 | |
| 717 | def convert_build_dict(build): |
| 718 | return { |
| 719 | 'buildbucket_id': build.get('id'), |
| 720 | 'status': build.get('status'), |
| 721 | 'result': build.get('result'), |
| 722 | 'bucket': build.get('bucket'), |
| 723 | 'builder_name': json.loads( |
| 724 | build.get('parameters_json', '{}')).get('builder_name'), |
| 725 | 'failure_reason': build.get('failure_reason'), |
| 726 | 'url': build.get('url'), |
| 727 | } |
| 728 | |
| 729 | converted = [] |
| 730 | for _, build in sorted(builds.items()): |
| 731 | converted.append(convert_build_dict(build)) |
| 732 | write_json(output_file, converted) |
| 733 | |
| 734 | |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 735 | def print_stats(similarity, find_copies, args): |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 736 | """Prints statistics about the change to the user.""" |
| 737 | # --no-ext-diff is broken in some versions of Git, so try to work around |
| 738 | # this by overriding the environment (but there is still a problem if the |
| 739 | # git config key "diff.external" is used). |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 740 | env = GetNoGitPagerEnv() |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 741 | if 'GIT_EXTERNAL_DIFF' in env: |
| 742 | del env['GIT_EXTERNAL_DIFF'] |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 743 | |
| 744 | if find_copies: |
scottmg | b84b5e3 | 2016-11-10 09:25:33 -0800 | [diff] [blame] | 745 | similarity_options = ['-l100000', '-C%s' % similarity] |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 746 | else: |
| 747 | similarity_options = ['-M%s' % similarity] |
| 748 | |
szager@chromium.org | d057f9a | 2014-05-29 21:09:36 +0000 | [diff] [blame] | 749 | try: |
| 750 | stdout = sys.stdout.fileno() |
| 751 | except AttributeError: |
| 752 | stdout = None |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 753 | return subprocess2.call( |
bratell@opera.com | 82b91cd | 2013-07-09 06:33:41 +0000 | [diff] [blame] | 754 | ['git', |
bratell@opera.com | f267b0e | 2013-05-02 09:11:43 +0000 | [diff] [blame] | 755 | 'diff', '--no-ext-diff', '--stat'] + similarity_options + args, |
szager@chromium.org | d057f9a | 2014-05-29 21:09:36 +0000 | [diff] [blame] | 756 | stdout=stdout, env=env) |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 757 | |
| 758 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 759 | class BuildbucketResponseException(Exception): |
| 760 | pass |
| 761 | |
| 762 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 763 | class Settings(object): |
| 764 | def __init__(self): |
| 765 | self.default_server = None |
| 766 | self.cc = None |
thestig@chromium.org | 7a54e81 | 2014-02-11 19:57:22 +0000 | [diff] [blame] | 767 | self.root = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 768 | self.tree_status_url = None |
| 769 | self.viewvc_url = None |
| 770 | self.updated = False |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 771 | self.is_gerrit = None |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 772 | self.squash_gerrit_uploads = None |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 773 | self.gerrit_skip_ensure_authenticated = None |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 774 | self.git_editor = None |
sheyang@chromium.org | 152cf83 | 2014-06-11 21:37:49 +0000 | [diff] [blame] | 775 | self.project = None |
kjellander@chromium.org | 6abc652 | 2014-12-02 07:34:49 +0000 | [diff] [blame] | 776 | self.force_https_commit_url = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 777 | |
| 778 | def LazyUpdateIfNeeded(self): |
| 779 | """Updates the settings from a codereview.settings file, if available.""" |
| 780 | if not self.updated: |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 781 | # The only value that actually changes the behavior is |
| 782 | # autoupdate = "false". Everything else means "true". |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 783 | autoupdate = RunGit(['config', 'rietveld.autoupdate'], |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 784 | error_ok=True |
| 785 | ).strip().lower() |
| 786 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 787 | cr_settings_file = FindCodereviewSettingsFile() |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 788 | if autoupdate != 'false' and cr_settings_file: |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 789 | LoadCodereviewSettingsFromFile(cr_settings_file) |
| 790 | self.updated = True |
| 791 | |
| 792 | def GetDefaultServerUrl(self, error_ok=False): |
| 793 | if not self.default_server: |
| 794 | self.LazyUpdateIfNeeded() |
maruel@chromium.org | eb5edbc | 2012-01-16 17:03:28 +0000 | [diff] [blame] | 795 | self.default_server = gclient_utils.UpgradeToHttps( |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 796 | self._GetRietveldConfig('server', error_ok=True)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 797 | if error_ok: |
| 798 | return self.default_server |
| 799 | if not self.default_server: |
| 800 | error_message = ('Could not find settings file. You must configure ' |
| 801 | 'your review setup by running "git cl config".') |
maruel@chromium.org | eb5edbc | 2012-01-16 17:03:28 +0000 | [diff] [blame] | 802 | self.default_server = gclient_utils.UpgradeToHttps( |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 803 | self._GetRietveldConfig('server', error_message=error_message)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 804 | return self.default_server |
| 805 | |
thestig@chromium.org | 7a54e81 | 2014-02-11 19:57:22 +0000 | [diff] [blame] | 806 | @staticmethod |
| 807 | def GetRelativeRoot(): |
| 808 | return RunGit(['rev-parse', '--show-cdup']).strip() |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 809 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 810 | def GetRoot(self): |
thestig@chromium.org | 7a54e81 | 2014-02-11 19:57:22 +0000 | [diff] [blame] | 811 | if self.root is None: |
| 812 | self.root = os.path.abspath(self.GetRelativeRoot()) |
| 813 | return self.root |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 814 | |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 815 | def GetGitMirror(self, remote='origin'): |
| 816 | """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] | 817 | local_url = RunGit(['config', '--get', 'remote.%s.url' % remote]).strip() |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 818 | if not os.path.isdir(local_url): |
| 819 | return None |
| 820 | git_cache.Mirror.SetCachePath(os.path.dirname(local_url)) |
| 821 | remote_url = git_cache.Mirror.CacheDirToUrl(local_url) |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 822 | # Use the /dev/null print_func to avoid terminal spew. |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 823 | mirror = git_cache.Mirror(remote_url, print_func=lambda *args: None) |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 824 | if mirror.exists(): |
| 825 | return mirror |
| 826 | return None |
| 827 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 828 | def GetTreeStatusUrl(self, error_ok=False): |
| 829 | if not self.tree_status_url: |
| 830 | error_message = ('You must configure your tree status URL by running ' |
| 831 | '"git cl config".') |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 832 | self.tree_status_url = self._GetRietveldConfig( |
| 833 | 'tree-status-url', error_ok=error_ok, error_message=error_message) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 834 | return self.tree_status_url |
| 835 | |
| 836 | def GetViewVCUrl(self): |
| 837 | if not self.viewvc_url: |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 838 | self.viewvc_url = self._GetRietveldConfig('viewvc-url', error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 839 | return self.viewvc_url |
| 840 | |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 841 | def GetBugPrefix(self): |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 842 | return self._GetRietveldConfig('bug-prefix', error_ok=True) |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 843 | |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 844 | def GetIsSkipDependencyUpload(self, branch_name): |
| 845 | """Returns true if specified branch should skip dep uploads.""" |
| 846 | return self._GetBranchConfig(branch_name, 'skip-deps-uploads', |
| 847 | error_ok=True) |
| 848 | |
rmistry@google.com | 5626a92 | 2015-02-26 14:03:30 +0000 | [diff] [blame] | 849 | def GetRunPostUploadHook(self): |
| 850 | run_post_upload_hook = self._GetRietveldConfig( |
| 851 | 'run-post-upload-hook', error_ok=True) |
| 852 | return run_post_upload_hook == "True" |
| 853 | |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 854 | def GetDefaultCCList(self): |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 855 | return self._GetRietveldConfig('cc', error_ok=True) |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 856 | |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 857 | def GetDefaultPrivateFlag(self): |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 858 | return self._GetRietveldConfig('private', error_ok=True) |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 859 | |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 860 | def GetIsGerrit(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 861 | """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] | 862 | if self.is_gerrit is None: |
Aaron Gable | 9b46527 | 2017-05-12 10:53:51 -0700 | [diff] [blame] | 863 | self.is_gerrit = ( |
| 864 | self._GetConfig('gerrit.host', error_ok=True).lower() == 'true') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 865 | return self.is_gerrit |
| 866 | |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 867 | def GetSquashGerritUploads(self): |
| 868 | """Return true if uploads to Gerrit should be squashed by default.""" |
| 869 | if self.squash_gerrit_uploads is None: |
tandrii | a60502f | 2016-06-20 02:01:53 -0700 | [diff] [blame] | 870 | self.squash_gerrit_uploads = self.GetSquashGerritUploadsOverride() |
| 871 | if self.squash_gerrit_uploads is None: |
| 872 | # Default is squash now (http://crbug.com/611892#c23). |
| 873 | self.squash_gerrit_uploads = not ( |
| 874 | RunGit(['config', '--bool', 'gerrit.squash-uploads'], |
| 875 | error_ok=True).strip() == 'false') |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 876 | return self.squash_gerrit_uploads |
| 877 | |
tandrii | a60502f | 2016-06-20 02:01:53 -0700 | [diff] [blame] | 878 | def GetSquashGerritUploadsOverride(self): |
| 879 | """Return True or False if codereview.settings should be overridden. |
| 880 | |
| 881 | Returns None if no override has been defined. |
| 882 | """ |
| 883 | # See also http://crbug.com/611892#c23 |
| 884 | result = RunGit(['config', '--bool', 'gerrit.override-squash-uploads'], |
| 885 | error_ok=True).strip() |
| 886 | if result == 'true': |
| 887 | return True |
| 888 | if result == 'false': |
| 889 | return False |
| 890 | return None |
| 891 | |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 892 | def GetGerritSkipEnsureAuthenticated(self): |
| 893 | """Return True if EnsureAuthenticated should not be done for Gerrit |
| 894 | uploads.""" |
| 895 | if self.gerrit_skip_ensure_authenticated is None: |
| 896 | self.gerrit_skip_ensure_authenticated = ( |
shinyak@chromium.org | 00dbccd | 2016-04-15 07:24:43 +0000 | [diff] [blame] | 897 | RunGit(['config', '--bool', 'gerrit.skip-ensure-authenticated'], |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 898 | error_ok=True).strip() == 'true') |
| 899 | return self.gerrit_skip_ensure_authenticated |
| 900 | |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 901 | def GetGitEditor(self): |
| 902 | """Return the editor specified in the git config, or None if none is.""" |
| 903 | if self.git_editor is None: |
| 904 | self.git_editor = self._GetConfig('core.editor', error_ok=True) |
| 905 | return self.git_editor or None |
| 906 | |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 907 | def GetLintRegex(self): |
| 908 | return (self._GetRietveldConfig('cpplint-regex', error_ok=True) or |
| 909 | DEFAULT_LINT_REGEX) |
| 910 | |
| 911 | def GetLintIgnoreRegex(self): |
| 912 | return (self._GetRietveldConfig('cpplint-ignore-regex', error_ok=True) or |
| 913 | DEFAULT_LINT_IGNORE_REGEX) |
| 914 | |
sheyang@chromium.org | 152cf83 | 2014-06-11 21:37:49 +0000 | [diff] [blame] | 915 | def GetProject(self): |
| 916 | if not self.project: |
| 917 | self.project = self._GetRietveldConfig('project', error_ok=True) |
| 918 | return self.project |
| 919 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 920 | def _GetRietveldConfig(self, param, **kwargs): |
| 921 | return self._GetConfig('rietveld.' + param, **kwargs) |
| 922 | |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 923 | def _GetBranchConfig(self, branch_name, param, **kwargs): |
| 924 | return self._GetConfig('branch.' + branch_name + '.' + param, **kwargs) |
| 925 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 926 | def _GetConfig(self, param, **kwargs): |
| 927 | self.LazyUpdateIfNeeded() |
| 928 | return RunGit(['config', param], **kwargs).strip() |
| 929 | |
| 930 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 931 | @contextlib.contextmanager |
| 932 | def _get_gerrit_project_config_file(remote_url): |
| 933 | """Context manager to fetch and store Gerrit's project.config from |
| 934 | refs/meta/config branch and store it in temp file. |
| 935 | |
| 936 | Provides a temporary filename or None if there was error. |
| 937 | """ |
| 938 | error, _ = RunGitWithCode([ |
| 939 | 'fetch', remote_url, |
| 940 | '+refs/meta/config:refs/git_cl/meta/config']) |
| 941 | if error: |
| 942 | # Ref doesn't exist or isn't accessible to current user. |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 943 | print('WARNING: Failed to fetch project config for %s: %s' % |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 944 | (remote_url, error)) |
| 945 | yield None |
| 946 | return |
| 947 | |
| 948 | error, project_config_data = RunGitWithCode( |
| 949 | ['show', 'refs/git_cl/meta/config:project.config']) |
| 950 | if error: |
| 951 | print('WARNING: project.config file not found') |
| 952 | yield None |
| 953 | return |
| 954 | |
| 955 | with gclient_utils.temporary_directory() as tempdir: |
| 956 | project_config_file = os.path.join(tempdir, 'project.config') |
| 957 | gclient_utils.FileWrite(project_config_file, project_config_data) |
| 958 | yield project_config_file |
| 959 | |
| 960 | |
| 961 | def _is_git_numberer_enabled(remote_url, remote_ref): |
| 962 | """Returns True if Git Numberer is enabled on this ref.""" |
| 963 | # TODO(tandrii): this should be deleted once repos below are 100% on Gerrit. |
Andrii Shyshkalov | cd6a936 | 2016-12-07 12:04:12 +0100 | [diff] [blame] | 964 | KNOWN_PROJECTS_WHITELIST = [ |
| 965 | 'chromium/src', |
| 966 | 'external/webrtc', |
| 967 | 'v8/v8', |
Andrii Shyshkalov | aa31b97 | 2017-03-24 16:16:33 +0100 | [diff] [blame] | 968 | 'infra/experimental', |
Andrii Shyshkalov | cd6a936 | 2016-12-07 12:04:12 +0100 | [diff] [blame] | 969 | ] |
| 970 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 971 | assert remote_ref and remote_ref.startswith('refs/'), remote_ref |
| 972 | url_parts = urlparse.urlparse(remote_url) |
| 973 | project_name = url_parts.path.lstrip('/').rstrip('git./') |
| 974 | for known in KNOWN_PROJECTS_WHITELIST: |
| 975 | if project_name.endswith(known): |
| 976 | break |
| 977 | else: |
| 978 | # Early exit to avoid extra fetches for repos that aren't using Git |
| 979 | # Numberer. |
| 980 | return False |
Andrii Shyshkalov | cd6a936 | 2016-12-07 12:04:12 +0100 | [diff] [blame] | 981 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 982 | with _get_gerrit_project_config_file(remote_url) as project_config_file: |
| 983 | if project_config_file is None: |
| 984 | # Failed to fetch project.config, which shouldn't happen on open source |
| 985 | # repos KNOWN_PROJECTS_WHITELIST. |
Andrii Shyshkalov | cd6a936 | 2016-12-07 12:04:12 +0100 | [diff] [blame] | 986 | return False |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 987 | def get_opts(x): |
| 988 | code, out = RunGitWithCode( |
| 989 | ['config', '-f', project_config_file, '--get-all', |
| 990 | 'plugin.git-numberer.validate-%s-refglob' % x]) |
| 991 | if code == 0: |
| 992 | return out.strip().splitlines() |
| 993 | return [] |
| 994 | enabled, disabled = map(get_opts, ['enabled', 'disabled']) |
Andrii Shyshkalov | cd6a936 | 2016-12-07 12:04:12 +0100 | [diff] [blame] | 995 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 996 | logging.info('validator config enabled %s disabled %s refglobs for ' |
| 997 | '(this ref: %s)', enabled, disabled, remote_ref) |
Andrii Shyshkalov | 351c61d | 2017-01-21 20:40:16 +0000 | [diff] [blame] | 998 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 999 | def match_refglobs(refglobs): |
Andrii Shyshkalov | cd6a936 | 2016-12-07 12:04:12 +0100 | [diff] [blame] | 1000 | for refglob in refglobs: |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 1001 | if remote_ref == refglob or fnmatch.fnmatch(remote_ref, refglob): |
Andrii Shyshkalov | cd6a936 | 2016-12-07 12:04:12 +0100 | [diff] [blame] | 1002 | return True |
| 1003 | return False |
| 1004 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 1005 | if match_refglobs(disabled): |
| 1006 | return False |
| 1007 | return match_refglobs(enabled) |
Andrii Shyshkalov | cd6a936 | 2016-12-07 12:04:12 +0100 | [diff] [blame] | 1008 | |
| 1009 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1010 | def ShortBranchName(branch): |
| 1011 | """Convert a name like 'refs/heads/foo' to just 'foo'.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1012 | return branch.replace('refs/heads/', '', 1) |
| 1013 | |
| 1014 | |
| 1015 | def GetCurrentBranchRef(): |
| 1016 | """Returns branch ref (e.g., refs/heads/master) or None.""" |
| 1017 | return RunGit(['symbolic-ref', 'HEAD'], |
| 1018 | stderr=subprocess2.VOID, error_ok=True).strip() or None |
| 1019 | |
| 1020 | |
| 1021 | def GetCurrentBranch(): |
| 1022 | """Returns current branch or None. |
| 1023 | |
| 1024 | For refs/heads/* branches, returns just last part. For others, full ref. |
| 1025 | """ |
| 1026 | branchref = GetCurrentBranchRef() |
| 1027 | if branchref: |
| 1028 | return ShortBranchName(branchref) |
| 1029 | return None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1030 | |
| 1031 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1032 | class _CQState(object): |
| 1033 | """Enum for states of CL with respect to Commit Queue.""" |
| 1034 | NONE = 'none' |
| 1035 | DRY_RUN = 'dry_run' |
| 1036 | COMMIT = 'commit' |
| 1037 | |
| 1038 | ALL_STATES = [NONE, DRY_RUN, COMMIT] |
| 1039 | |
| 1040 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1041 | class _ParsedIssueNumberArgument(object): |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 1042 | def __init__(self, issue=None, patchset=None, hostname=None, codereview=None): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1043 | self.issue = issue |
| 1044 | self.patchset = patchset |
| 1045 | self.hostname = hostname |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 1046 | assert codereview in (None, 'rietveld', 'gerrit') |
| 1047 | self.codereview = codereview |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1048 | |
| 1049 | @property |
| 1050 | def valid(self): |
| 1051 | return self.issue is not None |
| 1052 | |
| 1053 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 1054 | def ParseIssueNumberArgument(arg, codereview=None): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1055 | """Parses the issue argument and returns _ParsedIssueNumberArgument.""" |
| 1056 | fail_result = _ParsedIssueNumberArgument() |
| 1057 | |
| 1058 | if arg.isdigit(): |
Aaron Gable | aee6c85 | 2017-06-26 12:49:01 -0700 | [diff] [blame] | 1059 | return _ParsedIssueNumberArgument(issue=int(arg), codereview=codereview) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1060 | if not arg.startswith('http'): |
| 1061 | return fail_result |
Aaron Gable | aee6c85 | 2017-06-26 12:49:01 -0700 | [diff] [blame] | 1062 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1063 | url = gclient_utils.UpgradeToHttps(arg) |
| 1064 | try: |
| 1065 | parsed_url = urlparse.urlparse(url) |
| 1066 | except ValueError: |
| 1067 | return fail_result |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 1068 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 1069 | if codereview is not None: |
| 1070 | parsed = _CODEREVIEW_IMPLEMENTATIONS[codereview].ParseIssueURL(parsed_url) |
| 1071 | return parsed or fail_result |
| 1072 | |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 1073 | results = {} |
| 1074 | for name, cls in _CODEREVIEW_IMPLEMENTATIONS.iteritems(): |
| 1075 | parsed = cls.ParseIssueURL(parsed_url) |
| 1076 | if parsed is not None: |
| 1077 | results[name] = parsed |
| 1078 | |
| 1079 | if not results: |
| 1080 | return fail_result |
| 1081 | if len(results) == 1: |
| 1082 | return results.values()[0] |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 1083 | |
| 1084 | if parsed_url.netloc and parsed_url.netloc.split('.')[0].endswith('-review'): |
| 1085 | # This is likely Gerrit. |
| 1086 | return results['gerrit'] |
| 1087 | # Choose Rietveld as before if URL can parsed by either. |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 1088 | return results['rietveld'] |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1089 | |
| 1090 | |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 1091 | class GerritChangeNotExists(Exception): |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 1092 | def __init__(self, issue, url): |
| 1093 | self.issue = issue |
| 1094 | self.url = url |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 1095 | super(GerritChangeNotExists, self).__init__() |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 1096 | |
| 1097 | def __str__(self): |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 1098 | 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] | 1099 | self.issue, self.url) |
| 1100 | |
| 1101 | |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1102 | _CommentSummary = collections.namedtuple( |
| 1103 | '_CommentSummary', ['date', 'message', 'sender', |
| 1104 | # TODO(tandrii): these two aren't known in Gerrit. |
| 1105 | 'approval', 'disapproval']) |
| 1106 | |
| 1107 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1108 | class Changelist(object): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1109 | """Changelist works with one changelist in local branch. |
| 1110 | |
| 1111 | Supports two codereview backends: Rietveld or Gerrit, selected at object |
| 1112 | creation. |
| 1113 | |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 1114 | Notes: |
| 1115 | * Not safe for concurrent multi-{thread,process} use. |
| 1116 | * Caches values from current branch. Therefore, re-use after branch change |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1117 | with great care. |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1118 | """ |
| 1119 | |
| 1120 | def __init__(self, branchref=None, issue=None, codereview=None, **kwargs): |
| 1121 | """Create a new ChangeList instance. |
| 1122 | |
| 1123 | If issue is given, the codereview must be given too. |
| 1124 | |
| 1125 | If `codereview` is given, it must be 'rietveld' or 'gerrit'. |
| 1126 | Otherwise, it's decided based on current configuration of the local branch, |
| 1127 | with default being 'rietveld' for backwards compatibility. |
| 1128 | See _load_codereview_impl for more details. |
| 1129 | |
| 1130 | **kwargs will be passed directly to codereview implementation. |
| 1131 | """ |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1132 | # 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] | 1133 | global settings |
| 1134 | if not settings: |
| 1135 | # Happens when git_cl.py is used as a utility library. |
| 1136 | settings = Settings() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1137 | |
| 1138 | if issue: |
| 1139 | assert codereview, 'codereview must be known, if issue is known' |
| 1140 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1141 | self.branchref = branchref |
| 1142 | if self.branchref: |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 1143 | assert branchref.startswith('refs/heads/') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1144 | self.branch = ShortBranchName(self.branchref) |
| 1145 | else: |
| 1146 | self.branch = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1147 | self.upstream_branch = None |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1148 | self.lookedup_issue = False |
| 1149 | self.issue = issue or None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1150 | self.has_description = False |
| 1151 | self.description = None |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1152 | self.lookedup_patchset = False |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1153 | self.patchset = None |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1154 | self.cc = None |
| 1155 | self.watchers = () |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 1156 | self._remote = None |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 1157 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1158 | self._codereview_impl = None |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 1159 | self._codereview = None |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1160 | self._load_codereview_impl(codereview, **kwargs) |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 1161 | assert self._codereview_impl |
| 1162 | assert self._codereview in _CODEREVIEW_IMPLEMENTATIONS |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1163 | |
| 1164 | def _load_codereview_impl(self, codereview=None, **kwargs): |
| 1165 | if codereview: |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 1166 | assert codereview in _CODEREVIEW_IMPLEMENTATIONS |
| 1167 | cls = _CODEREVIEW_IMPLEMENTATIONS[codereview] |
| 1168 | self._codereview = codereview |
| 1169 | self._codereview_impl = cls(self, **kwargs) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1170 | return |
| 1171 | |
| 1172 | # Automatic selection based on issue number set for a current branch. |
| 1173 | # Rietveld takes precedence over Gerrit. |
| 1174 | assert not self.issue |
| 1175 | # Whether we find issue or not, we are doing the lookup. |
| 1176 | self.lookedup_issue = True |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1177 | if self.GetBranch(): |
| 1178 | for codereview, cls in _CODEREVIEW_IMPLEMENTATIONS.iteritems(): |
| 1179 | issue = _git_get_branch_config_value( |
| 1180 | cls.IssueConfigKey(), value_type=int, branch=self.GetBranch()) |
| 1181 | if issue: |
| 1182 | self._codereview = codereview |
| 1183 | self._codereview_impl = cls(self, **kwargs) |
| 1184 | self.issue = int(issue) |
| 1185 | return |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1186 | |
| 1187 | # No issue is set for this branch, so decide based on repo-wide settings. |
| 1188 | return self._load_codereview_impl( |
| 1189 | codereview='gerrit' if settings.GetIsGerrit() else 'rietveld', |
| 1190 | **kwargs) |
| 1191 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 1192 | def IsGerrit(self): |
| 1193 | return self._codereview == 'gerrit' |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1194 | |
| 1195 | def GetCCList(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1196 | """Returns the users cc'd on this CL. |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1197 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1198 | The return value is a string suitable for passing to git cl with the --cc |
| 1199 | flag. |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1200 | """ |
| 1201 | if self.cc is None: |
tyoshino@chromium.org | 99918ab | 2013-09-30 06:17:28 +0000 | [diff] [blame] | 1202 | base_cc = settings.GetDefaultCCList() |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1203 | more_cc = ','.join(self.watchers) |
| 1204 | self.cc = ','.join(filter(None, (base_cc, more_cc))) or '' |
| 1205 | return self.cc |
| 1206 | |
tyoshino@chromium.org | 99918ab | 2013-09-30 06:17:28 +0000 | [diff] [blame] | 1207 | def GetCCListWithoutDefault(self): |
| 1208 | """Return the users cc'd on this CL excluding default ones.""" |
| 1209 | if self.cc is None: |
| 1210 | self.cc = ','.join(self.watchers) |
| 1211 | return self.cc |
| 1212 | |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1213 | def SetWatchers(self, watchers): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1214 | """Sets the list of email addresses that should be cc'd based on the changed |
| 1215 | files in this CL. |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1216 | """ |
| 1217 | self.watchers = watchers |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1218 | |
| 1219 | def GetBranch(self): |
| 1220 | """Returns the short branch name, e.g. 'master'.""" |
| 1221 | if not self.branch: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1222 | branchref = GetCurrentBranchRef() |
szager@chromium.org | d62c61f | 2014-10-20 22:33:21 +0000 | [diff] [blame] | 1223 | if not branchref: |
| 1224 | return None |
| 1225 | self.branchref = branchref |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1226 | self.branch = ShortBranchName(self.branchref) |
| 1227 | return self.branch |
| 1228 | |
| 1229 | def GetBranchRef(self): |
| 1230 | """Returns the full branch name, e.g. 'refs/heads/master'.""" |
| 1231 | self.GetBranch() # Poke the lazy loader. |
| 1232 | return self.branchref |
| 1233 | |
tandrii@chromium.org | 534f67a | 2016-04-07 18:47:05 +0000 | [diff] [blame] | 1234 | def ClearBranch(self): |
| 1235 | """Clears cached branch data of this object.""" |
| 1236 | self.branch = self.branchref = None |
| 1237 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1238 | def _GitGetBranchConfigValue(self, key, default=None, **kwargs): |
| 1239 | assert 'branch' not in kwargs, 'this CL branch is used automatically' |
| 1240 | kwargs['branch'] = self.GetBranch() |
| 1241 | return _git_get_branch_config_value(key, default, **kwargs) |
| 1242 | |
| 1243 | def _GitSetBranchConfigValue(self, key, value, **kwargs): |
| 1244 | assert 'branch' not in kwargs, 'this CL branch is used automatically' |
| 1245 | assert self.GetBranch(), ( |
| 1246 | 'this CL must have an associated branch to %sset %s%s' % |
| 1247 | ('un' if value is None else '', |
| 1248 | key, |
| 1249 | '' if value is None else ' to %r' % value)) |
| 1250 | kwargs['branch'] = self.GetBranch() |
| 1251 | return _git_set_branch_config_value(key, value, **kwargs) |
| 1252 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1253 | @staticmethod |
| 1254 | def FetchUpstreamTuple(branch): |
pgervais@chromium.org | d6617f3 | 2013-11-19 00:34:54 +0000 | [diff] [blame] | 1255 | """Returns a tuple containing remote and remote ref, |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1256 | e.g. 'origin', 'refs/heads/master' |
| 1257 | """ |
| 1258 | remote = '.' |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1259 | upstream_branch = _git_get_branch_config_value('merge', branch=branch) |
| 1260 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1261 | if upstream_branch: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1262 | remote = _git_get_branch_config_value('remote', branch=branch) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1263 | else: |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 1264 | upstream_branch = RunGit(['config', 'rietveld.upstream-branch'], |
| 1265 | error_ok=True).strip() |
| 1266 | if upstream_branch: |
| 1267 | remote = RunGit(['config', 'rietveld.upstream-remote']).strip() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1268 | else: |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 1269 | # Else, try to guess the origin remote. |
| 1270 | remote_branches = RunGit(['branch', '-r']).split() |
| 1271 | if 'origin/master' in remote_branches: |
| 1272 | # Fall back on origin/master if it exits. |
| 1273 | remote = 'origin' |
| 1274 | upstream_branch = 'refs/heads/master' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1275 | else: |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 1276 | DieWithError( |
| 1277 | 'Unable to determine default branch to diff against.\n' |
| 1278 | 'Either pass complete "git diff"-style arguments, like\n' |
| 1279 | ' git cl upload origin/master\n' |
| 1280 | 'or verify this branch is set up to track another \n' |
| 1281 | '(via the --track argument to "git checkout -b ...").') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1282 | |
| 1283 | return remote, upstream_branch |
| 1284 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1285 | def GetCommonAncestorWithUpstream(self): |
pgervais@chromium.org | 8ba38ff | 2015-06-11 21:41:25 +0000 | [diff] [blame] | 1286 | upstream_branch = self.GetUpstreamBranch() |
| 1287 | if not BranchExists(upstream_branch): |
| 1288 | DieWithError('The upstream for the current branch (%s) does not exist ' |
| 1289 | 'anymore.\nPlease fix it and try again.' % self.GetBranch()) |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 1290 | return git_common.get_or_create_merge_base(self.GetBranch(), |
pgervais@chromium.org | 8ba38ff | 2015-06-11 21:41:25 +0000 | [diff] [blame] | 1291 | upstream_branch) |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1292 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1293 | def GetUpstreamBranch(self): |
| 1294 | if self.upstream_branch is None: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1295 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1296 | if remote is not '.': |
mmoss@chromium.org | e758545 | 2014-08-24 01:41:11 +0000 | [diff] [blame] | 1297 | upstream_branch = upstream_branch.replace('refs/heads/', |
| 1298 | 'refs/remotes/%s/' % remote) |
| 1299 | upstream_branch = upstream_branch.replace('refs/branch-heads/', |
| 1300 | 'refs/remotes/branch-heads/') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1301 | self.upstream_branch = upstream_branch |
| 1302 | return self.upstream_branch |
| 1303 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1304 | def GetRemoteBranch(self): |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1305 | if not self._remote: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1306 | remote, branch = None, self.GetBranch() |
| 1307 | seen_branches = set() |
| 1308 | while branch not in seen_branches: |
| 1309 | seen_branches.add(branch) |
| 1310 | remote, branch = self.FetchUpstreamTuple(branch) |
| 1311 | branch = ShortBranchName(branch) |
| 1312 | if remote != '.' or branch.startswith('refs/remotes'): |
| 1313 | break |
| 1314 | else: |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1315 | remotes = RunGit(['remote'], error_ok=True).split() |
| 1316 | if len(remotes) == 1: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1317 | remote, = remotes |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1318 | elif 'origin' in remotes: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1319 | remote = 'origin' |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 1320 | logging.warn('Could not determine which remote this change is ' |
| 1321 | 'associated with, so defaulting to "%s".' % self._remote) |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1322 | else: |
| 1323 | logging.warn('Could not determine which remote this change is ' |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 1324 | 'associated with.') |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1325 | branch = 'HEAD' |
| 1326 | if branch.startswith('refs/remotes'): |
| 1327 | self._remote = (remote, branch) |
mmoss@chromium.org | e758545 | 2014-08-24 01:41:11 +0000 | [diff] [blame] | 1328 | elif branch.startswith('refs/branch-heads/'): |
| 1329 | self._remote = (remote, branch.replace('refs/', 'refs/remotes/')) |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1330 | else: |
| 1331 | self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch)) |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1332 | return self._remote |
| 1333 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1334 | def GitSanityChecks(self, upstream_git_obj): |
| 1335 | """Checks git repo status and ensures diff is from local commits.""" |
| 1336 | |
sbc@chromium.org | 7970606 | 2015-01-14 21:18:12 +0000 | [diff] [blame] | 1337 | if upstream_git_obj is None: |
| 1338 | if self.GetBranch() is None: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1339 | print('ERROR: Unable to determine current branch (detached HEAD?)', |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1340 | file=sys.stderr) |
sbc@chromium.org | 7970606 | 2015-01-14 21:18:12 +0000 | [diff] [blame] | 1341 | else: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1342 | print('ERROR: No upstream branch.', file=sys.stderr) |
sbc@chromium.org | 7970606 | 2015-01-14 21:18:12 +0000 | [diff] [blame] | 1343 | return False |
| 1344 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1345 | # Verify the commit we're diffing against is in our current branch. |
| 1346 | upstream_sha = RunGit(['rev-parse', '--verify', upstream_git_obj]).strip() |
| 1347 | common_ancestor = RunGit(['merge-base', upstream_sha, 'HEAD']).strip() |
| 1348 | if upstream_sha != common_ancestor: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1349 | print('ERROR: %s is not in the current branch. You may need to rebase ' |
| 1350 | 'your tracking branch' % upstream_sha, file=sys.stderr) |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1351 | return False |
| 1352 | |
| 1353 | # List the commits inside the diff, and verify they are all local. |
| 1354 | commits_in_diff = RunGit( |
| 1355 | ['rev-list', '^%s' % upstream_sha, 'HEAD']).splitlines() |
| 1356 | code, remote_branch = RunGitWithCode(['config', 'gitcl.remotebranch']) |
| 1357 | remote_branch = remote_branch.strip() |
| 1358 | if code != 0: |
| 1359 | _, remote_branch = self.GetRemoteBranch() |
| 1360 | |
| 1361 | commits_in_remote = RunGit( |
| 1362 | ['rev-list', '^%s' % upstream_sha, remote_branch]).splitlines() |
| 1363 | |
| 1364 | common_commits = set(commits_in_diff) & set(commits_in_remote) |
| 1365 | if common_commits: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1366 | print('ERROR: Your diff contains %d commits already in %s.\n' |
| 1367 | 'Run "git log --oneline %s..HEAD" to get a list of commits in ' |
| 1368 | 'the diff. If you are using a custom git flow, you can override' |
| 1369 | ' the reference used for this check with "git config ' |
| 1370 | 'gitcl.remotebranch <git-ref>".' % ( |
| 1371 | len(common_commits), remote_branch, upstream_git_obj), |
| 1372 | file=sys.stderr) |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1373 | return False |
| 1374 | return True |
| 1375 | |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 1376 | def GetGitBaseUrlFromConfig(self): |
sheyang@chromium.org | a656e70 | 2014-05-15 20:43:05 +0000 | [diff] [blame] | 1377 | """Return the configured base URL from branch.<branchname>.baseurl. |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 1378 | |
| 1379 | Returns None if it is not set. |
| 1380 | """ |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1381 | return self._GitGetBranchConfigValue('base-url') |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1382 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1383 | def GetRemoteUrl(self): |
| 1384 | """Return the configured remote URL, e.g. 'git://example.org/foo.git/'. |
| 1385 | |
| 1386 | Returns None if there is no remote. |
| 1387 | """ |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1388 | remote, _ = self.GetRemoteBranch() |
dyen@chromium.org | 2a13d4f | 2014-06-13 00:06:37 +0000 | [diff] [blame] | 1389 | url = RunGit(['config', 'remote.%s.url' % remote], error_ok=True).strip() |
| 1390 | |
| 1391 | # If URL is pointing to a local directory, it is probably a git cache. |
| 1392 | if os.path.isdir(url): |
| 1393 | url = RunGit(['config', 'remote.%s.url' % remote], |
| 1394 | error_ok=True, |
| 1395 | cwd=url).strip() |
| 1396 | return url |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1397 | |
tandrii@chromium.org | 87985d2 | 2016-03-24 17:33:33 +0000 | [diff] [blame] | 1398 | def GetIssue(self): |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1399 | """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] | 1400 | if self.issue is None and not self.lookedup_issue: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1401 | self.issue = self._GitGetBranchConfigValue( |
| 1402 | self._codereview_impl.IssueConfigKey(), value_type=int) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1403 | self.lookedup_issue = True |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1404 | return self.issue |
| 1405 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1406 | def GetIssueURL(self): |
| 1407 | """Get the URL for a particular issue.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1408 | issue = self.GetIssue() |
| 1409 | if not issue: |
dbeam@chromium.org | 015fd3d | 2013-06-18 19:02:50 +0000 | [diff] [blame] | 1410 | return None |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1411 | return '%s/%s' % (self._codereview_impl.GetCodereviewServer(), issue) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1412 | |
Andrii Shyshkalov | 3186301 | 2017-02-08 11:35:12 +0100 | [diff] [blame] | 1413 | def GetDescription(self, pretty=False, force=False): |
| 1414 | if not self.has_description or force: |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1415 | if self.GetIssue(): |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 1416 | self.description = self._codereview_impl.FetchDescription(force=force) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1417 | self.has_description = True |
| 1418 | if pretty: |
Asanka Herath | 7c61dcb | 2016-12-14 13:01:58 -0500 | [diff] [blame] | 1419 | # Set width to 72 columns + 2 space indent. |
| 1420 | wrapper = textwrap.TextWrapper(width=74, replace_whitespace=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1421 | wrapper.initial_indent = wrapper.subsequent_indent = ' ' |
Asanka Herath | 7c61dcb | 2016-12-14 13:01:58 -0500 | [diff] [blame] | 1422 | lines = self.description.splitlines() |
| 1423 | return '\n'.join([wrapper.fill(line) for line in lines]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1424 | return self.description |
| 1425 | |
Robert Iannucci | 09f1f3d | 2017-03-28 16:54:32 -0700 | [diff] [blame] | 1426 | def GetDescriptionFooters(self): |
| 1427 | """Returns (non_footer_lines, footers) for the commit message. |
| 1428 | |
| 1429 | Returns: |
| 1430 | non_footer_lines (list(str)) - Simple list of description lines without |
| 1431 | any footer. The lines do not contain newlines, nor does the list contain |
| 1432 | the empty line between the message and the footers. |
| 1433 | footers (list(tuple(KEY, VALUE))) - List of parsed footers, e.g. |
| 1434 | [("Change-Id", "Ideadbeef...."), ...] |
| 1435 | """ |
| 1436 | raw_description = self.GetDescription() |
| 1437 | msg_lines, _, footers = git_footers.split_footers(raw_description) |
| 1438 | if footers: |
| 1439 | msg_lines = msg_lines[:len(msg_lines)-1] |
| 1440 | return msg_lines, footers |
| 1441 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1442 | def GetPatchset(self): |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1443 | """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] | 1444 | if self.patchset is None and not self.lookedup_patchset: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1445 | self.patchset = self._GitGetBranchConfigValue( |
| 1446 | self._codereview_impl.PatchsetConfigKey(), value_type=int) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1447 | self.lookedup_patchset = True |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1448 | return self.patchset |
| 1449 | |
| 1450 | def SetPatchset(self, patchset): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1451 | """Set this branch's patchset. If patchset=0, clears the patchset.""" |
| 1452 | assert self.GetBranch() |
| 1453 | if not patchset: |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1454 | self.patchset = None |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1455 | else: |
| 1456 | self.patchset = int(patchset) |
| 1457 | self._GitSetBranchConfigValue( |
| 1458 | self._codereview_impl.PatchsetConfigKey(), self.patchset) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1459 | |
tandrii@chromium.org | a342c92 | 2016-03-16 07:08:25 +0000 | [diff] [blame] | 1460 | def SetIssue(self, issue=None): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1461 | """Set this branch's issue. If issue isn't given, clears the issue.""" |
| 1462 | assert self.GetBranch() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1463 | if issue: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1464 | issue = int(issue) |
| 1465 | self._GitSetBranchConfigValue( |
| 1466 | self._codereview_impl.IssueConfigKey(), issue) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1467 | self.issue = issue |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1468 | codereview_server = self._codereview_impl.GetCodereviewServer() |
| 1469 | if codereview_server: |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1470 | self._GitSetBranchConfigValue( |
| 1471 | self._codereview_impl.CodereviewServerConfigKey(), |
| 1472 | codereview_server) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1473 | else: |
Aaron Gable | 400e989 | 2017-07-12 15:31:21 -0700 | [diff] [blame] | 1474 | desc = self.GetDescription() |
Aaron Gable | 4e5207d | 2017-07-13 10:07:39 -0700 | [diff] [blame] | 1475 | if desc and git_footers.get_footer_change_id(desc): |
Aaron Gable | 400e989 | 2017-07-12 15:31:21 -0700 | [diff] [blame] | 1476 | print('WARNING: The change patched into this branch has a Change-Id. ' |
| 1477 | 'Removing it.') |
| 1478 | RunGit(['commit', '--amend', '-m', |
| 1479 | git_footers.remove_footer(desc, 'Change-Id')]) |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1480 | # Reset all of these just to be clean. |
| 1481 | reset_suffixes = [ |
| 1482 | 'last-upload-hash', |
| 1483 | self._codereview_impl.IssueConfigKey(), |
| 1484 | self._codereview_impl.PatchsetConfigKey(), |
| 1485 | self._codereview_impl.CodereviewServerConfigKey(), |
| 1486 | ] + self._PostUnsetIssueProperties() |
| 1487 | for prop in reset_suffixes: |
| 1488 | self._GitSetBranchConfigValue(prop, None, error_ok=True) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1489 | self.issue = None |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 1490 | self.patchset = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1491 | |
dnj | ba1b0f3 | 2016-09-02 12:37:42 -0700 | [diff] [blame] | 1492 | def GetChange(self, upstream_branch, author, local_description=False): |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1493 | if not self.GitSanityChecks(upstream_branch): |
| 1494 | DieWithError('\nGit sanity check failure') |
| 1495 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1496 | root = settings.GetRelativeRoot() |
bratell@opera.com | f267b0e | 2013-05-02 09:11:43 +0000 | [diff] [blame] | 1497 | if not root: |
| 1498 | root = '.' |
bauerb@chromium.org | 512f1ef | 2011-04-20 15:17:57 +0000 | [diff] [blame] | 1499 | absroot = os.path.abspath(root) |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1500 | |
| 1501 | # 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] | 1502 | name = RunGitWithCode(['rev-parse', 'HEAD'])[1].strip() |
bauerb@chromium.org | 512f1ef | 2011-04-20 15:17:57 +0000 | [diff] [blame] | 1503 | # Need to pass a relative path for msysgit. |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1504 | try: |
maruel@chromium.org | 80a9ef1 | 2011-12-13 20:44:10 +0000 | [diff] [blame] | 1505 | files = scm.GIT.CaptureStatus([root], '.', upstream_branch) |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1506 | except subprocess2.CalledProcessError: |
| 1507 | DieWithError( |
pgervais@chromium.org | d6617f3 | 2013-11-19 00:34:54 +0000 | [diff] [blame] | 1508 | ('\nFailed to diff against upstream branch %s\n\n' |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1509 | 'This branch probably doesn\'t exist anymore. To reset the\n' |
| 1510 | 'tracking branch, please run\n' |
stip | 7a3dd35 | 2016-09-22 17:32:28 -0700 | [diff] [blame] | 1511 | ' git branch --set-upstream-to origin/master %s\n' |
| 1512 | 'or replace origin/master with the relevant branch') % |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1513 | (upstream_branch, self.GetBranch())) |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1514 | |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1515 | issue = self.GetIssue() |
| 1516 | patchset = self.GetPatchset() |
dnj | ba1b0f3 | 2016-09-02 12:37:42 -0700 | [diff] [blame] | 1517 | if issue and not local_description: |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1518 | description = self.GetDescription() |
| 1519 | else: |
| 1520 | # If the change was never uploaded, use the log messages of all commits |
| 1521 | # up to the branch point, as git cl upload will prefill the description |
| 1522 | # with these log messages. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1523 | args = ['log', '--pretty=format:%s%n%n%b', '%s...' % (upstream_branch)] |
| 1524 | description = RunGitWithCode(args)[1].strip() |
maruel@chromium.org | 03b3bdc | 2011-06-14 13:04:12 +0000 | [diff] [blame] | 1525 | |
| 1526 | if not author: |
maruel@chromium.org | 13f623c | 2011-07-22 16:02:23 +0000 | [diff] [blame] | 1527 | author = RunGit(['config', 'user.email']).strip() or None |
asvitkine@chromium.org | 1516995 | 2011-09-27 14:30:53 +0000 | [diff] [blame] | 1528 | return presubmit_support.GitChange( |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1529 | name, |
| 1530 | description, |
| 1531 | absroot, |
| 1532 | files, |
| 1533 | issue, |
| 1534 | patchset, |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 1535 | author, |
| 1536 | upstream=upstream_branch) |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1537 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 1538 | def UpdateDescription(self, description, force=False): |
Andrii Shyshkalov | 8305115 | 2017-02-07 23:47:29 +0100 | [diff] [blame] | 1539 | self._codereview_impl.UpdateDescriptionRemote(description, force=force) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1540 | self.description = description |
Andrii Shyshkalov | 8305115 | 2017-02-07 23:47:29 +0100 | [diff] [blame] | 1541 | self.has_description = True |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1542 | |
Robert Iannucci | 09f1f3d | 2017-03-28 16:54:32 -0700 | [diff] [blame] | 1543 | def UpdateDescriptionFooters(self, description_lines, footers, force=False): |
| 1544 | """Sets the description for this CL remotely. |
| 1545 | |
| 1546 | You can get description_lines and footers with GetDescriptionFooters. |
| 1547 | |
| 1548 | Args: |
| 1549 | description_lines (list(str)) - List of CL description lines without |
| 1550 | newline characters. |
| 1551 | footers (list(tuple(KEY, VALUE))) - List of footers, as returned by |
| 1552 | GetDescriptionFooters. Key must conform to the git footers format (i.e. |
| 1553 | `List-Of-Tokens`). It will be case-normalized so that each token is |
| 1554 | title-cased. |
| 1555 | """ |
| 1556 | new_description = '\n'.join(description_lines) |
| 1557 | if footers: |
| 1558 | new_description += '\n' |
| 1559 | for k, v in footers: |
| 1560 | foot = '%s: %s' % (git_footers.normalize_name(k), v) |
| 1561 | if not git_footers.FOOTER_PATTERN.match(foot): |
| 1562 | raise ValueError('Invalid footer %r' % foot) |
| 1563 | new_description += foot + '\n' |
| 1564 | self.UpdateDescription(new_description, force) |
| 1565 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1566 | def RunHook(self, committing, may_prompt, verbose, change): |
| 1567 | """Calls sys.exit() if the hook fails; returns a HookResults otherwise.""" |
| 1568 | try: |
| 1569 | return presubmit_support.DoPresubmitChecks(change, committing, |
| 1570 | verbose=verbose, output_stream=sys.stdout, input_stream=sys.stdin, |
| 1571 | default_presubmit=None, may_prompt=may_prompt, |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1572 | rietveld_obj=self._codereview_impl.GetRietveldObjForPresubmit(), |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 1573 | gerrit_obj=self._codereview_impl.GetGerritObjForPresubmit()) |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 1574 | except presubmit_support.PresubmitFailure as e: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1575 | DieWithError( |
| 1576 | ('%s\nMaybe your depot_tools is out of date?\n' |
| 1577 | 'If all fails, contact maruel@') % e) |
| 1578 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1579 | def CMDPatchIssue(self, issue_arg, reject, nocommit, directory): |
| 1580 | """Fetches and applies the issue patch from codereview to local branch.""" |
tandrii@chromium.org | ef7c68c | 2016-04-07 09:39:39 +0000 | [diff] [blame] | 1581 | if isinstance(issue_arg, (int, long)) or issue_arg.isdigit(): |
| 1582 | parsed_issue_arg = _ParsedIssueNumberArgument(int(issue_arg)) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1583 | else: |
| 1584 | # Assume url. |
| 1585 | parsed_issue_arg = self._codereview_impl.ParseIssueURL( |
| 1586 | urlparse.urlparse(issue_arg)) |
| 1587 | if not parsed_issue_arg or not parsed_issue_arg.valid: |
| 1588 | DieWithError('Failed to parse issue argument "%s". ' |
| 1589 | 'Must be an issue number or a valid URL.' % issue_arg) |
| 1590 | return self._codereview_impl.CMDPatchWithParsedIssue( |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 1591 | parsed_issue_arg, reject, nocommit, directory, False) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1592 | |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1593 | def CMDUpload(self, options, git_diff_args, orig_args): |
| 1594 | """Uploads a change to codereview.""" |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 1595 | custom_cl_base = None |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1596 | if git_diff_args: |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 1597 | custom_cl_base = base_branch = git_diff_args[0] |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1598 | else: |
| 1599 | if self.GetBranch() is None: |
| 1600 | DieWithError('Can\'t upload from detached HEAD state. Get on a branch!') |
| 1601 | |
| 1602 | # Default to diffing against common ancestor of upstream branch |
| 1603 | base_branch = self.GetCommonAncestorWithUpstream() |
| 1604 | git_diff_args = [base_branch, 'HEAD'] |
| 1605 | |
Aaron Gable | c4c40d1 | 2017-05-22 11:49:53 -0700 | [diff] [blame] | 1606 | # Warn about Rietveld deprecation for initial uploads to Rietveld. |
| 1607 | if not self.IsGerrit() and not self.GetIssue(): |
| 1608 | print('=====================================') |
| 1609 | print('NOTICE: Rietveld is being deprecated. ' |
| 1610 | 'You can upload changes to Gerrit with') |
| 1611 | print(' git cl upload --gerrit') |
| 1612 | print('or set Gerrit to be your default code review tool with') |
| 1613 | print(' git config gerrit.host true') |
| 1614 | print('=====================================') |
| 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: |
| 1627 | self.SetWatchers(watchlist.GetWatchersForPaths(files)) |
| 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, |
| 1639 | may_prompt=not options.force, |
| 1640 | verbose=options.verbose, |
| 1641 | change=change) |
| 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(',') |
| 1646 | |
Ravi Mistry | fda50ca | 2016-11-14 10:19:18 -0500 | [diff] [blame] | 1647 | # TODO(tandrii): Checking local patchset against remote patchset is only |
| 1648 | # supported for Rietveld. Extend it to Gerrit or remove it completely. |
| 1649 | if self.GetIssue() and not self.IsGerrit(): |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1650 | latest_patchset = self.GetMostRecentPatchset() |
| 1651 | local_patchset = self.GetPatchset() |
| 1652 | if (latest_patchset and local_patchset and |
| 1653 | local_patchset != latest_patchset): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1654 | print('The last upload made from this repository was patchset #%d but ' |
| 1655 | 'the most recent patchset on the server is #%d.' |
| 1656 | % (local_patchset, latest_patchset)) |
| 1657 | print('Uploading will still work, but if you\'ve uploaded to this ' |
| 1658 | 'issue from another machine or branch the patch you\'re ' |
| 1659 | 'uploading now might not include those changes.') |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 1660 | confirm_or_exit(action='upload') |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1661 | |
| 1662 | print_stats(options.similarity, options.find_copies, git_diff_args) |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 1663 | ret = self.CMDUploadChange(options, git_diff_args, custom_cl_base, change) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1664 | if not ret: |
tandrii | 4d0545a | 2016-07-06 03:56:49 -0700 | [diff] [blame] | 1665 | if options.use_commit_queue: |
| 1666 | self.SetCQState(_CQState.COMMIT) |
| 1667 | elif options.cq_dry_run: |
| 1668 | self.SetCQState(_CQState.DRY_RUN) |
| 1669 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1670 | _git_set_branch_config_value('last-upload-hash', |
| 1671 | RunGit(['rev-parse', 'HEAD']).strip()) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1672 | # Run post upload hooks, if specified. |
| 1673 | if settings.GetRunPostUploadHook(): |
| 1674 | presubmit_support.DoPostUploadExecuter( |
| 1675 | change, |
| 1676 | self, |
| 1677 | settings.GetRoot(), |
| 1678 | options.verbose, |
| 1679 | sys.stdout) |
| 1680 | |
| 1681 | # Upload all dependencies if specified. |
| 1682 | if options.dependencies: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1683 | print() |
| 1684 | print('--dependencies has been specified.') |
| 1685 | print('All dependent local branches will be re-uploaded.') |
| 1686 | print() |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1687 | # Remove the dependencies flag from args so that we do not end up in a |
| 1688 | # loop. |
| 1689 | orig_args.remove('--dependencies') |
| 1690 | ret = upload_branch_deps(self, orig_args) |
| 1691 | return ret |
| 1692 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1693 | def SetCQState(self, new_state): |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 1694 | """Updates the CQ state for the latest patchset. |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1695 | |
| 1696 | Issue must have been already uploaded and known. |
| 1697 | """ |
| 1698 | assert new_state in _CQState.ALL_STATES |
| 1699 | assert self.GetIssue() |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 1700 | try: |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 1701 | self._codereview_impl.SetCQState(new_state) |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 1702 | return 0 |
| 1703 | except KeyboardInterrupt: |
| 1704 | raise |
| 1705 | except: |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 1706 | print('WARNING: Failed to %s.\n' |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 1707 | 'Either:\n' |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 1708 | ' * Your project has no CQ,\n' |
| 1709 | ' * You don\'t have permission to change the CQ state,\n' |
| 1710 | ' * There\'s a bug in this code (see stack trace below).\n' |
| 1711 | 'Consider specifying which bots to trigger manually or asking your ' |
| 1712 | 'project owners for permissions or contacting Chrome Infra at:\n' |
| 1713 | 'https://www.chromium.org/infra\n\n' % |
| 1714 | ('cancel CQ' if new_state == _CQState.NONE else 'trigger CQ')) |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 1715 | # Still raise exception so that stack trace is printed. |
| 1716 | raise |
| 1717 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1718 | # Forward methods to codereview specific implementation. |
| 1719 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 1720 | def AddComment(self, message, publish=None): |
| 1721 | return self._codereview_impl.AddComment(message, publish=publish) |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 1722 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 1723 | def GetCommentsSummary(self, readable=True): |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1724 | """Returns list of _CommentSummary for each comment. |
| 1725 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 1726 | args: |
| 1727 | 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] | 1728 | """ |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 1729 | return self._codereview_impl.GetCommentsSummary(readable) |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1730 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1731 | def CloseIssue(self): |
| 1732 | return self._codereview_impl.CloseIssue() |
| 1733 | |
| 1734 | def GetStatus(self): |
| 1735 | return self._codereview_impl.GetStatus() |
| 1736 | |
| 1737 | def GetCodereviewServer(self): |
| 1738 | return self._codereview_impl.GetCodereviewServer() |
| 1739 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1740 | def GetIssueOwner(self): |
| 1741 | """Get owner from codereview, which may differ from this checkout.""" |
| 1742 | return self._codereview_impl.GetIssueOwner() |
| 1743 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1744 | def GetMostRecentPatchset(self): |
| 1745 | return self._codereview_impl.GetMostRecentPatchset() |
| 1746 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1747 | def CannotTriggerTryJobReason(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1748 | """Returns reason (str) if unable trigger try jobs on this CL or None.""" |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1749 | return self._codereview_impl.CannotTriggerTryJobReason() |
| 1750 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1751 | def GetTryJobProperties(self, patchset=None): |
| 1752 | """Returns dictionary of properties to launch try job.""" |
| 1753 | return self._codereview_impl.GetTryJobProperties(patchset=patchset) |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 1754 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1755 | def __getattr__(self, attr): |
| 1756 | # This is because lots of untested code accesses Rietveld-specific stuff |
| 1757 | # 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] | 1758 | # on a case by case basis. |
tandrii | 4d89550 | 2016-08-18 08:26:19 -0700 | [diff] [blame] | 1759 | # Note that child method defines __getattr__ as well, and forwards it here, |
| 1760 | # because _RietveldChangelistImpl is not cleaned up yet, and given |
| 1761 | # deprecation of Rietveld, it should probably be just removed. |
| 1762 | # Until that time, avoid infinite recursion by bypassing __getattr__ |
| 1763 | # of implementation class. |
| 1764 | return self._codereview_impl.__getattribute__(attr) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1765 | |
| 1766 | |
| 1767 | class _ChangelistCodereviewBase(object): |
| 1768 | """Abstract base class encapsulating codereview specifics of a changelist.""" |
| 1769 | def __init__(self, changelist): |
| 1770 | self._changelist = changelist # instance of Changelist |
| 1771 | |
| 1772 | def __getattr__(self, attr): |
| 1773 | # Forward methods to changelist. |
| 1774 | # TODO(tandrii): maybe clean up _GerritChangelistImpl and |
| 1775 | # _RietveldChangelistImpl to avoid this hack? |
| 1776 | return getattr(self._changelist, attr) |
| 1777 | |
| 1778 | def GetStatus(self): |
| 1779 | """Apply a rough heuristic to give a simple summary of an issue's review |
| 1780 | or CQ status, assuming adherence to a common workflow. |
| 1781 | |
| 1782 | Returns None if no issue for this branch, or specific string keywords. |
| 1783 | """ |
| 1784 | raise NotImplementedError() |
| 1785 | |
| 1786 | def GetCodereviewServer(self): |
| 1787 | """Returns server URL without end slash, like "https://codereview.com".""" |
| 1788 | raise NotImplementedError() |
| 1789 | |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 1790 | def FetchDescription(self, force=False): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1791 | """Fetches and returns description from the codereview server.""" |
| 1792 | raise NotImplementedError() |
| 1793 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1794 | @classmethod |
| 1795 | def IssueConfigKey(cls): |
| 1796 | """Returns branch setting storing issue number.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1797 | raise NotImplementedError() |
| 1798 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 1799 | @classmethod |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1800 | def PatchsetConfigKey(cls): |
| 1801 | """Returns branch setting storing patchset number.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1802 | raise NotImplementedError() |
| 1803 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1804 | @classmethod |
| 1805 | def CodereviewServerConfigKey(cls): |
| 1806 | """Returns branch setting storing codereview server.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1807 | raise NotImplementedError() |
| 1808 | |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 1809 | def _PostUnsetIssueProperties(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1810 | """Which branch-specific properties to erase when unsetting issue.""" |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1811 | return [] |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 1812 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1813 | def GetRietveldObjForPresubmit(self): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1814 | # This is an unfortunate Rietveld-embeddedness in presubmit. |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1815 | # For non-Rietveld code reviews, this probably should return a dummy object. |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1816 | raise NotImplementedError() |
| 1817 | |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 1818 | def GetGerritObjForPresubmit(self): |
| 1819 | # None is valid return value, otherwise presubmit_support.GerritAccessor. |
| 1820 | return None |
| 1821 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 1822 | def UpdateDescriptionRemote(self, description, force=False): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1823 | """Update the description on codereview site.""" |
| 1824 | raise NotImplementedError() |
| 1825 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 1826 | def AddComment(self, message, publish=None): |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 1827 | """Posts a comment to the codereview site.""" |
| 1828 | raise NotImplementedError() |
| 1829 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 1830 | def GetCommentsSummary(self, readable=True): |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1831 | raise NotImplementedError() |
| 1832 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1833 | def CloseIssue(self): |
| 1834 | """Closes the issue.""" |
| 1835 | raise NotImplementedError() |
| 1836 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1837 | def GetMostRecentPatchset(self): |
| 1838 | """Returns the most recent patchset number from the codereview site.""" |
| 1839 | raise NotImplementedError() |
| 1840 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1841 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 1842 | directory, force): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1843 | """Fetches and applies the issue. |
| 1844 | |
| 1845 | Arguments: |
| 1846 | parsed_issue_arg: instance of _ParsedIssueNumberArgument. |
| 1847 | reject: if True, reject the failed patch instead of switching to 3-way |
| 1848 | merge. Rietveld only. |
| 1849 | nocommit: do not commit the patch, thus leave the tree dirty. Rietveld |
| 1850 | only. |
| 1851 | directory: switch to directory before applying the patch. Rietveld only. |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 1852 | force: if true, overwrites existing local state. |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1853 | """ |
| 1854 | raise NotImplementedError() |
| 1855 | |
| 1856 | @staticmethod |
| 1857 | def ParseIssueURL(parsed_url): |
| 1858 | """Parses url and returns instance of _ParsedIssueNumberArgument or None if |
| 1859 | failed.""" |
| 1860 | raise NotImplementedError() |
| 1861 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 1862 | def EnsureAuthenticated(self, force, refresh=False): |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1863 | """Best effort check that user is authenticated with codereview server. |
| 1864 | |
| 1865 | Arguments: |
| 1866 | force: whether to skip confirmation questions. |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 1867 | refresh: whether to attempt to refresh credentials. Ignored if not |
| 1868 | applicable. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1869 | """ |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1870 | raise NotImplementedError() |
| 1871 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1872 | def EnsureCanUploadPatchset(self, force): |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 1873 | """Best effort check that uploading isn't supposed to fail for predictable |
| 1874 | reasons. |
| 1875 | |
| 1876 | This method should raise informative exception if uploading shouldn't |
| 1877 | proceed. |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1878 | |
| 1879 | Arguments: |
| 1880 | force: whether to skip confirmation questions. |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 1881 | """ |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1882 | raise NotImplementedError() |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 1883 | |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 1884 | def CMDUploadChange(self, options, git_diff_args, custom_cl_base, change): |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 1885 | """Uploads a change to codereview.""" |
| 1886 | raise NotImplementedError() |
| 1887 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1888 | def SetCQState(self, new_state): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1889 | """Updates the CQ state for the latest patchset. |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1890 | |
| 1891 | Issue must have been already uploaded and known. |
| 1892 | """ |
| 1893 | raise NotImplementedError() |
| 1894 | |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 1895 | def CannotTriggerTryJobReason(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1896 | """Returns reason (str) if unable trigger try jobs on this CL or None.""" |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 1897 | raise NotImplementedError() |
| 1898 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1899 | def GetIssueOwner(self): |
| 1900 | raise NotImplementedError() |
| 1901 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1902 | def GetTryJobProperties(self, patchset=None): |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 1903 | raise NotImplementedError() |
| 1904 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1905 | |
| 1906 | class _RietveldChangelistImpl(_ChangelistCodereviewBase): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1907 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 1908 | def __init__(self, changelist, auth_config=None, codereview_host=None): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1909 | super(_RietveldChangelistImpl, self).__init__(changelist) |
| 1910 | assert settings, 'must be initialized in _ChangelistCodereviewBase' |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 1911 | if not codereview_host: |
martiniss | 6eda05f | 2016-06-30 10:18:35 -0700 | [diff] [blame] | 1912 | settings.GetDefaultServerUrl() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1913 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 1914 | self._rietveld_server = codereview_host |
Andrii Shyshkalov | 98cef57 | 2017-01-25 13:57:52 +0100 | [diff] [blame] | 1915 | self._auth_config = auth_config or auth.make_auth_config() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1916 | self._props = None |
| 1917 | self._rpc_server = None |
| 1918 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1919 | def GetCodereviewServer(self): |
| 1920 | if not self._rietveld_server: |
| 1921 | # If we're on a branch then get the server potentially associated |
| 1922 | # with that branch. |
| 1923 | if self.GetIssue(): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1924 | self._rietveld_server = gclient_utils.UpgradeToHttps( |
| 1925 | self._GitGetBranchConfigValue(self.CodereviewServerConfigKey())) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1926 | if not self._rietveld_server: |
| 1927 | self._rietveld_server = settings.GetDefaultServerUrl() |
| 1928 | return self._rietveld_server |
| 1929 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 1930 | def EnsureAuthenticated(self, force, refresh=False): |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1931 | """Best effort check that user is authenticated with Rietveld server.""" |
| 1932 | if self._auth_config.use_oauth2: |
| 1933 | authenticator = auth.get_authenticator_for_host( |
| 1934 | self.GetCodereviewServer(), self._auth_config) |
| 1935 | if not authenticator.has_cached_credentials(): |
| 1936 | raise auth.LoginRequiredError(self.GetCodereviewServer()) |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 1937 | if refresh: |
| 1938 | authenticator.get_access_token() |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1939 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1940 | def EnsureCanUploadPatchset(self, force): |
| 1941 | # No checks for Rietveld because we are deprecating Rietveld. |
| 1942 | pass |
| 1943 | |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 1944 | def FetchDescription(self, force=False): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1945 | issue = self.GetIssue() |
| 1946 | assert issue |
| 1947 | try: |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 1948 | return self.RpcServer().get_description(issue, force=force).strip() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1949 | except urllib2.HTTPError as e: |
| 1950 | if e.code == 404: |
| 1951 | DieWithError( |
| 1952 | ('\nWhile fetching the description for issue %d, received a ' |
| 1953 | '404 (not found)\n' |
| 1954 | 'error. It is likely that you deleted this ' |
| 1955 | 'issue on the server. If this is the\n' |
| 1956 | 'case, please run\n\n' |
| 1957 | ' git cl issue 0\n\n' |
| 1958 | 'to clear the association with the deleted issue. Then run ' |
| 1959 | 'this command again.') % issue) |
| 1960 | else: |
| 1961 | DieWithError( |
| 1962 | '\nFailed to fetch issue description. HTTP error %d' % e.code) |
| 1963 | except urllib2.URLError as e: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 1964 | print('Warning: Failed to retrieve CL description due to network ' |
| 1965 | 'failure.', file=sys.stderr) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1966 | return '' |
| 1967 | |
| 1968 | def GetMostRecentPatchset(self): |
| 1969 | return self.GetIssueProperties()['patchsets'][-1] |
| 1970 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1971 | def GetIssueProperties(self): |
| 1972 | if self._props is None: |
| 1973 | issue = self.GetIssue() |
| 1974 | if not issue: |
| 1975 | self._props = {} |
| 1976 | else: |
| 1977 | self._props = self.RpcServer().get_issue_properties(issue, True) |
| 1978 | return self._props |
| 1979 | |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 1980 | def CannotTriggerTryJobReason(self): |
| 1981 | props = self.GetIssueProperties() |
| 1982 | if not props: |
| 1983 | return 'Rietveld doesn\'t know about your issue %s' % self.GetIssue() |
| 1984 | if props.get('closed'): |
| 1985 | return 'CL %s is closed' % self.GetIssue() |
| 1986 | if props.get('private'): |
| 1987 | return 'CL %s is private' % self.GetIssue() |
| 1988 | return None |
| 1989 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1990 | def GetTryJobProperties(self, patchset=None): |
| 1991 | """Returns dictionary of properties to launch try job.""" |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 1992 | project = (self.GetIssueProperties() or {}).get('project') |
| 1993 | return { |
| 1994 | 'issue': self.GetIssue(), |
| 1995 | 'patch_project': project, |
| 1996 | 'patch_storage': 'rietveld', |
| 1997 | 'patchset': patchset or self.GetPatchset(), |
| 1998 | 'rietveld': self.GetCodereviewServer(), |
| 1999 | } |
| 2000 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 2001 | def GetIssueOwner(self): |
| 2002 | return (self.GetIssueProperties() or {}).get('owner_email') |
| 2003 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 2004 | def AddComment(self, message, publish=None): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2005 | return self.RpcServer().add_comment(self.GetIssue(), message) |
| 2006 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2007 | def GetCommentsSummary(self, _readable=True): |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 2008 | summary = [] |
| 2009 | for message in self.GetIssueProperties().get('messages', []): |
| 2010 | date = datetime.datetime.strptime(message['date'], '%Y-%m-%d %H:%M:%S.%f') |
| 2011 | summary.append(_CommentSummary( |
| 2012 | date=date, |
| 2013 | disapproval=bool(message['disapproval']), |
| 2014 | approval=bool(message['approval']), |
| 2015 | sender=message['sender'], |
| 2016 | message=message['text'], |
| 2017 | )) |
| 2018 | return summary |
| 2019 | |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2020 | def GetStatus(self): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2021 | """Applies a rough heuristic to give a simple summary of an issue's review |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2022 | or CQ status, assuming adherence to a common workflow. |
| 2023 | |
| 2024 | Returns None if no issue for this branch, or one of the following keywords: |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 2025 | * 'error' - error from review tool (including deleted issues) |
| 2026 | * 'unsent' - not sent for review |
| 2027 | * 'waiting' - waiting for review |
| 2028 | * 'reply' - waiting for owner to reply to review |
| 2029 | * 'not lgtm' - Code-Review label has been set negatively |
| 2030 | * 'lgtm' - LGTM from at least one approved reviewer |
| 2031 | * 'commit' - in the commit queue |
| 2032 | * 'closed' - closed |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2033 | """ |
| 2034 | if not self.GetIssue(): |
| 2035 | return None |
| 2036 | |
| 2037 | try: |
| 2038 | props = self.GetIssueProperties() |
| 2039 | except urllib2.HTTPError: |
| 2040 | return 'error' |
| 2041 | |
| 2042 | if props.get('closed'): |
| 2043 | # Issue is closed. |
| 2044 | return 'closed' |
tandrii@chromium.org | b4f6a22 | 2016-03-03 01:11:04 +0000 | [diff] [blame] | 2045 | if props.get('commit') and not props.get('cq_dry_run', False): |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2046 | # Issue is in the commit queue. |
| 2047 | return 'commit' |
| 2048 | |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2049 | messages = props.get('messages') or [] |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 2050 | if not messages: |
| 2051 | # No message was sent. |
| 2052 | return 'unsent' |
| 2053 | |
| 2054 | if get_approving_reviewers(props): |
| 2055 | return 'lgtm' |
| 2056 | elif get_approving_reviewers(props, disapproval=True): |
| 2057 | return 'not lgtm' |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2058 | |
tandrii | 9d2c7a3 | 2016-06-22 03:42:45 -0700 | [diff] [blame] | 2059 | # Skip CQ messages that don't require owner's action. |
| 2060 | while messages and messages[-1]['sender'] == COMMIT_BOT_EMAIL: |
| 2061 | if 'Dry run:' in messages[-1]['text']: |
| 2062 | messages.pop() |
| 2063 | elif 'The CQ bit was unchecked' in messages[-1]['text']: |
| 2064 | # This message always follows prior messages from CQ, |
| 2065 | # so skip this too. |
| 2066 | messages.pop() |
| 2067 | else: |
| 2068 | # This is probably a CQ messages warranting user attention. |
| 2069 | break |
| 2070 | |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2071 | if messages[-1]['sender'] != props.get('owner_email'): |
tandrii | 9d2c7a3 | 2016-06-22 03:42:45 -0700 | [diff] [blame] | 2072 | # Non-LGTM reply from non-owner and not CQ bot. |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2073 | return 'reply' |
| 2074 | return 'waiting' |
| 2075 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 2076 | def UpdateDescriptionRemote(self, description, force=False): |
Andrii Shyshkalov | 8305115 | 2017-02-07 23:47:29 +0100 | [diff] [blame] | 2077 | self.RpcServer().update_description(self.GetIssue(), description) |
maruel@chromium.org | b021b32 | 2013-04-08 17:57:29 +0000 | [diff] [blame] | 2078 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2079 | def CloseIssue(self): |
maruel@chromium.org | b021b32 | 2013-04-08 17:57:29 +0000 | [diff] [blame] | 2080 | return self.RpcServer().close_issue(self.GetIssue()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2081 | |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 2082 | def SetFlag(self, flag, value): |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2083 | return self.SetFlags({flag: value}) |
| 2084 | |
| 2085 | def SetFlags(self, flags): |
| 2086 | """Sets flags on this CL/patchset in Rietveld. |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2087 | """ |
phajdan.jr | 6859823 | 2016-08-10 03:28:28 -0700 | [diff] [blame] | 2088 | patchset = self.GetPatchset() or self.GetMostRecentPatchset() |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 2089 | try: |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2090 | return self.RpcServer().set_flags( |
phajdan.jr | 6859823 | 2016-08-10 03:28:28 -0700 | [diff] [blame] | 2091 | self.GetIssue(), patchset, flags) |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 2092 | except urllib2.HTTPError as e: |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 2093 | if e.code == 404: |
| 2094 | DieWithError('The issue %s doesn\'t exist.' % self.GetIssue()) |
| 2095 | if e.code == 403: |
| 2096 | DieWithError( |
| 2097 | ('Access denied to issue %s. Maybe the patchset %s doesn\'t ' |
phajdan.jr | 6859823 | 2016-08-10 03:28:28 -0700 | [diff] [blame] | 2098 | 'match?') % (self.GetIssue(), patchset)) |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 2099 | raise |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2100 | |
maruel@chromium.org | cab38e9 | 2011-04-09 00:30:51 +0000 | [diff] [blame] | 2101 | def RpcServer(self): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2102 | """Returns an upload.RpcServer() to access this review's rietveld instance. |
| 2103 | """ |
maruel@chromium.org | e77ebbf | 2011-03-29 20:35:38 +0000 | [diff] [blame] | 2104 | if not self._rpc_server: |
maruel@chromium.org | 4bac4b5 | 2012-11-27 20:33:52 +0000 | [diff] [blame] | 2105 | self._rpc_server = rietveld.CachingRietveld( |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2106 | self.GetCodereviewServer(), |
Andrii Shyshkalov | 98cef57 | 2017-01-25 13:57:52 +0100 | [diff] [blame] | 2107 | self._auth_config) |
maruel@chromium.org | e77ebbf | 2011-03-29 20:35:38 +0000 | [diff] [blame] | 2108 | return self._rpc_server |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2109 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2110 | @classmethod |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2111 | def IssueConfigKey(cls): |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2112 | return 'rietveldissue' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2113 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2114 | @classmethod |
| 2115 | def PatchsetConfigKey(cls): |
| 2116 | return 'rietveldpatchset' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2117 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2118 | @classmethod |
| 2119 | def CodereviewServerConfigKey(cls): |
| 2120 | return 'rietveldserver' |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 2121 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2122 | def GetRietveldObjForPresubmit(self): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2123 | return self.RpcServer() |
| 2124 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2125 | def SetCQState(self, new_state): |
| 2126 | props = self.GetIssueProperties() |
| 2127 | if props.get('private'): |
| 2128 | DieWithError('Cannot set-commit on private issue') |
| 2129 | |
| 2130 | if new_state == _CQState.COMMIT: |
tandrii | 4d84359 | 2016-07-27 08:22:56 -0700 | [diff] [blame] | 2131 | self.SetFlags({'commit': '1', 'cq_dry_run': '0'}) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2132 | elif new_state == _CQState.NONE: |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2133 | self.SetFlags({'commit': '0', 'cq_dry_run': '0'}) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2134 | else: |
tandrii | 4b233bd | 2016-07-06 03:50:29 -0700 | [diff] [blame] | 2135 | assert new_state == _CQState.DRY_RUN |
| 2136 | self.SetFlags({'commit': '1', 'cq_dry_run': '1'}) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2137 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2138 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 2139 | directory, force): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2140 | # PatchIssue should never be called with a dirty tree. It is up to the |
| 2141 | # caller to check this, but just in case we assert here since the |
| 2142 | # consequences of the caller not checking this could be dire. |
| 2143 | assert(not git_common.is_dirty_git_tree('apply')) |
| 2144 | assert(parsed_issue_arg.valid) |
| 2145 | self._changelist.issue = parsed_issue_arg.issue |
| 2146 | if parsed_issue_arg.hostname: |
| 2147 | self._rietveld_server = 'https://%s' % parsed_issue_arg.hostname |
| 2148 | |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2149 | patchset = parsed_issue_arg.patchset or self.GetMostRecentPatchset() |
| 2150 | patchset_object = self.RpcServer().get_patch(self.GetIssue(), patchset) |
| 2151 | scm_obj = checkout.GitCheckout(settings.GetRoot(), None, None, None, None) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2152 | try: |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2153 | scm_obj.apply_patch(patchset_object) |
| 2154 | except Exception as e: |
| 2155 | print(str(e)) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2156 | return 1 |
| 2157 | |
| 2158 | # If we had an issue, commit the current state and register the issue. |
| 2159 | if not nocommit: |
Aaron Gable | d343c63 | 2017-03-15 11:02:26 -0700 | [diff] [blame] | 2160 | self.SetIssue(self.GetIssue()) |
| 2161 | self.SetPatchset(patchset) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2162 | RunGit(['commit', '-m', (self.GetDescription() + '\n\n' + |
| 2163 | 'patch from issue %(i)s at patchset ' |
| 2164 | '%(p)s (http://crrev.com/%(i)s#ps%(p)s)' |
| 2165 | % {'i': self.GetIssue(), 'p': patchset})]) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 2166 | print('Committed patch locally.') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2167 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 2168 | print('Patch applied to index.') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2169 | return 0 |
| 2170 | |
| 2171 | @staticmethod |
| 2172 | def ParseIssueURL(parsed_url): |
| 2173 | if not parsed_url.scheme or not parsed_url.scheme.startswith('http'): |
| 2174 | return None |
wychen | 3c1c172 | 2016-08-04 11:46:36 -0700 | [diff] [blame] | 2175 | # Rietveld patch: https://domain/<number>/#ps<patchset> |
| 2176 | match = re.match(r'/(\d+)/$', parsed_url.path) |
| 2177 | match2 = re.match(r'ps(\d+)$', parsed_url.fragment) |
| 2178 | if match and match2: |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2179 | return _ParsedIssueNumberArgument( |
wychen | 3c1c172 | 2016-08-04 11:46:36 -0700 | [diff] [blame] | 2180 | issue=int(match.group(1)), |
| 2181 | patchset=int(match2.group(1)), |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 2182 | hostname=parsed_url.netloc, |
| 2183 | codereview='rietveld') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2184 | # Typical url: https://domain/<issue_number>[/[other]] |
| 2185 | match = re.match('/(\d+)(/.*)?$', parsed_url.path) |
| 2186 | if match: |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2187 | return _ParsedIssueNumberArgument( |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2188 | issue=int(match.group(1)), |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 2189 | hostname=parsed_url.netloc, |
| 2190 | codereview='rietveld') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2191 | # Rietveld patch: https://domain/download/issue<number>_<patchset>.diff |
| 2192 | match = re.match(r'/download/issue(\d+)_(\d+).diff$', parsed_url.path) |
| 2193 | if match: |
skobes | 6468b90 | 2016-10-24 08:45:10 -0700 | [diff] [blame] | 2194 | return _ParsedIssueNumberArgument( |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2195 | issue=int(match.group(1)), |
| 2196 | patchset=int(match.group(2)), |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 2197 | hostname=parsed_url.netloc, |
| 2198 | codereview='rietveld') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2199 | return None |
| 2200 | |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2201 | def CMDUploadChange(self, options, args, custom_cl_base, change): |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2202 | """Upload the patch to Rietveld.""" |
| 2203 | upload_args = ['--assume_yes'] # Don't ask about untracked files. |
| 2204 | upload_args.extend(['--server', self.GetCodereviewServer()]) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2205 | upload_args.extend(auth.auth_config_to_command_options(self._auth_config)) |
| 2206 | if options.emulate_svn_auto_props: |
| 2207 | upload_args.append('--emulate_svn_auto_props') |
| 2208 | |
| 2209 | change_desc = None |
| 2210 | |
| 2211 | if options.email is not None: |
| 2212 | upload_args.extend(['--email', options.email]) |
| 2213 | |
| 2214 | if self.GetIssue(): |
nodir | ca16600 | 2016-06-27 10:59:51 -0700 | [diff] [blame] | 2215 | if options.title is not None: |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2216 | upload_args.extend(['--title', options.title]) |
| 2217 | if options.message: |
| 2218 | upload_args.extend(['--message', options.message]) |
| 2219 | upload_args.extend(['--issue', str(self.GetIssue())]) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 2220 | print('This branch is associated with issue %s. ' |
| 2221 | 'Adding patch to that issue.' % self.GetIssue()) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2222 | else: |
nodir | ca16600 | 2016-06-27 10:59:51 -0700 | [diff] [blame] | 2223 | if options.title is not None: |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2224 | upload_args.extend(['--title', options.title]) |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 2225 | if options.message: |
| 2226 | message = options.message |
| 2227 | else: |
| 2228 | message = CreateDescriptionFromLog(args) |
| 2229 | if options.title: |
| 2230 | message = options.title + '\n\n' + message |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2231 | change_desc = ChangeDescription(message) |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 2232 | if options.reviewers or options.add_owners_to: |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 2233 | change_desc.update_reviewers(options.reviewers, options.tbrs, |
| 2234 | options.add_owners_to, change) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2235 | if not options.force: |
Aaron Gable | 3a16ed1 | 2017-03-23 10:51:55 -0700 | [diff] [blame] | 2236 | change_desc.prompt(bug=options.bug, git_footer=False) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2237 | |
| 2238 | if not change_desc.description: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 2239 | print('Description is empty; aborting.') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2240 | return 1 |
| 2241 | |
| 2242 | upload_args.extend(['--message', change_desc.description]) |
| 2243 | if change_desc.get_reviewers(): |
| 2244 | upload_args.append('--reviewers=%s' % ','.join( |
| 2245 | change_desc.get_reviewers())) |
| 2246 | if options.send_mail: |
| 2247 | if not change_desc.get_reviewers(): |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 2248 | DieWithError("Must specify reviewers to send email.", change_desc) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2249 | upload_args.append('--send_mail') |
| 2250 | |
| 2251 | # We check this before applying rietveld.private assuming that in |
| 2252 | # rietveld.cc only addresses which we can send private CLs to are listed |
| 2253 | # if rietveld.private is set, and so we should ignore rietveld.cc only |
| 2254 | # when --private is specified explicitly on the command line. |
| 2255 | if options.private: |
| 2256 | logging.warn('rietveld.cc is ignored since private flag is specified. ' |
| 2257 | 'You need to review and add them manually if necessary.') |
| 2258 | cc = self.GetCCListWithoutDefault() |
| 2259 | else: |
| 2260 | cc = self.GetCCList() |
| 2261 | cc = ','.join(filter(None, (cc, ','.join(options.cc)))) |
bradnelson | d975b30 | 2016-10-23 12:20:23 -0700 | [diff] [blame] | 2262 | if change_desc.get_cced(): |
| 2263 | cc = ','.join(filter(None, (cc, ','.join(change_desc.get_cced())))) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2264 | if cc: |
| 2265 | upload_args.extend(['--cc', cc]) |
| 2266 | |
| 2267 | if options.private or settings.GetDefaultPrivateFlag() == "True": |
| 2268 | upload_args.append('--private') |
| 2269 | |
| 2270 | upload_args.extend(['--git_similarity', str(options.similarity)]) |
| 2271 | if not options.find_copies: |
| 2272 | upload_args.extend(['--git_no_find_copies']) |
| 2273 | |
| 2274 | # Include the upstream repo's URL in the change -- this is useful for |
| 2275 | # projects that have their source spread across multiple repos. |
| 2276 | remote_url = self.GetGitBaseUrlFromConfig() |
| 2277 | if not remote_url: |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 2278 | if self.GetRemoteUrl() and '/' in self.GetUpstreamBranch(): |
| 2279 | remote_url = '%s@%s' % (self.GetRemoteUrl(), |
| 2280 | self.GetUpstreamBranch().split('/')[-1]) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2281 | if remote_url: |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2282 | remote, remote_branch = self.GetRemoteBranch() |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 2283 | target_ref = GetTargetRef(remote, remote_branch, options.target_branch) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2284 | if target_ref: |
| 2285 | upload_args.extend(['--target_ref', target_ref]) |
| 2286 | |
| 2287 | # Look for dependent patchsets. See crbug.com/480453 for more details. |
| 2288 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
| 2289 | upstream_branch = ShortBranchName(upstream_branch) |
| 2290 | if remote is '.': |
| 2291 | # A local branch is being tracked. |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 2292 | local_branch = upstream_branch |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2293 | if settings.GetIsSkipDependencyUpload(local_branch): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 2294 | print() |
| 2295 | print('Skipping dependency patchset upload because git config ' |
| 2296 | 'branch.%s.skip-deps-uploads is set to True.' % local_branch) |
| 2297 | print() |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2298 | else: |
| 2299 | auth_config = auth.extract_auth_config_from_options(options) |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 2300 | branch_cl = Changelist(branchref='refs/heads/'+local_branch, |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2301 | auth_config=auth_config) |
| 2302 | branch_cl_issue_url = branch_cl.GetIssueURL() |
| 2303 | branch_cl_issue = branch_cl.GetIssue() |
| 2304 | branch_cl_patchset = branch_cl.GetPatchset() |
| 2305 | if branch_cl_issue_url and branch_cl_issue and branch_cl_patchset: |
| 2306 | upload_args.extend( |
| 2307 | ['--depends_on_patchset', '%s:%s' % ( |
| 2308 | branch_cl_issue, branch_cl_patchset)]) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2309 | print( |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2310 | '\n' |
| 2311 | 'The current branch (%s) is tracking a local branch (%s) with ' |
| 2312 | 'an associated CL.\n' |
| 2313 | 'Adding %s/#ps%s as a dependency patchset.\n' |
| 2314 | '\n' % (self.GetBranch(), local_branch, branch_cl_issue_url, |
| 2315 | branch_cl_patchset)) |
| 2316 | |
| 2317 | project = settings.GetProject() |
| 2318 | if project: |
| 2319 | upload_args.extend(['--project', project]) |
Aaron Gable | 665a439 | 2017-06-29 10:53:46 -0700 | [diff] [blame] | 2320 | else: |
| 2321 | print() |
| 2322 | print('WARNING: Uploading without a project specified. Please ensure ' |
| 2323 | 'your repo\'s codereview.settings has a "PROJECT: foo" line.') |
| 2324 | print() |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2325 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2326 | try: |
| 2327 | upload_args = ['upload'] + upload_args + args |
| 2328 | logging.info('upload.RealMain(%s)', upload_args) |
| 2329 | issue, patchset = upload.RealMain(upload_args) |
| 2330 | issue = int(issue) |
| 2331 | patchset = int(patchset) |
| 2332 | except KeyboardInterrupt: |
| 2333 | sys.exit(1) |
| 2334 | except: |
| 2335 | # If we got an exception after the user typed a description for their |
| 2336 | # change, back up the description before re-raising. |
| 2337 | if change_desc: |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 2338 | SaveDescriptionBackup(change_desc) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2339 | raise |
| 2340 | |
| 2341 | if not self.GetIssue(): |
| 2342 | self.SetIssue(issue) |
| 2343 | self.SetPatchset(patchset) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2344 | return 0 |
| 2345 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 2346 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2347 | class _GerritChangelistImpl(_ChangelistCodereviewBase): |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 2348 | def __init__(self, changelist, auth_config=None, codereview_host=None): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2349 | # auth_config is Rietveld thing, kept here to preserve interface only. |
| 2350 | super(_GerritChangelistImpl, self).__init__(changelist) |
| 2351 | self._change_id = None |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2352 | # Lazily cached values. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2353 | self._gerrit_host = None # e.g. chromium-review.googlesource.com |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 2354 | self._gerrit_server = None # e.g. https://chromium-review.googlesource.com |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2355 | # Map from change number (issue) to its detail cache. |
| 2356 | self._detail_cache = {} |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2357 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 2358 | if codereview_host is not None: |
| 2359 | assert not codereview_host.startswith('https://'), codereview_host |
| 2360 | self._gerrit_host = codereview_host |
| 2361 | self._gerrit_server = 'https://%s' % codereview_host |
| 2362 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2363 | def _GetGerritHost(self): |
| 2364 | # Lazy load of configs. |
| 2365 | self.GetCodereviewServer() |
tandrii | e32e3ea | 2016-06-22 02:52:48 -0700 | [diff] [blame] | 2366 | if self._gerrit_host and '.' not in self._gerrit_host: |
| 2367 | # Abbreviated domain like "chromium" instead of chromium.googlesource.com. |
| 2368 | # This happens for internal stuff http://crbug.com/614312. |
| 2369 | parsed = urlparse.urlparse(self.GetRemoteUrl()) |
| 2370 | if parsed.scheme == 'sso': |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2371 | print('WARNING: using non-https URLs for remote is likely broken\n' |
tandrii | e32e3ea | 2016-06-22 02:52:48 -0700 | [diff] [blame] | 2372 | ' Your current remote is: %s' % self.GetRemoteUrl()) |
| 2373 | self._gerrit_host = '%s.googlesource.com' % self._gerrit_host |
| 2374 | self._gerrit_server = 'https://%s' % self._gerrit_host |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2375 | return self._gerrit_host |
| 2376 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2377 | def _GetGitHost(self): |
| 2378 | """Returns git host to be used when uploading change to Gerrit.""" |
| 2379 | return urlparse.urlparse(self.GetRemoteUrl()).netloc |
| 2380 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2381 | def GetCodereviewServer(self): |
| 2382 | if not self._gerrit_server: |
| 2383 | # If we're on a branch then get the server potentially associated |
| 2384 | # with that branch. |
| 2385 | if self.GetIssue(): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2386 | self._gerrit_server = self._GitGetBranchConfigValue( |
| 2387 | self.CodereviewServerConfigKey()) |
| 2388 | if self._gerrit_server: |
| 2389 | self._gerrit_host = urlparse.urlparse(self._gerrit_server).netloc |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2390 | if not self._gerrit_server: |
| 2391 | # We assume repo to be hosted on Gerrit, and hence Gerrit server |
| 2392 | # has "-review" suffix for lowest level subdomain. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2393 | parts = self._GetGitHost().split('.') |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2394 | parts[0] = parts[0] + '-review' |
| 2395 | self._gerrit_host = '.'.join(parts) |
| 2396 | self._gerrit_server = 'https://%s' % self._gerrit_host |
| 2397 | return self._gerrit_server |
| 2398 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2399 | @classmethod |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2400 | def IssueConfigKey(cls): |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2401 | return 'gerritissue' |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2402 | |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2403 | @classmethod |
| 2404 | def PatchsetConfigKey(cls): |
| 2405 | return 'gerritpatchset' |
| 2406 | |
| 2407 | @classmethod |
| 2408 | def CodereviewServerConfigKey(cls): |
| 2409 | return 'gerritserver' |
| 2410 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 2411 | def EnsureAuthenticated(self, force, refresh=None): |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2412 | """Best effort check that user is authenticated with Gerrit server.""" |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 2413 | if settings.GetGerritSkipEnsureAuthenticated(): |
| 2414 | # For projects with unusual authentication schemes. |
| 2415 | # See http://crbug.com/603378. |
| 2416 | return |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2417 | # Lazy-loader to identify Gerrit and Git hosts. |
| 2418 | if gerrit_util.GceAuthenticator.is_gce(): |
| 2419 | return |
| 2420 | self.GetCodereviewServer() |
| 2421 | git_host = self._GetGitHost() |
| 2422 | assert self._gerrit_server and self._gerrit_host |
| 2423 | cookie_auth = gerrit_util.CookiesAuthenticator() |
| 2424 | |
| 2425 | gerrit_auth = cookie_auth.get_auth_header(self._gerrit_host) |
| 2426 | git_auth = cookie_auth.get_auth_header(git_host) |
| 2427 | if gerrit_auth and git_auth: |
| 2428 | if gerrit_auth == git_auth: |
| 2429 | return |
Andrii Shyshkalov | 354e1d2 | 2017-06-09 19:31:33 +0200 | [diff] [blame] | 2430 | all_gsrc = cookie_auth.get_auth_header('d0esN0tEx1st.googlesource.com') |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2431 | print(( |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2432 | 'WARNING: You have different credentials for Gerrit and git hosts:\n' |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2433 | ' %s\n' |
| 2434 | ' %s\n' |
Andrii Shyshkalov | 51acef9 | 2017-04-11 17:19:59 +0200 | [diff] [blame] | 2435 | ' Consider running the following command:\n' |
| 2436 | ' git cl creds-check\n' |
Andrii Shyshkalov | 354e1d2 | 2017-06-09 19:31:33 +0200 | [diff] [blame] | 2437 | ' %s\n' |
Andrii Shyshkalov | 8e4576f | 2017-05-10 15:46:53 +0200 | [diff] [blame] | 2438 | ' %s') % |
Andrii Shyshkalov | 51acef9 | 2017-04-11 17:19:59 +0200 | [diff] [blame] | 2439 | (git_host, self._gerrit_host, |
Andrii Shyshkalov | 354e1d2 | 2017-06-09 19:31:33 +0200 | [diff] [blame] | 2440 | ('Hint: delete creds for .googlesource.com' if all_gsrc else ''), |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2441 | cookie_auth.get_new_password_message(git_host))) |
| 2442 | if not force: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2443 | 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] | 2444 | return |
| 2445 | else: |
| 2446 | missing = ( |
Anna Henningsen | 4e89144 | 2017-07-06 21:40:58 +0200 | [diff] [blame] | 2447 | ([] if gerrit_auth else [self._gerrit_host]) + |
| 2448 | ([] if git_auth else [git_host])) |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2449 | DieWithError('Credentials for the following hosts are required:\n' |
| 2450 | ' %s\n' |
| 2451 | 'These are read from %s (or legacy %s)\n' |
| 2452 | '%s' % ( |
| 2453 | '\n '.join(missing), |
| 2454 | cookie_auth.get_gitcookies_path(), |
| 2455 | cookie_auth.get_netrc_path(), |
| 2456 | cookie_auth.get_new_password_message(git_host))) |
| 2457 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2458 | def EnsureCanUploadPatchset(self, force): |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 2459 | if not self.GetIssue(): |
| 2460 | return |
| 2461 | |
| 2462 | # Warm change details cache now to avoid RPCs later, reducing latency for |
| 2463 | # developers. |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2464 | self._GetChangeDetail( |
| 2465 | ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT']) |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 2466 | |
| 2467 | status = self._GetChangeDetail()['status'] |
| 2468 | if status in ('MERGED', 'ABANDONED'): |
| 2469 | DieWithError('Change %s has been %s, new uploads are not allowed' % |
| 2470 | (self.GetIssueURL(), |
| 2471 | 'submitted' if status == 'MERGED' else 'abandoned')) |
| 2472 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2473 | if gerrit_util.GceAuthenticator.is_gce(): |
| 2474 | return |
| 2475 | cookies_user = gerrit_util.CookiesAuthenticator().get_auth_email( |
| 2476 | self._GetGerritHost()) |
| 2477 | if self.GetIssueOwner() == cookies_user: |
| 2478 | return |
| 2479 | logging.debug('change %s owner is %s, cookies user is %s', |
| 2480 | self.GetIssue(), self.GetIssueOwner(), cookies_user) |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2481 | # Maybe user has linked accounts or something like that, |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2482 | # so ask what Gerrit thinks of this user. |
| 2483 | details = gerrit_util.GetAccountDetails(self._GetGerritHost(), 'self') |
| 2484 | if details['email'] == self.GetIssueOwner(): |
| 2485 | return |
| 2486 | if not force: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2487 | 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] | 2488 | 'as %s.\n' |
| 2489 | 'Uploading may fail due to lack of permissions.' % |
| 2490 | (self.GetIssue(), self.GetIssueOwner(), details['email'])) |
| 2491 | confirm_or_exit(action='upload') |
| 2492 | |
| 2493 | |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 2494 | def _PostUnsetIssueProperties(self): |
| 2495 | """Which branch-specific properties to erase when unsetting issue.""" |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 2496 | return ['gerritsquashhash'] |
tandrii@chromium.org | 9b7fd71 | 2016-06-01 13:45:20 +0000 | [diff] [blame] | 2497 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2498 | def GetRietveldObjForPresubmit(self): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2499 | class ThisIsNotRietveldIssue(object): |
| 2500 | def __nonzero__(self): |
| 2501 | # This is a hack to make presubmit_support think that rietveld is not |
| 2502 | # defined, yet still ensure that calls directly result in a decent |
| 2503 | # exception message below. |
| 2504 | return False |
| 2505 | |
| 2506 | def __getattr__(self, attr): |
| 2507 | print( |
| 2508 | 'You aren\'t using Rietveld at the moment, but Gerrit.\n' |
| 2509 | 'Using Rietveld in your PRESUBMIT scripts won\'t work.\n' |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2510 | 'Please, either change your PRESUBMIT to not use rietveld_obj.%s,\n' |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2511 | 'or use Rietveld for codereview.\n' |
| 2512 | 'See also http://crbug.com/579160.' % attr) |
| 2513 | raise NotImplementedError() |
| 2514 | return ThisIsNotRietveldIssue() |
| 2515 | |
tandrii@chromium.org | 37b07a7 | 2016-04-29 16:42:28 +0000 | [diff] [blame] | 2516 | def GetGerritObjForPresubmit(self): |
| 2517 | return presubmit_support.GerritAccessor(self._GetGerritHost()) |
| 2518 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2519 | def GetStatus(self): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2520 | """Apply a rough heuristic to give a simple summary of an issue's review |
| 2521 | or CQ status, assuming adherence to a common workflow. |
| 2522 | |
| 2523 | 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] | 2524 | * 'error' - error from review tool (including deleted issues) |
| 2525 | * 'unsent' - no reviewers added |
| 2526 | * 'waiting' - waiting for review |
| 2527 | * 'reply' - waiting for uploader to reply to review |
| 2528 | * 'lgtm' - Code-Review label has been set |
| 2529 | * 'commit' - in the commit queue |
| 2530 | * 'closed' - successfully submitted or abandoned |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2531 | """ |
| 2532 | if not self.GetIssue(): |
| 2533 | return None |
| 2534 | |
| 2535 | try: |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2536 | data = self._GetChangeDetail([ |
| 2537 | 'DETAILED_LABELS', 'CURRENT_REVISION', 'SUBMITTABLE']) |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2538 | except (httplib.HTTPException, GerritChangeNotExists): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2539 | return 'error' |
| 2540 | |
tandrii@chromium.org | 5e1bf38 | 2016-05-17 08:43:24 +0000 | [diff] [blame] | 2541 | if data['status'] in ('ABANDONED', 'MERGED'): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2542 | return 'closed' |
| 2543 | |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2544 | if data['labels'].get('Commit-Queue', {}).get('approved'): |
| 2545 | # The section will have an "approved" subsection if anyone has voted |
| 2546 | # the maximum value on the label. |
| 2547 | return 'commit' |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2548 | |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2549 | if data['labels'].get('Code-Review', {}).get('approved'): |
| 2550 | return 'lgtm' |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2551 | |
| 2552 | if not data.get('reviewers', {}).get('REVIEWER', []): |
| 2553 | return 'unsent' |
| 2554 | |
Andrii Shyshkalov | 33e88a4 | 2017-01-27 14:45:30 +0100 | [diff] [blame] | 2555 | owner = data['owner'].get('_account_id') |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2556 | messages = sorted(data.get('messages', []), key=lambda m: m.get('updated')) |
| 2557 | last_message_author = messages.pop().get('author', {}) |
| 2558 | while last_message_author: |
Andrii Shyshkalov | 33e88a4 | 2017-01-27 14:45:30 +0100 | [diff] [blame] | 2559 | if last_message_author.get('email') == COMMIT_BOT_EMAIL: |
| 2560 | # Ignore replies from CQ. |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2561 | last_message_author = messages.pop().get('author', {}) |
Andrii Shyshkalov | 33e88a4 | 2017-01-27 14:45:30 +0100 | [diff] [blame] | 2562 | continue |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2563 | if last_message_author.get('_account_id') == owner: |
| 2564 | # Most recent message was by owner. |
| 2565 | return 'waiting' |
| 2566 | else: |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2567 | # Some reply from non-owner. |
| 2568 | return 'reply' |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2569 | |
| 2570 | # Somehow there are no messages even though there are reviewers. |
| 2571 | return 'unsent' |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2572 | |
| 2573 | def GetMostRecentPatchset(self): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2574 | data = self._GetChangeDetail(['CURRENT_REVISION']) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2575 | return data['revisions'][data['current_revision']]['_number'] |
| 2576 | |
Kenneth Russell | 61e2ed4 | 2017-02-15 11:47:13 -0800 | [diff] [blame] | 2577 | def FetchDescription(self, force=False): |
| 2578 | data = self._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'], |
| 2579 | no_cache=force) |
tandrii@chromium.org | 2d3da63 | 2016-04-25 19:23:27 +0000 | [diff] [blame] | 2580 | current_rev = data['current_revision'] |
Andrii Shyshkalov | 9c3a464 | 2017-01-24 17:41:22 +0100 | [diff] [blame] | 2581 | return data['revisions'][current_rev]['commit']['message'] |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2582 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 2583 | def UpdateDescriptionRemote(self, description, force=False): |
| 2584 | if gerrit_util.HasPendingChangeEdit(self._GetGerritHost(), self.GetIssue()): |
| 2585 | if not force: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2586 | confirm_or_exit( |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 2587 | 'The description cannot be modified while the issue has a pending ' |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2588 | 'unpublished edit. Either publish the edit in the Gerrit web UI ' |
| 2589 | 'or delete it.\n\n', action='delete the unpublished edit') |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 2590 | |
| 2591 | gerrit_util.DeletePendingChangeEdit(self._GetGerritHost(), |
| 2592 | self.GetIssue()) |
scottmg@chromium.org | 6d1266e | 2016-04-26 11:12:26 +0000 | [diff] [blame] | 2593 | gerrit_util.SetCommitMessage(self._GetGerritHost(), self.GetIssue(), |
Andrii Shyshkalov | ea4fc83 | 2016-12-01 14:53:23 +0100 | [diff] [blame] | 2594 | description, notify='NONE') |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2595 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 2596 | def AddComment(self, message, publish=None): |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 2597 | gerrit_util.SetReview(self._GetGerritHost(), self.GetIssue(), |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 2598 | msg=message, ready=publish) |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 2599 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2600 | def GetCommentsSummary(self, readable=True): |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2601 | # DETAILED_ACCOUNTS is to get emails in accounts. |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2602 | messages = self._GetChangeDetail( |
| 2603 | options=['MESSAGES', 'DETAILED_ACCOUNTS']).get('messages', []) |
| 2604 | file_comments = gerrit_util.GetChangeComments( |
| 2605 | self._GetGerritHost(), self.GetIssue()) |
| 2606 | |
| 2607 | # Build dictionary of file comments for easy access and sorting later. |
| 2608 | # {author+date: {path: {patchset: {line: url+message}}}} |
| 2609 | comments = collections.defaultdict( |
| 2610 | lambda: collections.defaultdict(lambda: collections.defaultdict(dict))) |
| 2611 | for path, line_comments in file_comments.iteritems(): |
| 2612 | for comment in line_comments: |
| 2613 | if comment.get('tag', '').startswith('autogenerated'): |
| 2614 | continue |
| 2615 | key = (comment['author']['email'], comment['updated']) |
| 2616 | if comment.get('side', 'REVISION') == 'PARENT': |
| 2617 | patchset = 'Base' |
| 2618 | else: |
| 2619 | patchset = 'PS%d' % comment['patch_set'] |
| 2620 | line = comment.get('line', 0) |
| 2621 | url = ('https://%s/c/%s/%s/%s#%s%s' % |
| 2622 | (self._GetGerritHost(), self.GetIssue(), comment['patch_set'], path, |
| 2623 | 'b' if comment.get('side') == 'PARENT' else '', |
| 2624 | str(line) if line else '')) |
| 2625 | comments[key][path][patchset][line] = (url, comment['message']) |
| 2626 | |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2627 | summary = [] |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2628 | for msg in messages: |
| 2629 | # Don't bother showing autogenerated messages. |
| 2630 | if msg.get('tag') and msg.get('tag').startswith('autogenerated'): |
| 2631 | continue |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2632 | # Gerrit spits out nanoseconds. |
| 2633 | assert len(msg['date'].split('.')[-1]) == 9 |
| 2634 | date = datetime.datetime.strptime(msg['date'][:-3], |
| 2635 | '%Y-%m-%d %H:%M:%S.%f') |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2636 | message = msg['message'] |
| 2637 | key = (msg['author']['email'], msg['date']) |
| 2638 | if key in comments: |
| 2639 | message += '\n' |
| 2640 | for path, patchsets in sorted(comments.get(key, {}).items()): |
| 2641 | if readable: |
| 2642 | message += '\n%s' % path |
| 2643 | for patchset, lines in sorted(patchsets.items()): |
| 2644 | for line, (url, content) in sorted(lines.items()): |
| 2645 | if line: |
| 2646 | line_str = 'Line %d' % line |
| 2647 | path_str = '%s:%d:' % (path, line) |
| 2648 | else: |
| 2649 | line_str = 'File comment' |
| 2650 | path_str = '%s:0:' % path |
| 2651 | if readable: |
| 2652 | message += '\n %s, %s: %s' % (patchset, line_str, url) |
| 2653 | message += '\n %s\n' % content |
| 2654 | else: |
| 2655 | message += '\n%s ' % path_str |
| 2656 | message += '\n%s\n' % content |
| 2657 | |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2658 | summary.append(_CommentSummary( |
| 2659 | date=date, |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2660 | message=message, |
Andrii Shyshkalov | 5a0cf20 | 2017-03-17 16:14:59 +0100 | [diff] [blame] | 2661 | sender=msg['author']['email'], |
| 2662 | # These could be inferred from the text messages and correlated with |
| 2663 | # Code-Review label maximum, however this is not reliable. |
| 2664 | # Leaving as is until the need arises. |
| 2665 | approval=False, |
| 2666 | disapproval=False, |
| 2667 | )) |
| 2668 | return summary |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 2669 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2670 | def CloseIssue(self): |
| 2671 | gerrit_util.AbandonChange(self._GetGerritHost(), self.GetIssue(), msg='') |
| 2672 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2673 | def SubmitIssue(self, wait_for_merge=True): |
| 2674 | gerrit_util.SubmitChange(self._GetGerritHost(), self.GetIssue(), |
| 2675 | wait_for_merge=wait_for_merge) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2676 | |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2677 | def _GetChangeDetail(self, options=None, issue=None, |
| 2678 | no_cache=False): |
| 2679 | """Returns details of the issue by querying Gerrit and caching results. |
| 2680 | |
| 2681 | If fresh data is needed, set no_cache=True which will clear cache and |
| 2682 | thus new data will be fetched from Gerrit. |
| 2683 | """ |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2684 | options = options or [] |
| 2685 | issue = issue or self.GetIssue() |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 2686 | assert issue, 'issue is required to query Gerrit' |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2687 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 2688 | # Optimization to avoid multiple RPCs: |
| 2689 | if (('CURRENT_REVISION' in options or 'ALL_REVISIONS' in options) and |
| 2690 | 'CURRENT_COMMIT' not in options): |
| 2691 | options.append('CURRENT_COMMIT') |
| 2692 | |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2693 | # Normalize issue and options for consistent keys in cache. |
| 2694 | issue = str(issue) |
| 2695 | options = [o.upper() for o in options] |
| 2696 | |
| 2697 | # Check in cache first unless no_cache is True. |
| 2698 | if no_cache: |
| 2699 | self._detail_cache.pop(issue, None) |
| 2700 | else: |
| 2701 | options_set = frozenset(options) |
| 2702 | for cached_options_set, data in self._detail_cache.get(issue, []): |
| 2703 | # Assumption: data fetched before with extra options is suitable |
| 2704 | # for return for a smaller set of options. |
| 2705 | # For example, if we cached data for |
| 2706 | # options=[CURRENT_REVISION, DETAILED_FOOTERS] |
| 2707 | # and request is for options=[CURRENT_REVISION], |
| 2708 | # THEN we can return prior cached data. |
| 2709 | if options_set.issubset(cached_options_set): |
| 2710 | return data |
| 2711 | |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 20:51:20 +0100 | [diff] [blame] | 2712 | try: |
Aaron Gable | 19ee16c | 2017-04-18 11:56:35 -0700 | [diff] [blame] | 2713 | data = gerrit_util.GetChangeDetail( |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 2714 | self._GetGerritHost(), str(issue), options) |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 20:51:20 +0100 | [diff] [blame] | 2715 | except gerrit_util.GerritError as e: |
| 2716 | if e.http_status == 404: |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2717 | raise GerritChangeNotExists(issue, self.GetCodereviewServer()) |
Andrii Shyshkalov | c6c8b4c | 2016-11-09 20:51:20 +0100 | [diff] [blame] | 2718 | raise |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2719 | |
| 2720 | self._detail_cache.setdefault(issue, []).append((frozenset(options), data)) |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 2721 | return data |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2722 | |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 2723 | def _GetChangeCommit(self, issue=None): |
| 2724 | issue = issue or self.GetIssue() |
| 2725 | assert issue, 'issue is required to query Gerrit' |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 2726 | try: |
| 2727 | data = gerrit_util.GetChangeCommit(self._GetGerritHost(), str(issue)) |
| 2728 | except gerrit_util.GerritError as e: |
| 2729 | if e.http_status == 404: |
| 2730 | raise GerritChangeNotExists(issue, self.GetCodereviewServer()) |
| 2731 | raise |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 2732 | return data |
| 2733 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2734 | def CMDLand(self, force, bypass_hooks, verbose): |
| 2735 | if git_common.is_dirty_git_tree('land'): |
| 2736 | return 1 |
tandrii | d60367b | 2016-06-22 05:25:12 -0700 | [diff] [blame] | 2737 | detail = self._GetChangeDetail(['CURRENT_REVISION', 'LABELS']) |
| 2738 | if u'Commit-Queue' in detail.get('labels', {}): |
| 2739 | if not force: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2740 | confirm_or_exit('\nIt seems this repository has a Commit Queue, ' |
| 2741 | 'which can test and land changes for you. ' |
| 2742 | 'Are you sure you wish to bypass it?\n', |
| 2743 | action='bypass CQ') |
tandrii | d60367b | 2016-06-22 05:25:12 -0700 | [diff] [blame] | 2744 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2745 | differs = True |
tandrii | c4344b5 | 2016-08-29 06:04:54 -0700 | [diff] [blame] | 2746 | last_upload = self._GitGetBranchConfigValue('gerritsquashhash') |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2747 | # Note: git diff outputs nothing if there is no diff. |
| 2748 | if not last_upload or RunGit(['diff', last_upload]).strip(): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2749 | print('WARNING: Some changes from local branch haven\'t been uploaded.') |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2750 | else: |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2751 | if detail['current_revision'] == last_upload: |
| 2752 | differs = False |
| 2753 | else: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2754 | print('WARNING: Local branch contents differ from latest uploaded ' |
| 2755 | 'patchset.') |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2756 | if differs: |
| 2757 | if not force: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2758 | confirm_or_exit( |
| 2759 | 'Do you want to submit latest Gerrit patchset and bypass hooks?\n', |
| 2760 | action='submit') |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2761 | print('WARNING: Bypassing hooks and submitting latest uploaded patchset.') |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2762 | elif not bypass_hooks: |
| 2763 | hook_results = self.RunHook( |
| 2764 | committing=True, |
| 2765 | may_prompt=not force, |
| 2766 | verbose=verbose, |
| 2767 | change=self.GetChange(self.GetCommonAncestorWithUpstream(), None)) |
| 2768 | if not hook_results.should_continue(): |
| 2769 | return 1 |
| 2770 | |
| 2771 | self.SubmitIssue(wait_for_merge=True) |
| 2772 | print('Issue %s has been submitted.' % self.GetIssueURL()) |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 2773 | links = self._GetChangeCommit().get('web_links', []) |
| 2774 | for link in links: |
Aaron Gable | 02cdbb4 | 2016-12-13 16:24:25 -0800 | [diff] [blame] | 2775 | if link.get('name') == 'gitiles' and link.get('url'): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2776 | print('Landed as: %s' % link.get('url')) |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 2777 | break |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2778 | return 0 |
| 2779 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2780 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 2781 | directory, force): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2782 | assert not reject |
| 2783 | assert not nocommit |
| 2784 | assert not directory |
| 2785 | assert parsed_issue_arg.valid |
| 2786 | |
| 2787 | self._changelist.issue = parsed_issue_arg.issue |
| 2788 | |
| 2789 | if parsed_issue_arg.hostname: |
| 2790 | self._gerrit_host = parsed_issue_arg.hostname |
| 2791 | self._gerrit_server = 'https://%s' % self._gerrit_host |
| 2792 | |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 2793 | try: |
| 2794 | detail = self._GetChangeDetail(['ALL_REVISIONS']) |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2795 | except GerritChangeNotExists as e: |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 2796 | DieWithError(str(e)) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2797 | |
| 2798 | if not parsed_issue_arg.patchset: |
| 2799 | # Use current revision by default. |
| 2800 | revision_info = detail['revisions'][detail['current_revision']] |
| 2801 | patchset = int(revision_info['_number']) |
| 2802 | else: |
| 2803 | patchset = parsed_issue_arg.patchset |
| 2804 | for revision_info in detail['revisions'].itervalues(): |
| 2805 | if int(revision_info['_number']) == parsed_issue_arg.patchset: |
| 2806 | break |
| 2807 | else: |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2808 | DieWithError('Couldn\'t find patchset %i in change %i' % |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2809 | (parsed_issue_arg.patchset, self.GetIssue())) |
| 2810 | |
| 2811 | fetch_info = revision_info['fetch']['http'] |
| 2812 | RunGit(['fetch', fetch_info['url'], fetch_info['ref']]) |
Aaron Gable | 9387b4f | 2017-06-08 10:50:03 -0700 | [diff] [blame] | 2813 | |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 2814 | if force: |
| 2815 | RunGit(['reset', '--hard', 'FETCH_HEAD']) |
| 2816 | print('Checked out commit for change %i patchset %i locally' % |
| 2817 | (parsed_issue_arg.issue, patchset)) |
| 2818 | else: |
Aaron Gable | 9387b4f | 2017-06-08 10:50:03 -0700 | [diff] [blame] | 2819 | RunGit(['cherry-pick', 'FETCH_HEAD']) |
| 2820 | print('Committed patch for change %i patchset %i locally.' % |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 2821 | (parsed_issue_arg.issue, patchset)) |
| 2822 | print('Note: this created a local commit which does not have ' |
| 2823 | 'the same hash as the one uploaded for review. This will make ' |
| 2824 | 'uploading changes based on top of this branch difficult.\n' |
| 2825 | 'If you want to do that, use "git cl patch --force" instead.') |
| 2826 | |
| 2827 | self.SetIssue(parsed_issue_arg.issue) |
| 2828 | self.SetPatchset(patchset) |
| 2829 | fetched_hash = RunGit(['rev-parse', 'FETCH_HEAD']).strip() |
| 2830 | self._GitSetBranchConfigValue('last-upload-hash', fetched_hash) |
| 2831 | self._GitSetBranchConfigValue('gerritsquashhash', fetched_hash) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2832 | return 0 |
| 2833 | |
| 2834 | @staticmethod |
| 2835 | def ParseIssueURL(parsed_url): |
| 2836 | if not parsed_url.scheme or not parsed_url.scheme.startswith('http'): |
| 2837 | return None |
| 2838 | # Gerrit's new UI is https://domain/c/<issue_number>[/[patchset]] |
| 2839 | # But current GWT UI is https://domain/#/c/<issue_number>[/[patchset]] |
| 2840 | # Short urls like https://domain/<issue_number> can be used, but don't allow |
| 2841 | # specifying the patchset (you'd 404), but we allow that here. |
| 2842 | if parsed_url.path == '/': |
| 2843 | part = parsed_url.fragment |
| 2844 | else: |
| 2845 | part = parsed_url.path |
| 2846 | match = re.match('(/c)?/(\d+)(/(\d+)?/?)?$', part) |
| 2847 | if match: |
| 2848 | return _ParsedIssueNumberArgument( |
| 2849 | issue=int(match.group(2)), |
| 2850 | patchset=int(match.group(4)) if match.group(4) else None, |
Andrii Shyshkalov | 90f3192 | 2017-04-10 16:10:21 +0200 | [diff] [blame] | 2851 | hostname=parsed_url.netloc, |
| 2852 | codereview='gerrit') |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2853 | return None |
| 2854 | |
tandrii | 16e0b4e | 2016-06-07 10:34:28 -0700 | [diff] [blame] | 2855 | def _GerritCommitMsgHookCheck(self, offer_removal): |
| 2856 | hook = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg') |
| 2857 | if not os.path.exists(hook): |
| 2858 | return |
| 2859 | # Crude attempt to distinguish Gerrit Codereview hook from potentially |
| 2860 | # custom developer made one. |
| 2861 | data = gclient_utils.FileRead(hook) |
| 2862 | if not('From Gerrit Code Review' in data and 'add_ChangeId()' in data): |
| 2863 | return |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2864 | print('WARNING: You have Gerrit commit-msg hook installed.\n' |
qyearsley | 12fa6ff | 2016-08-24 09:18:40 -0700 | [diff] [blame] | 2865 | 'It is not necessary for uploading with git cl in squash mode, ' |
tandrii | 16e0b4e | 2016-06-07 10:34:28 -0700 | [diff] [blame] | 2866 | 'and may interfere with it in subtle ways.\n' |
| 2867 | 'We recommend you remove the commit-msg hook.') |
| 2868 | if offer_removal: |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2869 | if ask_for_explicit_yes('Do you want to remove it now?'): |
tandrii | 16e0b4e | 2016-06-07 10:34:28 -0700 | [diff] [blame] | 2870 | gclient_utils.rm_file_or_tree(hook) |
| 2871 | print('Gerrit commit-msg hook removed.') |
| 2872 | else: |
| 2873 | print('OK, will keep Gerrit commit-msg hook in place.') |
| 2874 | |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2875 | def CMDUploadChange(self, options, git_diff_args, custom_cl_base, change): |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2876 | """Upload the current branch to Gerrit.""" |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2877 | if options.squash and options.no_squash: |
| 2878 | DieWithError('Can only use one of --squash or --no-squash') |
tandrii | a60502f | 2016-06-20 02:01:53 -0700 | [diff] [blame] | 2879 | |
| 2880 | if not options.squash and not options.no_squash: |
| 2881 | # Load default for user, repo, squash=true, in this order. |
| 2882 | options.squash = settings.GetSquashGerritUploads() |
| 2883 | elif options.no_squash: |
| 2884 | options.squash = False |
tandrii | 26f3e4e | 2016-06-10 08:37:04 -0700 | [diff] [blame] | 2885 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2886 | remote, remote_branch = self.GetRemoteBranch() |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 2887 | branch = GetTargetRef(remote, remote_branch, options.target_branch) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2888 | |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2889 | # This may be None; default fallback value is determined in logic below. |
| 2890 | title = options.title |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 2891 | automatic_title = False |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2892 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2893 | if options.squash: |
tandrii | 16e0b4e | 2016-06-07 10:34:28 -0700 | [diff] [blame] | 2894 | self._GerritCommitMsgHookCheck(offer_removal=not options.force) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2895 | if self.GetIssue(): |
| 2896 | # Try to get the message from a previous upload. |
| 2897 | message = self.GetDescription() |
| 2898 | if not message: |
| 2899 | DieWithError( |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2900 | 'failed to fetch description from current Gerrit change %d\n' |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2901 | '%s' % (self.GetIssue(), self.GetIssueURL())) |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2902 | if not title: |
Andrii Shyshkalov | 2d8a207 | 2017-04-10 15:02:18 +0200 | [diff] [blame] | 2903 | if options.message: |
Aaron Gable | 7303dcb | 2017-06-07 14:17:32 -0700 | [diff] [blame] | 2904 | # When uploading a subsequent patchset, -m|--message is taken |
| 2905 | # as the patchset title if --title was not provided. |
| 2906 | title = options.message.strip() |
Andrii Shyshkalov | 2d8a207 | 2017-04-10 15:02:18 +0200 | [diff] [blame] | 2907 | else: |
| 2908 | default_title = RunGit( |
| 2909 | ['show', '-s', '--format=%s', 'HEAD']).strip() |
Aaron Gable | 7303dcb | 2017-06-07 14:17:32 -0700 | [diff] [blame] | 2910 | if options.force: |
| 2911 | title = default_title |
| 2912 | else: |
| 2913 | title = ask_for_data( |
| 2914 | 'Title for patchset [%s]: ' % default_title) or default_title |
| 2915 | if title == default_title: |
| 2916 | automatic_title = True |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2917 | change_id = self._GetChangeDetail()['change_id'] |
| 2918 | while True: |
| 2919 | footer_change_ids = git_footers.get_footer_change_id(message) |
| 2920 | if footer_change_ids == [change_id]: |
| 2921 | break |
| 2922 | if not footer_change_ids: |
| 2923 | message = git_footers.add_footer_change_id(message, change_id) |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 2924 | print('WARNING: appended missing Change-Id to change description.') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2925 | continue |
| 2926 | # There is already a valid footer but with different or several ids. |
| 2927 | # Doing this automatically is non-trivial as we don't want to lose |
| 2928 | # existing other footers, yet we want to append just 1 desired |
| 2929 | # Change-Id. Thus, just create a new footer, but let user verify the |
| 2930 | # new description. |
| 2931 | message = '%s\n\nChange-Id: %s' % (message, change_id) |
| 2932 | print( |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2933 | 'WARNING: change %s has Change-Id footer(s):\n' |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2934 | ' %s\n' |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 2935 | 'but change has Change-Id %s, according to Gerrit.\n' |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2936 | 'Please, check the proposed correction to the description, ' |
| 2937 | 'and edit it if necessary but keep the "Change-Id: %s" footer\n' |
| 2938 | % (self.GetIssue(), '\n '.join(footer_change_ids), change_id, |
| 2939 | change_id)) |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 2940 | confirm_or_exit(action='edit') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2941 | if not options.force: |
| 2942 | change_desc = ChangeDescription(message) |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 2943 | change_desc.prompt(bug=options.bug) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2944 | message = change_desc.description |
| 2945 | if not message: |
| 2946 | DieWithError("Description is empty. Aborting...") |
| 2947 | # Continue the while loop. |
| 2948 | # Sanity check of this code - we should end up with proper message |
| 2949 | # footer. |
| 2950 | assert [change_id] == git_footers.get_footer_change_id(message) |
| 2951 | change_desc = ChangeDescription(message) |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2952 | else: # if not self.GetIssue() |
| 2953 | if options.message: |
| 2954 | message = options.message |
| 2955 | else: |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2956 | message = CreateDescriptionFromLog(git_diff_args) |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2957 | if options.title: |
| 2958 | message = options.title + '\n\n' + message |
| 2959 | change_desc = ChangeDescription(message) |
Andrii Shyshkalov | 8c90d03 | 2017-04-19 21:27:26 +0200 | [diff] [blame] | 2960 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2961 | if not options.force: |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 2962 | change_desc.prompt(bug=options.bug) |
Aaron Gable | b56ad33 | 2017-01-06 15:24:31 -0800 | [diff] [blame] | 2963 | # On first upload, patchset title is always this string, while |
| 2964 | # --title flag gets converted to first line of message. |
| 2965 | title = 'Initial upload' |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 2966 | automatic_title = True |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2967 | if not change_desc.description: |
| 2968 | DieWithError("Description is empty. Aborting...") |
Andrii Shyshkalov | 8c90d03 | 2017-04-19 21:27:26 +0200 | [diff] [blame] | 2969 | change_ids = git_footers.get_footer_change_id(change_desc.description) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2970 | if len(change_ids) > 1: |
| 2971 | DieWithError('too many Change-Id footers, at most 1 allowed.') |
| 2972 | if not change_ids: |
| 2973 | # Generate the Change-Id automatically. |
Andrii Shyshkalov | 8c90d03 | 2017-04-19 21:27:26 +0200 | [diff] [blame] | 2974 | change_desc.set_description(git_footers.add_footer_change_id( |
| 2975 | change_desc.description, |
| 2976 | GenerateGerritChangeId(change_desc.description))) |
| 2977 | change_ids = git_footers.get_footer_change_id(change_desc.description) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2978 | assert len(change_ids) == 1 |
| 2979 | change_id = change_ids[0] |
| 2980 | |
Robert Iannucci | db02dd0 | 2017-04-19 12:18:20 -0700 | [diff] [blame] | 2981 | if options.reviewers or options.tbrs or options.add_owners_to: |
| 2982 | change_desc.update_reviewers(options.reviewers, options.tbrs, |
| 2983 | options.add_owners_to, change) |
| 2984 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2985 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2986 | parent = self._ComputeParent(remote, upstream_branch, custom_cl_base, |
| 2987 | options.force, change_desc) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2988 | tree = RunGit(['rev-parse', 'HEAD:']).strip() |
| 2989 | ref_to_push = RunGit(['commit-tree', tree, '-p', parent, |
Robert Iannucci | db02dd0 | 2017-04-19 12:18:20 -0700 | [diff] [blame] | 2990 | '-m', change_desc.description]).strip() |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2991 | else: |
| 2992 | change_desc = ChangeDescription( |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2993 | options.message or CreateDescriptionFromLog(git_diff_args)) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2994 | if not change_desc.description: |
| 2995 | DieWithError("Description is empty. Aborting...") |
| 2996 | |
| 2997 | if not git_footers.get_footer_change_id(change_desc.description): |
| 2998 | DownloadGerritHook(False) |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 2999 | change_desc.set_description( |
| 3000 | self._AddChangeIdToCommitMessage(options, git_diff_args)) |
Robert Iannucci | db02dd0 | 2017-04-19 12:18:20 -0700 | [diff] [blame] | 3001 | if options.reviewers or options.tbrs or options.add_owners_to: |
| 3002 | change_desc.update_reviewers(options.reviewers, options.tbrs, |
| 3003 | options.add_owners_to, change) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3004 | ref_to_push = 'HEAD' |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 3005 | # For no-squash mode, we assume the remote called "origin" is the one we |
| 3006 | # want. It is not worthwhile to support different workflows for |
| 3007 | # no-squash mode. |
| 3008 | parent = 'origin/%s' % branch |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3009 | change_id = git_footers.get_footer_change_id(change_desc.description)[0] |
| 3010 | |
| 3011 | assert change_desc |
| 3012 | commits = RunGitSilent(['rev-list', '%s..%s' % (parent, |
| 3013 | ref_to_push)]).splitlines() |
| 3014 | if len(commits) > 1: |
| 3015 | print('WARNING: This will upload %d commits. Run the following command ' |
| 3016 | 'to see which commits will be uploaded: ' % len(commits)) |
| 3017 | print('git log %s..%s' % (parent, ref_to_push)) |
| 3018 | print('You can also use `git squash-branch` to squash these into a ' |
| 3019 | 'single commit.') |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 3020 | confirm_or_exit(action='upload') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3021 | |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 3022 | if options.reviewers or options.tbrs or options.add_owners_to: |
| 3023 | change_desc.update_reviewers(options.reviewers, options.tbrs, |
| 3024 | options.add_owners_to, change) |
| 3025 | |
tandrii@chromium.org | bf766ba | 2016-04-13 12:51:23 +0000 | [diff] [blame] | 3026 | # Extra options that can be specified at push time. Doc: |
| 3027 | # https://gerrit-review.googlesource.com/Documentation/user-upload.html |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 3028 | refspec_opts = [] |
Andrii Shyshkalov | 2d8a207 | 2017-04-10 15:02:18 +0200 | [diff] [blame] | 3029 | |
Aaron Gable | 844cf29 | 2017-06-28 11:32:59 -0700 | [diff] [blame] | 3030 | # By default, new changes are started in WIP mode, and subsequent patchsets |
| 3031 | # don't send email. At any time, passing --send-mail will mark the change |
| 3032 | # ready and send email for that particular patch. |
Aaron Gable | afd5277 | 2017-06-27 16:40:10 -0700 | [diff] [blame] | 3033 | if options.send_mail: |
| 3034 | refspec_opts.append('ready') |
Aaron Gable | 844cf29 | 2017-06-28 11:32:59 -0700 | [diff] [blame] | 3035 | refspec_opts.append('notify=ALL') |
Aaron Gable | afd5277 | 2017-06-27 16:40:10 -0700 | [diff] [blame] | 3036 | else: |
Aaron Gable | 844cf29 | 2017-06-28 11:32:59 -0700 | [diff] [blame] | 3037 | if not self.GetIssue(): |
| 3038 | refspec_opts.append('wip') |
| 3039 | else: |
| 3040 | refspec_opts.append('notify=NONE') |
Aaron Gable | 70f4e24 | 2017-06-26 10:45:59 -0700 | [diff] [blame] | 3041 | |
Andrii Shyshkalov | 2d8a207 | 2017-04-10 15:02:18 +0200 | [diff] [blame] | 3042 | # TODO(tandrii): options.message should be posted as a comment |
Aaron Gable | e5adf61 | 2017-07-14 10:43:58 -0700 | [diff] [blame^] | 3043 | # 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] | 3044 | |
Aaron Gable | 9b713dd | 2016-12-14 16:04:21 -0800 | [diff] [blame] | 3045 | if title: |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 3046 | if not re.match(r'^[\w ]+$', title): |
| 3047 | title = re.sub(r'[^\w ]', '', title) |
| 3048 | if not automatic_title: |
| 3049 | print('WARNING: Patchset title may only contain alphanumeric chars ' |
| 3050 | 'and spaces. You can edit it in the UI. ' |
| 3051 | 'See https://crbug.com/663787.\n' |
| 3052 | 'Cleaned up title: %s' % title) |
| 3053 | # Per doc, spaces must be converted to underscores, and Gerrit will do the |
| 3054 | # reverse on its side. |
| 3055 | refspec_opts.append('m=' + title.replace(' ', '_')) |
tandrii@chromium.org | bf766ba | 2016-04-13 12:51:23 +0000 | [diff] [blame] | 3056 | |
agable | c678797 | 2016-09-09 16:13:34 -0700 | [diff] [blame] | 3057 | if options.private: |
Aaron Gable | b02daf0 | 2017-05-23 11:53:46 -0700 | [diff] [blame] | 3058 | refspec_opts.append('private') |
agable | c678797 | 2016-09-09 16:13:34 -0700 | [diff] [blame] | 3059 | |
rmistry | 9eadede | 2016-09-19 11:22:43 -0700 | [diff] [blame] | 3060 | if options.topic: |
| 3061 | # Documentation on Gerrit topics is here: |
| 3062 | # https://gerrit-review.googlesource.com/Documentation/user-upload.html#topic |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 3063 | refspec_opts.append('topic=%s' % options.topic) |
rmistry | 9eadede | 2016-09-19 11:22:43 -0700 | [diff] [blame] | 3064 | |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 3065 | refspec_suffix = '' |
| 3066 | if refspec_opts: |
| 3067 | refspec_suffix = '%' + ','.join(refspec_opts) |
| 3068 | assert ' ' not in refspec_suffix, ( |
| 3069 | 'spaces not allowed in refspec: "%s"' % refspec_suffix) |
| 3070 | refspec = '%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix) |
| 3071 | |
Andrii Shyshkalov | 7d51883 | 2016-12-15 20:48:21 +0100 | [diff] [blame] | 3072 | try: |
| 3073 | push_stdout = gclient_utils.CheckCallAndFilter( |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 3074 | ['git', 'push', self.GetRemoteUrl(), refspec], |
| 3075 | print_stdout=True, |
Andrii Shyshkalov | 7d51883 | 2016-12-15 20:48:21 +0100 | [diff] [blame] | 3076 | # Flush after every line: useful for seeing progress when running as |
| 3077 | # recipe. |
| 3078 | filter_fn=lambda _: sys.stdout.flush()) |
| 3079 | except subprocess2.CalledProcessError: |
| 3080 | DieWithError('Failed to create a change. Please examine output above ' |
Andrii Shyshkalov | 9d93221 | 2017-04-10 14:28:23 +0200 | [diff] [blame] | 3081 | 'for the reason of the failure.\n' |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3082 | 'Hint: run command below to diagnose common Git/Gerrit ' |
Andrii Shyshkalov | 9d93221 | 2017-04-10 14:28:23 +0200 | [diff] [blame] | 3083 | 'credential problems:\n' |
| 3084 | ' git cl creds-check\n', |
| 3085 | change_desc) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3086 | |
| 3087 | if options.squash: |
| 3088 | regex = re.compile(r'remote:\s+https?://[\w\-\.\/]*/(\d+)\s.*') |
| 3089 | change_numbers = [m.group(1) |
| 3090 | for m in map(regex.match, push_stdout.splitlines()) |
| 3091 | if m] |
| 3092 | if len(change_numbers) != 1: |
| 3093 | DieWithError( |
| 3094 | ('Created|Updated %d issues on Gerrit, but only 1 expected.\n' |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 3095 | 'Change-Id: %s') % (len(change_numbers), change_id), change_desc) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3096 | self.SetIssue(change_numbers[0]) |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 3097 | self._GitSetBranchConfigValue('gerritsquashhash', ref_to_push) |
tandrii | 8818977 | 2016-09-29 04:29:57 -0700 | [diff] [blame] | 3098 | |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 3099 | reviewers = sorted(change_desc.get_reviewers()) |
| 3100 | |
tandrii | 8818977 | 2016-09-29 04:29:57 -0700 | [diff] [blame] | 3101 | # Add cc's from the CC_LIST and --cc flag (if any). |
Aaron Gable | d105249 | 2017-05-15 15:05:34 -0700 | [diff] [blame] | 3102 | if not options.private: |
| 3103 | cc = self.GetCCList().split(',') |
| 3104 | else: |
| 3105 | cc = [] |
tandrii | 8818977 | 2016-09-29 04:29:57 -0700 | [diff] [blame] | 3106 | if options.cc: |
| 3107 | cc.extend(options.cc) |
| 3108 | cc = filter(None, [email.strip() for email in cc]) |
bradnelson | d975b30 | 2016-10-23 12:20:23 -0700 | [diff] [blame] | 3109 | if change_desc.get_cced(): |
| 3110 | cc.extend(change_desc.get_cced()) |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 3111 | |
| 3112 | gerrit_util.AddReviewers( |
| 3113 | self._GetGerritHost(), self.GetIssue(), reviewers, cc, |
| 3114 | notify=bool(options.send_mail)) |
| 3115 | |
Aaron Gable | fd23808 | 2017-06-07 13:42:34 -0700 | [diff] [blame] | 3116 | if change_desc.get_reviewers(tbr_only=True): |
| 3117 | print('Adding self-LGTM (Code-Review +1) because of TBRs.') |
| 3118 | gerrit_util.SetReview( |
| 3119 | self._GetGerritHost(), self.GetIssue(), |
Aaron Gable | 75e7872 | 2017-06-09 10:40:16 -0700 | [diff] [blame] | 3120 | labels={'Code-Review': 1}, notify=bool(options.send_mail)) |
Aaron Gable | fd23808 | 2017-06-07 13:42:34 -0700 | [diff] [blame] | 3121 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3122 | return 0 |
| 3123 | |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 3124 | def _ComputeParent(self, remote, upstream_branch, custom_cl_base, force, |
| 3125 | change_desc): |
| 3126 | """Computes parent of the generated commit to be uploaded to Gerrit. |
| 3127 | |
| 3128 | Returns revision or a ref name. |
| 3129 | """ |
| 3130 | if custom_cl_base: |
| 3131 | # Try to avoid creating additional unintended CLs when uploading, unless |
| 3132 | # user wants to take this risk. |
| 3133 | local_ref_of_target_remote = self.GetRemoteBranch()[1] |
| 3134 | code, _ = RunGitWithCode(['merge-base', '--is-ancestor', custom_cl_base, |
| 3135 | local_ref_of_target_remote]) |
| 3136 | if code == 1: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3137 | print('\nWARNING: Manually specified base of this CL `%s` ' |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 3138 | 'doesn\'t seem to belong to target remote branch `%s`.\n\n' |
| 3139 | 'If you proceed with upload, more than 1 CL may be created by ' |
| 3140 | 'Gerrit as a result, in turn confusing or crashing git cl.\n\n' |
| 3141 | 'If you are certain that specified base `%s` has already been ' |
| 3142 | 'uploaded to Gerrit as another CL, you may proceed.\n' % |
| 3143 | (custom_cl_base, local_ref_of_target_remote, custom_cl_base)) |
| 3144 | if not force: |
| 3145 | confirm_or_exit( |
| 3146 | 'Do you take responsibility for cleaning up potential mess ' |
| 3147 | 'resulting from proceeding with upload?', |
| 3148 | action='upload') |
| 3149 | return custom_cl_base |
| 3150 | |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3151 | if remote != '.': |
| 3152 | return self.GetCommonAncestorWithUpstream() |
| 3153 | |
| 3154 | # If our upstream branch is local, we base our squashed commit on its |
| 3155 | # squashed version. |
| 3156 | upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch) |
| 3157 | |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3158 | if upstream_branch_name == 'master': |
Aaron Gable | 0bbd1c2 | 2017-05-08 14:37:08 -0700 | [diff] [blame] | 3159 | return self.GetCommonAncestorWithUpstream() |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3160 | |
| 3161 | # Check the squashed hash of the parent. |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 3162 | # TODO(tandrii): consider checking parent change in Gerrit and using its |
| 3163 | # hash if tree hash of latest parent revision (patchset) in Gerrit matches |
| 3164 | # the tree hash of the parent branch. The upside is less likely bogus |
| 3165 | # requests to reupload parent change just because it's uploadhash is |
| 3166 | # missing, yet the downside likely exists, too (albeit unknown to me yet). |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3167 | parent = RunGit(['config', |
| 3168 | 'branch.%s.gerritsquashhash' % upstream_branch_name], |
| 3169 | error_ok=True).strip() |
| 3170 | # Verify that the upstream branch has been uploaded too, otherwise |
| 3171 | # Gerrit will create additional CLs when uploading. |
| 3172 | if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) != |
| 3173 | RunGitSilent(['rev-parse', parent + ':'])): |
| 3174 | DieWithError( |
| 3175 | '\nUpload upstream branch %s first.\n' |
| 3176 | 'It is likely that this branch has been rebased since its last ' |
| 3177 | 'upload, so you just need to upload it again.\n' |
| 3178 | '(If you uploaded it with --no-squash, then branch dependencies ' |
| 3179 | 'are not supported, and you should reupload with --squash.)' |
| 3180 | % upstream_branch_name, |
| 3181 | change_desc) |
| 3182 | return parent |
| 3183 | |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 3184 | def _AddChangeIdToCommitMessage(self, options, args): |
| 3185 | """Re-commits using the current message, assumes the commit hook is in |
| 3186 | place. |
| 3187 | """ |
| 3188 | log_desc = options.message or CreateDescriptionFromLog(args) |
| 3189 | git_command = ['commit', '--amend', '-m', log_desc] |
| 3190 | RunGit(git_command) |
| 3191 | new_log_desc = CreateDescriptionFromLog(args) |
| 3192 | if git_footers.get_footer_change_id(new_log_desc): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 3193 | print('git-cl: Added Change-Id to commit message.') |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 3194 | return new_log_desc |
| 3195 | else: |
tandrii@chromium.org | b067ec5 | 2016-05-31 15:24:44 +0000 | [diff] [blame] | 3196 | DieWithError('ERROR: Gerrit commit-msg hook not installed.') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3197 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 3198 | def SetCQState(self, new_state): |
| 3199 | """Sets the Commit-Queue label assuming canonical CQ config for Gerrit.""" |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 3200 | vote_map = { |
| 3201 | _CQState.NONE: 0, |
| 3202 | _CQState.DRY_RUN: 1, |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 3203 | _CQState.COMMIT: 2, |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 3204 | } |
Andrii Shyshkalov | 828701b | 2016-12-09 10:46:47 +0100 | [diff] [blame] | 3205 | kwargs = {'labels': {'Commit-Queue': vote_map[new_state]}} |
| 3206 | if new_state == _CQState.DRY_RUN: |
| 3207 | # Don't spam everybody reviewer/owner. |
Aaron Gable | 75e7872 | 2017-06-09 10:40:16 -0700 | [diff] [blame] | 3208 | kwargs['notify'] = False |
Andrii Shyshkalov | 828701b | 2016-12-09 10:46:47 +0100 | [diff] [blame] | 3209 | gerrit_util.SetReview(self._GetGerritHost(), self.GetIssue(), **kwargs) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 3210 | |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 3211 | def CannotTriggerTryJobReason(self): |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3212 | try: |
| 3213 | data = self._GetChangeDetail() |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 3214 | except GerritChangeNotExists: |
| 3215 | return 'Gerrit doesn\'t know about your change %s' % self.GetIssue() |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3216 | |
| 3217 | if data['status'] in ('ABANDONED', 'MERGED'): |
| 3218 | return 'CL %s is closed' % self.GetIssue() |
| 3219 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3220 | def GetTryJobProperties(self, patchset=None): |
| 3221 | """Returns dictionary of properties to launch try job.""" |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3222 | data = self._GetChangeDetail(['ALL_REVISIONS']) |
| 3223 | patchset = int(patchset or self.GetPatchset()) |
| 3224 | assert patchset |
| 3225 | revision_data = None # Pylint wants it to be defined. |
| 3226 | for revision_data in data['revisions'].itervalues(): |
| 3227 | if int(revision_data['_number']) == patchset: |
| 3228 | break |
| 3229 | else: |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 3230 | raise Exception('Patchset %d is not known in Gerrit change %d' % |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3231 | (patchset, self.GetIssue())) |
| 3232 | return { |
| 3233 | 'patch_issue': self.GetIssue(), |
| 3234 | 'patch_set': patchset or self.GetPatchset(), |
| 3235 | 'patch_project': data['project'], |
| 3236 | 'patch_storage': 'gerrit', |
| 3237 | 'patch_ref': revision_data['fetch']['http']['ref'], |
| 3238 | 'patch_repository_url': revision_data['fetch']['http']['url'], |
| 3239 | 'patch_gerrit_url': self.GetCodereviewServer(), |
| 3240 | } |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 3241 | |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 3242 | def GetIssueOwner(self): |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3243 | return self._GetChangeDetail(['DETAILED_ACCOUNTS'])['owner']['email'] |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 3244 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 3245 | |
| 3246 | _CODEREVIEW_IMPLEMENTATIONS = { |
| 3247 | 'rietveld': _RietveldChangelistImpl, |
| 3248 | 'gerrit': _GerritChangelistImpl, |
| 3249 | } |
| 3250 | |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 3251 | |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 3252 | def _add_codereview_issue_select_options(parser, extra=""): |
| 3253 | _add_codereview_select_options(parser) |
| 3254 | |
| 3255 | text = ('Operate on this issue number instead of the current branch\'s ' |
| 3256 | 'implicit issue.') |
| 3257 | if extra: |
| 3258 | text += ' '+extra |
| 3259 | parser.add_option('-i', '--issue', type=int, help=text) |
| 3260 | |
| 3261 | |
| 3262 | def _process_codereview_issue_select_options(parser, options): |
| 3263 | _process_codereview_select_options(parser, options) |
| 3264 | if options.issue is not None and not options.forced_codereview: |
| 3265 | parser.error('--issue must be specified with either --rietveld or --gerrit') |
| 3266 | |
| 3267 | |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3268 | def _add_codereview_select_options(parser): |
| 3269 | """Appends --gerrit and --rietveld options to force specific codereview.""" |
| 3270 | parser.codereview_group = optparse.OptionGroup( |
| 3271 | parser, 'EXPERIMENTAL! Codereview override options') |
| 3272 | parser.add_option_group(parser.codereview_group) |
| 3273 | parser.codereview_group.add_option( |
| 3274 | '--gerrit', action='store_true', |
| 3275 | help='Force the use of Gerrit for codereview') |
| 3276 | parser.codereview_group.add_option( |
| 3277 | '--rietveld', action='store_true', |
| 3278 | help='Force the use of Rietveld for codereview') |
| 3279 | |
| 3280 | |
| 3281 | def _process_codereview_select_options(parser, options): |
| 3282 | if options.gerrit and options.rietveld: |
| 3283 | parser.error('Options --gerrit and --rietveld are mutually exclusive') |
| 3284 | options.forced_codereview = None |
| 3285 | if options.gerrit: |
| 3286 | options.forced_codereview = 'gerrit' |
| 3287 | elif options.rietveld: |
| 3288 | options.forced_codereview = 'rietveld' |
| 3289 | |
| 3290 | |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3291 | def _get_bug_line_values(default_project, bugs): |
| 3292 | """Given default_project and comma separated list of bugs, yields bug line |
| 3293 | values. |
| 3294 | |
| 3295 | Each bug can be either: |
| 3296 | * a number, which is combined with default_project |
| 3297 | * string, which is left as is. |
| 3298 | |
| 3299 | This function may produce more than one line, because bugdroid expects one |
| 3300 | project per line. |
| 3301 | |
| 3302 | >>> list(_get_bug_line_values('v8', '123,chromium:789')) |
| 3303 | ['v8:123', 'chromium:789'] |
| 3304 | """ |
| 3305 | default_bugs = [] |
| 3306 | others = [] |
| 3307 | for bug in bugs.split(','): |
| 3308 | bug = bug.strip() |
| 3309 | if bug: |
| 3310 | try: |
| 3311 | default_bugs.append(int(bug)) |
| 3312 | except ValueError: |
| 3313 | others.append(bug) |
| 3314 | |
| 3315 | if default_bugs: |
| 3316 | default_bugs = ','.join(map(str, default_bugs)) |
| 3317 | if default_project: |
| 3318 | yield '%s:%s' % (default_project, default_bugs) |
| 3319 | else: |
| 3320 | yield default_bugs |
| 3321 | for other in sorted(others): |
| 3322 | # Don't bother finding common prefixes, CLs with >2 bugs are very very rare. |
| 3323 | yield other |
| 3324 | |
| 3325 | |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3326 | class ChangeDescription(object): |
| 3327 | """Contains a parsed form of the change description.""" |
maruel@chromium.org | c6f60e8 | 2013-04-19 17:01:57 +0000 | [diff] [blame] | 3328 | R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$' |
bradnelson | d975b30 | 2016-10-23 12:20:23 -0700 | [diff] [blame] | 3329 | CC_LINE = r'^[ \t]*(CC)[ \t]*=[ \t]*(.*?)[ \t]*$' |
Aaron Gable | 3a16ed1 | 2017-03-23 10:51:55 -0700 | [diff] [blame] | 3330 | BUG_LINE = r'^[ \t]*(?:(BUG)[ \t]*=|Bug:)[ \t]*(.*?)[ \t]*$' |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3331 | CHERRY_PICK_LINE = r'^\(cherry picked from commit [a-fA-F0-9]{40}\)$' |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3332 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3333 | def __init__(self, description): |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3334 | self._description_lines = (description or '').strip().splitlines() |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3335 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3336 | @property # www.logilab.org/ticket/89786 |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 3337 | def description(self): # pylint: disable=method-hidden |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3338 | return '\n'.join(self._description_lines) |
| 3339 | |
| 3340 | def set_description(self, desc): |
| 3341 | if isinstance(desc, basestring): |
| 3342 | lines = desc.splitlines() |
| 3343 | else: |
| 3344 | lines = [line.rstrip() for line in desc] |
| 3345 | while lines and not lines[0]: |
| 3346 | lines.pop(0) |
| 3347 | while lines and not lines[-1]: |
| 3348 | lines.pop(-1) |
| 3349 | self._description_lines = lines |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3350 | |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3351 | def update_reviewers(self, reviewers, tbrs, add_owners_to=None, change=None): |
| 3352 | """Rewrites the R=/TBR= line(s) as a single line each. |
| 3353 | |
| 3354 | Args: |
| 3355 | reviewers (list(str)) - list of additional emails to use for reviewers. |
| 3356 | tbrs (list(str)) - list of additional emails to use for TBRs. |
| 3357 | add_owners_to (None|'R'|'TBR') - Pass to do an OWNERS lookup for files in |
| 3358 | the change that are missing OWNER coverage. If this is not None, you |
| 3359 | must also pass a value for `change`. |
| 3360 | change (Change) - The Change that should be used for OWNERS lookups. |
| 3361 | """ |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3362 | assert isinstance(reviewers, list), reviewers |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3363 | assert isinstance(tbrs, list), tbrs |
| 3364 | |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 3365 | assert add_owners_to in (None, 'TBR', 'R'), add_owners_to |
Robert Iannucci | a28592e | 2017-04-18 13:14:49 -0700 | [diff] [blame] | 3366 | assert not add_owners_to or change, add_owners_to |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3367 | |
| 3368 | if not reviewers and not tbrs and not add_owners_to: |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3369 | return |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3370 | |
| 3371 | reviewers = set(reviewers) |
| 3372 | tbrs = set(tbrs) |
| 3373 | LOOKUP = { |
| 3374 | 'TBR': tbrs, |
| 3375 | 'R': reviewers, |
| 3376 | } |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3377 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3378 | # 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] | 3379 | regexp = re.compile(self.R_LINE) |
| 3380 | matches = [regexp.match(line) for line in self._description_lines] |
| 3381 | new_desc = [l for i, l in enumerate(self._description_lines) |
| 3382 | if not matches[i]] |
| 3383 | self.set_description(new_desc) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3384 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3385 | # Construct new unified R= and TBR= lines. |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3386 | |
| 3387 | # 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] | 3388 | for match in matches: |
| 3389 | if not match: |
| 3390 | continue |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3391 | LOOKUP[match.group(1)].update(cleanup_list([match.group(2).strip()])) |
| 3392 | |
| 3393 | # Next, maybe fill in OWNERS coverage gaps to either tbrs/reviewers. |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 3394 | if add_owners_to: |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 3395 | owners_db = owners.Database(change.RepositoryRoot(), |
Jochen Eisinger | 72606f8 | 2017-04-04 10:44:18 +0200 | [diff] [blame] | 3396 | fopen=file, os_path=os.path) |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 3397 | missing_files = owners_db.files_not_covered_by(change.LocalPaths(), |
Robert Iannucci | 100aa21 | 2017-04-18 17:28:26 -0700 | [diff] [blame] | 3398 | (tbrs | reviewers)) |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3399 | LOOKUP[add_owners_to].update( |
| 3400 | owners_db.reviewers_for(missing_files, change.author_email)) |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 3401 | |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3402 | # If any folks ended up in both groups, remove them from tbrs. |
| 3403 | tbrs -= reviewers |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 3404 | |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 3405 | new_r_line = 'R=' + ', '.join(sorted(reviewers)) if reviewers else None |
| 3406 | new_tbr_line = 'TBR=' + ', '.join(sorted(tbrs)) if tbrs else None |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3407 | |
| 3408 | # Put the new lines in the description where the old first R= line was. |
| 3409 | line_loc = next((i for i, match in enumerate(matches) if match), -1) |
| 3410 | if 0 <= line_loc < len(self._description_lines): |
| 3411 | if new_tbr_line: |
| 3412 | self._description_lines.insert(line_loc, new_tbr_line) |
| 3413 | if new_r_line: |
| 3414 | self._description_lines.insert(line_loc, new_r_line) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3415 | else: |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3416 | if new_r_line: |
| 3417 | self.append_footer(new_r_line) |
| 3418 | if new_tbr_line: |
| 3419 | self.append_footer(new_tbr_line) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3420 | |
Aaron Gable | 3a16ed1 | 2017-03-23 10:51:55 -0700 | [diff] [blame] | 3421 | def prompt(self, bug=None, git_footer=True): |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3422 | """Asks the user to update the description.""" |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3423 | self.set_description([ |
| 3424 | '# Enter a description of the change.', |
| 3425 | '# This will be displayed on the codereview site.', |
| 3426 | '# 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] | 3427 | '#--------------------This line is 72 characters long' |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3428 | '--------------------', |
| 3429 | ] + self._description_lines) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3430 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3431 | regexp = re.compile(self.BUG_LINE) |
| 3432 | if not any((regexp.match(line) for line in self._description_lines)): |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3433 | prefix = settings.GetBugPrefix() |
| 3434 | values = list(_get_bug_line_values(prefix, bug or '')) or [prefix] |
Aaron Gable | 3a16ed1 | 2017-03-23 10:51:55 -0700 | [diff] [blame] | 3435 | if git_footer: |
| 3436 | self.append_footer('Bug: %s' % ', '.join(values)) |
| 3437 | else: |
| 3438 | for value in values: |
| 3439 | self.append_footer('BUG=%s' % value) |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3440 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3441 | content = gclient_utils.RunEditor(self.description, True, |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 3442 | git_editor=settings.GetGitEditor()) |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 3443 | if not content: |
| 3444 | DieWithError('Running editor failed') |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3445 | lines = content.splitlines() |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3446 | |
| 3447 | # Strip off comments. |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3448 | clean_lines = [line.rstrip() for line in lines if not line.startswith('#')] |
| 3449 | if not clean_lines: |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 3450 | DieWithError('No CL description, aborting') |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3451 | self.set_description(clean_lines) |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3452 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3453 | def append_footer(self, line): |
tandrii@chromium.org | 601e1d1 | 2016-06-03 13:03:54 +0000 | [diff] [blame] | 3454 | """Adds a footer line to the description. |
| 3455 | |
| 3456 | Differentiates legacy "KEY=xxx" footers (used to be called tags) and |
| 3457 | Gerrit's footers in the form of "Footer-Key: footer any value" and ensures |
| 3458 | that Gerrit footers are always at the end. |
| 3459 | """ |
| 3460 | parsed_footer_line = git_footers.parse_footer(line) |
| 3461 | if parsed_footer_line: |
| 3462 | # Line is a gerrit footer in the form: Footer-Key: any value. |
| 3463 | # Thus, must be appended observing Gerrit footer rules. |
| 3464 | self.set_description( |
| 3465 | git_footers.add_footer(self.description, |
| 3466 | key=parsed_footer_line[0], |
| 3467 | value=parsed_footer_line[1])) |
| 3468 | return |
| 3469 | |
| 3470 | if not self._description_lines: |
| 3471 | self._description_lines.append(line) |
| 3472 | return |
| 3473 | |
| 3474 | top_lines, gerrit_footers, _ = git_footers.split_footers(self.description) |
| 3475 | if gerrit_footers: |
| 3476 | # git_footers.split_footers ensures that there is an empty line before |
| 3477 | # actual (gerrit) footers, if any. We have to keep it that way. |
| 3478 | assert top_lines and top_lines[-1] == '' |
| 3479 | top_lines, separator = top_lines[:-1], top_lines[-1:] |
| 3480 | else: |
| 3481 | separator = [] # No need for separator if there are no gerrit_footers. |
| 3482 | |
| 3483 | prev_line = top_lines[-1] if top_lines else '' |
| 3484 | if (not presubmit_support.Change.TAG_LINE_RE.match(prev_line) or |
| 3485 | not presubmit_support.Change.TAG_LINE_RE.match(line)): |
| 3486 | top_lines.append('') |
| 3487 | top_lines.append(line) |
| 3488 | self._description_lines = top_lines + separator + gerrit_footers |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3489 | |
tandrii | 99a72f2 | 2016-08-17 14:33:24 -0700 | [diff] [blame] | 3490 | def get_reviewers(self, tbr_only=False): |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3491 | """Retrieves the list of reviewers.""" |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 3492 | matches = [re.match(self.R_LINE, line) for line in self._description_lines] |
tandrii | 99a72f2 | 2016-08-17 14:33:24 -0700 | [diff] [blame] | 3493 | reviewers = [match.group(2).strip() |
| 3494 | for match in matches |
| 3495 | 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] | 3496 | return cleanup_list(reviewers) |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3497 | |
bradnelson | d975b30 | 2016-10-23 12:20:23 -0700 | [diff] [blame] | 3498 | def get_cced(self): |
| 3499 | """Retrieves the list of reviewers.""" |
| 3500 | matches = [re.match(self.CC_LINE, line) for line in self._description_lines] |
| 3501 | cced = [match.group(2).strip() for match in matches if match] |
| 3502 | return cleanup_list(cced) |
| 3503 | |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3504 | def update_with_git_number_footers(self, parent_hash, parent_msg, dest_ref): |
| 3505 | """Updates this commit description given the parent. |
| 3506 | |
| 3507 | This is essentially what Gnumbd used to do. |
| 3508 | Consult https://goo.gl/WMmpDe for more details. |
| 3509 | """ |
| 3510 | assert parent_msg # No, orphan branch creation isn't supported. |
| 3511 | assert parent_hash |
| 3512 | assert dest_ref |
| 3513 | parent_footer_map = git_footers.parse_footers(parent_msg) |
| 3514 | # This will also happily parse svn-position, which GnumbD is no longer |
| 3515 | # supporting. While we'd generate correct footers, the verifier plugin |
| 3516 | # installed in Gerrit will block such commit (ie git push below will fail). |
| 3517 | parent_position = git_footers.get_position(parent_footer_map) |
| 3518 | |
| 3519 | # Cherry-picks may have last line obscuring their prior footers, |
| 3520 | # from git_footers perspective. This is also what Gnumbd did. |
| 3521 | cp_line = None |
| 3522 | if (self._description_lines and |
| 3523 | re.match(self.CHERRY_PICK_LINE, self._description_lines[-1])): |
| 3524 | cp_line = self._description_lines.pop() |
| 3525 | |
Andrii Shyshkalov | de37c01 | 2017-07-06 21:06:50 +0200 | [diff] [blame] | 3526 | top_lines, footer_lines, _ = git_footers.split_footers(self.description) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3527 | |
| 3528 | # Original-ify all Cr- footers, to avoid re-lands, cherry-picks, or just |
| 3529 | # user interference with actual footers we'd insert below. |
Andrii Shyshkalov | de37c01 | 2017-07-06 21:06:50 +0200 | [diff] [blame] | 3530 | for i, line in enumerate(footer_lines): |
| 3531 | k, v = git_footers.parse_footer(line) or (None, None) |
| 3532 | if k and k.startswith('Cr-'): |
| 3533 | footer_lines[i] = '%s: %s' % ('Cr-Original-' + k[len('Cr-'):], v) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3534 | |
| 3535 | # Add Position and Lineage footers based on the parent. |
Andrii Shyshkalov | b5effa1 | 2016-12-14 19:35:12 +0100 | [diff] [blame] | 3536 | lineage = list(reversed(parent_footer_map.get('Cr-Branched-From', []))) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3537 | if parent_position[0] == dest_ref: |
| 3538 | # Same branch as parent. |
| 3539 | number = int(parent_position[1]) + 1 |
| 3540 | else: |
| 3541 | number = 1 # New branch, and extra lineage. |
| 3542 | lineage.insert(0, '%s-%s@{#%d}' % (parent_hash, parent_position[0], |
| 3543 | int(parent_position[1]))) |
| 3544 | |
Andrii Shyshkalov | de37c01 | 2017-07-06 21:06:50 +0200 | [diff] [blame] | 3545 | footer_lines.append('Cr-Commit-Position: %s@{#%d}' % (dest_ref, number)) |
| 3546 | footer_lines.extend('Cr-Branched-From: %s' % v for v in lineage) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3547 | |
| 3548 | self._description_lines = top_lines |
| 3549 | if cp_line: |
| 3550 | self._description_lines.append(cp_line) |
| 3551 | if self._description_lines[-1] != '': |
| 3552 | self._description_lines.append('') # Ensure footer separator. |
Andrii Shyshkalov | de37c01 | 2017-07-06 21:06:50 +0200 | [diff] [blame] | 3553 | self._description_lines.extend(footer_lines) |
Andrii Shyshkalov | 15e50cc | 2016-12-02 14:34:08 +0100 | [diff] [blame] | 3554 | |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 3555 | |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 3556 | def get_approving_reviewers(props, disapproval=False): |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 3557 | """Retrieves the reviewers that approved a CL from the issue properties with |
| 3558 | messages. |
| 3559 | |
| 3560 | Note that the list may contain reviewers that are not committer, thus are not |
| 3561 | considered by the CQ. |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 3562 | |
| 3563 | 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] | 3564 | """ |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 3565 | approval_type = 'disapproval' if disapproval else 'approval' |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 3566 | return sorted( |
| 3567 | set( |
| 3568 | message['sender'] |
| 3569 | for message in props['messages'] |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 3570 | if message[approval_type] and message['sender'] in props['reviewers'] |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 3571 | ) |
| 3572 | ) |
| 3573 | |
| 3574 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3575 | def FindCodereviewSettingsFile(filename='codereview.settings'): |
| 3576 | """Finds the given file starting in the cwd and going up. |
| 3577 | |
| 3578 | Only looks up to the top of the repository unless an |
| 3579 | 'inherit-review-settings-ok' file exists in the root of the repository. |
| 3580 | """ |
| 3581 | inherit_ok_file = 'inherit-review-settings-ok' |
| 3582 | cwd = os.getcwd() |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 3583 | root = settings.GetRoot() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3584 | if os.path.isfile(os.path.join(root, inherit_ok_file)): |
| 3585 | root = '/' |
| 3586 | while True: |
| 3587 | if filename in os.listdir(cwd): |
| 3588 | if os.path.isfile(os.path.join(cwd, filename)): |
| 3589 | return open(os.path.join(cwd, filename)) |
| 3590 | if cwd == root: |
| 3591 | break |
| 3592 | cwd = os.path.dirname(cwd) |
| 3593 | |
| 3594 | |
| 3595 | def LoadCodereviewSettingsFromFile(fileobj): |
| 3596 | """Parse a codereview.settings file and updates hooks.""" |
maruel@chromium.org | 99ac1c5 | 2012-01-16 14:52:12 +0000 | [diff] [blame] | 3597 | keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3598 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3599 | def SetProperty(name, setting, unset_error_ok=False): |
| 3600 | fullname = 'rietveld.' + name |
| 3601 | if setting in keyvals: |
| 3602 | RunGit(['config', fullname, keyvals[setting]]) |
| 3603 | else: |
| 3604 | RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok) |
| 3605 | |
tandrii | 48df581 | 2016-10-17 03:55:37 -0700 | [diff] [blame] | 3606 | if not keyvals.get('GERRIT_HOST', False): |
| 3607 | SetProperty('server', 'CODE_REVIEW_SERVER') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3608 | # Only server setting is required. Other settings can be absent. |
| 3609 | # In that case, we ignore errors raised during option deletion attempt. |
| 3610 | SetProperty('cc', 'CC_LIST', unset_error_ok=True) |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 3611 | SetProperty('private', 'PRIVATE', unset_error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3612 | SetProperty('tree-status-url', 'STATUS', unset_error_ok=True) |
| 3613 | SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True) |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 3614 | SetProperty('bug-prefix', 'BUG_PREFIX', unset_error_ok=True) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 3615 | SetProperty('cpplint-regex', 'LINT_REGEX', unset_error_ok=True) |
| 3616 | SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX', unset_error_ok=True) |
sheyang@chromium.org | 152cf83 | 2014-06-11 21:37:49 +0000 | [diff] [blame] | 3617 | SetProperty('project', 'PROJECT', unset_error_ok=True) |
rmistry@google.com | 5626a92 | 2015-02-26 14:03:30 +0000 | [diff] [blame] | 3618 | SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK', |
| 3619 | unset_error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3620 | |
ukai@chromium.org | 7044efc | 2013-11-28 01:51:21 +0000 | [diff] [blame] | 3621 | if 'GERRIT_HOST' in keyvals: |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3622 | RunGit(['config', 'gerrit.host', keyvals['GERRIT_HOST']]) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3623 | |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 3624 | if 'GERRIT_SQUASH_UPLOADS' in keyvals: |
tandrii | 8dd81ea | 2016-06-16 13:24:23 -0700 | [diff] [blame] | 3625 | RunGit(['config', 'gerrit.squash-uploads', |
| 3626 | keyvals['GERRIT_SQUASH_UPLOADS']]) |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 3627 | |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 3628 | if 'GERRIT_SKIP_ENSURE_AUTHENTICATED' in keyvals: |
shinyak@chromium.org | 00dbccd | 2016-04-15 07:24:43 +0000 | [diff] [blame] | 3629 | RunGit(['config', 'gerrit.skip-ensure-authenticated', |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 3630 | keyvals['GERRIT_SKIP_ENSURE_AUTHENTICATED']]) |
| 3631 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3632 | if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals: |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 3633 | # should be of the form |
| 3634 | # PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof |
| 3635 | # ORIGIN_URL_CONFIG: http://src.chromium.org/git |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3636 | RunGit(['config', keyvals['PUSH_URL_CONFIG'], |
| 3637 | keyvals['ORIGIN_URL_CONFIG']]) |
| 3638 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3639 | |
joshua.lock@intel.com | 426f69b | 2012-08-02 23:41:49 +0000 | [diff] [blame] | 3640 | def urlretrieve(source, destination): |
| 3641 | """urllib is broken for SSL connections via a proxy therefore we |
| 3642 | can't use urllib.urlretrieve().""" |
| 3643 | with open(destination, 'w') as f: |
| 3644 | f.write(urllib2.urlopen(source).read()) |
| 3645 | |
| 3646 | |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3647 | def hasSheBang(fname): |
| 3648 | """Checks fname is a #! script.""" |
| 3649 | with open(fname) as f: |
| 3650 | return f.read(2).startswith('#!') |
| 3651 | |
| 3652 | |
bpastene@chromium.org | 917f0ff | 2016-04-05 00:45:30 +0000 | [diff] [blame] | 3653 | # TODO(bpastene) Remove once a cleaner fix to crbug.com/600473 presents itself. |
| 3654 | def DownloadHooks(*args, **kwargs): |
| 3655 | pass |
| 3656 | |
| 3657 | |
tandrii@chromium.org | 18630d6 | 2016-03-04 12:06:02 +0000 | [diff] [blame] | 3658 | def DownloadGerritHook(force): |
| 3659 | """Download and install Gerrit commit-msg hook. |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3660 | |
| 3661 | Args: |
| 3662 | force: True to update hooks. False to install hooks if not present. |
| 3663 | """ |
| 3664 | if not settings.GetIsGerrit(): |
| 3665 | return |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3666 | src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg' |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3667 | dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg') |
| 3668 | if not os.access(dst, os.X_OK): |
| 3669 | if os.path.exists(dst): |
| 3670 | if not force: |
| 3671 | return |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3672 | try: |
joshua.lock@intel.com | 426f69b | 2012-08-02 23:41:49 +0000 | [diff] [blame] | 3673 | urlretrieve(src, dst) |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3674 | if not hasSheBang(dst): |
| 3675 | DieWithError('Not a script: %s\n' |
| 3676 | 'You need to download from\n%s\n' |
| 3677 | 'into .git/hooks/commit-msg and ' |
| 3678 | 'chmod +x .git/hooks/commit-msg' % (dst, src)) |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3679 | os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) |
| 3680 | except Exception: |
| 3681 | if os.path.exists(dst): |
| 3682 | os.remove(dst) |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3683 | DieWithError('\nFailed to download hooks.\n' |
| 3684 | 'You need to download from\n%s\n' |
| 3685 | 'into .git/hooks/commit-msg and ' |
| 3686 | 'chmod +x .git/hooks/commit-msg' % src) |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3687 | |
| 3688 | |
tandrii@chromium.org | e7d3d16 | 2016-03-15 14:15:57 +0000 | [diff] [blame] | 3689 | def GetRietveldCodereviewSettingsInteractively(): |
| 3690 | """Prompt the user for settings.""" |
| 3691 | server = settings.GetDefaultServerUrl(error_ok=True) |
| 3692 | prompt = 'Rietveld server (host[:port])' |
| 3693 | prompt += ' [%s]' % (server or DEFAULT_SERVER) |
| 3694 | newserver = ask_for_data(prompt + ':') |
| 3695 | if not server and not newserver: |
| 3696 | newserver = DEFAULT_SERVER |
| 3697 | if newserver: |
| 3698 | newserver = gclient_utils.UpgradeToHttps(newserver) |
| 3699 | if newserver != server: |
| 3700 | RunGit(['config', 'rietveld.server', newserver]) |
| 3701 | |
| 3702 | def SetProperty(initial, caption, name, is_url): |
| 3703 | prompt = caption |
| 3704 | if initial: |
| 3705 | prompt += ' ("x" to clear) [%s]' % initial |
| 3706 | new_val = ask_for_data(prompt + ':') |
| 3707 | if new_val == 'x': |
| 3708 | RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True) |
| 3709 | elif new_val: |
| 3710 | if is_url: |
| 3711 | new_val = gclient_utils.UpgradeToHttps(new_val) |
| 3712 | if new_val != initial: |
| 3713 | RunGit(['config', 'rietveld.' + name, new_val]) |
| 3714 | |
| 3715 | SetProperty(settings.GetDefaultCCList(), 'CC list', 'cc', False) |
| 3716 | SetProperty(settings.GetDefaultPrivateFlag(), |
| 3717 | 'Private flag (rietveld only)', 'private', False) |
| 3718 | SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL', |
| 3719 | 'tree-status-url', False) |
| 3720 | SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url', True) |
| 3721 | SetProperty(settings.GetBugPrefix(), 'Bug Prefix', 'bug-prefix', False) |
| 3722 | SetProperty(settings.GetRunPostUploadHook(), 'Run Post Upload Hook', |
| 3723 | 'run-post-upload-hook', False) |
| 3724 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 3725 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3726 | class _GitCookiesChecker(object): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3727 | """Provides facilities for validating and suggesting fixes to .gitcookies.""" |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3728 | |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 3729 | _GOOGLESOURCE = 'googlesource.com' |
| 3730 | |
| 3731 | def __init__(self): |
| 3732 | # Cached list of [host, identity, source], where source is either |
| 3733 | # .gitcookies or .netrc. |
| 3734 | self._all_hosts = None |
| 3735 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3736 | def ensure_configured_gitcookies(self): |
| 3737 | """Runs checks and suggests fixes to make git use .gitcookies from default |
| 3738 | path.""" |
| 3739 | default = gerrit_util.CookiesAuthenticator.get_gitcookies_path() |
| 3740 | configured_path = RunGitSilent( |
| 3741 | ['config', '--global', 'http.cookiefile']).strip() |
Andrii Shyshkalov | 1e250cd | 2017-05-10 15:39:31 +0200 | [diff] [blame] | 3742 | configured_path = os.path.expanduser(configured_path) |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3743 | if configured_path: |
| 3744 | self._ensure_default_gitcookies_path(configured_path, default) |
| 3745 | else: |
| 3746 | self._configure_gitcookies_path(default) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3747 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3748 | @staticmethod |
| 3749 | def _ensure_default_gitcookies_path(configured_path, default_path): |
| 3750 | assert configured_path |
| 3751 | if configured_path == default_path: |
| 3752 | print('git is already configured to use your .gitcookies from %s' % |
| 3753 | configured_path) |
| 3754 | return |
| 3755 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 3756 | print('WARNING: You have configured custom path to .gitcookies: %s\n' |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3757 | 'Gerrit and other depot_tools expect .gitcookies at %s\n' % |
| 3758 | (configured_path, default_path)) |
| 3759 | |
| 3760 | if not os.path.exists(configured_path): |
| 3761 | print('However, your configured .gitcookies file is missing.') |
| 3762 | confirm_or_exit('Reconfigure git to use default .gitcookies?', |
| 3763 | action='reconfigure') |
| 3764 | RunGit(['config', '--global', 'http.cookiefile', default_path]) |
| 3765 | return |
| 3766 | |
| 3767 | if os.path.exists(default_path): |
| 3768 | print('WARNING: default .gitcookies file already exists %s' % |
| 3769 | default_path) |
| 3770 | DieWithError('Please delete %s manually and re-run git cl creds-check' % |
| 3771 | default_path) |
| 3772 | |
| 3773 | confirm_or_exit('Move existing .gitcookies to default location?', |
| 3774 | action='move') |
| 3775 | shutil.move(configured_path, default_path) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3776 | RunGit(['config', '--global', 'http.cookiefile', default_path]) |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3777 | print('Moved and reconfigured git to use .gitcookies from %s' % |
| 3778 | default_path) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3779 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3780 | @staticmethod |
| 3781 | def _configure_gitcookies_path(default_path): |
| 3782 | netrc_path = gerrit_util.CookiesAuthenticator.get_netrc_path() |
| 3783 | if os.path.exists(netrc_path): |
| 3784 | print('You seem to be using outdated .netrc for git credentials: %s' % |
| 3785 | netrc_path) |
| 3786 | print('This tool will guide you through setting up recommended ' |
| 3787 | '.gitcookies store for git credentials.\n' |
| 3788 | '\n' |
| 3789 | 'IMPORTANT: If something goes wrong and you decide to go back, do:\n' |
| 3790 | ' git config --global --unset http.cookiefile\n' |
| 3791 | ' mv %s %s.backup\n\n' % (default_path, default_path)) |
| 3792 | confirm_or_exit(action='setup .gitcookies') |
| 3793 | RunGit(['config', '--global', 'http.cookiefile', default_path]) |
| 3794 | print('Configured git to use .gitcookies from %s' % default_path) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3795 | |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 3796 | def get_hosts_with_creds(self, include_netrc=False): |
| 3797 | if self._all_hosts is None: |
| 3798 | a = gerrit_util.CookiesAuthenticator() |
| 3799 | self._all_hosts = [ |
| 3800 | (h, u, s) |
| 3801 | for h, u, s in itertools.chain( |
| 3802 | ((h, u, '.netrc') for h, (u, _, _) in a.netrc.hosts.iteritems()), |
| 3803 | ((h, u, '.gitcookies') for h, (u, _) in a.gitcookies.iteritems()) |
| 3804 | ) |
| 3805 | if h.endswith(self._GOOGLESOURCE) |
| 3806 | ] |
| 3807 | |
| 3808 | if include_netrc: |
| 3809 | return self._all_hosts |
| 3810 | return [(h, u, s) for h, u, s in self._all_hosts if s != '.netrc'] |
| 3811 | |
| 3812 | def print_current_creds(self, include_netrc=False): |
| 3813 | hosts = sorted(self.get_hosts_with_creds(include_netrc=include_netrc)) |
| 3814 | if not hosts: |
| 3815 | print('No Git/Gerrit credentials found') |
| 3816 | return |
| 3817 | lengths = [max(map(len, (row[i] for row in hosts))) for i in xrange(3)] |
| 3818 | header = [('Host', 'User', 'Which file'), |
| 3819 | ['=' * l for l in lengths]] |
| 3820 | for row in (header + hosts): |
| 3821 | print('\t'.join((('%%+%ds' % l) % s) |
| 3822 | for l, s in zip(lengths, row))) |
| 3823 | |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3824 | @staticmethod |
| 3825 | def _parse_identity(identity): |
| 3826 | """Parses identity "git-<ldap>.example.com" into <ldap> and domain.""" |
| 3827 | username, domain = identity.split('.', 1) |
| 3828 | if username.startswith('git-'): |
| 3829 | username = username[len('git-'):] |
| 3830 | return username, domain |
| 3831 | |
| 3832 | def _get_usernames_of_domain(self, domain): |
| 3833 | """Returns list of usernames referenced by .gitcookies in a given domain.""" |
| 3834 | identities_by_domain = {} |
| 3835 | for _, identity, _ in self.get_hosts_with_creds(): |
| 3836 | username, domain = self._parse_identity(identity) |
| 3837 | identities_by_domain.setdefault(domain, []).append(username) |
| 3838 | return identities_by_domain.get(domain) |
| 3839 | |
| 3840 | def _canonical_git_googlesource_host(self, host): |
| 3841 | """Normalizes Gerrit hosts (with '-review') to Git host.""" |
| 3842 | assert host.endswith(self._GOOGLESOURCE) |
| 3843 | # Prefix doesn't include '.' at the end. |
| 3844 | prefix = host[:-(1 + len(self._GOOGLESOURCE))] |
| 3845 | if prefix.endswith('-review'): |
| 3846 | prefix = prefix[:-len('-review')] |
| 3847 | return prefix + '.' + self._GOOGLESOURCE |
| 3848 | |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3849 | def _canonical_gerrit_googlesource_host(self, host): |
| 3850 | git_host = self._canonical_git_googlesource_host(host) |
| 3851 | prefix = git_host.split('.', 1)[0] |
| 3852 | return prefix + '-review.' + self._GOOGLESOURCE |
| 3853 | |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3854 | def _get_counterpart_host(self, host): |
| 3855 | assert host.endswith(self._GOOGLESOURCE) |
| 3856 | git = self._canonical_git_googlesource_host(host) |
| 3857 | gerrit = self._canonical_gerrit_googlesource_host(git) |
| 3858 | return git if gerrit == host else gerrit |
| 3859 | |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3860 | def has_generic_host(self): |
| 3861 | """Returns whether generic .googlesource.com has been configured. |
| 3862 | |
| 3863 | Chrome Infra recommends to use explicit ${host}.googlesource.com instead. |
| 3864 | """ |
| 3865 | for host, _, _ in self.get_hosts_with_creds(include_netrc=False): |
| 3866 | if host == '.' + self._GOOGLESOURCE: |
| 3867 | return True |
| 3868 | return False |
| 3869 | |
| 3870 | def _get_git_gerrit_identity_pairs(self): |
| 3871 | """Returns map from canonic host to pair of identities (Git, Gerrit). |
| 3872 | |
| 3873 | One of identities might be None, meaning not configured. |
| 3874 | """ |
| 3875 | host_to_identity_pairs = {} |
| 3876 | for host, identity, _ in self.get_hosts_with_creds(): |
| 3877 | canonical = self._canonical_git_googlesource_host(host) |
| 3878 | pair = host_to_identity_pairs.setdefault(canonical, [None, None]) |
| 3879 | idx = 0 if canonical == host else 1 |
| 3880 | pair[idx] = identity |
| 3881 | return host_to_identity_pairs |
| 3882 | |
| 3883 | def get_partially_configured_hosts(self): |
| 3884 | return set( |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3885 | (host if i1 else self._canonical_gerrit_googlesource_host(host)) |
| 3886 | for host, (i1, i2) in self._get_git_gerrit_identity_pairs().iteritems() |
| 3887 | if None in (i1, i2) and host != '.' + self._GOOGLESOURCE) |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3888 | |
| 3889 | def get_conflicting_hosts(self): |
| 3890 | return set( |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3891 | host |
| 3892 | for host, (i1, i2) in self._get_git_gerrit_identity_pairs().iteritems() |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3893 | if None not in (i1, i2) and i1 != i2) |
| 3894 | |
| 3895 | def get_duplicated_hosts(self): |
| 3896 | counters = collections.Counter(h for h, _, _ in self.get_hosts_with_creds()) |
| 3897 | return set(host for host, count in counters.iteritems() if count > 1) |
| 3898 | |
| 3899 | _EXPECTED_HOST_IDENTITY_DOMAINS = { |
| 3900 | 'chromium.googlesource.com': 'chromium.org', |
| 3901 | 'chrome-internal.googlesource.com': 'google.com', |
| 3902 | } |
| 3903 | |
| 3904 | def get_hosts_with_wrong_identities(self): |
| 3905 | """Finds hosts which **likely** reference wrong identities. |
| 3906 | |
| 3907 | Note: skips hosts which have conflicting identities for Git and Gerrit. |
| 3908 | """ |
| 3909 | hosts = set() |
| 3910 | for host, expected in self._EXPECTED_HOST_IDENTITY_DOMAINS.iteritems(): |
| 3911 | pair = self._get_git_gerrit_identity_pairs().get(host) |
| 3912 | if pair and pair[0] == pair[1]: |
| 3913 | _, domain = self._parse_identity(pair[0]) |
| 3914 | if domain != expected: |
| 3915 | hosts.add(host) |
| 3916 | return hosts |
| 3917 | |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3918 | @staticmethod |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3919 | def _format_hosts(hosts, extra_column_func=None): |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3920 | hosts = sorted(hosts) |
| 3921 | assert hosts |
| 3922 | if extra_column_func is None: |
| 3923 | extras = [''] * len(hosts) |
| 3924 | else: |
| 3925 | extras = [extra_column_func(host) for host in hosts] |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3926 | tmpl = '%%-%ds %%-%ds' % (max(map(len, hosts)), max(map(len, extras))) |
| 3927 | lines = [] |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3928 | for he in zip(hosts, extras): |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3929 | lines.append(tmpl % he) |
| 3930 | return lines |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3931 | |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3932 | def _find_problems(self): |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3933 | if self.has_generic_host(): |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3934 | yield ('.googlesource.com wildcard record detected', |
| 3935 | ['Chrome Infrastructure team recommends to list full host names ' |
| 3936 | 'explicitly.'], |
| 3937 | None) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3938 | |
| 3939 | dups = self.get_duplicated_hosts() |
| 3940 | if dups: |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3941 | yield ('The following hosts were defined twice', |
| 3942 | self._format_hosts(dups), |
| 3943 | None) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3944 | |
| 3945 | partial = self.get_partially_configured_hosts() |
| 3946 | if partial: |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3947 | yield ('Credentials should come in pairs for Git and Gerrit hosts. ' |
| 3948 | 'These hosts are missing', |
| 3949 | self._format_hosts(partial, lambda host: 'but %s defined' % |
| 3950 | self._get_counterpart_host(host)), |
| 3951 | partial) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3952 | |
| 3953 | conflicting = self.get_conflicting_hosts() |
| 3954 | if conflicting: |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3955 | yield ('The following Git hosts have differing credentials from their ' |
| 3956 | 'Gerrit counterparts', |
| 3957 | self._format_hosts(conflicting, lambda host: '%s vs %s' % |
| 3958 | tuple(self._get_git_gerrit_identity_pairs()[host])), |
| 3959 | conflicting) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3960 | |
| 3961 | wrong = self.get_hosts_with_wrong_identities() |
| 3962 | if wrong: |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 3963 | yield ('These hosts likely use wrong identity', |
| 3964 | self._format_hosts(wrong, lambda host: '%s but %s recommended' % |
| 3965 | (self._get_git_gerrit_identity_pairs()[host][0], |
| 3966 | self._EXPECTED_HOST_IDENTITY_DOMAINS[host])), |
| 3967 | wrong) |
| 3968 | |
| 3969 | def find_and_report_problems(self): |
| 3970 | """Returns True if there was at least one problem, else False.""" |
| 3971 | found = False |
| 3972 | bad_hosts = set() |
| 3973 | for title, sublines, hosts in self._find_problems(): |
| 3974 | if not found: |
| 3975 | found = True |
| 3976 | print('\n\n.gitcookies problem report:\n') |
| 3977 | bad_hosts.update(hosts or []) |
| 3978 | print(' %s%s' % (title , (':' if sublines else ''))) |
| 3979 | if sublines: |
| 3980 | print() |
| 3981 | print(' %s' % '\n '.join(sublines)) |
| 3982 | print() |
| 3983 | |
| 3984 | if bad_hosts: |
| 3985 | assert found |
| 3986 | print(' You can manually remove corresponding lines in your %s file and ' |
| 3987 | 'visit the following URLs with correct account to generate ' |
| 3988 | 'correct credential lines:\n' % |
| 3989 | gerrit_util.CookiesAuthenticator.get_gitcookies_path()) |
| 3990 | print(' %s' % '\n '.join(sorted(set( |
| 3991 | gerrit_util.CookiesAuthenticator().get_new_password_url( |
| 3992 | self._canonical_git_googlesource_host(host)) |
| 3993 | for host in bad_hosts |
| 3994 | )))) |
| 3995 | return found |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3996 | |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3997 | |
| 3998 | def CMDcreds_check(parser, args): |
| 3999 | """Checks credentials and suggests changes.""" |
| 4000 | _, _ = parser.parse_args(args) |
| 4001 | |
| 4002 | if gerrit_util.GceAuthenticator.is_gce(): |
| 4003 | DieWithError('this command is not designed for GCE, are you on a bot?') |
| 4004 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 4005 | checker = _GitCookiesChecker() |
| 4006 | checker.ensure_configured_gitcookies() |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 4007 | |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 4008 | print('Your .netrc and .gitcookies have credentials for these hosts:') |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 4009 | checker.print_current_creds(include_netrc=True) |
| 4010 | |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 4011 | if not checker.find_and_report_problems(): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 4012 | print('\nNo problems detected in your .gitcookies file.') |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 4013 | return 0 |
| 4014 | return 1 |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 4015 | |
| 4016 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4017 | @subcommand.usage('[repo root containing codereview.settings]') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4018 | def CMDconfig(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4019 | """Edits configuration for this tree.""" |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4020 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 4021 | print('WARNING: git cl config works for Rietveld only.') |
tandrii | 5d0a042 | 2016-09-14 06:24:35 -0700 | [diff] [blame] | 4022 | # TODO(tandrii): remove this once we switch to Gerrit. |
| 4023 | # See bugs http://crbug.com/637561 and http://crbug.com/600469. |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 4024 | parser.add_option('--activate-update', action='store_true', |
| 4025 | help='activate auto-updating [rietveld] section in ' |
| 4026 | '.git/config') |
| 4027 | parser.add_option('--deactivate-update', action='store_true', |
| 4028 | help='deactivate auto-updating [rietveld] section in ' |
| 4029 | '.git/config') |
| 4030 | options, args = parser.parse_args(args) |
| 4031 | |
| 4032 | if options.deactivate_update: |
| 4033 | RunGit(['config', 'rietveld.autoupdate', 'false']) |
| 4034 | return |
| 4035 | |
| 4036 | if options.activate_update: |
| 4037 | RunGit(['config', '--unset', 'rietveld.autoupdate']) |
| 4038 | return |
| 4039 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4040 | if len(args) == 0: |
tandrii@chromium.org | e7d3d16 | 2016-03-15 14:15:57 +0000 | [diff] [blame] | 4041 | GetRietveldCodereviewSettingsInteractively() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4042 | return 0 |
| 4043 | |
| 4044 | url = args[0] |
| 4045 | if not url.endswith('codereview.settings'): |
| 4046 | url = os.path.join(url, 'codereview.settings') |
| 4047 | |
| 4048 | # Load code review settings and download hooks (if available). |
| 4049 | LoadCodereviewSettingsFromFile(urllib2.urlopen(url)) |
| 4050 | return 0 |
| 4051 | |
| 4052 | |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 4053 | def CMDbaseurl(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4054 | """Gets or sets base-url for this branch.""" |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 4055 | branchref = RunGit(['symbolic-ref', 'HEAD']).strip() |
| 4056 | branch = ShortBranchName(branchref) |
| 4057 | _, args = parser.parse_args(args) |
| 4058 | if not args: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4059 | print('Current base-url:') |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 4060 | return RunGit(['config', 'branch.%s.base-url' % branch], |
| 4061 | error_ok=False).strip() |
| 4062 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4063 | print('Setting base-url to %s' % args[0]) |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 4064 | return RunGit(['config', 'branch.%s.base-url' % branch, args[0]], |
| 4065 | error_ok=False).strip() |
| 4066 | |
| 4067 | |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 4068 | def color_for_status(status): |
| 4069 | """Maps a Changelist status to color, for CMDstatus and other tools.""" |
| 4070 | return { |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4071 | 'unsent': Fore.YELLOW, |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 4072 | 'waiting': Fore.BLUE, |
| 4073 | 'reply': Fore.YELLOW, |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4074 | 'not lgtm': Fore.RED, |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 4075 | 'lgtm': Fore.GREEN, |
| 4076 | 'commit': Fore.MAGENTA, |
| 4077 | 'closed': Fore.CYAN, |
| 4078 | 'error': Fore.WHITE, |
| 4079 | }.get(status, Fore.WHITE) |
| 4080 | |
tandrii@chromium.org | 04ea846 | 2016-04-25 19:51:21 +0000 | [diff] [blame] | 4081 | |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4082 | def get_cl_statuses(changes, fine_grained, max_processes=None): |
| 4083 | """Returns a blocking iterable of (cl, status) for given branches. |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4084 | |
| 4085 | If fine_grained is true, this will fetch CL statuses from the server. |
| 4086 | Otherwise, simply indicate if there's a matching url for the given branches. |
| 4087 | |
| 4088 | If max_processes is specified, it is used as the maximum number of processes |
| 4089 | to spawn to fetch CL status from the server. Otherwise 1 process per branch is |
| 4090 | spawned. |
calamity@chromium.org | cf19748 | 2016-04-29 20:15:53 +0000 | [diff] [blame] | 4091 | |
| 4092 | See GetStatus() for a list of possible statuses. |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4093 | """ |
qyearsley | 12fa6ff | 2016-08-24 09:18:40 -0700 | [diff] [blame] | 4094 | # Silence upload.py otherwise it becomes unwieldy. |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4095 | upload.verbosity = 0 |
| 4096 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 4097 | if not changes: |
| 4098 | raise StopIteration() |
calamity@chromium.org | cf19748 | 2016-04-29 20:15:53 +0000 | [diff] [blame] | 4099 | |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 4100 | if not fine_grained: |
| 4101 | # Fast path which doesn't involve querying codereview servers. |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 4102 | # 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] | 4103 | for cl in changes: |
| 4104 | yield (cl, 'waiting' if cl.GetIssueURL() else 'error') |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 4105 | return |
| 4106 | |
| 4107 | # First, sort out authentication issues. |
| 4108 | logging.debug('ensuring credentials exist') |
| 4109 | for cl in changes: |
| 4110 | cl.EnsureAuthenticated(force=False, refresh=True) |
| 4111 | |
| 4112 | def fetch(cl): |
| 4113 | try: |
| 4114 | return (cl, cl.GetStatus()) |
| 4115 | except: |
| 4116 | # See http://crbug.com/629863. |
| 4117 | logging.exception('failed to fetch status for %s:', cl) |
| 4118 | raise |
| 4119 | |
| 4120 | threads_count = len(changes) |
| 4121 | if max_processes: |
| 4122 | threads_count = max(1, min(threads_count, max_processes)) |
| 4123 | logging.debug('querying %d CLs using %d threads', len(changes), threads_count) |
| 4124 | |
| 4125 | pool = ThreadPool(threads_count) |
| 4126 | fetched_cls = set() |
| 4127 | try: |
| 4128 | it = pool.imap_unordered(fetch, changes).__iter__() |
| 4129 | while True: |
| 4130 | try: |
| 4131 | cl, status = it.next(timeout=5) |
| 4132 | except multiprocessing.TimeoutError: |
| 4133 | break |
| 4134 | fetched_cls.add(cl) |
| 4135 | yield cl, status |
| 4136 | finally: |
| 4137 | pool.close() |
| 4138 | |
| 4139 | # Add any branches that failed to fetch. |
| 4140 | for cl in set(changes) - fetched_cls: |
| 4141 | yield (cl, 'error') |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 4142 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4143 | |
| 4144 | def upload_branch_deps(cl, args): |
| 4145 | """Uploads CLs of local branches that are dependents of the current branch. |
| 4146 | |
| 4147 | If the local branch dependency tree looks like: |
| 4148 | test1 -> test2.1 -> test3.1 |
| 4149 | -> test3.2 |
| 4150 | -> test2.2 -> test3.3 |
| 4151 | |
| 4152 | and you run "git cl upload --dependencies" from test1 then "git cl upload" is |
| 4153 | run on the dependent branches in this order: |
| 4154 | test2.1, test3.1, test3.2, test2.2, test3.3 |
| 4155 | |
| 4156 | Note: This function does not rebase your local dependent branches. Use it when |
| 4157 | you make a change to the parent branch that will not conflict with its |
| 4158 | dependent branches, and you would like their dependencies updated in |
| 4159 | Rietveld. |
| 4160 | """ |
| 4161 | if git_common.is_dirty_git_tree('upload-branch-deps'): |
| 4162 | return 1 |
| 4163 | |
| 4164 | root_branch = cl.GetBranch() |
| 4165 | if root_branch is None: |
| 4166 | DieWithError('Can\'t find dependent branches from detached HEAD state. ' |
| 4167 | 'Get on a branch!') |
Andrii Shyshkalov | 1090fd5 | 2017-01-26 09:37:54 +0100 | [diff] [blame] | 4168 | if not cl.GetIssue() or (not cl.IsGerrit() and not cl.GetPatchset()): |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4169 | DieWithError('Current branch does not have an uploaded CL. We cannot set ' |
| 4170 | 'patchset dependencies without an uploaded CL.') |
| 4171 | |
| 4172 | branches = RunGit(['for-each-ref', |
| 4173 | '--format=%(refname:short) %(upstream:short)', |
| 4174 | 'refs/heads']) |
| 4175 | if not branches: |
| 4176 | print('No local branches found.') |
| 4177 | return 0 |
| 4178 | |
| 4179 | # Create a dictionary of all local branches to the branches that are dependent |
| 4180 | # on it. |
| 4181 | tracked_to_dependents = collections.defaultdict(list) |
| 4182 | for b in branches.splitlines(): |
| 4183 | tokens = b.split() |
| 4184 | if len(tokens) == 2: |
| 4185 | branch_name, tracked = tokens |
| 4186 | tracked_to_dependents[tracked].append(branch_name) |
| 4187 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4188 | print() |
| 4189 | print('The dependent local branches of %s are:' % root_branch) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4190 | dependents = [] |
| 4191 | def traverse_dependents_preorder(branch, padding=''): |
| 4192 | dependents_to_process = tracked_to_dependents.get(branch, []) |
| 4193 | padding += ' ' |
| 4194 | for dependent in dependents_to_process: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4195 | print('%s%s' % (padding, dependent)) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4196 | dependents.append(dependent) |
| 4197 | traverse_dependents_preorder(dependent, padding) |
| 4198 | traverse_dependents_preorder(root_branch) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4199 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4200 | |
| 4201 | if not dependents: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4202 | print('There are no dependent local branches for %s' % root_branch) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4203 | return 0 |
| 4204 | |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 4205 | confirm_or_exit('This command will checkout all dependent branches and run ' |
| 4206 | '"git cl upload".', action='continue') |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4207 | |
andybons@chromium.org | 962f946 | 2016-02-03 20:00:42 +0000 | [diff] [blame] | 4208 | # Add a default patchset title to all upload calls in Rietveld. |
tandrii@chromium.org | 4c72b08 | 2016-03-31 22:26:35 +0000 | [diff] [blame] | 4209 | if not cl.IsGerrit(): |
andybons@chromium.org | 962f946 | 2016-02-03 20:00:42 +0000 | [diff] [blame] | 4210 | args.extend(['-t', 'Updated patchset dependency']) |
| 4211 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4212 | # Record all dependents that failed to upload. |
| 4213 | failures = {} |
| 4214 | # Go through all dependents, checkout the branch and upload. |
| 4215 | try: |
| 4216 | for dependent_branch in dependents: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4217 | print() |
| 4218 | print('--------------------------------------') |
| 4219 | print('Running "git cl upload" from %s:' % dependent_branch) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4220 | RunGit(['checkout', '-q', dependent_branch]) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4221 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4222 | try: |
| 4223 | if CMDupload(OptionParser(), args) != 0: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4224 | print('Upload failed for %s!' % dependent_branch) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4225 | failures[dependent_branch] = 1 |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 4226 | except: # pylint: disable=bare-except |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4227 | failures[dependent_branch] = 1 |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4228 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4229 | finally: |
| 4230 | # Swap back to the original root branch. |
| 4231 | RunGit(['checkout', '-q', root_branch]) |
| 4232 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4233 | print() |
| 4234 | print('Upload complete for dependent branches!') |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4235 | for dependent_branch in dependents: |
| 4236 | upload_status = 'failed' if failures.get(dependent_branch) else 'succeeded' |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4237 | print(' %s : %s' % (dependent_branch, upload_status)) |
| 4238 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4239 | |
| 4240 | return 0 |
| 4241 | |
| 4242 | |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4243 | def CMDarchive(parser, args): |
| 4244 | """Archives and deletes branches associated with closed changelists.""" |
| 4245 | parser.add_option( |
| 4246 | '-j', '--maxjobs', action='store', type=int, |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4247 | help='The maximum number of jobs to use when retrieving review status.') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4248 | parser.add_option( |
| 4249 | '-f', '--force', action='store_true', |
| 4250 | help='Bypasses the confirmation prompt.') |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4251 | parser.add_option( |
| 4252 | '-d', '--dry-run', action='store_true', |
| 4253 | help='Skip the branch tagging and removal steps.') |
| 4254 | parser.add_option( |
| 4255 | '-t', '--notags', action='store_true', |
| 4256 | help='Do not tag archived branches. ' |
| 4257 | 'Note: local commit history may be lost.') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4258 | |
| 4259 | auth.add_auth_options(parser) |
| 4260 | options, args = parser.parse_args(args) |
| 4261 | if args: |
| 4262 | parser.error('Unsupported args: %s' % ' '.join(args)) |
| 4263 | auth_config = auth.extract_auth_config_from_options(options) |
| 4264 | |
| 4265 | branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads']) |
| 4266 | if not branches: |
| 4267 | return 0 |
| 4268 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4269 | print('Finding all branches associated with closed issues...') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4270 | changes = [Changelist(branchref=b, auth_config=auth_config) |
| 4271 | for b in branches.splitlines()] |
| 4272 | alignment = max(5, max(len(c.GetBranch()) for c in changes)) |
| 4273 | statuses = get_cl_statuses(changes, |
| 4274 | fine_grained=True, |
| 4275 | max_processes=options.maxjobs) |
| 4276 | proposal = [(cl.GetBranch(), |
| 4277 | 'git-cl-archived-%s-%s' % (cl.GetIssue(), cl.GetBranch())) |
| 4278 | for cl, status in statuses |
| 4279 | if status == 'closed'] |
| 4280 | proposal.sort() |
| 4281 | |
| 4282 | if not proposal: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4283 | print('No branches with closed codereview issues found.') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4284 | return 0 |
| 4285 | |
| 4286 | current_branch = GetCurrentBranch() |
| 4287 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4288 | print('\nBranches with closed issues that will be archived:\n') |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4289 | if options.notags: |
| 4290 | for next_item in proposal: |
| 4291 | print(' ' + next_item[0]) |
| 4292 | else: |
| 4293 | print('%*s | %s' % (alignment, 'Branch name', 'Archival tag name')) |
| 4294 | for next_item in proposal: |
| 4295 | print('%*s %s' % (alignment, next_item[0], next_item[1])) |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4296 | |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4297 | # Quit now on precondition failure or if instructed by the user, either |
| 4298 | # via an interactive prompt or by command line flags. |
| 4299 | if options.dry_run: |
| 4300 | print('\nNo changes were made (dry run).\n') |
| 4301 | return 0 |
| 4302 | elif any(branch == current_branch for branch, _ in proposal): |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4303 | print('You are currently on a branch \'%s\' which is associated with a ' |
| 4304 | 'closed codereview issue, so archive cannot proceed. Please ' |
| 4305 | 'checkout another branch and run this command again.' % |
| 4306 | current_branch) |
| 4307 | return 1 |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4308 | elif not options.force: |
sergiyb | 4a5ecbe | 2016-06-20 09:46:00 -0700 | [diff] [blame] | 4309 | answer = ask_for_data('\nProceed with deletion (Y/n)? ').lower() |
| 4310 | if answer not in ('y', ''): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4311 | print('Aborted.') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4312 | return 1 |
| 4313 | |
| 4314 | for branch, tagname in proposal: |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4315 | if not options.notags: |
| 4316 | RunGit(['tag', tagname, branch]) |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4317 | RunGit(['branch', '-D', branch]) |
kmarshall | 9249e01 | 2016-08-23 12:02:16 -0700 | [diff] [blame] | 4318 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4319 | print('\nJob\'s done!') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4320 | |
| 4321 | return 0 |
| 4322 | |
| 4323 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4324 | def CMDstatus(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4325 | """Show status of changelists. |
| 4326 | |
| 4327 | 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] | 4328 | - Blue waiting for review |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4329 | - 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] | 4330 | - Green LGTM'ed |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4331 | - Red 'not LGTM'ed |
jsbell@chromium.org | aeab41a | 2013-12-10 20:01:22 +0000 | [diff] [blame] | 4332 | - Magenta in the commit queue |
| 4333 | - Cyan was committed, branch can be deleted |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4334 | - White error, or unknown status |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4335 | |
| 4336 | Also see 'git cl comments'. |
| 4337 | """ |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4338 | parser.add_option('--field', |
phajdan.jr | 289d03e | 2016-08-16 08:21:06 -0700 | [diff] [blame] | 4339 | help='print only specific field (desc|id|patch|status|url)') |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 4340 | parser.add_option('-f', '--fast', action='store_true', |
| 4341 | help='Do not retrieve review status') |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4342 | parser.add_option( |
| 4343 | '-j', '--maxjobs', action='store', type=int, |
| 4344 | 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] | 4345 | |
| 4346 | auth.add_auth_options(parser) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 4347 | _add_codereview_issue_select_options( |
| 4348 | parser, 'Must be in conjunction with --field.') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4349 | options, args = parser.parse_args(args) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 4350 | _process_codereview_issue_select_options(parser, options) |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4351 | if args: |
| 4352 | parser.error('Unsupported args: %s' % args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4353 | auth_config = auth.extract_auth_config_from_options(options) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4354 | |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 4355 | if options.issue is not None and not options.field: |
| 4356 | parser.error('--field must be specified with --issue') |
iannucci | 3c972b9 | 2016-08-17 13:24:10 -0700 | [diff] [blame] | 4357 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4358 | if options.field: |
iannucci | 3c972b9 | 2016-08-17 13:24:10 -0700 | [diff] [blame] | 4359 | cl = Changelist(auth_config=auth_config, issue=options.issue, |
| 4360 | codereview=options.forced_codereview) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4361 | if options.field.startswith('desc'): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4362 | print(cl.GetDescription()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4363 | elif options.field == 'id': |
| 4364 | issueid = cl.GetIssue() |
| 4365 | if issueid: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4366 | print(issueid) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4367 | elif options.field == 'patch': |
| 4368 | patchset = cl.GetPatchset() |
| 4369 | if patchset: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4370 | print(patchset) |
phajdan.jr | 289d03e | 2016-08-16 08:21:06 -0700 | [diff] [blame] | 4371 | elif options.field == 'status': |
| 4372 | print(cl.GetStatus()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4373 | elif options.field == 'url': |
| 4374 | url = cl.GetIssueURL() |
| 4375 | if url: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4376 | print(url) |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 4377 | return 0 |
| 4378 | |
| 4379 | branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads']) |
| 4380 | if not branches: |
| 4381 | print('No local branch found.') |
| 4382 | return 0 |
| 4383 | |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4384 | changes = [ |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4385 | Changelist(branchref=b, auth_config=auth_config) |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4386 | for b in branches.splitlines()] |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4387 | print('Branches associated with reviews:') |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4388 | output = get_cl_statuses(changes, |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4389 | fine_grained=not options.fast, |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4390 | max_processes=options.maxjobs) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 4391 | |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4392 | branch_statuses = {} |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4393 | alignment = max(5, max(len(ShortBranchName(c.GetBranch())) for c in changes)) |
| 4394 | for cl in sorted(changes, key=lambda c: c.GetBranch()): |
| 4395 | branch = cl.GetBranch() |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 4396 | while branch not in branch_statuses: |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4397 | c, status = output.next() |
| 4398 | branch_statuses[c.GetBranch()] = status |
| 4399 | status = branch_statuses.pop(branch) |
| 4400 | url = cl.GetIssueURL() |
| 4401 | if url and (not status or status == 'error'): |
| 4402 | # The issue probably doesn't exist anymore. |
| 4403 | url += ' (broken)' |
| 4404 | |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 4405 | color = color_for_status(status) |
maruel@chromium.org | 885f651 | 2013-07-27 02:17:26 +0000 | [diff] [blame] | 4406 | reset = Fore.RESET |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 4407 | if not setup_color.IS_TTY: |
maruel@chromium.org | 885f651 | 2013-07-27 02:17:26 +0000 | [diff] [blame] | 4408 | color = '' |
| 4409 | reset = '' |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 4410 | status_str = '(%s)' % status if status else '' |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4411 | print(' %*s : %s%s %s%s' % ( |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4412 | alignment, ShortBranchName(branch), color, url, |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4413 | status_str, reset)) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 4414 | |
Andrii Shyshkalov | d0e1d9d | 2017-01-24 17:10:51 +0100 | [diff] [blame] | 4415 | |
| 4416 | branch = GetCurrentBranch() |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4417 | print() |
Andrii Shyshkalov | d0e1d9d | 2017-01-24 17:10:51 +0100 | [diff] [blame] | 4418 | print('Current branch: %s' % branch) |
| 4419 | for cl in changes: |
| 4420 | if cl.GetBranch() == branch: |
| 4421 | break |
dpranke@chromium.org | ee87f58 | 2015-07-31 18:46:25 +0000 | [diff] [blame] | 4422 | if not cl.GetIssue(): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4423 | print('No issue assigned.') |
dpranke@chromium.org | ee87f58 | 2015-07-31 18:46:25 +0000 | [diff] [blame] | 4424 | return 0 |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4425 | print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())) |
maruel@chromium.org | 85616e0 | 2014-07-28 15:37:55 +0000 | [diff] [blame] | 4426 | if not options.fast: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4427 | print('Issue description:') |
| 4428 | print(cl.GetDescription(pretty=True)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4429 | return 0 |
| 4430 | |
| 4431 | |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4432 | def colorize_CMDstatus_doc(): |
| 4433 | """To be called once in main() to add colors to git cl status help.""" |
| 4434 | colors = [i for i in dir(Fore) if i[0].isupper()] |
| 4435 | |
| 4436 | def colorize_line(line): |
| 4437 | for color in colors: |
| 4438 | if color in line.upper(): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 4439 | # Extract whitespace first and the leading '-'. |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4440 | indent = len(line) - len(line.lstrip(' ')) + 1 |
| 4441 | return line[:indent] + getattr(Fore, color) + line[indent:] + Fore.RESET |
| 4442 | return line |
| 4443 | |
| 4444 | lines = CMDstatus.__doc__.splitlines() |
| 4445 | CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines) |
| 4446 | |
| 4447 | |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4448 | def write_json(path, contents): |
Stefan Zager | 1306bd0 | 2017-06-22 19:26:46 -0700 | [diff] [blame] | 4449 | if path == '-': |
| 4450 | json.dump(contents, sys.stdout) |
| 4451 | else: |
| 4452 | with open(path, 'w') as f: |
| 4453 | json.dump(contents, f) |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4454 | |
| 4455 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4456 | @subcommand.usage('[issue_number]') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4457 | def CMDissue(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4458 | """Sets or displays the current code review issue number. |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4459 | |
| 4460 | Pass issue number 0 to clear the current issue. |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4461 | """ |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4462 | parser.add_option('-r', '--reverse', action='store_true', |
| 4463 | help='Lookup the branch(es) for the specified issues. If ' |
| 4464 | 'no issues are specified, all branches with mapped ' |
| 4465 | 'issues will be listed.') |
Stefan Zager | 1306bd0 | 2017-06-22 19:26:46 -0700 | [diff] [blame] | 4466 | parser.add_option('--json', |
| 4467 | help='Path to JSON output file, or "-" for stdout.') |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4468 | _add_codereview_select_options(parser) |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4469 | options, args = parser.parse_args(args) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4470 | _process_codereview_select_options(parser, options) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4471 | |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4472 | if options.reverse: |
| 4473 | branches = RunGit(['for-each-ref', 'refs/heads', |
| 4474 | '--format=%(refname:short)']).splitlines() |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4475 | # Reverse issue lookup. |
| 4476 | issue_branch_map = {} |
| 4477 | for branch in branches: |
| 4478 | cl = Changelist(branchref=branch) |
| 4479 | issue_branch_map.setdefault(cl.GetIssue(), []).append(branch) |
| 4480 | if not args: |
| 4481 | args = sorted(issue_branch_map.iterkeys()) |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4482 | result = {} |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4483 | for issue in args: |
| 4484 | if not issue: |
| 4485 | continue |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4486 | result[int(issue)] = issue_branch_map.get(int(issue)) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4487 | print('Branch for issue number %s: %s' % ( |
| 4488 | issue, ', '.join(issue_branch_map.get(int(issue)) or ('None',)))) |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4489 | if options.json: |
| 4490 | write_json(options.json, result) |
Aaron Gable | 78753da | 2017-06-15 10:35:49 -0700 | [diff] [blame] | 4491 | return 0 |
| 4492 | |
| 4493 | if len(args) > 0: |
| 4494 | issue = ParseIssueNumberArgument(args[0], options.forced_codereview) |
| 4495 | if not issue.valid: |
| 4496 | DieWithError('Pass a url or number to set the issue, 0 to unset it, ' |
| 4497 | 'or no argument to list it.\n' |
| 4498 | 'Maybe you want to run git cl status?') |
| 4499 | cl = Changelist(codereview=issue.codereview) |
| 4500 | cl.SetIssue(issue.issue) |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 4501 | else: |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4502 | cl = Changelist(codereview=options.forced_codereview) |
Aaron Gable | 78753da | 2017-06-15 10:35:49 -0700 | [diff] [blame] | 4503 | print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())) |
| 4504 | if options.json: |
| 4505 | write_json(options.json, { |
| 4506 | 'issue': cl.GetIssue(), |
| 4507 | 'issue_url': cl.GetIssueURL(), |
| 4508 | }) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4509 | return 0 |
| 4510 | |
| 4511 | |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 4512 | def CMDcomments(parser, args): |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4513 | """Shows or posts review comments for any changelist.""" |
| 4514 | parser.add_option('-a', '--add-comment', dest='comment', |
| 4515 | help='comment to add to an issue') |
Andrii Shyshkalov | 0d6b46e | 2017-03-17 22:23:22 +0100 | [diff] [blame] | 4516 | parser.add_option('-i', '--issue', dest='issue', |
| 4517 | help='review issue id (defaults to current issue). ' |
| 4518 | 'If given, requires --rietveld or --gerrit') |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 4519 | parser.add_option('-m', '--machine-readable', dest='readable', |
| 4520 | action='store_false', default=True, |
| 4521 | help='output comments in a format compatible with ' |
| 4522 | 'editor parsing') |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 4523 | parser.add_option('-j', '--json-file', |
Stefan Zager | 1306bd0 | 2017-06-22 19:26:46 -0700 | [diff] [blame] | 4524 | help='File to write JSON summary to, or "-" for stdout') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4525 | auth.add_auth_options(parser) |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 4526 | _add_codereview_select_options(parser) |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4527 | options, args = parser.parse_args(args) |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 4528 | _process_codereview_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4529 | auth_config = auth.extract_auth_config_from_options(options) |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 4530 | |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4531 | issue = None |
| 4532 | if options.issue: |
| 4533 | try: |
| 4534 | issue = int(options.issue) |
| 4535 | except ValueError: |
| 4536 | DieWithError('A review issue id is expected to be a number') |
Andrii Shyshkalov | 0d6b46e | 2017-03-17 22:23:22 +0100 | [diff] [blame] | 4537 | if not options.forced_codereview: |
| 4538 | parser.error('--gerrit or --rietveld is required if --issue is specified') |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4539 | |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 4540 | cl = Changelist(issue=issue, |
Andrii Shyshkalov | 70909e1 | 2017-04-10 14:38:32 +0200 | [diff] [blame] | 4541 | codereview=options.forced_codereview, |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 4542 | auth_config=auth_config) |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4543 | |
| 4544 | if options.comment: |
| 4545 | cl.AddComment(options.comment) |
| 4546 | return 0 |
| 4547 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 4548 | summary = sorted(cl.GetCommentsSummary(readable=options.readable), |
| 4549 | key=lambda c: c.date) |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4550 | for comment in summary: |
| 4551 | if comment.disapproval: |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4552 | color = Fore.RED |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4553 | elif comment.approval: |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4554 | color = Fore.GREEN |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4555 | elif comment.sender == cl.GetIssueOwner(): |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4556 | color = Fore.MAGENTA |
| 4557 | else: |
| 4558 | color = Fore.BLUE |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4559 | print('\n%s%s %s%s\n%s' % ( |
| 4560 | color, |
| 4561 | comment.date.strftime('%Y-%m-%d %H:%M:%S UTC'), |
| 4562 | comment.sender, |
| 4563 | Fore.RESET, |
| 4564 | '\n'.join(' ' + l for l in comment.message.strip().splitlines()))) |
| 4565 | |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 4566 | if options.json_file: |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4567 | def pre_serialize(c): |
| 4568 | dct = c.__dict__.copy() |
| 4569 | dct['date'] = dct['date'].strftime('%Y-%m-%d %H:%M:%S.%f') |
| 4570 | return dct |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 4571 | with open(options.json_file, 'wb') as f: |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 4572 | json.dump(map(pre_serialize, summary), f) |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 4573 | return 0 |
| 4574 | |
| 4575 | |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4576 | @subcommand.usage('[codereview url or issue id]') |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4577 | def CMDdescription(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4578 | """Brings up the editor for the current CL's description.""" |
smut@google.com | 34fb6b1 | 2015-07-13 20:03:26 +0000 | [diff] [blame] | 4579 | parser.add_option('-d', '--display', action='store_true', |
| 4580 | help='Display the description instead of opening an editor') |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4581 | parser.add_option('-n', '--new-description', |
dnj | ba1b0f3 | 2016-09-02 12:37:42 -0700 | [diff] [blame] | 4582 | help='New description to set for this issue (- for stdin, ' |
| 4583 | '+ to load from local commit HEAD)') |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 4584 | parser.add_option('-f', '--force', action='store_true', |
| 4585 | help='Delete any unpublished Gerrit edits for this issue ' |
| 4586 | 'without prompting') |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4587 | |
| 4588 | _add_codereview_select_options(parser) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4589 | auth.add_auth_options(parser) |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4590 | options, args = parser.parse_args(args) |
| 4591 | _process_codereview_select_options(parser, options) |
| 4592 | |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 4593 | target_issue_arg = None |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4594 | if len(args) > 0: |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4595 | target_issue_arg = ParseIssueNumberArgument(args[0], |
| 4596 | options.forced_codereview) |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 4597 | if not target_issue_arg.valid: |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 4598 | parser.error('invalid codereview url or CL id') |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4599 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4600 | auth_config = auth.extract_auth_config_from_options(options) |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4601 | |
martiniss | 6eda05f | 2016-06-30 10:18:35 -0700 | [diff] [blame] | 4602 | kwargs = { |
| 4603 | 'auth_config': auth_config, |
| 4604 | 'codereview': options.forced_codereview, |
| 4605 | } |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4606 | detected_codereview_from_url = False |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 4607 | if target_issue_arg: |
| 4608 | kwargs['issue'] = target_issue_arg.issue |
| 4609 | kwargs['codereview_host'] = target_issue_arg.hostname |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4610 | if target_issue_arg.codereview and not options.forced_codereview: |
| 4611 | detected_codereview_from_url = True |
| 4612 | kwargs['codereview'] = target_issue_arg.codereview |
martiniss | 6eda05f | 2016-06-30 10:18:35 -0700 | [diff] [blame] | 4613 | |
| 4614 | cl = Changelist(**kwargs) |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4615 | if not cl.GetIssue(): |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4616 | assert not detected_codereview_from_url |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4617 | DieWithError('This branch has no associated changelist.') |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4618 | |
| 4619 | if detected_codereview_from_url: |
| 4620 | logging.info('canonical issue/change URL: %s (type: %s)\n', |
| 4621 | cl.GetIssueURL(), target_issue_arg.codereview) |
| 4622 | |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4623 | description = ChangeDescription(cl.GetDescription()) |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4624 | |
smut@google.com | 34fb6b1 | 2015-07-13 20:03:26 +0000 | [diff] [blame] | 4625 | if options.display: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4626 | print(description.description) |
smut@google.com | 34fb6b1 | 2015-07-13 20:03:26 +0000 | [diff] [blame] | 4627 | return 0 |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4628 | |
| 4629 | if options.new_description: |
| 4630 | text = options.new_description |
| 4631 | if text == '-': |
| 4632 | text = '\n'.join(l.rstrip() for l in sys.stdin) |
dnj | ba1b0f3 | 2016-09-02 12:37:42 -0700 | [diff] [blame] | 4633 | elif text == '+': |
| 4634 | base_branch = cl.GetCommonAncestorWithUpstream() |
| 4635 | change = cl.GetChange(base_branch, None, local_description=True) |
| 4636 | text = change.FullDescriptionText() |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4637 | |
| 4638 | description.set_description(text) |
| 4639 | else: |
Aaron Gable | 3a16ed1 | 2017-03-23 10:51:55 -0700 | [diff] [blame] | 4640 | description.prompt(git_footer=cl.IsGerrit()) |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4641 | |
Andrii Shyshkalov | 680253d | 2017-03-15 21:07:36 +0100 | [diff] [blame] | 4642 | if cl.GetDescription().strip() != description.description: |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 4643 | cl.UpdateDescription(description.description, force=options.force) |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4644 | return 0 |
| 4645 | |
| 4646 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4647 | def CreateDescriptionFromLog(args): |
| 4648 | """Pulls out the commit log to use as a base for the CL description.""" |
| 4649 | log_args = [] |
| 4650 | if len(args) == 1 and not args[0].endswith('.'): |
| 4651 | log_args = [args[0] + '..'] |
| 4652 | elif len(args) == 1 and args[0].endswith('...'): |
| 4653 | log_args = [args[0][:-1]] |
| 4654 | elif len(args) == 2: |
| 4655 | log_args = [args[0] + '..' + args[1]] |
| 4656 | else: |
| 4657 | log_args = args[:] # Hope for the best! |
maruel@chromium.org | 373af80 | 2012-05-25 21:07:33 +0000 | [diff] [blame] | 4658 | return RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4659 | |
| 4660 | |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4661 | def CMDlint(parser, args): |
| 4662 | """Runs cpplint on the current changelist.""" |
tzik@chromium.org | f204d4b | 2014-03-13 07:40:55 +0000 | [diff] [blame] | 4663 | parser.add_option('--filter', action='append', metavar='-x,+y', |
| 4664 | help='Comma-separated list of cpplint\'s category-filters') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4665 | auth.add_auth_options(parser) |
| 4666 | options, args = parser.parse_args(args) |
| 4667 | auth_config = auth.extract_auth_config_from_options(options) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4668 | |
| 4669 | # Access to a protected member _XX of a client class |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 4670 | # pylint: disable=protected-access |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4671 | try: |
| 4672 | import cpplint |
| 4673 | import cpplint_chromium |
| 4674 | except ImportError: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4675 | 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] | 4676 | return 1 |
| 4677 | |
| 4678 | # Change the current working directory before calling lint so that it |
| 4679 | # shows the correct base. |
| 4680 | previous_cwd = os.getcwd() |
| 4681 | os.chdir(settings.GetRoot()) |
| 4682 | try: |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4683 | cl = Changelist(auth_config=auth_config) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4684 | change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None) |
| 4685 | files = [f.LocalPath() for f in change.AffectedFiles()] |
thestig@chromium.org | 5839eb5 | 2014-05-30 16:20:51 +0000 | [diff] [blame] | 4686 | if not files: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4687 | print('Cannot lint an empty CL') |
thestig@chromium.org | 5839eb5 | 2014-05-30 16:20:51 +0000 | [diff] [blame] | 4688 | return 1 |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4689 | |
| 4690 | # Process cpplints arguments if any. |
tzik@chromium.org | f204d4b | 2014-03-13 07:40:55 +0000 | [diff] [blame] | 4691 | command = args + files |
| 4692 | if options.filter: |
| 4693 | command = ['--filter=' + ','.join(options.filter)] + command |
| 4694 | filenames = cpplint.ParseArguments(command) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4695 | |
| 4696 | white_regex = re.compile(settings.GetLintRegex()) |
| 4697 | black_regex = re.compile(settings.GetLintIgnoreRegex()) |
| 4698 | extra_check_functions = [cpplint_chromium.CheckPointerDeclarationWhitespace] |
| 4699 | for filename in filenames: |
| 4700 | if white_regex.match(filename): |
| 4701 | if black_regex.match(filename): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4702 | print('Ignoring file %s' % filename) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4703 | else: |
| 4704 | cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level, |
| 4705 | extra_check_functions) |
| 4706 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4707 | print('Skipping file %s' % filename) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4708 | finally: |
| 4709 | os.chdir(previous_cwd) |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4710 | print('Total errors found: %d\n' % cpplint._cpplint_state.error_count) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4711 | if cpplint._cpplint_state.error_count != 0: |
| 4712 | return 1 |
| 4713 | return 0 |
| 4714 | |
| 4715 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4716 | def CMDpresubmit(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4717 | """Runs presubmit tests on the current changelist.""" |
ilevy@chromium.org | 375a902 | 2013-01-07 01:12:05 +0000 | [diff] [blame] | 4718 | parser.add_option('-u', '--upload', action='store_true', |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 4719 | help='Run upload hook instead of the push hook') |
ilevy@chromium.org | 375a902 | 2013-01-07 01:12:05 +0000 | [diff] [blame] | 4720 | parser.add_option('-f', '--force', action='store_true', |
sbc@chromium.org | 495ad15 | 2012-09-04 23:07:42 +0000 | [diff] [blame] | 4721 | help='Run checks even if tree is dirty') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4722 | auth.add_auth_options(parser) |
| 4723 | options, args = parser.parse_args(args) |
| 4724 | auth_config = auth.extract_auth_config_from_options(options) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4725 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 4726 | if not options.force and git_common.is_dirty_git_tree('presubmit'): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 4727 | print('use --force to check even if tree is dirty.') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4728 | return 1 |
| 4729 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4730 | cl = Changelist(auth_config=auth_config) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4731 | if args: |
| 4732 | base_branch = args[0] |
| 4733 | else: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 4734 | # Default to diffing against the common ancestor of the upstream branch. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 4735 | base_branch = cl.GetCommonAncestorWithUpstream() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4736 | |
ilevy@chromium.org | 051ad0e | 2013-03-04 21:57:34 +0000 | [diff] [blame] | 4737 | cl.RunHook( |
| 4738 | committing=not options.upload, |
| 4739 | may_prompt=False, |
| 4740 | verbose=options.verbose, |
| 4741 | change=cl.GetChange(base_branch, None)) |
dpranke@chromium.org | 0a2bb37 | 2011-03-25 01:16:22 +0000 | [diff] [blame] | 4742 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4743 | |
| 4744 | |
tandrii@chromium.org | 65874e1 | 2016-03-04 12:03:02 +0000 | [diff] [blame] | 4745 | def GenerateGerritChangeId(message): |
| 4746 | """Returns Ixxxxxx...xxx change id. |
| 4747 | |
| 4748 | Works the same way as |
| 4749 | https://gerrit-review.googlesource.com/tools/hooks/commit-msg |
| 4750 | but can be called on demand on all platforms. |
| 4751 | |
| 4752 | The basic idea is to generate git hash of a state of the tree, original commit |
| 4753 | message, author/committer info and timestamps. |
| 4754 | """ |
| 4755 | lines = [] |
| 4756 | tree_hash = RunGitSilent(['write-tree']) |
| 4757 | lines.append('tree %s' % tree_hash.strip()) |
| 4758 | code, parent = RunGitWithCode(['rev-parse', 'HEAD~0'], suppress_stderr=False) |
| 4759 | if code == 0: |
| 4760 | lines.append('parent %s' % parent.strip()) |
| 4761 | author = RunGitSilent(['var', 'GIT_AUTHOR_IDENT']) |
| 4762 | lines.append('author %s' % author.strip()) |
| 4763 | committer = RunGitSilent(['var', 'GIT_COMMITTER_IDENT']) |
| 4764 | lines.append('committer %s' % committer.strip()) |
| 4765 | lines.append('') |
| 4766 | # Note: Gerrit's commit-hook actually cleans message of some lines and |
| 4767 | # whitespace. This code is not doing this, but it clearly won't decrease |
| 4768 | # entropy. |
| 4769 | lines.append(message) |
| 4770 | change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'], |
| 4771 | stdin='\n'.join(lines)) |
| 4772 | return 'I%s' % change_hash.strip() |
| 4773 | |
| 4774 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 4775 | def GetTargetRef(remote, remote_branch, target_branch): |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4776 | """Computes the remote branch ref to use for the CL. |
| 4777 | |
| 4778 | Args: |
| 4779 | remote (str): The git remote for the CL. |
| 4780 | remote_branch (str): The git remote branch for the CL. |
| 4781 | target_branch (str): The target branch specified by the user. |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4782 | """ |
| 4783 | if not (remote and remote_branch): |
| 4784 | return None |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 4785 | |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4786 | if target_branch: |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 4787 | # Canonicalize branch references to the equivalent local full symbolic |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4788 | # refs, which are then translated into the remote full symbolic refs |
| 4789 | # below. |
| 4790 | if '/' not in target_branch: |
| 4791 | remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch) |
| 4792 | else: |
| 4793 | prefix_replacements = ( |
| 4794 | ('^((refs/)?remotes/)?branch-heads/', 'refs/remotes/branch-heads/'), |
| 4795 | ('^((refs/)?remotes/)?%s/' % remote, 'refs/remotes/%s/' % remote), |
| 4796 | ('^(refs/)?heads/', 'refs/remotes/%s/' % remote), |
| 4797 | ) |
| 4798 | match = None |
| 4799 | for regex, replacement in prefix_replacements: |
| 4800 | match = re.search(regex, target_branch) |
| 4801 | if match: |
| 4802 | remote_branch = target_branch.replace(match.group(0), replacement) |
| 4803 | break |
| 4804 | if not match: |
| 4805 | # This is a branch path but not one we recognize; use as-is. |
| 4806 | remote_branch = target_branch |
rmistry@google.com | c68112d | 2015-03-03 12:48:06 +0000 | [diff] [blame] | 4807 | elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS: |
| 4808 | # Handle the refs that need to land in different refs. |
| 4809 | remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch] |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 4810 | |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4811 | # Create the true path to the remote branch. |
| 4812 | # Does the following translation: |
| 4813 | # * refs/remotes/origin/refs/diff/test -> refs/diff/test |
| 4814 | # * refs/remotes/origin/master -> refs/heads/master |
| 4815 | # * refs/remotes/branch-heads/test -> refs/branch-heads/test |
| 4816 | if remote_branch.startswith('refs/remotes/%s/refs/' % remote): |
| 4817 | remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '') |
| 4818 | elif remote_branch.startswith('refs/remotes/%s/' % remote): |
| 4819 | remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, |
| 4820 | 'refs/heads/') |
| 4821 | elif remote_branch.startswith('refs/remotes/branch-heads'): |
| 4822 | remote_branch = remote_branch.replace('refs/remotes/', 'refs/') |
Andrii Shyshkalov | 768f1d8 | 2016-12-08 15:10:13 +0100 | [diff] [blame] | 4823 | |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4824 | return remote_branch |
| 4825 | |
| 4826 | |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4827 | def cleanup_list(l): |
| 4828 | """Fixes a list so that comma separated items are put as individual items. |
| 4829 | |
| 4830 | So that "--reviewers joe@c,john@c --reviewers joa@c" results in |
| 4831 | options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']). |
| 4832 | """ |
| 4833 | items = sum((i.split(',') for i in l), []) |
| 4834 | stripped_items = (i.strip() for i in items) |
| 4835 | return sorted(filter(None, stripped_items)) |
| 4836 | |
| 4837 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4838 | @subcommand.usage('[args to "git diff"]') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4839 | def CMDupload(parser, args): |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 4840 | """Uploads the current changelist to codereview. |
| 4841 | |
| 4842 | Can skip dependency patchset uploads for a branch by running: |
| 4843 | git config branch.branch_name.skip-deps-uploads True |
| 4844 | To unset run: |
| 4845 | git config --unset branch.branch_name.skip-deps-uploads |
| 4846 | Can also set the above globally by using the --global flag. |
| 4847 | """ |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4848 | parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 4849 | help='bypass upload presubmit hook') |
brettw@chromium.org | b65c43c | 2013-06-10 22:04:49 +0000 | [diff] [blame] | 4850 | parser.add_option('--bypass-watchlists', action='store_true', |
| 4851 | dest='bypass_watchlists', |
| 4852 | help='bypass watchlists auto CC-ing reviewers') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4853 | parser.add_option('-f', action='store_true', dest='force', |
| 4854 | help="force yes to questions (don't prompt)") |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 4855 | parser.add_option('--message', '-m', dest='message', |
| 4856 | help='message for patchset') |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 4857 | parser.add_option('-b', '--bug', |
| 4858 | help='pre-populate the bug number(s) for this issue. ' |
| 4859 | 'If several, separate with commas') |
tandrii | b80458a | 2016-06-23 12:20:07 -0700 | [diff] [blame] | 4860 | parser.add_option('--message-file', dest='message_file', |
| 4861 | help='file which contains message for patchset') |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 4862 | parser.add_option('--title', '-t', dest='title', |
| 4863 | help='title for patchset') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4864 | parser.add_option('-r', '--reviewers', |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4865 | action='append', default=[], |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4866 | help='reviewer email addresses') |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 4867 | parser.add_option('--tbrs', |
| 4868 | action='append', default=[], |
| 4869 | help='TBR email addresses') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4870 | parser.add_option('--cc', |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4871 | action='append', default=[], |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4872 | help='cc email addresses') |
adamk@chromium.org | 36f4730 | 2013-04-05 01:08:31 +0000 | [diff] [blame] | 4873 | parser.add_option('-s', '--send-mail', action='store_true', |
Aaron Gable | 59f4851 | 2017-01-12 10:54:46 -0800 | [diff] [blame] | 4874 | help='send email to reviewer(s) and cc(s) immediately') |
pgervais@chromium.org | b9f2751 | 2014-08-08 15:52:33 +0000 | [diff] [blame] | 4875 | parser.add_option('--emulate_svn_auto_props', |
| 4876 | '--emulate-svn-auto-props', |
| 4877 | action="store_true", |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4878 | dest="emulate_svn_auto_props", |
| 4879 | help="Emulate Subversion's auto properties feature.") |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4880 | parser.add_option('-c', '--use-commit-queue', action='store_true', |
| 4881 | help='tell the commit queue to commit this patchset') |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 4882 | parser.add_option('--private', action='store_true', |
| 4883 | help='set the review private (rietveld only)') |
ukai@chromium.org | 8ef7ab2 | 2012-11-28 04:24:52 +0000 | [diff] [blame] | 4884 | parser.add_option('--target_branch', |
pgervais@chromium.org | b9f2751 | 2014-08-08 15:52:33 +0000 | [diff] [blame] | 4885 | '--target-branch', |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4886 | metavar='TARGET', |
| 4887 | help='Apply CL to remote ref TARGET. ' + |
| 4888 | 'Default: remote branch head, or master') |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 4889 | parser.add_option('--squash', action='store_true', |
| 4890 | help='Squash multiple commits into one (Gerrit only)') |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 4891 | parser.add_option('--no-squash', action='store_true', |
| 4892 | help='Don\'t squash multiple commits into one ' + |
| 4893 | '(Gerrit only)') |
rmistry | 9eadede | 2016-09-19 11:22:43 -0700 | [diff] [blame] | 4894 | parser.add_option('--topic', default=None, |
| 4895 | help='Topic to specify when uploading (Gerrit only)') |
pgervais@chromium.org | 9114137 | 2014-01-09 23:27:20 +0000 | [diff] [blame] | 4896 | parser.add_option('--email', default=None, |
| 4897 | help='email address to use to connect to Rietveld') |
Robert Iannucci | f2708bd | 2017-04-17 15:49:02 -0700 | [diff] [blame] | 4898 | parser.add_option('--tbr-owners', dest='add_owners_to', action='store_const', |
| 4899 | const='TBR', help='add a set of OWNERS to TBR') |
| 4900 | parser.add_option('--r-owners', dest='add_owners_to', action='store_const', |
| 4901 | const='R', help='add a set of OWNERS to R') |
tandrii@chromium.org | d50452a | 2015-11-23 16:38:15 +0000 | [diff] [blame] | 4902 | parser.add_option('-d', '--cq-dry-run', dest='cq_dry_run', |
| 4903 | action='store_true', |
rmistry@google.com | ef96622 | 2015-04-07 11:15:01 +0000 | [diff] [blame] | 4904 | help='Send the patchset to do a CQ dry run right after ' |
| 4905 | 'upload.') |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4906 | parser.add_option('--dependencies', action='store_true', |
| 4907 | help='Uploads CLs of all the local branches that depend on ' |
| 4908 | 'the current branch') |
pgervais@chromium.org | 9114137 | 2014-01-09 23:27:20 +0000 | [diff] [blame] | 4909 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4910 | orig_args = args |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 4911 | add_git_similarity(parser) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4912 | auth.add_auth_options(parser) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4913 | _add_codereview_select_options(parser) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4914 | (options, args) = parser.parse_args(args) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4915 | _process_codereview_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4916 | auth_config = auth.extract_auth_config_from_options(options) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4917 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 4918 | if git_common.is_dirty_git_tree('upload'): |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4919 | return 1 |
| 4920 | |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4921 | options.reviewers = cleanup_list(options.reviewers) |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 4922 | options.tbrs = cleanup_list(options.tbrs) |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4923 | options.cc = cleanup_list(options.cc) |
| 4924 | |
tandrii | b80458a | 2016-06-23 12:20:07 -0700 | [diff] [blame] | 4925 | if options.message_file: |
| 4926 | if options.message: |
| 4927 | parser.error('only one of --message and --message-file allowed.') |
| 4928 | options.message = gclient_utils.FileRead(options.message_file) |
| 4929 | options.message_file = None |
| 4930 | |
tandrii | 4d0545a | 2016-07-06 03:56:49 -0700 | [diff] [blame] | 4931 | if options.cq_dry_run and options.use_commit_queue: |
| 4932 | parser.error('only one of --use-commit-queue and --cq-dry-run allowed.') |
| 4933 | |
tandrii@chromium.org | 512d79c | 2016-03-31 12:55:28 +0000 | [diff] [blame] | 4934 | # For sanity of test expectations, do this otherwise lazy-loading *now*. |
| 4935 | settings.GetIsGerrit() |
| 4936 | |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4937 | cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 4938 | return cl.CMDUpload(options, args, orig_args) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4939 | |
| 4940 | |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 4941 | @subcommand.usage('--description=<description file>') |
| 4942 | def CMDsplit(parser, args): |
| 4943 | """Splits a branch into smaller branches and uploads CLs. |
| 4944 | |
| 4945 | Creates a branch and uploads a CL for each group of files modified in the |
| 4946 | 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] | 4947 | comment, the string '$directory', is replaced with the directory containing |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 4948 | the shared OWNERS file. |
| 4949 | """ |
| 4950 | parser.add_option("-d", "--description", dest="description_file", |
| 4951 | help="A text file containing a CL description. ") |
| 4952 | parser.add_option("-c", "--comment", dest="comment_file", |
| 4953 | help="A text file containing a CL comment.") |
| 4954 | options, _ = parser.parse_args(args) |
| 4955 | |
| 4956 | if not options.description_file: |
| 4957 | parser.error('No --description flag specified.') |
| 4958 | |
| 4959 | def WrappedCMDupload(args): |
| 4960 | return CMDupload(OptionParser(), args) |
| 4961 | |
| 4962 | return split_cl.SplitCl(options.description_file, options.comment_file, |
| 4963 | Changelist, WrappedCMDupload) |
| 4964 | |
| 4965 | |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 4966 | @subcommand.usage('DEPRECATED') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4967 | def CMDdcommit(parser, args): |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 4968 | """DEPRECATED: Used to commit the current changelist via git-svn.""" |
| 4969 | message = ('git-cl no longer supports committing to SVN repositories via ' |
| 4970 | 'git-svn. You probably want to use `git cl land` instead.') |
| 4971 | print(message) |
| 4972 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4973 | |
| 4974 | |
Andrii Shyshkalov | aa31b97 | 2017-03-24 16:16:33 +0100 | [diff] [blame] | 4975 | # Two special branches used by git cl land. |
| 4976 | MERGE_BRANCH = 'git-cl-commit' |
| 4977 | CHERRY_PICK_BRANCH = 'git-cl-cherry-pick' |
| 4978 | |
| 4979 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4980 | @subcommand.usage('[upstream branch to apply against]') |
pgervais@chromium.org | cee6dc4 | 2014-05-07 17:04:03 +0000 | [diff] [blame] | 4981 | def CMDland(parser, args): |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 4982 | """Commits the current changelist via git. |
| 4983 | |
| 4984 | In case of Gerrit, uses Gerrit REST api to "submit" the issue, which pushes |
| 4985 | upstream and closes the issue automatically and atomically. |
| 4986 | |
| 4987 | Otherwise (in case of Rietveld): |
| 4988 | Squashes branch into a single commit. |
| 4989 | Updates commit message with metadata (e.g. pointer to review). |
| 4990 | Pushes the code upstream. |
| 4991 | Updates review and closes. |
| 4992 | """ |
| 4993 | parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 4994 | help='bypass upload presubmit hook') |
| 4995 | parser.add_option('-m', dest='message', |
| 4996 | help="override review description") |
| 4997 | parser.add_option('-f', action='store_true', dest='force', |
| 4998 | help="force yes to questions (don't prompt)") |
| 4999 | parser.add_option('-c', dest='contributor', |
| 5000 | help="external contributor for patch (appended to " + |
| 5001 | "description and used as author for git). Should be " + |
| 5002 | "formatted as 'First Last <email@example.com>'") |
| 5003 | add_git_similarity(parser) |
| 5004 | auth.add_auth_options(parser) |
| 5005 | (options, args) = parser.parse_args(args) |
| 5006 | auth_config = auth.extract_auth_config_from_options(options) |
| 5007 | |
| 5008 | cl = Changelist(auth_config=auth_config) |
| 5009 | |
| 5010 | # TODO(tandrii): refactor this into _RietveldChangelistImpl method. |
| 5011 | if cl.IsGerrit(): |
| 5012 | if options.message: |
| 5013 | # This could be implemented, but it requires sending a new patch to |
| 5014 | # Gerrit, as Gerrit unlike Rietveld versions messages with patchsets. |
| 5015 | # Besides, Gerrit has the ability to change the commit message on submit |
| 5016 | # automatically, thus there is no need to support this option (so far?). |
| 5017 | parser.error('-m MESSAGE option is not supported for Gerrit.') |
| 5018 | if options.contributor: |
| 5019 | parser.error( |
| 5020 | '-c CONTRIBUTOR option is not supported for Gerrit.\n' |
| 5021 | 'Before uploading a commit to Gerrit, ensure it\'s author field is ' |
| 5022 | 'the contributor\'s "name <email>". If you can\'t upload such a ' |
| 5023 | 'commit for review, contact your repository admin and request' |
| 5024 | '"Forge-Author" permission.') |
| 5025 | if not cl.GetIssue(): |
| 5026 | DieWithError('You must upload the change first to Gerrit.\n' |
| 5027 | ' If you would rather have `git cl land` upload ' |
| 5028 | 'automatically for you, see http://crbug.com/642759') |
| 5029 | return cl._codereview_impl.CMDLand(options.force, options.bypass_hooks, |
| 5030 | options.verbose) |
| 5031 | |
| 5032 | current = cl.GetBranch() |
| 5033 | remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch()) |
| 5034 | if remote == '.': |
| 5035 | print() |
| 5036 | print('Attempting to push branch %r into another local branch!' % current) |
| 5037 | print() |
| 5038 | print('Either reparent this branch on top of origin/master:') |
| 5039 | print(' git reparent-branch --root') |
| 5040 | print() |
| 5041 | print('OR run `git rebase-update` if you think the parent branch is ') |
| 5042 | print('already committed.') |
| 5043 | print() |
| 5044 | print(' Current parent: %r' % upstream_branch) |
| 5045 | return 1 |
| 5046 | |
| 5047 | if not args: |
| 5048 | # Default to merging against our best guess of the upstream branch. |
| 5049 | args = [cl.GetUpstreamBranch()] |
| 5050 | |
| 5051 | if options.contributor: |
| 5052 | if not re.match('^.*\s<\S+@\S+>$', options.contributor): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 5053 | print("Please provide contributor as 'First Last <email@example.com>'") |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5054 | return 1 |
| 5055 | |
| 5056 | base_branch = args[0] |
| 5057 | |
| 5058 | if git_common.is_dirty_git_tree('land'): |
| 5059 | return 1 |
| 5060 | |
| 5061 | # This rev-list syntax means "show all commits not in my branch that |
| 5062 | # are in base_branch". |
| 5063 | upstream_commits = RunGit(['rev-list', '^' + cl.GetBranchRef(), |
| 5064 | base_branch]).splitlines() |
| 5065 | if upstream_commits: |
| 5066 | print('Base branch "%s" has %d commits ' |
| 5067 | 'not in this branch.' % (base_branch, len(upstream_commits))) |
| 5068 | print('Run "git merge %s" before attempting to land.' % base_branch) |
| 5069 | return 1 |
| 5070 | |
| 5071 | merge_base = RunGit(['merge-base', base_branch, 'HEAD']).strip() |
| 5072 | if not options.bypass_hooks: |
| 5073 | author = None |
| 5074 | if options.contributor: |
| 5075 | author = re.search(r'\<(.*)\>', options.contributor).group(1) |
| 5076 | hook_results = cl.RunHook( |
| 5077 | committing=True, |
| 5078 | may_prompt=not options.force, |
| 5079 | verbose=options.verbose, |
| 5080 | change=cl.GetChange(merge_base, author)) |
| 5081 | if not hook_results.should_continue(): |
| 5082 | return 1 |
| 5083 | |
| 5084 | # Check the tree status if the tree status URL is set. |
| 5085 | status = GetTreeStatus() |
| 5086 | if 'closed' == status: |
| 5087 | print('The tree is closed. Please wait for it to reopen. Use ' |
| 5088 | '"git cl land --bypass-hooks" to commit on a closed tree.') |
| 5089 | return 1 |
| 5090 | elif 'unknown' == status: |
| 5091 | print('Unable to determine tree status. Please verify manually and ' |
| 5092 | 'use "git cl land --bypass-hooks" to commit on a closed tree.') |
| 5093 | return 1 |
| 5094 | |
| 5095 | change_desc = ChangeDescription(options.message) |
| 5096 | if not change_desc.description and cl.GetIssue(): |
| 5097 | change_desc = ChangeDescription(cl.GetDescription()) |
| 5098 | |
| 5099 | if not change_desc.description: |
| 5100 | if not cl.GetIssue() and options.bypass_hooks: |
| 5101 | change_desc = ChangeDescription(CreateDescriptionFromLog([merge_base])) |
| 5102 | else: |
| 5103 | print('No description set.') |
| 5104 | print('Visit %s/edit to set it.' % (cl.GetIssueURL())) |
| 5105 | return 1 |
| 5106 | |
| 5107 | # Keep a separate copy for the commit message, because the commit message |
| 5108 | # contains the link to the Rietveld issue, while the Rietveld message contains |
| 5109 | # the commit viewvc url. |
| 5110 | if cl.GetIssue(): |
Aaron Gable | a1bab27 | 2017-04-11 16:38:18 -0700 | [diff] [blame] | 5111 | change_desc.update_reviewers( |
Robert Iannucci | 6c98dc6 | 2017-04-18 11:38:00 -0700 | [diff] [blame] | 5112 | get_approving_reviewers(cl.GetIssueProperties()), []) |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5113 | |
| 5114 | commit_desc = ChangeDescription(change_desc.description) |
| 5115 | if cl.GetIssue(): |
| 5116 | # Xcode won't linkify this URL unless there is a non-whitespace character |
| 5117 | # after it. Add a period on a new line to circumvent this. Also add a space |
| 5118 | # before the period to make sure that Gitiles continues to correctly resolve |
| 5119 | # the URL. |
| 5120 | commit_desc.append_footer('Review-Url: %s .' % cl.GetIssueURL()) |
| 5121 | if options.contributor: |
| 5122 | commit_desc.append_footer('Patch from %s.' % options.contributor) |
| 5123 | |
| 5124 | print('Description:') |
| 5125 | print(commit_desc.description) |
| 5126 | |
| 5127 | branches = [merge_base, cl.GetBranchRef()] |
| 5128 | if not options.force: |
| 5129 | print_stats(options.similarity, options.find_copies, branches) |
| 5130 | |
| 5131 | # We want to squash all this branch's commits into one commit with the proper |
| 5132 | # description. We do this by doing a "reset --soft" to the base branch (which |
| 5133 | # keeps the working copy the same), then landing that. |
Andrii Shyshkalov | aa31b97 | 2017-03-24 16:16:33 +0100 | [diff] [blame] | 5134 | # Delete the special branches if they exist. |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5135 | for branch in [MERGE_BRANCH, CHERRY_PICK_BRANCH]: |
| 5136 | showref_cmd = ['show-ref', '--quiet', '--verify', 'refs/heads/%s' % branch] |
| 5137 | result = RunGitWithCode(showref_cmd) |
| 5138 | if result[0] == 0: |
| 5139 | RunGit(['branch', '-D', branch]) |
| 5140 | |
| 5141 | # We might be in a directory that's present in this branch but not in the |
| 5142 | # trunk. Move up to the top of the tree so that git commands that expect a |
| 5143 | # valid CWD won't fail after we check out the merge branch. |
| 5144 | rel_base_path = settings.GetRelativeRoot() |
| 5145 | if rel_base_path: |
| 5146 | os.chdir(rel_base_path) |
| 5147 | |
| 5148 | # Stuff our change into the merge branch. |
| 5149 | # We wrap in a try...finally block so if anything goes wrong, |
| 5150 | # we clean up the branches. |
| 5151 | retcode = -1 |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5152 | revision = None |
| 5153 | try: |
| 5154 | RunGit(['checkout', '-q', '-b', MERGE_BRANCH]) |
| 5155 | RunGit(['reset', '--soft', merge_base]) |
| 5156 | if options.contributor: |
| 5157 | RunGit( |
| 5158 | [ |
| 5159 | 'commit', '--author', options.contributor, |
| 5160 | '-m', commit_desc.description, |
| 5161 | ]) |
| 5162 | else: |
| 5163 | RunGit(['commit', '-m', commit_desc.description]) |
| 5164 | |
| 5165 | remote, branch = cl.FetchUpstreamTuple(cl.GetBranch()) |
| 5166 | mirror = settings.GetGitMirror(remote) |
| 5167 | if mirror: |
| 5168 | pushurl = mirror.url |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 5169 | git_numberer_enabled = _is_git_numberer_enabled(pushurl, branch) |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5170 | else: |
| 5171 | pushurl = remote # Usually, this is 'origin'. |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 5172 | git_numberer_enabled = _is_git_numberer_enabled( |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5173 | RunGit(['config', 'remote.%s.url' % remote]).strip(), branch) |
| 5174 | |
Andrii Shyshkalov | aa31b97 | 2017-03-24 16:16:33 +0100 | [diff] [blame] | 5175 | retcode = PushToGitWithAutoRebase( |
| 5176 | pushurl, branch, commit_desc.description, git_numberer_enabled) |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5177 | if retcode == 0: |
| 5178 | revision = RunGit(['rev-parse', 'HEAD']).strip() |
Andrii Shyshkalov | aa31b97 | 2017-03-24 16:16:33 +0100 | [diff] [blame] | 5179 | if git_numberer_enabled: |
| 5180 | change_desc = ChangeDescription( |
| 5181 | RunGit(['show', '-s', '--format=%B', 'HEAD']).strip()) |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5182 | except: # pylint: disable=bare-except |
| 5183 | if _IS_BEING_TESTED: |
| 5184 | logging.exception('this is likely your ACTUAL cause of test failure.\n' |
| 5185 | + '-' * 30 + '8<' + '-' * 30) |
| 5186 | logging.error('\n' + '-' * 30 + '8<' + '-' * 30 + '\n\n\n') |
| 5187 | raise |
| 5188 | finally: |
| 5189 | # And then swap back to the original branch and clean up. |
| 5190 | RunGit(['checkout', '-q', cl.GetBranch()]) |
| 5191 | RunGit(['branch', '-D', MERGE_BRANCH]) |
Andrii Shyshkalov | aa31b97 | 2017-03-24 16:16:33 +0100 | [diff] [blame] | 5192 | RunGit(['branch', '-D', CHERRY_PICK_BRANCH], error_ok=True) |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5193 | |
| 5194 | if not revision: |
| 5195 | print('Failed to push. If this persists, please file a bug.') |
| 5196 | return 1 |
| 5197 | |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5198 | if cl.GetIssue(): |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5199 | viewvc_url = settings.GetViewVCUrl() |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 5200 | if viewvc_url and revision: |
| 5201 | change_desc.append_footer( |
| 5202 | 'Committed: %s%s' % (viewvc_url, revision)) |
| 5203 | elif revision: |
| 5204 | change_desc.append_footer('Committed: %s' % (revision,)) |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5205 | print('Closing issue ' |
| 5206 | '(you may be prompted for your codereview password)...') |
| 5207 | cl.UpdateDescription(change_desc.description) |
| 5208 | cl.CloseIssue() |
| 5209 | props = cl.GetIssueProperties() |
| 5210 | patch_num = len(props['patchsets']) |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 5211 | comment = "Committed patchset #%d (id:%d) manually as %s" % ( |
| 5212 | patch_num, props['patchsets'][-1], revision) |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5213 | if options.bypass_hooks: |
| 5214 | comment += ' (tree was closed).' if GetTreeStatus() == 'closed' else '.' |
| 5215 | else: |
| 5216 | comment += ' (presubmit successful).' |
| 5217 | cl.RpcServer().add_comment(cl.GetIssue(), comment) |
| 5218 | |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5219 | if os.path.isfile(POSTUPSTREAM_HOOK): |
| 5220 | RunCommand([POSTUPSTREAM_HOOK, merge_base], error_ok=True) |
| 5221 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 5222 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5223 | |
| 5224 | |
Andrii Shyshkalov | aa31b97 | 2017-03-24 16:16:33 +0100 | [diff] [blame] | 5225 | def PushToGitWithAutoRebase(remote, branch, original_description, |
| 5226 | git_numberer_enabled, max_attempts=3): |
| 5227 | """Pushes current HEAD commit on top of remote's branch. |
| 5228 | |
| 5229 | Attempts to fetch and autorebase on push failures. |
| 5230 | Adds git number footers on the fly. |
| 5231 | |
| 5232 | Returns integer code from last command. |
| 5233 | """ |
| 5234 | cherry = RunGit(['rev-parse', 'HEAD']).strip() |
| 5235 | code = 0 |
| 5236 | attempts_left = max_attempts |
| 5237 | while attempts_left: |
| 5238 | attempts_left -= 1 |
| 5239 | print('Attempt %d of %d' % (max_attempts - attempts_left, max_attempts)) |
| 5240 | |
| 5241 | # Fetch remote/branch into local cherry_pick_branch, overriding the latter. |
| 5242 | # If fetch fails, retry. |
| 5243 | print('Fetching %s/%s...' % (remote, branch)) |
| 5244 | code, out = RunGitWithCode( |
| 5245 | ['retry', 'fetch', remote, |
| 5246 | '+%s:refs/heads/%s' % (branch, CHERRY_PICK_BRANCH)]) |
| 5247 | if code: |
| 5248 | print('Fetch failed with exit code %d.' % code) |
| 5249 | print(out.strip()) |
| 5250 | continue |
| 5251 | |
| 5252 | print('Cherry-picking commit on top of latest %s' % branch) |
| 5253 | RunGitWithCode(['checkout', 'refs/heads/%s' % CHERRY_PICK_BRANCH], |
| 5254 | suppress_stderr=True) |
| 5255 | parent_hash = RunGit(['rev-parse', 'HEAD']).strip() |
| 5256 | code, out = RunGitWithCode(['cherry-pick', cherry]) |
| 5257 | if code: |
| 5258 | print('Your patch doesn\'t apply cleanly to \'%s\' HEAD @ %s, ' |
| 5259 | 'the following files have merge conflicts:' % |
| 5260 | (branch, parent_hash)) |
| 5261 | print(RunGit(['diff', '--name-status', '--diff-filter=U']).strip()) |
| 5262 | print('Please rebase your patch and try again.') |
| 5263 | RunGitWithCode(['cherry-pick', '--abort']) |
| 5264 | break |
| 5265 | |
| 5266 | commit_desc = ChangeDescription(original_description) |
| 5267 | if git_numberer_enabled: |
| 5268 | logging.debug('Adding git number footers') |
| 5269 | parent_msg = RunGit(['show', '-s', '--format=%B', parent_hash]).strip() |
| 5270 | commit_desc.update_with_git_number_footers(parent_hash, parent_msg, |
| 5271 | branch) |
| 5272 | # Ensure timestamps are monotonically increasing. |
| 5273 | timestamp = max(1 + _get_committer_timestamp(parent_hash), |
| 5274 | _get_committer_timestamp('HEAD')) |
| 5275 | _git_amend_head(commit_desc.description, timestamp) |
| 5276 | |
| 5277 | code, out = RunGitWithCode( |
| 5278 | ['push', '--porcelain', remote, 'HEAD:%s' % branch]) |
| 5279 | print(out) |
| 5280 | if code == 0: |
| 5281 | break |
| 5282 | if IsFatalPushFailure(out): |
| 5283 | print('Fatal push error. Make sure your .netrc credentials and git ' |
Andrii Shyshkalov | 9d93221 | 2017-04-10 14:28:23 +0200 | [diff] [blame] | 5284 | 'user.email are correct and you have push access to the repo.\n' |
| 5285 | 'Hint: run command below to diangose common Git/Gerrit credential ' |
| 5286 | 'problems:\n' |
| 5287 | ' git cl creds-check\n') |
Andrii Shyshkalov | aa31b97 | 2017-03-24 16:16:33 +0100 | [diff] [blame] | 5288 | break |
| 5289 | return code |
| 5290 | |
| 5291 | |
| 5292 | def IsFatalPushFailure(push_stdout): |
| 5293 | """True if retrying push won't help.""" |
| 5294 | return '(prohibited by Gerrit)' in push_stdout |
| 5295 | |
| 5296 | |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 5297 | @subcommand.usage('<patch url or issue id or issue url>') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5298 | def CMDpatch(parser, args): |
marq@chromium.org | e5e5900 | 2013-10-02 23:21:25 +0000 | [diff] [blame] | 5299 | """Patches in a code review.""" |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5300 | parser.add_option('-b', dest='newbranch', |
| 5301 | help='create a new branch off trunk for the patch') |
qsr@chromium.org | 1ef44af | 2013-10-16 16:24:32 +0000 | [diff] [blame] | 5302 | parser.add_option('-f', '--force', action='store_true', |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 5303 | help='overwrite state on the current or chosen branch') |
qsr@chromium.org | 1ef44af | 2013-10-16 16:24:32 +0000 | [diff] [blame] | 5304 | parser.add_option('-d', '--directory', action='store', metavar='DIR', |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 5305 | help='change to the directory DIR immediately, ' |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5306 | 'before doing anything else. Rietveld only.') |
qsr@chromium.org | 1ef44af | 2013-10-16 16:24:32 +0000 | [diff] [blame] | 5307 | parser.add_option('--reject', action='store_true', |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 5308 | help='failed patches spew .rej files rather than ' |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5309 | 'attempting a 3-way merge. Rietveld only.') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5310 | parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit', |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5311 | help='don\'t commit after patch applies. Rietveld only.') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5312 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5313 | |
| 5314 | group = optparse.OptionGroup( |
| 5315 | parser, |
| 5316 | 'Options for continuing work on the current issue uploaded from a ' |
| 5317 | 'different clone (e.g. different machine). Must be used independently ' |
| 5318 | 'from the other options. No issue number should be specified, and the ' |
| 5319 | 'branch must have an issue number associated with it') |
| 5320 | group.add_option('--reapply', action='store_true', dest='reapply', |
| 5321 | help='Reset the branch and reapply the issue.\n' |
| 5322 | 'CAUTION: This will undo any local changes in this ' |
| 5323 | 'branch') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5324 | |
| 5325 | group.add_option('--pull', action='store_true', dest='pull', |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5326 | help='Performs a pull before reapplying.') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5327 | parser.add_option_group(group) |
| 5328 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5329 | auth.add_auth_options(parser) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 5330 | _add_codereview_select_options(parser) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5331 | (options, args) = parser.parse_args(args) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 5332 | _process_codereview_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5333 | auth_config = auth.extract_auth_config_from_options(options) |
| 5334 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5335 | if options.reapply: |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5336 | if options.newbranch: |
| 5337 | parser.error('--reapply works on the current branch only') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5338 | if len(args) > 0: |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5339 | parser.error('--reapply implies no additional arguments') |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 5340 | |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5341 | cl = Changelist(auth_config=auth_config, |
| 5342 | codereview=options.forced_codereview) |
| 5343 | if not cl.GetIssue(): |
| 5344 | parser.error('current branch must have an associated issue') |
| 5345 | |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5346 | upstream = cl.GetUpstreamBranch() |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5347 | if upstream is None: |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5348 | parser.error('No upstream branch specified. Cannot reset branch') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5349 | |
| 5350 | RunGit(['reset', '--hard', upstream]) |
| 5351 | if options.pull: |
| 5352 | RunGit(['pull']) |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5353 | |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5354 | return cl.CMDPatchIssue(cl.GetIssue(), options.reject, options.nocommit, |
| 5355 | options.directory) |
| 5356 | |
| 5357 | if len(args) != 1 or not args[0]: |
| 5358 | parser.error('Must specify issue number or url') |
| 5359 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 5360 | target_issue_arg = ParseIssueNumberArgument(args[0], |
| 5361 | options.forced_codereview) |
| 5362 | if not target_issue_arg.valid: |
| 5363 | parser.error('invalid codereview url or CL id') |
| 5364 | |
| 5365 | cl_kwargs = { |
| 5366 | 'auth_config': auth_config, |
| 5367 | 'codereview_host': target_issue_arg.hostname, |
| 5368 | 'codereview': options.forced_codereview, |
| 5369 | } |
| 5370 | detected_codereview_from_url = False |
| 5371 | if target_issue_arg.codereview and not options.forced_codereview: |
| 5372 | detected_codereview_from_url = True |
| 5373 | cl_kwargs['codereview'] = target_issue_arg.codereview |
| 5374 | cl_kwargs['issue'] = target_issue_arg.issue |
| 5375 | |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5376 | # We don't want uncommitted changes mixed up with the patch. |
| 5377 | if git_common.is_dirty_git_tree('patch'): |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 5378 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5379 | |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5380 | if options.newbranch: |
| 5381 | if options.force: |
| 5382 | RunGit(['branch', '-D', options.newbranch], |
| 5383 | stderr=subprocess2.PIPE, error_ok=True) |
| 5384 | RunGit(['new-branch', options.newbranch]) |
tandrii | df09a46 | 2016-08-18 16:23:55 -0700 | [diff] [blame] | 5385 | elif not GetCurrentBranch(): |
| 5386 | DieWithError('A branch is required to apply patch. Hint: use -b option.') |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5387 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 5388 | cl = Changelist(**cl_kwargs) |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5389 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5390 | if cl.IsGerrit(): |
| 5391 | if options.reject: |
| 5392 | parser.error('--reject is not supported with Gerrit codereview.') |
| 5393 | if options.nocommit: |
| 5394 | parser.error('--nocommit is not supported with Gerrit codereview.') |
| 5395 | if options.directory: |
| 5396 | parser.error('--directory is not supported with Gerrit codereview.') |
| 5397 | |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 5398 | if detected_codereview_from_url: |
| 5399 | print('canonical issue/change URL: %s (type: %s)\n' % |
| 5400 | (cl.GetIssueURL(), target_issue_arg.codereview)) |
| 5401 | |
| 5402 | return cl.CMDPatchWithParsedIssue(target_issue_arg, options.reject, |
Aaron Gable | 62619a3 | 2017-06-16 08:22:09 -0700 | [diff] [blame] | 5403 | options.nocommit, options.directory, |
| 5404 | options.force) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5405 | |
| 5406 | |
jochen@chromium.org | 3ec0d54 | 2014-01-14 20:00:03 +0000 | [diff] [blame] | 5407 | def GetTreeStatus(url=None): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5408 | """Fetches the tree status and returns either 'open', 'closed', |
| 5409 | 'unknown' or 'unset'.""" |
jochen@chromium.org | 3ec0d54 | 2014-01-14 20:00:03 +0000 | [diff] [blame] | 5410 | url = url or settings.GetTreeStatusUrl(error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5411 | if url: |
| 5412 | status = urllib2.urlopen(url).read().lower() |
| 5413 | if status.find('closed') != -1 or status == '0': |
| 5414 | return 'closed' |
| 5415 | elif status.find('open') != -1 or status == '1': |
| 5416 | return 'open' |
| 5417 | return 'unknown' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5418 | return 'unset' |
| 5419 | |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 5420 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5421 | def GetTreeStatusReason(): |
| 5422 | """Fetches the tree status from a json url and returns the message |
| 5423 | with the reason for the tree to be opened or closed.""" |
msb@chromium.org | bf1a7ba | 2011-02-01 16:21:46 +0000 | [diff] [blame] | 5424 | url = settings.GetTreeStatusUrl() |
| 5425 | json_url = urlparse.urljoin(url, '/current?format=json') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5426 | connection = urllib2.urlopen(json_url) |
| 5427 | status = json.loads(connection.read()) |
| 5428 | connection.close() |
| 5429 | return status['message'] |
| 5430 | |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 5431 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5432 | def CMDtree(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5433 | """Shows the status of the tree.""" |
dpranke@chromium.org | 97ae58e | 2011-03-18 00:29:20 +0000 | [diff] [blame] | 5434 | _, args = parser.parse_args(args) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5435 | status = GetTreeStatus() |
| 5436 | if 'unset' == status: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5437 | 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] | 5438 | return 2 |
| 5439 | |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5440 | print('The tree is %s' % status) |
| 5441 | print() |
| 5442 | print(GetTreeStatusReason()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5443 | if status != 'open': |
| 5444 | return 1 |
| 5445 | return 0 |
| 5446 | |
| 5447 | |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5448 | def CMDtry(parser, args): |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 5449 | """Triggers try jobs using either BuildBucket or CQ dry run.""" |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5450 | group = optparse.OptionGroup(parser, 'Try job options') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5451 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5452 | '-b', '--bot', action='append', |
| 5453 | help=('IMPORTANT: specify ONE builder per --bot flag. Use it multiple ' |
| 5454 | 'times to specify multiple builders. ex: ' |
| 5455 | '"-b win_rel -b win_layout". See ' |
| 5456 | 'the try server waterfall for the builders name and the tests ' |
| 5457 | 'available.')) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5458 | group.add_option( |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 5459 | '-B', '--bucket', default='', |
| 5460 | help=('Buildbucket bucket to send the try requests.')) |
| 5461 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5462 | '-m', '--master', default='', |
| 5463 | help=('Specify a try master where to run the tries.')) |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 5464 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5465 | '-r', '--revision', |
tandrii | f7b29d4 | 2016-10-07 08:45:41 -0700 | [diff] [blame] | 5466 | help='Revision to use for the try job; default: the revision will ' |
| 5467 | 'be determined by the try recipe that builder runs, which usually ' |
| 5468 | 'defaults to HEAD of origin/master') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5469 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5470 | '-c', '--clobber', action='store_true', default=False, |
tandrii | f7b29d4 | 2016-10-07 08:45:41 -0700 | [diff] [blame] | 5471 | help='Force a clobber before building; that is don\'t do an ' |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5472 | 'incremental build') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5473 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5474 | '--project', |
| 5475 | help='Override which project to use. Projects are defined ' |
tandrii | f7b29d4 | 2016-10-07 08:45:41 -0700 | [diff] [blame] | 5476 | 'in recipe to determine to which repository or directory to ' |
| 5477 | 'apply the patch') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5478 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5479 | '-p', '--property', dest='properties', action='append', default=[], |
| 5480 | help='Specify generic properties in the form -p key1=value1 -p ' |
tandrii | f7b29d4 | 2016-10-07 08:45:41 -0700 | [diff] [blame] | 5481 | 'key2=value2 etc. The value will be treated as ' |
| 5482 | 'json if decodable, or as string otherwise. ' |
| 5483 | 'NOTE: using this may make your try job not usable for CQ, ' |
| 5484 | 'which will then schedule another try job with default properties') |
sheyang@chromium.org | db37557 | 2015-08-17 19:22:23 +0000 | [diff] [blame] | 5485 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5486 | '--buildbucket-host', default='cr-buildbucket.appspot.com', |
| 5487 | help='Host of buildbucket. The default host is %default.') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5488 | parser.add_option_group(group) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5489 | auth.add_auth_options(parser) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5490 | options, args = parser.parse_args(args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5491 | auth_config = auth.extract_auth_config_from_options(options) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5492 | |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 5493 | # Make sure that all properties are prop=value pairs. |
| 5494 | bad_params = [x for x in options.properties if '=' not in x] |
| 5495 | if bad_params: |
| 5496 | parser.error('Got properties with missing "=": %s' % bad_params) |
| 5497 | |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5498 | if args: |
| 5499 | parser.error('Unknown arguments: %s' % args) |
| 5500 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5501 | cl = Changelist(auth_config=auth_config) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5502 | if not cl.GetIssue(): |
| 5503 | parser.error('Need to upload first') |
| 5504 | |
Andrii Shyshkalov | eadad92 | 2017-01-26 09:38:30 +0100 | [diff] [blame] | 5505 | if cl.IsGerrit(): |
| 5506 | # HACK: warm up Gerrit change detail cache to save on RPCs. |
| 5507 | cl._codereview_impl._GetChangeDetail(['DETAILED_ACCOUNTS', 'ALL_REVISIONS']) |
| 5508 | |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 5509 | error_message = cl.CannotTriggerTryJobReason() |
| 5510 | if error_message: |
qyearsley | 99e2cdf | 2016-10-23 12:51:41 -0700 | [diff] [blame] | 5511 | parser.error('Can\'t trigger try jobs: %s' % error_message) |
jrobbins@chromium.org | 16f10f7 | 2014-06-24 22:14:36 +0000 | [diff] [blame] | 5512 | |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 5513 | if options.bucket and options.master: |
| 5514 | parser.error('Only one of --bucket and --master may be used.') |
| 5515 | |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 5516 | buckets = _get_bucket_map(cl, options, parser) |
phajdan.jr@chromium.org | 8da7f27 | 2014-03-14 01:28:39 +0000 | [diff] [blame] | 5517 | |
qyearsley | dd49f94 | 2016-10-28 11:57:22 -0700 | [diff] [blame] | 5518 | # If no bots are listed and we couldn't get a list based on PRESUBMIT files, |
| 5519 | # 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] | 5520 | if not buckets: |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 5521 | if options.verbose: |
Quinten Yearsley | fc5fd92 | 2017-05-31 11:50:52 -0700 | [diff] [blame] | 5522 | print('git cl try with no bots now defaults to CQ dry run.') |
| 5523 | print('Scheduling CQ dry run on: %s' % cl.GetIssueURL()) |
| 5524 | return cl.SetCQState(_CQState.DRY_RUN) |
stip@chromium.org | 43064fd | 2013-12-18 20:07:44 +0000 | [diff] [blame] | 5525 | |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 5526 | for builders in buckets.itervalues(): |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 5527 | if any('triggered' in b for b in builders): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5528 | 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] | 5529 | 'of bot requires an initial job from a parent (usually a builder). ' |
| 5530 | 'Instead send your job to the parent.\n' |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5531 | 'Bot list: %s' % builders, file=sys.stderr) |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 5532 | return 1 |
ilevy@chromium.org | f3b2123 | 2012-09-24 20:48:55 +0000 | [diff] [blame] | 5533 | |
ilevy@chromium.org | 36e420b | 2013-08-06 23:21:12 +0000 | [diff] [blame] | 5534 | patchset = cl.GetMostRecentPatchset() |
Ravi Mistry | fda50ca | 2016-11-14 10:19:18 -0500 | [diff] [blame] | 5535 | # TODO(tandrii): Checking local patchset against remote patchset is only |
| 5536 | # supported for Rietveld. Extend it to Gerrit or remove it completely. |
| 5537 | if not cl.IsGerrit() and patchset != cl.GetPatchset(): |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 5538 | print('Warning: Codereview server has newer patchsets (%s) than most ' |
| 5539 | 'recent upload from local checkout (%s). Did a previous upload ' |
| 5540 | 'fail?\n' |
| 5541 | 'By default, git cl try uses the latest patchset from ' |
| 5542 | 'codereview, continuing to use patchset %s.\n' % |
| 5543 | (patchset, cl.GetPatchset(), patchset)) |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 5544 | |
tandrii | 568043b | 2016-10-11 07:49:18 -0700 | [diff] [blame] | 5545 | try: |
borenet | 6c0efe6 | 2016-10-19 08:13:29 -0700 | [diff] [blame] | 5546 | _trigger_try_jobs(auth_config, cl, buckets, options, 'git_cl_try', |
| 5547 | patchset) |
tandrii | 568043b | 2016-10-11 07:49:18 -0700 | [diff] [blame] | 5548 | except BuildbucketResponseException as ex: |
| 5549 | print('ERROR: %s' % ex) |
| 5550 | return 1 |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5551 | return 0 |
| 5552 | |
| 5553 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5554 | def CMDtry_results(parser, args): |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5555 | """Prints info about try jobs associated with current CL.""" |
| 5556 | group = optparse.OptionGroup(parser, 'Try job results options') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5557 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5558 | '-p', '--patchset', type=int, help='patchset number if not current.') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5559 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5560 | '--print-master', action='store_true', help='print master name as well.') |
tandrii@chromium.org | 6cf98c8 | 2016-03-15 11:56:00 +0000 | [diff] [blame] | 5561 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5562 | '--color', action='store_true', default=setup_color.IS_TTY, |
| 5563 | help='force color output, useful when piping output.') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5564 | group.add_option( |
tandrii | 1838bad | 2016-10-06 00:10:52 -0700 | [diff] [blame] | 5565 | '--buildbucket-host', default='cr-buildbucket.appspot.com', |
| 5566 | help='Host of buildbucket. The default host is %default.') |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 5567 | group.add_option( |
Stefan Zager | 1306bd0 | 2017-06-22 19:26:46 -0700 | [diff] [blame] | 5568 | '--json', help=('Path of JSON output file to write try job results to,' |
| 5569 | 'or "-" for stdout.')) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5570 | parser.add_option_group(group) |
| 5571 | auth.add_auth_options(parser) |
| 5572 | options, args = parser.parse_args(args) |
| 5573 | if args: |
| 5574 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
| 5575 | |
| 5576 | auth_config = auth.extract_auth_config_from_options(options) |
| 5577 | cl = Changelist(auth_config=auth_config) |
| 5578 | if not cl.GetIssue(): |
| 5579 | parser.error('Need to upload first') |
| 5580 | |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 5581 | patchset = options.patchset |
| 5582 | if not patchset: |
| 5583 | patchset = cl.GetMostRecentPatchset() |
| 5584 | if not patchset: |
| 5585 | parser.error('Codereview doesn\'t know about issue %s. ' |
| 5586 | 'No access to issue or wrong issue number?\n' |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 5587 | 'Either upload first, or pass --patchset explicitly' % |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 5588 | cl.GetIssue()) |
| 5589 | |
Ravi Mistry | fda50ca | 2016-11-14 10:19:18 -0500 | [diff] [blame] | 5590 | # TODO(tandrii): Checking local patchset against remote patchset is only |
| 5591 | # supported for Rietveld. Extend it to Gerrit or remove it completely. |
| 5592 | if not cl.IsGerrit() and patchset != cl.GetPatchset(): |
tandrii | 45b2a58 | 2016-10-11 03:14:16 -0700 | [diff] [blame] | 5593 | print('Warning: Codereview server has newer patchsets (%s) than most ' |
| 5594 | 'recent upload from local checkout (%s). Did a previous upload ' |
| 5595 | 'fail?\n' |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 5596 | 'By default, git cl try-results uses the latest patchset from ' |
| 5597 | 'codereview, continuing to use patchset %s.\n' % |
tandrii | 45b2a58 | 2016-10-11 03:14:16 -0700 | [diff] [blame] | 5598 | (patchset, cl.GetPatchset(), patchset)) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5599 | try: |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 5600 | jobs = fetch_try_jobs(auth_config, cl, options.buildbucket_host, patchset) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5601 | except BuildbucketResponseException as ex: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5602 | print('Buildbucket error: %s' % ex) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5603 | return 1 |
qyearsley | 53f48a1 | 2016-09-01 10:45:13 -0700 | [diff] [blame] | 5604 | if options.json: |
| 5605 | write_try_results_json(options.json, jobs) |
| 5606 | else: |
| 5607 | print_try_jobs(options, jobs) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5608 | return 0 |
| 5609 | |
| 5610 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 5611 | @subcommand.usage('[new upstream branch]') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5612 | def CMDupstream(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5613 | """Prints or sets the name of the upstream branch, if any.""" |
dpranke@chromium.org | 97ae58e | 2011-03-18 00:29:20 +0000 | [diff] [blame] | 5614 | _, args = parser.parse_args(args) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5615 | if len(args) > 1: |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5616 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5617 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5618 | cl = Changelist() |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5619 | if args: |
| 5620 | # One arg means set upstream branch. |
bauerb@chromium.org | c9cf90a | 2014-04-28 20:32:31 +0000 | [diff] [blame] | 5621 | branch = cl.GetBranch() |
stip | 7a3dd35 | 2016-09-22 17:32:28 -0700 | [diff] [blame] | 5622 | RunGit(['branch', '--set-upstream-to', args[0], branch]) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5623 | cl = Changelist() |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5624 | print('Upstream branch set to %s' % (cl.GetUpstreamBranch(),)) |
bauerb@chromium.org | c9cf90a | 2014-04-28 20:32:31 +0000 | [diff] [blame] | 5625 | |
| 5626 | # Clear configured merge-base, if there is one. |
| 5627 | git_common.remove_merge_base(branch) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5628 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5629 | print(cl.GetUpstreamBranch()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5630 | return 0 |
| 5631 | |
| 5632 | |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 5633 | def CMDweb(parser, args): |
| 5634 | """Opens the current CL in the web browser.""" |
| 5635 | _, args = parser.parse_args(args) |
| 5636 | if args: |
| 5637 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
| 5638 | |
| 5639 | issue_url = Changelist().GetIssueURL() |
| 5640 | if not issue_url: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5641 | print('ERROR No issue to open', file=sys.stderr) |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 5642 | return 1 |
| 5643 | |
| 5644 | webbrowser.open(issue_url) |
| 5645 | return 0 |
| 5646 | |
| 5647 | |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5648 | def CMDset_commit(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5649 | """Sets the commit bit to trigger the Commit Queue.""" |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 5650 | parser.add_option('-d', '--dry-run', action='store_true', |
| 5651 | help='trigger in dry run mode') |
| 5652 | parser.add_option('-c', '--clear', action='store_true', |
| 5653 | help='stop CQ run, if any') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5654 | auth.add_auth_options(parser) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5655 | _add_codereview_issue_select_options(parser) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5656 | options, args = parser.parse_args(args) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5657 | _process_codereview_issue_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5658 | auth_config = auth.extract_auth_config_from_options(options) |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5659 | if args: |
| 5660 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 5661 | if options.dry_run and options.clear: |
| 5662 | parser.error('Make up your mind: both --dry-run and --clear not allowed') |
| 5663 | |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5664 | cl = Changelist(auth_config=auth_config, issue=options.issue, |
| 5665 | codereview=options.forced_codereview) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 5666 | if options.clear: |
tandrii | d9e5ce5 | 2016-07-13 02:32:59 -0700 | [diff] [blame] | 5667 | state = _CQState.NONE |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 5668 | elif options.dry_run: |
| 5669 | state = _CQState.DRY_RUN |
| 5670 | else: |
| 5671 | state = _CQState.COMMIT |
| 5672 | if not cl.GetIssue(): |
| 5673 | parser.error('Must upload the issue first') |
tandrii | 9de9ec6 | 2016-07-13 03:01:59 -0700 | [diff] [blame] | 5674 | cl.SetCQState(state) |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5675 | return 0 |
| 5676 | |
| 5677 | |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 5678 | def CMDset_close(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 5679 | """Closes the issue.""" |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5680 | _add_codereview_issue_select_options(parser) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5681 | auth.add_auth_options(parser) |
| 5682 | options, args = parser.parse_args(args) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5683 | _process_codereview_issue_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5684 | auth_config = auth.extract_auth_config_from_options(options) |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 5685 | if args: |
| 5686 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
iannucci | e53c935 | 2016-08-17 14:40:40 -0700 | [diff] [blame] | 5687 | cl = Changelist(auth_config=auth_config, issue=options.issue, |
| 5688 | codereview=options.forced_codereview) |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 5689 | # Ensure there actually is an issue to close. |
| 5690 | cl.GetDescription() |
| 5691 | cl.CloseIssue() |
| 5692 | return 0 |
| 5693 | |
| 5694 | |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5695 | def CMDdiff(parser, args): |
wychen@chromium.org | 37b2ec0 | 2015-04-03 00:49:15 +0000 | [diff] [blame] | 5696 | """Shows differences between local tree and last upload.""" |
thomasanderson | 074beb2 | 2016-08-29 14:03:20 -0700 | [diff] [blame] | 5697 | parser.add_option( |
| 5698 | '--stat', |
| 5699 | action='store_true', |
| 5700 | dest='stat', |
| 5701 | help='Generate a diffstat') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5702 | auth.add_auth_options(parser) |
| 5703 | options, args = parser.parse_args(args) |
| 5704 | auth_config = auth.extract_auth_config_from_options(options) |
| 5705 | if args: |
| 5706 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 5707 | |
| 5708 | # Uncommitted (staged and unstaged) changes will be destroyed by |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5709 | # "git reset --hard" if there are merging conflicts in CMDPatchIssue(). |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 5710 | # Staged changes would be committed along with the patch from last |
| 5711 | # upload, hence counted toward the "last upload" side in the final |
| 5712 | # diff output, and this is not what we want. |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 5713 | if git_common.is_dirty_git_tree('diff'): |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 5714 | return 1 |
| 5715 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5716 | cl = Changelist(auth_config=auth_config) |
sbc@chromium.org | 78dc984 | 2013-11-25 18:43:44 +0000 | [diff] [blame] | 5717 | issue = cl.GetIssue() |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5718 | branch = cl.GetBranch() |
sbc@chromium.org | 78dc984 | 2013-11-25 18:43:44 +0000 | [diff] [blame] | 5719 | if not issue: |
| 5720 | DieWithError('No issue found for current branch (%s)' % branch) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5721 | TMP_BRANCH = 'git-cl-diff' |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 5722 | base_branch = cl.GetCommonAncestorWithUpstream() |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5723 | |
| 5724 | # Create a new branch based on the merge-base |
| 5725 | RunGit(['checkout', '-q', '-b', TMP_BRANCH, base_branch]) |
tandrii@chromium.org | 534f67a | 2016-04-07 18:47:05 +0000 | [diff] [blame] | 5726 | # Clear cached branch in cl object, to avoid overwriting original CL branch |
| 5727 | # properties. |
| 5728 | cl.ClearBranch() |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5729 | try: |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5730 | rtn = cl.CMDPatchIssue(issue, reject=False, nocommit=False, directory=None) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5731 | if rtn != 0: |
wychen@chromium.org | a872e75 | 2015-04-28 23:42:18 +0000 | [diff] [blame] | 5732 | RunGit(['reset', '--hard']) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5733 | return rtn |
| 5734 | |
wychen@chromium.org | 0692853 | 2015-02-03 02:11:29 +0000 | [diff] [blame] | 5735 | # Switch back to starting branch and diff against the temporary |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5736 | # branch containing the latest rietveld patch. |
thomasanderson | 074beb2 | 2016-08-29 14:03:20 -0700 | [diff] [blame] | 5737 | cmd = ['git', 'diff'] |
| 5738 | if options.stat: |
| 5739 | cmd.append('--stat') |
| 5740 | cmd.extend([TMP_BRANCH, branch, '--']) |
| 5741 | subprocess2.check_call(cmd) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5742 | finally: |
| 5743 | RunGit(['checkout', '-q', branch]) |
| 5744 | RunGit(['branch', '-D', TMP_BRANCH]) |
| 5745 | |
| 5746 | return 0 |
| 5747 | |
| 5748 | |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5749 | def CMDowners(parser, args): |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 5750 | """Interactively finds potential owners for reviewing.""" |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5751 | parser.add_option( |
| 5752 | '--no-color', |
| 5753 | action='store_true', |
| 5754 | help='Use this option to disable color output') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5755 | auth.add_auth_options(parser) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5756 | options, args = parser.parse_args(args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5757 | auth_config = auth.extract_auth_config_from_options(options) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5758 | |
| 5759 | author = RunGit(['config', 'user.email']).strip() or None |
| 5760 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5761 | cl = Changelist(auth_config=auth_config) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5762 | |
| 5763 | if args: |
| 5764 | if len(args) > 1: |
| 5765 | parser.error('Unknown args') |
| 5766 | base_branch = args[0] |
| 5767 | else: |
| 5768 | # Default to diffing against the common ancestor of the upstream branch. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 5769 | base_branch = cl.GetCommonAncestorWithUpstream() |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5770 | |
| 5771 | change = cl.GetChange(base_branch, None) |
| 5772 | return owners_finder.OwnersFinder( |
| 5773 | [f.LocalPath() for f in |
| 5774 | cl.GetChange(base_branch, None).AffectedFiles()], |
Jochen Eisinger | 72606f8 | 2017-04-04 10:44:18 +0200 | [diff] [blame] | 5775 | change.RepositoryRoot(), |
Jochen Eisinger | 72606f8 | 2017-04-04 10:44:18 +0200 | [diff] [blame] | 5776 | author, fopen=file, os_path=os.path, |
Jochen Eisinger | d0573ec | 2017-04-13 10:55:06 +0200 | [diff] [blame] | 5777 | disable_color=options.no_color, |
| 5778 | override_files=change.OriginalOwnersFiles()).run() |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5779 | |
| 5780 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5781 | def BuildGitDiffCmd(diff_type, upstream_commit, args): |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5782 | """Generates a diff command.""" |
| 5783 | # Generate diff for the current branch's changes. |
| 5784 | diff_cmd = ['diff', '--no-ext-diff', '--no-prefix', diff_type, |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5785 | upstream_commit, '--'] |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5786 | |
| 5787 | if args: |
| 5788 | for arg in args: |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5789 | if os.path.isdir(arg) or os.path.isfile(arg): |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5790 | diff_cmd.append(arg) |
| 5791 | else: |
| 5792 | DieWithError('Argument "%s" is not a file or a directory' % arg) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5793 | |
| 5794 | return diff_cmd |
| 5795 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5796 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5797 | def MatchingFileType(file_name, extensions): |
| 5798 | """Returns true if the file name ends with one of the given extensions.""" |
| 5799 | 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] | 5800 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5801 | |
enne@chromium.org | 555cfe4 | 2014-01-29 18:21:39 +0000 | [diff] [blame] | 5802 | @subcommand.usage('[files or directories to diff]') |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5803 | def CMDformat(parser, args): |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5804 | """Runs auto-formatting tools (clang-format etc.) on the diff.""" |
Christopher Lam | c5ba692 | 2017-01-24 11:19:14 +1100 | [diff] [blame] | 5805 | CLANG_EXTS = ['.cc', '.cpp', '.h', '.m', '.mm', '.proto', '.java'] |
kylechar | 58edce2 | 2016-06-17 06:07:51 -0700 | [diff] [blame] | 5806 | GN_EXTS = ['.gn', '.gni', '.typemap'] |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 5807 | parser.add_option('--full', action='store_true', |
| 5808 | help='Reformat the full content of all touched files') |
| 5809 | parser.add_option('--dry-run', action='store_true', |
| 5810 | help='Don\'t modify any file on disk.') |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5811 | parser.add_option('--python', action='store_true', |
| 5812 | help='Format python code with yapf (experimental).') |
Christopher Lam | c5ba692 | 2017-01-24 11:19:14 +1100 | [diff] [blame] | 5813 | parser.add_option('--js', action='store_true', |
| 5814 | help='Format javascript code with clang-format.') |
wittman@chromium.org | 04d5a22 | 2014-03-07 18:30:42 +0000 | [diff] [blame] | 5815 | parser.add_option('--diff', action='store_true', |
| 5816 | help='Print diff to stdout rather than modifying files.') |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5817 | opts, args = parser.parse_args(args) |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5818 | |
Daniel Cheng | c55eecf | 2016-12-30 03:11:02 -0800 | [diff] [blame] | 5819 | # Normalize any remaining args against the current path, so paths relative to |
| 5820 | # the current directory are still resolved as expected. |
| 5821 | args = [os.path.join(os.getcwd(), arg) for arg in args] |
| 5822 | |
enne@chromium.org | ff7a1fb | 2013-12-10 19:21:41 +0000 | [diff] [blame] | 5823 | # git diff generates paths against the root of the repository. Change |
| 5824 | # 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] | 5825 | rel_base_path = settings.GetRelativeRoot() |
enne@chromium.org | ff7a1fb | 2013-12-10 19:21:41 +0000 | [diff] [blame] | 5826 | if rel_base_path: |
| 5827 | os.chdir(rel_base_path) |
| 5828 | |
digit@chromium.org | 29e4727 | 2013-05-17 17:01:46 +0000 | [diff] [blame] | 5829 | # Grab the merge-base commit, i.e. the upstream commit of the current |
| 5830 | # branch when it was created or the last time it was rebased. This is |
| 5831 | # to cover the case where the user may have called "git fetch origin", |
| 5832 | # moving the origin branch to a newer commit, but hasn't rebased yet. |
| 5833 | upstream_commit = None |
| 5834 | cl = Changelist() |
| 5835 | upstream_branch = cl.GetUpstreamBranch() |
| 5836 | if upstream_branch: |
| 5837 | upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch]) |
| 5838 | upstream_commit = upstream_commit.strip() |
| 5839 | |
| 5840 | if not upstream_commit: |
| 5841 | DieWithError('Could not find base commit for this branch. ' |
| 5842 | 'Are you in detached state?') |
| 5843 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5844 | changed_files_cmd = BuildGitDiffCmd('--name-only', upstream_commit, args) |
| 5845 | diff_output = RunGit(changed_files_cmd) |
| 5846 | diff_files = diff_output.splitlines() |
jkarlin@chromium.org | ad21b92 | 2016-01-28 17:48:42 +0000 | [diff] [blame] | 5847 | # Filter out files deleted by this CL |
| 5848 | 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] | 5849 | |
Christopher Lam | c5ba692 | 2017-01-24 11:19:14 +1100 | [diff] [blame] | 5850 | if opts.js: |
| 5851 | CLANG_EXTS.append('.js') |
| 5852 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5853 | clang_diff_files = [x for x in diff_files if MatchingFileType(x, CLANG_EXTS)] |
| 5854 | python_diff_files = [x for x in diff_files if MatchingFileType(x, ['.py'])] |
| 5855 | 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] | 5856 | 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] | 5857 | |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 5858 | top_dir = os.path.normpath( |
| 5859 | RunGit(["rev-parse", "--show-toplevel"]).rstrip('\n')) |
| 5860 | |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5861 | # Set to 2 to signal to CheckPatchFormatted() that this patch isn't |
| 5862 | # formatted. This is used to block during the presubmit. |
| 5863 | return_value = 0 |
| 5864 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5865 | if clang_diff_files: |
techtonik@gmail.com | 5573df1 | 2016-04-12 18:34:10 +0000 | [diff] [blame] | 5866 | # Locate the clang-format binary in the checkout |
| 5867 | try: |
| 5868 | clang_format_tool = clang_format.FindClangFormatToolInChromiumTree() |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 5869 | except clang_format.NotFoundError as e: |
techtonik@gmail.com | 5573df1 | 2016-04-12 18:34:10 +0000 | [diff] [blame] | 5870 | DieWithError(e) |
| 5871 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5872 | if opts.full: |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5873 | cmd = [clang_format_tool] |
| 5874 | if not opts.dry_run and not opts.diff: |
| 5875 | cmd.append('-i') |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5876 | stdout = RunCommand(cmd + clang_diff_files, cwd=top_dir) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5877 | if opts.diff: |
| 5878 | sys.stdout.write(stdout) |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5879 | else: |
| 5880 | env = os.environ.copy() |
| 5881 | env['PATH'] = str(os.path.dirname(clang_format_tool)) |
| 5882 | try: |
| 5883 | script = clang_format.FindClangFormatScriptInChromiumTree( |
| 5884 | 'clang-format-diff.py') |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 5885 | except clang_format.NotFoundError as e: |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5886 | DieWithError(e) |
digit@chromium.org | d6ddc1c | 2013-10-25 15:36:32 +0000 | [diff] [blame] | 5887 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5888 | cmd = [sys.executable, script, '-p0'] |
| 5889 | if not opts.dry_run and not opts.diff: |
| 5890 | cmd.append('-i') |
digit@chromium.org | d6ddc1c | 2013-10-25 15:36:32 +0000 | [diff] [blame] | 5891 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5892 | diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, clang_diff_files) |
| 5893 | diff_output = RunGit(diff_cmd) |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5894 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 5895 | stdout = RunCommand(cmd, stdin=diff_output, cwd=top_dir, env=env) |
| 5896 | if opts.diff: |
| 5897 | sys.stdout.write(stdout) |
| 5898 | if opts.dry_run and len(stdout) > 0: |
| 5899 | return_value = 2 |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5900 | |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5901 | # Similar code to above, but using yapf on .py files rather than clang-format |
| 5902 | # on C/C++ files |
| 5903 | if opts.python: |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5904 | yapf_tool = gclient_utils.FindExecutable('yapf') |
| 5905 | if yapf_tool is None: |
| 5906 | DieWithError('yapf not found in PATH') |
| 5907 | |
| 5908 | if opts.full: |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5909 | if python_diff_files: |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5910 | cmd = [yapf_tool] |
| 5911 | if not opts.dry_run and not opts.diff: |
| 5912 | cmd.append('-i') |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5913 | stdout = RunCommand(cmd + python_diff_files, cwd=top_dir) |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 5914 | if opts.diff: |
| 5915 | sys.stdout.write(stdout) |
| 5916 | else: |
| 5917 | # TODO(sbc): yapf --lines mode still has some issues. |
| 5918 | # https://github.com/google/yapf/issues/154 |
| 5919 | DieWithError('--python currently only works with --full') |
| 5920 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5921 | # Dart's formatter does not have the nice property of only operating on |
| 5922 | # modified chunks, so hard code full. |
| 5923 | if dart_diff_files: |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5924 | try: |
| 5925 | command = [dart_format.FindDartFmtToolInChromiumTree()] |
| 5926 | if not opts.dry_run and not opts.diff: |
| 5927 | command.append('-w') |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 5928 | command.extend(dart_diff_files) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5929 | |
ppi@chromium.org | 6593d93 | 2016-03-03 15:41:15 +0000 | [diff] [blame] | 5930 | stdout = RunCommand(command, cwd=top_dir) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5931 | if opts.dry_run and stdout: |
| 5932 | return_value = 2 |
| 5933 | except dart_format.NotFoundError as e: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 5934 | print('Warning: Unable to check Dart code formatting. Dart SDK not ' |
| 5935 | 'found in this checkout. Files in other languages are still ' |
| 5936 | 'formatted.') |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5937 | |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 5938 | # Format GN build files. Always run on full build files for canonical form. |
| 5939 | if gn_diff_files: |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 5940 | cmd = ['gn', 'format'] |
brettw | 4b8ed59 | 2016-08-05 16:19:12 -0700 | [diff] [blame] | 5941 | if opts.dry_run or opts.diff: |
| 5942 | cmd.append('--dry-run') |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 5943 | for gn_diff_file in gn_diff_files: |
brettw | 4b8ed59 | 2016-08-05 16:19:12 -0700 | [diff] [blame] | 5944 | gn_ret = subprocess2.call(cmd + [gn_diff_file], |
| 5945 | shell=sys.platform == 'win32', |
| 5946 | cwd=top_dir) |
| 5947 | if opts.dry_run and gn_ret == 2: |
| 5948 | return_value = 2 # Not formatted. |
| 5949 | elif opts.diff and gn_ret == 2: |
| 5950 | # TODO this should compute and print the actual diff. |
| 5951 | print("This change has GN build file diff for " + gn_diff_file) |
| 5952 | elif gn_ret != 0: |
| 5953 | # For non-dry run cases (and non-2 return values for dry-run), a |
| 5954 | # nonzero error code indicates a failure, probably because the file |
| 5955 | # doesn't parse. |
| 5956 | DieWithError("gn format failed on " + gn_diff_file + |
| 5957 | "\nTry running 'gn format' on this file manually.") |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 5958 | |
Steven Holte | 2e664bf | 2017-04-21 13:10:47 -0700 | [diff] [blame] | 5959 | for xml_dir in GetDirtyMetricsDirs(diff_files): |
| 5960 | tool_dir = os.path.join(top_dir, xml_dir) |
| 5961 | cmd = [os.path.join(tool_dir, 'pretty_print.py'), '--non-interactive'] |
| 5962 | if opts.dry_run or opts.diff: |
| 5963 | cmd.append('--diff') |
| 5964 | stdout = RunCommand(cmd, cwd=top_dir) |
| 5965 | if opts.diff: |
| 5966 | sys.stdout.write(stdout) |
| 5967 | if opts.dry_run and stdout: |
| 5968 | return_value = 2 # Not formatted. |
Alexei Svitkine | f3cac41 | 2017-02-06 11:08:50 -0500 | [diff] [blame] | 5969 | |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 5970 | return return_value |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5971 | |
Steven Holte | 2e664bf | 2017-04-21 13:10:47 -0700 | [diff] [blame] | 5972 | def GetDirtyMetricsDirs(diff_files): |
| 5973 | xml_diff_files = [x for x in diff_files if MatchingFileType(x, ['.xml'])] |
| 5974 | metrics_xml_dirs = [ |
| 5975 | os.path.join('tools', 'metrics', 'actions'), |
| 5976 | os.path.join('tools', 'metrics', 'histograms'), |
| 5977 | os.path.join('tools', 'metrics', 'rappor'), |
| 5978 | os.path.join('tools', 'metrics', 'ukm')] |
| 5979 | for xml_dir in metrics_xml_dirs: |
| 5980 | if any(file.startswith(xml_dir) for file in xml_diff_files): |
| 5981 | yield xml_dir |
| 5982 | |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 5983 | |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5984 | @subcommand.usage('<codereview url or issue id>') |
| 5985 | def CMDcheckout(parser, args): |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 5986 | """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] | 5987 | _, args = parser.parse_args(args) |
| 5988 | |
| 5989 | if len(args) != 1: |
| 5990 | parser.print_help() |
| 5991 | return 1 |
| 5992 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 5993 | issue_arg = ParseIssueNumberArgument(args[0]) |
tandrii@chromium.org | de6c9a1 | 2016-04-11 15:33:53 +0000 | [diff] [blame] | 5994 | if not issue_arg.valid: |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 5995 | parser.error('invalid codereview url or CL id') |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 5996 | |
tandrii@chromium.org | abd27e5 | 2016-04-11 15:43:32 +0000 | [diff] [blame] | 5997 | target_issue = str(issue_arg.issue) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 5998 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 5999 | def find_issues(issueprefix): |
tandrii@chromium.org | 26c8fd2 | 2016-04-11 21:33:21 +0000 | [diff] [blame] | 6000 | output = RunGit(['config', '--local', '--get-regexp', |
| 6001 | r'branch\..*\.%s' % issueprefix], |
| 6002 | error_ok=True) |
| 6003 | for key, issue in [x.split() for x in output.splitlines()]: |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 6004 | if issue == target_issue: |
| 6005 | yield re.sub(r'branch\.(.*)\.%s' % issueprefix, r'\1', key) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6006 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 6007 | branches = [] |
| 6008 | for cls in _CODEREVIEW_IMPLEMENTATIONS.values(): |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 6009 | branches.extend(find_issues(cls.IssueConfigKey())) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6010 | if len(branches) == 0: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 6011 | print('No branch found for issue %s.' % target_issue) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6012 | return 1 |
| 6013 | if len(branches) == 1: |
| 6014 | RunGit(['checkout', branches[0]]) |
| 6015 | else: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 6016 | print('Multiple branches match issue %s:' % target_issue) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6017 | for i in range(len(branches)): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 6018 | print('%d: %s' % (i, branches[i])) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6019 | which = raw_input('Choose by index: ') |
| 6020 | try: |
| 6021 | RunGit(['checkout', branches[int(which)]]) |
| 6022 | except (IndexError, ValueError): |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 6023 | print('Invalid selection, not checking out any branch.') |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6024 | return 1 |
| 6025 | |
| 6026 | return 0 |
| 6027 | |
| 6028 | |
maruel@chromium.org | 29404b5 | 2014-09-08 22:58:00 +0000 | [diff] [blame] | 6029 | def CMDlol(parser, args): |
| 6030 | # This command is intentionally undocumented. |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 6031 | print(zlib.decompress(base64.b64decode( |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 6032 | 'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE' |
| 6033 | 'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9' |
| 6034 | 'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W' |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 6035 | 'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY'))) |
maruel@chromium.org | 29404b5 | 2014-09-08 22:58:00 +0000 | [diff] [blame] | 6036 | return 0 |
| 6037 | |
| 6038 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 6039 | class OptionParser(optparse.OptionParser): |
| 6040 | """Creates the option parse and add --verbose support.""" |
| 6041 | def __init__(self, *args, **kwargs): |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 6042 | optparse.OptionParser.__init__( |
| 6043 | self, *args, prog='git cl', version=__version__, **kwargs) |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 6044 | self.add_option( |
| 6045 | '-v', '--verbose', action='count', default=0, |
| 6046 | help='Use 2 times for more debugging info') |
| 6047 | |
| 6048 | def parse_args(self, args=None, values=None): |
| 6049 | options, args = optparse.OptionParser.parse_args(self, args, values) |
| 6050 | levels = [logging.WARNING, logging.INFO, logging.DEBUG] |
Andrii Shyshkalov | 5b04a57 | 2017-01-23 17:44:41 +0100 | [diff] [blame] | 6051 | logging.basicConfig( |
| 6052 | level=levels[min(options.verbose, len(levels) - 1)], |
| 6053 | format='[%(levelname).1s%(asctime)s %(process)d %(thread)d ' |
| 6054 | '%(filename)s] %(message)s') |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 6055 | return options, args |
| 6056 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 6057 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 6058 | def main(argv): |
maruel@chromium.org | 82798cb | 2012-02-23 18:16:12 +0000 | [diff] [blame] | 6059 | if sys.hexversion < 0x02060000: |
vapier | a7fbd5a | 2016-06-16 09:17:49 -0700 | [diff] [blame] | 6060 | print('\nYour python version %s is unsupported, please upgrade.\n' % |
| 6061 | (sys.version.split(' ', 1)[0],), file=sys.stderr) |
maruel@chromium.org | 82798cb | 2012-02-23 18:16:12 +0000 | [diff] [blame] | 6062 | return 2 |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 6063 | |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 6064 | # Reload settings. |
| 6065 | global settings |
| 6066 | settings = Settings() |
| 6067 | |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 6068 | colorize_CMDstatus_doc() |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 6069 | dispatcher = subcommand.CommandDispatcher(__name__) |
| 6070 | try: |
| 6071 | return dispatcher.execute(OptionParser(), argv) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 6072 | except auth.AuthenticationError as e: |
| 6073 | DieWithError(str(e)) |
vapier | fd77ac7 | 2016-06-16 08:33:57 -0700 | [diff] [blame] | 6074 | except urllib2.HTTPError as e: |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 6075 | if e.code != 500: |
| 6076 | raise |
| 6077 | DieWithError( |
| 6078 | ('AppEngine is misbehaving and returned HTTP %d, again. Keep faith ' |
| 6079 | '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] | 6080 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 6081 | |
| 6082 | |
| 6083 | if __name__ == '__main__': |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 6084 | # These affect sys.stdout so do it outside of main() to simplify mocks in |
| 6085 | # unit testing. |
maruel@chromium.org | 6f09cd9 | 2011-04-01 16:38:12 +0000 | [diff] [blame] | 6086 | fix_encoding.fix_encoding() |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 6087 | setup_color.init() |
sbc@chromium.org | 013731e | 2015-02-26 18:28:43 +0000 | [diff] [blame] | 6088 | try: |
| 6089 | sys.exit(main(sys.argv[1:])) |
| 6090 | except KeyboardInterrupt: |
| 6091 | sys.stderr.write('interrupted\n') |
| 6092 | sys.exit(1) |