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