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 | |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 10 | from distutils.version import LooseVersion |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 11 | from multiprocessing.pool import ThreadPool |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 12 | import base64 |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 13 | import collections |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 14 | import glob |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 15 | import httplib |
maruel@chromium.org | 4f6852c | 2012-04-20 20:39:20 +0000 | [diff] [blame] | 16 | import json |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 17 | import logging |
| 18 | import optparse |
| 19 | import os |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 20 | import Queue |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 21 | import re |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 22 | import stat |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 23 | import sys |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 24 | import tempfile |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 25 | import textwrap |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 26 | import time |
| 27 | import traceback |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 28 | import urllib |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 29 | import urllib2 |
maruel@chromium.org | 967c0a8 | 2013-06-17 22:52:24 +0000 | [diff] [blame] | 30 | import urlparse |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 31 | import uuid |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 32 | import webbrowser |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 33 | import zlib |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 34 | |
| 35 | try: |
maruel@chromium.org | c98c0c5 | 2011-04-06 13:39:43 +0000 | [diff] [blame] | 36 | import readline # pylint: disable=F0401,W0611 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 37 | except ImportError: |
| 38 | pass |
| 39 | |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 40 | from third_party import colorama |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 41 | from third_party import httplib2 |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 42 | from third_party import upload |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 43 | import auth |
hinoka@chromium.org | feb9e2a | 2015-09-25 19:11:09 +0000 | [diff] [blame] | 44 | from luci_hacks import trigger_luci_job as luci_trigger |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 45 | import clang_format |
tandrii@chromium.org | 71184c0 | 2016-01-13 15:18:44 +0000 | [diff] [blame] | 46 | import commit_queue |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 47 | import dart_format |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 48 | import setup_color |
maruel@chromium.org | 6f09cd9 | 2011-04-01 16:38:12 +0000 | [diff] [blame] | 49 | import fix_encoding |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 50 | import gclient_utils |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 51 | import gerrit_util |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 52 | import git_cache |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 53 | import git_common |
tandrii@chromium.org | 09d7a6a | 2016-03-04 15:44:48 +0000 | [diff] [blame] | 54 | import git_footers |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 55 | import owners |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 56 | import owners_finder |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 57 | import presubmit_support |
maruel@chromium.org | cab38e9 | 2011-04-09 00:30:51 +0000 | [diff] [blame] | 58 | import rietveld |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 59 | import scm |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 60 | import subcommand |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 61 | import subprocess2 |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 62 | import watchlists |
| 63 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 64 | __version__ = '1.0' |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 65 | |
maruel@chromium.org | eb5edbc | 2012-01-16 17:03:28 +0000 | [diff] [blame] | 66 | DEFAULT_SERVER = 'https://codereview.appspot.com' |
maruel@chromium.org | 0ba7f96 | 2011-01-11 22:13:58 +0000 | [diff] [blame] | 67 | POSTUPSTREAM_HOOK_PATTERN = '.git/hooks/post-cl-%s' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 68 | DESCRIPTION_BACKUP_FILE = '~/.git_cl_description_backup' |
pgervais@chromium.org | d6617f3 | 2013-11-19 00:34:54 +0000 | [diff] [blame] | 69 | GIT_INSTRUCTIONS_URL = 'http://code.google.com/p/chromium/wiki/UsingGit' |
rmistry@google.com | c68112d | 2015-03-03 12:48:06 +0000 | [diff] [blame] | 70 | REFS_THAT_ALIAS_TO_OTHER_REFS = { |
| 71 | 'refs/remotes/origin/lkgr': 'refs/remotes/origin/master', |
| 72 | 'refs/remotes/origin/lkcr': 'refs/remotes/origin/master', |
| 73 | } |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 74 | |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 75 | # Valid extensions for files we want to lint. |
| 76 | DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)" |
| 77 | DEFAULT_LINT_IGNORE_REGEX = r"$^" |
| 78 | |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 79 | # Shortcut since it quickly becomes redundant. |
| 80 | Fore = colorama.Fore |
maruel@chromium.org | 9054173 | 2011-04-01 17:54:18 +0000 | [diff] [blame] | 81 | |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 82 | # Initialized in main() |
| 83 | settings = None |
| 84 | |
| 85 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 86 | def DieWithError(message): |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 87 | print >> sys.stderr, message |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 88 | sys.exit(1) |
| 89 | |
| 90 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 91 | def GetNoGitPagerEnv(): |
| 92 | env = os.environ.copy() |
| 93 | # 'cat' is a magical git string that disables pagers on all platforms. |
| 94 | env['GIT_PAGER'] = 'cat' |
| 95 | return env |
| 96 | |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 97 | |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 98 | def RunCommand(args, error_ok=False, error_message=None, **kwargs): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 99 | try: |
maruel@chromium.org | 373af80 | 2012-05-25 21:07:33 +0000 | [diff] [blame] | 100 | return subprocess2.check_output(args, shell=False, **kwargs) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 101 | except subprocess2.CalledProcessError as e: |
| 102 | logging.debug('Failed running %s', args) |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 103 | if not error_ok: |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 104 | DieWithError( |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 105 | 'Command "%s" failed.\n%s' % ( |
| 106 | ' '.join(args), error_message or e.stdout or '')) |
| 107 | return e.stdout |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 108 | |
| 109 | |
| 110 | def RunGit(args, **kwargs): |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 111 | """Returns stdout.""" |
bratell@opera.com | 82b91cd | 2013-07-09 06:33:41 +0000 | [diff] [blame] | 112 | return RunCommand(['git'] + args, **kwargs) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 113 | |
| 114 | |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 115 | def RunGitWithCode(args, suppress_stderr=False): |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 116 | """Returns return code and stdout.""" |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 117 | try: |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 118 | if suppress_stderr: |
| 119 | stderr = subprocess2.VOID |
| 120 | else: |
| 121 | stderr = sys.stderr |
bratell@opera.com | 82b91cd | 2013-07-09 06:33:41 +0000 | [diff] [blame] | 122 | out, code = subprocess2.communicate(['git'] + args, |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 123 | env=GetNoGitPagerEnv(), |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 124 | stdout=subprocess2.PIPE, |
| 125 | stderr=stderr) |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 126 | return code, out[0] |
| 127 | except ValueError: |
| 128 | # When the subprocess fails, it returns None. That triggers a ValueError |
| 129 | # when trying to unpack the return value into (out, code). |
| 130 | return 1, '' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 131 | |
| 132 | |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 133 | def RunGitSilent(args): |
| 134 | """Returns stdout, suppresses stderr and ingores the return code.""" |
| 135 | return RunGitWithCode(args, suppress_stderr=True)[1] |
| 136 | |
| 137 | |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 138 | def IsGitVersionAtLeast(min_version): |
ilevy@chromium.org | cc56ee4 | 2013-07-10 22:16:29 +0000 | [diff] [blame] | 139 | prefix = 'git version ' |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 140 | version = RunGit(['--version']).strip() |
ilevy@chromium.org | cc56ee4 | 2013-07-10 22:16:29 +0000 | [diff] [blame] | 141 | return (version.startswith(prefix) and |
| 142 | LooseVersion(version[len(prefix):]) >= LooseVersion(min_version)) |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 143 | |
| 144 | |
pgervais@chromium.org | 8ba38ff | 2015-06-11 21:41:25 +0000 | [diff] [blame] | 145 | def BranchExists(branch): |
| 146 | """Return True if specified branch exists.""" |
| 147 | code, _ = RunGitWithCode(['rev-parse', '--verify', branch], |
| 148 | suppress_stderr=True) |
| 149 | return not code |
| 150 | |
| 151 | |
maruel@chromium.org | 9054173 | 2011-04-01 17:54:18 +0000 | [diff] [blame] | 152 | def ask_for_data(prompt): |
| 153 | try: |
| 154 | return raw_input(prompt) |
| 155 | except KeyboardInterrupt: |
| 156 | # Hide the exception. |
| 157 | sys.exit(1) |
| 158 | |
| 159 | |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 160 | def git_set_branch_value(key, value): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 161 | branch = GetCurrentBranch() |
rogerta@chromium.org | caa1655 | 2013-03-18 20:45:05 +0000 | [diff] [blame] | 162 | if not branch: |
| 163 | return |
| 164 | |
| 165 | cmd = ['config'] |
| 166 | if isinstance(value, int): |
| 167 | cmd.append('--int') |
| 168 | git_key = 'branch.%s.%s' % (branch, key) |
| 169 | RunGit(cmd + [git_key, str(value)]) |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 170 | |
| 171 | |
| 172 | def git_get_branch_default(key, default): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 173 | branch = GetCurrentBranch() |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 174 | if branch: |
| 175 | git_key = 'branch.%s.%s' % (branch, key) |
| 176 | (_, stdout) = RunGitWithCode(['config', '--int', '--get', git_key]) |
| 177 | try: |
| 178 | return int(stdout.strip()) |
| 179 | except ValueError: |
| 180 | pass |
| 181 | return default |
| 182 | |
| 183 | |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 184 | def add_git_similarity(parser): |
| 185 | parser.add_option( |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 186 | '--similarity', metavar='SIM', type='int', action='store', |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 187 | help='Sets the percentage that a pair of files need to match in order to' |
| 188 | ' be considered copies (default 50)') |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 189 | parser.add_option( |
| 190 | '--find-copies', action='store_true', |
| 191 | help='Allows git to look for copies.') |
| 192 | parser.add_option( |
| 193 | '--no-find-copies', action='store_false', dest='find_copies', |
| 194 | help='Disallows git from looking for copies.') |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 195 | |
| 196 | old_parser_args = parser.parse_args |
| 197 | def Parse(args): |
| 198 | options, args = old_parser_args(args) |
| 199 | |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 200 | if options.similarity is None: |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 201 | options.similarity = git_get_branch_default('git-cl-similarity', 50) |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 202 | else: |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 203 | print('Note: Saving similarity of %d%% in git config.' |
| 204 | % options.similarity) |
| 205 | git_set_branch_value('git-cl-similarity', options.similarity) |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 206 | |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 207 | options.similarity = max(0, min(options.similarity, 100)) |
| 208 | |
| 209 | if options.find_copies is None: |
| 210 | options.find_copies = bool( |
| 211 | git_get_branch_default('git-find-copies', True)) |
| 212 | else: |
| 213 | git_set_branch_value('git-find-copies', int(options.find_copies)) |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 214 | |
| 215 | print('Using %d%% similarity for rename/copy detection. ' |
| 216 | 'Override with --similarity.' % options.similarity) |
| 217 | |
| 218 | return options, args |
| 219 | parser.parse_args = Parse |
| 220 | |
| 221 | |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 222 | def _get_properties_from_options(options): |
| 223 | properties = dict(x.split('=', 1) for x in options.properties) |
| 224 | for key, val in properties.iteritems(): |
| 225 | try: |
| 226 | properties[key] = json.loads(val) |
| 227 | except ValueError: |
| 228 | pass # If a value couldn't be evaluated, treat it as a string. |
| 229 | return properties |
| 230 | |
| 231 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 232 | def _prefix_master(master): |
| 233 | """Convert user-specified master name to full master name. |
| 234 | |
| 235 | Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket |
| 236 | name, while the developers always use shortened master name |
| 237 | (tryserver.chromium.linux) by stripping off the prefix 'master.'. This |
| 238 | function does the conversion for buildbucket migration. |
| 239 | """ |
| 240 | prefix = 'master.' |
| 241 | if master.startswith(prefix): |
| 242 | return master |
| 243 | return '%s%s' % (prefix, master) |
| 244 | |
| 245 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 246 | def _buildbucket_retry(operation_name, http, *args, **kwargs): |
| 247 | """Retries requests to buildbucket service and returns parsed json content.""" |
| 248 | try_count = 0 |
| 249 | while True: |
| 250 | response, content = http.request(*args, **kwargs) |
| 251 | try: |
| 252 | content_json = json.loads(content) |
| 253 | except ValueError: |
| 254 | content_json = None |
| 255 | |
| 256 | # Buildbucket could return an error even if status==200. |
| 257 | if content_json and content_json.get('error'): |
nodir@chromium.org | baff4e1 | 2016-03-08 00:33:57 +0000 | [diff] [blame] | 258 | error = content_json.get('error') |
| 259 | if error.get('code') == 403: |
| 260 | raise BuildbucketResponseException( |
| 261 | 'Access denied: %s' % error.get('message', '')) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 262 | msg = 'Error in response. Reason: %s. Message: %s.' % ( |
nodir@chromium.org | baff4e1 | 2016-03-08 00:33:57 +0000 | [diff] [blame] | 263 | error.get('reason', ''), error.get('message', '')) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 264 | raise BuildbucketResponseException(msg) |
| 265 | |
| 266 | if response.status == 200: |
| 267 | if not content_json: |
| 268 | raise BuildbucketResponseException( |
| 269 | 'Buildbucket returns invalid json content: %s.\n' |
| 270 | 'Please file bugs at http://crbug.com, label "Infra-BuildBucket".' % |
| 271 | content) |
| 272 | return content_json |
| 273 | if response.status < 500 or try_count >= 2: |
| 274 | raise httplib2.HttpLib2Error(content) |
| 275 | |
| 276 | # status >= 500 means transient failures. |
| 277 | logging.debug('Transient errors when %s. Will retry.', operation_name) |
| 278 | time.sleep(0.5 + 1.5*try_count) |
| 279 | try_count += 1 |
| 280 | assert False, 'unreachable' |
| 281 | |
| 282 | |
hinoka@chromium.org | feb9e2a | 2015-09-25 19:11:09 +0000 | [diff] [blame] | 283 | def trigger_luci_job(changelist, masters, options): |
| 284 | """Send a job to run on LUCI.""" |
| 285 | issue_props = changelist.GetIssueProperties() |
| 286 | issue = changelist.GetIssue() |
| 287 | patchset = changelist.GetMostRecentPatchset() |
| 288 | for builders_and_tests in sorted(masters.itervalues()): |
tandrii@chromium.org | 3764fa2 | 2015-10-21 16:40:40 +0000 | [diff] [blame] | 289 | # TODO(hinoka et al): add support for other properties. |
| 290 | # Currently, this completely ignores testfilter and other properties. |
| 291 | for builder in sorted(builders_and_tests): |
hinoka@chromium.org | feb9e2a | 2015-09-25 19:11:09 +0000 | [diff] [blame] | 292 | luci_trigger.trigger( |
| 293 | builder, 'HEAD', issue, patchset, issue_props['project']) |
| 294 | |
| 295 | |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 296 | def trigger_try_jobs(auth_config, changelist, options, masters, category): |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 297 | rietveld_url = settings.GetDefaultServerUrl() |
| 298 | rietveld_host = urlparse.urlparse(rietveld_url).hostname |
| 299 | authenticator = auth.get_authenticator_for_host(rietveld_host, auth_config) |
| 300 | http = authenticator.authorize(httplib2.Http()) |
| 301 | http.force_exception_to_status_code = True |
| 302 | issue_props = changelist.GetIssueProperties() |
| 303 | issue = changelist.GetIssue() |
| 304 | patchset = changelist.GetMostRecentPatchset() |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 305 | properties = _get_properties_from_options(options) |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 306 | |
| 307 | buildbucket_put_url = ( |
| 308 | 'https://{hostname}/_ah/api/buildbucket/v1/builds/batch'.format( |
sheyang@chromium.org | db37557 | 2015-08-17 19:22:23 +0000 | [diff] [blame] | 309 | hostname=options.buildbucket_host)) |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 310 | buildset = 'patch/rietveld/{hostname}/{issue}/{patch}'.format( |
| 311 | hostname=rietveld_host, |
| 312 | issue=issue, |
| 313 | patch=patchset) |
| 314 | |
| 315 | batch_req_body = {'builds': []} |
| 316 | print_text = [] |
| 317 | print_text.append('Tried jobs on:') |
| 318 | for master, builders_and_tests in sorted(masters.iteritems()): |
| 319 | print_text.append('Master: %s' % master) |
| 320 | bucket = _prefix_master(master) |
| 321 | for builder, tests in sorted(builders_and_tests.iteritems()): |
| 322 | print_text.append(' %s: %s' % (builder, tests)) |
| 323 | parameters = { |
| 324 | 'builder_name': builder, |
nodir@chromium.org | d221731 | 2015-09-21 15:51:21 +0000 | [diff] [blame] | 325 | 'changes': [{ |
| 326 | 'author': {'email': issue_props['owner_email']}, |
| 327 | 'revision': options.revision, |
| 328 | }], |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 329 | 'properties': { |
| 330 | 'category': category, |
| 331 | 'issue': issue, |
| 332 | 'master': master, |
| 333 | 'patch_project': issue_props['project'], |
| 334 | 'patch_storage': 'rietveld', |
| 335 | 'patchset': patchset, |
| 336 | 'reason': options.name, |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 337 | 'rietveld': rietveld_url, |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 338 | }, |
| 339 | } |
tandrii@chromium.org | 3764fa2 | 2015-10-21 16:40:40 +0000 | [diff] [blame] | 340 | if tests: |
| 341 | parameters['properties']['testfilter'] = tests |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 342 | if properties: |
| 343 | parameters['properties'].update(properties) |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 344 | if options.clobber: |
| 345 | parameters['properties']['clobber'] = True |
| 346 | batch_req_body['builds'].append( |
| 347 | { |
| 348 | 'bucket': bucket, |
| 349 | 'parameters_json': json.dumps(parameters), |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 350 | 'client_operation_id': str(uuid.uuid4()), |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 351 | 'tags': ['builder:%s' % builder, |
| 352 | 'buildset:%s' % buildset, |
| 353 | 'master:%s' % master, |
| 354 | 'user_agent:git_cl_try'] |
| 355 | } |
| 356 | ) |
| 357 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 358 | _buildbucket_retry( |
| 359 | 'triggering tryjobs', |
| 360 | http, |
| 361 | buildbucket_put_url, |
| 362 | 'PUT', |
| 363 | body=json.dumps(batch_req_body), |
| 364 | headers={'Content-Type': 'application/json'} |
| 365 | ) |
tandrii@chromium.org | 35c6145 | 2016-02-26 15:24:57 +0000 | [diff] [blame] | 366 | print_text.append('To see results here, run: git cl try-results') |
| 367 | print_text.append('To see results in browser, run: git cl web') |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 368 | print '\n'.join(print_text) |
kjellander@chromium.org | 4442454 | 2015-06-02 18:35:29 +0000 | [diff] [blame] | 369 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 370 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 371 | def fetch_try_jobs(auth_config, changelist, options): |
| 372 | """Fetches tryjobs from buildbucket. |
| 373 | |
| 374 | Returns a map from build id to build info as json dictionary. |
| 375 | """ |
| 376 | rietveld_url = settings.GetDefaultServerUrl() |
| 377 | rietveld_host = urlparse.urlparse(rietveld_url).hostname |
| 378 | authenticator = auth.get_authenticator_for_host(rietveld_host, auth_config) |
| 379 | if authenticator.has_cached_credentials(): |
| 380 | http = authenticator.authorize(httplib2.Http()) |
| 381 | else: |
| 382 | print ('Warning: Some results might be missing because %s' % |
| 383 | # Get the message on how to login. |
| 384 | auth.LoginRequiredError(rietveld_host).message) |
| 385 | http = httplib2.Http() |
| 386 | |
| 387 | http.force_exception_to_status_code = True |
| 388 | |
| 389 | buildset = 'patch/rietveld/{hostname}/{issue}/{patch}'.format( |
| 390 | hostname=rietveld_host, |
| 391 | issue=changelist.GetIssue(), |
| 392 | patch=options.patchset) |
| 393 | params = {'tag': 'buildset:%s' % buildset} |
| 394 | |
| 395 | builds = {} |
| 396 | while True: |
| 397 | url = 'https://{hostname}/_ah/api/buildbucket/v1/search?{params}'.format( |
| 398 | hostname=options.buildbucket_host, |
| 399 | params=urllib.urlencode(params)) |
| 400 | content = _buildbucket_retry('fetching tryjobs', http, url, 'GET') |
| 401 | for build in content.get('builds', []): |
| 402 | builds[build['id']] = build |
| 403 | if 'next_cursor' in content: |
| 404 | params['start_cursor'] = content['next_cursor'] |
| 405 | else: |
| 406 | break |
| 407 | return builds |
| 408 | |
| 409 | |
| 410 | def print_tryjobs(options, builds): |
| 411 | """Prints nicely result of fetch_try_jobs.""" |
| 412 | if not builds: |
| 413 | print 'No tryjobs scheduled' |
| 414 | return |
| 415 | |
| 416 | # Make a copy, because we'll be modifying builds dictionary. |
| 417 | builds = builds.copy() |
| 418 | builder_names_cache = {} |
| 419 | |
| 420 | def get_builder(b): |
| 421 | try: |
| 422 | return builder_names_cache[b['id']] |
| 423 | except KeyError: |
| 424 | try: |
| 425 | parameters = json.loads(b['parameters_json']) |
| 426 | name = parameters['builder_name'] |
| 427 | except (ValueError, KeyError) as error: |
| 428 | print 'WARNING: failed to get builder name for build %s: %s' % ( |
| 429 | b['id'], error) |
| 430 | name = None |
| 431 | builder_names_cache[b['id']] = name |
| 432 | return name |
| 433 | |
| 434 | def get_bucket(b): |
| 435 | bucket = b['bucket'] |
| 436 | if bucket.startswith('master.'): |
| 437 | return bucket[len('master.'):] |
| 438 | return bucket |
| 439 | |
| 440 | if options.print_master: |
| 441 | name_fmt = '%%-%ds %%-%ds' % ( |
| 442 | max(len(str(get_bucket(b))) for b in builds.itervalues()), |
| 443 | max(len(str(get_builder(b))) for b in builds.itervalues())) |
| 444 | def get_name(b): |
| 445 | return name_fmt % (get_bucket(b), get_builder(b)) |
| 446 | else: |
| 447 | name_fmt = '%%-%ds' % ( |
| 448 | max(len(str(get_builder(b))) for b in builds.itervalues())) |
| 449 | def get_name(b): |
| 450 | return name_fmt % get_builder(b) |
| 451 | |
| 452 | def sort_key(b): |
| 453 | return b['status'], b.get('result'), get_name(b), b.get('url') |
| 454 | |
| 455 | def pop(title, f, color=None, **kwargs): |
| 456 | """Pop matching builds from `builds` dict and print them.""" |
| 457 | |
tandrii@chromium.org | 6cf98c8 | 2016-03-15 11:56:00 +0000 | [diff] [blame] | 458 | if not options.color or color is None: |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 459 | colorize = str |
| 460 | else: |
| 461 | colorize = lambda x: '%s%s%s' % (color, x, Fore.RESET) |
| 462 | |
| 463 | result = [] |
| 464 | for b in builds.values(): |
| 465 | if all(b.get(k) == v for k, v in kwargs.iteritems()): |
| 466 | builds.pop(b['id']) |
| 467 | result.append(b) |
| 468 | if result: |
| 469 | print colorize(title) |
| 470 | for b in sorted(result, key=sort_key): |
| 471 | print ' ', colorize('\t'.join(map(str, f(b)))) |
| 472 | |
| 473 | total = len(builds) |
| 474 | pop(status='COMPLETED', result='SUCCESS', |
| 475 | title='Successes:', color=Fore.GREEN, |
| 476 | f=lambda b: (get_name(b), b.get('url'))) |
| 477 | pop(status='COMPLETED', result='FAILURE', failure_reason='INFRA_FAILURE', |
| 478 | title='Infra Failures:', color=Fore.MAGENTA, |
| 479 | f=lambda b: (get_name(b), b.get('url'))) |
| 480 | pop(status='COMPLETED', result='FAILURE', failure_reason='BUILD_FAILURE', |
| 481 | title='Failures:', color=Fore.RED, |
| 482 | f=lambda b: (get_name(b), b.get('url'))) |
| 483 | pop(status='COMPLETED', result='CANCELED', |
| 484 | title='Canceled:', color=Fore.MAGENTA, |
| 485 | f=lambda b: (get_name(b),)) |
| 486 | pop(status='COMPLETED', result='FAILURE', |
| 487 | failure_reason='INVALID_BUILD_DEFINITION', |
| 488 | title='Wrong master/builder name:', color=Fore.MAGENTA, |
| 489 | f=lambda b: (get_name(b),)) |
| 490 | pop(status='COMPLETED', result='FAILURE', |
| 491 | title='Other failures:', |
| 492 | f=lambda b: (get_name(b), b.get('failure_reason'), b.get('url'))) |
| 493 | pop(status='COMPLETED', |
| 494 | title='Other finished:', |
| 495 | f=lambda b: (get_name(b), b.get('result'), b.get('url'))) |
| 496 | pop(status='STARTED', |
| 497 | title='Started:', color=Fore.YELLOW, |
| 498 | f=lambda b: (get_name(b), b.get('url'))) |
| 499 | pop(status='SCHEDULED', |
| 500 | title='Scheduled:', |
| 501 | f=lambda b: (get_name(b), 'id=%s' % b['id'])) |
| 502 | # The last section is just in case buildbucket API changes OR there is a bug. |
| 503 | pop(title='Other:', |
| 504 | f=lambda b: (get_name(b), 'id=%s' % b['id'])) |
| 505 | assert len(builds) == 0 |
| 506 | print 'Total: %d tryjobs' % total |
| 507 | |
| 508 | |
bauerb@chromium.org | 866276c | 2011-03-18 20:09:31 +0000 | [diff] [blame] | 509 | def MatchSvnGlob(url, base_url, glob_spec, allow_wildcards): |
| 510 | """Return the corresponding git ref if |base_url| together with |glob_spec| |
| 511 | matches the full |url|. |
| 512 | |
| 513 | If |allow_wildcards| is true, |glob_spec| can contain wildcards (see below). |
| 514 | """ |
| 515 | fetch_suburl, as_ref = glob_spec.split(':') |
| 516 | if allow_wildcards: |
| 517 | glob_match = re.match('(.+/)?(\*|{[^/]*})(/.+)?', fetch_suburl) |
| 518 | if glob_match: |
| 519 | # Parse specs like "branches/*/src:refs/remotes/svn/*" or |
| 520 | # "branches/{472,597,648}/src:refs/remotes/svn/*". |
| 521 | branch_re = re.escape(base_url) |
| 522 | if glob_match.group(1): |
| 523 | branch_re += '/' + re.escape(glob_match.group(1)) |
| 524 | wildcard = glob_match.group(2) |
| 525 | if wildcard == '*': |
| 526 | branch_re += '([^/]*)' |
| 527 | else: |
| 528 | # Escape and replace surrounding braces with parentheses and commas |
| 529 | # with pipe symbols. |
| 530 | wildcard = re.escape(wildcard) |
| 531 | wildcard = re.sub('^\\\\{', '(', wildcard) |
| 532 | wildcard = re.sub('\\\\,', '|', wildcard) |
| 533 | wildcard = re.sub('\\\\}$', ')', wildcard) |
| 534 | branch_re += wildcard |
| 535 | if glob_match.group(3): |
| 536 | branch_re += re.escape(glob_match.group(3)) |
| 537 | match = re.match(branch_re, url) |
| 538 | if match: |
| 539 | return re.sub('\*$', match.group(1), as_ref) |
| 540 | |
| 541 | # Parse specs like "trunk/src:refs/remotes/origin/trunk". |
| 542 | if fetch_suburl: |
| 543 | full_url = base_url + '/' + fetch_suburl |
| 544 | else: |
| 545 | full_url = base_url |
| 546 | if full_url == url: |
| 547 | return as_ref |
| 548 | return None |
| 549 | |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 550 | |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 551 | def print_stats(similarity, find_copies, args): |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 552 | """Prints statistics about the change to the user.""" |
| 553 | # --no-ext-diff is broken in some versions of Git, so try to work around |
| 554 | # this by overriding the environment (but there is still a problem if the |
| 555 | # git config key "diff.external" is used). |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 556 | env = GetNoGitPagerEnv() |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 557 | if 'GIT_EXTERNAL_DIFF' in env: |
| 558 | del env['GIT_EXTERNAL_DIFF'] |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 559 | |
| 560 | if find_copies: |
| 561 | similarity_options = ['--find-copies-harder', '-l100000', |
| 562 | '-C%s' % similarity] |
| 563 | else: |
| 564 | similarity_options = ['-M%s' % similarity] |
| 565 | |
szager@chromium.org | d057f9a | 2014-05-29 21:09:36 +0000 | [diff] [blame] | 566 | try: |
| 567 | stdout = sys.stdout.fileno() |
| 568 | except AttributeError: |
| 569 | stdout = None |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 570 | return subprocess2.call( |
bratell@opera.com | 82b91cd | 2013-07-09 06:33:41 +0000 | [diff] [blame] | 571 | ['git', |
bratell@opera.com | f267b0e | 2013-05-02 09:11:43 +0000 | [diff] [blame] | 572 | 'diff', '--no-ext-diff', '--stat'] + similarity_options + args, |
szager@chromium.org | d057f9a | 2014-05-29 21:09:36 +0000 | [diff] [blame] | 573 | stdout=stdout, env=env) |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 574 | |
| 575 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 576 | class BuildbucketResponseException(Exception): |
| 577 | pass |
| 578 | |
| 579 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 580 | class Settings(object): |
| 581 | def __init__(self): |
| 582 | self.default_server = None |
| 583 | self.cc = None |
thestig@chromium.org | 7a54e81 | 2014-02-11 19:57:22 +0000 | [diff] [blame] | 584 | self.root = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 585 | self.is_git_svn = None |
| 586 | self.svn_branch = None |
| 587 | self.tree_status_url = None |
| 588 | self.viewvc_url = None |
| 589 | self.updated = False |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 590 | self.is_gerrit = None |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 591 | self.squash_gerrit_uploads = None |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 592 | self.gerrit_skip_ensure_authenticated = None |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 593 | self.git_editor = None |
sheyang@chromium.org | 152cf83 | 2014-06-11 21:37:49 +0000 | [diff] [blame] | 594 | self.project = None |
kjellander@chromium.org | 6abc652 | 2014-12-02 07:34:49 +0000 | [diff] [blame] | 595 | self.force_https_commit_url = None |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 596 | self.pending_ref_prefix = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 597 | |
| 598 | def LazyUpdateIfNeeded(self): |
| 599 | """Updates the settings from a codereview.settings file, if available.""" |
| 600 | if not self.updated: |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 601 | # The only value that actually changes the behavior is |
| 602 | # autoupdate = "false". Everything else means "true". |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 603 | autoupdate = RunGit(['config', 'rietveld.autoupdate'], |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 604 | error_ok=True |
| 605 | ).strip().lower() |
| 606 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 607 | cr_settings_file = FindCodereviewSettingsFile() |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 608 | if autoupdate != 'false' and cr_settings_file: |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 609 | LoadCodereviewSettingsFromFile(cr_settings_file) |
| 610 | self.updated = True |
| 611 | |
| 612 | def GetDefaultServerUrl(self, error_ok=False): |
| 613 | if not self.default_server: |
| 614 | self.LazyUpdateIfNeeded() |
maruel@chromium.org | eb5edbc | 2012-01-16 17:03:28 +0000 | [diff] [blame] | 615 | self.default_server = gclient_utils.UpgradeToHttps( |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 616 | self._GetRietveldConfig('server', error_ok=True)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 617 | if error_ok: |
| 618 | return self.default_server |
| 619 | if not self.default_server: |
| 620 | error_message = ('Could not find settings file. You must configure ' |
| 621 | 'your review setup by running "git cl config".') |
maruel@chromium.org | eb5edbc | 2012-01-16 17:03:28 +0000 | [diff] [blame] | 622 | self.default_server = gclient_utils.UpgradeToHttps( |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 623 | self._GetRietveldConfig('server', error_message=error_message)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 624 | return self.default_server |
| 625 | |
thestig@chromium.org | 7a54e81 | 2014-02-11 19:57:22 +0000 | [diff] [blame] | 626 | @staticmethod |
| 627 | def GetRelativeRoot(): |
| 628 | return RunGit(['rev-parse', '--show-cdup']).strip() |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 629 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 630 | def GetRoot(self): |
thestig@chromium.org | 7a54e81 | 2014-02-11 19:57:22 +0000 | [diff] [blame] | 631 | if self.root is None: |
| 632 | self.root = os.path.abspath(self.GetRelativeRoot()) |
| 633 | return self.root |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 634 | |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 635 | def GetGitMirror(self, remote='origin'): |
| 636 | """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] | 637 | local_url = RunGit(['config', '--get', 'remote.%s.url' % remote]).strip() |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 638 | if not os.path.isdir(local_url): |
| 639 | return None |
| 640 | git_cache.Mirror.SetCachePath(os.path.dirname(local_url)) |
| 641 | remote_url = git_cache.Mirror.CacheDirToUrl(local_url) |
| 642 | # Use the /dev/null print_func to avoid terminal spew in WaitForRealCommit. |
| 643 | mirror = git_cache.Mirror(remote_url, print_func = lambda *args: None) |
| 644 | if mirror.exists(): |
| 645 | return mirror |
| 646 | return None |
| 647 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 648 | def GetIsGitSvn(self): |
| 649 | """Return true if this repo looks like it's using git-svn.""" |
| 650 | if self.is_git_svn is None: |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 651 | if self.GetPendingRefPrefix(): |
| 652 | # If PENDING_REF_PREFIX is set then it's a pure git repo no matter what. |
| 653 | self.is_git_svn = False |
| 654 | else: |
| 655 | # If you have any "svn-remote.*" config keys, we think you're using svn. |
| 656 | self.is_git_svn = RunGitWithCode( |
| 657 | ['config', '--local', '--get-regexp', r'^svn-remote\.'])[0] == 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 658 | return self.is_git_svn |
| 659 | |
| 660 | def GetSVNBranch(self): |
| 661 | if self.svn_branch is None: |
| 662 | if not self.GetIsGitSvn(): |
| 663 | DieWithError('Repo doesn\'t appear to be a git-svn repo.') |
| 664 | |
| 665 | # Try to figure out which remote branch we're based on. |
| 666 | # Strategy: |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 667 | # 1) iterate through our branch history and find the svn URL. |
| 668 | # 2) find the svn-remote that fetches from the URL. |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 669 | |
| 670 | # regexp matching the git-svn line that contains the URL. |
| 671 | git_svn_re = re.compile(r'^\s*git-svn-id: (\S+)@', re.MULTILINE) |
| 672 | |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 673 | # We don't want to go through all of history, so read a line from the |
| 674 | # pipe at a time. |
| 675 | # The -100 is an arbitrary limit so we don't search forever. |
bratell@opera.com | 82b91cd | 2013-07-09 06:33:41 +0000 | [diff] [blame] | 676 | cmd = ['git', 'log', '-100', '--pretty=medium'] |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 677 | proc = subprocess2.Popen(cmd, stdout=subprocess2.PIPE, |
| 678 | env=GetNoGitPagerEnv()) |
maruel@chromium.org | 740f9d7 | 2011-06-10 18:33:10 +0000 | [diff] [blame] | 679 | url = None |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 680 | for line in proc.stdout: |
| 681 | match = git_svn_re.match(line) |
| 682 | if match: |
| 683 | url = match.group(1) |
| 684 | proc.stdout.close() # Cut pipe. |
| 685 | break |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 686 | |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 687 | if url: |
| 688 | svn_remote_re = re.compile(r'^svn-remote\.([^.]+)\.url (.*)$') |
| 689 | remotes = RunGit(['config', '--get-regexp', |
| 690 | r'^svn-remote\..*\.url']).splitlines() |
| 691 | for remote in remotes: |
| 692 | match = svn_remote_re.match(remote) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 693 | if match: |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 694 | remote = match.group(1) |
| 695 | base_url = match.group(2) |
szager@chromium.org | 4ac2553 | 2013-12-16 22:07:02 +0000 | [diff] [blame] | 696 | rewrite_root = RunGit( |
| 697 | ['config', 'svn-remote.%s.rewriteRoot' % remote], |
| 698 | error_ok=True).strip() |
| 699 | if rewrite_root: |
| 700 | base_url = rewrite_root |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 701 | fetch_spec = RunGit( |
bauerb@chromium.org | 866276c | 2011-03-18 20:09:31 +0000 | [diff] [blame] | 702 | ['config', 'svn-remote.%s.fetch' % remote], |
| 703 | error_ok=True).strip() |
| 704 | if fetch_spec: |
| 705 | self.svn_branch = MatchSvnGlob(url, base_url, fetch_spec, False) |
| 706 | if self.svn_branch: |
| 707 | break |
| 708 | branch_spec = RunGit( |
| 709 | ['config', 'svn-remote.%s.branches' % remote], |
| 710 | error_ok=True).strip() |
| 711 | if branch_spec: |
| 712 | self.svn_branch = MatchSvnGlob(url, base_url, branch_spec, True) |
| 713 | if self.svn_branch: |
| 714 | break |
| 715 | tag_spec = RunGit( |
| 716 | ['config', 'svn-remote.%s.tags' % remote], |
| 717 | error_ok=True).strip() |
| 718 | if tag_spec: |
| 719 | self.svn_branch = MatchSvnGlob(url, base_url, tag_spec, True) |
| 720 | if self.svn_branch: |
| 721 | break |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 722 | |
| 723 | if not self.svn_branch: |
| 724 | DieWithError('Can\'t guess svn branch -- try specifying it on the ' |
| 725 | 'command line') |
| 726 | |
| 727 | return self.svn_branch |
| 728 | |
| 729 | def GetTreeStatusUrl(self, error_ok=False): |
| 730 | if not self.tree_status_url: |
| 731 | error_message = ('You must configure your tree status URL by running ' |
| 732 | '"git cl config".') |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 733 | self.tree_status_url = self._GetRietveldConfig( |
| 734 | 'tree-status-url', error_ok=error_ok, error_message=error_message) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 735 | return self.tree_status_url |
| 736 | |
| 737 | def GetViewVCUrl(self): |
| 738 | if not self.viewvc_url: |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 739 | self.viewvc_url = self._GetRietveldConfig('viewvc-url', error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 740 | return self.viewvc_url |
| 741 | |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 742 | def GetBugPrefix(self): |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 743 | return self._GetRietveldConfig('bug-prefix', error_ok=True) |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 744 | |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 745 | def GetIsSkipDependencyUpload(self, branch_name): |
| 746 | """Returns true if specified branch should skip dep uploads.""" |
| 747 | return self._GetBranchConfig(branch_name, 'skip-deps-uploads', |
| 748 | error_ok=True) |
| 749 | |
rmistry@google.com | 5626a92 | 2015-02-26 14:03:30 +0000 | [diff] [blame] | 750 | def GetRunPostUploadHook(self): |
| 751 | run_post_upload_hook = self._GetRietveldConfig( |
| 752 | 'run-post-upload-hook', error_ok=True) |
| 753 | return run_post_upload_hook == "True" |
| 754 | |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 755 | def GetDefaultCCList(self): |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 756 | return self._GetRietveldConfig('cc', error_ok=True) |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 757 | |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 758 | def GetDefaultPrivateFlag(self): |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 759 | return self._GetRietveldConfig('private', error_ok=True) |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 760 | |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 761 | def GetIsGerrit(self): |
| 762 | """Return true if this repo is assosiated with gerrit code review system.""" |
| 763 | if self.is_gerrit is None: |
| 764 | self.is_gerrit = self._GetConfig('gerrit.host', error_ok=True) |
| 765 | return self.is_gerrit |
| 766 | |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 767 | def GetSquashGerritUploads(self): |
| 768 | """Return true if uploads to Gerrit should be squashed by default.""" |
| 769 | if self.squash_gerrit_uploads is None: |
| 770 | self.squash_gerrit_uploads = ( |
| 771 | RunGit(['config', '--bool', 'gerrit.squash-uploads'], |
| 772 | error_ok=True).strip() == 'true') |
| 773 | return self.squash_gerrit_uploads |
| 774 | |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 775 | def GetGerritSkipEnsureAuthenticated(self): |
| 776 | """Return True if EnsureAuthenticated should not be done for Gerrit |
| 777 | uploads.""" |
| 778 | if self.gerrit_skip_ensure_authenticated is None: |
| 779 | self.gerrit_skip_ensure_authenticated = ( |
shinyak@chromium.org | 00dbccd | 2016-04-15 07:24:43 +0000 | [diff] [blame] | 780 | RunGit(['config', '--bool', 'gerrit.skip-ensure-authenticated'], |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 781 | error_ok=True).strip() == 'true') |
| 782 | return self.gerrit_skip_ensure_authenticated |
| 783 | |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 784 | def GetGitEditor(self): |
| 785 | """Return the editor specified in the git config, or None if none is.""" |
| 786 | if self.git_editor is None: |
| 787 | self.git_editor = self._GetConfig('core.editor', error_ok=True) |
| 788 | return self.git_editor or None |
| 789 | |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 790 | def GetLintRegex(self): |
| 791 | return (self._GetRietveldConfig('cpplint-regex', error_ok=True) or |
| 792 | DEFAULT_LINT_REGEX) |
| 793 | |
| 794 | def GetLintIgnoreRegex(self): |
| 795 | return (self._GetRietveldConfig('cpplint-ignore-regex', error_ok=True) or |
| 796 | DEFAULT_LINT_IGNORE_REGEX) |
| 797 | |
sheyang@chromium.org | 152cf83 | 2014-06-11 21:37:49 +0000 | [diff] [blame] | 798 | def GetProject(self): |
| 799 | if not self.project: |
| 800 | self.project = self._GetRietveldConfig('project', error_ok=True) |
| 801 | return self.project |
| 802 | |
kjellander@chromium.org | 6abc652 | 2014-12-02 07:34:49 +0000 | [diff] [blame] | 803 | def GetForceHttpsCommitUrl(self): |
| 804 | if not self.force_https_commit_url: |
| 805 | self.force_https_commit_url = self._GetRietveldConfig( |
| 806 | 'force-https-commit-url', error_ok=True) |
| 807 | return self.force_https_commit_url |
| 808 | |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 809 | def GetPendingRefPrefix(self): |
| 810 | if not self.pending_ref_prefix: |
| 811 | self.pending_ref_prefix = self._GetRietveldConfig( |
| 812 | 'pending-ref-prefix', error_ok=True) |
| 813 | return self.pending_ref_prefix |
| 814 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 815 | def _GetRietveldConfig(self, param, **kwargs): |
| 816 | return self._GetConfig('rietveld.' + param, **kwargs) |
| 817 | |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 818 | def _GetBranchConfig(self, branch_name, param, **kwargs): |
| 819 | return self._GetConfig('branch.' + branch_name + '.' + param, **kwargs) |
| 820 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 821 | def _GetConfig(self, param, **kwargs): |
| 822 | self.LazyUpdateIfNeeded() |
| 823 | return RunGit(['config', param], **kwargs).strip() |
| 824 | |
| 825 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 826 | def ShortBranchName(branch): |
| 827 | """Convert a name like 'refs/heads/foo' to just 'foo'.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 828 | return branch.replace('refs/heads/', '', 1) |
| 829 | |
| 830 | |
| 831 | def GetCurrentBranchRef(): |
| 832 | """Returns branch ref (e.g., refs/heads/master) or None.""" |
| 833 | return RunGit(['symbolic-ref', 'HEAD'], |
| 834 | stderr=subprocess2.VOID, error_ok=True).strip() or None |
| 835 | |
| 836 | |
| 837 | def GetCurrentBranch(): |
| 838 | """Returns current branch or None. |
| 839 | |
| 840 | For refs/heads/* branches, returns just last part. For others, full ref. |
| 841 | """ |
| 842 | branchref = GetCurrentBranchRef() |
| 843 | if branchref: |
| 844 | return ShortBranchName(branchref) |
| 845 | return None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 846 | |
| 847 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 848 | class _CQState(object): |
| 849 | """Enum for states of CL with respect to Commit Queue.""" |
| 850 | NONE = 'none' |
| 851 | DRY_RUN = 'dry_run' |
| 852 | COMMIT = 'commit' |
| 853 | |
| 854 | ALL_STATES = [NONE, DRY_RUN, COMMIT] |
| 855 | |
| 856 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 857 | class _ParsedIssueNumberArgument(object): |
| 858 | def __init__(self, issue=None, patchset=None, hostname=None): |
| 859 | self.issue = issue |
| 860 | self.patchset = patchset |
| 861 | self.hostname = hostname |
| 862 | |
| 863 | @property |
| 864 | def valid(self): |
| 865 | return self.issue is not None |
| 866 | |
| 867 | |
| 868 | class _RietveldParsedIssueNumberArgument(_ParsedIssueNumberArgument): |
| 869 | def __init__(self, *args, **kwargs): |
| 870 | self.patch_url = kwargs.pop('patch_url', None) |
| 871 | super(_RietveldParsedIssueNumberArgument, self).__init__(*args, **kwargs) |
| 872 | |
| 873 | |
| 874 | def ParseIssueNumberArgument(arg): |
| 875 | """Parses the issue argument and returns _ParsedIssueNumberArgument.""" |
| 876 | fail_result = _ParsedIssueNumberArgument() |
| 877 | |
| 878 | if arg.isdigit(): |
| 879 | return _ParsedIssueNumberArgument(issue=int(arg)) |
| 880 | if not arg.startswith('http'): |
| 881 | return fail_result |
| 882 | url = gclient_utils.UpgradeToHttps(arg) |
| 883 | try: |
| 884 | parsed_url = urlparse.urlparse(url) |
| 885 | except ValueError: |
| 886 | return fail_result |
| 887 | for cls in _CODEREVIEW_IMPLEMENTATIONS.itervalues(): |
| 888 | tmp = cls.ParseIssueURL(parsed_url) |
| 889 | if tmp is not None: |
| 890 | return tmp |
| 891 | return fail_result |
| 892 | |
| 893 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 894 | class Changelist(object): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 895 | """Changelist works with one changelist in local branch. |
| 896 | |
| 897 | Supports two codereview backends: Rietveld or Gerrit, selected at object |
| 898 | creation. |
| 899 | |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 900 | Notes: |
| 901 | * Not safe for concurrent multi-{thread,process} use. |
| 902 | * Caches values from current branch. Therefore, re-use after branch change |
| 903 | with care. |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 904 | """ |
| 905 | |
| 906 | def __init__(self, branchref=None, issue=None, codereview=None, **kwargs): |
| 907 | """Create a new ChangeList instance. |
| 908 | |
| 909 | If issue is given, the codereview must be given too. |
| 910 | |
| 911 | If `codereview` is given, it must be 'rietveld' or 'gerrit'. |
| 912 | Otherwise, it's decided based on current configuration of the local branch, |
| 913 | with default being 'rietveld' for backwards compatibility. |
| 914 | See _load_codereview_impl for more details. |
| 915 | |
| 916 | **kwargs will be passed directly to codereview implementation. |
| 917 | """ |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 918 | # 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] | 919 | global settings |
| 920 | if not settings: |
| 921 | # Happens when git_cl.py is used as a utility library. |
| 922 | settings = Settings() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 923 | |
| 924 | if issue: |
| 925 | assert codereview, 'codereview must be known, if issue is known' |
| 926 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 927 | self.branchref = branchref |
| 928 | if self.branchref: |
| 929 | self.branch = ShortBranchName(self.branchref) |
| 930 | else: |
| 931 | self.branch = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 932 | self.upstream_branch = None |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 933 | self.lookedup_issue = False |
| 934 | self.issue = issue or None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 935 | self.has_description = False |
| 936 | self.description = None |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 937 | self.lookedup_patchset = False |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 938 | self.patchset = None |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 939 | self.cc = None |
| 940 | self.watchers = () |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 941 | self._remote = None |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 942 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 943 | self._codereview_impl = None |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 944 | self._codereview = None |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 945 | self._load_codereview_impl(codereview, **kwargs) |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 946 | assert self._codereview_impl |
| 947 | assert self._codereview in _CODEREVIEW_IMPLEMENTATIONS |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 948 | |
| 949 | def _load_codereview_impl(self, codereview=None, **kwargs): |
| 950 | if codereview: |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 951 | assert codereview in _CODEREVIEW_IMPLEMENTATIONS |
| 952 | cls = _CODEREVIEW_IMPLEMENTATIONS[codereview] |
| 953 | self._codereview = codereview |
| 954 | self._codereview_impl = cls(self, **kwargs) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 955 | return |
| 956 | |
| 957 | # Automatic selection based on issue number set for a current branch. |
| 958 | # Rietveld takes precedence over Gerrit. |
| 959 | assert not self.issue |
| 960 | # Whether we find issue or not, we are doing the lookup. |
| 961 | self.lookedup_issue = True |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 962 | for codereview, cls in _CODEREVIEW_IMPLEMENTATIONS.iteritems(): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 963 | setting = cls.IssueSetting(self.GetBranch()) |
| 964 | issue = RunGit(['config', setting], error_ok=True).strip() |
| 965 | if issue: |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 966 | self._codereview = codereview |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 967 | self._codereview_impl = cls(self, **kwargs) |
| 968 | self.issue = int(issue) |
| 969 | return |
| 970 | |
| 971 | # No issue is set for this branch, so decide based on repo-wide settings. |
| 972 | return self._load_codereview_impl( |
| 973 | codereview='gerrit' if settings.GetIsGerrit() else 'rietveld', |
| 974 | **kwargs) |
| 975 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 976 | def IsGerrit(self): |
| 977 | return self._codereview == 'gerrit' |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 978 | |
| 979 | def GetCCList(self): |
| 980 | """Return the users cc'd on this CL. |
| 981 | |
| 982 | Return is a string suitable for passing to gcl with the --cc flag. |
| 983 | """ |
| 984 | if self.cc is None: |
tyoshino@chromium.org | 99918ab | 2013-09-30 06:17:28 +0000 | [diff] [blame] | 985 | base_cc = settings.GetDefaultCCList() |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 986 | more_cc = ','.join(self.watchers) |
| 987 | self.cc = ','.join(filter(None, (base_cc, more_cc))) or '' |
| 988 | return self.cc |
| 989 | |
tyoshino@chromium.org | 99918ab | 2013-09-30 06:17:28 +0000 | [diff] [blame] | 990 | def GetCCListWithoutDefault(self): |
| 991 | """Return the users cc'd on this CL excluding default ones.""" |
| 992 | if self.cc is None: |
| 993 | self.cc = ','.join(self.watchers) |
| 994 | return self.cc |
| 995 | |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 996 | def SetWatchers(self, watchers): |
| 997 | """Set the list of email addresses that should be cc'd based on the changed |
| 998 | files in this CL. |
| 999 | """ |
| 1000 | self.watchers = watchers |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1001 | |
| 1002 | def GetBranch(self): |
| 1003 | """Returns the short branch name, e.g. 'master'.""" |
| 1004 | if not self.branch: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1005 | branchref = GetCurrentBranchRef() |
szager@chromium.org | d62c61f | 2014-10-20 22:33:21 +0000 | [diff] [blame] | 1006 | if not branchref: |
| 1007 | return None |
| 1008 | self.branchref = branchref |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1009 | self.branch = ShortBranchName(self.branchref) |
| 1010 | return self.branch |
| 1011 | |
| 1012 | def GetBranchRef(self): |
| 1013 | """Returns the full branch name, e.g. 'refs/heads/master'.""" |
| 1014 | self.GetBranch() # Poke the lazy loader. |
| 1015 | return self.branchref |
| 1016 | |
tandrii@chromium.org | 534f67a | 2016-04-07 18:47:05 +0000 | [diff] [blame] | 1017 | def ClearBranch(self): |
| 1018 | """Clears cached branch data of this object.""" |
| 1019 | self.branch = self.branchref = None |
| 1020 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1021 | @staticmethod |
| 1022 | def FetchUpstreamTuple(branch): |
pgervais@chromium.org | d6617f3 | 2013-11-19 00:34:54 +0000 | [diff] [blame] | 1023 | """Returns a tuple containing remote and remote ref, |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1024 | e.g. 'origin', 'refs/heads/master' |
| 1025 | """ |
| 1026 | remote = '.' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1027 | upstream_branch = RunGit(['config', 'branch.%s.merge' % branch], |
| 1028 | error_ok=True).strip() |
| 1029 | if upstream_branch: |
| 1030 | remote = RunGit(['config', 'branch.%s.remote' % branch]).strip() |
| 1031 | else: |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 1032 | upstream_branch = RunGit(['config', 'rietveld.upstream-branch'], |
| 1033 | error_ok=True).strip() |
| 1034 | if upstream_branch: |
| 1035 | remote = RunGit(['config', 'rietveld.upstream-remote']).strip() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1036 | else: |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 1037 | # Fall back on trying a git-svn upstream branch. |
| 1038 | if settings.GetIsGitSvn(): |
| 1039 | upstream_branch = settings.GetSVNBranch() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1040 | else: |
bauerb@chromium.org | ade368c | 2011-03-01 08:57:50 +0000 | [diff] [blame] | 1041 | # Else, try to guess the origin remote. |
| 1042 | remote_branches = RunGit(['branch', '-r']).split() |
| 1043 | if 'origin/master' in remote_branches: |
| 1044 | # Fall back on origin/master if it exits. |
| 1045 | remote = 'origin' |
| 1046 | upstream_branch = 'refs/heads/master' |
| 1047 | elif 'origin/trunk' in remote_branches: |
| 1048 | # Fall back on origin/trunk if it exists. Generally a shared |
| 1049 | # git-svn clone |
| 1050 | remote = 'origin' |
| 1051 | upstream_branch = 'refs/heads/trunk' |
| 1052 | else: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1053 | DieWithError( |
| 1054 | 'Unable to determine default branch to diff against.\n' |
| 1055 | 'Either pass complete "git diff"-style arguments, like\n' |
| 1056 | ' git cl upload origin/master\n' |
| 1057 | 'or verify this branch is set up to track another \n' |
| 1058 | '(via the --track argument to "git checkout -b ...").') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1059 | |
| 1060 | return remote, upstream_branch |
| 1061 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1062 | def GetCommonAncestorWithUpstream(self): |
pgervais@chromium.org | 8ba38ff | 2015-06-11 21:41:25 +0000 | [diff] [blame] | 1063 | upstream_branch = self.GetUpstreamBranch() |
| 1064 | if not BranchExists(upstream_branch): |
| 1065 | DieWithError('The upstream for the current branch (%s) does not exist ' |
| 1066 | 'anymore.\nPlease fix it and try again.' % self.GetBranch()) |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 1067 | return git_common.get_or_create_merge_base(self.GetBranch(), |
pgervais@chromium.org | 8ba38ff | 2015-06-11 21:41:25 +0000 | [diff] [blame] | 1068 | upstream_branch) |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1069 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1070 | def GetUpstreamBranch(self): |
| 1071 | if self.upstream_branch is None: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1072 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1073 | if remote is not '.': |
mmoss@chromium.org | e758545 | 2014-08-24 01:41:11 +0000 | [diff] [blame] | 1074 | upstream_branch = upstream_branch.replace('refs/heads/', |
| 1075 | 'refs/remotes/%s/' % remote) |
| 1076 | upstream_branch = upstream_branch.replace('refs/branch-heads/', |
| 1077 | 'refs/remotes/branch-heads/') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1078 | self.upstream_branch = upstream_branch |
| 1079 | return self.upstream_branch |
| 1080 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1081 | def GetRemoteBranch(self): |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1082 | if not self._remote: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1083 | remote, branch = None, self.GetBranch() |
| 1084 | seen_branches = set() |
| 1085 | while branch not in seen_branches: |
| 1086 | seen_branches.add(branch) |
| 1087 | remote, branch = self.FetchUpstreamTuple(branch) |
| 1088 | branch = ShortBranchName(branch) |
| 1089 | if remote != '.' or branch.startswith('refs/remotes'): |
| 1090 | break |
| 1091 | else: |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1092 | remotes = RunGit(['remote'], error_ok=True).split() |
| 1093 | if len(remotes) == 1: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1094 | remote, = remotes |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1095 | elif 'origin' in remotes: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1096 | remote = 'origin' |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1097 | logging.warning('Could not determine which remote this change is ' |
| 1098 | 'associated with, so defaulting to "%s". This may ' |
| 1099 | 'not be what you want. You may prevent this message ' |
| 1100 | 'by running "git svn info" as documented here: %s', |
| 1101 | self._remote, |
| 1102 | GIT_INSTRUCTIONS_URL) |
| 1103 | else: |
| 1104 | logging.warn('Could not determine which remote this change is ' |
| 1105 | 'associated with. You may prevent this message by ' |
| 1106 | 'running "git svn info" as documented here: %s', |
| 1107 | GIT_INSTRUCTIONS_URL) |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1108 | branch = 'HEAD' |
| 1109 | if branch.startswith('refs/remotes'): |
| 1110 | self._remote = (remote, branch) |
mmoss@chromium.org | e758545 | 2014-08-24 01:41:11 +0000 | [diff] [blame] | 1111 | elif branch.startswith('refs/branch-heads/'): |
| 1112 | self._remote = (remote, branch.replace('refs/', 'refs/remotes/')) |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1113 | else: |
| 1114 | self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch)) |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1115 | return self._remote |
| 1116 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1117 | def GitSanityChecks(self, upstream_git_obj): |
| 1118 | """Checks git repo status and ensures diff is from local commits.""" |
| 1119 | |
sbc@chromium.org | 7970606 | 2015-01-14 21:18:12 +0000 | [diff] [blame] | 1120 | if upstream_git_obj is None: |
| 1121 | if self.GetBranch() is None: |
| 1122 | print >> sys.stderr, ( |
dpranke@chromium.org | ee87f58 | 2015-07-31 18:46:25 +0000 | [diff] [blame] | 1123 | 'ERROR: unable to determine current branch (detached HEAD?)') |
sbc@chromium.org | 7970606 | 2015-01-14 21:18:12 +0000 | [diff] [blame] | 1124 | else: |
| 1125 | print >> sys.stderr, ( |
| 1126 | 'ERROR: no upstream branch') |
| 1127 | return False |
| 1128 | |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1129 | # Verify the commit we're diffing against is in our current branch. |
| 1130 | upstream_sha = RunGit(['rev-parse', '--verify', upstream_git_obj]).strip() |
| 1131 | common_ancestor = RunGit(['merge-base', upstream_sha, 'HEAD']).strip() |
| 1132 | if upstream_sha != common_ancestor: |
| 1133 | print >> sys.stderr, ( |
| 1134 | 'ERROR: %s is not in the current branch. You may need to rebase ' |
| 1135 | 'your tracking branch' % upstream_sha) |
| 1136 | return False |
| 1137 | |
| 1138 | # List the commits inside the diff, and verify they are all local. |
| 1139 | commits_in_diff = RunGit( |
| 1140 | ['rev-list', '^%s' % upstream_sha, 'HEAD']).splitlines() |
| 1141 | code, remote_branch = RunGitWithCode(['config', 'gitcl.remotebranch']) |
| 1142 | remote_branch = remote_branch.strip() |
| 1143 | if code != 0: |
| 1144 | _, remote_branch = self.GetRemoteBranch() |
| 1145 | |
| 1146 | commits_in_remote = RunGit( |
| 1147 | ['rev-list', '^%s' % upstream_sha, remote_branch]).splitlines() |
| 1148 | |
| 1149 | common_commits = set(commits_in_diff) & set(commits_in_remote) |
| 1150 | if common_commits: |
| 1151 | print >> sys.stderr, ( |
| 1152 | 'ERROR: Your diff contains %d commits already in %s.\n' |
| 1153 | 'Run "git log --oneline %s..HEAD" to get a list of commits in ' |
| 1154 | 'the diff. If you are using a custom git flow, you can override' |
| 1155 | ' the reference used for this check with "git config ' |
| 1156 | 'gitcl.remotebranch <git-ref>".' % ( |
| 1157 | len(common_commits), remote_branch, upstream_git_obj)) |
| 1158 | return False |
| 1159 | return True |
| 1160 | |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 1161 | def GetGitBaseUrlFromConfig(self): |
sheyang@chromium.org | a656e70 | 2014-05-15 20:43:05 +0000 | [diff] [blame] | 1162 | """Return the configured base URL from branch.<branchname>.baseurl. |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 1163 | |
| 1164 | Returns None if it is not set. |
| 1165 | """ |
sheyang@chromium.org | a656e70 | 2014-05-15 20:43:05 +0000 | [diff] [blame] | 1166 | return RunGit(['config', 'branch.%s.base-url' % self.GetBranch()], |
| 1167 | error_ok=True).strip() |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1168 | |
kjellander@chromium.org | 6abc652 | 2014-12-02 07:34:49 +0000 | [diff] [blame] | 1169 | def GetGitSvnRemoteUrl(self): |
| 1170 | """Return the configured git-svn remote URL parsed from git svn info. |
| 1171 | |
| 1172 | Returns None if it is not set. |
| 1173 | """ |
| 1174 | # URL is dependent on the current directory. |
| 1175 | data = RunGit(['svn', 'info'], cwd=settings.GetRoot()) |
| 1176 | if data: |
| 1177 | keys = dict(line.split(': ', 1) for line in data.splitlines() |
| 1178 | if ': ' in line) |
| 1179 | return keys.get('URL', None) |
| 1180 | return None |
| 1181 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1182 | def GetRemoteUrl(self): |
| 1183 | """Return the configured remote URL, e.g. 'git://example.org/foo.git/'. |
| 1184 | |
| 1185 | Returns None if there is no remote. |
| 1186 | """ |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1187 | remote, _ = self.GetRemoteBranch() |
dyen@chromium.org | 2a13d4f | 2014-06-13 00:06:37 +0000 | [diff] [blame] | 1188 | url = RunGit(['config', 'remote.%s.url' % remote], error_ok=True).strip() |
| 1189 | |
| 1190 | # If URL is pointing to a local directory, it is probably a git cache. |
| 1191 | if os.path.isdir(url): |
| 1192 | url = RunGit(['config', 'remote.%s.url' % remote], |
| 1193 | error_ok=True, |
| 1194 | cwd=url).strip() |
| 1195 | return url |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1196 | |
tandrii@chromium.org | 87985d2 | 2016-03-24 17:33:33 +0000 | [diff] [blame] | 1197 | def GetIssue(self): |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1198 | """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] | 1199 | if self.issue is None and not self.lookedup_issue: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1200 | issue = RunGit(['config', |
| 1201 | self._codereview_impl.IssueSetting(self.GetBranch())], |
| 1202 | error_ok=True).strip() |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1203 | self.issue = int(issue) or None if issue else None |
| 1204 | self.lookedup_issue = True |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1205 | return self.issue |
| 1206 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1207 | def GetIssueURL(self): |
| 1208 | """Get the URL for a particular issue.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1209 | issue = self.GetIssue() |
| 1210 | if not issue: |
dbeam@chromium.org | 015fd3d | 2013-06-18 19:02:50 +0000 | [diff] [blame] | 1211 | return None |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1212 | return '%s/%s' % (self._codereview_impl.GetCodereviewServer(), issue) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1213 | |
| 1214 | def GetDescription(self, pretty=False): |
| 1215 | if not self.has_description: |
| 1216 | if self.GetIssue(): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1217 | self.description = self._codereview_impl.FetchDescription() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1218 | self.has_description = True |
| 1219 | if pretty: |
| 1220 | wrapper = textwrap.TextWrapper() |
| 1221 | wrapper.initial_indent = wrapper.subsequent_indent = ' ' |
| 1222 | return wrapper.fill(self.description) |
| 1223 | return self.description |
| 1224 | |
| 1225 | def GetPatchset(self): |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1226 | """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] | 1227 | if self.patchset is None and not self.lookedup_patchset: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1228 | patchset = RunGit(['config', self._codereview_impl.PatchsetSetting()], |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1229 | error_ok=True).strip() |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1230 | self.patchset = int(patchset) or None if patchset else None |
| 1231 | self.lookedup_patchset = True |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1232 | return self.patchset |
| 1233 | |
| 1234 | def SetPatchset(self, patchset): |
| 1235 | """Set this branch's patchset. If patchset=0, clears the patchset.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1236 | patchset_setting = self._codereview_impl.PatchsetSetting() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1237 | if patchset: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1238 | RunGit(['config', patchset_setting, str(patchset)]) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1239 | self.patchset = patchset |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1240 | else: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1241 | RunGit(['config', '--unset', patchset_setting], |
maruel@chromium.org | 32f9f5e | 2011-09-14 13:41:47 +0000 | [diff] [blame] | 1242 | stderr=subprocess2.PIPE, error_ok=True) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1243 | self.patchset = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1244 | |
tandrii@chromium.org | a342c92 | 2016-03-16 07:08:25 +0000 | [diff] [blame] | 1245 | def SetIssue(self, issue=None): |
| 1246 | """Set this branch's issue. If issue isn't given, clears the issue.""" |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1247 | issue_setting = self._codereview_impl.IssueSetting(self.GetBranch()) |
| 1248 | codereview_setting = self._codereview_impl.GetCodereviewServerSetting() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1249 | if issue: |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1250 | self.issue = issue |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1251 | RunGit(['config', issue_setting, str(issue)]) |
| 1252 | codereview_server = self._codereview_impl.GetCodereviewServer() |
| 1253 | if codereview_server: |
| 1254 | RunGit(['config', codereview_setting, codereview_server]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1255 | else: |
teravest@chromium.org | d79d4b8 | 2013-10-23 20:09:08 +0000 | [diff] [blame] | 1256 | current_issue = self.GetIssue() |
| 1257 | if current_issue: |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1258 | RunGit(['config', '--unset', issue_setting]) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 1259 | self.issue = None |
| 1260 | self.SetPatchset(None) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1261 | |
asvitkine@chromium.org | 1516995 | 2011-09-27 14:30:53 +0000 | [diff] [blame] | 1262 | def GetChange(self, upstream_branch, author): |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 1263 | if not self.GitSanityChecks(upstream_branch): |
| 1264 | DieWithError('\nGit sanity check failure') |
| 1265 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1266 | root = settings.GetRelativeRoot() |
bratell@opera.com | f267b0e | 2013-05-02 09:11:43 +0000 | [diff] [blame] | 1267 | if not root: |
| 1268 | root = '.' |
bauerb@chromium.org | 512f1ef | 2011-04-20 15:17:57 +0000 | [diff] [blame] | 1269 | absroot = os.path.abspath(root) |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1270 | |
| 1271 | # 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] | 1272 | name = RunGitWithCode(['rev-parse', 'HEAD'])[1].strip() |
bauerb@chromium.org | 512f1ef | 2011-04-20 15:17:57 +0000 | [diff] [blame] | 1273 | # Need to pass a relative path for msysgit. |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1274 | try: |
maruel@chromium.org | 80a9ef1 | 2011-12-13 20:44:10 +0000 | [diff] [blame] | 1275 | files = scm.GIT.CaptureStatus([root], '.', upstream_branch) |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1276 | except subprocess2.CalledProcessError: |
| 1277 | DieWithError( |
pgervais@chromium.org | d6617f3 | 2013-11-19 00:34:54 +0000 | [diff] [blame] | 1278 | ('\nFailed to diff against upstream branch %s\n\n' |
maruel@chromium.org | 2b38e9c | 2011-10-19 00:04:35 +0000 | [diff] [blame] | 1279 | 'This branch probably doesn\'t exist anymore. To reset the\n' |
| 1280 | 'tracking branch, please run\n' |
| 1281 | ' git branch --set-upstream %s trunk\n' |
| 1282 | 'replacing trunk with origin/master or the relevant branch') % |
| 1283 | (upstream_branch, self.GetBranch())) |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1284 | |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1285 | issue = self.GetIssue() |
| 1286 | patchset = self.GetPatchset() |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1287 | if issue: |
| 1288 | description = self.GetDescription() |
| 1289 | else: |
| 1290 | # If the change was never uploaded, use the log messages of all commits |
| 1291 | # up to the branch point, as git cl upload will prefill the description |
| 1292 | # with these log messages. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1293 | args = ['log', '--pretty=format:%s%n%n%b', '%s...' % (upstream_branch)] |
| 1294 | description = RunGitWithCode(args)[1].strip() |
maruel@chromium.org | 03b3bdc | 2011-06-14 13:04:12 +0000 | [diff] [blame] | 1295 | |
| 1296 | if not author: |
maruel@chromium.org | 13f623c | 2011-07-22 16:02:23 +0000 | [diff] [blame] | 1297 | author = RunGit(['config', 'user.email']).strip() or None |
asvitkine@chromium.org | 1516995 | 2011-09-27 14:30:53 +0000 | [diff] [blame] | 1298 | return presubmit_support.GitChange( |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1299 | name, |
| 1300 | description, |
| 1301 | absroot, |
| 1302 | files, |
| 1303 | issue, |
| 1304 | patchset, |
agable@chromium.org | ea84ef1 | 2014-04-30 19:55:12 +0000 | [diff] [blame] | 1305 | author, |
| 1306 | upstream=upstream_branch) |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1307 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1308 | def UpdateDescription(self, description): |
| 1309 | self.description = description |
| 1310 | return self._codereview_impl.UpdateDescriptionRemote(description) |
| 1311 | |
| 1312 | def RunHook(self, committing, may_prompt, verbose, change): |
| 1313 | """Calls sys.exit() if the hook fails; returns a HookResults otherwise.""" |
| 1314 | try: |
| 1315 | return presubmit_support.DoPresubmitChecks(change, committing, |
| 1316 | verbose=verbose, output_stream=sys.stdout, input_stream=sys.stdin, |
| 1317 | default_presubmit=None, may_prompt=may_prompt, |
| 1318 | rietveld_obj=self._codereview_impl.GetRieveldObjForPresubmit()) |
| 1319 | except presubmit_support.PresubmitFailure, e: |
| 1320 | DieWithError( |
| 1321 | ('%s\nMaybe your depot_tools is out of date?\n' |
| 1322 | 'If all fails, contact maruel@') % e) |
| 1323 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1324 | def CMDPatchIssue(self, issue_arg, reject, nocommit, directory): |
| 1325 | """Fetches and applies the issue patch from codereview to local branch.""" |
tandrii@chromium.org | ef7c68c | 2016-04-07 09:39:39 +0000 | [diff] [blame] | 1326 | if isinstance(issue_arg, (int, long)) or issue_arg.isdigit(): |
| 1327 | parsed_issue_arg = _ParsedIssueNumberArgument(int(issue_arg)) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1328 | else: |
| 1329 | # Assume url. |
| 1330 | parsed_issue_arg = self._codereview_impl.ParseIssueURL( |
| 1331 | urlparse.urlparse(issue_arg)) |
| 1332 | if not parsed_issue_arg or not parsed_issue_arg.valid: |
| 1333 | DieWithError('Failed to parse issue argument "%s". ' |
| 1334 | 'Must be an issue number or a valid URL.' % issue_arg) |
| 1335 | return self._codereview_impl.CMDPatchWithParsedIssue( |
| 1336 | parsed_issue_arg, reject, nocommit, directory) |
| 1337 | |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1338 | def CMDUpload(self, options, git_diff_args, orig_args): |
| 1339 | """Uploads a change to codereview.""" |
| 1340 | if git_diff_args: |
| 1341 | # TODO(ukai): is it ok for gerrit case? |
| 1342 | base_branch = git_diff_args[0] |
| 1343 | else: |
| 1344 | if self.GetBranch() is None: |
| 1345 | DieWithError('Can\'t upload from detached HEAD state. Get on a branch!') |
| 1346 | |
| 1347 | # Default to diffing against common ancestor of upstream branch |
| 1348 | base_branch = self.GetCommonAncestorWithUpstream() |
| 1349 | git_diff_args = [base_branch, 'HEAD'] |
| 1350 | |
| 1351 | # Make sure authenticated to codereview before running potentially expensive |
| 1352 | # hooks. It is a fast, best efforts check. Codereview still can reject the |
| 1353 | # authentication during the actual upload. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1354 | self._codereview_impl.EnsureAuthenticated(force=options.force) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1355 | |
| 1356 | # Apply watchlists on upload. |
| 1357 | change = self.GetChange(base_branch, None) |
| 1358 | watchlist = watchlists.Watchlists(change.RepositoryRoot()) |
| 1359 | files = [f.LocalPath() for f in change.AffectedFiles()] |
| 1360 | if not options.bypass_watchlists: |
| 1361 | self.SetWatchers(watchlist.GetWatchersForPaths(files)) |
| 1362 | |
| 1363 | if not options.bypass_hooks: |
| 1364 | if options.reviewers or options.tbr_owners: |
| 1365 | # Set the reviewer list now so that presubmit checks can access it. |
| 1366 | change_description = ChangeDescription(change.FullDescriptionText()) |
| 1367 | change_description.update_reviewers(options.reviewers, |
| 1368 | options.tbr_owners, |
| 1369 | change) |
| 1370 | change.SetDescriptionText(change_description.description) |
| 1371 | hook_results = self.RunHook(committing=False, |
| 1372 | may_prompt=not options.force, |
| 1373 | verbose=options.verbose, |
| 1374 | change=change) |
| 1375 | if not hook_results.should_continue(): |
| 1376 | return 1 |
| 1377 | if not options.reviewers and hook_results.reviewers: |
| 1378 | options.reviewers = hook_results.reviewers.split(',') |
| 1379 | |
| 1380 | if self.GetIssue(): |
| 1381 | latest_patchset = self.GetMostRecentPatchset() |
| 1382 | local_patchset = self.GetPatchset() |
| 1383 | if (latest_patchset and local_patchset and |
| 1384 | local_patchset != latest_patchset): |
| 1385 | print ('The last upload made from this repository was patchset #%d but ' |
| 1386 | 'the most recent patchset on the server is #%d.' |
| 1387 | % (local_patchset, latest_patchset)) |
| 1388 | print ('Uploading will still work, but if you\'ve uploaded to this ' |
| 1389 | 'issue from another machine or branch the patch you\'re ' |
| 1390 | 'uploading now might not include those changes.') |
| 1391 | ask_for_data('About to upload; enter to confirm.') |
| 1392 | |
| 1393 | print_stats(options.similarity, options.find_copies, git_diff_args) |
| 1394 | ret = self.CMDUploadChange(options, git_diff_args, change) |
| 1395 | if not ret: |
| 1396 | git_set_branch_value('last-upload-hash', |
| 1397 | RunGit(['rev-parse', 'HEAD']).strip()) |
| 1398 | # Run post upload hooks, if specified. |
| 1399 | if settings.GetRunPostUploadHook(): |
| 1400 | presubmit_support.DoPostUploadExecuter( |
| 1401 | change, |
| 1402 | self, |
| 1403 | settings.GetRoot(), |
| 1404 | options.verbose, |
| 1405 | sys.stdout) |
| 1406 | |
| 1407 | # Upload all dependencies if specified. |
| 1408 | if options.dependencies: |
| 1409 | print |
| 1410 | print '--dependencies has been specified.' |
| 1411 | print 'All dependent local branches will be re-uploaded.' |
| 1412 | print |
| 1413 | # Remove the dependencies flag from args so that we do not end up in a |
| 1414 | # loop. |
| 1415 | orig_args.remove('--dependencies') |
| 1416 | ret = upload_branch_deps(self, orig_args) |
| 1417 | return ret |
| 1418 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1419 | def SetCQState(self, new_state): |
| 1420 | """Update the CQ state for latest patchset. |
| 1421 | |
| 1422 | Issue must have been already uploaded and known. |
| 1423 | """ |
| 1424 | assert new_state in _CQState.ALL_STATES |
| 1425 | assert self.GetIssue() |
| 1426 | return self._codereview_impl.SetCQState(new_state) |
| 1427 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1428 | # Forward methods to codereview specific implementation. |
| 1429 | |
| 1430 | def CloseIssue(self): |
| 1431 | return self._codereview_impl.CloseIssue() |
| 1432 | |
| 1433 | def GetStatus(self): |
| 1434 | return self._codereview_impl.GetStatus() |
| 1435 | |
| 1436 | def GetCodereviewServer(self): |
| 1437 | return self._codereview_impl.GetCodereviewServer() |
| 1438 | |
| 1439 | def GetApprovingReviewers(self): |
| 1440 | return self._codereview_impl.GetApprovingReviewers() |
| 1441 | |
| 1442 | def GetMostRecentPatchset(self): |
| 1443 | return self._codereview_impl.GetMostRecentPatchset() |
| 1444 | |
| 1445 | def __getattr__(self, attr): |
| 1446 | # This is because lots of untested code accesses Rietveld-specific stuff |
| 1447 | # directly, and it's hard to fix for sure. So, just let it work, and fix |
| 1448 | # on a cases by case basis. |
| 1449 | return getattr(self._codereview_impl, attr) |
| 1450 | |
| 1451 | |
| 1452 | class _ChangelistCodereviewBase(object): |
| 1453 | """Abstract base class encapsulating codereview specifics of a changelist.""" |
| 1454 | def __init__(self, changelist): |
| 1455 | self._changelist = changelist # instance of Changelist |
| 1456 | |
| 1457 | def __getattr__(self, attr): |
| 1458 | # Forward methods to changelist. |
| 1459 | # TODO(tandrii): maybe clean up _GerritChangelistImpl and |
| 1460 | # _RietveldChangelistImpl to avoid this hack? |
| 1461 | return getattr(self._changelist, attr) |
| 1462 | |
| 1463 | def GetStatus(self): |
| 1464 | """Apply a rough heuristic to give a simple summary of an issue's review |
| 1465 | or CQ status, assuming adherence to a common workflow. |
| 1466 | |
| 1467 | Returns None if no issue for this branch, or specific string keywords. |
| 1468 | """ |
| 1469 | raise NotImplementedError() |
| 1470 | |
| 1471 | def GetCodereviewServer(self): |
| 1472 | """Returns server URL without end slash, like "https://codereview.com".""" |
| 1473 | raise NotImplementedError() |
| 1474 | |
| 1475 | def FetchDescription(self): |
| 1476 | """Fetches and returns description from the codereview server.""" |
| 1477 | raise NotImplementedError() |
| 1478 | |
| 1479 | def GetCodereviewServerSetting(self): |
| 1480 | """Returns git config setting for the codereview server.""" |
| 1481 | raise NotImplementedError() |
| 1482 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 1483 | @classmethod |
| 1484 | def IssueSetting(cls, branch): |
tandrii@chromium.org | d03bc63 | 2016-04-12 14:17:26 +0000 | [diff] [blame] | 1485 | return 'branch.%s.%s' % (branch, cls.IssueSettingSuffix()) |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 1486 | |
| 1487 | @classmethod |
tandrii@chromium.org | d03bc63 | 2016-04-12 14:17:26 +0000 | [diff] [blame] | 1488 | def IssueSettingSuffix(cls): |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1489 | """Returns name of git config setting which stores issue number for a given |
| 1490 | branch.""" |
| 1491 | raise NotImplementedError() |
| 1492 | |
| 1493 | def PatchsetSetting(self): |
| 1494 | """Returns name of git config setting which stores issue number.""" |
| 1495 | raise NotImplementedError() |
| 1496 | |
| 1497 | def GetRieveldObjForPresubmit(self): |
| 1498 | # This is an unfortunate Rietveld-embeddedness in presubmit. |
| 1499 | # For non-Rietveld codereviews, this probably should return a dummy object. |
| 1500 | raise NotImplementedError() |
| 1501 | |
| 1502 | def UpdateDescriptionRemote(self, description): |
| 1503 | """Update the description on codereview site.""" |
| 1504 | raise NotImplementedError() |
| 1505 | |
| 1506 | def CloseIssue(self): |
| 1507 | """Closes the issue.""" |
| 1508 | raise NotImplementedError() |
| 1509 | |
| 1510 | def GetApprovingReviewers(self): |
| 1511 | """Returns a list of reviewers approving the change. |
| 1512 | |
| 1513 | Note: not necessarily committers. |
| 1514 | """ |
| 1515 | raise NotImplementedError() |
| 1516 | |
| 1517 | def GetMostRecentPatchset(self): |
| 1518 | """Returns the most recent patchset number from the codereview site.""" |
| 1519 | raise NotImplementedError() |
| 1520 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1521 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, |
| 1522 | directory): |
| 1523 | """Fetches and applies the issue. |
| 1524 | |
| 1525 | Arguments: |
| 1526 | parsed_issue_arg: instance of _ParsedIssueNumberArgument. |
| 1527 | reject: if True, reject the failed patch instead of switching to 3-way |
| 1528 | merge. Rietveld only. |
| 1529 | nocommit: do not commit the patch, thus leave the tree dirty. Rietveld |
| 1530 | only. |
| 1531 | directory: switch to directory before applying the patch. Rietveld only. |
| 1532 | """ |
| 1533 | raise NotImplementedError() |
| 1534 | |
| 1535 | @staticmethod |
| 1536 | def ParseIssueURL(parsed_url): |
| 1537 | """Parses url and returns instance of _ParsedIssueNumberArgument or None if |
| 1538 | failed.""" |
| 1539 | raise NotImplementedError() |
| 1540 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1541 | def EnsureAuthenticated(self, force): |
| 1542 | """Best effort check that user is authenticated with codereview server. |
| 1543 | |
| 1544 | Arguments: |
| 1545 | force: whether to skip confirmation questions. |
| 1546 | """ |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1547 | raise NotImplementedError() |
| 1548 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 1549 | def CMDUploadChange(self, options, args, change): |
| 1550 | """Uploads a change to codereview.""" |
| 1551 | raise NotImplementedError() |
| 1552 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1553 | def SetCQState(self, new_state): |
| 1554 | """Update the CQ state for latest patchset. |
| 1555 | |
| 1556 | Issue must have been already uploaded and known. |
| 1557 | """ |
| 1558 | raise NotImplementedError() |
| 1559 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1560 | |
| 1561 | class _RietveldChangelistImpl(_ChangelistCodereviewBase): |
| 1562 | def __init__(self, changelist, auth_config=None, rietveld_server=None): |
| 1563 | super(_RietveldChangelistImpl, self).__init__(changelist) |
| 1564 | assert settings, 'must be initialized in _ChangelistCodereviewBase' |
| 1565 | settings.GetDefaultServerUrl() |
| 1566 | |
| 1567 | self._rietveld_server = rietveld_server |
| 1568 | self._auth_config = auth_config |
| 1569 | self._props = None |
| 1570 | self._rpc_server = None |
| 1571 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1572 | def GetCodereviewServer(self): |
| 1573 | if not self._rietveld_server: |
| 1574 | # If we're on a branch then get the server potentially associated |
| 1575 | # with that branch. |
| 1576 | if self.GetIssue(): |
| 1577 | rietveld_server_setting = self.GetCodereviewServerSetting() |
| 1578 | if rietveld_server_setting: |
| 1579 | self._rietveld_server = gclient_utils.UpgradeToHttps(RunGit( |
| 1580 | ['config', rietveld_server_setting], error_ok=True).strip()) |
| 1581 | if not self._rietveld_server: |
| 1582 | self._rietveld_server = settings.GetDefaultServerUrl() |
| 1583 | return self._rietveld_server |
| 1584 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1585 | def EnsureAuthenticated(self, force): |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1586 | """Best effort check that user is authenticated with Rietveld server.""" |
| 1587 | if self._auth_config.use_oauth2: |
| 1588 | authenticator = auth.get_authenticator_for_host( |
| 1589 | self.GetCodereviewServer(), self._auth_config) |
| 1590 | if not authenticator.has_cached_credentials(): |
| 1591 | raise auth.LoginRequiredError(self.GetCodereviewServer()) |
| 1592 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1593 | def FetchDescription(self): |
| 1594 | issue = self.GetIssue() |
| 1595 | assert issue |
| 1596 | try: |
| 1597 | return self.RpcServer().get_description(issue).strip() |
| 1598 | except urllib2.HTTPError as e: |
| 1599 | if e.code == 404: |
| 1600 | DieWithError( |
| 1601 | ('\nWhile fetching the description for issue %d, received a ' |
| 1602 | '404 (not found)\n' |
| 1603 | 'error. It is likely that you deleted this ' |
| 1604 | 'issue on the server. If this is the\n' |
| 1605 | 'case, please run\n\n' |
| 1606 | ' git cl issue 0\n\n' |
| 1607 | 'to clear the association with the deleted issue. Then run ' |
| 1608 | 'this command again.') % issue) |
| 1609 | else: |
| 1610 | DieWithError( |
| 1611 | '\nFailed to fetch issue description. HTTP error %d' % e.code) |
| 1612 | except urllib2.URLError as e: |
| 1613 | print >> sys.stderr, ( |
| 1614 | 'Warning: Failed to retrieve CL description due to network ' |
| 1615 | 'failure.') |
| 1616 | return '' |
| 1617 | |
| 1618 | def GetMostRecentPatchset(self): |
| 1619 | return self.GetIssueProperties()['patchsets'][-1] |
| 1620 | |
| 1621 | def GetPatchSetDiff(self, issue, patchset): |
| 1622 | return self.RpcServer().get( |
| 1623 | '/download/issue%s_%s.diff' % (issue, patchset)) |
| 1624 | |
| 1625 | def GetIssueProperties(self): |
| 1626 | if self._props is None: |
| 1627 | issue = self.GetIssue() |
| 1628 | if not issue: |
| 1629 | self._props = {} |
| 1630 | else: |
| 1631 | self._props = self.RpcServer().get_issue_properties(issue, True) |
| 1632 | return self._props |
| 1633 | |
| 1634 | def GetApprovingReviewers(self): |
| 1635 | return get_approving_reviewers(self.GetIssueProperties()) |
| 1636 | |
| 1637 | def AddComment(self, message): |
| 1638 | return self.RpcServer().add_comment(self.GetIssue(), message) |
| 1639 | |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 1640 | def GetStatus(self): |
| 1641 | """Apply a rough heuristic to give a simple summary of an issue's review |
| 1642 | or CQ status, assuming adherence to a common workflow. |
| 1643 | |
| 1644 | Returns None if no issue for this branch, or one of the following keywords: |
| 1645 | * 'error' - error from review tool (including deleted issues) |
| 1646 | * 'unsent' - not sent for review |
| 1647 | * 'waiting' - waiting for review |
| 1648 | * 'reply' - waiting for owner to reply to review |
| 1649 | * 'lgtm' - LGTM from at least one approved reviewer |
| 1650 | * 'commit' - in the commit queue |
| 1651 | * 'closed' - closed |
| 1652 | """ |
| 1653 | if not self.GetIssue(): |
| 1654 | return None |
| 1655 | |
| 1656 | try: |
| 1657 | props = self.GetIssueProperties() |
| 1658 | except urllib2.HTTPError: |
| 1659 | return 'error' |
| 1660 | |
| 1661 | if props.get('closed'): |
| 1662 | # Issue is closed. |
| 1663 | return 'closed' |
tandrii@chromium.org | b4f6a22 | 2016-03-03 01:11:04 +0000 | [diff] [blame] | 1664 | 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] | 1665 | # Issue is in the commit queue. |
| 1666 | return 'commit' |
| 1667 | |
| 1668 | try: |
| 1669 | reviewers = self.GetApprovingReviewers() |
| 1670 | except urllib2.HTTPError: |
| 1671 | return 'error' |
| 1672 | |
| 1673 | if reviewers: |
| 1674 | # Was LGTM'ed. |
| 1675 | return 'lgtm' |
| 1676 | |
| 1677 | messages = props.get('messages') or [] |
| 1678 | |
| 1679 | if not messages: |
| 1680 | # No message was sent. |
| 1681 | return 'unsent' |
| 1682 | if messages[-1]['sender'] != props.get('owner_email'): |
| 1683 | # Non-LGTM reply from non-owner |
| 1684 | return 'reply' |
| 1685 | return 'waiting' |
| 1686 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1687 | def UpdateDescriptionRemote(self, description): |
maruel@chromium.org | b021b32 | 2013-04-08 17:57:29 +0000 | [diff] [blame] | 1688 | return self.RpcServer().update_description( |
| 1689 | self.GetIssue(), self.description) |
| 1690 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1691 | def CloseIssue(self): |
maruel@chromium.org | b021b32 | 2013-04-08 17:57:29 +0000 | [diff] [blame] | 1692 | return self.RpcServer().close_issue(self.GetIssue()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1693 | |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 1694 | def SetFlag(self, flag, value): |
| 1695 | """Patchset must match.""" |
| 1696 | if not self.GetPatchset(): |
| 1697 | DieWithError('The patchset needs to match. Send another patchset.') |
| 1698 | try: |
| 1699 | return self.RpcServer().set_flag( |
maruel@chromium.org | 5242430 | 2012-08-29 15:14:30 +0000 | [diff] [blame] | 1700 | self.GetIssue(), self.GetPatchset(), flag, value) |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 1701 | except urllib2.HTTPError, e: |
| 1702 | if e.code == 404: |
| 1703 | DieWithError('The issue %s doesn\'t exist.' % self.GetIssue()) |
| 1704 | if e.code == 403: |
| 1705 | DieWithError( |
| 1706 | ('Access denied to issue %s. Maybe the patchset %s doesn\'t ' |
| 1707 | 'match?') % (self.GetIssue(), self.GetPatchset())) |
| 1708 | raise |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1709 | |
maruel@chromium.org | cab38e9 | 2011-04-09 00:30:51 +0000 | [diff] [blame] | 1710 | def RpcServer(self): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1711 | """Returns an upload.RpcServer() to access this review's rietveld instance. |
| 1712 | """ |
maruel@chromium.org | e77ebbf | 2011-03-29 20:35:38 +0000 | [diff] [blame] | 1713 | if not self._rpc_server: |
maruel@chromium.org | 4bac4b5 | 2012-11-27 20:33:52 +0000 | [diff] [blame] | 1714 | self._rpc_server = rietveld.CachingRietveld( |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1715 | self.GetCodereviewServer(), |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 1716 | self._auth_config or auth.make_auth_config()) |
maruel@chromium.org | e77ebbf | 2011-03-29 20:35:38 +0000 | [diff] [blame] | 1717 | return self._rpc_server |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1718 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 1719 | @classmethod |
tandrii@chromium.org | d03bc63 | 2016-04-12 14:17:26 +0000 | [diff] [blame] | 1720 | def IssueSettingSuffix(cls): |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 1721 | return 'rietveldissue' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1722 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1723 | def PatchsetSetting(self): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1724 | """Return the git setting that stores this change's most recent patchset.""" |
| 1725 | return 'branch.%s.rietveldpatchset' % self.GetBranch() |
| 1726 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1727 | def GetCodereviewServerSetting(self): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1728 | """Returns the git setting that stores this change's rietveld server.""" |
szager@chromium.org | d62c61f | 2014-10-20 22:33:21 +0000 | [diff] [blame] | 1729 | branch = self.GetBranch() |
| 1730 | if branch: |
| 1731 | return 'branch.%s.rietveldserver' % branch |
| 1732 | return None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1733 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1734 | def GetRieveldObjForPresubmit(self): |
| 1735 | return self.RpcServer() |
| 1736 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1737 | def SetCQState(self, new_state): |
| 1738 | props = self.GetIssueProperties() |
| 1739 | if props.get('private'): |
| 1740 | DieWithError('Cannot set-commit on private issue') |
| 1741 | |
| 1742 | if new_state == _CQState.COMMIT: |
| 1743 | self.SetFlag('commit', '1') |
| 1744 | elif new_state == _CQState.NONE: |
| 1745 | self.SetFlag('commit', '0') |
| 1746 | else: |
| 1747 | raise NotImplementedError() |
| 1748 | |
| 1749 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1750 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, |
| 1751 | directory): |
| 1752 | # TODO(maruel): Use apply_issue.py |
| 1753 | |
| 1754 | # PatchIssue should never be called with a dirty tree. It is up to the |
| 1755 | # caller to check this, but just in case we assert here since the |
| 1756 | # consequences of the caller not checking this could be dire. |
| 1757 | assert(not git_common.is_dirty_git_tree('apply')) |
| 1758 | assert(parsed_issue_arg.valid) |
| 1759 | self._changelist.issue = parsed_issue_arg.issue |
| 1760 | if parsed_issue_arg.hostname: |
| 1761 | self._rietveld_server = 'https://%s' % parsed_issue_arg.hostname |
| 1762 | |
tandrii@chromium.org | ef7c68c | 2016-04-07 09:39:39 +0000 | [diff] [blame] | 1763 | if (isinstance(parsed_issue_arg, _RietveldParsedIssueNumberArgument) and |
| 1764 | parsed_issue_arg.patch_url): |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1765 | assert parsed_issue_arg.patchset |
| 1766 | patchset = parsed_issue_arg.patchset |
| 1767 | patch_data = urllib2.urlopen(parsed_issue_arg.patch_url).read() |
| 1768 | else: |
| 1769 | patchset = parsed_issue_arg.patchset or self.GetMostRecentPatchset() |
| 1770 | patch_data = self.GetPatchSetDiff(self.GetIssue(), patchset) |
| 1771 | |
| 1772 | # Switch up to the top-level directory, if necessary, in preparation for |
| 1773 | # applying the patch. |
| 1774 | top = settings.GetRelativeRoot() |
| 1775 | if top: |
| 1776 | os.chdir(top) |
| 1777 | |
| 1778 | # Git patches have a/ at the beginning of source paths. We strip that out |
| 1779 | # with a sed script rather than the -p flag to patch so we can feed either |
| 1780 | # Git or svn-style patches into the same apply command. |
| 1781 | # re.sub() should be used but flags=re.MULTILINE is only in python 2.7. |
| 1782 | try: |
| 1783 | patch_data = subprocess2.check_output( |
| 1784 | ['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'], stdin=patch_data) |
| 1785 | except subprocess2.CalledProcessError: |
| 1786 | DieWithError('Git patch mungling failed.') |
| 1787 | logging.info(patch_data) |
| 1788 | |
| 1789 | # We use "git apply" to apply the patch instead of "patch" so that we can |
| 1790 | # pick up file adds. |
| 1791 | # The --index flag means: also insert into the index (so we catch adds). |
| 1792 | cmd = ['git', 'apply', '--index', '-p0'] |
| 1793 | if directory: |
| 1794 | cmd.extend(('--directory', directory)) |
| 1795 | if reject: |
| 1796 | cmd.append('--reject') |
| 1797 | elif IsGitVersionAtLeast('1.7.12'): |
| 1798 | cmd.append('--3way') |
| 1799 | try: |
| 1800 | subprocess2.check_call(cmd, env=GetNoGitPagerEnv(), |
| 1801 | stdin=patch_data, stdout=subprocess2.VOID) |
| 1802 | except subprocess2.CalledProcessError: |
| 1803 | print 'Failed to apply the patch' |
| 1804 | return 1 |
| 1805 | |
| 1806 | # If we had an issue, commit the current state and register the issue. |
| 1807 | if not nocommit: |
| 1808 | RunGit(['commit', '-m', (self.GetDescription() + '\n\n' + |
| 1809 | 'patch from issue %(i)s at patchset ' |
| 1810 | '%(p)s (http://crrev.com/%(i)s#ps%(p)s)' |
| 1811 | % {'i': self.GetIssue(), 'p': patchset})]) |
| 1812 | self.SetIssue(self.GetIssue()) |
| 1813 | self.SetPatchset(patchset) |
| 1814 | print "Committed patch locally." |
| 1815 | else: |
| 1816 | print "Patch applied to index." |
| 1817 | return 0 |
| 1818 | |
| 1819 | @staticmethod |
| 1820 | def ParseIssueURL(parsed_url): |
| 1821 | if not parsed_url.scheme or not parsed_url.scheme.startswith('http'): |
| 1822 | return None |
| 1823 | # Typical url: https://domain/<issue_number>[/[other]] |
| 1824 | match = re.match('/(\d+)(/.*)?$', parsed_url.path) |
| 1825 | if match: |
| 1826 | return _RietveldParsedIssueNumberArgument( |
| 1827 | issue=int(match.group(1)), |
| 1828 | hostname=parsed_url.netloc) |
| 1829 | # Rietveld patch: https://domain/download/issue<number>_<patchset>.diff |
| 1830 | match = re.match(r'/download/issue(\d+)_(\d+).diff$', parsed_url.path) |
| 1831 | if match: |
| 1832 | return _RietveldParsedIssueNumberArgument( |
| 1833 | issue=int(match.group(1)), |
| 1834 | patchset=int(match.group(2)), |
| 1835 | hostname=parsed_url.netloc, |
| 1836 | patch_url=gclient_utils.UpgradeToHttps(parsed_url.geturl())) |
| 1837 | return None |
| 1838 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 1839 | def CMDUploadChange(self, options, args, change): |
| 1840 | """Upload the patch to Rietveld.""" |
| 1841 | upload_args = ['--assume_yes'] # Don't ask about untracked files. |
| 1842 | upload_args.extend(['--server', self.GetCodereviewServer()]) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 1843 | upload_args.extend(auth.auth_config_to_command_options(self._auth_config)) |
| 1844 | if options.emulate_svn_auto_props: |
| 1845 | upload_args.append('--emulate_svn_auto_props') |
| 1846 | |
| 1847 | change_desc = None |
| 1848 | |
| 1849 | if options.email is not None: |
| 1850 | upload_args.extend(['--email', options.email]) |
| 1851 | |
| 1852 | if self.GetIssue(): |
| 1853 | if options.title: |
| 1854 | upload_args.extend(['--title', options.title]) |
| 1855 | if options.message: |
| 1856 | upload_args.extend(['--message', options.message]) |
| 1857 | upload_args.extend(['--issue', str(self.GetIssue())]) |
| 1858 | print ('This branch is associated with issue %s. ' |
| 1859 | 'Adding patch to that issue.' % self.GetIssue()) |
| 1860 | else: |
| 1861 | if options.title: |
| 1862 | upload_args.extend(['--title', options.title]) |
| 1863 | message = (options.title or options.message or |
| 1864 | CreateDescriptionFromLog(args)) |
| 1865 | change_desc = ChangeDescription(message) |
| 1866 | if options.reviewers or options.tbr_owners: |
| 1867 | change_desc.update_reviewers(options.reviewers, |
| 1868 | options.tbr_owners, |
| 1869 | change) |
| 1870 | if not options.force: |
| 1871 | change_desc.prompt() |
| 1872 | |
| 1873 | if not change_desc.description: |
| 1874 | print "Description is empty; aborting." |
| 1875 | return 1 |
| 1876 | |
| 1877 | upload_args.extend(['--message', change_desc.description]) |
| 1878 | if change_desc.get_reviewers(): |
| 1879 | upload_args.append('--reviewers=%s' % ','.join( |
| 1880 | change_desc.get_reviewers())) |
| 1881 | if options.send_mail: |
| 1882 | if not change_desc.get_reviewers(): |
| 1883 | DieWithError("Must specify reviewers to send email.") |
| 1884 | upload_args.append('--send_mail') |
| 1885 | |
| 1886 | # We check this before applying rietveld.private assuming that in |
| 1887 | # rietveld.cc only addresses which we can send private CLs to are listed |
| 1888 | # if rietveld.private is set, and so we should ignore rietveld.cc only |
| 1889 | # when --private is specified explicitly on the command line. |
| 1890 | if options.private: |
| 1891 | logging.warn('rietveld.cc is ignored since private flag is specified. ' |
| 1892 | 'You need to review and add them manually if necessary.') |
| 1893 | cc = self.GetCCListWithoutDefault() |
| 1894 | else: |
| 1895 | cc = self.GetCCList() |
| 1896 | cc = ','.join(filter(None, (cc, ','.join(options.cc)))) |
| 1897 | if cc: |
| 1898 | upload_args.extend(['--cc', cc]) |
| 1899 | |
| 1900 | if options.private or settings.GetDefaultPrivateFlag() == "True": |
| 1901 | upload_args.append('--private') |
| 1902 | |
| 1903 | upload_args.extend(['--git_similarity', str(options.similarity)]) |
| 1904 | if not options.find_copies: |
| 1905 | upload_args.extend(['--git_no_find_copies']) |
| 1906 | |
| 1907 | # Include the upstream repo's URL in the change -- this is useful for |
| 1908 | # projects that have their source spread across multiple repos. |
| 1909 | remote_url = self.GetGitBaseUrlFromConfig() |
| 1910 | if not remote_url: |
| 1911 | if settings.GetIsGitSvn(): |
| 1912 | remote_url = self.GetGitSvnRemoteUrl() |
| 1913 | else: |
| 1914 | if self.GetRemoteUrl() and '/' in self.GetUpstreamBranch(): |
| 1915 | remote_url = '%s@%s' % (self.GetRemoteUrl(), |
| 1916 | self.GetUpstreamBranch().split('/')[-1]) |
| 1917 | if remote_url: |
| 1918 | upload_args.extend(['--base_url', remote_url]) |
| 1919 | remote, remote_branch = self.GetRemoteBranch() |
| 1920 | target_ref = GetTargetRef(remote, remote_branch, options.target_branch, |
| 1921 | settings.GetPendingRefPrefix()) |
| 1922 | if target_ref: |
| 1923 | upload_args.extend(['--target_ref', target_ref]) |
| 1924 | |
| 1925 | # Look for dependent patchsets. See crbug.com/480453 for more details. |
| 1926 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
| 1927 | upstream_branch = ShortBranchName(upstream_branch) |
| 1928 | if remote is '.': |
| 1929 | # A local branch is being tracked. |
| 1930 | local_branch = ShortBranchName(upstream_branch) |
| 1931 | if settings.GetIsSkipDependencyUpload(local_branch): |
| 1932 | print |
| 1933 | print ('Skipping dependency patchset upload because git config ' |
| 1934 | 'branch.%s.skip-deps-uploads is set to True.' % local_branch) |
| 1935 | print |
| 1936 | else: |
| 1937 | auth_config = auth.extract_auth_config_from_options(options) |
| 1938 | branch_cl = Changelist(branchref=local_branch, |
| 1939 | auth_config=auth_config) |
| 1940 | branch_cl_issue_url = branch_cl.GetIssueURL() |
| 1941 | branch_cl_issue = branch_cl.GetIssue() |
| 1942 | branch_cl_patchset = branch_cl.GetPatchset() |
| 1943 | if branch_cl_issue_url and branch_cl_issue and branch_cl_patchset: |
| 1944 | upload_args.extend( |
| 1945 | ['--depends_on_patchset', '%s:%s' % ( |
| 1946 | branch_cl_issue, branch_cl_patchset)]) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 1947 | print( |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 1948 | '\n' |
| 1949 | 'The current branch (%s) is tracking a local branch (%s) with ' |
| 1950 | 'an associated CL.\n' |
| 1951 | 'Adding %s/#ps%s as a dependency patchset.\n' |
| 1952 | '\n' % (self.GetBranch(), local_branch, branch_cl_issue_url, |
| 1953 | branch_cl_patchset)) |
| 1954 | |
| 1955 | project = settings.GetProject() |
| 1956 | if project: |
| 1957 | upload_args.extend(['--project', project]) |
| 1958 | |
| 1959 | if options.cq_dry_run: |
| 1960 | upload_args.extend(['--cq_dry_run']) |
| 1961 | |
| 1962 | try: |
| 1963 | upload_args = ['upload'] + upload_args + args |
| 1964 | logging.info('upload.RealMain(%s)', upload_args) |
| 1965 | issue, patchset = upload.RealMain(upload_args) |
| 1966 | issue = int(issue) |
| 1967 | patchset = int(patchset) |
| 1968 | except KeyboardInterrupt: |
| 1969 | sys.exit(1) |
| 1970 | except: |
| 1971 | # If we got an exception after the user typed a description for their |
| 1972 | # change, back up the description before re-raising. |
| 1973 | if change_desc: |
| 1974 | backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE) |
| 1975 | print('\nGot exception while uploading -- saving description to %s\n' % |
| 1976 | backup_path) |
| 1977 | backup_file = open(backup_path, 'w') |
| 1978 | backup_file.write(change_desc.description) |
| 1979 | backup_file.close() |
| 1980 | raise |
| 1981 | |
| 1982 | if not self.GetIssue(): |
| 1983 | self.SetIssue(issue) |
| 1984 | self.SetPatchset(patchset) |
| 1985 | |
| 1986 | if options.use_commit_queue: |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 1987 | self.SetCQState(_CQState.COMMIT) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 1988 | return 0 |
| 1989 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1990 | |
| 1991 | class _GerritChangelistImpl(_ChangelistCodereviewBase): |
| 1992 | def __init__(self, changelist, auth_config=None): |
| 1993 | # auth_config is Rietveld thing, kept here to preserve interface only. |
| 1994 | super(_GerritChangelistImpl, self).__init__(changelist) |
| 1995 | self._change_id = None |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1996 | # Lazily cached values. |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1997 | self._gerrit_server = None # e.g. https://chromium-review.googlesource.com |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 1998 | self._gerrit_host = None # e.g. chromium-review.googlesource.com |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1999 | |
| 2000 | def _GetGerritHost(self): |
| 2001 | # Lazy load of configs. |
| 2002 | self.GetCodereviewServer() |
| 2003 | return self._gerrit_host |
| 2004 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2005 | def _GetGitHost(self): |
| 2006 | """Returns git host to be used when uploading change to Gerrit.""" |
| 2007 | return urlparse.urlparse(self.GetRemoteUrl()).netloc |
| 2008 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2009 | def GetCodereviewServer(self): |
| 2010 | if not self._gerrit_server: |
| 2011 | # If we're on a branch then get the server potentially associated |
| 2012 | # with that branch. |
| 2013 | if self.GetIssue(): |
| 2014 | gerrit_server_setting = self.GetCodereviewServerSetting() |
| 2015 | if gerrit_server_setting: |
| 2016 | self._gerrit_server = RunGit(['config', gerrit_server_setting], |
| 2017 | error_ok=True).strip() |
| 2018 | if self._gerrit_server: |
| 2019 | self._gerrit_host = urlparse.urlparse(self._gerrit_server).netloc |
| 2020 | if not self._gerrit_server: |
| 2021 | # We assume repo to be hosted on Gerrit, and hence Gerrit server |
| 2022 | # has "-review" suffix for lowest level subdomain. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2023 | parts = self._GetGitHost().split('.') |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2024 | parts[0] = parts[0] + '-review' |
| 2025 | self._gerrit_host = '.'.join(parts) |
| 2026 | self._gerrit_server = 'https://%s' % self._gerrit_host |
| 2027 | return self._gerrit_server |
| 2028 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2029 | @classmethod |
tandrii@chromium.org | d03bc63 | 2016-04-12 14:17:26 +0000 | [diff] [blame] | 2030 | def IssueSettingSuffix(cls): |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 2031 | return 'gerritissue' |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2032 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2033 | def EnsureAuthenticated(self, force): |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2034 | """Best effort check that user is authenticated with Gerrit server.""" |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 2035 | if settings.GetGerritSkipEnsureAuthenticated(): |
| 2036 | # For projects with unusual authentication schemes. |
| 2037 | # See http://crbug.com/603378. |
| 2038 | return |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2039 | # Lazy-loader to identify Gerrit and Git hosts. |
| 2040 | if gerrit_util.GceAuthenticator.is_gce(): |
| 2041 | return |
| 2042 | self.GetCodereviewServer() |
| 2043 | git_host = self._GetGitHost() |
| 2044 | assert self._gerrit_server and self._gerrit_host |
| 2045 | cookie_auth = gerrit_util.CookiesAuthenticator() |
| 2046 | |
| 2047 | gerrit_auth = cookie_auth.get_auth_header(self._gerrit_host) |
| 2048 | git_auth = cookie_auth.get_auth_header(git_host) |
| 2049 | if gerrit_auth and git_auth: |
| 2050 | if gerrit_auth == git_auth: |
| 2051 | return |
| 2052 | print(( |
| 2053 | 'WARNING: you have different credentials for Gerrit and git hosts.\n' |
| 2054 | ' Check your %s or %s file for credentials of hosts:\n' |
| 2055 | ' %s\n' |
| 2056 | ' %s\n' |
| 2057 | ' %s') % |
| 2058 | (cookie_auth.get_gitcookies_path(), cookie_auth.get_netrc_path(), |
| 2059 | git_host, self._gerrit_host, |
| 2060 | cookie_auth.get_new_password_message(git_host))) |
| 2061 | if not force: |
| 2062 | ask_for_data('If you know what you are doing, press Enter to continue, ' |
| 2063 | 'Ctrl+C to abort.') |
| 2064 | return |
| 2065 | else: |
| 2066 | missing = ( |
| 2067 | [] if gerrit_auth else [self._gerrit_host] + |
| 2068 | [] if git_auth else [git_host]) |
| 2069 | DieWithError('Credentials for the following hosts are required:\n' |
| 2070 | ' %s\n' |
| 2071 | 'These are read from %s (or legacy %s)\n' |
| 2072 | '%s' % ( |
| 2073 | '\n '.join(missing), |
| 2074 | cookie_auth.get_gitcookies_path(), |
| 2075 | cookie_auth.get_netrc_path(), |
| 2076 | cookie_auth.get_new_password_message(git_host))) |
| 2077 | |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2078 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2079 | def PatchsetSetting(self): |
| 2080 | """Return the git setting that stores this change's most recent patchset.""" |
| 2081 | return 'branch.%s.gerritpatchset' % self.GetBranch() |
| 2082 | |
| 2083 | def GetCodereviewServerSetting(self): |
| 2084 | """Returns the git setting that stores this change's Gerrit server.""" |
| 2085 | branch = self.GetBranch() |
| 2086 | if branch: |
| 2087 | return 'branch.%s.gerritserver' % branch |
| 2088 | return None |
| 2089 | |
| 2090 | def GetRieveldObjForPresubmit(self): |
| 2091 | class ThisIsNotRietveldIssue(object): |
| 2092 | def __nonzero__(self): |
| 2093 | # This is a hack to make presubmit_support think that rietveld is not |
| 2094 | # defined, yet still ensure that calls directly result in a decent |
| 2095 | # exception message below. |
| 2096 | return False |
| 2097 | |
| 2098 | def __getattr__(self, attr): |
| 2099 | print( |
| 2100 | 'You aren\'t using Rietveld at the moment, but Gerrit.\n' |
| 2101 | 'Using Rietveld in your PRESUBMIT scripts won\'t work.\n' |
| 2102 | 'Please, either change your PRESUBIT to not use rietveld_obj.%s,\n' |
| 2103 | 'or use Rietveld for codereview.\n' |
| 2104 | 'See also http://crbug.com/579160.' % attr) |
| 2105 | raise NotImplementedError() |
| 2106 | return ThisIsNotRietveldIssue() |
| 2107 | |
| 2108 | def GetStatus(self): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2109 | """Apply a rough heuristic to give a simple summary of an issue's review |
| 2110 | or CQ status, assuming adherence to a common workflow. |
| 2111 | |
| 2112 | Returns None if no issue for this branch, or one of the following keywords: |
| 2113 | * 'error' - error from review tool (including deleted issues) |
| 2114 | * 'unsent' - no reviewers added |
| 2115 | * 'waiting' - waiting for review |
| 2116 | * 'reply' - waiting for owner to reply to review |
| 2117 | * 'not lgtm' - Code-Review -2 from at least one approved reviewer |
| 2118 | * 'lgtm' - Code-Review +2 from at least one approved reviewer |
| 2119 | * 'commit' - in the commit queue |
| 2120 | * 'closed' - abandoned |
| 2121 | """ |
| 2122 | if not self.GetIssue(): |
| 2123 | return None |
| 2124 | |
| 2125 | try: |
| 2126 | data = self._GetChangeDetail(['DETAILED_LABELS', 'CURRENT_REVISION']) |
| 2127 | except httplib.HTTPException: |
| 2128 | return 'error' |
| 2129 | |
| 2130 | if data['status'] == 'ABANDONED': |
| 2131 | return 'closed' |
| 2132 | |
| 2133 | cq_label = data['labels'].get('Commit-Queue', {}) |
| 2134 | if cq_label: |
| 2135 | # Vote value is a stringified integer, which we expect from 0 to 2. |
| 2136 | vote_value = cq_label.get('value', '0') |
| 2137 | vote_text = cq_label.get('values', {}).get(vote_value, '') |
| 2138 | if vote_text.lower() == 'commit': |
| 2139 | return 'commit' |
| 2140 | |
| 2141 | lgtm_label = data['labels'].get('Code-Review', {}) |
| 2142 | if lgtm_label: |
| 2143 | if 'rejected' in lgtm_label: |
| 2144 | return 'not lgtm' |
| 2145 | if 'approved' in lgtm_label: |
| 2146 | return 'lgtm' |
| 2147 | |
| 2148 | if not data.get('reviewers', {}).get('REVIEWER', []): |
| 2149 | return 'unsent' |
| 2150 | |
| 2151 | messages = data.get('messages', []) |
| 2152 | if messages: |
| 2153 | owner = data['owner'].get('_account_id') |
| 2154 | last_message_author = messages[-1].get('author', {}).get('_account_id') |
| 2155 | if owner != last_message_author: |
| 2156 | # Some reply from non-owner. |
| 2157 | return 'reply' |
| 2158 | |
| 2159 | return 'waiting' |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2160 | |
| 2161 | def GetMostRecentPatchset(self): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2162 | data = self._GetChangeDetail(['CURRENT_REVISION']) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2163 | return data['revisions'][data['current_revision']]['_number'] |
| 2164 | |
| 2165 | def FetchDescription(self): |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2166 | data = self._GetChangeDetail(['COMMIT_FOOTERS', 'CURRENT_REVISION']) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2167 | return data['revisions'][data['current_revision']]['commit_with_footers'] |
| 2168 | |
| 2169 | def UpdateDescriptionRemote(self, description): |
| 2170 | # TODO(tandrii) |
| 2171 | raise NotImplementedError() |
| 2172 | |
| 2173 | def CloseIssue(self): |
| 2174 | gerrit_util.AbandonChange(self._GetGerritHost(), self.GetIssue(), msg='') |
| 2175 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2176 | def SubmitIssue(self, wait_for_merge=True): |
| 2177 | gerrit_util.SubmitChange(self._GetGerritHost(), self.GetIssue(), |
| 2178 | wait_for_merge=wait_for_merge) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2179 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2180 | def _GetChangeDetail(self, options=None, issue=None): |
| 2181 | options = options or [] |
| 2182 | issue = issue or self.GetIssue() |
| 2183 | assert issue, 'issue required to query Gerrit' |
tandrii@chromium.org | 11a899e | 2016-04-13 12:45:44 +0000 | [diff] [blame] | 2184 | return gerrit_util.GetChangeDetail(self._GetGerritHost(), str(issue), |
| 2185 | options) |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2186 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2187 | def CMDLand(self, force, bypass_hooks, verbose): |
| 2188 | if git_common.is_dirty_git_tree('land'): |
| 2189 | return 1 |
| 2190 | differs = True |
| 2191 | last_upload = RunGit(['config', |
| 2192 | 'branch.%s.gerritsquashhash' % self.GetBranch()], |
| 2193 | error_ok=True).strip() |
| 2194 | # Note: git diff outputs nothing if there is no diff. |
| 2195 | if not last_upload or RunGit(['diff', last_upload]).strip(): |
| 2196 | print('WARNING: some changes from local branch haven\'t been uploaded') |
| 2197 | else: |
| 2198 | detail = self._GetChangeDetail(['CURRENT_REVISION']) |
| 2199 | if detail['current_revision'] == last_upload: |
| 2200 | differs = False |
| 2201 | else: |
| 2202 | print('WARNING: local branch contents differ from latest uploaded ' |
| 2203 | 'patchset') |
| 2204 | if differs: |
| 2205 | if not force: |
| 2206 | ask_for_data( |
| 2207 | 'Do you want to submit latest Gerrit patchset and bypass hooks?') |
| 2208 | print('WARNING: bypassing hooks and submitting latest uploaded patchset') |
| 2209 | elif not bypass_hooks: |
| 2210 | hook_results = self.RunHook( |
| 2211 | committing=True, |
| 2212 | may_prompt=not force, |
| 2213 | verbose=verbose, |
| 2214 | change=self.GetChange(self.GetCommonAncestorWithUpstream(), None)) |
| 2215 | if not hook_results.should_continue(): |
| 2216 | return 1 |
| 2217 | |
| 2218 | self.SubmitIssue(wait_for_merge=True) |
| 2219 | print('Issue %s has been submitted.' % self.GetIssueURL()) |
| 2220 | return 0 |
| 2221 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 2222 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit, |
| 2223 | directory): |
| 2224 | assert not reject |
| 2225 | assert not nocommit |
| 2226 | assert not directory |
| 2227 | assert parsed_issue_arg.valid |
| 2228 | |
| 2229 | self._changelist.issue = parsed_issue_arg.issue |
| 2230 | |
| 2231 | if parsed_issue_arg.hostname: |
| 2232 | self._gerrit_host = parsed_issue_arg.hostname |
| 2233 | self._gerrit_server = 'https://%s' % self._gerrit_host |
| 2234 | |
| 2235 | detail = self._GetChangeDetail(['ALL_REVISIONS']) |
| 2236 | |
| 2237 | if not parsed_issue_arg.patchset: |
| 2238 | # Use current revision by default. |
| 2239 | revision_info = detail['revisions'][detail['current_revision']] |
| 2240 | patchset = int(revision_info['_number']) |
| 2241 | else: |
| 2242 | patchset = parsed_issue_arg.patchset |
| 2243 | for revision_info in detail['revisions'].itervalues(): |
| 2244 | if int(revision_info['_number']) == parsed_issue_arg.patchset: |
| 2245 | break |
| 2246 | else: |
| 2247 | DieWithError('Couldn\'t find patchset %i in issue %i' % |
| 2248 | (parsed_issue_arg.patchset, self.GetIssue())) |
| 2249 | |
| 2250 | fetch_info = revision_info['fetch']['http'] |
| 2251 | RunGit(['fetch', fetch_info['url'], fetch_info['ref']]) |
| 2252 | RunGit(['cherry-pick', 'FETCH_HEAD']) |
| 2253 | self.SetIssue(self.GetIssue()) |
| 2254 | self.SetPatchset(patchset) |
| 2255 | print('Committed patch for issue %i pathset %i locally' % |
| 2256 | (self.GetIssue(), self.GetPatchset())) |
| 2257 | return 0 |
| 2258 | |
| 2259 | @staticmethod |
| 2260 | def ParseIssueURL(parsed_url): |
| 2261 | if not parsed_url.scheme or not parsed_url.scheme.startswith('http'): |
| 2262 | return None |
| 2263 | # Gerrit's new UI is https://domain/c/<issue_number>[/[patchset]] |
| 2264 | # But current GWT UI is https://domain/#/c/<issue_number>[/[patchset]] |
| 2265 | # Short urls like https://domain/<issue_number> can be used, but don't allow |
| 2266 | # specifying the patchset (you'd 404), but we allow that here. |
| 2267 | if parsed_url.path == '/': |
| 2268 | part = parsed_url.fragment |
| 2269 | else: |
| 2270 | part = parsed_url.path |
| 2271 | match = re.match('(/c)?/(\d+)(/(\d+)?/?)?$', part) |
| 2272 | if match: |
| 2273 | return _ParsedIssueNumberArgument( |
| 2274 | issue=int(match.group(2)), |
| 2275 | patchset=int(match.group(4)) if match.group(4) else None, |
| 2276 | hostname=parsed_url.netloc) |
| 2277 | return None |
| 2278 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2279 | def CMDUploadChange(self, options, args, change): |
| 2280 | """Upload the current branch to Gerrit.""" |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2281 | if options.squash and options.no_squash: |
| 2282 | DieWithError('Can only use one of --squash or --no-squash') |
| 2283 | options.squash = ((settings.GetSquashGerritUploads() or options.squash) and |
| 2284 | not options.no_squash) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2285 | # We assume the remote called "origin" is the one we want. |
| 2286 | # It is probably not worthwhile to support different workflows. |
| 2287 | gerrit_remote = 'origin' |
| 2288 | |
| 2289 | remote, remote_branch = self.GetRemoteBranch() |
| 2290 | branch = GetTargetRef(remote, remote_branch, options.target_branch, |
| 2291 | pending_prefix='') |
| 2292 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2293 | if options.squash: |
| 2294 | if not self.GetIssue(): |
| 2295 | # TODO(tandrii): deperecate this after 2016Q2. Backwards compatibility |
| 2296 | # with shadow branch, which used to contain change-id for a given |
| 2297 | # branch, using which we can fetch actual issue number and set it as the |
| 2298 | # property of the branch, which is the new way. |
| 2299 | message = RunGitSilent([ |
| 2300 | 'show', '--format=%B', '-s', |
| 2301 | 'refs/heads/git_cl_uploads/%s' % self.GetBranch()]) |
| 2302 | if message: |
| 2303 | change_ids = git_footers.get_footer_change_id(message.strip()) |
| 2304 | if change_ids and len(change_ids) == 1: |
| 2305 | details = self._GetChangeDetail(issue=change_ids[0]) |
| 2306 | if details: |
| 2307 | print('WARNING: found old upload in branch git_cl_uploads/%s ' |
| 2308 | 'corresponding to issue %s' % |
| 2309 | (self.GetBranch(), details['_number'])) |
| 2310 | self.SetIssue(details['_number']) |
| 2311 | if not self.GetIssue(): |
| 2312 | DieWithError( |
| 2313 | '\n' # For readability of the blob below. |
| 2314 | 'Found old upload in branch git_cl_uploads/%s, ' |
| 2315 | 'but failed to find corresponding Gerrit issue.\n' |
| 2316 | 'If you know the issue number, set it manually first:\n' |
| 2317 | ' git cl issue 123456\n' |
| 2318 | 'If you intended to upload this CL as new issue, ' |
| 2319 | 'just delete or rename the old upload branch:\n' |
| 2320 | ' git rename-branch git_cl_uploads/%s old_upload-%s\n' |
| 2321 | 'After that, please run git cl upload again.' % |
| 2322 | tuple([self.GetBranch()] * 3)) |
| 2323 | # End of backwards compatability. |
| 2324 | |
| 2325 | if self.GetIssue(): |
| 2326 | # Try to get the message from a previous upload. |
| 2327 | message = self.GetDescription() |
| 2328 | if not message: |
| 2329 | DieWithError( |
| 2330 | 'failed to fetch description from current Gerrit issue %d\n' |
| 2331 | '%s' % (self.GetIssue(), self.GetIssueURL())) |
| 2332 | change_id = self._GetChangeDetail()['change_id'] |
| 2333 | while True: |
| 2334 | footer_change_ids = git_footers.get_footer_change_id(message) |
| 2335 | if footer_change_ids == [change_id]: |
| 2336 | break |
| 2337 | if not footer_change_ids: |
| 2338 | message = git_footers.add_footer_change_id(message, change_id) |
| 2339 | print('WARNING: appended missing Change-Id to issue description') |
| 2340 | continue |
| 2341 | # There is already a valid footer but with different or several ids. |
| 2342 | # Doing this automatically is non-trivial as we don't want to lose |
| 2343 | # existing other footers, yet we want to append just 1 desired |
| 2344 | # Change-Id. Thus, just create a new footer, but let user verify the |
| 2345 | # new description. |
| 2346 | message = '%s\n\nChange-Id: %s' % (message, change_id) |
| 2347 | print( |
| 2348 | 'WARNING: issue %s has Change-Id footer(s):\n' |
| 2349 | ' %s\n' |
| 2350 | 'but issue has Change-Id %s, according to Gerrit.\n' |
| 2351 | 'Please, check the proposed correction to the description, ' |
| 2352 | 'and edit it if necessary but keep the "Change-Id: %s" footer\n' |
| 2353 | % (self.GetIssue(), '\n '.join(footer_change_ids), change_id, |
| 2354 | change_id)) |
| 2355 | ask_for_data('Press enter to edit now, Ctrl+C to abort') |
| 2356 | if not options.force: |
| 2357 | change_desc = ChangeDescription(message) |
| 2358 | change_desc.prompt() |
| 2359 | message = change_desc.description |
| 2360 | if not message: |
| 2361 | DieWithError("Description is empty. Aborting...") |
| 2362 | # Continue the while loop. |
| 2363 | # Sanity check of this code - we should end up with proper message |
| 2364 | # footer. |
| 2365 | assert [change_id] == git_footers.get_footer_change_id(message) |
| 2366 | change_desc = ChangeDescription(message) |
| 2367 | else: |
| 2368 | change_desc = ChangeDescription( |
| 2369 | options.message or CreateDescriptionFromLog(args)) |
| 2370 | if not options.force: |
| 2371 | change_desc.prompt() |
| 2372 | if not change_desc.description: |
| 2373 | DieWithError("Description is empty. Aborting...") |
| 2374 | message = change_desc.description |
| 2375 | change_ids = git_footers.get_footer_change_id(message) |
| 2376 | if len(change_ids) > 1: |
| 2377 | DieWithError('too many Change-Id footers, at most 1 allowed.') |
| 2378 | if not change_ids: |
| 2379 | # Generate the Change-Id automatically. |
| 2380 | message = git_footers.add_footer_change_id( |
| 2381 | message, GenerateGerritChangeId(message)) |
| 2382 | change_desc.set_description(message) |
| 2383 | change_ids = git_footers.get_footer_change_id(message) |
| 2384 | assert len(change_ids) == 1 |
| 2385 | change_id = change_ids[0] |
| 2386 | |
| 2387 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
| 2388 | if remote is '.': |
| 2389 | # If our upstream branch is local, we base our squashed commit on its |
| 2390 | # squashed version. |
| 2391 | upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch) |
| 2392 | # Check the squashed hash of the parent. |
| 2393 | parent = RunGit(['config', |
| 2394 | 'branch.%s.gerritsquashhash' % upstream_branch_name], |
| 2395 | error_ok=True).strip() |
| 2396 | # Verify that the upstream branch has been uploaded too, otherwise |
| 2397 | # Gerrit will create additional CLs when uploading. |
| 2398 | if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) != |
| 2399 | RunGitSilent(['rev-parse', parent + ':'])): |
| 2400 | # TODO(tandrii): remove "old depot_tools" part on April 12, 2016. |
| 2401 | DieWithError( |
| 2402 | 'Upload upstream branch %s first.\n' |
| 2403 | 'Note: maybe you\'ve uploaded it with --no-squash or with an old ' |
| 2404 | 'version of depot_tools. If so, then re-upload it with:\n' |
| 2405 | ' git cl upload --squash\n' % upstream_branch_name) |
| 2406 | else: |
| 2407 | parent = self.GetCommonAncestorWithUpstream() |
| 2408 | |
| 2409 | tree = RunGit(['rev-parse', 'HEAD:']).strip() |
| 2410 | ref_to_push = RunGit(['commit-tree', tree, '-p', parent, |
| 2411 | '-m', message]).strip() |
| 2412 | else: |
| 2413 | change_desc = ChangeDescription( |
| 2414 | options.message or CreateDescriptionFromLog(args)) |
| 2415 | if not change_desc.description: |
| 2416 | DieWithError("Description is empty. Aborting...") |
| 2417 | |
| 2418 | if not git_footers.get_footer_change_id(change_desc.description): |
| 2419 | DownloadGerritHook(False) |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 2420 | change_desc.set_description(self._AddChangeIdToCommitMessage(options, |
| 2421 | args)) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2422 | ref_to_push = 'HEAD' |
| 2423 | parent = '%s/%s' % (gerrit_remote, branch) |
| 2424 | change_id = git_footers.get_footer_change_id(change_desc.description)[0] |
| 2425 | |
| 2426 | assert change_desc |
| 2427 | commits = RunGitSilent(['rev-list', '%s..%s' % (parent, |
| 2428 | ref_to_push)]).splitlines() |
| 2429 | if len(commits) > 1: |
| 2430 | print('WARNING: This will upload %d commits. Run the following command ' |
| 2431 | 'to see which commits will be uploaded: ' % len(commits)) |
| 2432 | print('git log %s..%s' % (parent, ref_to_push)) |
| 2433 | print('You can also use `git squash-branch` to squash these into a ' |
| 2434 | 'single commit.') |
| 2435 | ask_for_data('About to upload; enter to confirm.') |
| 2436 | |
| 2437 | if options.reviewers or options.tbr_owners: |
| 2438 | change_desc.update_reviewers(options.reviewers, options.tbr_owners, |
| 2439 | change) |
| 2440 | |
tandrii@chromium.org | bf766ba | 2016-04-13 12:51:23 +0000 | [diff] [blame] | 2441 | # Extra options that can be specified at push time. Doc: |
| 2442 | # https://gerrit-review.googlesource.com/Documentation/user-upload.html |
| 2443 | refspec_opts = [] |
| 2444 | if options.title: |
| 2445 | # Per doc, spaces must be converted to underscores, and Gerrit will do the |
| 2446 | # reverse on its side. |
| 2447 | if '_' in options.title: |
| 2448 | print('WARNING: underscores in title will be converted to spaces.') |
| 2449 | refspec_opts.append('m=' + options.title.replace(' ', '_')) |
| 2450 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2451 | cc = self.GetCCList().split(',') |
| 2452 | if options.cc: |
| 2453 | cc.extend(options.cc) |
| 2454 | cc = filter(None, cc) |
| 2455 | if cc: |
tandrii@chromium.org | 0b2d707 | 2016-04-18 16:19:03 +0000 | [diff] [blame] | 2456 | # refspec_opts.extend('cc=' + email.strip() for email in cc) |
| 2457 | # TODO(tandrii): enable this back. http://crbug.com/604377 |
| 2458 | print('WARNING: Gerrit doesn\'t yet support cc-ing arbitrary emails.\n' |
| 2459 | ' Ignoring cc-ed emails. See http://crbug.com/604377.') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2460 | |
tandrii@chromium.org | 8acd833 | 2016-04-13 12:56:03 +0000 | [diff] [blame] | 2461 | if change_desc.get_reviewers(): |
| 2462 | refspec_opts.extend('r=' + email.strip() |
| 2463 | for email in change_desc.get_reviewers()) |
| 2464 | |
tandrii@chromium.org | bf766ba | 2016-04-13 12:51:23 +0000 | [diff] [blame] | 2465 | |
| 2466 | refspec_suffix = '' |
| 2467 | if refspec_opts: |
| 2468 | refspec_suffix = '%' + ','.join(refspec_opts) |
| 2469 | assert ' ' not in refspec_suffix, ( |
| 2470 | 'spaces not allowed in refspec: "%s"' % refspec_suffix) |
tandrii@chromium.org | bf766ba | 2016-04-13 12:51:23 +0000 | [diff] [blame] | 2471 | refspec = '%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix) |
tandrii@chromium.org | bf766ba | 2016-04-13 12:51:23 +0000 | [diff] [blame] | 2472 | |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2473 | push_stdout = gclient_utils.CheckCallAndFilter( |
tandrii@chromium.org | 8acd833 | 2016-04-13 12:56:03 +0000 | [diff] [blame] | 2474 | ['git', 'push', gerrit_remote, refspec], |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2475 | print_stdout=True, |
| 2476 | # Flush after every line: useful for seeing progress when running as |
| 2477 | # recipe. |
| 2478 | filter_fn=lambda _: sys.stdout.flush()) |
| 2479 | |
| 2480 | if options.squash: |
| 2481 | regex = re.compile(r'remote:\s+https?://[\w\-\.\/]*/(\d+)\s.*') |
| 2482 | change_numbers = [m.group(1) |
| 2483 | for m in map(regex.match, push_stdout.splitlines()) |
| 2484 | if m] |
| 2485 | if len(change_numbers) != 1: |
| 2486 | DieWithError( |
| 2487 | ('Created|Updated %d issues on Gerrit, but only 1 expected.\n' |
| 2488 | 'Change-Id: %s') % (len(change_numbers), change_id)) |
| 2489 | self.SetIssue(change_numbers[0]) |
| 2490 | RunGit(['config', 'branch.%s.gerritsquashhash' % self.GetBranch(), |
| 2491 | ref_to_push]) |
| 2492 | return 0 |
| 2493 | |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 2494 | def _AddChangeIdToCommitMessage(self, options, args): |
| 2495 | """Re-commits using the current message, assumes the commit hook is in |
| 2496 | place. |
| 2497 | """ |
| 2498 | log_desc = options.message or CreateDescriptionFromLog(args) |
| 2499 | git_command = ['commit', '--amend', '-m', log_desc] |
| 2500 | RunGit(git_command) |
| 2501 | new_log_desc = CreateDescriptionFromLog(args) |
| 2502 | if git_footers.get_footer_change_id(new_log_desc): |
| 2503 | print 'git-cl: Added Change-Id to commit message.' |
| 2504 | return new_log_desc |
| 2505 | else: |
| 2506 | print >> sys.stderr, 'ERROR: Gerrit commit-msg hook not available.' |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2507 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2508 | def SetCQState(self, new_state): |
| 2509 | """Sets the Commit-Queue label assuming canonical CQ config for Gerrit.""" |
| 2510 | # TODO(tandrii): maybe allow configurability in codereview.settings or by |
| 2511 | # self-discovery of label config for this CL using REST API. |
| 2512 | vote_map = { |
| 2513 | _CQState.NONE: 0, |
| 2514 | _CQState.DRY_RUN: 1, |
| 2515 | _CQState.COMMIT : 2, |
| 2516 | } |
| 2517 | gerrit_util.SetReview(self._GetGerritHost(), self.GetIssue(), |
| 2518 | labels={'Commit-Queue': vote_map[new_state]}) |
| 2519 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 2520 | |
| 2521 | _CODEREVIEW_IMPLEMENTATIONS = { |
| 2522 | 'rietveld': _RietveldChangelistImpl, |
| 2523 | 'gerrit': _GerritChangelistImpl, |
| 2524 | } |
| 2525 | |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2526 | |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 2527 | def _add_codereview_select_options(parser): |
| 2528 | """Appends --gerrit and --rietveld options to force specific codereview.""" |
| 2529 | parser.codereview_group = optparse.OptionGroup( |
| 2530 | parser, 'EXPERIMENTAL! Codereview override options') |
| 2531 | parser.add_option_group(parser.codereview_group) |
| 2532 | parser.codereview_group.add_option( |
| 2533 | '--gerrit', action='store_true', |
| 2534 | help='Force the use of Gerrit for codereview') |
| 2535 | parser.codereview_group.add_option( |
| 2536 | '--rietveld', action='store_true', |
| 2537 | help='Force the use of Rietveld for codereview') |
| 2538 | |
| 2539 | |
| 2540 | def _process_codereview_select_options(parser, options): |
| 2541 | if options.gerrit and options.rietveld: |
| 2542 | parser.error('Options --gerrit and --rietveld are mutually exclusive') |
| 2543 | options.forced_codereview = None |
| 2544 | if options.gerrit: |
| 2545 | options.forced_codereview = 'gerrit' |
| 2546 | elif options.rietveld: |
| 2547 | options.forced_codereview = 'rietveld' |
| 2548 | |
| 2549 | |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 2550 | class ChangeDescription(object): |
| 2551 | """Contains a parsed form of the change description.""" |
maruel@chromium.org | c6f60e8 | 2013-04-19 17:01:57 +0000 | [diff] [blame] | 2552 | R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$' |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2553 | BUG_LINE = r'^[ \t]*(BUG)[ \t]*=[ \t]*(.*?)[ \t]*$' |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 2554 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2555 | def __init__(self, description): |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2556 | self._description_lines = (description or '').strip().splitlines() |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2557 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2558 | @property # www.logilab.org/ticket/89786 |
| 2559 | def description(self): # pylint: disable=E0202 |
| 2560 | return '\n'.join(self._description_lines) |
| 2561 | |
| 2562 | def set_description(self, desc): |
| 2563 | if isinstance(desc, basestring): |
| 2564 | lines = desc.splitlines() |
| 2565 | else: |
| 2566 | lines = [line.rstrip() for line in desc] |
| 2567 | while lines and not lines[0]: |
| 2568 | lines.pop(0) |
| 2569 | while lines and not lines[-1]: |
| 2570 | lines.pop(-1) |
| 2571 | self._description_lines = lines |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2572 | |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 2573 | def update_reviewers(self, reviewers, add_owners_tbr=False, change=None): |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2574 | """Rewrites the R=/TBR= line(s) as a single line each.""" |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2575 | assert isinstance(reviewers, list), reviewers |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 2576 | if not reviewers and not add_owners_tbr: |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2577 | return |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2578 | reviewers = reviewers[:] |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2579 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2580 | # Get the set of R= and TBR= lines and remove them from the desciption. |
| 2581 | regexp = re.compile(self.R_LINE) |
| 2582 | matches = [regexp.match(line) for line in self._description_lines] |
| 2583 | new_desc = [l for i, l in enumerate(self._description_lines) |
| 2584 | if not matches[i]] |
| 2585 | self.set_description(new_desc) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2586 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2587 | # Construct new unified R= and TBR= lines. |
| 2588 | r_names = [] |
| 2589 | tbr_names = [] |
| 2590 | for match in matches: |
| 2591 | if not match: |
| 2592 | continue |
| 2593 | people = cleanup_list([match.group(2).strip()]) |
| 2594 | if match.group(1) == 'TBR': |
| 2595 | tbr_names.extend(people) |
| 2596 | else: |
| 2597 | r_names.extend(people) |
| 2598 | for name in r_names: |
| 2599 | if name not in reviewers: |
| 2600 | reviewers.append(name) |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 2601 | if add_owners_tbr: |
| 2602 | owners_db = owners.Database(change.RepositoryRoot(), |
| 2603 | fopen=file, os_path=os.path, glob=glob.glob) |
| 2604 | all_reviewers = set(tbr_names + reviewers) |
| 2605 | missing_files = owners_db.files_not_covered_by(change.LocalPaths(), |
| 2606 | all_reviewers) |
| 2607 | tbr_names.extend(owners_db.reviewers_for(missing_files, |
| 2608 | change.author_email)) |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2609 | new_r_line = 'R=' + ', '.join(reviewers) if reviewers else None |
| 2610 | new_tbr_line = 'TBR=' + ', '.join(tbr_names) if tbr_names else None |
| 2611 | |
| 2612 | # Put the new lines in the description where the old first R= line was. |
| 2613 | line_loc = next((i for i, match in enumerate(matches) if match), -1) |
| 2614 | if 0 <= line_loc < len(self._description_lines): |
| 2615 | if new_tbr_line: |
| 2616 | self._description_lines.insert(line_loc, new_tbr_line) |
| 2617 | if new_r_line: |
| 2618 | self._description_lines.insert(line_loc, new_r_line) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2619 | else: |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2620 | if new_r_line: |
| 2621 | self.append_footer(new_r_line) |
| 2622 | if new_tbr_line: |
| 2623 | self.append_footer(new_tbr_line) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2624 | |
| 2625 | def prompt(self): |
| 2626 | """Asks the user to update the description.""" |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2627 | self.set_description([ |
| 2628 | '# Enter a description of the change.', |
| 2629 | '# This will be displayed on the codereview site.', |
| 2630 | '# 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] | 2631 | '#--------------------This line is 72 characters long' |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2632 | '--------------------', |
| 2633 | ] + self._description_lines) |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2634 | |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2635 | regexp = re.compile(self.BUG_LINE) |
| 2636 | if not any((regexp.match(line) for line in self._description_lines)): |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 2637 | self.append_footer('BUG=%s' % settings.GetBugPrefix()) |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2638 | content = gclient_utils.RunEditor(self.description, True, |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 2639 | git_editor=settings.GetGitEditor()) |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 2640 | if not content: |
| 2641 | DieWithError('Running editor failed') |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2642 | lines = content.splitlines() |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2643 | |
| 2644 | # Strip off comments. |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2645 | clean_lines = [line.rstrip() for line in lines if not line.startswith('#')] |
| 2646 | if not clean_lines: |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 2647 | DieWithError('No CL description, aborting') |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2648 | self.set_description(clean_lines) |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 2649 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2650 | def append_footer(self, line): |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2651 | if self._description_lines: |
| 2652 | # Add an empty line if either the last line or the new line isn't a tag. |
| 2653 | last_line = self._description_lines[-1] |
| 2654 | if (not presubmit_support.Change.TAG_LINE_RE.match(last_line) or |
| 2655 | not presubmit_support.Change.TAG_LINE_RE.match(line)): |
| 2656 | self._description_lines.append('') |
| 2657 | self._description_lines.append(line) |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 2658 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2659 | def get_reviewers(self): |
| 2660 | """Retrieves the list of reviewers.""" |
agable@chromium.org | 42c2079 | 2013-09-12 17:34:49 +0000 | [diff] [blame] | 2661 | matches = [re.match(self.R_LINE, line) for line in self._description_lines] |
| 2662 | reviewers = [match.group(2).strip() for match in matches if match] |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 2663 | return cleanup_list(reviewers) |
dpranke@chromium.org | 20254fc | 2011-03-22 18:28:59 +0000 | [diff] [blame] | 2664 | |
| 2665 | |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 2666 | def get_approving_reviewers(props): |
| 2667 | """Retrieves the reviewers that approved a CL from the issue properties with |
| 2668 | messages. |
| 2669 | |
| 2670 | Note that the list may contain reviewers that are not committer, thus are not |
| 2671 | considered by the CQ. |
| 2672 | """ |
| 2673 | return sorted( |
| 2674 | set( |
| 2675 | message['sender'] |
| 2676 | for message in props['messages'] |
| 2677 | if message['approval'] and message['sender'] in props['reviewers'] |
| 2678 | ) |
| 2679 | ) |
| 2680 | |
| 2681 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2682 | def FindCodereviewSettingsFile(filename='codereview.settings'): |
| 2683 | """Finds the given file starting in the cwd and going up. |
| 2684 | |
| 2685 | Only looks up to the top of the repository unless an |
| 2686 | 'inherit-review-settings-ok' file exists in the root of the repository. |
| 2687 | """ |
| 2688 | inherit_ok_file = 'inherit-review-settings-ok' |
| 2689 | cwd = os.getcwd() |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 2690 | root = settings.GetRoot() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2691 | if os.path.isfile(os.path.join(root, inherit_ok_file)): |
| 2692 | root = '/' |
| 2693 | while True: |
| 2694 | if filename in os.listdir(cwd): |
| 2695 | if os.path.isfile(os.path.join(cwd, filename)): |
| 2696 | return open(os.path.join(cwd, filename)) |
| 2697 | if cwd == root: |
| 2698 | break |
| 2699 | cwd = os.path.dirname(cwd) |
| 2700 | |
| 2701 | |
| 2702 | def LoadCodereviewSettingsFromFile(fileobj): |
| 2703 | """Parse a codereview.settings file and updates hooks.""" |
maruel@chromium.org | 99ac1c5 | 2012-01-16 14:52:12 +0000 | [diff] [blame] | 2704 | keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2705 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2706 | def SetProperty(name, setting, unset_error_ok=False): |
| 2707 | fullname = 'rietveld.' + name |
| 2708 | if setting in keyvals: |
| 2709 | RunGit(['config', fullname, keyvals[setting]]) |
| 2710 | else: |
| 2711 | RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok) |
| 2712 | |
| 2713 | SetProperty('server', 'CODE_REVIEW_SERVER') |
| 2714 | # Only server setting is required. Other settings can be absent. |
| 2715 | # In that case, we ignore errors raised during option deletion attempt. |
| 2716 | SetProperty('cc', 'CC_LIST', unset_error_ok=True) |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 2717 | SetProperty('private', 'PRIVATE', unset_error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2718 | SetProperty('tree-status-url', 'STATUS', unset_error_ok=True) |
| 2719 | SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True) |
rmistry@google.com | 9075258 | 2014-01-14 21:04:50 +0000 | [diff] [blame] | 2720 | SetProperty('bug-prefix', 'BUG_PREFIX', unset_error_ok=True) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 2721 | SetProperty('cpplint-regex', 'LINT_REGEX', unset_error_ok=True) |
kjellander@chromium.org | 6abc652 | 2014-12-02 07:34:49 +0000 | [diff] [blame] | 2722 | SetProperty('force-https-commit-url', 'FORCE_HTTPS_COMMIT_URL', |
| 2723 | unset_error_ok=True) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 2724 | SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX', unset_error_ok=True) |
sheyang@chromium.org | 152cf83 | 2014-06-11 21:37:49 +0000 | [diff] [blame] | 2725 | SetProperty('project', 'PROJECT', unset_error_ok=True) |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 2726 | SetProperty('pending-ref-prefix', 'PENDING_REF_PREFIX', unset_error_ok=True) |
rmistry@google.com | 5626a92 | 2015-02-26 14:03:30 +0000 | [diff] [blame] | 2727 | SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK', |
| 2728 | unset_error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2729 | |
ukai@chromium.org | 7044efc | 2013-11-28 01:51:21 +0000 | [diff] [blame] | 2730 | if 'GERRIT_HOST' in keyvals: |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 2731 | RunGit(['config', 'gerrit.host', keyvals['GERRIT_HOST']]) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 2732 | |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 2733 | if 'GERRIT_SQUASH_UPLOADS' in keyvals: |
| 2734 | RunGit(['config', 'gerrit.squash-uploads', |
| 2735 | keyvals['GERRIT_SQUASH_UPLOADS']]) |
| 2736 | |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 2737 | if 'GERRIT_SKIP_ENSURE_AUTHENTICATED' in keyvals: |
shinyak@chromium.org | 00dbccd | 2016-04-15 07:24:43 +0000 | [diff] [blame] | 2738 | RunGit(['config', 'gerrit.skip-ensure-authenticated', |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 2739 | keyvals['GERRIT_SKIP_ENSURE_AUTHENTICATED']]) |
| 2740 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2741 | if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals: |
| 2742 | #should be of the form |
| 2743 | #PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof |
| 2744 | #ORIGIN_URL_CONFIG: http://src.chromium.org/git |
| 2745 | RunGit(['config', keyvals['PUSH_URL_CONFIG'], |
| 2746 | keyvals['ORIGIN_URL_CONFIG']]) |
| 2747 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2748 | |
joshua.lock@intel.com | 426f69b | 2012-08-02 23:41:49 +0000 | [diff] [blame] | 2749 | def urlretrieve(source, destination): |
| 2750 | """urllib is broken for SSL connections via a proxy therefore we |
| 2751 | can't use urllib.urlretrieve().""" |
| 2752 | with open(destination, 'w') as f: |
| 2753 | f.write(urllib2.urlopen(source).read()) |
| 2754 | |
| 2755 | |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 2756 | def hasSheBang(fname): |
| 2757 | """Checks fname is a #! script.""" |
| 2758 | with open(fname) as f: |
| 2759 | return f.read(2).startswith('#!') |
| 2760 | |
| 2761 | |
bpastene@chromium.org | 917f0ff | 2016-04-05 00:45:30 +0000 | [diff] [blame] | 2762 | # TODO(bpastene) Remove once a cleaner fix to crbug.com/600473 presents itself. |
| 2763 | def DownloadHooks(*args, **kwargs): |
| 2764 | pass |
| 2765 | |
| 2766 | |
tandrii@chromium.org | 18630d6 | 2016-03-04 12:06:02 +0000 | [diff] [blame] | 2767 | def DownloadGerritHook(force): |
| 2768 | """Download and install Gerrit commit-msg hook. |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 2769 | |
| 2770 | Args: |
| 2771 | force: True to update hooks. False to install hooks if not present. |
| 2772 | """ |
| 2773 | if not settings.GetIsGerrit(): |
| 2774 | return |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 2775 | src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg' |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 2776 | dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg') |
| 2777 | if not os.access(dst, os.X_OK): |
| 2778 | if os.path.exists(dst): |
| 2779 | if not force: |
| 2780 | return |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 2781 | try: |
tandrii@chromium.org | 18630d6 | 2016-03-04 12:06:02 +0000 | [diff] [blame] | 2782 | print( |
| 2783 | 'WARNING: installing Gerrit commit-msg hook.\n' |
| 2784 | ' This behavior of git cl will soon be disabled.\n' |
| 2785 | ' See bug http://crbug.com/579176.') |
joshua.lock@intel.com | 426f69b | 2012-08-02 23:41:49 +0000 | [diff] [blame] | 2786 | urlretrieve(src, dst) |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 2787 | if not hasSheBang(dst): |
| 2788 | DieWithError('Not a script: %s\n' |
| 2789 | 'You need to download from\n%s\n' |
| 2790 | 'into .git/hooks/commit-msg and ' |
| 2791 | 'chmod +x .git/hooks/commit-msg' % (dst, src)) |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 2792 | os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) |
| 2793 | except Exception: |
| 2794 | if os.path.exists(dst): |
| 2795 | os.remove(dst) |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 2796 | DieWithError('\nFailed to download hooks.\n' |
| 2797 | 'You need to download from\n%s\n' |
| 2798 | 'into .git/hooks/commit-msg and ' |
| 2799 | 'chmod +x .git/hooks/commit-msg' % src) |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 2800 | |
| 2801 | |
tandrii@chromium.org | e7d3d16 | 2016-03-15 14:15:57 +0000 | [diff] [blame] | 2802 | |
| 2803 | def GetRietveldCodereviewSettingsInteractively(): |
| 2804 | """Prompt the user for settings.""" |
| 2805 | server = settings.GetDefaultServerUrl(error_ok=True) |
| 2806 | prompt = 'Rietveld server (host[:port])' |
| 2807 | prompt += ' [%s]' % (server or DEFAULT_SERVER) |
| 2808 | newserver = ask_for_data(prompt + ':') |
| 2809 | if not server and not newserver: |
| 2810 | newserver = DEFAULT_SERVER |
| 2811 | if newserver: |
| 2812 | newserver = gclient_utils.UpgradeToHttps(newserver) |
| 2813 | if newserver != server: |
| 2814 | RunGit(['config', 'rietveld.server', newserver]) |
| 2815 | |
| 2816 | def SetProperty(initial, caption, name, is_url): |
| 2817 | prompt = caption |
| 2818 | if initial: |
| 2819 | prompt += ' ("x" to clear) [%s]' % initial |
| 2820 | new_val = ask_for_data(prompt + ':') |
| 2821 | if new_val == 'x': |
| 2822 | RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True) |
| 2823 | elif new_val: |
| 2824 | if is_url: |
| 2825 | new_val = gclient_utils.UpgradeToHttps(new_val) |
| 2826 | if new_val != initial: |
| 2827 | RunGit(['config', 'rietveld.' + name, new_val]) |
| 2828 | |
| 2829 | SetProperty(settings.GetDefaultCCList(), 'CC list', 'cc', False) |
| 2830 | SetProperty(settings.GetDefaultPrivateFlag(), |
| 2831 | 'Private flag (rietveld only)', 'private', False) |
| 2832 | SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL', |
| 2833 | 'tree-status-url', False) |
| 2834 | SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url', True) |
| 2835 | SetProperty(settings.GetBugPrefix(), 'Bug Prefix', 'bug-prefix', False) |
| 2836 | SetProperty(settings.GetRunPostUploadHook(), 'Run Post Upload Hook', |
| 2837 | 'run-post-upload-hook', False) |
| 2838 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 2839 | @subcommand.usage('[repo root containing codereview.settings]') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2840 | def CMDconfig(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 2841 | """Edits configuration for this tree.""" |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2842 | |
tandrii@chromium.org | e7d3d16 | 2016-03-15 14:15:57 +0000 | [diff] [blame] | 2843 | print('WARNING: git cl config works for Rietveld only.\n' |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 2844 | 'For Gerrit, see http://crbug.com/603116.') |
| 2845 | # TODO(tandrii): add Gerrit support as part of http://crbug.com/603116. |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 2846 | parser.add_option('--activate-update', action='store_true', |
| 2847 | help='activate auto-updating [rietveld] section in ' |
| 2848 | '.git/config') |
| 2849 | parser.add_option('--deactivate-update', action='store_true', |
| 2850 | help='deactivate auto-updating [rietveld] section in ' |
| 2851 | '.git/config') |
| 2852 | options, args = parser.parse_args(args) |
| 2853 | |
| 2854 | if options.deactivate_update: |
| 2855 | RunGit(['config', 'rietveld.autoupdate', 'false']) |
| 2856 | return |
| 2857 | |
| 2858 | if options.activate_update: |
| 2859 | RunGit(['config', '--unset', 'rietveld.autoupdate']) |
| 2860 | return |
| 2861 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2862 | if len(args) == 0: |
tandrii@chromium.org | e7d3d16 | 2016-03-15 14:15:57 +0000 | [diff] [blame] | 2863 | GetRietveldCodereviewSettingsInteractively() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2864 | return 0 |
| 2865 | |
| 2866 | url = args[0] |
| 2867 | if not url.endswith('codereview.settings'): |
| 2868 | url = os.path.join(url, 'codereview.settings') |
| 2869 | |
| 2870 | # Load code review settings and download hooks (if available). |
| 2871 | LoadCodereviewSettingsFromFile(urllib2.urlopen(url)) |
| 2872 | return 0 |
| 2873 | |
| 2874 | |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 2875 | def CMDbaseurl(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 2876 | """Gets or sets base-url for this branch.""" |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 2877 | branchref = RunGit(['symbolic-ref', 'HEAD']).strip() |
| 2878 | branch = ShortBranchName(branchref) |
| 2879 | _, args = parser.parse_args(args) |
| 2880 | if not args: |
| 2881 | print("Current base-url:") |
| 2882 | return RunGit(['config', 'branch.%s.base-url' % branch], |
| 2883 | error_ok=False).strip() |
| 2884 | else: |
| 2885 | print("Setting base-url to %s" % args[0]) |
| 2886 | return RunGit(['config', 'branch.%s.base-url' % branch, args[0]], |
| 2887 | error_ok=False).strip() |
| 2888 | |
| 2889 | |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2890 | def color_for_status(status): |
| 2891 | """Maps a Changelist status to color, for CMDstatus and other tools.""" |
| 2892 | return { |
| 2893 | 'unsent': Fore.RED, |
| 2894 | 'waiting': Fore.BLUE, |
| 2895 | 'reply': Fore.YELLOW, |
| 2896 | 'lgtm': Fore.GREEN, |
| 2897 | 'commit': Fore.MAGENTA, |
| 2898 | 'closed': Fore.CYAN, |
| 2899 | 'error': Fore.WHITE, |
| 2900 | }.get(status, Fore.WHITE) |
| 2901 | |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 2902 | def fetch_cl_status(branch, auth_config=None): |
| 2903 | """Fetches information for an issue and returns (branch, issue, status).""" |
| 2904 | cl = Changelist(branchref=branch, auth_config=auth_config) |
| 2905 | url = cl.GetIssueURL() |
| 2906 | status = cl.GetStatus() |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 2907 | |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 2908 | if url and (not status or status == 'error'): |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 2909 | # The issue probably doesn't exist anymore. |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 2910 | url += ' (broken)' |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 2911 | |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 2912 | return (branch, url, status) |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 2913 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 2914 | def get_cl_statuses( |
| 2915 | branches, fine_grained, max_processes=None, auth_config=None): |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 2916 | """Returns a blocking iterable of (branch, issue, color) for given branches. |
| 2917 | |
| 2918 | If fine_grained is true, this will fetch CL statuses from the server. |
| 2919 | Otherwise, simply indicate if there's a matching url for the given branches. |
| 2920 | |
| 2921 | If max_processes is specified, it is used as the maximum number of processes |
| 2922 | to spawn to fetch CL status from the server. Otherwise 1 process per branch is |
| 2923 | spawned. |
| 2924 | """ |
| 2925 | # Silence upload.py otherwise it becomes unwieldly. |
| 2926 | upload.verbosity = 0 |
| 2927 | |
| 2928 | if fine_grained: |
| 2929 | # Process one branch synchronously to work through authentication, then |
| 2930 | # spawn processes to process all the other branches in parallel. |
| 2931 | if branches: |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 2932 | fetch = lambda branch: fetch_cl_status(branch, auth_config=auth_config) |
| 2933 | yield fetch(branches[0]) |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 2934 | |
| 2935 | branches_to_fetch = branches[1:] |
| 2936 | pool = ThreadPool( |
| 2937 | min(max_processes, len(branches_to_fetch)) |
| 2938 | if max_processes is not None |
| 2939 | else len(branches_to_fetch)) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 2940 | for x in pool.imap_unordered(fetch, branches_to_fetch): |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 2941 | yield x |
| 2942 | else: |
| 2943 | # Do not use GetApprovingReviewers(), since it requires an HTTP request. |
| 2944 | for b in branches: |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 2945 | cl = Changelist(branchref=b, auth_config=auth_config) |
| 2946 | url = cl.GetIssueURL() |
| 2947 | yield (b, url, 'waiting' if url else 'error') |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 2948 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 2949 | |
| 2950 | def upload_branch_deps(cl, args): |
| 2951 | """Uploads CLs of local branches that are dependents of the current branch. |
| 2952 | |
| 2953 | If the local branch dependency tree looks like: |
| 2954 | test1 -> test2.1 -> test3.1 |
| 2955 | -> test3.2 |
| 2956 | -> test2.2 -> test3.3 |
| 2957 | |
| 2958 | and you run "git cl upload --dependencies" from test1 then "git cl upload" is |
| 2959 | run on the dependent branches in this order: |
| 2960 | test2.1, test3.1, test3.2, test2.2, test3.3 |
| 2961 | |
| 2962 | Note: This function does not rebase your local dependent branches. Use it when |
| 2963 | you make a change to the parent branch that will not conflict with its |
| 2964 | dependent branches, and you would like their dependencies updated in |
| 2965 | Rietveld. |
| 2966 | """ |
| 2967 | if git_common.is_dirty_git_tree('upload-branch-deps'): |
| 2968 | return 1 |
| 2969 | |
| 2970 | root_branch = cl.GetBranch() |
| 2971 | if root_branch is None: |
| 2972 | DieWithError('Can\'t find dependent branches from detached HEAD state. ' |
| 2973 | 'Get on a branch!') |
| 2974 | if not cl.GetIssue() or not cl.GetPatchset(): |
| 2975 | DieWithError('Current branch does not have an uploaded CL. We cannot set ' |
| 2976 | 'patchset dependencies without an uploaded CL.') |
| 2977 | |
| 2978 | branches = RunGit(['for-each-ref', |
| 2979 | '--format=%(refname:short) %(upstream:short)', |
| 2980 | 'refs/heads']) |
| 2981 | if not branches: |
| 2982 | print('No local branches found.') |
| 2983 | return 0 |
| 2984 | |
| 2985 | # Create a dictionary of all local branches to the branches that are dependent |
| 2986 | # on it. |
| 2987 | tracked_to_dependents = collections.defaultdict(list) |
| 2988 | for b in branches.splitlines(): |
| 2989 | tokens = b.split() |
| 2990 | if len(tokens) == 2: |
| 2991 | branch_name, tracked = tokens |
| 2992 | tracked_to_dependents[tracked].append(branch_name) |
| 2993 | |
| 2994 | print |
| 2995 | print 'The dependent local branches of %s are:' % root_branch |
| 2996 | dependents = [] |
| 2997 | def traverse_dependents_preorder(branch, padding=''): |
| 2998 | dependents_to_process = tracked_to_dependents.get(branch, []) |
| 2999 | padding += ' ' |
| 3000 | for dependent in dependents_to_process: |
| 3001 | print '%s%s' % (padding, dependent) |
| 3002 | dependents.append(dependent) |
| 3003 | traverse_dependents_preorder(dependent, padding) |
| 3004 | traverse_dependents_preorder(root_branch) |
| 3005 | print |
| 3006 | |
| 3007 | if not dependents: |
| 3008 | print 'There are no dependent local branches for %s' % root_branch |
| 3009 | return 0 |
| 3010 | |
| 3011 | print ('This command will checkout all dependent branches and run ' |
| 3012 | '"git cl upload".') |
| 3013 | ask_for_data('[Press enter to continue or ctrl-C to quit]') |
| 3014 | |
andybons@chromium.org | 962f946 | 2016-02-03 20:00:42 +0000 | [diff] [blame] | 3015 | # Add a default patchset title to all upload calls in Rietveld. |
tandrii@chromium.org | 4c72b08 | 2016-03-31 22:26:35 +0000 | [diff] [blame] | 3016 | if not cl.IsGerrit(): |
andybons@chromium.org | 962f946 | 2016-02-03 20:00:42 +0000 | [diff] [blame] | 3017 | args.extend(['-t', 'Updated patchset dependency']) |
| 3018 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 3019 | # Record all dependents that failed to upload. |
| 3020 | failures = {} |
| 3021 | # Go through all dependents, checkout the branch and upload. |
| 3022 | try: |
| 3023 | for dependent_branch in dependents: |
| 3024 | print |
| 3025 | print '--------------------------------------' |
| 3026 | print 'Running "git cl upload" from %s:' % dependent_branch |
| 3027 | RunGit(['checkout', '-q', dependent_branch]) |
| 3028 | print |
| 3029 | try: |
| 3030 | if CMDupload(OptionParser(), args) != 0: |
| 3031 | print 'Upload failed for %s!' % dependent_branch |
| 3032 | failures[dependent_branch] = 1 |
| 3033 | except: # pylint: disable=W0702 |
| 3034 | failures[dependent_branch] = 1 |
| 3035 | print |
| 3036 | finally: |
| 3037 | # Swap back to the original root branch. |
| 3038 | RunGit(['checkout', '-q', root_branch]) |
| 3039 | |
| 3040 | print |
| 3041 | print 'Upload complete for dependent branches!' |
| 3042 | for dependent_branch in dependents: |
| 3043 | upload_status = 'failed' if failures.get(dependent_branch) else 'succeeded' |
| 3044 | print ' %s : %s' % (dependent_branch, upload_status) |
| 3045 | print |
| 3046 | |
| 3047 | return 0 |
| 3048 | |
| 3049 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3050 | def CMDstatus(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 3051 | """Show status of changelists. |
| 3052 | |
| 3053 | 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] | 3054 | - Red not sent for review or broken |
| 3055 | - Blue waiting for review |
| 3056 | - Yellow waiting for you to reply to review |
| 3057 | - Green LGTM'ed |
| 3058 | - Magenta in the commit queue |
| 3059 | - Cyan was committed, branch can be deleted |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 3060 | |
| 3061 | Also see 'git cl comments'. |
| 3062 | """ |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3063 | parser.add_option('--field', |
| 3064 | help='print only specific field (desc|id|patch|url)') |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 3065 | parser.add_option('-f', '--fast', action='store_true', |
| 3066 | help='Do not retrieve review status') |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 3067 | parser.add_option( |
| 3068 | '-j', '--maxjobs', action='store', type=int, |
| 3069 | 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] | 3070 | |
| 3071 | auth.add_auth_options(parser) |
| 3072 | options, args = parser.parse_args(args) |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 3073 | if args: |
| 3074 | parser.error('Unsupported args: %s' % args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3075 | auth_config = auth.extract_auth_config_from_options(options) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3076 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3077 | if options.field: |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3078 | cl = Changelist(auth_config=auth_config) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3079 | if options.field.startswith('desc'): |
| 3080 | print cl.GetDescription() |
| 3081 | elif options.field == 'id': |
| 3082 | issueid = cl.GetIssue() |
| 3083 | if issueid: |
| 3084 | print issueid |
| 3085 | elif options.field == 'patch': |
| 3086 | patchset = cl.GetPatchset() |
| 3087 | if patchset: |
| 3088 | print patchset |
| 3089 | elif options.field == 'url': |
| 3090 | url = cl.GetIssueURL() |
| 3091 | if url: |
| 3092 | print url |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 3093 | return 0 |
| 3094 | |
| 3095 | branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads']) |
| 3096 | if not branches: |
| 3097 | print('No local branch found.') |
| 3098 | return 0 |
| 3099 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3100 | changes = ( |
| 3101 | Changelist(branchref=b, auth_config=auth_config) |
| 3102 | for b in branches.splitlines()) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 3103 | # TODO(tandrii): refactor to use CLs list instead of branches list. |
jrobbins@chromium.org | a4c0305 | 2014-04-25 19:06:36 +0000 | [diff] [blame] | 3104 | branches = [c.GetBranch() for c in changes] |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 3105 | alignment = max(5, max(len(b) for b in branches)) |
| 3106 | print 'Branches associated with reviews:' |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 3107 | output = get_cl_statuses(branches, |
| 3108 | fine_grained=not options.fast, |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3109 | max_processes=options.maxjobs, |
| 3110 | auth_config=auth_config) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 3111 | |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 3112 | branch_statuses = {} |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 3113 | alignment = max(5, max(len(ShortBranchName(b)) for b in branches)) |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 3114 | for branch in sorted(branches): |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 3115 | while branch not in branch_statuses: |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 3116 | b, i, status = output.next() |
| 3117 | branch_statuses[b] = (i, status) |
| 3118 | issue_url, status = branch_statuses.pop(branch) |
| 3119 | color = color_for_status(status) |
maruel@chromium.org | 885f651 | 2013-07-27 02:17:26 +0000 | [diff] [blame] | 3120 | reset = Fore.RESET |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 3121 | if not setup_color.IS_TTY: |
maruel@chromium.org | 885f651 | 2013-07-27 02:17:26 +0000 | [diff] [blame] | 3122 | color = '' |
| 3123 | reset = '' |
nodir@chromium.org | a6de1f4 | 2015-06-10 04:23:17 +0000 | [diff] [blame] | 3124 | status_str = '(%s)' % status if status else '' |
| 3125 | print ' %*s : %s%s %s%s' % ( |
| 3126 | alignment, ShortBranchName(branch), color, issue_url, status_str, |
| 3127 | reset) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 3128 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3129 | cl = Changelist(auth_config=auth_config) |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 3130 | print |
| 3131 | print 'Current branch:', |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 3132 | print cl.GetBranch() |
dpranke@chromium.org | ee87f58 | 2015-07-31 18:46:25 +0000 | [diff] [blame] | 3133 | if not cl.GetIssue(): |
| 3134 | print 'No issue assigned.' |
| 3135 | return 0 |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 3136 | print 'Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()) |
maruel@chromium.org | 85616e0 | 2014-07-28 15:37:55 +0000 | [diff] [blame] | 3137 | if not options.fast: |
| 3138 | print 'Issue description:' |
| 3139 | print cl.GetDescription(pretty=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3140 | return 0 |
| 3141 | |
| 3142 | |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 3143 | def colorize_CMDstatus_doc(): |
| 3144 | """To be called once in main() to add colors to git cl status help.""" |
| 3145 | colors = [i for i in dir(Fore) if i[0].isupper()] |
| 3146 | |
| 3147 | def colorize_line(line): |
| 3148 | for color in colors: |
| 3149 | if color in line.upper(): |
| 3150 | # Extract whitespaces first and the leading '-'. |
| 3151 | indent = len(line) - len(line.lstrip(' ')) + 1 |
| 3152 | return line[:indent] + getattr(Fore, color) + line[indent:] + Fore.RESET |
| 3153 | return line |
| 3154 | |
| 3155 | lines = CMDstatus.__doc__.splitlines() |
| 3156 | CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines) |
| 3157 | |
| 3158 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 3159 | @subcommand.usage('[issue_number]') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3160 | def CMDissue(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 3161 | """Sets or displays the current code review issue number. |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3162 | |
| 3163 | Pass issue number 0 to clear the current issue. |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 3164 | """ |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 3165 | parser.add_option('-r', '--reverse', action='store_true', |
| 3166 | help='Lookup the branch(es) for the specified issues. If ' |
| 3167 | 'no issues are specified, all branches with mapped ' |
| 3168 | 'issues will be listed.') |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3169 | _add_codereview_select_options(parser) |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 3170 | options, args = parser.parse_args(args) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3171 | _process_codereview_select_options(parser, options) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3172 | |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 3173 | if options.reverse: |
| 3174 | branches = RunGit(['for-each-ref', 'refs/heads', |
| 3175 | '--format=%(refname:short)']).splitlines() |
| 3176 | |
| 3177 | # Reverse issue lookup. |
| 3178 | issue_branch_map = {} |
| 3179 | for branch in branches: |
| 3180 | cl = Changelist(branchref=branch) |
| 3181 | issue_branch_map.setdefault(cl.GetIssue(), []).append(branch) |
| 3182 | if not args: |
| 3183 | args = sorted(issue_branch_map.iterkeys()) |
| 3184 | for issue in args: |
| 3185 | if not issue: |
| 3186 | continue |
| 3187 | print 'Branch for issue number %s: %s' % ( |
| 3188 | issue, ', '.join(issue_branch_map.get(int(issue)) or ('None',))) |
| 3189 | else: |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3190 | cl = Changelist(codereview=options.forced_codereview) |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 3191 | if len(args) > 0: |
| 3192 | try: |
| 3193 | issue = int(args[0]) |
| 3194 | except ValueError: |
| 3195 | DieWithError('Pass a number to set the issue or none to list it.\n' |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 3196 | 'Maybe you want to run git cl status?') |
dnj@chromium.org | 406c440 | 2015-03-03 17:22:28 +0000 | [diff] [blame] | 3197 | cl.SetIssue(issue) |
| 3198 | print 'Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3199 | return 0 |
| 3200 | |
| 3201 | |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 3202 | def CMDcomments(parser, args): |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 3203 | """Shows or posts review comments for any changelist.""" |
| 3204 | parser.add_option('-a', '--add-comment', dest='comment', |
| 3205 | help='comment to add to an issue') |
| 3206 | parser.add_option('-i', dest='issue', |
| 3207 | help="review issue id (defaults to current issue)") |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 3208 | parser.add_option('-j', '--json-file', |
| 3209 | help='File to write JSON summary to') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3210 | auth.add_auth_options(parser) |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 3211 | options, args = parser.parse_args(args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3212 | auth_config = auth.extract_auth_config_from_options(options) |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 3213 | |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 3214 | issue = None |
| 3215 | if options.issue: |
| 3216 | try: |
| 3217 | issue = int(options.issue) |
| 3218 | except ValueError: |
| 3219 | DieWithError('A review issue id is expected to be a number') |
| 3220 | |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 3221 | cl = Changelist(issue=issue, codereview='rietveld', auth_config=auth_config) |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 3222 | |
| 3223 | if options.comment: |
| 3224 | cl.AddComment(options.comment) |
| 3225 | return 0 |
| 3226 | |
| 3227 | data = cl.GetIssueProperties() |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 3228 | summary = [] |
maruel@chromium.org | 5cab2d3 | 2014-11-11 18:32:41 +0000 | [diff] [blame] | 3229 | for message in sorted(data.get('messages', []), key=lambda x: x['date']): |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 3230 | summary.append({ |
| 3231 | 'date': message['date'], |
| 3232 | 'lgtm': False, |
| 3233 | 'message': message['text'], |
| 3234 | 'not_lgtm': False, |
| 3235 | 'sender': message['sender'], |
| 3236 | }) |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 3237 | if message['disapproval']: |
| 3238 | color = Fore.RED |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 3239 | summary[-1]['not lgtm'] = True |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 3240 | elif message['approval']: |
| 3241 | color = Fore.GREEN |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 3242 | summary[-1]['lgtm'] = True |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 3243 | elif message['sender'] == data['owner_email']: |
| 3244 | color = Fore.MAGENTA |
| 3245 | else: |
| 3246 | color = Fore.BLUE |
| 3247 | print '\n%s%s %s%s' % ( |
| 3248 | color, message['date'].split('.', 1)[0], message['sender'], |
| 3249 | Fore.RESET) |
| 3250 | if message['text'].strip(): |
| 3251 | print '\n'.join(' ' + l for l in message['text'].splitlines()) |
smut@google.com | c85ac94 | 2015-09-15 16:34:43 +0000 | [diff] [blame] | 3252 | if options.json_file: |
| 3253 | with open(options.json_file, 'wb') as f: |
| 3254 | json.dump(summary, f) |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 3255 | return 0 |
| 3256 | |
| 3257 | |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 3258 | def CMDdescription(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 3259 | """Brings up the editor for the current CL's description.""" |
smut@google.com | 34fb6b1 | 2015-07-13 20:03:26 +0000 | [diff] [blame] | 3260 | parser.add_option('-d', '--display', action='store_true', |
| 3261 | help='Display the description instead of opening an editor') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3262 | auth.add_auth_options(parser) |
| 3263 | options, _ = parser.parse_args(args) |
| 3264 | auth_config = auth.extract_auth_config_from_options(options) |
| 3265 | cl = Changelist(auth_config=auth_config) |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 3266 | if not cl.GetIssue(): |
| 3267 | DieWithError('This branch has no associated changelist.') |
| 3268 | description = ChangeDescription(cl.GetDescription()) |
smut@google.com | 34fb6b1 | 2015-07-13 20:03:26 +0000 | [diff] [blame] | 3269 | if options.display: |
| 3270 | print description.description |
| 3271 | return 0 |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 3272 | description.prompt() |
wychen@chromium.org | 063e4e5 | 2015-04-03 06:51:44 +0000 | [diff] [blame] | 3273 | if cl.GetDescription() != description.description: |
| 3274 | cl.UpdateDescription(description.description) |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 3275 | return 0 |
| 3276 | |
| 3277 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3278 | def CreateDescriptionFromLog(args): |
| 3279 | """Pulls out the commit log to use as a base for the CL description.""" |
| 3280 | log_args = [] |
| 3281 | if len(args) == 1 and not args[0].endswith('.'): |
| 3282 | log_args = [args[0] + '..'] |
| 3283 | elif len(args) == 1 and args[0].endswith('...'): |
| 3284 | log_args = [args[0][:-1]] |
| 3285 | elif len(args) == 2: |
| 3286 | log_args = [args[0] + '..' + args[1]] |
| 3287 | else: |
| 3288 | log_args = args[:] # Hope for the best! |
maruel@chromium.org | 373af80 | 2012-05-25 21:07:33 +0000 | [diff] [blame] | 3289 | return RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3290 | |
| 3291 | |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 3292 | def CMDlint(parser, args): |
| 3293 | """Runs cpplint on the current changelist.""" |
tzik@chromium.org | f204d4b | 2014-03-13 07:40:55 +0000 | [diff] [blame] | 3294 | parser.add_option('--filter', action='append', metavar='-x,+y', |
| 3295 | help='Comma-separated list of cpplint\'s category-filters') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3296 | auth.add_auth_options(parser) |
| 3297 | options, args = parser.parse_args(args) |
| 3298 | auth_config = auth.extract_auth_config_from_options(options) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 3299 | |
| 3300 | # Access to a protected member _XX of a client class |
| 3301 | # pylint: disable=W0212 |
| 3302 | try: |
| 3303 | import cpplint |
| 3304 | import cpplint_chromium |
| 3305 | except ImportError: |
| 3306 | print "Your depot_tools is missing cpplint.py and/or cpplint_chromium.py." |
| 3307 | return 1 |
| 3308 | |
| 3309 | # Change the current working directory before calling lint so that it |
| 3310 | # shows the correct base. |
| 3311 | previous_cwd = os.getcwd() |
| 3312 | os.chdir(settings.GetRoot()) |
| 3313 | try: |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3314 | cl = Changelist(auth_config=auth_config) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 3315 | change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None) |
| 3316 | files = [f.LocalPath() for f in change.AffectedFiles()] |
thestig@chromium.org | 5839eb5 | 2014-05-30 16:20:51 +0000 | [diff] [blame] | 3317 | if not files: |
| 3318 | print "Cannot lint an empty CL" |
| 3319 | return 1 |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 3320 | |
| 3321 | # Process cpplints arguments if any. |
tzik@chromium.org | f204d4b | 2014-03-13 07:40:55 +0000 | [diff] [blame] | 3322 | command = args + files |
| 3323 | if options.filter: |
| 3324 | command = ['--filter=' + ','.join(options.filter)] + command |
| 3325 | filenames = cpplint.ParseArguments(command) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 3326 | |
| 3327 | white_regex = re.compile(settings.GetLintRegex()) |
| 3328 | black_regex = re.compile(settings.GetLintIgnoreRegex()) |
| 3329 | extra_check_functions = [cpplint_chromium.CheckPointerDeclarationWhitespace] |
| 3330 | for filename in filenames: |
| 3331 | if white_regex.match(filename): |
| 3332 | if black_regex.match(filename): |
| 3333 | print "Ignoring file %s" % filename |
| 3334 | else: |
| 3335 | cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level, |
| 3336 | extra_check_functions) |
| 3337 | else: |
| 3338 | print "Skipping file %s" % filename |
| 3339 | finally: |
| 3340 | os.chdir(previous_cwd) |
| 3341 | print "Total errors found: %d\n" % cpplint._cpplint_state.error_count |
| 3342 | if cpplint._cpplint_state.error_count != 0: |
| 3343 | return 1 |
| 3344 | return 0 |
| 3345 | |
| 3346 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3347 | def CMDpresubmit(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 3348 | """Runs presubmit tests on the current changelist.""" |
ilevy@chromium.org | 375a902 | 2013-01-07 01:12:05 +0000 | [diff] [blame] | 3349 | parser.add_option('-u', '--upload', action='store_true', |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3350 | help='Run upload hook instead of the push/dcommit hook') |
ilevy@chromium.org | 375a902 | 2013-01-07 01:12:05 +0000 | [diff] [blame] | 3351 | parser.add_option('-f', '--force', action='store_true', |
sbc@chromium.org | 495ad15 | 2012-09-04 23:07:42 +0000 | [diff] [blame] | 3352 | help='Run checks even if tree is dirty') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3353 | auth.add_auth_options(parser) |
| 3354 | options, args = parser.parse_args(args) |
| 3355 | auth_config = auth.extract_auth_config_from_options(options) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3356 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 3357 | if not options.force and git_common.is_dirty_git_tree('presubmit'): |
ukai@chromium.org | 259e468 | 2012-10-25 07:36:33 +0000 | [diff] [blame] | 3358 | print 'use --force to check even if tree is dirty.' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3359 | return 1 |
| 3360 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3361 | cl = Changelist(auth_config=auth_config) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3362 | if args: |
| 3363 | base_branch = args[0] |
| 3364 | else: |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 3365 | # Default to diffing against the common ancestor of the upstream branch. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 3366 | base_branch = cl.GetCommonAncestorWithUpstream() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3367 | |
ilevy@chromium.org | 051ad0e | 2013-03-04 21:57:34 +0000 | [diff] [blame] | 3368 | cl.RunHook( |
| 3369 | committing=not options.upload, |
| 3370 | may_prompt=False, |
| 3371 | verbose=options.verbose, |
| 3372 | change=cl.GetChange(base_branch, None)) |
dpranke@chromium.org | 0a2bb37 | 2011-03-25 01:16:22 +0000 | [diff] [blame] | 3373 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3374 | |
| 3375 | |
tandrii@chromium.org | 65874e1 | 2016-03-04 12:03:02 +0000 | [diff] [blame] | 3376 | def GenerateGerritChangeId(message): |
| 3377 | """Returns Ixxxxxx...xxx change id. |
| 3378 | |
| 3379 | Works the same way as |
| 3380 | https://gerrit-review.googlesource.com/tools/hooks/commit-msg |
| 3381 | but can be called on demand on all platforms. |
| 3382 | |
| 3383 | The basic idea is to generate git hash of a state of the tree, original commit |
| 3384 | message, author/committer info and timestamps. |
| 3385 | """ |
| 3386 | lines = [] |
| 3387 | tree_hash = RunGitSilent(['write-tree']) |
| 3388 | lines.append('tree %s' % tree_hash.strip()) |
| 3389 | code, parent = RunGitWithCode(['rev-parse', 'HEAD~0'], suppress_stderr=False) |
| 3390 | if code == 0: |
| 3391 | lines.append('parent %s' % parent.strip()) |
| 3392 | author = RunGitSilent(['var', 'GIT_AUTHOR_IDENT']) |
| 3393 | lines.append('author %s' % author.strip()) |
| 3394 | committer = RunGitSilent(['var', 'GIT_COMMITTER_IDENT']) |
| 3395 | lines.append('committer %s' % committer.strip()) |
| 3396 | lines.append('') |
| 3397 | # Note: Gerrit's commit-hook actually cleans message of some lines and |
| 3398 | # whitespace. This code is not doing this, but it clearly won't decrease |
| 3399 | # entropy. |
| 3400 | lines.append(message) |
| 3401 | change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'], |
| 3402 | stdin='\n'.join(lines)) |
| 3403 | return 'I%s' % change_hash.strip() |
| 3404 | |
| 3405 | |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 3406 | def GetTargetRef(remote, remote_branch, target_branch, pending_prefix): |
| 3407 | """Computes the remote branch ref to use for the CL. |
| 3408 | |
| 3409 | Args: |
| 3410 | remote (str): The git remote for the CL. |
| 3411 | remote_branch (str): The git remote branch for the CL. |
| 3412 | target_branch (str): The target branch specified by the user. |
| 3413 | pending_prefix (str): The pending prefix from the settings. |
| 3414 | """ |
| 3415 | if not (remote and remote_branch): |
| 3416 | return None |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 3417 | |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 3418 | if target_branch: |
| 3419 | # Cannonicalize branch references to the equivalent local full symbolic |
| 3420 | # refs, which are then translated into the remote full symbolic refs |
| 3421 | # below. |
| 3422 | if '/' not in target_branch: |
| 3423 | remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch) |
| 3424 | else: |
| 3425 | prefix_replacements = ( |
| 3426 | ('^((refs/)?remotes/)?branch-heads/', 'refs/remotes/branch-heads/'), |
| 3427 | ('^((refs/)?remotes/)?%s/' % remote, 'refs/remotes/%s/' % remote), |
| 3428 | ('^(refs/)?heads/', 'refs/remotes/%s/' % remote), |
| 3429 | ) |
| 3430 | match = None |
| 3431 | for regex, replacement in prefix_replacements: |
| 3432 | match = re.search(regex, target_branch) |
| 3433 | if match: |
| 3434 | remote_branch = target_branch.replace(match.group(0), replacement) |
| 3435 | break |
| 3436 | if not match: |
| 3437 | # This is a branch path but not one we recognize; use as-is. |
| 3438 | remote_branch = target_branch |
rmistry@google.com | c68112d | 2015-03-03 12:48:06 +0000 | [diff] [blame] | 3439 | elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS: |
| 3440 | # Handle the refs that need to land in different refs. |
| 3441 | remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch] |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 3442 | |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 3443 | # Create the true path to the remote branch. |
| 3444 | # Does the following translation: |
| 3445 | # * refs/remotes/origin/refs/diff/test -> refs/diff/test |
| 3446 | # * refs/remotes/origin/master -> refs/heads/master |
| 3447 | # * refs/remotes/branch-heads/test -> refs/branch-heads/test |
| 3448 | if remote_branch.startswith('refs/remotes/%s/refs/' % remote): |
| 3449 | remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '') |
| 3450 | elif remote_branch.startswith('refs/remotes/%s/' % remote): |
| 3451 | remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, |
| 3452 | 'refs/heads/') |
| 3453 | elif remote_branch.startswith('refs/remotes/branch-heads'): |
| 3454 | remote_branch = remote_branch.replace('refs/remotes/', 'refs/') |
| 3455 | # If a pending prefix exists then replace refs/ with it. |
| 3456 | if pending_prefix: |
| 3457 | remote_branch = remote_branch.replace('refs/', pending_prefix) |
| 3458 | return remote_branch |
| 3459 | |
| 3460 | |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 3461 | def cleanup_list(l): |
| 3462 | """Fixes a list so that comma separated items are put as individual items. |
| 3463 | |
| 3464 | So that "--reviewers joe@c,john@c --reviewers joa@c" results in |
| 3465 | options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']). |
| 3466 | """ |
| 3467 | items = sum((i.split(',') for i in l), []) |
| 3468 | stripped_items = (i.strip() for i in items) |
| 3469 | return sorted(filter(None, stripped_items)) |
| 3470 | |
| 3471 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 3472 | @subcommand.usage('[args to "git diff"]') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3473 | def CMDupload(parser, args): |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 3474 | """Uploads the current changelist to codereview. |
| 3475 | |
| 3476 | Can skip dependency patchset uploads for a branch by running: |
| 3477 | git config branch.branch_name.skip-deps-uploads True |
| 3478 | To unset run: |
| 3479 | git config --unset branch.branch_name.skip-deps-uploads |
| 3480 | Can also set the above globally by using the --global flag. |
| 3481 | """ |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3482 | parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 3483 | help='bypass upload presubmit hook') |
brettw@chromium.org | b65c43c | 2013-06-10 22:04:49 +0000 | [diff] [blame] | 3484 | parser.add_option('--bypass-watchlists', action='store_true', |
| 3485 | dest='bypass_watchlists', |
| 3486 | help='bypass watchlists auto CC-ing reviewers') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3487 | parser.add_option('-f', action='store_true', dest='force', |
| 3488 | help="force yes to questions (don't prompt)") |
rogerta@chromium.org | 420d3b8 | 2012-05-14 18:41:38 +0000 | [diff] [blame] | 3489 | parser.add_option('-m', dest='message', help='message for patchset') |
andybons@chromium.org | 962f946 | 2016-02-03 20:00:42 +0000 | [diff] [blame] | 3490 | parser.add_option('-t', dest='title', |
| 3491 | help='title for patchset (Rietveld only)') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3492 | parser.add_option('-r', '--reviewers', |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 3493 | action='append', default=[], |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3494 | help='reviewer email addresses') |
| 3495 | parser.add_option('--cc', |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 3496 | action='append', default=[], |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3497 | help='cc email addresses') |
adamk@chromium.org | 36f4730 | 2013-04-05 01:08:31 +0000 | [diff] [blame] | 3498 | parser.add_option('-s', '--send-mail', action='store_true', |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3499 | help='send email to reviewer immediately') |
pgervais@chromium.org | b9f2751 | 2014-08-08 15:52:33 +0000 | [diff] [blame] | 3500 | parser.add_option('--emulate_svn_auto_props', |
| 3501 | '--emulate-svn-auto-props', |
| 3502 | action="store_true", |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3503 | dest="emulate_svn_auto_props", |
| 3504 | help="Emulate Subversion's auto properties feature.") |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3505 | parser.add_option('-c', '--use-commit-queue', action='store_true', |
| 3506 | help='tell the commit queue to commit this patchset') |
tyoshino@chromium.org | c1737d0 | 2013-05-29 14:17:28 +0000 | [diff] [blame] | 3507 | parser.add_option('--private', action='store_true', |
| 3508 | help='set the review private (rietveld only)') |
ukai@chromium.org | 8ef7ab2 | 2012-11-28 04:24:52 +0000 | [diff] [blame] | 3509 | parser.add_option('--target_branch', |
pgervais@chromium.org | b9f2751 | 2014-08-08 15:52:33 +0000 | [diff] [blame] | 3510 | '--target-branch', |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 3511 | metavar='TARGET', |
| 3512 | help='Apply CL to remote ref TARGET. ' + |
| 3513 | 'Default: remote branch head, or master') |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 3514 | parser.add_option('--squash', action='store_true', |
| 3515 | help='Squash multiple commits into one (Gerrit only)') |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 3516 | parser.add_option('--no-squash', action='store_true', |
| 3517 | help='Don\'t squash multiple commits into one ' + |
| 3518 | '(Gerrit only)') |
pgervais@chromium.org | 9114137 | 2014-01-09 23:27:20 +0000 | [diff] [blame] | 3519 | parser.add_option('--email', default=None, |
| 3520 | help='email address to use to connect to Rietveld') |
piman@chromium.org | 336f912 | 2014-09-04 02:16:55 +0000 | [diff] [blame] | 3521 | parser.add_option('--tbr-owners', dest='tbr_owners', action='store_true', |
| 3522 | help='add a set of OWNERS to TBR') |
tandrii@chromium.org | d50452a | 2015-11-23 16:38:15 +0000 | [diff] [blame] | 3523 | parser.add_option('-d', '--cq-dry-run', dest='cq_dry_run', |
| 3524 | action='store_true', |
rmistry@google.com | ef96622 | 2015-04-07 11:15:01 +0000 | [diff] [blame] | 3525 | help='Send the patchset to do a CQ dry run right after ' |
| 3526 | 'upload.') |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 3527 | parser.add_option('--dependencies', action='store_true', |
| 3528 | help='Uploads CLs of all the local branches that depend on ' |
| 3529 | 'the current branch') |
pgervais@chromium.org | 9114137 | 2014-01-09 23:27:20 +0000 | [diff] [blame] | 3530 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 3531 | orig_args = args |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 3532 | add_git_similarity(parser) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3533 | auth.add_auth_options(parser) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3534 | _add_codereview_select_options(parser) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3535 | (options, args) = parser.parse_args(args) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3536 | _process_codereview_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3537 | auth_config = auth.extract_auth_config_from_options(options) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3538 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 3539 | if git_common.is_dirty_git_tree('upload'): |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3540 | return 1 |
| 3541 | |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 3542 | options.reviewers = cleanup_list(options.reviewers) |
| 3543 | options.cc = cleanup_list(options.cc) |
| 3544 | |
tandrii@chromium.org | 512d79c | 2016-03-31 12:55:28 +0000 | [diff] [blame] | 3545 | # For sanity of test expectations, do this otherwise lazy-loading *now*. |
| 3546 | settings.GetIsGerrit() |
| 3547 | |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 3548 | cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 3549 | return cl.CMDUpload(options, args, orig_args) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3550 | |
| 3551 | |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3552 | def IsSubmoduleMergeCommit(ref): |
| 3553 | # When submodules are added to the repo, we expect there to be a single |
| 3554 | # non-git-svn merge commit at remote HEAD with a signature comment. |
| 3555 | pattern = '^SVN changes up to revision [0-9]*$' |
szager@chromium.org | e84b754 | 2012-06-15 21:26:58 +0000 | [diff] [blame] | 3556 | cmd = ['rev-list', '--merges', '--grep=%s' % pattern, '%s^!' % ref] |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3557 | return RunGit(cmd) != '' |
| 3558 | |
| 3559 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3560 | def SendUpstream(parser, args, cmd): |
pgervais@chromium.org | cee6dc4 | 2014-05-07 17:04:03 +0000 | [diff] [blame] | 3561 | """Common code for CMDland and CmdDCommit |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3562 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 3563 | In case of Gerrit, uses Gerrit REST api to "submit" the issue, which pushes |
| 3564 | upstream and closes the issue automatically and atomically. |
| 3565 | |
| 3566 | Otherwise (in case of Rietveld): |
| 3567 | Squashes branch into a single commit. |
| 3568 | Updates changelog with metadata (e.g. pointer to review). |
| 3569 | Pushes/dcommits the code upstream. |
| 3570 | Updates review and closes. |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3571 | """ |
| 3572 | parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks', |
| 3573 | help='bypass upload presubmit hook') |
| 3574 | parser.add_option('-m', dest='message', |
| 3575 | help="override review description") |
| 3576 | parser.add_option('-f', action='store_true', dest='force', |
| 3577 | help="force yes to questions (don't prompt)") |
| 3578 | parser.add_option('-c', dest='contributor', |
| 3579 | help="external contributor for patch (appended to " + |
| 3580 | "description and used as author for git). Should be " + |
| 3581 | "formatted as 'First Last <email@example.com>'") |
iannucci@chromium.org | 53937ba | 2012-10-02 18:20:43 +0000 | [diff] [blame] | 3582 | add_git_similarity(parser) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3583 | auth.add_auth_options(parser) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3584 | (options, args) = parser.parse_args(args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 3585 | auth_config = auth.extract_auth_config_from_options(options) |
| 3586 | |
| 3587 | cl = Changelist(auth_config=auth_config) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3588 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 3589 | # TODO(tandrii): refactor this into _RietveldChangelistImpl method. |
| 3590 | if cl.IsGerrit(): |
| 3591 | if options.message: |
| 3592 | # This could be implemented, but it requires sending a new patch to |
| 3593 | # Gerrit, as Gerrit unlike Rietveld versions messages with patchsets. |
| 3594 | # Besides, Gerrit has the ability to change the commit message on submit |
| 3595 | # automatically, thus there is no need to support this option (so far?). |
| 3596 | parser.error('-m MESSAGE option is not supported for Gerrit.') |
| 3597 | if options.contributor: |
| 3598 | parser.error( |
| 3599 | '-c CONTRIBUTOR option is not supported for Gerrit.\n' |
| 3600 | 'Before uploading a commit to Gerrit, ensure it\'s author field is ' |
| 3601 | 'the contributor\'s "name <email>". If you can\'t upload such a ' |
| 3602 | 'commit for review, contact your repository admin and request' |
| 3603 | '"Forge-Author" permission.') |
| 3604 | return cl._codereview_impl.CMDLand(options.force, options.bypass_hooks, |
| 3605 | options.verbose) |
| 3606 | |
iannucci@chromium.org | 5724c96 | 2014-04-11 09:32:56 +0000 | [diff] [blame] | 3607 | current = cl.GetBranch() |
| 3608 | remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch()) |
| 3609 | if not settings.GetIsGitSvn() and remote == '.': |
| 3610 | print |
| 3611 | print 'Attempting to push branch %r into another local branch!' % current |
| 3612 | print |
| 3613 | print 'Either reparent this branch on top of origin/master:' |
| 3614 | print ' git reparent-branch --root' |
| 3615 | print |
| 3616 | print 'OR run `git rebase-update` if you think the parent branch is already' |
| 3617 | print 'committed.' |
| 3618 | print |
| 3619 | print ' Current parent: %r' % upstream_branch |
| 3620 | return 1 |
| 3621 | |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3622 | if not args or cmd == 'land': |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3623 | # Default to merging against our best guess of the upstream branch. |
| 3624 | args = [cl.GetUpstreamBranch()] |
| 3625 | |
maruel@chromium.org | 13f623c | 2011-07-22 16:02:23 +0000 | [diff] [blame] | 3626 | if options.contributor: |
| 3627 | if not re.match('^.*\s<\S+@\S+>$', options.contributor): |
| 3628 | print "Please provide contibutor as 'First Last <email@example.com>'" |
| 3629 | return 1 |
| 3630 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3631 | base_branch = args[0] |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3632 | base_has_submodules = IsSubmoduleMergeCommit(base_branch) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3633 | |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 3634 | if git_common.is_dirty_git_tree(cmd): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3635 | return 1 |
| 3636 | |
| 3637 | # This rev-list syntax means "show all commits not in my branch that |
| 3638 | # are in base_branch". |
| 3639 | upstream_commits = RunGit(['rev-list', '^' + cl.GetBranchRef(), |
| 3640 | base_branch]).splitlines() |
| 3641 | if upstream_commits: |
| 3642 | print ('Base branch "%s" has %d commits ' |
| 3643 | 'not in this branch.' % (base_branch, len(upstream_commits))) |
| 3644 | print 'Run "git merge %s" before attempting to %s.' % (base_branch, cmd) |
| 3645 | return 1 |
| 3646 | |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3647 | # This is the revision `svn dcommit` will commit on top of. |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3648 | svn_head = None |
| 3649 | if cmd == 'dcommit' or base_has_submodules: |
| 3650 | svn_head = RunGit(['log', '--grep=^git-svn-id:', '-1', |
| 3651 | '--pretty=format:%H']) |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3652 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3653 | if cmd == 'dcommit': |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3654 | # If the base_head is a submodule merge commit, the first parent of the |
| 3655 | # base_head should be a git-svn commit, which is what we're interested in. |
| 3656 | base_svn_head = base_branch |
| 3657 | if base_has_submodules: |
| 3658 | base_svn_head += '^1' |
| 3659 | |
| 3660 | extra_commits = RunGit(['rev-list', '^' + svn_head, base_svn_head]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3661 | if extra_commits: |
| 3662 | print ('This branch has %d additional commits not upstreamed yet.' |
| 3663 | % len(extra_commits.splitlines())) |
| 3664 | print ('Upstream "%s" or rebase this branch on top of the upstream trunk ' |
| 3665 | 'before attempting to %s.' % (base_branch, cmd)) |
| 3666 | return 1 |
| 3667 | |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3668 | merge_base = RunGit(['merge-base', base_branch, 'HEAD']).strip() |
maruel@chromium.org | b0a6391 | 2012-01-17 18:10:16 +0000 | [diff] [blame] | 3669 | if not options.bypass_hooks: |
maruel@chromium.org | 13f623c | 2011-07-22 16:02:23 +0000 | [diff] [blame] | 3670 | author = None |
| 3671 | if options.contributor: |
| 3672 | author = re.search(r'\<(.*)\>', options.contributor).group(1) |
maruel@chromium.org | b0a6391 | 2012-01-17 18:10:16 +0000 | [diff] [blame] | 3673 | hook_results = cl.RunHook( |
| 3674 | committing=True, |
maruel@chromium.org | b0a6391 | 2012-01-17 18:10:16 +0000 | [diff] [blame] | 3675 | may_prompt=not options.force, |
| 3676 | verbose=options.verbose, |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3677 | change=cl.GetChange(merge_base, author)) |
maruel@chromium.org | b0a6391 | 2012-01-17 18:10:16 +0000 | [diff] [blame] | 3678 | if not hook_results.should_continue(): |
| 3679 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3680 | |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3681 | # Check the tree status if the tree status URL is set. |
| 3682 | status = GetTreeStatus() |
| 3683 | if 'closed' == status: |
| 3684 | print('The tree is closed. Please wait for it to reopen. Use ' |
| 3685 | '"git cl %s --bypass-hooks" to commit on a closed tree.' % cmd) |
| 3686 | return 1 |
| 3687 | elif 'unknown' == status: |
| 3688 | print('Unable to determine tree status. Please verify manually and ' |
| 3689 | 'use "git cl %s --bypass-hooks" to commit on a closed tree.' % cmd) |
| 3690 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3691 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3692 | change_desc = ChangeDescription(options.message) |
| 3693 | if not change_desc.description and cl.GetIssue(): |
| 3694 | change_desc = ChangeDescription(cl.GetDescription()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3695 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3696 | if not change_desc.description: |
erg@chromium.org | 1a17398 | 2012-08-29 20:43:05 +0000 | [diff] [blame] | 3697 | if not cl.GetIssue() and options.bypass_hooks: |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3698 | change_desc = ChangeDescription(CreateDescriptionFromLog([merge_base])) |
erg@chromium.org | 1a17398 | 2012-08-29 20:43:05 +0000 | [diff] [blame] | 3699 | else: |
| 3700 | print 'No description set.' |
| 3701 | print 'Visit %s/edit to set it.' % (cl.GetIssueURL()) |
| 3702 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3703 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3704 | # Keep a separate copy for the commit message, because the commit message |
| 3705 | # contains the link to the Rietveld issue, while the Rietveld message contains |
| 3706 | # the commit viewvc url. |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 3707 | # Keep a separate copy for the commit message. |
| 3708 | if cl.GetIssue(): |
maruel@chromium.org | cf08778 | 2013-07-23 13:08:48 +0000 | [diff] [blame] | 3709 | change_desc.update_reviewers(cl.GetApprovingReviewers()) |
maruel@chromium.org | e52678e | 2013-04-26 18:34:44 +0000 | [diff] [blame] | 3710 | |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3711 | commit_desc = ChangeDescription(change_desc.description) |
maruel@chromium.org | cc73ad6 | 2011-07-06 17:39:26 +0000 | [diff] [blame] | 3712 | if cl.GetIssue(): |
smut@google.com | 4c61dcc | 2015-06-08 22:31:29 +0000 | [diff] [blame] | 3713 | # Xcode won't linkify this URL unless there is a non-whitespace character |
sergiyb@chromium.org | 4b39c5f | 2015-07-07 10:33:12 +0000 | [diff] [blame] | 3714 | # after it. Add a period on a new line to circumvent this. Also add a space |
| 3715 | # before the period to make sure that Gitiles continues to correctly resolve |
| 3716 | # the URL. |
| 3717 | commit_desc.append_footer('Review URL: %s .' % cl.GetIssueURL()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3718 | if options.contributor: |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3719 | commit_desc.append_footer('Patch from %s.' % options.contributor) |
| 3720 | |
agable@chromium.org | eec3ea3 | 2013-08-15 20:31:39 +0000 | [diff] [blame] | 3721 | print('Description:') |
| 3722 | print(commit_desc.description) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3723 | |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3724 | branches = [merge_base, cl.GetBranchRef()] |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3725 | if not options.force: |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 3726 | print_stats(options.similarity, options.find_copies, branches) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3727 | |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3728 | # We want to squash all this branch's commits into one commit with the proper |
| 3729 | # description. We do this by doing a "reset --soft" to the base branch (which |
| 3730 | # keeps the working copy the same), then dcommitting that. If origin/master |
| 3731 | # has a submodule merge commit, we'll also need to cherry-pick the squashed |
| 3732 | # commit onto a branch based on the git-svn head. |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3733 | MERGE_BRANCH = 'git-cl-commit' |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3734 | CHERRY_PICK_BRANCH = 'git-cl-cherry-pick' |
| 3735 | # Delete the branches if they exist. |
| 3736 | for branch in [MERGE_BRANCH, CHERRY_PICK_BRANCH]: |
| 3737 | showref_cmd = ['show-ref', '--quiet', '--verify', 'refs/heads/%s' % branch] |
| 3738 | result = RunGitWithCode(showref_cmd) |
| 3739 | if result[0] == 0: |
| 3740 | RunGit(['branch', '-D', branch]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3741 | |
| 3742 | # We might be in a directory that's present in this branch but not in the |
| 3743 | # trunk. Move up to the top of the tree so that git commands that expect a |
| 3744 | # valid CWD won't fail after we check out the merge branch. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 3745 | rel_base_path = settings.GetRelativeRoot() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3746 | if rel_base_path: |
| 3747 | os.chdir(rel_base_path) |
| 3748 | |
| 3749 | # Stuff our change into the merge branch. |
| 3750 | # We wrap in a try...finally block so if anything goes wrong, |
| 3751 | # we clean up the branches. |
maruel@chromium.org | 0ba7f96 | 2011-01-11 22:13:58 +0000 | [diff] [blame] | 3752 | retcode = -1 |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3753 | pushed_to_pending = False |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3754 | pending_ref = None |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3755 | revision = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3756 | try: |
bauerb@chromium.org | b4a75c4 | 2011-03-08 08:35:38 +0000 | [diff] [blame] | 3757 | RunGit(['checkout', '-q', '-b', MERGE_BRANCH]) |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3758 | RunGit(['reset', '--soft', merge_base]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3759 | if options.contributor: |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3760 | RunGit( |
| 3761 | [ |
| 3762 | 'commit', '--author', options.contributor, |
| 3763 | '-m', commit_desc.description, |
| 3764 | ]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3765 | else: |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3766 | RunGit(['commit', '-m', commit_desc.description]) |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3767 | if base_has_submodules: |
| 3768 | cherry_pick_commit = RunGit(['rev-list', 'HEAD^!']).rstrip() |
| 3769 | RunGit(['branch', CHERRY_PICK_BRANCH, svn_head]) |
| 3770 | RunGit(['checkout', CHERRY_PICK_BRANCH]) |
| 3771 | RunGit(['cherry-pick', cherry_pick_commit]) |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3772 | if cmd == 'land': |
ilevy@chromium.org | 0f58fa8 | 2012-11-05 01:45:20 +0000 | [diff] [blame] | 3773 | remote, branch = cl.FetchUpstreamTuple(cl.GetBranch()) |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 3774 | mirror = settings.GetGitMirror(remote) |
| 3775 | pushurl = mirror.url if mirror else remote |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3776 | pending_prefix = settings.GetPendingRefPrefix() |
| 3777 | if not pending_prefix or branch.startswith(pending_prefix): |
| 3778 | # If not using refs/pending/heads/* at all, or target ref is already set |
| 3779 | # to pending, then push to the target ref directly. |
| 3780 | retcode, output = RunGitWithCode( |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 3781 | ['push', '--porcelain', pushurl, 'HEAD:%s' % branch]) |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3782 | pushed_to_pending = pending_prefix and branch.startswith(pending_prefix) |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3783 | else: |
| 3784 | # Cherry-pick the change on top of pending ref and then push it. |
| 3785 | assert branch.startswith('refs/'), branch |
| 3786 | assert pending_prefix[-1] == '/', pending_prefix |
| 3787 | pending_ref = pending_prefix + branch[len('refs/'):] |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 3788 | retcode, output = PushToGitPending(pushurl, pending_ref, branch) |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3789 | pushed_to_pending = (retcode == 0) |
iannucci@chromium.org | 34504a1 | 2014-08-29 23:51:37 +0000 | [diff] [blame] | 3790 | if retcode == 0: |
| 3791 | revision = RunGit(['rev-parse', 'HEAD']).strip() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3792 | else: |
| 3793 | # dcommit the merge branch. |
iannucci@chromium.org | a1950c4 | 2014-12-05 22:15:56 +0000 | [diff] [blame] | 3794 | cmd_args = [ |
kjellander@chromium.org | 6abc652 | 2014-12-02 07:34:49 +0000 | [diff] [blame] | 3795 | 'svn', 'dcommit', |
| 3796 | '-C%s' % options.similarity, |
| 3797 | '--no-rebase', '--rmdir', |
| 3798 | ] |
| 3799 | if settings.GetForceHttpsCommitUrl(): |
| 3800 | # Allow forcing https commit URLs for some projects that don't allow |
| 3801 | # committing to http URLs (like Google Code). |
| 3802 | remote_url = cl.GetGitSvnRemoteUrl() |
| 3803 | if urlparse.urlparse(remote_url).scheme == 'http': |
| 3804 | remote_url = remote_url.replace('http://', 'https://') |
iannucci@chromium.org | a1950c4 | 2014-12-05 22:15:56 +0000 | [diff] [blame] | 3805 | cmd_args.append('--commit-url=%s' % remote_url) |
| 3806 | _, output = RunGitWithCode(cmd_args) |
iannucci@chromium.org | 34504a1 | 2014-08-29 23:51:37 +0000 | [diff] [blame] | 3807 | if 'Committed r' in output: |
| 3808 | revision = re.match( |
| 3809 | '.*?\nCommitted r(\\d+)', output, re.DOTALL).group(1) |
| 3810 | logging.debug(output) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3811 | finally: |
| 3812 | # And then swap back to the original branch and clean up. |
| 3813 | RunGit(['checkout', '-q', cl.GetBranch()]) |
| 3814 | RunGit(['branch', '-D', MERGE_BRANCH]) |
szager@chromium.org | 9bb85e2 | 2012-06-13 20:28:23 +0000 | [diff] [blame] | 3815 | if base_has_submodules: |
| 3816 | RunGit(['branch', '-D', CHERRY_PICK_BRANCH]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3817 | |
iannucci@chromium.org | 34504a1 | 2014-08-29 23:51:37 +0000 | [diff] [blame] | 3818 | if not revision: |
iannucci@chromium.org | 6c217b1 | 2014-08-29 22:10:59 +0000 | [diff] [blame] | 3819 | print 'Failed to push. If this persists, please file a bug.' |
iannucci@chromium.org | 34504a1 | 2014-08-29 23:51:37 +0000 | [diff] [blame] | 3820 | return 1 |
iannucci@chromium.org | 6c217b1 | 2014-08-29 22:10:59 +0000 | [diff] [blame] | 3821 | |
iannucci@chromium.org | bbe9cc5 | 2014-09-05 18:25:51 +0000 | [diff] [blame] | 3822 | killed = False |
iannucci@chromium.org | 6c217b1 | 2014-08-29 22:10:59 +0000 | [diff] [blame] | 3823 | if pushed_to_pending: |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3824 | try: |
| 3825 | revision = WaitForRealCommit(remote, revision, base_branch, branch) |
| 3826 | # We set pushed_to_pending to False, since it made it all the way to the |
| 3827 | # real ref. |
| 3828 | pushed_to_pending = False |
| 3829 | except KeyboardInterrupt: |
iannucci@chromium.org | bbe9cc5 | 2014-09-05 18:25:51 +0000 | [diff] [blame] | 3830 | killed = True |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3831 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3832 | if cl.GetIssue(): |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3833 | to_pending = ' to pending queue' if pushed_to_pending else '' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3834 | viewvc_url = settings.GetViewVCUrl() |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3835 | if not to_pending: |
| 3836 | if viewvc_url and revision: |
| 3837 | change_desc.append_footer( |
| 3838 | 'Committed: %s%s' % (viewvc_url, revision)) |
| 3839 | elif revision: |
| 3840 | change_desc.append_footer('Committed: %s' % (revision,)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3841 | print ('Closing issue ' |
| 3842 | '(you may be prompted for your codereview password)...') |
maruel@chromium.org | 78936cb | 2013-04-11 00:17:52 +0000 | [diff] [blame] | 3843 | cl.UpdateDescription(change_desc.description) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3844 | cl.CloseIssue() |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 3845 | props = cl.GetIssueProperties() |
sadrul@chromium.org | 34b5d82 | 2013-02-18 01:39:24 +0000 | [diff] [blame] | 3846 | patch_num = len(props['patchsets']) |
rmistry@google.com | 52d224a | 2014-08-27 14:44:41 +0000 | [diff] [blame] | 3847 | comment = "Committed patchset #%d (id:%d)%s manually as %s" % ( |
mark@chromium.org | 782570c | 2014-09-26 21:48:02 +0000 | [diff] [blame] | 3848 | patch_num, props['patchsets'][-1], to_pending, revision) |
jochen@chromium.org | 3ec0d54 | 2014-01-14 20:00:03 +0000 | [diff] [blame] | 3849 | if options.bypass_hooks: |
| 3850 | comment += ' (tree was closed).' if GetTreeStatus() == 'closed' else '.' |
| 3851 | else: |
| 3852 | comment += ' (presubmit successful).' |
iannucci@chromium.org | b85a316 | 2013-01-26 01:11:13 +0000 | [diff] [blame] | 3853 | cl.RpcServer().add_comment(cl.GetIssue(), comment) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 3854 | cl.SetIssue(None) |
maruel@chromium.org | 0ba7f96 | 2011-01-11 22:13:58 +0000 | [diff] [blame] | 3855 | |
iannucci@chromium.org | 6c217b1 | 2014-08-29 22:10:59 +0000 | [diff] [blame] | 3856 | if pushed_to_pending: |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3857 | _, branch = cl.FetchUpstreamTuple(cl.GetBranch()) |
| 3858 | print 'The commit is in the pending queue (%s).' % pending_ref |
| 3859 | print ( |
thakis@chromium.org | 5f32a96 | 2014-09-05 21:33:23 +0000 | [diff] [blame] | 3860 | 'It will show up on %s in ~1 min, once it gets a Cr-Commit-Position ' |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3861 | 'footer.' % branch) |
| 3862 | |
iannucci@chromium.org | 6c217b1 | 2014-08-29 22:10:59 +0000 | [diff] [blame] | 3863 | hook = POSTUPSTREAM_HOOK_PATTERN % cmd |
| 3864 | if os.path.isfile(hook): |
| 3865 | RunCommand([hook, merge_base], error_ok=True) |
maruel@chromium.org | 0ba7f96 | 2011-01-11 22:13:58 +0000 | [diff] [blame] | 3866 | |
iannucci@chromium.org | bbe9cc5 | 2014-09-05 18:25:51 +0000 | [diff] [blame] | 3867 | return 1 if killed else 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3868 | |
| 3869 | |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3870 | def WaitForRealCommit(remote, pushed_commit, local_base_ref, real_ref): |
| 3871 | print |
| 3872 | print 'Waiting for commit to be landed on %s...' % real_ref |
| 3873 | print '(If you are impatient, you may Ctrl-C once without harm)' |
| 3874 | target_tree = RunGit(['rev-parse', '%s:' % pushed_commit]).strip() |
| 3875 | current_rev = RunGit(['rev-parse', local_base_ref]).strip() |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 3876 | mirror = settings.GetGitMirror(remote) |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3877 | |
| 3878 | loop = 0 |
| 3879 | while True: |
| 3880 | sys.stdout.write('fetching (%d)... \r' % loop) |
| 3881 | sys.stdout.flush() |
| 3882 | loop += 1 |
| 3883 | |
szager@chromium.org | 151ebcf | 2016-03-09 01:08:25 +0000 | [diff] [blame] | 3884 | if mirror: |
| 3885 | mirror.populate() |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3886 | RunGit(['retry', 'fetch', remote, real_ref], stderr=subprocess2.VOID) |
| 3887 | to_rev = RunGit(['rev-parse', 'FETCH_HEAD']).strip() |
| 3888 | commits = RunGit(['rev-list', '%s..%s' % (current_rev, to_rev)]) |
| 3889 | for commit in commits.splitlines(): |
| 3890 | if RunGit(['rev-parse', '%s:' % commit]).strip() == target_tree: |
| 3891 | print 'Found commit on %s' % real_ref |
| 3892 | return commit |
| 3893 | |
| 3894 | current_rev = to_rev |
| 3895 | |
| 3896 | |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3897 | def PushToGitPending(remote, pending_ref, upstream_ref): |
| 3898 | """Fetches pending_ref, cherry-picks current HEAD on top of it, pushes. |
| 3899 | |
| 3900 | Returns: |
| 3901 | (retcode of last operation, output log of last operation). |
| 3902 | """ |
| 3903 | assert pending_ref.startswith('refs/'), pending_ref |
| 3904 | local_pending_ref = 'refs/git-cl/' + pending_ref[len('refs/'):] |
| 3905 | cherry = RunGit(['rev-parse', 'HEAD']).strip() |
| 3906 | code = 0 |
| 3907 | out = '' |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3908 | max_attempts = 3 |
| 3909 | attempts_left = max_attempts |
| 3910 | while attempts_left: |
| 3911 | if attempts_left != max_attempts: |
| 3912 | print 'Retrying, %d attempts left...' % (attempts_left - 1,) |
| 3913 | attempts_left -= 1 |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3914 | |
| 3915 | # Fetch. Retry fetch errors. |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3916 | print 'Fetching pending ref %s...' % pending_ref |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3917 | code, out = RunGitWithCode( |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3918 | ['retry', 'fetch', remote, '+%s:%s' % (pending_ref, local_pending_ref)]) |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3919 | if code: |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3920 | print 'Fetch failed with exit code %d.' % code |
| 3921 | if out.strip(): |
| 3922 | print out.strip() |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3923 | continue |
| 3924 | |
| 3925 | # Try to cherry pick. Abort on merge conflicts. |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3926 | print 'Cherry-picking commit on top of pending ref...' |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3927 | RunGitWithCode(['checkout', local_pending_ref], suppress_stderr=True) |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3928 | code, out = RunGitWithCode(['cherry-pick', cherry]) |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3929 | if code: |
| 3930 | print ( |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3931 | 'Your patch doesn\'t apply cleanly to ref \'%s\', ' |
| 3932 | 'the following files have merge conflicts:' % pending_ref) |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3933 | print RunGit(['diff', '--name-status', '--diff-filter=U']).strip() |
| 3934 | print 'Please rebase your patch and try again.' |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3935 | RunGitWithCode(['cherry-pick', '--abort']) |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3936 | return code, out |
| 3937 | |
| 3938 | # Applied cleanly, try to push now. Retry on error (flake or non-ff push). |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3939 | print 'Pushing commit to %s... It can take a while.' % pending_ref |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3940 | code, out = RunGitWithCode( |
| 3941 | ['retry', 'push', '--porcelain', remote, 'HEAD:%s' % pending_ref]) |
| 3942 | if code == 0: |
| 3943 | # Success. |
iannucci@chromium.org | e6896b5 | 2014-08-29 01:38:03 +0000 | [diff] [blame] | 3944 | print 'Commit pushed to pending ref successfully!' |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3945 | return code, out |
| 3946 | |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3947 | print 'Push failed with exit code %d.' % code |
| 3948 | if out.strip(): |
| 3949 | print out.strip() |
| 3950 | if IsFatalPushFailure(out): |
| 3951 | print ( |
| 3952 | 'Fatal push error. Make sure your .netrc credentials and git ' |
| 3953 | 'user.email are correct and you have push access to the repo.') |
| 3954 | return code, out |
| 3955 | |
| 3956 | print 'All attempts to push to pending ref failed.' |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3957 | return code, out |
| 3958 | |
| 3959 | |
vadimsh@chromium.org | 749fbd9 | 2014-08-26 21:57:53 +0000 | [diff] [blame] | 3960 | def IsFatalPushFailure(push_stdout): |
| 3961 | """True if retrying push won't help.""" |
| 3962 | return '(prohibited by Gerrit)' in push_stdout |
| 3963 | |
| 3964 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 3965 | @subcommand.usage('[upstream branch to apply against]') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3966 | def CMDdcommit(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 3967 | """Commits the current changelist via git-svn.""" |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3968 | if not settings.GetIsGitSvn(): |
tandrii@chromium.org | 09d7a6a | 2016-03-04 15:44:48 +0000 | [diff] [blame] | 3969 | if git_footers.get_footer_svn_id(): |
mmoss@chromium.org | f0e4152 | 2015-06-10 19:52:01 +0000 | [diff] [blame] | 3970 | # If it looks like previous commits were mirrored with git-svn. |
| 3971 | message = """This repository appears to be a git-svn mirror, but no |
| 3972 | upstream SVN master is set. You probably need to run 'git auto-svn' once.""" |
| 3973 | else: |
| 3974 | message = """This doesn't appear to be an SVN repository. |
| 3975 | If your project has a true, writeable git repository, you probably want to run |
| 3976 | 'git cl land' instead. |
| 3977 | If your project has a git mirror of an upstream SVN master, you probably need |
| 3978 | to run 'git svn init'. |
| 3979 | |
| 3980 | Using the wrong command might cause your commit to appear to succeed, and the |
| 3981 | review to be closed, without actually landing upstream. If you choose to |
| 3982 | proceed, please verify that the commit lands upstream as expected.""" |
thakis@chromium.org | cde3bb6 | 2011-01-20 01:16:14 +0000 | [diff] [blame] | 3983 | print(message) |
maruel@chromium.org | 9054173 | 2011-04-01 17:54:18 +0000 | [diff] [blame] | 3984 | ask_for_data('[Press enter to dcommit or ctrl-C to quit]') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3985 | return SendUpstream(parser, args, 'dcommit') |
| 3986 | |
| 3987 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 3988 | @subcommand.usage('[upstream branch to apply against]') |
pgervais@chromium.org | cee6dc4 | 2014-05-07 17:04:03 +0000 | [diff] [blame] | 3989 | def CMDland(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 3990 | """Commits the current changelist via git.""" |
tandrii@chromium.org | 09d7a6a | 2016-03-04 15:44:48 +0000 | [diff] [blame] | 3991 | if settings.GetIsGitSvn() or git_footers.get_footer_svn_id(): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3992 | print('This appears to be an SVN repository.') |
| 3993 | print('Are you sure you didn\'t mean \'git cl dcommit\'?') |
mmoss@chromium.org | f0e4152 | 2015-06-10 19:52:01 +0000 | [diff] [blame] | 3994 | print('(Ignore if this is the first commit after migrating from svn->git)') |
maruel@chromium.org | 9054173 | 2011-04-01 17:54:18 +0000 | [diff] [blame] | 3995 | ask_for_data('[Press enter to push or ctrl-C to quit]') |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 3996 | return SendUpstream(parser, args, 'land') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3997 | |
| 3998 | |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 3999 | @subcommand.usage('<patch url or issue id or issue url>') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4000 | def CMDpatch(parser, args): |
marq@chromium.org | e5e5900 | 2013-10-02 23:21:25 +0000 | [diff] [blame] | 4001 | """Patches in a code review.""" |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4002 | parser.add_option('-b', dest='newbranch', |
| 4003 | help='create a new branch off trunk for the patch') |
qsr@chromium.org | 1ef44af | 2013-10-16 16:24:32 +0000 | [diff] [blame] | 4004 | parser.add_option('-f', '--force', action='store_true', |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4005 | help='with -b, clobber any existing branch') |
qsr@chromium.org | 1ef44af | 2013-10-16 16:24:32 +0000 | [diff] [blame] | 4006 | parser.add_option('-d', '--directory', action='store', metavar='DIR', |
| 4007 | help='Change to the directory DIR immediately, ' |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4008 | 'before doing anything else. Rietveld only.') |
qsr@chromium.org | 1ef44af | 2013-10-16 16:24:32 +0000 | [diff] [blame] | 4009 | parser.add_option('--reject', action='store_true', |
tapted@chromium.org | 6a0b07c | 2013-07-10 01:29:19 +0000 | [diff] [blame] | 4010 | help='failed patches spew .rej files rather than ' |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4011 | 'attempting a 3-way merge. Rietveld only.') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4012 | parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit', |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4013 | help='don\'t commit after patch applies. Rietveld only.') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 4014 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4015 | |
| 4016 | group = optparse.OptionGroup( |
| 4017 | parser, |
| 4018 | 'Options for continuing work on the current issue uploaded from a ' |
| 4019 | 'different clone (e.g. different machine). Must be used independently ' |
| 4020 | 'from the other options. No issue number should be specified, and the ' |
| 4021 | 'branch must have an issue number associated with it') |
| 4022 | group.add_option('--reapply', action='store_true', dest='reapply', |
| 4023 | help='Reset the branch and reapply the issue.\n' |
| 4024 | 'CAUTION: This will undo any local changes in this ' |
| 4025 | 'branch') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 4026 | |
| 4027 | group.add_option('--pull', action='store_true', dest='pull', |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4028 | help='Performs a pull before reapplying.') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 4029 | parser.add_option_group(group) |
| 4030 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4031 | auth.add_auth_options(parser) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4032 | _add_codereview_select_options(parser) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4033 | (options, args) = parser.parse_args(args) |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4034 | _process_codereview_select_options(parser, options) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4035 | auth_config = auth.extract_auth_config_from_options(options) |
| 4036 | |
tandrii@chromium.org | dde6462 | 2016-04-13 17:11:21 +0000 | [diff] [blame] | 4037 | cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4038 | |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 4039 | issue_arg = None |
| 4040 | if options.reapply : |
| 4041 | if len(args) > 0: |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4042 | parser.error('--reapply implies no additional arguments.') |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 4043 | |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 4044 | issue_arg = cl.GetIssue() |
| 4045 | upstream = cl.GetUpstreamBranch() |
| 4046 | if upstream == None: |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4047 | parser.error('No upstream branch specified. Cannot reset branch') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 4048 | |
| 4049 | RunGit(['reset', '--hard', upstream]) |
| 4050 | if options.pull: |
| 4051 | RunGit(['pull']) |
| 4052 | else: |
| 4053 | if len(args) != 1: |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4054 | parser.error('Must specify issue number or url') |
| 4055 | issue_arg = args[0] |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 4056 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4057 | if not issue_arg: |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 4058 | parser.print_help() |
| 4059 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4060 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4061 | if cl.IsGerrit(): |
| 4062 | if options.reject: |
| 4063 | parser.error('--reject is not supported with Gerrit codereview.') |
| 4064 | if options.nocommit: |
| 4065 | parser.error('--nocommit is not supported with Gerrit codereview.') |
| 4066 | if options.directory: |
| 4067 | parser.error('--directory is not supported with Gerrit codereview.') |
| 4068 | |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 4069 | # We don't want uncommitted changes mixed up with the patch. |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 4070 | if git_common.is_dirty_git_tree('patch'): |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 4071 | return 1 |
| 4072 | |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4073 | if options.newbranch: |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 4074 | if options.reapply: |
| 4075 | parser.error("--reapply excludes any option other than --pull") |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4076 | if options.force: |
| 4077 | RunGit(['branch', '-D', options.newbranch], |
| 4078 | stderr=subprocess2.PIPE, error_ok=True) |
| 4079 | RunGit(['checkout', '-b', options.newbranch, |
| 4080 | Changelist().GetUpstreamBranch()]) |
| 4081 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4082 | return cl.CMDPatchIssue(issue_arg, options.reject, options.nocommit, |
| 4083 | options.directory) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4084 | |
| 4085 | |
| 4086 | def CMDrebase(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4087 | """Rebases current branch on top of svn repo.""" |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4088 | # Provide a wrapper for git svn rebase to help avoid accidental |
| 4089 | # git svn dcommit. |
| 4090 | # It's the only command that doesn't use parser at all since we just defer |
| 4091 | # execution to git-svn. |
bratell@opera.com | 82b91cd | 2013-07-09 06:33:41 +0000 | [diff] [blame] | 4092 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 4093 | return RunGitWithCode(['svn', 'rebase'] + args)[1] |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4094 | |
| 4095 | |
jochen@chromium.org | 3ec0d54 | 2014-01-14 20:00:03 +0000 | [diff] [blame] | 4096 | def GetTreeStatus(url=None): |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4097 | """Fetches the tree status and returns either 'open', 'closed', |
| 4098 | 'unknown' or 'unset'.""" |
jochen@chromium.org | 3ec0d54 | 2014-01-14 20:00:03 +0000 | [diff] [blame] | 4099 | url = url or settings.GetTreeStatusUrl(error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4100 | if url: |
| 4101 | status = urllib2.urlopen(url).read().lower() |
| 4102 | if status.find('closed') != -1 or status == '0': |
| 4103 | return 'closed' |
| 4104 | elif status.find('open') != -1 or status == '1': |
| 4105 | return 'open' |
| 4106 | return 'unknown' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4107 | return 'unset' |
| 4108 | |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 4109 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4110 | def GetTreeStatusReason(): |
| 4111 | """Fetches the tree status from a json url and returns the message |
| 4112 | with the reason for the tree to be opened or closed.""" |
msb@chromium.org | bf1a7ba | 2011-02-01 16:21:46 +0000 | [diff] [blame] | 4113 | url = settings.GetTreeStatusUrl() |
| 4114 | json_url = urlparse.urljoin(url, '/current?format=json') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4115 | connection = urllib2.urlopen(json_url) |
| 4116 | status = json.loads(connection.read()) |
| 4117 | connection.close() |
| 4118 | return status['message'] |
| 4119 | |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 4120 | |
sheyang@chromium.org | 2b34d55 | 2014-08-14 22:18:42 +0000 | [diff] [blame] | 4121 | def GetBuilderMaster(bot_list): |
| 4122 | """For a given builder, fetch the master from AE if available.""" |
| 4123 | map_url = 'https://builders-map.appspot.com/' |
| 4124 | try: |
| 4125 | master_map = json.load(urllib2.urlopen(map_url)) |
| 4126 | except urllib2.URLError as e: |
| 4127 | return None, ('Failed to fetch builder-to-master map from %s. Error: %s.' % |
| 4128 | (map_url, e)) |
| 4129 | except ValueError as e: |
| 4130 | return None, ('Invalid json string from %s. Error: %s.' % (map_url, e)) |
| 4131 | if not master_map: |
| 4132 | return None, 'Failed to build master map.' |
| 4133 | |
| 4134 | result_master = '' |
| 4135 | for bot in bot_list: |
| 4136 | builder = bot.split(':', 1)[0] |
| 4137 | master_list = master_map.get(builder, []) |
| 4138 | if not master_list: |
| 4139 | return None, ('No matching master for builder %s.' % builder) |
| 4140 | elif len(master_list) > 1: |
| 4141 | return None, ('The builder name %s exists in multiple masters %s.' % |
| 4142 | (builder, master_list)) |
| 4143 | else: |
| 4144 | cur_master = master_list[0] |
| 4145 | if not result_master: |
| 4146 | result_master = cur_master |
| 4147 | elif result_master != cur_master: |
| 4148 | return None, 'The builders do not belong to the same master.' |
| 4149 | return result_master, None |
| 4150 | |
| 4151 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4152 | def CMDtree(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4153 | """Shows the status of the tree.""" |
dpranke@chromium.org | 97ae58e | 2011-03-18 00:29:20 +0000 | [diff] [blame] | 4154 | _, args = parser.parse_args(args) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4155 | status = GetTreeStatus() |
| 4156 | if 'unset' == status: |
| 4157 | print 'You must configure your tree status URL by running "git cl config".' |
| 4158 | return 2 |
| 4159 | |
| 4160 | print "The tree is %s" % status |
| 4161 | print |
| 4162 | print GetTreeStatusReason() |
| 4163 | if status != 'open': |
| 4164 | return 1 |
| 4165 | return 0 |
| 4166 | |
| 4167 | |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4168 | def CMDtry(parser, args): |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 4169 | """Triggers try jobs through BuildBucket.""" |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4170 | group = optparse.OptionGroup(parser, "Try job options") |
| 4171 | group.add_option( |
| 4172 | "-b", "--bot", action="append", |
| 4173 | help=("IMPORTANT: specify ONE builder per --bot flag. Use it multiple " |
| 4174 | "times to specify multiple builders. ex: " |
phajdan.jr@chromium.org | 5291413 | 2015-01-22 10:37:09 +0000 | [diff] [blame] | 4175 | "'-b win_rel -b win_layout'. See " |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4176 | "the try server waterfall for the builders name and the tests " |
phajdan.jr@chromium.org | 5291413 | 2015-01-22 10:37:09 +0000 | [diff] [blame] | 4177 | "available.")) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4178 | group.add_option( |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4179 | "-m", "--master", default='', |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 4180 | help=("Specify a try master where to run the tries.")) |
hinoka@chromium.org | feb9e2a | 2015-09-25 19:11:09 +0000 | [diff] [blame] | 4181 | group.add_option( "--luci", action='store_true') |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4182 | group.add_option( |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4183 | "-r", "--revision", |
| 4184 | help="Revision to use for the try job; default: the " |
| 4185 | "revision will be determined by the try server; see " |
| 4186 | "its waterfall for more info") |
| 4187 | group.add_option( |
| 4188 | "-c", "--clobber", action="store_true", default=False, |
| 4189 | help="Force a clobber before building; e.g. don't do an " |
| 4190 | "incremental build") |
| 4191 | group.add_option( |
| 4192 | "--project", |
| 4193 | help="Override which project to use. Projects are defined " |
| 4194 | "server-side to define what default bot set to use") |
| 4195 | group.add_option( |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 4196 | "-p", "--property", dest="properties", action="append", default=[], |
| 4197 | help="Specify generic properties in the form -p key1=value1 -p " |
| 4198 | "key2=value2 etc (buildbucket only). The value will be treated as " |
| 4199 | "json if decodable, or as string otherwise.") |
| 4200 | group.add_option( |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4201 | "-n", "--name", help="Try job name; default to current branch name") |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 4202 | group.add_option( |
sheyang@chromium.org | db37557 | 2015-08-17 19:22:23 +0000 | [diff] [blame] | 4203 | "--use-rietveld", action="store_true", default=False, |
| 4204 | help="Use Rietveld to trigger try jobs.") |
| 4205 | group.add_option( |
| 4206 | "--buildbucket-host", default='cr-buildbucket.appspot.com', |
| 4207 | help="Host of buildbucket. The default host is %default.") |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4208 | parser.add_option_group(group) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4209 | auth.add_auth_options(parser) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4210 | options, args = parser.parse_args(args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4211 | auth_config = auth.extract_auth_config_from_options(options) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4212 | |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 4213 | if options.use_rietveld and options.properties: |
| 4214 | parser.error('Properties can only be specified with buildbucket') |
| 4215 | |
| 4216 | # Make sure that all properties are prop=value pairs. |
| 4217 | bad_params = [x for x in options.properties if '=' not in x] |
| 4218 | if bad_params: |
| 4219 | parser.error('Got properties with missing "=": %s' % bad_params) |
| 4220 | |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4221 | if args: |
| 4222 | parser.error('Unknown arguments: %s' % args) |
| 4223 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4224 | cl = Changelist(auth_config=auth_config) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4225 | if not cl.GetIssue(): |
| 4226 | parser.error('Need to upload first') |
| 4227 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 4228 | if cl.IsGerrit(): |
| 4229 | parser.error( |
| 4230 | 'Not yet supported for Gerrit (http://crbug.com/599931).\n' |
| 4231 | 'If your project has Commit Queue, dry run is a workaround:\n' |
| 4232 | ' git cl set-commit --dry-run') |
| 4233 | # Code below assumes Rietveld issue. |
| 4234 | # TODO(tandrii): actually implement for Gerrit http://crbug.com/599931. |
| 4235 | |
jrobbins@chromium.org | 16f10f7 | 2014-06-24 22:14:36 +0000 | [diff] [blame] | 4236 | props = cl.GetIssueProperties() |
agable@chromium.org | 787e306 | 2014-08-20 16:31:19 +0000 | [diff] [blame] | 4237 | if props.get('closed'): |
| 4238 | parser.error('Cannot send tryjobs for a closed CL') |
| 4239 | |
jrobbins@chromium.org | 16f10f7 | 2014-06-24 22:14:36 +0000 | [diff] [blame] | 4240 | if props.get('private'): |
| 4241 | parser.error('Cannot use trybots with private issue') |
| 4242 | |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4243 | if not options.name: |
| 4244 | options.name = cl.GetBranch() |
| 4245 | |
phajdan.jr@chromium.org | 8da7f27 | 2014-03-14 01:28:39 +0000 | [diff] [blame] | 4246 | if options.bot and not options.master: |
sheyang@chromium.org | 2b34d55 | 2014-08-14 22:18:42 +0000 | [diff] [blame] | 4247 | options.master, err_msg = GetBuilderMaster(options.bot) |
| 4248 | if err_msg: |
| 4249 | parser.error('Tryserver master cannot be found because: %s\n' |
| 4250 | 'Please manually specify the tryserver master' |
| 4251 | ', e.g. "-m tryserver.chromium.linux".' % err_msg) |
phajdan.jr@chromium.org | 8da7f27 | 2014-03-14 01:28:39 +0000 | [diff] [blame] | 4252 | |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4253 | def GetMasterMap(): |
phajdan.jr@chromium.org | 5291413 | 2015-01-22 10:37:09 +0000 | [diff] [blame] | 4254 | # Process --bot. |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4255 | if not options.bot: |
| 4256 | change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4257 | |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4258 | # Get try masters from PRESUBMIT.py files. |
| 4259 | masters = presubmit_support.DoGetTryMasters( |
| 4260 | change, |
| 4261 | change.LocalPaths(), |
| 4262 | settings.GetRoot(), |
| 4263 | None, |
| 4264 | None, |
| 4265 | options.verbose, |
| 4266 | sys.stdout) |
| 4267 | if masters: |
| 4268 | return masters |
stip@chromium.org | 43064fd | 2013-12-18 20:07:44 +0000 | [diff] [blame] | 4269 | |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4270 | # Fall back to deprecated method: get try slaves from PRESUBMIT.py files. |
| 4271 | options.bot = presubmit_support.DoGetTrySlaves( |
| 4272 | change, |
| 4273 | change.LocalPaths(), |
| 4274 | settings.GetRoot(), |
| 4275 | None, |
| 4276 | None, |
| 4277 | options.verbose, |
| 4278 | sys.stdout) |
tandrii@chromium.org | 71184c0 | 2016-01-13 15:18:44 +0000 | [diff] [blame] | 4279 | |
| 4280 | if not options.bot: |
| 4281 | # Get try masters from cq.cfg if any. |
| 4282 | # TODO(tandrii): some (but very few) projects store cq.cfg in different |
| 4283 | # location. |
| 4284 | cq_cfg = os.path.join(change.RepositoryRoot(), |
| 4285 | 'infra', 'config', 'cq.cfg') |
| 4286 | if os.path.exists(cq_cfg): |
| 4287 | masters = {} |
machenbach@chromium.org | 5999480 | 2016-01-14 10:10:33 +0000 | [diff] [blame] | 4288 | cq_masters = commit_queue.get_master_builder_map( |
| 4289 | cq_cfg, include_experimental=False, include_triggered=False) |
tandrii@chromium.org | 71184c0 | 2016-01-13 15:18:44 +0000 | [diff] [blame] | 4290 | for master, builders in cq_masters.iteritems(): |
| 4291 | for builder in builders: |
| 4292 | # Skip presubmit builders, because these will fail without LGTM. |
| 4293 | if 'presubmit' not in builder.lower(): |
| 4294 | masters.setdefault(master, {})[builder] = ['defaulttests'] |
| 4295 | if masters: |
| 4296 | return masters |
| 4297 | |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4298 | if not options.bot: |
| 4299 | parser.error('No default try builder to try, use --bot') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4300 | |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4301 | builders_and_tests = {} |
| 4302 | # TODO(machenbach): The old style command-line options don't support |
| 4303 | # multiple try masters yet. |
| 4304 | old_style = filter(lambda x: isinstance(x, basestring), options.bot) |
| 4305 | new_style = filter(lambda x: isinstance(x, tuple), options.bot) |
| 4306 | |
| 4307 | for bot in old_style: |
| 4308 | if ':' in bot: |
phajdan.jr@chromium.org | 5291413 | 2015-01-22 10:37:09 +0000 | [diff] [blame] | 4309 | parser.error('Specifying testfilter is no longer supported') |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4310 | elif ',' in bot: |
| 4311 | parser.error('Specify one bot per --bot flag') |
| 4312 | else: |
tandrii@chromium.org | 3764fa2 | 2015-10-21 16:40:40 +0000 | [diff] [blame] | 4313 | builders_and_tests.setdefault(bot, []) |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4314 | |
| 4315 | for bot, tests in new_style: |
| 4316 | builders_and_tests.setdefault(bot, []).extend(tests) |
| 4317 | |
| 4318 | # Return a master map with one master to be backwards compatible. The |
| 4319 | # master name defaults to an empty string, which will cause the master |
| 4320 | # not to be set on rietveld (deprecated). |
| 4321 | return {options.master: builders_and_tests} |
| 4322 | |
| 4323 | masters = GetMasterMap() |
stip@chromium.org | 43064fd | 2013-12-18 20:07:44 +0000 | [diff] [blame] | 4324 | |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4325 | for builders in masters.itervalues(): |
| 4326 | if any('triggered' in b for b in builders): |
| 4327 | print >> sys.stderr, ( |
| 4328 | 'ERROR You are trying to send a job to a triggered bot. This type of' |
| 4329 | ' bot requires an\ninitial job from a parent (usually a builder). ' |
| 4330 | 'Instead send your job to the parent.\n' |
| 4331 | 'Bot list: %s' % builders) |
| 4332 | return 1 |
ilevy@chromium.org | f3b2123 | 2012-09-24 20:48:55 +0000 | [diff] [blame] | 4333 | |
ilevy@chromium.org | 36e420b | 2013-08-06 23:21:12 +0000 | [diff] [blame] | 4334 | patchset = cl.GetMostRecentPatchset() |
| 4335 | if patchset and patchset != cl.GetPatchset(): |
| 4336 | print( |
| 4337 | '\nWARNING Mismatch between local config and server. Did a previous ' |
| 4338 | 'upload fail?\ngit-cl try always uses latest patchset from rietveld. ' |
| 4339 | 'Continuing using\npatchset %s.\n' % patchset) |
hinoka@chromium.org | feb9e2a | 2015-09-25 19:11:09 +0000 | [diff] [blame] | 4340 | if options.luci: |
| 4341 | trigger_luci_job(cl, masters, options) |
| 4342 | elif not options.use_rietveld: |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 4343 | try: |
| 4344 | trigger_try_jobs(auth_config, cl, options, masters, 'git_cl_try') |
| 4345 | except BuildbucketResponseException as ex: |
| 4346 | print 'ERROR: %s' % ex |
fischman@chromium.org | d246c97 | 2013-12-21 22:47:38 +0000 | [diff] [blame] | 4347 | return 1 |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 4348 | except Exception as e: |
| 4349 | stacktrace = (''.join(traceback.format_stack()) + traceback.format_exc()) |
| 4350 | print 'ERROR: Exception when trying to trigger tryjobs: %s\n%s' % ( |
| 4351 | e, stacktrace) |
| 4352 | return 1 |
| 4353 | else: |
| 4354 | try: |
| 4355 | cl.RpcServer().trigger_distributed_try_jobs( |
| 4356 | cl.GetIssue(), patchset, options.name, options.clobber, |
| 4357 | options.revision, masters) |
| 4358 | except urllib2.HTTPError as e: |
| 4359 | if e.code == 404: |
| 4360 | print('404 from rietveld; ' |
| 4361 | 'did you mean to use "git try" instead of "git cl try"?') |
| 4362 | return 1 |
| 4363 | print('Tried jobs on:') |
machenbach@chromium.org | 58a69cb | 2014-03-01 02:08:29 +0000 | [diff] [blame] | 4364 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 4365 | for (master, builders) in sorted(masters.iteritems()): |
| 4366 | if master: |
| 4367 | print 'Master: %s' % master |
| 4368 | length = max(len(builder) for builder in builders) |
| 4369 | for builder in sorted(builders): |
| 4370 | print ' %*s: %s' % (length, builder, ','.join(builders[builder])) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 4371 | return 0 |
| 4372 | |
| 4373 | |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 4374 | def CMDtry_results(parser, args): |
| 4375 | group = optparse.OptionGroup(parser, "Try job results options") |
| 4376 | group.add_option( |
| 4377 | "-p", "--patchset", type=int, help="patchset number if not current.") |
| 4378 | group.add_option( |
tandrii@chromium.org | 6cf98c8 | 2016-03-15 11:56:00 +0000 | [diff] [blame] | 4379 | "--print-master", action='store_true', help="print master name as well.") |
| 4380 | group.add_option( |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 4381 | "--color", action='store_true', default=setup_color.IS_TTY, |
tandrii@chromium.org | 6cf98c8 | 2016-03-15 11:56:00 +0000 | [diff] [blame] | 4382 | help="force color output, useful when piping output.") |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 4383 | group.add_option( |
| 4384 | "--buildbucket-host", default='cr-buildbucket.appspot.com', |
| 4385 | help="Host of buildbucket. The default host is %default.") |
| 4386 | parser.add_option_group(group) |
| 4387 | auth.add_auth_options(parser) |
| 4388 | options, args = parser.parse_args(args) |
| 4389 | if args: |
| 4390 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
| 4391 | |
| 4392 | auth_config = auth.extract_auth_config_from_options(options) |
| 4393 | cl = Changelist(auth_config=auth_config) |
| 4394 | if not cl.GetIssue(): |
| 4395 | parser.error('Need to upload first') |
| 4396 | |
| 4397 | if not options.patchset: |
| 4398 | options.patchset = cl.GetMostRecentPatchset() |
| 4399 | if options.patchset and options.patchset != cl.GetPatchset(): |
| 4400 | print( |
| 4401 | '\nWARNING Mismatch between local config and server. Did a previous ' |
| 4402 | 'upload fail?\ngit-cl try always uses latest patchset from rietveld. ' |
| 4403 | 'Continuing using\npatchset %s.\n' % options.patchset) |
| 4404 | try: |
| 4405 | jobs = fetch_try_jobs(auth_config, cl, options) |
| 4406 | except BuildbucketResponseException as ex: |
| 4407 | print 'Buildbucket error: %s' % ex |
| 4408 | return 1 |
| 4409 | except Exception as e: |
| 4410 | stacktrace = (''.join(traceback.format_stack()) + traceback.format_exc()) |
| 4411 | print 'ERROR: Exception when trying to fetch tryjobs: %s\n%s' % ( |
| 4412 | e, stacktrace) |
| 4413 | return 1 |
| 4414 | print_tryjobs(options, jobs) |
| 4415 | return 0 |
| 4416 | |
| 4417 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4418 | @subcommand.usage('[new upstream branch]') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4419 | def CMDupstream(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4420 | """Prints or sets the name of the upstream branch, if any.""" |
dpranke@chromium.org | 97ae58e | 2011-03-18 00:29:20 +0000 | [diff] [blame] | 4421 | _, args = parser.parse_args(args) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 4422 | if len(args) > 1: |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 4423 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 4424 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4425 | cl = Changelist() |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 4426 | if args: |
| 4427 | # One arg means set upstream branch. |
bauerb@chromium.org | c9cf90a | 2014-04-28 20:32:31 +0000 | [diff] [blame] | 4428 | branch = cl.GetBranch() |
| 4429 | RunGit(['branch', '--set-upstream', branch, args[0]]) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 4430 | cl = Changelist() |
| 4431 | print "Upstream branch set to " + cl.GetUpstreamBranch() |
bauerb@chromium.org | c9cf90a | 2014-04-28 20:32:31 +0000 | [diff] [blame] | 4432 | |
| 4433 | # Clear configured merge-base, if there is one. |
| 4434 | git_common.remove_merge_base(branch) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 4435 | else: |
| 4436 | print cl.GetUpstreamBranch() |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4437 | return 0 |
| 4438 | |
| 4439 | |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 4440 | def CMDweb(parser, args): |
| 4441 | """Opens the current CL in the web browser.""" |
| 4442 | _, args = parser.parse_args(args) |
| 4443 | if args: |
| 4444 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
| 4445 | |
| 4446 | issue_url = Changelist().GetIssueURL() |
| 4447 | if not issue_url: |
| 4448 | print >> sys.stderr, 'ERROR No issue to open' |
| 4449 | return 1 |
| 4450 | |
| 4451 | webbrowser.open(issue_url) |
| 4452 | return 0 |
| 4453 | |
| 4454 | |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 4455 | def CMDset_commit(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4456 | """Sets the commit bit to trigger the Commit Queue.""" |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 4457 | parser.add_option('-d', '--dry-run', action='store_true', |
| 4458 | help='trigger in dry run mode') |
| 4459 | parser.add_option('-c', '--clear', action='store_true', |
| 4460 | help='stop CQ run, if any') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4461 | auth.add_auth_options(parser) |
| 4462 | options, args = parser.parse_args(args) |
| 4463 | auth_config = auth.extract_auth_config_from_options(options) |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 4464 | if args: |
| 4465 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 4466 | if options.dry_run and options.clear: |
| 4467 | parser.error('Make up your mind: both --dry-run and --clear not allowed') |
| 4468 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4469 | cl = Changelist(auth_config=auth_config) |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 4470 | if options.clear: |
| 4471 | state = _CQState.CLEAR |
| 4472 | elif options.dry_run: |
| 4473 | state = _CQState.DRY_RUN |
| 4474 | else: |
| 4475 | state = _CQState.COMMIT |
| 4476 | if not cl.GetIssue(): |
| 4477 | parser.error('Must upload the issue first') |
| 4478 | cl.SetCQState(state) |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 4479 | return 0 |
| 4480 | |
| 4481 | |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 4482 | def CMDset_close(parser, args): |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4483 | """Closes the issue.""" |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4484 | auth.add_auth_options(parser) |
| 4485 | options, args = parser.parse_args(args) |
| 4486 | auth_config = auth.extract_auth_config_from_options(options) |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 4487 | if args: |
| 4488 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4489 | cl = Changelist(auth_config=auth_config) |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 4490 | # Ensure there actually is an issue to close. |
| 4491 | cl.GetDescription() |
| 4492 | cl.CloseIssue() |
| 4493 | return 0 |
| 4494 | |
| 4495 | |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4496 | def CMDdiff(parser, args): |
wychen@chromium.org | 37b2ec0 | 2015-04-03 00:49:15 +0000 | [diff] [blame] | 4497 | """Shows differences between local tree and last upload.""" |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4498 | auth.add_auth_options(parser) |
| 4499 | options, args = parser.parse_args(args) |
| 4500 | auth_config = auth.extract_auth_config_from_options(options) |
| 4501 | if args: |
| 4502 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 4503 | |
| 4504 | # Uncommitted (staged and unstaged) changes will be destroyed by |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4505 | # "git reset --hard" if there are merging conflicts in CMDPatchIssue(). |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 4506 | # Staged changes would be committed along with the patch from last |
| 4507 | # upload, hence counted toward the "last upload" side in the final |
| 4508 | # diff output, and this is not what we want. |
sbc@chromium.org | 71437c0 | 2015-04-09 19:29:40 +0000 | [diff] [blame] | 4509 | if git_common.is_dirty_git_tree('diff'): |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 4510 | return 1 |
| 4511 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4512 | cl = Changelist(auth_config=auth_config) |
sbc@chromium.org | 78dc984 | 2013-11-25 18:43:44 +0000 | [diff] [blame] | 4513 | issue = cl.GetIssue() |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4514 | branch = cl.GetBranch() |
sbc@chromium.org | 78dc984 | 2013-11-25 18:43:44 +0000 | [diff] [blame] | 4515 | if not issue: |
| 4516 | DieWithError('No issue found for current branch (%s)' % branch) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4517 | TMP_BRANCH = 'git-cl-diff' |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 4518 | base_branch = cl.GetCommonAncestorWithUpstream() |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4519 | |
| 4520 | # Create a new branch based on the merge-base |
| 4521 | RunGit(['checkout', '-q', '-b', TMP_BRANCH, base_branch]) |
tandrii@chromium.org | 534f67a | 2016-04-07 18:47:05 +0000 | [diff] [blame] | 4522 | # Clear cached branch in cl object, to avoid overwriting original CL branch |
| 4523 | # properties. |
| 4524 | cl.ClearBranch() |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4525 | try: |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4526 | rtn = cl.CMDPatchIssue(issue, reject=False, nocommit=False, directory=None) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4527 | if rtn != 0: |
wychen@chromium.org | a872e75 | 2015-04-28 23:42:18 +0000 | [diff] [blame] | 4528 | RunGit(['reset', '--hard']) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4529 | return rtn |
| 4530 | |
wychen@chromium.org | 0692853 | 2015-02-03 02:11:29 +0000 | [diff] [blame] | 4531 | # Switch back to starting branch and diff against the temporary |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4532 | # branch containing the latest rietveld patch. |
wychen@chromium.org | 0692853 | 2015-02-03 02:11:29 +0000 | [diff] [blame] | 4533 | subprocess2.check_call(['git', 'diff', TMP_BRANCH, branch, '--']) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 4534 | finally: |
| 4535 | RunGit(['checkout', '-q', branch]) |
| 4536 | RunGit(['branch', '-D', TMP_BRANCH]) |
| 4537 | |
| 4538 | return 0 |
| 4539 | |
| 4540 | |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 4541 | def CMDowners(parser, args): |
wychen@chromium.org | 37b2ec0 | 2015-04-03 00:49:15 +0000 | [diff] [blame] | 4542 | """Interactively find the owners for reviewing.""" |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 4543 | parser.add_option( |
| 4544 | '--no-color', |
| 4545 | action='store_true', |
| 4546 | help='Use this option to disable color output') |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4547 | auth.add_auth_options(parser) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 4548 | options, args = parser.parse_args(args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4549 | auth_config = auth.extract_auth_config_from_options(options) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 4550 | |
| 4551 | author = RunGit(['config', 'user.email']).strip() or None |
| 4552 | |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 4553 | cl = Changelist(auth_config=auth_config) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 4554 | |
| 4555 | if args: |
| 4556 | if len(args) > 1: |
| 4557 | parser.error('Unknown args') |
| 4558 | base_branch = args[0] |
| 4559 | else: |
| 4560 | # Default to diffing against the common ancestor of the upstream branch. |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 4561 | base_branch = cl.GetCommonAncestorWithUpstream() |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 4562 | |
| 4563 | change = cl.GetChange(base_branch, None) |
| 4564 | return owners_finder.OwnersFinder( |
| 4565 | [f.LocalPath() for f in |
| 4566 | cl.GetChange(base_branch, None).AffectedFiles()], |
| 4567 | change.RepositoryRoot(), author, |
| 4568 | fopen=file, os_path=os.path, glob=glob.glob, |
| 4569 | disable_color=options.no_color).run() |
| 4570 | |
| 4571 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4572 | def BuildGitDiffCmd(diff_type, upstream_commit, args): |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4573 | """Generates a diff command.""" |
| 4574 | # Generate diff for the current branch's changes. |
| 4575 | diff_cmd = ['diff', '--no-ext-diff', '--no-prefix', diff_type, |
| 4576 | upstream_commit, '--' ] |
| 4577 | |
| 4578 | if args: |
| 4579 | for arg in args: |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4580 | if os.path.isdir(arg) or os.path.isfile(arg): |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4581 | diff_cmd.append(arg) |
| 4582 | else: |
| 4583 | DieWithError('Argument "%s" is not a file or a directory' % arg) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4584 | |
| 4585 | return diff_cmd |
| 4586 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4587 | def MatchingFileType(file_name, extensions): |
| 4588 | """Returns true if the file name ends with one of the given extensions.""" |
| 4589 | 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] | 4590 | |
enne@chromium.org | 555cfe4 | 2014-01-29 18:21:39 +0000 | [diff] [blame] | 4591 | @subcommand.usage('[files or directories to diff]') |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 4592 | def CMDformat(parser, args): |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 4593 | """Runs auto-formatting tools (clang-format etc.) on the diff.""" |
thakis@chromium.org | 9819b1b | 2014-12-09 21:21:53 +0000 | [diff] [blame] | 4594 | CLANG_EXTS = ['.cc', '.cpp', '.h', '.mm', '.proto', '.java'] |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 4595 | GN_EXTS = ['.gn', '.gni'] |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 4596 | parser.add_option('--full', action='store_true', |
| 4597 | help='Reformat the full content of all touched files') |
| 4598 | parser.add_option('--dry-run', action='store_true', |
| 4599 | help='Don\'t modify any file on disk.') |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 4600 | parser.add_option('--python', action='store_true', |
| 4601 | help='Format python code with yapf (experimental).') |
wittman@chromium.org | 04d5a22 | 2014-03-07 18:30:42 +0000 | [diff] [blame] | 4602 | parser.add_option('--diff', action='store_true', |
| 4603 | help='Print diff to stdout rather than modifying files.') |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 4604 | opts, args = parser.parse_args(args) |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 4605 | |
enne@chromium.org | ff7a1fb | 2013-12-10 19:21:41 +0000 | [diff] [blame] | 4606 | # git diff generates paths against the root of the repository. Change |
| 4607 | # 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] | 4608 | rel_base_path = settings.GetRelativeRoot() |
enne@chromium.org | ff7a1fb | 2013-12-10 19:21:41 +0000 | [diff] [blame] | 4609 | if rel_base_path: |
| 4610 | os.chdir(rel_base_path) |
| 4611 | |
digit@chromium.org | 29e4727 | 2013-05-17 17:01:46 +0000 | [diff] [blame] | 4612 | # Grab the merge-base commit, i.e. the upstream commit of the current |
| 4613 | # branch when it was created or the last time it was rebased. This is |
| 4614 | # to cover the case where the user may have called "git fetch origin", |
| 4615 | # moving the origin branch to a newer commit, but hasn't rebased yet. |
| 4616 | upstream_commit = None |
| 4617 | cl = Changelist() |
| 4618 | upstream_branch = cl.GetUpstreamBranch() |
| 4619 | if upstream_branch: |
| 4620 | upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch]) |
| 4621 | upstream_commit = upstream_commit.strip() |
| 4622 | |
| 4623 | if not upstream_commit: |
| 4624 | DieWithError('Could not find base commit for this branch. ' |
| 4625 | 'Are you in detached state?') |
| 4626 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4627 | changed_files_cmd = BuildGitDiffCmd('--name-only', upstream_commit, args) |
| 4628 | diff_output = RunGit(changed_files_cmd) |
| 4629 | diff_files = diff_output.splitlines() |
jkarlin@chromium.org | ad21b92 | 2016-01-28 17:48:42 +0000 | [diff] [blame] | 4630 | # Filter out files deleted by this CL |
| 4631 | 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] | 4632 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4633 | clang_diff_files = [x for x in diff_files if MatchingFileType(x, CLANG_EXTS)] |
| 4634 | python_diff_files = [x for x in diff_files if MatchingFileType(x, ['.py'])] |
| 4635 | 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] | 4636 | 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] | 4637 | |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 4638 | top_dir = os.path.normpath( |
| 4639 | RunGit(["rev-parse", "--show-toplevel"]).rstrip('\n')) |
| 4640 | |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4641 | # Set to 2 to signal to CheckPatchFormatted() that this patch isn't |
| 4642 | # formatted. This is used to block during the presubmit. |
| 4643 | return_value = 0 |
| 4644 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 4645 | if clang_diff_files: |
techtonik@gmail.com | 5573df1 | 2016-04-12 18:34:10 +0000 | [diff] [blame] | 4646 | # Locate the clang-format binary in the checkout |
| 4647 | try: |
| 4648 | clang_format_tool = clang_format.FindClangFormatToolInChromiumTree() |
| 4649 | except clang_format.NotFoundError, e: |
| 4650 | DieWithError(e) |
| 4651 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 4652 | if opts.full: |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4653 | cmd = [clang_format_tool] |
| 4654 | if not opts.dry_run and not opts.diff: |
| 4655 | cmd.append('-i') |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4656 | stdout = RunCommand(cmd + clang_diff_files, cwd=top_dir) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4657 | if opts.diff: |
| 4658 | sys.stdout.write(stdout) |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 4659 | else: |
| 4660 | env = os.environ.copy() |
| 4661 | env['PATH'] = str(os.path.dirname(clang_format_tool)) |
| 4662 | try: |
| 4663 | script = clang_format.FindClangFormatScriptInChromiumTree( |
| 4664 | 'clang-format-diff.py') |
| 4665 | except clang_format.NotFoundError, e: |
| 4666 | DieWithError(e) |
digit@chromium.org | d6ddc1c | 2013-10-25 15:36:32 +0000 | [diff] [blame] | 4667 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 4668 | cmd = [sys.executable, script, '-p0'] |
| 4669 | if not opts.dry_run and not opts.diff: |
| 4670 | cmd.append('-i') |
digit@chromium.org | d6ddc1c | 2013-10-25 15:36:32 +0000 | [diff] [blame] | 4671 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 4672 | diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, clang_diff_files) |
| 4673 | diff_output = RunGit(diff_cmd) |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4674 | |
sammc@chromium.org | 0b35f5d | 2016-02-25 22:39:23 +0000 | [diff] [blame] | 4675 | stdout = RunCommand(cmd, stdin=diff_output, cwd=top_dir, env=env) |
| 4676 | if opts.diff: |
| 4677 | sys.stdout.write(stdout) |
| 4678 | if opts.dry_run and len(stdout) > 0: |
| 4679 | return_value = 2 |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 4680 | |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 4681 | # Similar code to above, but using yapf on .py files rather than clang-format |
| 4682 | # on C/C++ files |
| 4683 | if opts.python: |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 4684 | yapf_tool = gclient_utils.FindExecutable('yapf') |
| 4685 | if yapf_tool is None: |
| 4686 | DieWithError('yapf not found in PATH') |
| 4687 | |
| 4688 | if opts.full: |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4689 | if python_diff_files: |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 4690 | cmd = [yapf_tool] |
| 4691 | if not opts.dry_run and not opts.diff: |
| 4692 | cmd.append('-i') |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4693 | stdout = RunCommand(cmd + python_diff_files, cwd=top_dir) |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 4694 | if opts.diff: |
| 4695 | sys.stdout.write(stdout) |
| 4696 | else: |
| 4697 | # TODO(sbc): yapf --lines mode still has some issues. |
| 4698 | # https://github.com/google/yapf/issues/154 |
| 4699 | DieWithError('--python currently only works with --full') |
| 4700 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4701 | # Dart's formatter does not have the nice property of only operating on |
| 4702 | # modified chunks, so hard code full. |
| 4703 | if dart_diff_files: |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4704 | try: |
| 4705 | command = [dart_format.FindDartFmtToolInChromiumTree()] |
| 4706 | if not opts.dry_run and not opts.diff: |
| 4707 | command.append('-w') |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 4708 | command.extend(dart_diff_files) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4709 | |
ppi@chromium.org | 6593d93 | 2016-03-03 15:41:15 +0000 | [diff] [blame] | 4710 | stdout = RunCommand(command, cwd=top_dir) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4711 | if opts.dry_run and stdout: |
| 4712 | return_value = 2 |
| 4713 | except dart_format.NotFoundError as e: |
erikcorry@chromium.org | 3e44502 | 2015-12-17 09:07:26 +0000 | [diff] [blame] | 4714 | print ('Warning: Unable to check Dart code formatting. Dart SDK not ' + |
| 4715 | 'found in this checkout. Files in other languages are still ' + |
| 4716 | 'formatted.') |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4717 | |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 4718 | # Format GN build files. Always run on full build files for canonical form. |
| 4719 | if gn_diff_files: |
| 4720 | cmd = ['gn', 'format'] |
| 4721 | if not opts.dry_run and not opts.diff: |
| 4722 | cmd.append('--in-place') |
| 4723 | for gn_diff_file in gn_diff_files: |
| 4724 | stdout = RunCommand(cmd + [gn_diff_file], cwd=top_dir) |
| 4725 | if opts.diff: |
| 4726 | sys.stdout.write(stdout) |
| 4727 | |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 4728 | return return_value |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 4729 | |
| 4730 | |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 4731 | @subcommand.usage('<codereview url or issue id>') |
| 4732 | def CMDcheckout(parser, args): |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 4733 | """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] | 4734 | _, args = parser.parse_args(args) |
| 4735 | |
| 4736 | if len(args) != 1: |
| 4737 | parser.print_help() |
| 4738 | return 1 |
| 4739 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 4740 | issue_arg = ParseIssueNumberArgument(args[0]) |
tandrii@chromium.org | de6c9a1 | 2016-04-11 15:33:53 +0000 | [diff] [blame] | 4741 | if not issue_arg.valid: |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 4742 | parser.print_help() |
| 4743 | return 1 |
tandrii@chromium.org | abd27e5 | 2016-04-11 15:43:32 +0000 | [diff] [blame] | 4744 | target_issue = str(issue_arg.issue) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 4745 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 4746 | def find_issues(issueprefix): |
tandrii@chromium.org | 26c8fd2 | 2016-04-11 21:33:21 +0000 | [diff] [blame] | 4747 | output = RunGit(['config', '--local', '--get-regexp', |
| 4748 | r'branch\..*\.%s' % issueprefix], |
| 4749 | error_ok=True) |
| 4750 | for key, issue in [x.split() for x in output.splitlines()]: |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 4751 | if issue == target_issue: |
| 4752 | yield re.sub(r'branch\.(.*)\.%s' % issueprefix, r'\1', key) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 4753 | |
tandrii@chromium.org | 5df290f | 2016-04-11 16:12:29 +0000 | [diff] [blame] | 4754 | branches = [] |
| 4755 | for cls in _CODEREVIEW_IMPLEMENTATIONS.values(): |
tandrii@chromium.org | d03bc63 | 2016-04-12 14:17:26 +0000 | [diff] [blame] | 4756 | branches.extend(find_issues(cls.IssueSettingSuffix())) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 4757 | if len(branches) == 0: |
| 4758 | print 'No branch found for issue %s.' % target_issue |
| 4759 | return 1 |
| 4760 | if len(branches) == 1: |
| 4761 | RunGit(['checkout', branches[0]]) |
| 4762 | else: |
| 4763 | print 'Multiple branches match issue %s:' % target_issue |
| 4764 | for i in range(len(branches)): |
| 4765 | print '%d: %s' % (i, branches[i]) |
| 4766 | which = raw_input('Choose by index: ') |
| 4767 | try: |
| 4768 | RunGit(['checkout', branches[int(which)]]) |
| 4769 | except (IndexError, ValueError): |
| 4770 | print 'Invalid selection, not checking out any branch.' |
| 4771 | return 1 |
| 4772 | |
| 4773 | return 0 |
| 4774 | |
| 4775 | |
maruel@chromium.org | 29404b5 | 2014-09-08 22:58:00 +0000 | [diff] [blame] | 4776 | def CMDlol(parser, args): |
| 4777 | # This command is intentionally undocumented. |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 4778 | print zlib.decompress(base64.b64decode( |
| 4779 | 'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE' |
| 4780 | 'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9' |
| 4781 | 'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W' |
| 4782 | 'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY')) |
maruel@chromium.org | 29404b5 | 2014-09-08 22:58:00 +0000 | [diff] [blame] | 4783 | return 0 |
| 4784 | |
| 4785 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4786 | class OptionParser(optparse.OptionParser): |
| 4787 | """Creates the option parse and add --verbose support.""" |
| 4788 | def __init__(self, *args, **kwargs): |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4789 | optparse.OptionParser.__init__( |
| 4790 | self, *args, prog='git cl', version=__version__, **kwargs) |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4791 | self.add_option( |
| 4792 | '-v', '--verbose', action='count', default=0, |
| 4793 | help='Use 2 times for more debugging info') |
| 4794 | |
| 4795 | def parse_args(self, args=None, values=None): |
| 4796 | options, args = optparse.OptionParser.parse_args(self, args, values) |
| 4797 | levels = [logging.WARNING, logging.INFO, logging.DEBUG] |
| 4798 | logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)]) |
| 4799 | return options, args |
| 4800 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4801 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4802 | def main(argv): |
maruel@chromium.org | 82798cb | 2012-02-23 18:16:12 +0000 | [diff] [blame] | 4803 | if sys.hexversion < 0x02060000: |
| 4804 | print >> sys.stderr, ( |
| 4805 | '\nYour python version %s is unsupported, please upgrade.\n' % |
| 4806 | sys.version.split(' ', 1)[0]) |
| 4807 | return 2 |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 4808 | |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 4809 | # Reload settings. |
| 4810 | global settings |
| 4811 | settings = Settings() |
| 4812 | |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4813 | colorize_CMDstatus_doc() |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4814 | dispatcher = subcommand.CommandDispatcher(__name__) |
| 4815 | try: |
| 4816 | return dispatcher.execute(OptionParser(), argv) |
vadimsh@chromium.org | eed4df3 | 2015-04-10 21:30:20 +0000 | [diff] [blame] | 4817 | except auth.AuthenticationError as e: |
| 4818 | DieWithError(str(e)) |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4819 | except urllib2.HTTPError, e: |
| 4820 | if e.code != 500: |
| 4821 | raise |
| 4822 | DieWithError( |
| 4823 | ('AppEngine is misbehaving and returned HTTP %d, again. Keep faith ' |
| 4824 | '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] | 4825 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4826 | |
| 4827 | |
| 4828 | if __name__ == '__main__': |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 4829 | # These affect sys.stdout so do it outside of main() to simplify mocks in |
| 4830 | # unit testing. |
maruel@chromium.org | 6f09cd9 | 2011-04-01 16:38:12 +0000 | [diff] [blame] | 4831 | fix_encoding.fix_encoding() |
iannucci@chromium.org | 596cd5c | 2016-04-04 21:34:39 +0000 | [diff] [blame] | 4832 | setup_color.init() |
sbc@chromium.org | 013731e | 2015-02-26 18:28:43 +0000 | [diff] [blame] | 4833 | try: |
| 4834 | sys.exit(main(sys.argv[1:])) |
| 4835 | except KeyboardInterrupt: |
| 4836 | sys.stderr.write('interrupted\n') |
| 4837 | sys.exit(1) |