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