Josip Sokcevic | 4de5dea | 2022-03-23 21:15:14 +0000 | [diff] [blame] | 1 | #!/usr/bin/env vpython3 |
Andrii Shyshkalov | 0d2dea0 | 2017-07-17 15:17:55 +0200 | [diff] [blame] | 2 | # Copyright (c) 2013 The Chromium Authors. All rights reserved. |
maruel@chromium.org | 725f1c3 | 2011-04-01 20:24:54 +0000 | [diff] [blame] | 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 6 | # Copyright (C) 2008 Evan Martin <martine@danga.com> |
Andrii Shyshkalov | 03da150 | 2018-10-15 03:42:34 +0000 | [diff] [blame] | 7 | """A git-command for integrating reviews on Gerrit.""" |
maruel@chromium.org | 725f1c3 | 2011-04-01 20:24:54 +0000 | [diff] [blame] | 8 | |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 9 | import base64 |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 10 | import collections |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 11 | import datetime |
Brian Sheedy | b4307d5 | 2019-12-02 19:18:17 +0000 | [diff] [blame] | 12 | import fnmatch |
Edward Lemur | 202c559 | 2019-10-21 22:44:52 +0000 | [diff] [blame] | 13 | import httplib2 |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 14 | import itertools |
maruel@chromium.org | 4f6852c | 2012-04-20 20:39:20 +0000 | [diff] [blame] | 15 | import json |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 16 | import logging |
calamity@chromium.org | cf19748 | 2016-04-29 20:15:53 +0000 | [diff] [blame] | 17 | import multiprocessing |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 18 | import optparse |
| 19 | import os |
| 20 | import re |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 21 | import shutil |
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 |
Aaron Gable | 9a03ae0 | 2017-11-03 11:31:07 -0700 | [diff] [blame] | 24 | import tempfile |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 25 | import textwrap |
Edward Lemur | fec80c4 | 2018-11-01 23:14:14 +0000 | [diff] [blame] | 26 | import time |
Gavin Mak | 7f5b53f | 2023-09-07 18:13:01 +0000 | [diff] [blame] | 27 | import urllib.parse |
| 28 | import urllib.request |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 29 | import uuid |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 30 | import webbrowser |
thakis@chromium.org | 3421c99 | 2014-11-02 02:20:32 +0000 | [diff] [blame] | 31 | import zlib |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 32 | |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 33 | from third_party import colorama |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 34 | from typing import Any |
| 35 | from typing import List |
| 36 | from typing import Mapping |
| 37 | from typing import NoReturn |
Daniel Cheng | 66d0f15 | 2023-08-29 23:21:58 +0000 | [diff] [blame] | 38 | from typing import Optional |
| 39 | from typing import Sequence |
| 40 | from typing import Tuple |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 41 | import auth |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 42 | import clang_format |
maruel@chromium.org | 6f09cd9 | 2011-04-01 16:38:12 +0000 | [diff] [blame] | 43 | import fix_encoding |
maruel@chromium.org | 0e0436a | 2011-10-25 13:32:41 +0000 | [diff] [blame] | 44 | import gclient_utils |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 45 | import gerrit_util |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 46 | import git_common |
tandrii@chromium.org | 09d7a6a | 2016-03-04 15:44:48 +0000 | [diff] [blame] | 47 | import git_footers |
Edward Lemur | 8515328 | 2020-02-14 22:06:29 +0000 | [diff] [blame] | 48 | import git_new_branch |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 49 | import metrics |
Edward Lesmes | 93277a7 | 2018-10-18 22:04:26 +0000 | [diff] [blame] | 50 | import metrics_utils |
Edward Lesmes | eeca9c6 | 2020-11-20 00:00:17 +0000 | [diff] [blame] | 51 | import owners_client |
iannucci@chromium.org | 9e84927 | 2014-04-04 00:31:55 +0000 | [diff] [blame] | 52 | import owners_finder |
Lei Zhang | b8c62cf | 2020-07-15 20:09:37 +0000 | [diff] [blame] | 53 | import presubmit_canned_checks |
Josip Sokcevic | 7958e30 | 2023-03-01 23:02:21 +0000 | [diff] [blame] | 54 | import presubmit_support |
Lukasz Anforowicz | b4d3954 | 2021-09-30 23:39:25 +0000 | [diff] [blame] | 55 | import rustfmt |
Josip Sokcevic | 7958e30 | 2023-03-01 23:02:21 +0000 | [diff] [blame] | 56 | import scm |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 57 | import setup_color |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 58 | import split_cl |
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 |
Olivier Robin | 0a6b544 | 2022-04-07 07:25:04 +0000 | [diff] [blame] | 61 | import swift_format |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 62 | import watchlists |
| 63 | |
Edward Lemur | 79d4f99 | 2019-11-11 23:49:02 +0000 | [diff] [blame] | 64 | |
tandrii | 7400cf0 | 2016-06-21 08:48:07 -0700 | [diff] [blame] | 65 | __version__ = '2.0' |
maruel@chromium.org | 2a74d37 | 2011-03-29 19:05:50 +0000 | [diff] [blame] | 66 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 67 | # TODO: Should fix these warnings. |
| 68 | # pylint: disable=line-too-long |
| 69 | |
Edward Lemur | 0f58ae4 | 2019-04-30 17:24:12 +0000 | [diff] [blame] | 70 | # Traces for git push will be stored in a traces directory inside the |
| 71 | # depot_tools checkout. |
| 72 | DEPOT_TOOLS = os.path.dirname(os.path.abspath(__file__)) |
| 73 | TRACES_DIR = os.path.join(DEPOT_TOOLS, 'traces') |
Edward Lemur | 227d510 | 2020-02-25 23:45:35 +0000 | [diff] [blame] | 74 | PRESUBMIT_SUPPORT = os.path.join(DEPOT_TOOLS, 'presubmit_support.py') |
Edward Lemur | 0f58ae4 | 2019-04-30 17:24:12 +0000 | [diff] [blame] | 75 | |
| 76 | # When collecting traces, Git hashes will be reduced to 6 characters to reduce |
| 77 | # the size after compression. |
| 78 | GIT_HASH_RE = re.compile(r'\b([a-f0-9]{6})[a-f0-9]{34}\b', flags=re.I) |
| 79 | # Used to redact the cookies from the gitcookies file. |
| 80 | GITCOOKIES_REDACT_RE = re.compile(r'1/.*') |
| 81 | |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 82 | MAX_ATTEMPTS = 3 |
| 83 | |
Edward Lemur | 1b52d87 | 2019-05-09 21:12:12 +0000 | [diff] [blame] | 84 | # The maximum number of traces we will keep. Multiplied by 3 since we store |
| 85 | # 3 files per trace. |
| 86 | MAX_TRACES = 3 * 10 |
Edward Lemur | 5737f02 | 2019-05-17 01:24:00 +0000 | [diff] [blame] | 87 | # Message to be displayed to the user to inform where to find the traces for a |
| 88 | # git-cl upload execution. |
Edward Lemur | 0f58ae4 | 2019-04-30 17:24:12 +0000 | [diff] [blame] | 89 | TRACES_MESSAGE = ( |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 90 | '\n' |
| 91 | 'The traces of this git-cl execution have been recorded at:\n' |
| 92 | ' %(trace_name)s-traces.zip\n' |
| 93 | 'Copies of your gitcookies file and git config have been recorded at:\n' |
| 94 | ' %(trace_name)s-git-info.zip\n') |
Edward Lemur | 1b52d87 | 2019-05-09 21:12:12 +0000 | [diff] [blame] | 95 | # Format of the message to be stored as part of the traces to give developers a |
| 96 | # better context when they go through traces. |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 97 | TRACES_README_FORMAT = ('Date: %(now)s\n' |
| 98 | '\n' |
| 99 | 'Change: https://%(gerrit_host)s/q/%(change_id)s\n' |
| 100 | 'Title: %(title)s\n' |
| 101 | '\n' |
| 102 | '%(description)s\n' |
| 103 | '\n' |
| 104 | 'Execution time: %(execution_time)s\n' |
| 105 | 'Exit code: %(exit_code)s\n') + TRACES_MESSAGE |
Edward Lemur | 0f58ae4 | 2019-04-30 17:24:12 +0000 | [diff] [blame] | 106 | |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 107 | POSTUPSTREAM_HOOK = '.git/hooks/post-cl-land' |
Henrique Ferreiro | ff24962 | 2019-11-28 23:19:29 +0000 | [diff] [blame] | 108 | DESCRIPTION_BACKUP_FILE = '.git_cl_description_backup' |
rmistry@google.com | c68112d | 2015-03-03 12:48:06 +0000 | [diff] [blame] | 109 | REFS_THAT_ALIAS_TO_OTHER_REFS = { |
Josip Sokcevic | 7e133ff | 2021-07-13 17:44:53 +0000 | [diff] [blame] | 110 | 'refs/remotes/origin/lkgr': 'refs/remotes/origin/main', |
| 111 | 'refs/remotes/origin/lkcr': 'refs/remotes/origin/main', |
rmistry@google.com | c68112d | 2015-03-03 12:48:06 +0000 | [diff] [blame] | 112 | } |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 113 | |
Josip Sokcevic | c39ab99 | 2020-09-24 20:09:15 +0000 | [diff] [blame] | 114 | DEFAULT_OLD_BRANCH = 'refs/remotes/origin/master' |
| 115 | DEFAULT_NEW_BRANCH = 'refs/remotes/origin/main' |
| 116 | |
Joanna Wang | a8db0cb | 2023-01-24 15:43:17 +0000 | [diff] [blame] | 117 | DEFAULT_BUILDBUCKET_HOST = 'cr-buildbucket.appspot.com' |
| 118 | |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 119 | # Valid extensions for files we want to lint. |
| 120 | DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)" |
| 121 | DEFAULT_LINT_IGNORE_REGEX = r"$^" |
| 122 | |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 123 | # File name for yapf style config files. |
| 124 | YAPF_CONFIG_FILENAME = '.style.yapf' |
| 125 | |
Edward Lesmes | 50da770 | 2020-03-30 19:23:43 +0000 | [diff] [blame] | 126 | # The issue, patchset and codereview server are stored on git config for each |
| 127 | # branch under branch.<branch-name>.<config-key>. |
| 128 | ISSUE_CONFIG_KEY = 'gerritissue' |
| 129 | PATCHSET_CONFIG_KEY = 'gerritpatchset' |
| 130 | CODEREVIEW_SERVER_CONFIG_KEY = 'gerritserver' |
Gavin Mak | be2e926 | 2022-11-08 23:41:55 +0000 | [diff] [blame] | 131 | # When using squash workflow, _CMDUploadChange doesn't simply push the commit(s) |
| 132 | # you make to Gerrit. Instead, it creates a new commit object that contains all |
| 133 | # changes you've made, diffed against a parent/merge base. |
| 134 | # This is the hash of the new squashed commit and you can find this on Gerrit. |
| 135 | GERRIT_SQUASH_HASH_CONFIG_KEY = 'gerritsquashhash' |
| 136 | # This is the latest uploaded local commit hash. |
| 137 | LAST_UPLOAD_HASH_CONFIG_KEY = 'last-upload-hash' |
Edward Lesmes | 50da770 | 2020-03-30 19:23:43 +0000 | [diff] [blame] | 138 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 139 | # Shortcut since it quickly becomes repetitive. |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 140 | Fore = colorama.Fore |
maruel@chromium.org | 9054173 | 2011-04-01 17:54:18 +0000 | [diff] [blame] | 141 | |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 142 | # Initialized in main() |
| 143 | settings = None |
| 144 | |
Andrii Shyshkalov | 768f1d8 | 2016-12-08 15:10:13 +0100 | [diff] [blame] | 145 | # Used by tests/git_cl_test.py to add extra logging. |
| 146 | # Inside the weirdly failing test, add this: |
| 147 | # >>> self.mock(git_cl, '_IS_BEING_TESTED', True) |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 148 | # And scroll up to see the stack trace printed. |
Andrii Shyshkalov | 768f1d8 | 2016-12-08 15:10:13 +0100 | [diff] [blame] | 149 | _IS_BEING_TESTED = False |
| 150 | |
Garrett Beaty | 08bb5c4 | 2022-09-21 17:34:20 +0000 | [diff] [blame] | 151 | _GOOGLESOURCE = 'googlesource.com' |
maruel@chromium.org | ddd5941 | 2011-11-30 14:20:38 +0000 | [diff] [blame] | 152 | |
Andrii Shyshkalov | 1ee78cd | 2020-03-12 01:31:53 +0000 | [diff] [blame] | 153 | _KNOWN_GERRIT_TO_SHORT_URLS = { |
| 154 | 'https://chrome-internal-review.googlesource.com': 'https://crrev.com/i', |
| 155 | 'https://chromium-review.googlesource.com': 'https://crrev.com/c', |
| 156 | } |
Andrii Shyshkalov | 8aebb60 | 2020-04-16 22:10:27 +0000 | [diff] [blame] | 157 | assert len(_KNOWN_GERRIT_TO_SHORT_URLS) == len( |
| 158 | set(_KNOWN_GERRIT_TO_SHORT_URLS.values())), 'must have unique values' |
Andrii Shyshkalov | 1ee78cd | 2020-03-12 01:31:53 +0000 | [diff] [blame] | 159 | |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 160 | # Maximum number of branches in a stack that can be traversed and uploaded |
| 161 | # at once. Picked arbitrarily. |
| 162 | _MAX_STACKED_BRANCHES_UPLOAD = 20 |
| 163 | |
Joanna Wang | 892f2ce | 2023-03-14 21:39:47 +0000 | [diff] [blame] | 164 | # Environment variable to indicate if user is participating in the stcked |
| 165 | # changes dogfood. |
| 166 | DOGFOOD_STACKED_CHANGES_VAR = 'DOGFOOD_STACKED_CHANGES' |
| 167 | |
| 168 | |
Josip Sokcevic | f736cab | 2020-10-20 23:41:38 +0000 | [diff] [blame] | 169 | class GitPushError(Exception): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 170 | pass |
Josip Sokcevic | f736cab | 2020-10-20 23:41:38 +0000 | [diff] [blame] | 171 | |
| 172 | |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 173 | def DieWithError(message, change_desc=None) -> NoReturn: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 174 | if change_desc: |
| 175 | SaveDescriptionBackup(change_desc) |
| 176 | print('\n ** Content of CL description **\n' + '=' * 72 + '\n' + |
| 177 | change_desc.description + '\n' + '=' * 72 + '\n') |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 178 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 179 | print(message, file=sys.stderr) |
| 180 | sys.exit(1) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 181 | |
| 182 | |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 183 | def SaveDescriptionBackup(change_desc): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 184 | backup_path = os.path.join(DEPOT_TOOLS, DESCRIPTION_BACKUP_FILE) |
| 185 | print('\nsaving CL description to %s\n' % backup_path) |
| 186 | with open(backup_path, 'wb') as backup_file: |
| 187 | backup_file.write(change_desc.description.encode('utf-8')) |
Christopher Lam | f732cd5 | 2017-01-24 12:40:11 +1100 | [diff] [blame] | 188 | |
| 189 | |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 190 | def GetNoGitPagerEnv(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 191 | env = os.environ.copy() |
| 192 | # 'cat' is a magical git string that disables pagers on all platforms. |
| 193 | env['GIT_PAGER'] = 'cat' |
| 194 | return env |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 195 | |
vadimsh@chromium.org | 566a02a | 2014-08-22 01:34:13 +0000 | [diff] [blame] | 196 | |
bsep@chromium.org | 627d900 | 2016-04-29 00:00:52 +0000 | [diff] [blame] | 197 | def RunCommand(args, error_ok=False, error_message=None, shell=False, **kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 198 | try: |
| 199 | stdout = subprocess2.check_output(args, shell=shell, **kwargs) |
| 200 | return stdout.decode('utf-8', 'replace') |
| 201 | except subprocess2.CalledProcessError as e: |
| 202 | logging.debug('Failed running %s', args) |
| 203 | if not error_ok: |
| 204 | message = error_message or e.stdout.decode('utf-8', 'replace') or '' |
| 205 | DieWithError('Command "%s" failed.\n%s' % (' '.join(args), message)) |
| 206 | out = e.stdout.decode('utf-8', 'replace') |
| 207 | if e.stderr: |
| 208 | out += e.stderr.decode('utf-8', 'replace') |
| 209 | return out |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 210 | |
| 211 | |
| 212 | def RunGit(args, **kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 213 | """Returns stdout.""" |
| 214 | return RunCommand(['git'] + args, **kwargs) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 215 | |
| 216 | |
enne@chromium.org | 3b7e15c | 2014-01-21 17:44:47 +0000 | [diff] [blame] | 217 | def RunGitWithCode(args, suppress_stderr=False): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 218 | """Returns return code and stdout.""" |
| 219 | if suppress_stderr: |
| 220 | stderr = subprocess2.DEVNULL |
| 221 | else: |
| 222 | stderr = sys.stderr |
| 223 | try: |
| 224 | (out, _), code = subprocess2.communicate(['git'] + args, |
| 225 | env=GetNoGitPagerEnv(), |
| 226 | stdout=subprocess2.PIPE, |
| 227 | stderr=stderr) |
| 228 | return code, out.decode('utf-8', 'replace') |
| 229 | except subprocess2.CalledProcessError as e: |
| 230 | logging.debug('Failed running %s', ['git'] + args) |
| 231 | return e.returncode, e.stdout.decode('utf-8', 'replace') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 232 | |
| 233 | |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 234 | def RunGitSilent(args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 235 | """Returns stdout, suppresses stderr and ignores the return code.""" |
| 236 | return RunGitWithCode(args, suppress_stderr=True)[1] |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 237 | |
| 238 | |
tandrii | 2a16b95 | 2016-10-19 07:09:44 -0700 | [diff] [blame] | 239 | def time_sleep(seconds): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 240 | # Use this so that it can be mocked in tests without interfering with python |
| 241 | # system machinery. |
| 242 | return time.sleep(seconds) |
tandrii | 2a16b95 | 2016-10-19 07:09:44 -0700 | [diff] [blame] | 243 | |
| 244 | |
Edward Lemur | 01f4a4f | 2018-11-03 00:40:38 +0000 | [diff] [blame] | 245 | def time_time(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 246 | # Use this so that it can be mocked in tests without interfering with python |
| 247 | # system machinery. |
| 248 | return time.time() |
Edward Lemur | 01f4a4f | 2018-11-03 00:40:38 +0000 | [diff] [blame] | 249 | |
| 250 | |
Edward Lemur | 1b52d87 | 2019-05-09 21:12:12 +0000 | [diff] [blame] | 251 | def datetime_now(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 252 | # Use this so that it can be mocked in tests without interfering with python |
| 253 | # system machinery. |
| 254 | return datetime.datetime.now() |
Edward Lemur | 1b52d87 | 2019-05-09 21:12:12 +0000 | [diff] [blame] | 255 | |
| 256 | |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 257 | def confirm_or_exit(prefix='', action='confirm'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 258 | """Asks user to press enter to continue or press Ctrl+C to abort.""" |
| 259 | if not prefix or prefix.endswith('\n'): |
| 260 | mid = 'Press' |
| 261 | elif prefix.endswith('.') or prefix.endswith('?'): |
| 262 | mid = ' Press' |
| 263 | elif prefix.endswith(' '): |
| 264 | mid = 'press' |
| 265 | else: |
| 266 | mid = ' press' |
| 267 | gclient_utils.AskForData('%s%s Enter to %s, or Ctrl+C to abort' % |
| 268 | (prefix, mid, action)) |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 269 | |
| 270 | |
| 271 | def ask_for_explicit_yes(prompt): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 272 | """Returns whether user typed 'y' or 'yes' to confirm the given prompt.""" |
| 273 | result = gclient_utils.AskForData(prompt + ' [Yes/No]: ').lower() |
| 274 | while True: |
| 275 | if 'yes'.startswith(result): |
| 276 | return True |
| 277 | if 'no'.startswith(result): |
| 278 | return False |
| 279 | result = gclient_utils.AskForData('Please, type yes or no: ').lower() |
Andrii Shyshkalov | abc26ac | 2017-03-14 14:49:38 +0100 | [diff] [blame] | 280 | |
| 281 | |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 282 | def _get_properties_from_options(options): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 283 | prop_list = getattr(options, 'properties', []) |
| 284 | properties = dict(x.split('=', 1) for x in prop_list) |
| 285 | for key, val in properties.items(): |
| 286 | try: |
| 287 | properties[key] = json.loads(val) |
| 288 | except ValueError: |
| 289 | pass # If a value couldn't be evaluated, treat it as a string. |
| 290 | return properties |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 291 | |
| 292 | |
Edward Lemur | 4c707a2 | 2019-09-24 21:13:43 +0000 | [diff] [blame] | 293 | def _call_buildbucket(http, buildbucket_host, method, request): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 294 | """Calls a buildbucket v2 method and returns the parsed json response.""" |
| 295 | headers = { |
| 296 | 'Accept': 'application/json', |
| 297 | 'Content-Type': 'application/json', |
| 298 | } |
| 299 | request = json.dumps(request) |
| 300 | url = 'https://%s/prpc/buildbucket.v2.Builds/%s' % (buildbucket_host, |
| 301 | method) |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 302 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 303 | logging.info('POST %s with %s' % (url, request)) |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 304 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 305 | attempts = 1 |
| 306 | time_to_sleep = 1 |
| 307 | while True: |
| 308 | response, content = http.request(url, |
| 309 | 'POST', |
| 310 | body=request, |
| 311 | headers=headers) |
| 312 | if response.status == 200: |
| 313 | return json.loads(content[4:]) |
| 314 | if attempts >= MAX_ATTEMPTS or 400 <= response.status < 500: |
| 315 | msg = '%s error when calling POST %s with %s: %s' % ( |
| 316 | response.status, url, request, content) |
| 317 | raise BuildbucketResponseException(msg) |
| 318 | logging.debug('%s error when calling POST %s with %s. ' |
| 319 | 'Sleeping for %d seconds and retrying...' % |
| 320 | (response.status, url, request, time_to_sleep)) |
| 321 | time.sleep(time_to_sleep) |
| 322 | time_to_sleep *= 2 |
| 323 | attempts += 1 |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 324 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 325 | assert False, 'unreachable' |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 326 | |
| 327 | |
Edward Lemur | 6215c79 | 2019-10-03 21:59:05 +0000 | [diff] [blame] | 328 | def _parse_bucket(raw_bucket): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 329 | legacy = True |
| 330 | project = bucket = None |
| 331 | if '/' in raw_bucket: |
| 332 | legacy = False |
| 333 | project, bucket = raw_bucket.split('/', 1) |
| 334 | # Assume luci.<project>.<bucket>. |
| 335 | elif raw_bucket.startswith('luci.'): |
| 336 | project, bucket = raw_bucket[len('luci.'):].split('.', 1) |
| 337 | # Otherwise, assume prefix is also the project name. |
| 338 | elif '.' in raw_bucket: |
| 339 | project = raw_bucket.split('.')[0] |
| 340 | bucket = raw_bucket |
| 341 | # Legacy buckets. |
| 342 | if legacy and project and bucket: |
| 343 | print('WARNING Please use %s/%s to specify the bucket.' % |
| 344 | (project, bucket)) |
| 345 | return project, bucket |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 346 | |
| 347 | |
Garrett Beaty | 08bb5c4 | 2022-09-21 17:34:20 +0000 | [diff] [blame] | 348 | def _canonical_git_googlesource_host(host): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 349 | """Normalizes Gerrit hosts (with '-review') to Git host.""" |
| 350 | assert host.endswith(_GOOGLESOURCE) |
| 351 | # Prefix doesn't include '.' at the end. |
| 352 | prefix = host[:-(1 + len(_GOOGLESOURCE))] |
| 353 | if prefix.endswith('-review'): |
| 354 | prefix = prefix[:-len('-review')] |
| 355 | return prefix + '.' + _GOOGLESOURCE |
Garrett Beaty | 08bb5c4 | 2022-09-21 17:34:20 +0000 | [diff] [blame] | 356 | |
| 357 | |
| 358 | def _canonical_gerrit_googlesource_host(host): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 359 | git_host = _canonical_git_googlesource_host(host) |
| 360 | prefix = git_host.split('.', 1)[0] |
| 361 | return prefix + '-review.' + _GOOGLESOURCE |
Garrett Beaty | 08bb5c4 | 2022-09-21 17:34:20 +0000 | [diff] [blame] | 362 | |
| 363 | |
| 364 | def _get_counterpart_host(host): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 365 | assert host.endswith(_GOOGLESOURCE) |
| 366 | git = _canonical_git_googlesource_host(host) |
| 367 | gerrit = _canonical_gerrit_googlesource_host(git) |
| 368 | return git if gerrit == host else gerrit |
Garrett Beaty | 08bb5c4 | 2022-09-21 17:34:20 +0000 | [diff] [blame] | 369 | |
| 370 | |
Quinten Yearsley | 777660f | 2020-03-04 23:37:06 +0000 | [diff] [blame] | 371 | def _trigger_tryjobs(changelist, jobs, options, patchset): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 372 | """Sends a request to Buildbucket to trigger tryjobs for a changelist. |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 373 | |
| 374 | Args: |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 375 | changelist: Changelist that the tryjobs are associated with. |
Edward Lemur | 4576851 | 2020-03-02 19:03:14 +0000 | [diff] [blame] | 376 | jobs: A list of (project, bucket, builder). |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 377 | options: Command-line options. |
| 378 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 379 | print('Scheduling jobs on:') |
| 380 | for project, bucket, builder in jobs: |
| 381 | print(' %s/%s: %s' % (project, bucket, builder)) |
| 382 | print('To see results here, run: git cl try-results') |
| 383 | print('To see results in browser, run: git cl web') |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 384 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 385 | requests = _make_tryjob_schedule_requests(changelist, jobs, options, |
| 386 | patchset) |
| 387 | if not requests: |
| 388 | return |
Andrii Shyshkalov | aeee6a8 | 2019-10-09 21:56:25 +0000 | [diff] [blame] | 389 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 390 | http = auth.Authenticator().authorize(httplib2.Http()) |
| 391 | http.force_exception_to_status_code = True |
Andrii Shyshkalov | aeee6a8 | 2019-10-09 21:56:25 +0000 | [diff] [blame] | 392 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 393 | batch_request = {'requests': requests} |
| 394 | batch_response = _call_buildbucket(http, DEFAULT_BUILDBUCKET_HOST, 'Batch', |
| 395 | batch_request) |
Andrii Shyshkalov | aeee6a8 | 2019-10-09 21:56:25 +0000 | [diff] [blame] | 396 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 397 | errors = [ |
| 398 | ' ' + response['error']['message'] |
| 399 | for response in batch_response.get('responses', []) |
| 400 | if 'error' in response |
| 401 | ] |
| 402 | if errors: |
| 403 | raise BuildbucketResponseException( |
| 404 | 'Failed to schedule builds for some bots:\n%s' % '\n'.join(errors)) |
Andrii Shyshkalov | aeee6a8 | 2019-10-09 21:56:25 +0000 | [diff] [blame] | 405 | |
| 406 | |
Quinten Yearsley | 777660f | 2020-03-04 23:37:06 +0000 | [diff] [blame] | 407 | def _make_tryjob_schedule_requests(changelist, jobs, options, patchset): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 408 | """Constructs requests for Buildbucket to trigger tryjobs.""" |
| 409 | gerrit_changes = [changelist.GetGerritChange(patchset)] |
| 410 | shared_properties = { |
| 411 | 'category': options.ensure_value('category', 'git_cl_try') |
| 412 | } |
| 413 | if options.ensure_value('clobber', False): |
| 414 | shared_properties['clobber'] = True |
| 415 | shared_properties.update(_get_properties_from_options(options) or {}) |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 416 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 417 | shared_tags = [{'key': 'user_agent', 'value': 'git_cl_try'}] |
| 418 | if options.ensure_value('retry_failed', False): |
| 419 | shared_tags.append({'key': 'retry_failed', 'value': '1'}) |
Andrii Shyshkalov | aeee6a8 | 2019-10-09 21:56:25 +0000 | [diff] [blame] | 420 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 421 | requests = [] |
| 422 | for (project, bucket, builder) in jobs: |
| 423 | properties = shared_properties.copy() |
| 424 | if 'presubmit' in builder.lower(): |
| 425 | properties['dry_run'] = 'true' |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 426 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 427 | requests.append({ |
| 428 | 'scheduleBuild': { |
| 429 | 'requestId': str(uuid.uuid4()), |
| 430 | 'builder': { |
| 431 | 'project': getattr(options, 'project', None) or project, |
| 432 | 'bucket': bucket, |
| 433 | 'builder': builder, |
| 434 | }, |
| 435 | 'gerritChanges': gerrit_changes, |
| 436 | 'properties': properties, |
| 437 | 'tags': [ |
| 438 | { |
| 439 | 'key': 'builder', |
| 440 | 'value': builder |
| 441 | }, |
| 442 | ] + shared_tags, |
| 443 | } |
| 444 | }) |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 445 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 446 | if options.ensure_value('revision', None): |
| 447 | remote, remote_branch = changelist.GetRemoteBranch() |
| 448 | requests[-1]['scheduleBuild']['gitilesCommit'] = { |
| 449 | 'host': |
| 450 | _canonical_git_googlesource_host(gerrit_changes[0]['host']), |
| 451 | 'project': gerrit_changes[0]['project'], |
| 452 | 'id': options.revision, |
| 453 | 'ref': GetTargetRef(remote, remote_branch, None) |
| 454 | } |
Anthony Polito | 1a5fe23 | 2020-01-24 23:17:52 +0000 | [diff] [blame] | 455 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 456 | return requests |
kjellander@chromium.org | 4442454 | 2015-06-02 18:35:29 +0000 | [diff] [blame] | 457 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 458 | |
Quinten Yearsley | 777660f | 2020-03-04 23:37:06 +0000 | [diff] [blame] | 459 | def _fetch_tryjobs(changelist, buildbucket_host, patchset=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 460 | """Fetches tryjobs from buildbucket. |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 461 | |
Edward Lemur | baaf6be | 2019-10-09 18:00:44 +0000 | [diff] [blame] | 462 | Returns list of buildbucket.v2.Build with the try jobs for the changelist. |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 463 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 464 | fields = ['id', 'builder', 'status', 'createTime', 'tags'] |
| 465 | request = { |
| 466 | 'predicate': { |
| 467 | 'gerritChanges': [changelist.GetGerritChange(patchset)], |
| 468 | }, |
| 469 | 'fields': ','.join('builds.*.' + field for field in fields), |
| 470 | } |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 471 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 472 | authenticator = auth.Authenticator() |
| 473 | if authenticator.has_cached_credentials(): |
| 474 | http = authenticator.authorize(httplib2.Http()) |
| 475 | else: |
| 476 | print('Warning: Some results might be missing because %s' % |
| 477 | # Get the message on how to login. |
| 478 | ( |
| 479 | str(auth.LoginRequiredError()), )) |
| 480 | http = httplib2.Http() |
| 481 | http.force_exception_to_status_code = True |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 482 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 483 | response = _call_buildbucket(http, buildbucket_host, 'SearchBuilds', |
| 484 | request) |
| 485 | return response.get('builds', []) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 486 | |
Edward Lemur | 4576851 | 2020-03-02 19:03:14 +0000 | [diff] [blame] | 487 | |
Edward Lemur | 5b929a4 | 2019-10-21 17:57:39 +0000 | [diff] [blame] | 488 | def _fetch_latest_builds(changelist, buildbucket_host, latest_patchset=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 489 | """Fetches builds from the latest patchset that has builds (within |
Quinten Yearsley | 983111f | 2019-09-26 17:18:48 +0000 | [diff] [blame] | 490 | the last few patchsets). |
| 491 | |
| 492 | Args: |
Quinten Yearsley | 983111f | 2019-09-26 17:18:48 +0000 | [diff] [blame] | 493 | changelist (Changelist): The CL to fetch builds for |
| 494 | buildbucket_host (str): Buildbucket host, e.g. "cr-buildbucket.appspot.com" |
Andrii Shyshkalov | 1ad5811 | 2019-10-08 01:46:14 +0000 | [diff] [blame] | 495 | lastest_patchset(int|NoneType): the patchset to start fetching builds from. |
| 496 | If None (default), starts with the latest available patchset. |
Quinten Yearsley | 983111f | 2019-09-26 17:18:48 +0000 | [diff] [blame] | 497 | Returns: |
Edward Lemur | baaf6be | 2019-10-09 18:00:44 +0000 | [diff] [blame] | 498 | A tuple (builds, patchset) where builds is a list of buildbucket.v2.Build, |
| 499 | and patchset is the patchset number where those builds came from. |
Quinten Yearsley | 983111f | 2019-09-26 17:18:48 +0000 | [diff] [blame] | 500 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 501 | assert buildbucket_host |
| 502 | assert changelist.GetIssue(), 'CL must be uploaded first' |
| 503 | assert changelist.GetCodereviewServer(), 'CL must be uploaded first' |
| 504 | if latest_patchset is None: |
| 505 | assert changelist.GetMostRecentPatchset() |
| 506 | ps = changelist.GetMostRecentPatchset() |
| 507 | else: |
| 508 | assert latest_patchset > 0, latest_patchset |
| 509 | ps = latest_patchset |
Andrii Shyshkalov | 1ad5811 | 2019-10-08 01:46:14 +0000 | [diff] [blame] | 510 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 511 | min_ps = max(1, ps - 5) |
| 512 | while ps >= min_ps: |
| 513 | builds = _fetch_tryjobs(changelist, buildbucket_host, patchset=ps) |
| 514 | if len(builds): |
| 515 | return builds, ps |
| 516 | ps -= 1 |
| 517 | return [], 0 |
Quinten Yearsley | 983111f | 2019-09-26 17:18:48 +0000 | [diff] [blame] | 518 | |
| 519 | |
Andrii Shyshkalov | 2cbae8a | 2019-10-11 21:30:27 +0000 | [diff] [blame] | 520 | def _filter_failed_for_retry(all_builds): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 521 | """Returns a list of buckets/builders that are worth retrying. |
Quinten Yearsley | 983111f | 2019-09-26 17:18:48 +0000 | [diff] [blame] | 522 | |
| 523 | Args: |
Quinten Yearsley | 777660f | 2020-03-04 23:37:06 +0000 | [diff] [blame] | 524 | all_builds (list): Builds, in the format returned by _fetch_tryjobs, |
Edward Lemur | baaf6be | 2019-10-09 18:00:44 +0000 | [diff] [blame] | 525 | i.e. a list of buildbucket.v2.Builds which includes status and builder |
| 526 | info. |
Quinten Yearsley | 983111f | 2019-09-26 17:18:48 +0000 | [diff] [blame] | 527 | |
| 528 | Returns: |
Edward Lemur | 4576851 | 2020-03-02 19:03:14 +0000 | [diff] [blame] | 529 | A dict {(proj, bucket): [builders]}. This is the same format accepted by |
Quinten Yearsley | 777660f | 2020-03-04 23:37:06 +0000 | [diff] [blame] | 530 | _trigger_tryjobs. |
Quinten Yearsley | 983111f | 2019-09-26 17:18:48 +0000 | [diff] [blame] | 531 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 532 | grouped = {} |
| 533 | for build in all_builds: |
| 534 | builder = build['builder'] |
| 535 | key = (builder['project'], builder['bucket'], builder['builder']) |
| 536 | grouped.setdefault(key, []).append(build) |
Andrii Shyshkalov | 2cbae8a | 2019-10-11 21:30:27 +0000 | [diff] [blame] | 537 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 538 | jobs = [] |
| 539 | for (project, bucket, builder), builds in grouped.items(): |
| 540 | if 'triggered' in builder: |
| 541 | print( |
| 542 | 'WARNING: Not scheduling %s. Triggered bots require an initial job ' |
| 543 | 'from a parent. Please schedule a manual job for the parent ' |
| 544 | 'instead.') |
| 545 | continue |
| 546 | if any(b['status'] in ('STARTED', 'SCHEDULED') for b in builds): |
| 547 | # Don't retry if any are running. |
| 548 | continue |
| 549 | # If builder had several builds, retry only if the last one failed. |
| 550 | # This is a bit different from CQ, which would re-use *any* SUCCESS-full |
| 551 | # build, but in case of retrying failed jobs retrying a flaky one makes |
| 552 | # sense. |
| 553 | builds = sorted(builds, key=lambda b: b['createTime']) |
| 554 | if builds[-1]['status'] not in ('FAILURE', 'INFRA_FAILURE'): |
| 555 | continue |
| 556 | # Don't retry experimental build previously triggered by CQ. |
| 557 | if any(t['key'] == 'cq_experimental' and t['value'] == 'true' |
| 558 | for t in builds[-1]['tags']): |
| 559 | continue |
| 560 | jobs.append((project, bucket, builder)) |
Edward Lemur | 4576851 | 2020-03-02 19:03:14 +0000 | [diff] [blame] | 561 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 562 | # Sort the jobs to make testing easier. |
| 563 | return sorted(jobs) |
Quinten Yearsley | 983111f | 2019-09-26 17:18:48 +0000 | [diff] [blame] | 564 | |
| 565 | |
Quinten Yearsley | 777660f | 2020-03-04 23:37:06 +0000 | [diff] [blame] | 566 | def _print_tryjobs(options, builds): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 567 | """Prints nicely result of _fetch_tryjobs.""" |
Edward Lemur | baaf6be | 2019-10-09 18:00:44 +0000 | [diff] [blame] | 568 | if not builds: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 569 | print('No tryjobs scheduled.') |
| 570 | return |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 571 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 572 | longest_builder = max(len(b['builder']['builder']) for b in builds) |
| 573 | name_fmt = '{builder:<%d}' % longest_builder |
| 574 | if options.print_master: |
| 575 | longest_bucket = max(len(b['builder']['bucket']) for b in builds) |
| 576 | name_fmt = ('{bucket:>%d} ' % longest_bucket) + name_fmt |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 577 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 578 | builds_by_status = {} |
| 579 | for b in builds: |
| 580 | builds_by_status.setdefault(b['status'], []).append({ |
| 581 | 'id': |
| 582 | b['id'], |
| 583 | 'name': |
| 584 | name_fmt.format(builder=b['builder']['builder'], |
| 585 | bucket=b['builder']['bucket']), |
| 586 | }) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 587 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 588 | sort_key = lambda b: (b['name'], b['id']) |
| 589 | |
| 590 | def print_builds(title, builds, fmt=None, color=None): |
| 591 | """Pop matching builds from `builds` dict and print them.""" |
| 592 | if not builds: |
| 593 | return |
| 594 | |
| 595 | fmt = fmt or '{name} https://ci.chromium.org/b/{id}' |
| 596 | if not options.color or color is None: |
| 597 | colorize = lambda x: x |
| 598 | else: |
| 599 | colorize = lambda x: '%s%s%s' % (color, x, Fore.RESET) |
| 600 | |
| 601 | print(colorize(title)) |
| 602 | for b in sorted(builds, key=sort_key): |
| 603 | print(' ', colorize(fmt.format(**b))) |
| 604 | |
| 605 | total = len(builds) |
| 606 | print_builds('Successes:', |
| 607 | builds_by_status.pop('SUCCESS', []), |
| 608 | color=Fore.GREEN) |
| 609 | print_builds('Infra Failures:', |
| 610 | builds_by_status.pop('INFRA_FAILURE', []), |
| 611 | color=Fore.MAGENTA) |
| 612 | print_builds('Failures:', |
| 613 | builds_by_status.pop('FAILURE', []), |
| 614 | color=Fore.RED) |
| 615 | print_builds('Canceled:', |
| 616 | builds_by_status.pop('CANCELED', []), |
| 617 | fmt='{name}', |
| 618 | color=Fore.MAGENTA) |
| 619 | print_builds('Started:', |
| 620 | builds_by_status.pop('STARTED', []), |
| 621 | color=Fore.YELLOW) |
| 622 | print_builds('Scheduled:', |
| 623 | builds_by_status.pop('SCHEDULED', []), |
| 624 | fmt='{name} id={id}') |
| 625 | # The last section is just in case buildbucket API changes OR there is a |
| 626 | # bug. |
| 627 | print_builds('Other:', |
| 628 | sum(builds_by_status.values(), []), |
| 629 | fmt='{name} id={id}') |
| 630 | print('Total: %d tryjobs' % total) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 631 | |
| 632 | |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 633 | def _ComputeDiffLineRanges(files, upstream_commit): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 634 | """Gets the changed line ranges for each file since upstream_commit. |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 635 | |
| 636 | Parses a git diff on provided files and returns a dict that maps a file name |
| 637 | to an ordered list of range tuples in the form (start_line, count). |
| 638 | Ranges are in the same format as a git diff. |
| 639 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 640 | # If files is empty then diff_output will be a full diff. |
| 641 | if len(files) == 0: |
| 642 | return {} |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 643 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 644 | # Take the git diff and find the line ranges where there are changes. |
| 645 | diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, files, allow_prefix=True) |
| 646 | diff_output = RunGit(diff_cmd) |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 647 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 648 | pattern = r'(?:^diff --git a/(?:.*) b/(.*))|(?:^@@.*\+(.*) @@)' |
| 649 | # 2 capture groups |
| 650 | # 0 == fname of diff file |
| 651 | # 1 == 'diff_start,diff_count' or 'diff_start' |
| 652 | # will match each of |
| 653 | # diff --git a/foo.foo b/foo.py |
| 654 | # @@ -12,2 +14,3 @@ |
| 655 | # @@ -12,2 +17 @@ |
| 656 | # running re.findall on the above string with pattern will give |
| 657 | # [('foo.py', ''), ('', '14,3'), ('', '17')] |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 658 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 659 | curr_file = None |
| 660 | line_diffs = {} |
| 661 | for match in re.findall(pattern, diff_output, flags=re.MULTILINE): |
| 662 | if match[0] != '': |
| 663 | # Will match the second filename in diff --git a/a.py b/b.py. |
| 664 | curr_file = match[0] |
| 665 | line_diffs[curr_file] = [] |
| 666 | else: |
| 667 | # Matches +14,3 |
| 668 | if ',' in match[1]: |
| 669 | diff_start, diff_count = match[1].split(',') |
| 670 | else: |
| 671 | # Single line changes are of the form +12 instead of +12,1. |
| 672 | diff_start = match[1] |
| 673 | diff_count = 1 |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 674 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 675 | diff_start = int(diff_start) |
| 676 | diff_count = int(diff_count) |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 677 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 678 | # If diff_count == 0 this is a removal we can ignore. |
| 679 | line_diffs[curr_file].append((diff_start, diff_count)) |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 680 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 681 | return line_diffs |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 682 | |
| 683 | |
Aiden Benner | 99b0ccb | 2018-11-20 19:53:31 +0000 | [diff] [blame] | 684 | def _FindYapfConfigFile(fpath, yapf_config_cache, top_dir=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 685 | """Checks if a yapf file is in any parent directory of fpath until top_dir. |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 686 | |
Aiden Benner | 99b0ccb | 2018-11-20 19:53:31 +0000 | [diff] [blame] | 687 | Recursively checks parent directories to find yapf file and if no yapf file |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 688 | is found returns None. Uses yapf_config_cache as a cache for previously found |
| 689 | configs. |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 690 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 691 | fpath = os.path.abspath(fpath) |
| 692 | # Return result if we've already computed it. |
| 693 | if fpath in yapf_config_cache: |
| 694 | return yapf_config_cache[fpath] |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 695 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 696 | parent_dir = os.path.dirname(fpath) |
| 697 | if os.path.isfile(fpath): |
| 698 | ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir) |
Aiden Benner | 99b0ccb | 2018-11-20 19:53:31 +0000 | [diff] [blame] | 699 | else: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 700 | # Otherwise fpath is a directory |
| 701 | yapf_file = os.path.join(fpath, YAPF_CONFIG_FILENAME) |
| 702 | if os.path.isfile(yapf_file): |
| 703 | ret = yapf_file |
| 704 | elif fpath in (top_dir, parent_dir): |
| 705 | # If we're at the top level directory, or if we're at root |
| 706 | # there is no provided style. |
| 707 | ret = None |
| 708 | else: |
| 709 | # Otherwise recurse on the current directory. |
| 710 | ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir) |
| 711 | yapf_config_cache[fpath] = ret |
| 712 | return ret |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 713 | |
| 714 | |
Brian Sheedy | b4307d5 | 2019-12-02 19:18:17 +0000 | [diff] [blame] | 715 | def _GetYapfIgnorePatterns(top_dir): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 716 | """Returns all patterns in the .yapfignore file. |
Brian Sheedy | 59b06a8 | 2019-10-14 17:03:29 +0000 | [diff] [blame] | 717 | |
| 718 | yapf is supposed to handle the ignoring of files listed in .yapfignore itself, |
| 719 | but this functionality appears to break when explicitly passing files to |
| 720 | yapf for formatting. According to |
Josip Sokcevic | c39ab99 | 2020-09-24 20:09:15 +0000 | [diff] [blame] | 721 | https://github.com/google/yapf/blob/HEAD/README.rst#excluding-files-from-formatting-yapfignore, |
Brian Sheedy | 59b06a8 | 2019-10-14 17:03:29 +0000 | [diff] [blame] | 722 | the .yapfignore file should be in the directory that yapf is invoked from, |
| 723 | which we assume to be the top level directory in this case. |
| 724 | |
| 725 | Args: |
| 726 | top_dir: The top level directory for the repository being formatted. |
| 727 | |
| 728 | Returns: |
Brian Sheedy | b4307d5 | 2019-12-02 19:18:17 +0000 | [diff] [blame] | 729 | A set of all fnmatch patterns to be ignored. |
Brian Sheedy | 59b06a8 | 2019-10-14 17:03:29 +0000 | [diff] [blame] | 730 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 731 | yapfignore_file = os.path.join(top_dir, '.yapfignore') |
| 732 | ignore_patterns = set() |
| 733 | if not os.path.exists(yapfignore_file): |
| 734 | return ignore_patterns |
Brian Sheedy | 59b06a8 | 2019-10-14 17:03:29 +0000 | [diff] [blame] | 735 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 736 | for line in gclient_utils.FileRead(yapfignore_file).split('\n'): |
| 737 | stripped_line = line.strip() |
| 738 | # Comments and blank lines should be ignored. |
| 739 | if stripped_line.startswith('#') or stripped_line == '': |
| 740 | continue |
| 741 | ignore_patterns.add(stripped_line) |
| 742 | return ignore_patterns |
Brian Sheedy | b4307d5 | 2019-12-02 19:18:17 +0000 | [diff] [blame] | 743 | |
| 744 | |
| 745 | def _FilterYapfIgnoredFiles(filepaths, patterns): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 746 | """Filters out any filepaths that match any of the given patterns. |
Brian Sheedy | b4307d5 | 2019-12-02 19:18:17 +0000 | [diff] [blame] | 747 | |
| 748 | Args: |
| 749 | filepaths: An iterable of strings containing filepaths to filter. |
| 750 | patterns: An iterable of strings containing fnmatch patterns to filter on. |
| 751 | |
| 752 | Returns: |
| 753 | A list of strings containing all the elements of |filepaths| that did not |
| 754 | match any of the patterns in |patterns|. |
| 755 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 756 | # Not inlined so that tests can use the same implementation. |
| 757 | return [ |
| 758 | f for f in filepaths |
| 759 | if not any(fnmatch.fnmatch(f, p) for p in patterns) |
| 760 | ] |
Brian Sheedy | 59b06a8 | 2019-10-14 17:03:29 +0000 | [diff] [blame] | 761 | |
| 762 | |
Daniel Cheng | 66d0f15 | 2023-08-29 23:21:58 +0000 | [diff] [blame] | 763 | def _GetCommitCountSummary(begin_commit: str, |
| 764 | end_commit: str = "HEAD") -> Optional[str]: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 765 | """Generate a summary of the number of commits in (begin_commit, end_commit). |
Daniel Cheng | 66d0f15 | 2023-08-29 23:21:58 +0000 | [diff] [blame] | 766 | |
| 767 | Returns a string containing the summary, or None if the range is empty. |
| 768 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 769 | count = int( |
| 770 | RunGitSilent(['rev-list', '--count', f'{begin_commit}..{end_commit}'])) |
Daniel Cheng | 66d0f15 | 2023-08-29 23:21:58 +0000 | [diff] [blame] | 771 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 772 | if not count: |
| 773 | return None |
Daniel Cheng | 66d0f15 | 2023-08-29 23:21:58 +0000 | [diff] [blame] | 774 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 775 | return f'{count} commit{"s"[:count!=1]}' |
Daniel Cheng | 66d0f15 | 2023-08-29 23:21:58 +0000 | [diff] [blame] | 776 | |
| 777 | |
Aaron Gable | 13101a6 | 2018-02-09 13:20:41 -0800 | [diff] [blame] | 778 | def print_stats(args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 779 | """Prints statistics about the change to the user.""" |
| 780 | # --no-ext-diff is broken in some versions of Git, so try to work around |
| 781 | # this by overriding the environment (but there is still a problem if the |
| 782 | # git config key "diff.external" is used). |
| 783 | env = GetNoGitPagerEnv() |
| 784 | if 'GIT_EXTERNAL_DIFF' in env: |
| 785 | del env['GIT_EXTERNAL_DIFF'] |
iannucci@chromium.org | 7954005 | 2012-10-19 23:15:26 +0000 | [diff] [blame] | 786 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 787 | return subprocess2.call( |
| 788 | ['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] + args, |
| 789 | env=env) |
maruel@chromium.org | 49e3d80 | 2012-07-18 23:54:45 +0000 | [diff] [blame] | 790 | |
| 791 | |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 792 | class BuildbucketResponseException(Exception): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 793 | pass |
sheyang@google.com | 6ebaf78 | 2015-05-12 19:17:54 +0000 | [diff] [blame] | 794 | |
| 795 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 796 | class Settings(object): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 797 | def __init__(self): |
| 798 | self.cc = None |
| 799 | self.root = None |
| 800 | self.tree_status_url = None |
| 801 | self.viewvc_url = None |
| 802 | self.updated = False |
| 803 | self.is_gerrit = None |
| 804 | self.squash_gerrit_uploads = None |
| 805 | self.gerrit_skip_ensure_authenticated = None |
| 806 | self.git_editor = None |
| 807 | self.format_full_by_default = None |
| 808 | self.is_status_commit_order_by_date = None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 809 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 810 | def _LazyUpdateIfNeeded(self): |
| 811 | """Updates the settings from a codereview.settings file, if available.""" |
| 812 | if self.updated: |
| 813 | return |
pgervais@chromium.org | 87884cc | 2014-01-03 22:23:41 +0000 | [diff] [blame] | 814 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 815 | # The only value that actually changes the behavior is |
| 816 | # autoupdate = "false". Everything else means "true". |
| 817 | autoupdate = (scm.GIT.GetConfig(self.GetRoot(), 'rietveld.autoupdate', |
| 818 | '').lower()) |
Edward Lemur | 2696407 | 2020-02-19 19:18:51 +0000 | [diff] [blame] | 819 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 820 | cr_settings_file = FindCodereviewSettingsFile() |
| 821 | if autoupdate != 'false' and cr_settings_file: |
| 822 | LoadCodereviewSettingsFromFile(cr_settings_file) |
| 823 | cr_settings_file.close() |
Edward Lemur | 2696407 | 2020-02-19 19:18:51 +0000 | [diff] [blame] | 824 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 825 | self.updated = True |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 826 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 827 | @staticmethod |
| 828 | def GetRelativeRoot(): |
| 829 | return scm.GIT.GetCheckoutRoot('.') |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 830 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 831 | def GetRoot(self): |
| 832 | if self.root is None: |
| 833 | self.root = os.path.abspath(self.GetRelativeRoot()) |
| 834 | return self.root |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 835 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 836 | def GetTreeStatusUrl(self, error_ok=False): |
| 837 | if not self.tree_status_url: |
| 838 | self.tree_status_url = self._GetConfig('rietveld.tree-status-url') |
| 839 | if self.tree_status_url is None and not error_ok: |
| 840 | DieWithError( |
| 841 | 'You must configure your tree status URL by running ' |
| 842 | '"git cl config".') |
| 843 | return self.tree_status_url |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 844 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 845 | def GetViewVCUrl(self): |
| 846 | if not self.viewvc_url: |
| 847 | self.viewvc_url = self._GetConfig('rietveld.viewvc-url') |
| 848 | return self.viewvc_url |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 849 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 850 | def GetBugPrefix(self): |
| 851 | return self._GetConfig('rietveld.bug-prefix') |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 852 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 853 | def GetRunPostUploadHook(self): |
| 854 | run_post_upload_hook = self._GetConfig('rietveld.run-post-upload-hook') |
| 855 | return run_post_upload_hook == "True" |
rmistry@google.com | 5626a92 | 2015-02-26 14:03:30 +0000 | [diff] [blame] | 856 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 857 | def GetDefaultCCList(self): |
| 858 | return self._GetConfig('rietveld.cc') |
Joanna Wang | c8f23e2 | 2023-01-19 21:18:10 +0000 | [diff] [blame] | 859 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 860 | def GetSquashGerritUploads(self): |
| 861 | """Returns True if uploads to Gerrit should be squashed by default.""" |
| 862 | if self.squash_gerrit_uploads is None: |
| 863 | self.squash_gerrit_uploads = self.GetSquashGerritUploadsOverride() |
| 864 | if self.squash_gerrit_uploads is None: |
| 865 | # Default is squash now (http://crbug.com/611892#c23). |
| 866 | self.squash_gerrit_uploads = self._GetConfig( |
| 867 | 'gerrit.squash-uploads').lower() != 'false' |
| 868 | return self.squash_gerrit_uploads |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 869 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 870 | def GetSquashGerritUploadsOverride(self): |
| 871 | """Return True or False if codereview.settings should be overridden. |
Edward Lesmes | 4de5413 | 2020-05-05 19:41:33 +0000 | [diff] [blame] | 872 | |
| 873 | Returns None if no override has been defined. |
| 874 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 875 | # See also http://crbug.com/611892#c23 |
| 876 | result = self._GetConfig('gerrit.override-squash-uploads').lower() |
| 877 | if result == 'true': |
| 878 | return True |
| 879 | if result == 'false': |
| 880 | return False |
| 881 | return None |
Edward Lesmes | 4de5413 | 2020-05-05 19:41:33 +0000 | [diff] [blame] | 882 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 883 | def GetIsGerrit(self): |
| 884 | """Return True if gerrit.host is set.""" |
| 885 | if self.is_gerrit is None: |
| 886 | self.is_gerrit = bool(self._GetConfig('gerrit.host', False)) |
| 887 | return self.is_gerrit |
Aleksey Khoroshilov | 35ef5ad | 2022-06-03 18:29:25 +0000 | [diff] [blame] | 888 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 889 | def GetGerritSkipEnsureAuthenticated(self): |
| 890 | """Return True if EnsureAuthenticated should not be done for Gerrit |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 891 | uploads.""" |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 892 | if self.gerrit_skip_ensure_authenticated is None: |
| 893 | self.gerrit_skip_ensure_authenticated = self._GetConfig( |
| 894 | 'gerrit.skip-ensure-authenticated').lower() == 'true' |
| 895 | return self.gerrit_skip_ensure_authenticated |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 896 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 897 | def GetGitEditor(self): |
| 898 | """Returns the editor specified in the git config, or None if none is.""" |
| 899 | if self.git_editor is None: |
| 900 | # Git requires single quotes for paths with spaces. We need to |
| 901 | # replace them with double quotes for Windows to treat such paths as |
| 902 | # a single path. |
| 903 | self.git_editor = self._GetConfig('core.editor').replace('\'', '"') |
| 904 | return self.git_editor or None |
jbroman@chromium.org | 615a262 | 2013-05-03 13:20:14 +0000 | [diff] [blame] | 905 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 906 | def GetLintRegex(self): |
| 907 | return self._GetConfig('rietveld.cpplint-regex', DEFAULT_LINT_REGEX) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 908 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 909 | def GetLintIgnoreRegex(self): |
| 910 | return self._GetConfig('rietveld.cpplint-ignore-regex', |
| 911 | DEFAULT_LINT_IGNORE_REGEX) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 912 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 913 | def GetFormatFullByDefault(self): |
| 914 | if self.format_full_by_default is None: |
| 915 | self._LazyUpdateIfNeeded() |
| 916 | result = (RunGit( |
| 917 | ['config', '--bool', 'rietveld.format-full-by-default'], |
| 918 | error_ok=True).strip()) |
| 919 | self.format_full_by_default = (result == 'true') |
| 920 | return self.format_full_by_default |
Jamie Madill | dc4d19e | 2019-10-24 21:50:02 +0000 | [diff] [blame] | 921 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 922 | def IsStatusCommitOrderByDate(self): |
| 923 | if self.is_status_commit_order_by_date is None: |
| 924 | result = (RunGit(['config', '--bool', 'cl.date-order'], |
| 925 | error_ok=True).strip()) |
| 926 | self.is_status_commit_order_by_date = (result == 'true') |
| 927 | return self.is_status_commit_order_by_date |
Sigurd Schneider | 1bfda8e | 2021-06-30 14:46:25 +0000 | [diff] [blame] | 928 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 929 | def _GetConfig(self, key, default=''): |
| 930 | self._LazyUpdateIfNeeded() |
| 931 | return scm.GIT.GetConfig(self.GetRoot(), key, default) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 932 | |
| 933 | |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 934 | class _CQState(object): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 935 | """Enum for states of CL with respect to CQ.""" |
| 936 | NONE = 'none' |
| 937 | DRY_RUN = 'dry_run' |
| 938 | COMMIT = 'commit' |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 939 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 940 | ALL_STATES = [NONE, DRY_RUN, COMMIT] |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 941 | |
| 942 | |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 943 | class _ParsedIssueNumberArgument(object): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 944 | def __init__(self, issue=None, patchset=None, hostname=None): |
| 945 | self.issue = issue |
| 946 | self.patchset = patchset |
| 947 | self.hostname = hostname |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 948 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 949 | @property |
| 950 | def valid(self): |
| 951 | return self.issue is not None |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 952 | |
| 953 | |
Edward Lemur | f38bc17 | 2019-09-03 21:02:13 +0000 | [diff] [blame] | 954 | def ParseIssueNumberArgument(arg): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 955 | """Parses the issue argument and returns _ParsedIssueNumberArgument.""" |
| 956 | fail_result = _ParsedIssueNumberArgument() |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 957 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 958 | if isinstance(arg, int): |
| 959 | return _ParsedIssueNumberArgument(issue=arg) |
| 960 | if not isinstance(arg, str): |
| 961 | return fail_result |
Edward Lemur | 678a684 | 2019-10-03 22:25:05 +0000 | [diff] [blame] | 962 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 963 | if arg.isdigit(): |
| 964 | return _ParsedIssueNumberArgument(issue=int(arg)) |
Aaron Gable | aee6c85 | 2017-06-26 12:49:01 -0700 | [diff] [blame] | 965 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 966 | url = gclient_utils.UpgradeToHttps(arg) |
| 967 | if not url.startswith('http'): |
| 968 | return fail_result |
| 969 | for gerrit_url, short_url in _KNOWN_GERRIT_TO_SHORT_URLS.items(): |
| 970 | if url.startswith(short_url): |
| 971 | url = gerrit_url + url[len(short_url):] |
| 972 | break |
Andrii Shyshkalov | 8aebb60 | 2020-04-16 22:10:27 +0000 | [diff] [blame] | 973 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 974 | try: |
| 975 | parsed_url = urllib.parse.urlparse(url) |
| 976 | except ValueError: |
| 977 | return fail_result |
Andrii Shyshkalov | 28d840e | 2017-04-10 15:45:09 +0200 | [diff] [blame] | 978 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 979 | # If "https://" was automatically added, fail if `arg` looks unlikely to be |
| 980 | # a URL. |
| 981 | if not arg.startswith('http') and '.' not in parsed_url.netloc: |
| 982 | return fail_result |
Alex Turner | 30ae637 | 2022-01-04 02:32:52 +0000 | [diff] [blame] | 983 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 984 | # Gerrit's new UI is https://domain/c/project/+/<issue_number>[/[patchset]] |
| 985 | # But old GWT UI is https://domain/#/c/project/+/<issue_number>[/[patchset]] |
| 986 | # Short urls like https://domain/<issue_number> can be used, but don't allow |
| 987 | # specifying the patchset (you'd 404), but we allow that here. |
| 988 | if parsed_url.path == '/': |
| 989 | part = parsed_url.fragment |
| 990 | else: |
| 991 | part = parsed_url.path |
Edward Lemur | 678a684 | 2019-10-03 22:25:05 +0000 | [diff] [blame] | 992 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 993 | match = re.match(r'(/c(/.*/\+)?)?/(?P<issue>\d+)(/(?P<patchset>\d+)?/?)?$', |
| 994 | part) |
| 995 | if not match: |
| 996 | return fail_result |
Edward Lemur | 678a684 | 2019-10-03 22:25:05 +0000 | [diff] [blame] | 997 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 998 | issue = int(match.group('issue')) |
| 999 | patchset = match.group('patchset') |
| 1000 | return _ParsedIssueNumberArgument( |
| 1001 | issue=issue, |
| 1002 | patchset=int(patchset) if patchset else None, |
| 1003 | hostname=parsed_url.netloc) |
tandrii@chromium.org | f86c7d3 | 2016-04-01 19:27:30 +0000 | [diff] [blame] | 1004 | |
| 1005 | |
Andrii Shyshkalov | b07575f | 2018-10-16 06:16:21 +0000 | [diff] [blame] | 1006 | def _create_description_from_log(args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1007 | """Pulls out the commit log to use as a base for the CL description.""" |
| 1008 | log_args = [] |
| 1009 | if len(args) == 1 and args[0] == None: |
| 1010 | # Handle the case where None is passed as the branch. |
| 1011 | return '' |
| 1012 | if len(args) == 1 and not args[0].endswith('.'): |
| 1013 | log_args = [args[0] + '..'] |
| 1014 | elif len(args) == 1 and args[0].endswith('...'): |
| 1015 | log_args = [args[0][:-1]] |
| 1016 | elif len(args) == 2: |
| 1017 | log_args = [args[0] + '..' + args[1]] |
| 1018 | else: |
| 1019 | log_args = args[:] # Hope for the best! |
| 1020 | return RunGit(['log', '--pretty=format:%B%n'] + log_args) |
Andrii Shyshkalov | b07575f | 2018-10-16 06:16:21 +0000 | [diff] [blame] | 1021 | |
| 1022 | |
Aaron Gable | a45ee11 | 2016-11-22 15:14:38 -0800 | [diff] [blame] | 1023 | class GerritChangeNotExists(Exception): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1024 | def __init__(self, issue, url): |
| 1025 | self.issue = issue |
| 1026 | self.url = url |
| 1027 | super(GerritChangeNotExists, self).__init__() |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 1028 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1029 | def __str__(self): |
| 1030 | return 'change %s at %s does not exist or you have no access to it' % ( |
| 1031 | self.issue, self.url) |
tandrii | c2405f5 | 2016-10-10 08:13:15 -0700 | [diff] [blame] | 1032 | |
| 1033 | |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1034 | _CommentSummary = collections.namedtuple( |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1035 | '_CommentSummary', |
| 1036 | [ |
| 1037 | 'date', |
| 1038 | 'message', |
| 1039 | 'sender', |
| 1040 | 'autogenerated', |
| 1041 | # TODO(tandrii): these two aren't known in Gerrit. |
| 1042 | 'approval', |
| 1043 | 'disapproval' |
| 1044 | ]) |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 1045 | |
Joanna Wang | 6215dd0 | 2023-02-07 15:58:03 +0000 | [diff] [blame] | 1046 | # TODO(b/265929888): Change `parent` to `pushed_commit_base`. |
Joanna Wang | e852391 | 2023-01-21 02:05:40 +0000 | [diff] [blame] | 1047 | _NewUpload = collections.namedtuple('NewUpload', [ |
Joanna Wang | 4049791 | 2023-01-24 21:18:16 +0000 | [diff] [blame] | 1048 | 'reviewers', 'ccs', 'commit_to_push', 'new_last_uploaded_commit', 'parent', |
Joanna Wang | 7603f04 | 2023-03-01 22:17:36 +0000 | [diff] [blame] | 1049 | 'change_desc', 'prev_patchset' |
Joanna Wang | e852391 | 2023-01-21 02:05:40 +0000 | [diff] [blame] | 1050 | ]) |
| 1051 | |
| 1052 | |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1053 | class ChangeDescription(object): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1054 | """Contains a parsed form of the change description.""" |
| 1055 | R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$' |
| 1056 | CC_LINE = r'^[ \t]*(CC)[ \t]*=[ \t]*(.*?)[ \t]*$' |
| 1057 | BUG_LINE = r'^[ \t]*(?:(BUG)[ \t]*=|Bug:)[ \t]*(.*?)[ \t]*$' |
| 1058 | FIXED_LINE = r'^[ \t]*Fixed[ \t]*:[ \t]*(.*?)[ \t]*$' |
| 1059 | CHERRY_PICK_LINE = r'^\(cherry picked from commit [a-fA-F0-9]{40}\)$' |
| 1060 | STRIP_HASH_TAG_PREFIX = r'^(\s*(revert|reland)( "|:)?\s*)*' |
| 1061 | BRACKET_HASH_TAG = r'\s*\[([^\[\]]+)\]' |
| 1062 | COLON_SEPARATED_HASH_TAG = r'^([a-zA-Z0-9_\- ]+):($|[^:])' |
| 1063 | BAD_HASH_TAG_CHUNK = r'[^a-zA-Z0-9]+' |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1064 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1065 | def __init__(self, description, bug=None, fixed=None): |
| 1066 | self._description_lines = (description or '').strip().splitlines() |
| 1067 | if bug: |
| 1068 | regexp = re.compile(self.BUG_LINE) |
| 1069 | prefix = settings.GetBugPrefix() |
| 1070 | if not any( |
| 1071 | (regexp.match(line) for line in self._description_lines)): |
| 1072 | values = list(_get_bug_line_values(prefix, bug)) |
| 1073 | self.append_footer('Bug: %s' % ', '.join(values)) |
| 1074 | if fixed: |
| 1075 | regexp = re.compile(self.FIXED_LINE) |
| 1076 | prefix = settings.GetBugPrefix() |
| 1077 | if not any( |
| 1078 | (regexp.match(line) for line in self._description_lines)): |
| 1079 | values = list(_get_bug_line_values(prefix, fixed)) |
| 1080 | self.append_footer('Fixed: %s' % ', '.join(values)) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1081 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1082 | @property # www.logilab.org/ticket/89786 |
| 1083 | def description(self): # pylint: disable=method-hidden |
| 1084 | return '\n'.join(self._description_lines) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1085 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1086 | def set_description(self, desc): |
| 1087 | if isinstance(desc, str): |
| 1088 | lines = desc.splitlines() |
| 1089 | else: |
| 1090 | lines = [line.rstrip() for line in desc] |
| 1091 | while lines and not lines[0]: |
| 1092 | lines.pop(0) |
| 1093 | while lines and not lines[-1]: |
| 1094 | lines.pop(-1) |
| 1095 | self._description_lines = lines |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1096 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1097 | def ensure_change_id(self, change_id): |
| 1098 | description = self.description |
| 1099 | footer_change_ids = git_footers.get_footer_change_id(description) |
| 1100 | # Make sure that the Change-Id in the description matches the given one. |
| 1101 | if footer_change_ids != [change_id]: |
| 1102 | if footer_change_ids: |
| 1103 | # Remove any existing Change-Id footers since they don't match |
| 1104 | # the expected change_id footer. |
| 1105 | description = git_footers.remove_footer(description, |
| 1106 | 'Change-Id') |
| 1107 | print( |
| 1108 | 'WARNING: Change-Id has been set to %s. Use `git cl issue 0` ' |
| 1109 | 'if you want to set a new one.') |
| 1110 | # Add the expected Change-Id footer. |
| 1111 | description = git_footers.add_footer_change_id( |
| 1112 | description, change_id) |
| 1113 | self.set_description(description) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1114 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1115 | def update_reviewers(self, reviewers): |
| 1116 | """Rewrites the R= line(s) as a single line each. |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1117 | |
| 1118 | Args: |
| 1119 | reviewers (list(str)) - list of additional emails to use for reviewers. |
| 1120 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1121 | if not reviewers: |
| 1122 | return |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1123 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1124 | reviewers = set(reviewers) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1125 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1126 | # Get the set of R= lines and remove them from the description. |
| 1127 | regexp = re.compile(self.R_LINE) |
| 1128 | matches = [regexp.match(line) for line in self._description_lines] |
| 1129 | new_desc = [ |
| 1130 | l for i, l in enumerate(self._description_lines) if not matches[i] |
| 1131 | ] |
| 1132 | self.set_description(new_desc) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1133 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1134 | # Construct new unified R= lines. |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1135 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1136 | # First, update reviewers with names from the R= lines (if any). |
| 1137 | for match in matches: |
| 1138 | if not match: |
| 1139 | continue |
| 1140 | reviewers.update(cleanup_list([match.group(2).strip()])) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1141 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1142 | new_r_line = 'R=' + ', '.join(sorted(reviewers)) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1143 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1144 | # Put the new lines in the description where the old first R= line was. |
| 1145 | line_loc = next((i for i, match in enumerate(matches) if match), -1) |
| 1146 | if 0 <= line_loc < len(self._description_lines): |
| 1147 | self._description_lines.insert(line_loc, new_r_line) |
| 1148 | else: |
| 1149 | self.append_footer(new_r_line) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1150 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1151 | def set_preserve_tryjobs(self): |
| 1152 | """Ensures description footer contains 'Cq-Do-Not-Cancel-Tryjobs: true'.""" |
| 1153 | footers = git_footers.parse_footers(self.description) |
| 1154 | for v in footers.get('Cq-Do-Not-Cancel-Tryjobs', []): |
| 1155 | if v.lower() == 'true': |
| 1156 | return |
| 1157 | self.append_footer('Cq-Do-Not-Cancel-Tryjobs: true') |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1158 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1159 | def prompt(self): |
| 1160 | """Asks the user to update the description.""" |
| 1161 | self.set_description([ |
| 1162 | '# Enter a description of the change.', |
| 1163 | '# This will be displayed on the codereview site.', |
| 1164 | '# The first line will also be used as the subject of the review.', |
| 1165 | '#--------------------This line is 72 characters long' |
| 1166 | '--------------------', |
| 1167 | ] + self._description_lines) |
| 1168 | bug_regexp = re.compile(self.BUG_LINE) |
| 1169 | fixed_regexp = re.compile(self.FIXED_LINE) |
| 1170 | prefix = settings.GetBugPrefix() |
| 1171 | has_issue = lambda l: bug_regexp.match(l) or fixed_regexp.match(l) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1172 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1173 | if not any((has_issue(line) for line in self._description_lines)): |
| 1174 | self.append_footer('Bug: %s' % prefix) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1175 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1176 | print('Waiting for editor...') |
| 1177 | content = gclient_utils.RunEditor(self.description, |
| 1178 | True, |
| 1179 | git_editor=settings.GetGitEditor()) |
| 1180 | if not content: |
| 1181 | DieWithError('Running editor failed') |
| 1182 | lines = content.splitlines() |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1183 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1184 | # Strip off comments and default inserted "Bug:" line. |
| 1185 | clean_lines = [ |
| 1186 | line.rstrip() for line in lines |
| 1187 | if not (line.startswith('#') or line.rstrip() == "Bug:" |
| 1188 | or line.rstrip() == "Bug: " + prefix) |
| 1189 | ] |
| 1190 | if not clean_lines: |
| 1191 | DieWithError('No CL description, aborting') |
| 1192 | self.set_description(clean_lines) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1193 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1194 | def append_footer(self, line): |
| 1195 | """Adds a footer line to the description. |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1196 | |
| 1197 | Differentiates legacy "KEY=xxx" footers (used to be called tags) and |
| 1198 | Gerrit's footers in the form of "Footer-Key: footer any value" and ensures |
| 1199 | that Gerrit footers are always at the end. |
| 1200 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1201 | parsed_footer_line = git_footers.parse_footer(line) |
| 1202 | if parsed_footer_line: |
| 1203 | # Line is a gerrit footer in the form: Footer-Key: any value. |
| 1204 | # Thus, must be appended observing Gerrit footer rules. |
| 1205 | self.set_description( |
| 1206 | git_footers.add_footer(self.description, |
| 1207 | key=parsed_footer_line[0], |
| 1208 | value=parsed_footer_line[1])) |
| 1209 | return |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1210 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1211 | if not self._description_lines: |
| 1212 | self._description_lines.append(line) |
| 1213 | return |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1214 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1215 | top_lines, gerrit_footers, _ = git_footers.split_footers( |
| 1216 | self.description) |
| 1217 | if gerrit_footers: |
| 1218 | # git_footers.split_footers ensures that there is an empty line |
| 1219 | # before actual (gerrit) footers, if any. We have to keep it that |
| 1220 | # way. |
| 1221 | assert top_lines and top_lines[-1] == '' |
| 1222 | top_lines, separator = top_lines[:-1], top_lines[-1:] |
| 1223 | else: |
| 1224 | separator = [ |
| 1225 | ] # No need for separator if there are no gerrit_footers. |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1226 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1227 | prev_line = top_lines[-1] if top_lines else '' |
| 1228 | if (not presubmit_support.Change.TAG_LINE_RE.match(prev_line) |
| 1229 | or not presubmit_support.Change.TAG_LINE_RE.match(line)): |
| 1230 | top_lines.append('') |
| 1231 | top_lines.append(line) |
| 1232 | self._description_lines = top_lines + separator + gerrit_footers |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1233 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1234 | def get_reviewers(self, tbr_only=False): |
| 1235 | """Retrieves the list of reviewers.""" |
| 1236 | matches = [ |
| 1237 | re.match(self.R_LINE, line) for line in self._description_lines |
| 1238 | ] |
| 1239 | reviewers = [ |
| 1240 | match.group(2).strip() for match in matches |
| 1241 | if match and (not tbr_only or match.group(1).upper() == 'TBR') |
| 1242 | ] |
| 1243 | return cleanup_list(reviewers) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1244 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1245 | def get_cced(self): |
| 1246 | """Retrieves the list of reviewers.""" |
| 1247 | matches = [ |
| 1248 | re.match(self.CC_LINE, line) for line in self._description_lines |
| 1249 | ] |
| 1250 | cced = [match.group(2).strip() for match in matches if match] |
| 1251 | return cleanup_list(cced) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1252 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1253 | def get_hash_tags(self): |
| 1254 | """Extracts and sanitizes a list of Gerrit hashtags.""" |
| 1255 | subject = (self._description_lines or ('', ))[0] |
| 1256 | subject = re.sub(self.STRIP_HASH_TAG_PREFIX, |
| 1257 | '', |
| 1258 | subject, |
| 1259 | flags=re.IGNORECASE) |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1260 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1261 | tags = [] |
| 1262 | start = 0 |
| 1263 | bracket_exp = re.compile(self.BRACKET_HASH_TAG) |
| 1264 | while True: |
| 1265 | m = bracket_exp.match(subject, start) |
| 1266 | if not m: |
| 1267 | break |
| 1268 | tags.append(self.sanitize_hash_tag(m.group(1))) |
| 1269 | start = m.end() |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1270 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1271 | if not tags: |
| 1272 | # Try "Tag: " prefix. |
| 1273 | m = re.match(self.COLON_SEPARATED_HASH_TAG, subject) |
| 1274 | if m: |
| 1275 | tags.append(self.sanitize_hash_tag(m.group(1))) |
| 1276 | return tags |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1277 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1278 | @classmethod |
| 1279 | def sanitize_hash_tag(cls, tag): |
| 1280 | """Returns a sanitized Gerrit hash tag. |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1281 | |
| 1282 | A sanitized hashtag can be used as a git push refspec parameter value. |
| 1283 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1284 | return re.sub(cls.BAD_HASH_TAG_CHUNK, '-', tag).strip('-').lower() |
Daniel Cheng | abf4847 | 2023-08-30 15:45:13 +0000 | [diff] [blame] | 1285 | |
| 1286 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1287 | class Changelist(object): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1288 | """Changelist works with one changelist in local branch. |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1289 | |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 1290 | Notes: |
| 1291 | * Not safe for concurrent multi-{thread,process} use. |
| 1292 | * Caches values from current branch. Therefore, re-use after branch change |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1293 | with great care. |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1294 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1295 | def __init__(self, |
| 1296 | branchref=None, |
| 1297 | issue=None, |
| 1298 | codereview_host=None, |
| 1299 | commit_date=None): |
| 1300 | """Create a new ChangeList instance. |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1301 | |
Edward Lemur | f38bc17 | 2019-09-03 21:02:13 +0000 | [diff] [blame] | 1302 | **kwargs will be passed directly to Gerrit implementation. |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1303 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1304 | # Poke settings so we get the "configure your server" message if |
| 1305 | # necessary. |
| 1306 | global settings |
| 1307 | if not settings: |
| 1308 | # Happens when git_cl.py is used as a utility library. |
| 1309 | settings = Settings() |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1310 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1311 | self.branchref = branchref |
| 1312 | if self.branchref: |
| 1313 | assert branchref.startswith('refs/heads/') |
| 1314 | self.branch = scm.GIT.ShortBranchName(self.branchref) |
| 1315 | else: |
| 1316 | self.branch = None |
| 1317 | self.commit_date = commit_date |
| 1318 | self.upstream_branch = None |
| 1319 | self.lookedup_issue = False |
| 1320 | self.issue = issue or None |
| 1321 | self.description = None |
| 1322 | self.lookedup_patchset = False |
| 1323 | self.patchset = None |
| 1324 | self.cc = None |
| 1325 | self.more_cc = [] |
| 1326 | self._remote = None |
| 1327 | self._cached_remote_url = (False, None) # (is_cached, value) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 1328 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1329 | # Lazily cached values. |
| 1330 | self._gerrit_host = None # e.g. chromium-review.googlesource.com |
| 1331 | self._gerrit_server = None # e.g. https://chromium-review.googlesource.com |
| 1332 | self._owners_client = None |
| 1333 | # Map from change number (issue) to its detail cache. |
| 1334 | self._detail_cache = {} |
Edward Lemur | 125d60a | 2019-09-13 18:25:41 +0000 | [diff] [blame] | 1335 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1336 | if codereview_host is not None: |
| 1337 | assert not codereview_host.startswith('https://'), codereview_host |
| 1338 | self._gerrit_host = codereview_host |
| 1339 | self._gerrit_server = 'https://%s' % codereview_host |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1340 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1341 | @property |
| 1342 | def owners_client(self): |
| 1343 | if self._owners_client is None: |
| 1344 | remote, remote_branch = self.GetRemoteBranch() |
| 1345 | branch = GetTargetRef(remote, remote_branch, None) |
| 1346 | self._owners_client = owners_client.GetCodeOwnersClient( |
| 1347 | host=self.GetGerritHost(), |
| 1348 | project=self.GetGerritProject(), |
| 1349 | branch=branch) |
| 1350 | return self._owners_client |
Edward Lesmes | e157691 | 2021-02-16 21:53:34 +0000 | [diff] [blame] | 1351 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1352 | def GetCCList(self): |
| 1353 | """Returns the users cc'd on this CL. |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1354 | |
Quinten Yearsley | 0c62da9 | 2017-05-31 13:39:42 -0700 | [diff] [blame] | 1355 | The return value is a string suitable for passing to git cl with the --cc |
| 1356 | flag. |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1357 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1358 | if self.cc is None: |
| 1359 | base_cc = settings.GetDefaultCCList() |
| 1360 | more_cc = ','.join(self.more_cc) |
| 1361 | self.cc = ','.join(filter(None, (base_cc, more_cc))) or '' |
| 1362 | return self.cc |
bauerb@chromium.org | ae6df35 | 2011-04-06 17:40:39 +0000 | [diff] [blame] | 1363 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1364 | def ExtendCC(self, more_cc): |
| 1365 | """Extends the list of users to cc on this CL based on the changed files.""" |
| 1366 | self.more_cc.extend(more_cc) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1367 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1368 | def GetCommitDate(self): |
| 1369 | """Returns the commit date as provided in the constructor""" |
| 1370 | return self.commit_date |
Sigurd Schneider | 9abde8c | 2020-11-17 08:44:52 +0000 | [diff] [blame] | 1371 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1372 | def GetBranch(self): |
| 1373 | """Returns the short branch name, e.g. 'main'.""" |
| 1374 | if not self.branch: |
| 1375 | branchref = scm.GIT.GetBranchRef(settings.GetRoot()) |
| 1376 | if not branchref: |
| 1377 | return None |
| 1378 | self.branchref = branchref |
| 1379 | self.branch = scm.GIT.ShortBranchName(self.branchref) |
| 1380 | return self.branch |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1381 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1382 | def GetBranchRef(self): |
| 1383 | """Returns the full branch name, e.g. 'refs/heads/main'.""" |
| 1384 | self.GetBranch() # Poke the lazy loader. |
| 1385 | return self.branchref |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1386 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1387 | def _GitGetBranchConfigValue(self, key, default=None): |
| 1388 | return scm.GIT.GetBranchConfig(settings.GetRoot(), self.GetBranch(), |
| 1389 | key, default) |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1390 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1391 | def _GitSetBranchConfigValue(self, key, value): |
| 1392 | action = 'set %s to %r' % (key, value) |
| 1393 | if not value: |
| 1394 | action = 'unset %s' % key |
| 1395 | assert self.GetBranch(), 'a branch is needed to ' + action |
| 1396 | return scm.GIT.SetBranchConfig(settings.GetRoot(), self.GetBranch(), |
| 1397 | key, value) |
tandrii | 5d48c32 | 2016-08-18 16:19:37 -0700 | [diff] [blame] | 1398 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1399 | @staticmethod |
| 1400 | def FetchUpstreamTuple(branch): |
| 1401 | """Returns a tuple containing remote and remote ref, |
Josip Sokcevic | c39ab99 | 2020-09-24 20:09:15 +0000 | [diff] [blame] | 1402 | e.g. 'origin', 'refs/heads/main' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1403 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1404 | remote, upstream_branch = scm.GIT.FetchUpstreamTuple( |
| 1405 | settings.GetRoot(), branch) |
| 1406 | if not remote or not upstream_branch: |
| 1407 | DieWithError( |
| 1408 | 'Unable to determine default branch to diff against.\n' |
| 1409 | 'Verify this branch is set up to track another \n' |
| 1410 | '(via the --track argument to "git checkout -b ..."). \n' |
| 1411 | 'or pass complete "git diff"-style arguments if supported, like\n' |
| 1412 | ' git cl upload origin/main\n') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1413 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1414 | return remote, upstream_branch |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1415 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1416 | def GetCommonAncestorWithUpstream(self): |
| 1417 | upstream_branch = self.GetUpstreamBranch() |
| 1418 | if not scm.GIT.IsValidRevision(settings.GetRoot(), upstream_branch): |
| 1419 | DieWithError( |
| 1420 | 'The upstream for the current branch (%s) does not exist ' |
| 1421 | 'anymore.\nPlease fix it and try again.' % self.GetBranch()) |
| 1422 | return git_common.get_or_create_merge_base(self.GetBranch(), |
| 1423 | upstream_branch) |
thestig@chromium.org | 8b0553c | 2014-02-11 00:33:37 +0000 | [diff] [blame] | 1424 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1425 | def GetUpstreamBranch(self): |
| 1426 | if self.upstream_branch is None: |
| 1427 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
| 1428 | if remote != '.': |
| 1429 | upstream_branch = upstream_branch.replace( |
| 1430 | 'refs/heads/', 'refs/remotes/%s/' % remote) |
| 1431 | upstream_branch = upstream_branch.replace( |
| 1432 | 'refs/branch-heads/', 'refs/remotes/branch-heads/') |
| 1433 | self.upstream_branch = upstream_branch |
| 1434 | return self.upstream_branch |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1435 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1436 | def GetRemoteBranch(self): |
| 1437 | if not self._remote: |
| 1438 | remote, branch = None, self.GetBranch() |
| 1439 | seen_branches = set() |
| 1440 | while branch not in seen_branches: |
| 1441 | seen_branches.add(branch) |
| 1442 | remote, branch = self.FetchUpstreamTuple(branch) |
| 1443 | branch = scm.GIT.ShortBranchName(branch) |
| 1444 | if remote != '.' or branch.startswith('refs/remotes'): |
| 1445 | break |
| 1446 | else: |
| 1447 | remotes = RunGit(['remote'], error_ok=True).split() |
| 1448 | if len(remotes) == 1: |
| 1449 | remote, = remotes |
| 1450 | elif 'origin' in remotes: |
| 1451 | remote = 'origin' |
| 1452 | logging.warning( |
| 1453 | 'Could not determine which remote this change is ' |
| 1454 | 'associated with, so defaulting to "%s".' % |
| 1455 | self._remote) |
| 1456 | else: |
| 1457 | logging.warning( |
| 1458 | 'Could not determine which remote this change is ' |
| 1459 | 'associated with.') |
| 1460 | branch = 'HEAD' |
| 1461 | if branch.startswith('refs/remotes'): |
| 1462 | self._remote = (remote, branch) |
| 1463 | elif branch.startswith('refs/branch-heads/'): |
| 1464 | self._remote = (remote, branch.replace('refs/', |
| 1465 | 'refs/remotes/')) |
| 1466 | else: |
| 1467 | self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch)) |
| 1468 | return self._remote |
jmbaker@chromium.org | a2cbbbb | 2012-03-22 20:40:40 +0000 | [diff] [blame] | 1469 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1470 | def GetRemoteUrl(self) -> Optional[str]: |
| 1471 | """Return the configured remote URL, e.g. 'git://example.org/foo.git/'. |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1472 | |
| 1473 | Returns None if there is no remote. |
| 1474 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1475 | is_cached, value = self._cached_remote_url |
| 1476 | if is_cached: |
| 1477 | return value |
Andrii Shyshkalov | 81db1d5 | 2018-08-23 02:17:41 +0000 | [diff] [blame] | 1478 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1479 | remote, _ = self.GetRemoteBranch() |
| 1480 | url = scm.GIT.GetConfig(settings.GetRoot(), 'remote.%s.url' % remote, |
| 1481 | '') |
dyen@chromium.org | 2a13d4f | 2014-06-13 00:06:37 +0000 | [diff] [blame] | 1482 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1483 | # Check if the remote url can be parsed as an URL. |
| 1484 | host = urllib.parse.urlparse(url).netloc |
| 1485 | if host: |
| 1486 | self._cached_remote_url = (True, url) |
| 1487 | return url |
Edward Lemur | 298f2cf | 2019-02-22 21:40:39 +0000 | [diff] [blame] | 1488 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1489 | # If it cannot be parsed as an url, assume it is a local directory, |
| 1490 | # probably a git cache. |
| 1491 | logging.warning( |
| 1492 | '"%s" doesn\'t appear to point to a git host. ' |
| 1493 | 'Interpreting it as a local directory.', url) |
| 1494 | if not os.path.isdir(url): |
| 1495 | logging.error( |
| 1496 | 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", ' |
| 1497 | 'but it doesn\'t exist.', { |
| 1498 | 'remote': remote, |
| 1499 | 'branch': self.GetBranch(), |
| 1500 | 'url': url |
| 1501 | }) |
| 1502 | return None |
Edward Lemur | 298f2cf | 2019-02-22 21:40:39 +0000 | [diff] [blame] | 1503 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1504 | cache_path = url |
| 1505 | url = scm.GIT.GetConfig(url, 'remote.%s.url' % remote, '') |
Edward Lemur | 298f2cf | 2019-02-22 21:40:39 +0000 | [diff] [blame] | 1506 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1507 | host = urllib.parse.urlparse(url).netloc |
| 1508 | if not host: |
| 1509 | logging.error( |
| 1510 | 'Remote "%(remote)s" for branch "%(branch)s" points to ' |
| 1511 | '"%(cache_path)s", but it is misconfigured.\n' |
| 1512 | '"%(cache_path)s" must be a git repo and must have a remote named ' |
| 1513 | '"%(remote)s" pointing to the git host.', { |
| 1514 | 'remote': remote, |
| 1515 | 'cache_path': cache_path, |
| 1516 | 'branch': self.GetBranch() |
| 1517 | }) |
| 1518 | return None |
Edward Lemur | 298f2cf | 2019-02-22 21:40:39 +0000 | [diff] [blame] | 1519 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1520 | self._cached_remote_url = (True, url) |
| 1521 | return url |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1522 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1523 | def GetIssue(self): |
| 1524 | """Returns the issue number as a int or None if not set.""" |
| 1525 | if self.issue is None and not self.lookedup_issue: |
| 1526 | if self.GetBranch(): |
| 1527 | self.issue = self._GitGetBranchConfigValue(ISSUE_CONFIG_KEY) |
| 1528 | if self.issue is not None: |
| 1529 | self.issue = int(self.issue) |
| 1530 | self.lookedup_issue = True |
| 1531 | return self.issue |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1532 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1533 | def GetIssueURL(self, short=False): |
| 1534 | """Get the URL for a particular issue.""" |
| 1535 | issue = self.GetIssue() |
| 1536 | if not issue: |
| 1537 | return None |
| 1538 | server = self.GetCodereviewServer() |
| 1539 | if short: |
| 1540 | server = _KNOWN_GERRIT_TO_SHORT_URLS.get(server, server) |
| 1541 | return '%s/%s' % (server, issue) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1542 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1543 | def FetchDescription(self, pretty=False): |
| 1544 | assert self.GetIssue(), 'issue is required to query Gerrit' |
Edward Lemur | 6c6827c | 2020-02-06 21:15:18 +0000 | [diff] [blame] | 1545 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1546 | if self.description is None: |
| 1547 | data = self._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT']) |
| 1548 | current_rev = data['current_revision'] |
| 1549 | self.description = data['revisions'][current_rev]['commit'][ |
| 1550 | 'message'] |
Edward Lemur | 6c6827c | 2020-02-06 21:15:18 +0000 | [diff] [blame] | 1551 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1552 | if not pretty: |
| 1553 | return self.description |
Edward Lemur | 6c6827c | 2020-02-06 21:15:18 +0000 | [diff] [blame] | 1554 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1555 | # Set width to 72 columns + 2 space indent. |
| 1556 | wrapper = textwrap.TextWrapper(width=74, replace_whitespace=True) |
| 1557 | wrapper.initial_indent = wrapper.subsequent_indent = ' ' |
| 1558 | lines = self.description.splitlines() |
| 1559 | return '\n'.join([wrapper.fill(line) for line in lines]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1560 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1561 | def GetPatchset(self): |
| 1562 | """Returns the patchset number as a int or None if not set.""" |
| 1563 | if self.patchset is None and not self.lookedup_patchset: |
| 1564 | if self.GetBranch(): |
| 1565 | self.patchset = self._GitGetBranchConfigValue( |
| 1566 | PATCHSET_CONFIG_KEY) |
| 1567 | if self.patchset is not None: |
| 1568 | self.patchset = int(self.patchset) |
| 1569 | self.lookedup_patchset = True |
| 1570 | return self.patchset |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1571 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1572 | def GetAuthor(self): |
| 1573 | return scm.GIT.GetConfig(settings.GetRoot(), 'user.email') |
Edward Lemur | 9aa1a96 | 2020-02-25 00:58:38 +0000 | [diff] [blame] | 1574 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1575 | def SetPatchset(self, patchset): |
| 1576 | """Set this branch's patchset. If patchset=0, clears the patchset.""" |
| 1577 | assert self.GetBranch() |
| 1578 | if not patchset: |
| 1579 | self.patchset = None |
| 1580 | else: |
| 1581 | self.patchset = int(patchset) |
| 1582 | self._GitSetBranchConfigValue(PATCHSET_CONFIG_KEY, str(self.patchset)) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1583 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1584 | def SetIssue(self, issue=None): |
| 1585 | """Set this branch's issue. If issue isn't given, clears the issue.""" |
| 1586 | assert self.GetBranch() |
| 1587 | if issue: |
| 1588 | issue = int(issue) |
| 1589 | self._GitSetBranchConfigValue(ISSUE_CONFIG_KEY, str(issue)) |
| 1590 | self.issue = issue |
| 1591 | codereview_server = self.GetCodereviewServer() |
| 1592 | if codereview_server: |
| 1593 | self._GitSetBranchConfigValue(CODEREVIEW_SERVER_CONFIG_KEY, |
| 1594 | codereview_server) |
| 1595 | else: |
| 1596 | # Reset all of these just to be clean. |
| 1597 | reset_suffixes = [ |
| 1598 | LAST_UPLOAD_HASH_CONFIG_KEY, |
| 1599 | ISSUE_CONFIG_KEY, |
| 1600 | PATCHSET_CONFIG_KEY, |
| 1601 | CODEREVIEW_SERVER_CONFIG_KEY, |
| 1602 | GERRIT_SQUASH_HASH_CONFIG_KEY, |
| 1603 | ] |
| 1604 | for prop in reset_suffixes: |
| 1605 | try: |
| 1606 | self._GitSetBranchConfigValue(prop, None) |
| 1607 | except subprocess2.CalledProcessError: |
| 1608 | pass |
| 1609 | msg = RunGit(['log', '-1', '--format=%B']).strip() |
| 1610 | if msg and git_footers.get_footer_change_id(msg): |
| 1611 | print( |
| 1612 | 'WARNING: The change patched into this branch has a Change-Id. ' |
| 1613 | 'Removing it.') |
| 1614 | RunGit([ |
| 1615 | 'commit', '--amend', '-m', |
| 1616 | git_footers.remove_footer(msg, 'Change-Id') |
| 1617 | ]) |
| 1618 | self.lookedup_issue = True |
| 1619 | self.issue = None |
| 1620 | self.patchset = None |
| 1621 | |
| 1622 | def GetAffectedFiles(self, |
| 1623 | upstream: str, |
| 1624 | end_commit: Optional[str] = None) -> Sequence[str]: |
| 1625 | """Returns the list of affected files for the given commit range.""" |
Edward Lemur | 8515328 | 2020-02-14 22:06:29 +0000 | [diff] [blame] | 1626 | try: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1627 | return [ |
| 1628 | f for _, f in scm.GIT.CaptureStatus( |
| 1629 | settings.GetRoot(), upstream, end_commit=end_commit) |
| 1630 | ] |
Edward Lemur | 8515328 | 2020-02-14 22:06:29 +0000 | [diff] [blame] | 1631 | except subprocess2.CalledProcessError: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1632 | DieWithError( |
| 1633 | ('\nFailed to diff against upstream branch %s\n\n' |
| 1634 | 'This branch probably doesn\'t exist anymore. To reset the\n' |
| 1635 | 'tracking branch, please run\n' |
| 1636 | ' git branch --set-upstream-to origin/main %s\n' |
| 1637 | 'or replace origin/main with the relevant branch') % |
| 1638 | (upstream, self.GetBranch())) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 1639 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1640 | def UpdateDescription(self, description, force=False): |
| 1641 | assert self.GetIssue(), 'issue is required to update description' |
bauerb@chromium.org | 6fb99c6 | 2011-04-18 15:57:28 +0000 | [diff] [blame] | 1642 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1643 | if gerrit_util.HasPendingChangeEdit(self.GetGerritHost(), |
| 1644 | self._GerritChangeIdentifier()): |
| 1645 | if not force: |
| 1646 | confirm_or_exit( |
| 1647 | 'The description cannot be modified while the issue has a pending ' |
| 1648 | 'unpublished edit. Either publish the edit in the Gerrit web UI ' |
| 1649 | 'or delete it.\n\n', |
| 1650 | action='delete the unpublished edit') |
Edward Lemur | 6c6827c | 2020-02-06 21:15:18 +0000 | [diff] [blame] | 1651 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1652 | gerrit_util.DeletePendingChangeEdit(self.GetGerritHost(), |
| 1653 | self._GerritChangeIdentifier()) |
| 1654 | gerrit_util.SetCommitMessage(self.GetGerritHost(), |
| 1655 | self._GerritChangeIdentifier(), |
| 1656 | description, |
| 1657 | notify='NONE') |
Edward Lemur | 6c6827c | 2020-02-06 21:15:18 +0000 | [diff] [blame] | 1658 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1659 | self.description = description |
Edward Lemur | 6c6827c | 2020-02-06 21:15:18 +0000 | [diff] [blame] | 1660 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1661 | def _GetCommonPresubmitArgs(self, verbose, upstream): |
| 1662 | args = [ |
| 1663 | '--root', |
| 1664 | settings.GetRoot(), |
| 1665 | '--upstream', |
| 1666 | upstream, |
| 1667 | ] |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1668 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1669 | args.extend(['--verbose'] * verbose) |
Edward Lemur | 227d510 | 2020-02-25 23:45:35 +0000 | [diff] [blame] | 1670 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1671 | remote, remote_branch = self.GetRemoteBranch() |
| 1672 | target_ref = GetTargetRef(remote, remote_branch, None) |
| 1673 | if settings.GetIsGerrit(): |
| 1674 | args.extend(['--gerrit_url', self.GetCodereviewServer()]) |
| 1675 | args.extend(['--gerrit_project', self.GetGerritProject()]) |
| 1676 | args.extend(['--gerrit_branch', target_ref]) |
Edward Lemur | 227d510 | 2020-02-25 23:45:35 +0000 | [diff] [blame] | 1677 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1678 | author = self.GetAuthor() |
| 1679 | issue = self.GetIssue() |
| 1680 | patchset = self.GetPatchset() |
| 1681 | if author: |
| 1682 | args.extend(['--author', author]) |
| 1683 | if issue: |
| 1684 | args.extend(['--issue', str(issue)]) |
| 1685 | if patchset: |
| 1686 | args.extend(['--patchset', str(patchset)]) |
Edward Lesmes | eb1bd62 | 2021-03-01 19:54:07 +0000 | [diff] [blame] | 1687 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1688 | return args |
Edward Lemur | 227d510 | 2020-02-25 23:45:35 +0000 | [diff] [blame] | 1689 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1690 | def RunHook(self, |
| 1691 | committing, |
| 1692 | may_prompt, |
| 1693 | verbose, |
| 1694 | parallel, |
| 1695 | upstream, |
| 1696 | description, |
| 1697 | all_files, |
| 1698 | files=None, |
| 1699 | resultdb=False, |
| 1700 | realm=None): |
| 1701 | """Calls sys.exit() if the hook fails; returns a HookResults otherwise.""" |
| 1702 | args = self._GetCommonPresubmitArgs(verbose, upstream) |
| 1703 | args.append('--commit' if committing else '--upload') |
| 1704 | if may_prompt: |
| 1705 | args.append('--may_prompt') |
| 1706 | if parallel: |
| 1707 | args.append('--parallel') |
| 1708 | if all_files: |
| 1709 | args.append('--all_files') |
| 1710 | if files: |
| 1711 | args.extend(files.split(';')) |
| 1712 | args.append('--source_controlled_only') |
| 1713 | if files or all_files: |
| 1714 | args.append('--no_diffs') |
Edward Lemur | 7552630 | 2020-02-27 22:31:05 +0000 | [diff] [blame] | 1715 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1716 | if resultdb and not realm: |
| 1717 | # TODO (crbug.com/1113463): store realm somewhere and look it up so |
| 1718 | # it is not required to pass the realm flag |
| 1719 | print( |
| 1720 | 'Note: ResultDB reporting will NOT be performed because --realm' |
| 1721 | ' was not specified. To enable ResultDB, please run the command' |
| 1722 | ' again with the --realm argument to specify the LUCI realm.') |
Edward Lemur | 227d510 | 2020-02-25 23:45:35 +0000 | [diff] [blame] | 1723 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1724 | return self._RunPresubmit(args, |
| 1725 | description, |
| 1726 | resultdb=resultdb, |
| 1727 | realm=realm) |
Dirk Pranke | 61bf6e8 | 2021-04-23 00:50:21 +0000 | [diff] [blame] | 1728 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1729 | def _RunPresubmit(self, |
| 1730 | args: Sequence[str], |
| 1731 | description: str, |
| 1732 | resultdb: bool = False, |
| 1733 | realm: Optional[str] = None) -> Mapping[str, Any]: |
| 1734 | args = list(args) |
Dirk Pranke | 61bf6e8 | 2021-04-23 00:50:21 +0000 | [diff] [blame] | 1735 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1736 | with gclient_utils.temporary_file() as description_file: |
| 1737 | with gclient_utils.temporary_file() as json_output: |
| 1738 | gclient_utils.FileWrite(description_file, description) |
| 1739 | args.extend(['--json_output', json_output]) |
| 1740 | args.extend(['--description_file', description_file]) |
| 1741 | start = time_time() |
| 1742 | cmd = ['vpython3', PRESUBMIT_SUPPORT] + args |
| 1743 | if resultdb and realm: |
| 1744 | cmd = ['rdb', 'stream', '-new', '-realm', realm, '--'] + cmd |
Dirk Pranke | 61bf6e8 | 2021-04-23 00:50:21 +0000 | [diff] [blame] | 1745 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1746 | p = subprocess2.Popen(cmd) |
| 1747 | exit_code = p.wait() |
Saagar Sanghavi | 9949ab7 | 2020-07-20 20:56:40 +0000 | [diff] [blame] | 1748 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1749 | metrics.collector.add_repeated( |
| 1750 | 'sub_commands', { |
| 1751 | 'command': 'presubmit', |
| 1752 | 'execution_time': time_time() - start, |
| 1753 | 'exit_code': exit_code, |
| 1754 | }) |
Saagar Sanghavi | 9949ab7 | 2020-07-20 20:56:40 +0000 | [diff] [blame] | 1755 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1756 | if exit_code: |
| 1757 | sys.exit(exit_code) |
Edward Lemur | 227d510 | 2020-02-25 23:45:35 +0000 | [diff] [blame] | 1758 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1759 | json_results = gclient_utils.FileRead(json_output) |
| 1760 | return json.loads(json_results) |
Edward Lemur | 227d510 | 2020-02-25 23:45:35 +0000 | [diff] [blame] | 1761 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1762 | def RunPostUploadHook(self, verbose, upstream, description): |
| 1763 | args = self._GetCommonPresubmitArgs(verbose, upstream) |
| 1764 | args.append('--post_upload') |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 1765 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1766 | with gclient_utils.temporary_file() as description_file: |
| 1767 | gclient_utils.FileWrite(description_file, description) |
| 1768 | args.extend(['--description_file', description_file]) |
| 1769 | subprocess2.Popen(['vpython3', PRESUBMIT_SUPPORT] + args).wait() |
Edward Lemur | 7552630 | 2020-02-27 22:31:05 +0000 | [diff] [blame] | 1770 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1771 | def _GetDescriptionForUpload(self, options: optparse.Values, |
| 1772 | git_diff_args: Sequence[str], |
| 1773 | files: Sequence[str]) -> ChangeDescription: |
| 1774 | """Get description message for upload.""" |
| 1775 | if self.GetIssue(): |
| 1776 | description = self.FetchDescription() |
| 1777 | elif options.message: |
| 1778 | description = options.message |
| 1779 | else: |
| 1780 | description = _create_description_from_log(git_diff_args) |
| 1781 | if options.title and options.squash: |
| 1782 | description = options.title + '\n\n' + description |
Edward Lemur | 7552630 | 2020-02-27 22:31:05 +0000 | [diff] [blame] | 1783 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1784 | bug = options.bug |
| 1785 | fixed = options.fixed |
| 1786 | if not self.GetIssue(): |
| 1787 | # Extract bug number from branch name, but only if issue is being |
| 1788 | # created. It must start with bug or fix, followed by _ or - and |
| 1789 | # number. Optionally, it may contain _ or - after number with |
| 1790 | # arbitrary text. Examples: bug-123 bug_123 fix-123 |
| 1791 | # fix-123-some-description |
| 1792 | branch = self.GetBranch() |
| 1793 | if branch is not None: |
| 1794 | match = re.match( |
| 1795 | r'^(?P<type>bug|fix(?:e[sd])?)[_-]?(?P<bugnum>\d+)([-_]|$)', |
| 1796 | branch) |
| 1797 | if not bug and not fixed and match: |
| 1798 | if match.group('type') == 'bug': |
| 1799 | bug = match.group('bugnum') |
| 1800 | else: |
| 1801 | fixed = match.group('bugnum') |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 1802 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1803 | change_description = ChangeDescription(description, bug, fixed) |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 1804 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1805 | # Fill gaps in OWNERS coverage to reviewers if requested. |
| 1806 | if options.add_owners_to: |
| 1807 | assert options.add_owners_to in ('R'), options.add_owners_to |
| 1808 | status = self.owners_client.GetFilesApprovalStatus( |
| 1809 | files, [], options.reviewers) |
| 1810 | missing_files = [ |
| 1811 | f for f in files |
| 1812 | if status[f] == self._owners_client.INSUFFICIENT_REVIEWERS |
| 1813 | ] |
| 1814 | owners = self.owners_client.SuggestOwners( |
| 1815 | missing_files, exclude=[self.GetAuthor()]) |
| 1816 | assert isinstance(options.reviewers, list), options.reviewers |
| 1817 | options.reviewers.extend(owners) |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 1818 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1819 | # Set the reviewer list now so that presubmit checks can access it. |
| 1820 | if options.reviewers: |
| 1821 | change_description.update_reviewers(options.reviewers) |
Edward Lesmes | 8c43c3f | 2021-01-20 00:20:26 +0000 | [diff] [blame] | 1822 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1823 | return change_description |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 1824 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1825 | def _GetTitleForUpload(self, options, multi_change_upload=False): |
| 1826 | # type: (optparse.Values, Optional[bool]) -> str |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 1827 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1828 | # Getting titles for multipl commits is not supported so we return the |
| 1829 | # default. |
| 1830 | if not options.squash or multi_change_upload or options.title: |
| 1831 | return options.title |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1832 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1833 | # On first upload, patchset title is always this string, while |
| 1834 | # options.title gets converted to first line of message. |
| 1835 | if not self.GetIssue(): |
| 1836 | return 'Initial upload' |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 1837 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1838 | # When uploading subsequent patchsets, options.message is taken as the |
| 1839 | # title if options.title is not provided. |
| 1840 | if options.message: |
| 1841 | return options.message.strip() |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 1842 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1843 | # Use the subject of the last commit as title by default. |
| 1844 | title = RunGit(['show', '-s', '--format=%s', 'HEAD']).strip() |
| 1845 | if options.force or options.skip_title: |
| 1846 | return title |
| 1847 | user_title = gclient_utils.AskForData('Title for patchset [%s]: ' % |
| 1848 | title) |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 1849 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1850 | # Use the default title if the user confirms the default with a 'y'. |
| 1851 | if user_title.lower() == 'y': |
| 1852 | return title |
| 1853 | return user_title or title |
mlcui | 3da9171 | 2021-05-05 10:00:30 +0000 | [diff] [blame] | 1854 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1855 | def _GetRefSpecOptions(self, |
| 1856 | options: optparse.Values, |
| 1857 | change_desc: ChangeDescription, |
| 1858 | multi_change_upload: bool = False, |
| 1859 | dogfood_path: bool = False) -> List[str]: |
| 1860 | # Extra options that can be specified at push time. Doc: |
| 1861 | # https://gerrit-review.googlesource.com/Documentation/user-upload.html |
| 1862 | refspec_opts = [] |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 1863 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1864 | # By default, new changes are started in WIP mode, and subsequent |
| 1865 | # patchsets don't send email. At any time, passing --send-mail or |
| 1866 | # --send-email will mark the change ready and send email for that |
| 1867 | # particular patch. |
| 1868 | if options.send_mail: |
| 1869 | refspec_opts.append('ready') |
| 1870 | refspec_opts.append('notify=ALL') |
| 1871 | elif (not self.GetIssue() and options.squash and not dogfood_path): |
| 1872 | refspec_opts.append('wip') |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1873 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1874 | # TODO(tandrii): options.message should be posted as a comment if |
| 1875 | # --send-mail or --send-email is set on non-initial upload as Rietveld |
| 1876 | # used to do it. |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1877 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1878 | # Set options.title in case user was prompted in _GetTitleForUpload and |
| 1879 | # _CMDUploadChange needs to be called again. |
| 1880 | options.title = self._GetTitleForUpload( |
| 1881 | options, multi_change_upload=multi_change_upload) |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1882 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1883 | if options.title: |
| 1884 | # Punctuation and whitespace in |title| must be percent-encoded. |
| 1885 | refspec_opts.append( |
| 1886 | 'm=' + gerrit_util.PercentEncodeForGitRef(options.title)) |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1887 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1888 | if options.private: |
| 1889 | refspec_opts.append('private') |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1890 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1891 | if options.topic: |
| 1892 | # Documentation on Gerrit topics is here: |
| 1893 | # https://gerrit-review.googlesource.com/Documentation/user-upload.html#topic |
| 1894 | refspec_opts.append('topic=%s' % options.topic) |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1895 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1896 | if options.enable_auto_submit: |
| 1897 | refspec_opts.append('l=Auto-Submit+1') |
| 1898 | if options.set_bot_commit: |
| 1899 | refspec_opts.append('l=Bot-Commit+1') |
| 1900 | if options.use_commit_queue: |
| 1901 | refspec_opts.append('l=Commit-Queue+2') |
| 1902 | elif options.cq_dry_run: |
| 1903 | refspec_opts.append('l=Commit-Queue+1') |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1904 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1905 | if change_desc.get_reviewers(tbr_only=True): |
| 1906 | score = gerrit_util.GetCodeReviewTbrScore(self.GetGerritHost(), |
| 1907 | self.GetGerritProject()) |
| 1908 | refspec_opts.append('l=Code-Review+%s' % score) |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1909 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1910 | # Gerrit sorts hashtags, so order is not important. |
| 1911 | hashtags = {change_desc.sanitize_hash_tag(t) for t in options.hashtags} |
| 1912 | # We check GetIssue because we only add hashtags from the |
| 1913 | # description on the first upload. |
| 1914 | # TODO(b/265929888): When we fully launch the new path: |
| 1915 | # 1) remove fetching hashtags from description alltogether |
| 1916 | # 2) Or use descrtiption hashtags for: |
| 1917 | # `not (self.GetIssue() and multi_change_upload)` |
| 1918 | # 3) Or enabled change description tags for multi and single changes |
| 1919 | # by adding them post `git push`. |
| 1920 | if not (self.GetIssue() and dogfood_path): |
| 1921 | hashtags.update(change_desc.get_hash_tags()) |
| 1922 | refspec_opts.extend(['hashtag=%s' % t for t in hashtags]) |
Joanna Wang | a1abbed | 2023-01-24 01:41:05 +0000 | [diff] [blame] | 1923 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1924 | # Note: Reviewers, and ccs are handled individually for each |
| 1925 | # branch/change. |
| 1926 | return refspec_opts |
Joanna Wang | 4049791 | 2023-01-24 21:18:16 +0000 | [diff] [blame] | 1927 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1928 | def PrepareSquashedCommit(self, |
| 1929 | options: optparse.Values, |
| 1930 | parent: str, |
| 1931 | orig_parent: str, |
| 1932 | end_commit: Optional[str] = None) -> _NewUpload: |
| 1933 | """Create a squashed commit to upload. |
Joanna Wang | 05b6034 | 2023-03-29 20:25:57 +0000 | [diff] [blame] | 1934 | |
| 1935 | |
| 1936 | Args: |
| 1937 | parent: The commit to use as the parent for the new squashed. |
| 1938 | orig_parent: The commit that is an actual ancestor of `end_commit`. It |
| 1939 | is part of the same original tree as end_commit, which does not |
| 1940 | contain squashed commits. This is used to create the change |
| 1941 | description for the new squashed commit with: |
| 1942 | `git log orig_parent..end_commit`. |
| 1943 | end_commit: The commit to use as the end of the new squashed commit. |
| 1944 | """ |
Joanna Wang | b88a434 | 2023-01-24 01:28:22 +0000 | [diff] [blame] | 1945 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1946 | if end_commit is None: |
| 1947 | end_commit = RunGit(['rev-parse', self.branchref]).strip() |
Joanna Wang | b88a434 | 2023-01-24 01:28:22 +0000 | [diff] [blame] | 1948 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1949 | reviewers, ccs, change_desc = self._PrepareChange( |
| 1950 | options, orig_parent, end_commit) |
| 1951 | latest_tree = RunGit(['rev-parse', end_commit + ':']).strip() |
| 1952 | with gclient_utils.temporary_file() as desc_tempfile: |
| 1953 | gclient_utils.FileWrite(desc_tempfile, change_desc.description) |
| 1954 | commit_to_push = RunGit( |
| 1955 | ['commit-tree', latest_tree, '-p', parent, '-F', |
| 1956 | desc_tempfile]).strip() |
Joanna Wang | b88a434 | 2023-01-24 01:28:22 +0000 | [diff] [blame] | 1957 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1958 | # Gerrit may or may not update fast enough to return the correct |
| 1959 | # patchset number after we push. Get the pre-upload patchset and |
| 1960 | # increment later. |
| 1961 | prev_patchset = self.GetMostRecentPatchset(update=False) or 0 |
| 1962 | return _NewUpload(reviewers, ccs, commit_to_push, end_commit, parent, |
| 1963 | change_desc, prev_patchset) |
Joanna Wang | b88a434 | 2023-01-24 01:28:22 +0000 | [diff] [blame] | 1964 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1965 | def PrepareCherryPickSquashedCommit(self, options: optparse.Values, |
| 1966 | parent: str) -> _NewUpload: |
| 1967 | """Create a commit cherry-picked on parent to push.""" |
Joanna Wang | e852391 | 2023-01-21 02:05:40 +0000 | [diff] [blame] | 1968 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1969 | # The `parent` is what we will cherry-pick on top of. |
| 1970 | # The `cherry_pick_base` is the beginning range of what |
| 1971 | # we are cherry-picking. |
| 1972 | cherry_pick_base = self.GetCommonAncestorWithUpstream() |
| 1973 | reviewers, ccs, change_desc = self._PrepareChange( |
| 1974 | options, cherry_pick_base, self.branchref) |
Joanna Wang | e852391 | 2023-01-21 02:05:40 +0000 | [diff] [blame] | 1975 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1976 | new_upload_hash = RunGit(['rev-parse', self.branchref]).strip() |
| 1977 | latest_tree = RunGit(['rev-parse', self.branchref + ':']).strip() |
| 1978 | with gclient_utils.temporary_file() as desc_tempfile: |
| 1979 | gclient_utils.FileWrite(desc_tempfile, change_desc.description) |
| 1980 | commit_to_cp = RunGit([ |
| 1981 | 'commit-tree', latest_tree, '-p', cherry_pick_base, '-F', |
| 1982 | desc_tempfile |
| 1983 | ]).strip() |
Joanna Wang | e852391 | 2023-01-21 02:05:40 +0000 | [diff] [blame] | 1984 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1985 | RunGit(['checkout', '-q', parent]) |
| 1986 | ret, _out = RunGitWithCode(['cherry-pick', commit_to_cp]) |
| 1987 | if ret: |
| 1988 | RunGit(['cherry-pick', '--abort']) |
| 1989 | RunGit(['checkout', '-q', self.branch]) |
| 1990 | DieWithError('Could not cleanly cherry-pick') |
Joanna Wang | e852391 | 2023-01-21 02:05:40 +0000 | [diff] [blame] | 1991 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1992 | commit_to_push = RunGit(['rev-parse', 'HEAD']).strip() |
| 1993 | RunGit(['checkout', '-q', self.branch]) |
Joanna Wang | e852391 | 2023-01-21 02:05:40 +0000 | [diff] [blame] | 1994 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1995 | # Gerrit may or may not update fast enough to return the correct |
| 1996 | # patchset number after we push. Get the pre-upload patchset and |
| 1997 | # increment later. |
| 1998 | prev_patchset = self.GetMostRecentPatchset(update=False) or 0 |
| 1999 | return _NewUpload(reviewers, ccs, commit_to_push, new_upload_hash, |
| 2000 | cherry_pick_base, change_desc, prev_patchset) |
Joanna Wang | e852391 | 2023-01-21 02:05:40 +0000 | [diff] [blame] | 2001 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2002 | def _PrepareChange( |
| 2003 | self, options: optparse.Values, parent: str, end_commit: str |
| 2004 | ) -> Tuple[Sequence[str], Sequence[str], ChangeDescription]: |
| 2005 | """Prepares the change to be uploaded.""" |
| 2006 | self.EnsureCanUploadPatchset(options.force) |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2007 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2008 | files = self.GetAffectedFiles(parent, end_commit=end_commit) |
| 2009 | change_desc = self._GetDescriptionForUpload(options, |
| 2010 | [parent, end_commit], files) |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2011 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2012 | watchlist = watchlists.Watchlists(settings.GetRoot()) |
| 2013 | self.ExtendCC(watchlist.GetWatchersForPaths(files)) |
| 2014 | if not options.bypass_hooks: |
| 2015 | hook_results = self.RunHook(committing=False, |
| 2016 | may_prompt=not options.force, |
| 2017 | verbose=options.verbose, |
| 2018 | parallel=options.parallel, |
| 2019 | upstream=parent, |
| 2020 | description=change_desc.description, |
| 2021 | all_files=False) |
| 2022 | self.ExtendCC(hook_results['more_cc']) |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2023 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2024 | # Update the change description and ensure we have a Change Id. |
| 2025 | if self.GetIssue(): |
| 2026 | if options.edit_description: |
| 2027 | change_desc.prompt() |
| 2028 | change_detail = self._GetChangeDetail(['CURRENT_REVISION']) |
| 2029 | change_id = change_detail['change_id'] |
| 2030 | change_desc.ensure_change_id(change_id) |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2031 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2032 | else: # No change issue. First time uploading |
| 2033 | if not options.force and not options.message_file: |
| 2034 | change_desc.prompt() |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2035 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2036 | # Check if user added a change_id in the descripiton. |
| 2037 | change_ids = git_footers.get_footer_change_id( |
| 2038 | change_desc.description) |
| 2039 | if len(change_ids) == 1: |
| 2040 | change_id = change_ids[0] |
| 2041 | else: |
| 2042 | change_id = GenerateGerritChangeId(change_desc.description) |
| 2043 | change_desc.ensure_change_id(change_id) |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2044 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2045 | if options.preserve_tryjobs: |
| 2046 | change_desc.set_preserve_tryjobs() |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2047 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2048 | SaveDescriptionBackup(change_desc) |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2049 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2050 | # Add ccs |
| 2051 | ccs = [] |
| 2052 | # Add default, watchlist, presubmit ccs if this is the initial upload |
| 2053 | # and CL is not private and auto-ccing has not been disabled. |
| 2054 | if not options.private and not options.no_autocc and not self.GetIssue( |
| 2055 | ): |
| 2056 | ccs = self.GetCCList().split(',') |
| 2057 | if len(ccs) > 100: |
| 2058 | lsc = ( |
| 2059 | 'https://chromium.googlesource.com/chromium/src/+/HEAD/docs/' |
| 2060 | 'process/lsc/lsc_workflow.md') |
| 2061 | print('WARNING: This will auto-CC %s users.' % len(ccs)) |
| 2062 | print('LSC may be more appropriate: %s' % lsc) |
| 2063 | print( |
| 2064 | 'You can also use the --no-autocc flag to disable auto-CC.') |
| 2065 | confirm_or_exit(action='continue') |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2066 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2067 | # Add ccs from the --cc flag. |
| 2068 | if options.cc: |
| 2069 | ccs.extend(options.cc) |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2070 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2071 | ccs = [email.strip() for email in ccs if email.strip()] |
| 2072 | if change_desc.get_cced(): |
| 2073 | ccs.extend(change_desc.get_cced()) |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2074 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2075 | return change_desc.get_reviewers(), ccs, change_desc |
Joanna Wang | b46232e | 2023-01-21 01:58:46 +0000 | [diff] [blame] | 2076 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2077 | def PostUploadUpdates(self, options: optparse.Values, |
| 2078 | new_upload: _NewUpload, change_number: str) -> None: |
| 2079 | """Makes necessary post upload changes to the local and remote cl.""" |
| 2080 | if not self.GetIssue(): |
| 2081 | self.SetIssue(change_number) |
Joanna Wang | 4049791 | 2023-01-24 21:18:16 +0000 | [diff] [blame] | 2082 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2083 | self.SetPatchset(new_upload.prev_patchset + 1) |
Joanna Wang | 7603f04 | 2023-03-01 22:17:36 +0000 | [diff] [blame] | 2084 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2085 | self._GitSetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY, |
| 2086 | new_upload.commit_to_push) |
| 2087 | self._GitSetBranchConfigValue(LAST_UPLOAD_HASH_CONFIG_KEY, |
| 2088 | new_upload.new_last_uploaded_commit) |
Joanna Wang | 4049791 | 2023-01-24 21:18:16 +0000 | [diff] [blame] | 2089 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2090 | if settings.GetRunPostUploadHook(): |
| 2091 | self.RunPostUploadHook(options.verbose, new_upload.parent, |
| 2092 | new_upload.change_desc.description) |
Joanna Wang | 4049791 | 2023-01-24 21:18:16 +0000 | [diff] [blame] | 2093 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2094 | if new_upload.reviewers or new_upload.ccs: |
| 2095 | gerrit_util.AddReviewers(self.GetGerritHost(), |
| 2096 | self._GerritChangeIdentifier(), |
| 2097 | reviewers=new_upload.reviewers, |
| 2098 | ccs=new_upload.ccs, |
| 2099 | notify=bool(options.send_mail)) |
Joanna Wang | 4049791 | 2023-01-24 21:18:16 +0000 | [diff] [blame] | 2100 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2101 | def CMDUpload(self, options, git_diff_args, orig_args): |
| 2102 | """Uploads a change to codereview.""" |
| 2103 | custom_cl_base = None |
| 2104 | if git_diff_args: |
| 2105 | custom_cl_base = base_branch = git_diff_args[0] |
| 2106 | else: |
| 2107 | if self.GetBranch() is None: |
| 2108 | DieWithError( |
| 2109 | 'Can\'t upload from detached HEAD state. Get on a branch!') |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2110 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2111 | # Default to diffing against common ancestor of upstream branch |
| 2112 | base_branch = self.GetCommonAncestorWithUpstream() |
| 2113 | git_diff_args = [base_branch, 'HEAD'] |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2114 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2115 | # Fast best-effort checks to abort before running potentially expensive |
| 2116 | # hooks if uploading is likely to fail anyway. Passing these checks does |
| 2117 | # not guarantee that uploading will not fail. |
| 2118 | self.EnsureAuthenticated(force=options.force) |
| 2119 | self.EnsureCanUploadPatchset(force=options.force) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2120 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2121 | print(f'Processing {_GetCommitCountSummary(*git_diff_args)}...') |
Daniel Cheng | 66d0f15 | 2023-08-29 23:21:58 +0000 | [diff] [blame] | 2122 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2123 | # Apply watchlists on upload. |
| 2124 | watchlist = watchlists.Watchlists(settings.GetRoot()) |
| 2125 | files = self.GetAffectedFiles(base_branch) |
| 2126 | if not options.bypass_watchlists: |
| 2127 | self.ExtendCC(watchlist.GetWatchersForPaths(files)) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2128 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2129 | change_desc = self._GetDescriptionForUpload(options, git_diff_args, |
| 2130 | files) |
| 2131 | if not options.bypass_hooks: |
| 2132 | hook_results = self.RunHook(committing=False, |
| 2133 | may_prompt=not options.force, |
| 2134 | verbose=options.verbose, |
| 2135 | parallel=options.parallel, |
| 2136 | upstream=base_branch, |
| 2137 | description=change_desc.description, |
| 2138 | all_files=False) |
| 2139 | self.ExtendCC(hook_results['more_cc']) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2140 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2141 | print_stats(git_diff_args) |
| 2142 | ret = self.CMDUploadChange(options, git_diff_args, custom_cl_base, |
| 2143 | change_desc) |
| 2144 | if not ret: |
| 2145 | if self.GetBranch() is not None: |
| 2146 | self._GitSetBranchConfigValue( |
| 2147 | LAST_UPLOAD_HASH_CONFIG_KEY, |
| 2148 | scm.GIT.ResolveCommit(settings.GetRoot(), 'HEAD')) |
| 2149 | # Run post upload hooks, if specified. |
| 2150 | if settings.GetRunPostUploadHook(): |
| 2151 | self.RunPostUploadHook(options.verbose, base_branch, |
| 2152 | change_desc.description) |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2153 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2154 | # Upload all dependencies if specified. |
| 2155 | if options.dependencies: |
| 2156 | print() |
| 2157 | print('--dependencies has been specified.') |
| 2158 | print('All dependent local branches will be re-uploaded.') |
| 2159 | print() |
| 2160 | # Remove the dependencies flag from args so that we do not end |
| 2161 | # up in a loop. |
| 2162 | orig_args.remove('--dependencies') |
| 2163 | ret = upload_branch_deps(self, orig_args, options.force) |
| 2164 | return ret |
tandrii@chromium.org | 9e6c3a5 | 2016-04-12 14:13:08 +0000 | [diff] [blame] | 2165 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2166 | def SetCQState(self, new_state): |
| 2167 | """Updates the CQ state for the latest patchset. |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2168 | |
Struan Shrimpton | 8b2072b | 2023-07-31 21:01:26 +0000 | [diff] [blame] | 2169 | Issue must have been already uploaded and known. |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 2170 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2171 | assert new_state in _CQState.ALL_STATES |
| 2172 | assert self.GetIssue() |
| 2173 | try: |
| 2174 | vote_map = { |
| 2175 | _CQState.NONE: 0, |
| 2176 | _CQState.DRY_RUN: 1, |
| 2177 | _CQState.COMMIT: 2, |
| 2178 | } |
| 2179 | labels = {'Commit-Queue': vote_map[new_state]} |
| 2180 | notify = False if new_state == _CQState.DRY_RUN else None |
| 2181 | gerrit_util.SetReview(self.GetGerritHost(), |
| 2182 | self._GerritChangeIdentifier(), |
| 2183 | labels=labels, |
| 2184 | notify=notify) |
| 2185 | return 0 |
| 2186 | except KeyboardInterrupt: |
| 2187 | raise |
| 2188 | except: |
| 2189 | print( |
| 2190 | 'WARNING: Failed to %s.\n' |
| 2191 | 'Either:\n' |
| 2192 | ' * Your project has no CQ,\n' |
| 2193 | ' * You don\'t have permission to change the CQ state,\n' |
| 2194 | ' * There\'s a bug in this code (see stack trace below).\n' |
| 2195 | 'Consider specifying which bots to trigger manually or asking your ' |
| 2196 | 'project owners for permissions or contacting Chrome Infra at:\n' |
| 2197 | 'https://www.chromium.org/infra\n\n' % |
| 2198 | ('cancel CQ' if new_state == _CQState.NONE else 'trigger CQ')) |
| 2199 | # Still raise exception so that stack trace is printed. |
| 2200 | raise |
qyearsley | 1fdfcb6 | 2016-10-24 13:22:03 -0700 | [diff] [blame] | 2201 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2202 | def GetGerritHost(self): |
| 2203 | # Lazy load of configs. |
| 2204 | self.GetCodereviewServer() |
Aravind Vasudevan | 0e3589e | 2023-05-25 23:00:30 +0000 | [diff] [blame] | 2205 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2206 | if self._gerrit_host and '.' not in self._gerrit_host: |
| 2207 | # Abbreviated domain like "chromium" instead of |
| 2208 | # chromium.googlesource.com. |
| 2209 | parsed = urllib.parse.urlparse(self.GetRemoteUrl()) |
| 2210 | if parsed.scheme == 'sso': |
| 2211 | self._gerrit_host = '%s.googlesource.com' % self._gerrit_host |
| 2212 | self._gerrit_server = 'https://%s' % self._gerrit_host |
Aravind Vasudevan | 0e3589e | 2023-05-25 23:00:30 +0000 | [diff] [blame] | 2213 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2214 | return self._gerrit_host |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2215 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2216 | def _GetGitHost(self): |
| 2217 | """Returns git host to be used when uploading change to Gerrit.""" |
| 2218 | remote_url = self.GetRemoteUrl() |
| 2219 | if not remote_url: |
| 2220 | return None |
| 2221 | return urllib.parse.urlparse(remote_url).netloc |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2222 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2223 | def GetCodereviewServer(self): |
| 2224 | if not self._gerrit_server: |
| 2225 | # If we're on a branch then get the server potentially associated |
| 2226 | # with that branch. |
| 2227 | if self.GetIssue() and self.GetBranch(): |
| 2228 | self._gerrit_server = self._GitGetBranchConfigValue( |
| 2229 | CODEREVIEW_SERVER_CONFIG_KEY) |
| 2230 | if self._gerrit_server: |
| 2231 | self._gerrit_host = urllib.parse.urlparse( |
| 2232 | self._gerrit_server).netloc |
| 2233 | if not self._gerrit_server: |
| 2234 | url = urllib.parse.urlparse(self.GetRemoteUrl()) |
| 2235 | parts = url.netloc.split('.') |
Aravind Vasudevan | 0e3589e | 2023-05-25 23:00:30 +0000 | [diff] [blame] | 2236 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2237 | # We assume repo to be hosted on Gerrit, and hence Gerrit server |
| 2238 | # has "-review" suffix for lowest level subdomain. |
| 2239 | parts[0] = parts[0] + '-review' |
Aravind Vasudevan | 0e3589e | 2023-05-25 23:00:30 +0000 | [diff] [blame] | 2240 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2241 | if url.scheme == 'sso' and len(parts) == 1: |
| 2242 | # sso:// uses abbreivated hosts, eg. sso://chromium instead |
| 2243 | # of chromium.googlesource.com. Hence, for code review |
| 2244 | # server, they need to be expanded. |
| 2245 | parts[0] += '.googlesource.com' |
Aravind Vasudevan | 0e3589e | 2023-05-25 23:00:30 +0000 | [diff] [blame] | 2246 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2247 | self._gerrit_host = '.'.join(parts) |
| 2248 | self._gerrit_server = 'https://%s' % self._gerrit_host |
| 2249 | return self._gerrit_server |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2250 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2251 | def GetGerritProject(self): |
| 2252 | """Returns Gerrit project name based on remote git URL.""" |
| 2253 | remote_url = self.GetRemoteUrl() |
| 2254 | if remote_url is None: |
| 2255 | logging.warning('can\'t detect Gerrit project.') |
| 2256 | return None |
| 2257 | project = urllib.parse.urlparse(remote_url).path.strip('/') |
| 2258 | if project.endswith('.git'): |
| 2259 | project = project[:-len('.git')] |
| 2260 | # *.googlesource.com hosts ensure that Git/Gerrit projects don't start |
| 2261 | # with 'a/' prefix, because 'a/' prefix is used to force authentication |
| 2262 | # in gitiles/git-over-https protocol. E.g., |
| 2263 | # https://chromium.googlesource.com/a/v8/v8 refers to the same |
| 2264 | # repo/project as https://chromium.googlesource.com/v8/v8 |
| 2265 | if project.startswith('a/'): |
| 2266 | project = project[len('a/'):] |
| 2267 | return project |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 2268 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2269 | def _GerritChangeIdentifier(self): |
| 2270 | """Handy method for gerrit_util.ChangeIdentifier for a given CL. |
Andrii Shyshkalov | d06cc78 | 2018-08-23 17:24:19 +0000 | [diff] [blame] | 2271 | |
| 2272 | Not to be confused by value of "Change-Id:" footer. |
Andrii Shyshkalov | 2d0e03c | 2018-08-25 04:18:09 +0000 | [diff] [blame] | 2273 | If Gerrit project can be determined, this will speed up Gerrit HTTP API RPC. |
Andrii Shyshkalov | d06cc78 | 2018-08-23 17:24:19 +0000 | [diff] [blame] | 2274 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2275 | project = self.GetGerritProject() |
| 2276 | if project: |
| 2277 | return gerrit_util.ChangeIdentifier(project, self.GetIssue()) |
| 2278 | # Fall back on still unique, but less efficient change number. |
| 2279 | return str(self.GetIssue()) |
Andrii Shyshkalov | d06cc78 | 2018-08-23 17:24:19 +0000 | [diff] [blame] | 2280 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2281 | def EnsureAuthenticated(self, force, refresh=None): |
| 2282 | """Best effort check that user is authenticated with Gerrit server.""" |
| 2283 | if settings.GetGerritSkipEnsureAuthenticated(): |
| 2284 | # For projects with unusual authentication schemes. |
| 2285 | # See http://crbug.com/603378. |
| 2286 | return |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 2287 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2288 | # Check presence of cookies only if using cookies-based auth method. |
| 2289 | cookie_auth = gerrit_util.Authenticator.get() |
| 2290 | if not isinstance(cookie_auth, gerrit_util.CookiesAuthenticator): |
| 2291 | return |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 2292 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2293 | remote_url = self.GetRemoteUrl() |
| 2294 | if remote_url is None: |
| 2295 | logging.warning('invalid remote') |
| 2296 | return |
| 2297 | if urllib.parse.urlparse(remote_url).scheme not in ['https', 'sso']: |
| 2298 | logging.warning( |
| 2299 | 'Ignoring branch %(branch)s with non-https/sso remote ' |
| 2300 | '%(remote)s', { |
| 2301 | 'branch': self.branch, |
| 2302 | 'remote': self.GetRemoteUrl() |
| 2303 | }) |
| 2304 | return |
Daniel Cheng | cf6269b | 2019-05-18 01:02:12 +0000 | [diff] [blame] | 2305 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2306 | # Lazy-loader to identify Gerrit and Git hosts. |
| 2307 | self.GetCodereviewServer() |
| 2308 | git_host = self._GetGitHost() |
| 2309 | assert self._gerrit_server and self._gerrit_host and git_host |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2310 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2311 | gerrit_auth = cookie_auth.get_auth_header(self._gerrit_host) |
| 2312 | git_auth = cookie_auth.get_auth_header(git_host) |
| 2313 | if gerrit_auth and git_auth: |
| 2314 | if gerrit_auth == git_auth: |
| 2315 | return |
| 2316 | all_gsrc = cookie_auth.get_auth_header( |
| 2317 | 'd0esN0tEx1st.googlesource.com') |
| 2318 | print( |
| 2319 | 'WARNING: You have different credentials for Gerrit and git hosts:\n' |
| 2320 | ' %s\n' |
| 2321 | ' %s\n' |
| 2322 | ' Consider running the following command:\n' |
| 2323 | ' git cl creds-check\n' |
| 2324 | ' %s\n' |
| 2325 | ' %s' % |
| 2326 | (git_host, self._gerrit_host, |
| 2327 | ('Hint: delete creds for .googlesource.com' if all_gsrc else |
| 2328 | ''), cookie_auth.get_new_password_message(git_host))) |
| 2329 | if not force: |
| 2330 | confirm_or_exit('If you know what you are doing', |
| 2331 | action='continue') |
| 2332 | return |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 2333 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2334 | missing = (([] if gerrit_auth else [self._gerrit_host]) + |
| 2335 | ([] if git_auth else [git_host])) |
| 2336 | DieWithError('Credentials for the following hosts are required:\n' |
| 2337 | ' %s\n' |
| 2338 | 'These are read from %s (or legacy %s)\n' |
| 2339 | '%s' % |
| 2340 | ('\n '.join(missing), cookie_auth.get_gitcookies_path(), |
| 2341 | cookie_auth.get_netrc_path(), |
| 2342 | cookie_auth.get_new_password_message(git_host))) |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 2343 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2344 | def EnsureCanUploadPatchset(self, force): |
| 2345 | if not self.GetIssue(): |
| 2346 | return |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 2347 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2348 | status = self._GetChangeDetail()['status'] |
| 2349 | if status == 'ABANDONED': |
| 2350 | DieWithError( |
| 2351 | 'Change %s has been abandoned, new uploads are not allowed' % |
| 2352 | (self.GetIssueURL())) |
| 2353 | if status == 'MERGED': |
| 2354 | answer = gclient_utils.AskForData( |
| 2355 | 'Change %s has been submitted, new uploads are not allowed. ' |
| 2356 | 'Would you like to start a new change (Y/n)?' % |
| 2357 | self.GetIssueURL()).lower() |
| 2358 | if answer not in ('y', ''): |
| 2359 | DieWithError('New uploads are not allowed.') |
| 2360 | self.SetIssue() |
| 2361 | return |
Andrii Shyshkalov | 3e63142 | 2017-02-16 17:46:44 +0100 | [diff] [blame] | 2362 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2363 | # TODO(vadimsh): For some reason the chunk of code below was skipped if |
| 2364 | # 'is_gce' is True. I'm just refactoring it to be 'skip if not cookies'. |
| 2365 | # Apparently this check is not very important? Otherwise get_auth_email |
| 2366 | # could have been added to other implementations of Authenticator. |
| 2367 | cookies_auth = gerrit_util.Authenticator.get() |
| 2368 | if not isinstance(cookies_auth, gerrit_util.CookiesAuthenticator): |
| 2369 | return |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 2370 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2371 | cookies_user = cookies_auth.get_auth_email(self.GetGerritHost()) |
| 2372 | if self.GetIssueOwner() == cookies_user: |
| 2373 | return |
| 2374 | logging.debug('change %s owner is %s, cookies user is %s', |
| 2375 | self.GetIssue(), self.GetIssueOwner(), cookies_user) |
| 2376 | # Maybe user has linked accounts or something like that, |
| 2377 | # so ask what Gerrit thinks of this user. |
| 2378 | details = gerrit_util.GetAccountDetails(self.GetGerritHost(), 'self') |
| 2379 | if details['email'] == self.GetIssueOwner(): |
| 2380 | return |
| 2381 | if not force: |
| 2382 | print( |
| 2383 | 'WARNING: Change %s is owned by %s, but you authenticate to Gerrit ' |
| 2384 | 'as %s.\n' |
| 2385 | 'Uploading may fail due to lack of permissions.' % |
| 2386 | (self.GetIssue(), self.GetIssueOwner(), details['email'])) |
| 2387 | confirm_or_exit(action='upload') |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 2388 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2389 | def GetStatus(self): |
| 2390 | """Applies a rough heuristic to give a simple summary of an issue's review |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2391 | or CQ status, assuming adherence to a common workflow. |
| 2392 | |
| 2393 | Returns None if no issue for this branch, or one of the following keywords: |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2394 | * 'error' - error from review tool (including deleted issues) |
| 2395 | * 'unsent' - no reviewers added |
| 2396 | * 'waiting' - waiting for review |
| 2397 | * 'reply' - waiting for uploader to reply to review |
| 2398 | * 'lgtm' - Code-Review label has been set |
Andrii Shyshkalov | 0e889b7 | 2019-07-15 22:28:48 +0000 | [diff] [blame] | 2399 | * 'dry-run' - dry-running in the CQ |
| 2400 | * 'commit' - in the CQ |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2401 | * 'closed' - successfully submitted or abandoned |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2402 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2403 | if not self.GetIssue(): |
| 2404 | return None |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2405 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2406 | try: |
| 2407 | data = self._GetChangeDetail( |
| 2408 | ['DETAILED_LABELS', 'CURRENT_REVISION', 'SUBMITTABLE']) |
| 2409 | except GerritChangeNotExists: |
| 2410 | return 'error' |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2411 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2412 | if data['status'] in ('ABANDONED', 'MERGED'): |
| 2413 | return 'closed' |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2414 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2415 | cq_label = data['labels'].get('Commit-Queue', {}) |
| 2416 | max_cq_vote = 0 |
| 2417 | for vote in cq_label.get('all', []): |
| 2418 | max_cq_vote = max(max_cq_vote, vote.get('value', 0)) |
| 2419 | if max_cq_vote == 2: |
| 2420 | return 'commit' |
| 2421 | if max_cq_vote == 1: |
| 2422 | return 'dry-run' |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2423 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2424 | if data['labels'].get('Code-Review', {}).get('approved'): |
| 2425 | return 'lgtm' |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2426 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2427 | if not data.get('reviewers', {}).get('REVIEWER', []): |
| 2428 | return 'unsent' |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2429 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2430 | owner = data['owner'].get('_account_id') |
| 2431 | messages = sorted(data.get('messages', []), key=lambda m: m.get('date')) |
| 2432 | while messages: |
| 2433 | m = messages.pop() |
| 2434 | if (m.get('tag', '').startswith('autogenerated:cq') |
| 2435 | or m.get('tag', '').startswith('autogenerated:cv')): |
| 2436 | # Ignore replies from LUCI CV/CQ. |
| 2437 | continue |
| 2438 | if m.get('author', {}).get('_account_id') == owner: |
| 2439 | # Most recent message was by owner. |
| 2440 | return 'waiting' |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 2441 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2442 | # Some reply from non-owner. |
| 2443 | return 'reply' |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 2444 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2445 | # Somehow there are no messages even though there are reviewers. |
| 2446 | return 'unsent' |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2447 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2448 | def GetMostRecentPatchset(self, update=True): |
| 2449 | if not self.GetIssue(): |
| 2450 | return None |
Edward Lemur | 6c6827c | 2020-02-06 21:15:18 +0000 | [diff] [blame] | 2451 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2452 | data = self._GetChangeDetail(['CURRENT_REVISION']) |
| 2453 | patchset = data['revisions'][data['current_revision']]['_number'] |
| 2454 | if update: |
| 2455 | self.SetPatchset(patchset) |
| 2456 | return patchset |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2457 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2458 | def _IsPatchsetRangeSignificant(self, lower, upper): |
| 2459 | """Returns True if the inclusive range of patchsets contains any reworks or |
Gavin Mak | f35a9eb | 2022-11-17 18:34:36 +0000 | [diff] [blame] | 2460 | rebases.""" |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2461 | if not self.GetIssue(): |
| 2462 | return False |
Gavin Mak | f35a9eb | 2022-11-17 18:34:36 +0000 | [diff] [blame] | 2463 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2464 | data = self._GetChangeDetail(['ALL_REVISIONS']) |
| 2465 | ps_kind = {} |
| 2466 | for rev_info in data.get('revisions', {}).values(): |
| 2467 | ps_kind[rev_info['_number']] = rev_info.get('kind', '') |
Gavin Mak | f35a9eb | 2022-11-17 18:34:36 +0000 | [diff] [blame] | 2468 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2469 | for ps in range(lower, upper + 1): |
| 2470 | assert ps in ps_kind, 'expected patchset %d in change detail' % ps |
| 2471 | if ps_kind[ps] not in ('NO_CHANGE', 'NO_CODE_CHANGE'): |
| 2472 | return True |
| 2473 | return False |
Gavin Mak | f35a9eb | 2022-11-17 18:34:36 +0000 | [diff] [blame] | 2474 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2475 | def GetMostRecentDryRunPatchset(self): |
| 2476 | """Get patchsets equivalent to the most recent patchset and return |
Gavin Mak | e61ccc5 | 2020-11-13 00:12:57 +0000 | [diff] [blame] | 2477 | the patchset with the latest dry run. If none have been dry run, return |
| 2478 | the latest patchset.""" |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2479 | if not self.GetIssue(): |
| 2480 | return None |
Gavin Mak | e61ccc5 | 2020-11-13 00:12:57 +0000 | [diff] [blame] | 2481 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2482 | data = self._GetChangeDetail(['ALL_REVISIONS']) |
| 2483 | patchset = data['revisions'][data['current_revision']]['_number'] |
| 2484 | dry_run = { |
| 2485 | int(m['_revision_number']) |
| 2486 | for m in data.get('messages', []) |
| 2487 | if m.get('tag', '').endswith('dry-run') |
| 2488 | } |
Gavin Mak | e61ccc5 | 2020-11-13 00:12:57 +0000 | [diff] [blame] | 2489 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2490 | for revision_info in sorted(data.get('revisions', {}).values(), |
| 2491 | key=lambda c: c['_number'], |
| 2492 | reverse=True): |
| 2493 | if revision_info['_number'] in dry_run: |
| 2494 | patchset = revision_info['_number'] |
| 2495 | break |
| 2496 | if revision_info.get('kind', '') not in \ |
| 2497 | ('NO_CHANGE', 'NO_CODE_CHANGE', 'TRIVIAL_REBASE'): |
| 2498 | break |
| 2499 | self.SetPatchset(patchset) |
| 2500 | return patchset |
Gavin Mak | e61ccc5 | 2020-11-13 00:12:57 +0000 | [diff] [blame] | 2501 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2502 | def AddComment(self, message, publish=None): |
| 2503 | gerrit_util.SetReview(self.GetGerritHost(), |
| 2504 | self._GerritChangeIdentifier(), |
| 2505 | msg=message, |
| 2506 | ready=publish) |
Andrii Shyshkalov | 625986d | 2017-03-16 00:24:37 +0100 | [diff] [blame] | 2507 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2508 | def GetCommentsSummary(self, readable=True): |
| 2509 | # DETAILED_ACCOUNTS is to get emails in accounts. |
| 2510 | # CURRENT_REVISION is included to get the latest patchset so that |
| 2511 | # only the robot comments from the latest patchset can be shown. |
| 2512 | messages = self._GetChangeDetail( |
| 2513 | options=['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION']).get( |
| 2514 | 'messages', []) |
| 2515 | file_comments = gerrit_util.GetChangeComments( |
| 2516 | self.GetGerritHost(), self._GerritChangeIdentifier()) |
| 2517 | robot_file_comments = gerrit_util.GetChangeRobotComments( |
| 2518 | self.GetGerritHost(), self._GerritChangeIdentifier()) |
Quinten Yearsley | 0e617c0 | 2019-02-20 00:37:03 +0000 | [diff] [blame] | 2519 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2520 | # Add the robot comments onto the list of comments, but only |
| 2521 | # keep those that are from the latest patchset. |
| 2522 | latest_patch_set = self.GetMostRecentPatchset() |
| 2523 | for path, robot_comments in robot_file_comments.items(): |
| 2524 | line_comments = file_comments.setdefault(path, []) |
| 2525 | line_comments.extend([ |
| 2526 | c for c in robot_comments if c['patch_set'] == latest_patch_set |
| 2527 | ]) |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2528 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2529 | # Build dictionary of file comments for easy access and sorting later. |
| 2530 | # {author+date: {path: {patchset: {line: url+message}}}} |
| 2531 | comments = collections.defaultdict(lambda: collections.defaultdict( |
| 2532 | lambda: collections.defaultdict(dict))) |
Andrii Shyshkalov | a3762a9 | 2020-11-25 10:20:42 +0000 | [diff] [blame] | 2533 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2534 | server = self.GetCodereviewServer() |
| 2535 | if server in _KNOWN_GERRIT_TO_SHORT_URLS: |
| 2536 | # /c/ is automatically added by short URL server. |
| 2537 | url_prefix = '%s/%s' % (_KNOWN_GERRIT_TO_SHORT_URLS[server], |
| 2538 | self.GetIssue()) |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2539 | else: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2540 | url_prefix = '%s/c/%s' % (server, self.GetIssue()) |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2541 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2542 | for path, line_comments in file_comments.items(): |
| 2543 | for comment in line_comments: |
| 2544 | tag = comment.get('tag', '') |
| 2545 | if tag.startswith( |
| 2546 | 'autogenerated') and 'robot_id' not in comment: |
| 2547 | continue |
| 2548 | key = (comment['author']['email'], comment['updated']) |
| 2549 | if comment.get('side', 'REVISION') == 'PARENT': |
| 2550 | patchset = 'Base' |
| 2551 | else: |
| 2552 | patchset = 'PS%d' % comment['patch_set'] |
| 2553 | line = comment.get('line', 0) |
| 2554 | url = ('%s/%s/%s#%s%s' % |
| 2555 | (url_prefix, comment['patch_set'], |
| 2556 | path, 'b' if comment.get('side') == 'PARENT' else '', |
| 2557 | str(line) if line else '')) |
| 2558 | comments[key][path][patchset][line] = (url, comment['message']) |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 2559 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2560 | summaries = [] |
| 2561 | for msg in messages: |
| 2562 | summary = self._BuildCommentSummary(msg, comments, readable) |
| 2563 | if summary: |
| 2564 | summaries.append(summary) |
| 2565 | return summaries |
Josip Sokcevic | 266129c | 2021-11-09 00:22:00 +0000 | [diff] [blame] | 2566 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2567 | @staticmethod |
| 2568 | def _BuildCommentSummary(msg, comments, readable): |
| 2569 | if 'email' not in msg['author']: |
| 2570 | # Some bot accounts may not have an email associated. |
| 2571 | return None |
Quinten Yearsley | 0e617c0 | 2019-02-20 00:37:03 +0000 | [diff] [blame] | 2572 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2573 | key = (msg['author']['email'], msg['date']) |
| 2574 | # Don't bother showing autogenerated messages that don't have associated |
| 2575 | # file or line comments. this will filter out most autogenerated |
| 2576 | # messages, but will keep robot comments like those from Tricium. |
| 2577 | is_autogenerated = msg.get('tag', '').startswith('autogenerated') |
| 2578 | if is_autogenerated and not comments.get(key): |
| 2579 | return None |
| 2580 | message = msg['message'] |
| 2581 | # Gerrit spits out nanoseconds. |
| 2582 | assert len(msg['date'].split('.')[-1]) == 9 |
| 2583 | date = datetime.datetime.strptime(msg['date'][:-3], |
| 2584 | '%Y-%m-%d %H:%M:%S.%f') |
| 2585 | if key in comments: |
| 2586 | message += '\n' |
| 2587 | for path, patchsets in sorted(comments.get(key, {}).items()): |
| 2588 | if readable: |
| 2589 | message += '\n%s' % path |
| 2590 | for patchset, lines in sorted(patchsets.items()): |
| 2591 | for line, (url, content) in sorted(lines.items()): |
| 2592 | if line: |
| 2593 | line_str = 'Line %d' % line |
| 2594 | path_str = '%s:%d:' % (path, line) |
| 2595 | else: |
| 2596 | line_str = 'File comment' |
| 2597 | path_str = '%s:0:' % path |
| 2598 | if readable: |
| 2599 | message += '\n %s, %s: %s' % (patchset, line_str, url) |
| 2600 | message += '\n %s\n' % content |
| 2601 | else: |
| 2602 | message += '\n%s ' % path_str |
| 2603 | message += '\n%s\n' % content |
Andrii Shyshkalov | d8aa49f | 2017-03-17 16:05:49 +0100 | [diff] [blame] | 2604 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2605 | return _CommentSummary( |
| 2606 | date=date, |
| 2607 | message=message, |
| 2608 | sender=msg['author']['email'], |
| 2609 | autogenerated=is_autogenerated, |
| 2610 | # These could be inferred from the text messages and correlated with |
| 2611 | # Code-Review label maximum, however this is not reliable. |
| 2612 | # Leaving as is until the need arises. |
| 2613 | approval=False, |
| 2614 | disapproval=False, |
| 2615 | ) |
tandrii@chromium.org | aa5ced1 | 2016-03-29 09:41:14 +0000 | [diff] [blame] | 2616 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2617 | def CloseIssue(self): |
| 2618 | gerrit_util.AbandonChange(self.GetGerritHost(), |
| 2619 | self._GerritChangeIdentifier(), |
| 2620 | msg='') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 2621 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2622 | def SubmitIssue(self): |
| 2623 | gerrit_util.SubmitChange(self.GetGerritHost(), |
| 2624 | self._GerritChangeIdentifier()) |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2625 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2626 | def _GetChangeDetail(self, options=None): |
| 2627 | """Returns details of associated Gerrit change and caching results.""" |
| 2628 | options = options or [] |
| 2629 | assert self.GetIssue(), 'issue is required to query Gerrit' |
Andrii Shyshkalov | 8039be7 | 2017-01-26 09:38:18 +0100 | [diff] [blame] | 2630 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2631 | # Optimization to avoid multiple RPCs: |
| 2632 | if 'CURRENT_REVISION' in options or 'ALL_REVISIONS' in options: |
| 2633 | options.append('CURRENT_COMMIT') |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2634 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2635 | # Normalize issue and options for consistent keys in cache. |
| 2636 | cache_key = str(self.GetIssue()) |
| 2637 | options_set = frozenset(o.upper() for o in options) |
| 2638 | |
| 2639 | for cached_options_set, data in self._detail_cache.get(cache_key, []): |
| 2640 | # Assumption: data fetched before with extra options is suitable |
| 2641 | # for return for a smaller set of options. |
| 2642 | # For example, if we cached data for |
| 2643 | # options=[CURRENT_REVISION, DETAILED_FOOTERS] |
| 2644 | # and request is for options=[CURRENT_REVISION], |
| 2645 | # THEN we can return prior cached data. |
| 2646 | if options_set.issubset(cached_options_set): |
| 2647 | return data |
| 2648 | |
| 2649 | try: |
| 2650 | data = gerrit_util.GetChangeDetail(self.GetGerritHost(), |
| 2651 | self._GerritChangeIdentifier(), |
| 2652 | options_set) |
| 2653 | except gerrit_util.GerritError as e: |
| 2654 | if e.http_status == 404: |
| 2655 | raise GerritChangeNotExists(self.GetIssue(), |
| 2656 | self.GetCodereviewServer()) |
| 2657 | raise |
| 2658 | |
| 2659 | self._detail_cache.setdefault(cache_key, []).append((options_set, data)) |
Edward Lesmes | 7677e5c | 2020-02-19 20:39:03 +0000 | [diff] [blame] | 2660 | return data |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2661 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2662 | def _GetChangeCommit(self, revision='current'): |
| 2663 | assert self.GetIssue(), 'issue must be set to query Gerrit' |
| 2664 | try: |
| 2665 | data = gerrit_util.GetChangeCommit(self.GetGerritHost(), |
| 2666 | self._GerritChangeIdentifier(), |
| 2667 | revision) |
| 2668 | except gerrit_util.GerritError as e: |
| 2669 | if e.http_status == 404: |
| 2670 | raise GerritChangeNotExists(self.GetIssue(), |
| 2671 | self.GetCodereviewServer()) |
| 2672 | raise |
| 2673 | return data |
Andrii Shyshkalov | 258e0a6 | 2017-01-24 16:50:57 +0100 | [diff] [blame] | 2674 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2675 | def _IsCqConfigured(self): |
| 2676 | detail = self._GetChangeDetail(['LABELS']) |
| 2677 | return u'Commit-Queue' in detail.get('labels', {}) |
tandrii@chromium.org | 013a280 | 2016-03-29 09:52:33 +0000 | [diff] [blame] | 2678 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2679 | def CMDLand(self, force, bypass_hooks, verbose, parallel, resultdb, realm): |
| 2680 | if git_common.is_dirty_git_tree('land'): |
| 2681 | return 1 |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 2682 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2683 | detail = self._GetChangeDetail(['CURRENT_REVISION', 'LABELS']) |
| 2684 | if not force and self._IsCqConfigured(): |
| 2685 | confirm_or_exit( |
| 2686 | '\nIt seems this repository has a CQ, ' |
| 2687 | 'which can test and land changes for you. ' |
| 2688 | 'Are you sure you wish to bypass it?\n', |
| 2689 | action='bypass CQ') |
| 2690 | differs = True |
| 2691 | last_upload = self._GitGetBranchConfigValue( |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 2692 | GERRIT_SQUASH_HASH_CONFIG_KEY) |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2693 | # Note: git diff outputs nothing if there is no diff. |
| 2694 | if not last_upload or RunGit(['diff', last_upload]).strip(): |
| 2695 | print( |
| 2696 | 'WARNING: Some changes from local branch haven\'t been uploaded.' |
| 2697 | ) |
Edward Lemur | 5a644f8 | 2020-03-18 16:44:57 +0000 | [diff] [blame] | 2698 | else: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2699 | if detail['current_revision'] == last_upload: |
| 2700 | differs = False |
| 2701 | else: |
| 2702 | print( |
| 2703 | 'WARNING: Local branch contents differ from latest uploaded ' |
| 2704 | 'patchset.') |
| 2705 | if differs: |
| 2706 | if not force: |
| 2707 | confirm_or_exit( |
| 2708 | 'Do you want to submit latest Gerrit patchset and bypass hooks?\n', |
| 2709 | action='submit') |
| 2710 | print( |
| 2711 | 'WARNING: Bypassing hooks and submitting latest uploaded patchset.' |
| 2712 | ) |
| 2713 | elif not bypass_hooks: |
| 2714 | upstream = self.GetCommonAncestorWithUpstream() |
| 2715 | if self.GetIssue(): |
| 2716 | description = self.FetchDescription() |
| 2717 | else: |
| 2718 | description = _create_description_from_log([upstream]) |
| 2719 | self.RunHook(committing=True, |
| 2720 | may_prompt=not force, |
| 2721 | verbose=verbose, |
| 2722 | parallel=parallel, |
| 2723 | upstream=upstream, |
| 2724 | description=description, |
| 2725 | all_files=False, |
| 2726 | resultdb=resultdb, |
| 2727 | realm=realm) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2728 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2729 | self.SubmitIssue() |
| 2730 | print('Issue %s has been submitted.' % self.GetIssueURL()) |
| 2731 | links = self._GetChangeCommit().get('web_links', []) |
| 2732 | for link in links: |
| 2733 | if link.get('name') in ['gitiles', 'browse'] and link.get('url'): |
| 2734 | print('Landed as: %s' % link.get('url')) |
| 2735 | break |
| 2736 | return 0 |
Robert Iannucci | db02dd0 | 2017-04-19 12:18:20 -0700 | [diff] [blame] | 2737 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2738 | def CMDPatchWithParsedIssue(self, parsed_issue_arg, nocommit, force, |
| 2739 | newbranch): |
| 2740 | assert parsed_issue_arg.valid |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2741 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2742 | self.issue = parsed_issue_arg.issue |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2743 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2744 | if parsed_issue_arg.hostname: |
| 2745 | self._gerrit_host = parsed_issue_arg.hostname |
| 2746 | self._gerrit_server = 'https://%s' % self._gerrit_host |
Andrii Shyshkalov | 76988a8 | 2018-10-15 03:12:25 +0000 | [diff] [blame] | 2747 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2748 | try: |
| 2749 | detail = self._GetChangeDetail(['ALL_REVISIONS']) |
| 2750 | except GerritChangeNotExists as e: |
| 2751 | DieWithError(str(e)) |
agable | c678797 | 2016-09-09 16:13:34 -0700 | [diff] [blame] | 2752 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2753 | if not parsed_issue_arg.patchset: |
| 2754 | # Use current revision by default. |
| 2755 | revision_info = detail['revisions'][detail['current_revision']] |
| 2756 | patchset = int(revision_info['_number']) |
| 2757 | else: |
| 2758 | patchset = parsed_issue_arg.patchset |
| 2759 | for revision_info in detail['revisions'].values(): |
| 2760 | if int(revision_info['_number']) == parsed_issue_arg.patchset: |
| 2761 | break |
| 2762 | else: |
| 2763 | DieWithError('Couldn\'t find patchset %i in change %i' % |
| 2764 | (parsed_issue_arg.patchset, self.GetIssue())) |
Andrii Shyshkalov | 2f72791 | 2018-10-15 17:02:33 +0000 | [diff] [blame] | 2765 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2766 | remote_url = self.GetRemoteUrl() |
| 2767 | if remote_url.endswith('.git'): |
| 2768 | remote_url = remote_url[:-len('.git')] |
| 2769 | remote_url = remote_url.rstrip('/') |
Andrii Shyshkalov | febbae9 | 2017-04-05 15:05:20 +0000 | [diff] [blame] | 2770 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2771 | fetch_info = revision_info['fetch']['http'] |
| 2772 | fetch_info['url'] = fetch_info['url'].rstrip('/') |
Josip Sokcevic | f2cfd3d | 2021-03-30 18:39:18 +0000 | [diff] [blame] | 2773 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2774 | if remote_url != fetch_info['url']: |
| 2775 | DieWithError( |
| 2776 | 'Trying to patch a change from %s but this repo appears ' |
| 2777 | 'to be %s.' % (fetch_info['url'], remote_url)) |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 2778 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2779 | RunGit(['fetch', fetch_info['url'], fetch_info['ref']]) |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2780 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2781 | # Set issue immediately in case the cherry-pick fails, which happens |
| 2782 | # when resolving conflicts. |
| 2783 | if self.GetBranch(): |
| 2784 | self.SetIssue(parsed_issue_arg.issue) |
tandrii | 8818977 | 2016-09-29 04:29:57 -0700 | [diff] [blame] | 2785 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2786 | if force: |
| 2787 | RunGit(['reset', '--hard', 'FETCH_HEAD']) |
| 2788 | print('Checked out commit for change %i patchset %i locally' % |
| 2789 | (parsed_issue_arg.issue, patchset)) |
| 2790 | elif nocommit: |
| 2791 | RunGit(['cherry-pick', '--no-commit', 'FETCH_HEAD']) |
| 2792 | print('Patch applied to index.') |
| 2793 | else: |
| 2794 | RunGit(['cherry-pick', 'FETCH_HEAD']) |
| 2795 | print('Committed patch for change %i patchset %i locally.' % |
| 2796 | (parsed_issue_arg.issue, patchset)) |
| 2797 | print( |
| 2798 | 'Note: this created a local commit which does not have ' |
| 2799 | 'the same hash as the one uploaded for review. This will make ' |
| 2800 | 'uploading changes based on top of this branch difficult.\n' |
| 2801 | 'If you want to do that, use "git cl patch --force" instead.') |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 2802 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2803 | if self.GetBranch(): |
| 2804 | self.SetPatchset(patchset) |
| 2805 | fetched_hash = scm.GIT.ResolveCommit(settings.GetRoot(), |
| 2806 | 'FETCH_HEAD') |
| 2807 | self._GitSetBranchConfigValue(LAST_UPLOAD_HASH_CONFIG_KEY, |
| 2808 | fetched_hash) |
| 2809 | self._GitSetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY, |
| 2810 | fetched_hash) |
| 2811 | else: |
| 2812 | print( |
| 2813 | 'WARNING: You are in detached HEAD state.\n' |
| 2814 | 'The patch has been applied to your checkout, but you will not be ' |
| 2815 | 'able to upload a new patch set to the gerrit issue.\n' |
| 2816 | 'Try using the \'-b\' option if you would like to work on a ' |
| 2817 | 'branch and/or upload a new patch set.') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 2818 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 2819 | return 0 |
| 2820 | |
| 2821 | @staticmethod |
| 2822 | def _GerritCommitMsgHookCheck(offer_removal): |
| 2823 | # type: (bool) -> None |
| 2824 | """Checks for the gerrit's commit-msg hook and removes it if necessary.""" |
| 2825 | hook = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg') |
| 2826 | if not os.path.exists(hook): |
| 2827 | return |
| 2828 | # Crude attempt to distinguish Gerrit Codereview hook from a potentially |
| 2829 | # custom developer-made one. |
| 2830 | data = gclient_utils.FileRead(hook) |
| 2831 | if not ('From Gerrit Code Review' in data and 'add_ChangeId()' in data): |
| 2832 | return |
| 2833 | print('WARNING: You have Gerrit commit-msg hook installed.\n' |
| 2834 | 'It is not necessary for uploading with git cl in squash mode, ' |
| 2835 | 'and may interfere with it in subtle ways.\n' |
| 2836 | 'We recommend you remove the commit-msg hook.') |
| 2837 | if offer_removal: |
| 2838 | if ask_for_explicit_yes('Do you want to remove it now?'): |
| 2839 | gclient_utils.rm_file_or_tree(hook) |
| 2840 | print('Gerrit commit-msg hook removed.') |
| 2841 | else: |
| 2842 | print('OK, will keep Gerrit commit-msg hook in place.') |
| 2843 | |
| 2844 | def _CleanUpOldTraces(self): |
| 2845 | """Keep only the last |MAX_TRACES| traces.""" |
| 2846 | try: |
| 2847 | traces = sorted([ |
| 2848 | os.path.join(TRACES_DIR, f) for f in os.listdir(TRACES_DIR) |
| 2849 | if (os.path.isfile(os.path.join(TRACES_DIR, f)) |
| 2850 | and not f.startswith('tmp')) |
| 2851 | ]) |
| 2852 | traces_to_delete = traces[:-MAX_TRACES] |
| 2853 | for trace in traces_to_delete: |
| 2854 | os.remove(trace) |
| 2855 | except OSError: |
| 2856 | print('WARNING: Failed to remove old git traces from\n' |
| 2857 | ' %s' |
| 2858 | 'Consider removing them manually.' % TRACES_DIR) |
| 2859 | |
| 2860 | def _WriteGitPushTraces(self, trace_name, traces_dir, git_push_metadata): |
| 2861 | """Zip and write the git push traces stored in traces_dir.""" |
| 2862 | gclient_utils.safe_makedirs(TRACES_DIR) |
| 2863 | traces_zip = trace_name + '-traces' |
| 2864 | traces_readme = trace_name + '-README' |
| 2865 | # Create a temporary dir to store git config and gitcookies in. It will |
| 2866 | # be compressed and stored next to the traces. |
| 2867 | git_info_dir = tempfile.mkdtemp() |
| 2868 | git_info_zip = trace_name + '-git-info' |
| 2869 | |
| 2870 | git_push_metadata['now'] = datetime_now().strftime( |
| 2871 | '%Y-%m-%dT%H:%M:%S.%f') |
| 2872 | |
| 2873 | git_push_metadata['trace_name'] = trace_name |
| 2874 | gclient_utils.FileWrite(traces_readme, |
| 2875 | TRACES_README_FORMAT % git_push_metadata) |
| 2876 | |
| 2877 | # Keep only the first 6 characters of the git hashes on the packet |
| 2878 | # trace. This greatly decreases size after compression. |
| 2879 | packet_traces = os.path.join(traces_dir, 'trace-packet') |
| 2880 | if os.path.isfile(packet_traces): |
| 2881 | contents = gclient_utils.FileRead(packet_traces) |
| 2882 | gclient_utils.FileWrite(packet_traces, |
| 2883 | GIT_HASH_RE.sub(r'\1', contents)) |
| 2884 | shutil.make_archive(traces_zip, 'zip', traces_dir) |
| 2885 | |
| 2886 | # Collect and compress the git config and gitcookies. |
| 2887 | git_config = RunGit(['config', '-l']) |
| 2888 | gclient_utils.FileWrite(os.path.join(git_info_dir, 'git-config'), |
| 2889 | git_config) |
| 2890 | |
| 2891 | cookie_auth = gerrit_util.Authenticator.get() |
| 2892 | if isinstance(cookie_auth, gerrit_util.CookiesAuthenticator): |
| 2893 | gitcookies_path = cookie_auth.get_gitcookies_path() |
| 2894 | if os.path.isfile(gitcookies_path): |
| 2895 | gitcookies = gclient_utils.FileRead(gitcookies_path) |
| 2896 | gclient_utils.FileWrite( |
| 2897 | os.path.join(git_info_dir, 'gitcookies'), |
| 2898 | GITCOOKIES_REDACT_RE.sub('REDACTED', gitcookies)) |
| 2899 | shutil.make_archive(git_info_zip, 'zip', git_info_dir) |
| 2900 | |
| 2901 | gclient_utils.rmtree(git_info_dir) |
| 2902 | |
| 2903 | def _RunGitPushWithTraces(self, |
| 2904 | refspec, |
| 2905 | refspec_opts, |
| 2906 | git_push_metadata, |
| 2907 | git_push_options=None): |
| 2908 | """Run git push and collect the traces resulting from the execution.""" |
| 2909 | # Create a temporary directory to store traces in. Traces will be |
| 2910 | # compressed and stored in a 'traces' dir inside depot_tools. |
| 2911 | traces_dir = tempfile.mkdtemp() |
| 2912 | trace_name = os.path.join(TRACES_DIR, |
| 2913 | datetime_now().strftime('%Y%m%dT%H%M%S.%f')) |
| 2914 | |
| 2915 | env = os.environ.copy() |
| 2916 | env['GIT_REDACT_COOKIES'] = 'o,SSO,GSSO_Uberproxy' |
| 2917 | env['GIT_TR2_EVENT'] = os.path.join(traces_dir, 'tr2-event') |
| 2918 | env['GIT_TRACE2_EVENT'] = os.path.join(traces_dir, 'tr2-event') |
| 2919 | env['GIT_TRACE_CURL'] = os.path.join(traces_dir, 'trace-curl') |
| 2920 | env['GIT_TRACE_CURL_NO_DATA'] = '1' |
| 2921 | env['GIT_TRACE_PACKET'] = os.path.join(traces_dir, 'trace-packet') |
| 2922 | |
| 2923 | push_returncode = 0 |
| 2924 | before_push = time_time() |
| 2925 | try: |
| 2926 | remote_url = self.GetRemoteUrl() |
| 2927 | push_cmd = ['git', 'push', remote_url, refspec] |
| 2928 | if git_push_options: |
| 2929 | for opt in git_push_options: |
| 2930 | push_cmd.extend(['-o', opt]) |
| 2931 | |
| 2932 | push_stdout = gclient_utils.CheckCallAndFilter( |
| 2933 | push_cmd, |
| 2934 | env=env, |
| 2935 | print_stdout=True, |
| 2936 | # Flush after every line: useful for seeing progress when |
| 2937 | # running as recipe. |
| 2938 | filter_fn=lambda _: sys.stdout.flush()) |
| 2939 | push_stdout = push_stdout.decode('utf-8', 'replace') |
| 2940 | except subprocess2.CalledProcessError as e: |
| 2941 | push_returncode = e.returncode |
| 2942 | if 'blocked keyword' in str(e.stdout) or 'banned word' in str( |
| 2943 | e.stdout): |
| 2944 | raise GitPushError( |
| 2945 | 'Failed to create a change, very likely due to blocked keyword. ' |
| 2946 | 'Please examine output above for the reason of the failure.\n' |
| 2947 | 'If this is a false positive, you can try to bypass blocked ' |
| 2948 | 'keyword by using push option ' |
| 2949 | '-o banned-words~skip, e.g.:\n' |
| 2950 | 'git cl upload -o banned-words~skip\n\n' |
| 2951 | 'If git-cl is not working correctly, file a bug under the ' |
| 2952 | 'Infra>SDK component.') |
| 2953 | if 'git push -o nokeycheck' in str(e.stdout): |
| 2954 | raise GitPushError( |
| 2955 | 'Failed to create a change, very likely due to a private key being ' |
| 2956 | 'detected. Please examine output above for the reason of the ' |
| 2957 | 'failure.\n' |
| 2958 | 'If this is a false positive, you can try to bypass private key ' |
| 2959 | 'detection by using push option ' |
| 2960 | '-o nokeycheck, e.g.:\n' |
| 2961 | 'git cl upload -o nokeycheck\n\n' |
| 2962 | 'If git-cl is not working correctly, file a bug under the ' |
| 2963 | 'Infra>SDK component.') |
| 2964 | |
| 2965 | raise GitPushError( |
| 2966 | 'Failed to create a change. Please examine output above for the ' |
| 2967 | 'reason of the failure.\n' |
| 2968 | 'For emergencies, Googlers can escalate to ' |
| 2969 | 'go/gob-support or go/notify#gob\n' |
| 2970 | 'Hint: run command below to diagnose common Git/Gerrit ' |
| 2971 | 'credential problems:\n' |
| 2972 | ' git cl creds-check\n' |
| 2973 | '\n' |
| 2974 | 'If git-cl is not working correctly, file a bug under the Infra>SDK ' |
| 2975 | 'component including the files below.\n' |
| 2976 | 'Review the files before upload, since they might contain sensitive ' |
| 2977 | 'information.\n' |
| 2978 | 'Set the Restrict-View-Google label so that they are not publicly ' |
| 2979 | 'accessible.\n' + TRACES_MESSAGE % {'trace_name': trace_name}) |
| 2980 | finally: |
| 2981 | execution_time = time_time() - before_push |
| 2982 | metrics.collector.add_repeated( |
| 2983 | 'sub_commands', { |
| 2984 | 'command': |
| 2985 | 'git push', |
| 2986 | 'execution_time': |
| 2987 | execution_time, |
| 2988 | 'exit_code': |
| 2989 | push_returncode, |
| 2990 | 'arguments': |
| 2991 | metrics_utils.extract_known_subcommand_args(refspec_opts), |
| 2992 | }) |
| 2993 | |
| 2994 | git_push_metadata['execution_time'] = execution_time |
| 2995 | git_push_metadata['exit_code'] = push_returncode |
| 2996 | self._WriteGitPushTraces(trace_name, traces_dir, git_push_metadata) |
| 2997 | |
| 2998 | self._CleanUpOldTraces() |
| 2999 | gclient_utils.rmtree(traces_dir) |
| 3000 | |
| 3001 | return push_stdout |
| 3002 | |
| 3003 | def CMDUploadChange(self, options, git_diff_args, custom_cl_base, |
| 3004 | change_desc): |
| 3005 | """Upload the current branch to Gerrit, retry if new remote HEAD is |
| 3006 | found. options and change_desc may be mutated.""" |
| 3007 | remote, remote_branch = self.GetRemoteBranch() |
| 3008 | branch = GetTargetRef(remote, remote_branch, options.target_branch) |
| 3009 | |
| 3010 | try: |
| 3011 | return self._CMDUploadChange(options, git_diff_args, custom_cl_base, |
| 3012 | change_desc, branch) |
| 3013 | except GitPushError as e: |
| 3014 | # Repository might be in the middle of transition to main branch as |
| 3015 | # default, and uploads to old default might be blocked. |
| 3016 | if remote_branch not in [DEFAULT_OLD_BRANCH, DEFAULT_NEW_BRANCH]: |
| 3017 | DieWithError(str(e), change_desc) |
| 3018 | |
| 3019 | project_head = gerrit_util.GetProjectHead(self._gerrit_host, |
| 3020 | self.GetGerritProject()) |
| 3021 | if project_head == branch: |
| 3022 | DieWithError(str(e), change_desc) |
| 3023 | branch = project_head |
| 3024 | |
| 3025 | print("WARNING: Fetching remote state and retrying upload to default " |
| 3026 | "branch...") |
| 3027 | RunGit(['fetch', '--prune', remote]) |
| 3028 | options.edit_description = False |
| 3029 | options.force = True |
| 3030 | try: |
| 3031 | self._CMDUploadChange(options, git_diff_args, custom_cl_base, |
| 3032 | change_desc, branch) |
| 3033 | except GitPushError as e: |
| 3034 | DieWithError(str(e), change_desc) |
| 3035 | |
| 3036 | def _CMDUploadChange(self, options, git_diff_args, custom_cl_base, |
| 3037 | change_desc, branch): |
| 3038 | """Upload the current branch to Gerrit.""" |
| 3039 | if options.squash: |
| 3040 | Changelist._GerritCommitMsgHookCheck( |
| 3041 | offer_removal=not options.force) |
| 3042 | external_parent = None |
| 3043 | if self.GetIssue(): |
| 3044 | # User requested to change description |
| 3045 | if options.edit_description: |
| 3046 | change_desc.prompt() |
| 3047 | change_detail = self._GetChangeDetail(['CURRENT_REVISION']) |
| 3048 | change_id = change_detail['change_id'] |
| 3049 | change_desc.ensure_change_id(change_id) |
| 3050 | |
| 3051 | # Check if changes outside of this workspace have been uploaded. |
| 3052 | current_rev = change_detail['current_revision'] |
| 3053 | last_uploaded_rev = self._GitGetBranchConfigValue( |
| 3054 | GERRIT_SQUASH_HASH_CONFIG_KEY) |
| 3055 | if last_uploaded_rev and current_rev != last_uploaded_rev: |
| 3056 | external_parent = self._UpdateWithExternalChanges() |
| 3057 | else: # if not self.GetIssue() |
| 3058 | if not options.force and not options.message_file: |
| 3059 | change_desc.prompt() |
| 3060 | change_ids = git_footers.get_footer_change_id( |
| 3061 | change_desc.description) |
| 3062 | if len(change_ids) == 1: |
| 3063 | change_id = change_ids[0] |
| 3064 | else: |
| 3065 | change_id = GenerateGerritChangeId(change_desc.description) |
| 3066 | change_desc.ensure_change_id(change_id) |
| 3067 | |
| 3068 | if options.preserve_tryjobs: |
| 3069 | change_desc.set_preserve_tryjobs() |
| 3070 | |
| 3071 | remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch()) |
| 3072 | parent = external_parent or self._ComputeParent( |
| 3073 | remote, upstream_branch, custom_cl_base, options.force, |
| 3074 | change_desc) |
| 3075 | tree = RunGit(['rev-parse', 'HEAD:']).strip() |
| 3076 | with gclient_utils.temporary_file() as desc_tempfile: |
| 3077 | gclient_utils.FileWrite(desc_tempfile, change_desc.description) |
| 3078 | ref_to_push = RunGit( |
| 3079 | ['commit-tree', tree, '-p', parent, '-F', |
| 3080 | desc_tempfile]).strip() |
| 3081 | else: # if not options.squash |
| 3082 | if options.no_add_changeid: |
| 3083 | pass |
| 3084 | else: # adding Change-Ids is okay. |
| 3085 | if not git_footers.get_footer_change_id( |
| 3086 | change_desc.description): |
| 3087 | DownloadGerritHook(False) |
| 3088 | change_desc.set_description( |
| 3089 | self._AddChangeIdToCommitMessage( |
| 3090 | change_desc.description, git_diff_args)) |
| 3091 | ref_to_push = 'HEAD' |
| 3092 | # For no-squash mode, we assume the remote called "origin" is the |
| 3093 | # one we want. It is not worthwhile to support different workflows |
| 3094 | # for no-squash mode. |
| 3095 | parent = 'origin/%s' % branch |
| 3096 | # attempt to extract the changeid from the current description |
| 3097 | # fail informatively if not possible. |
| 3098 | change_id_candidates = git_footers.get_footer_change_id( |
| 3099 | change_desc.description) |
| 3100 | if not change_id_candidates: |
| 3101 | DieWithError("Unable to extract change-id from message.") |
| 3102 | change_id = change_id_candidates[0] |
| 3103 | |
| 3104 | SaveDescriptionBackup(change_desc) |
| 3105 | commits = RunGitSilent(['rev-list', |
| 3106 | '%s..%s' % (parent, ref_to_push)]).splitlines() |
| 3107 | if len(commits) > 1: |
| 3108 | print( |
| 3109 | 'WARNING: This will upload %d commits. Run the following command ' |
| 3110 | 'to see which commits will be uploaded: ' % len(commits)) |
| 3111 | print('git log %s..%s' % (parent, ref_to_push)) |
| 3112 | print('You can also use `git squash-branch` to squash these into a ' |
| 3113 | 'single commit.') |
| 3114 | confirm_or_exit(action='upload') |
| 3115 | |
| 3116 | reviewers = sorted(change_desc.get_reviewers()) |
| 3117 | cc = [] |
| 3118 | # Add default, watchlist, presubmit ccs if this is the initial upload |
| 3119 | # and CL is not private and auto-ccing has not been disabled. |
| 3120 | if not options.private and not options.no_autocc and not self.GetIssue( |
| 3121 | ): |
| 3122 | cc = self.GetCCList().split(',') |
| 3123 | if len(cc) > 100: |
| 3124 | lsc = ('https://chromium.googlesource.com/chromium/src/+/HEAD/docs/' |
| 3125 | 'process/lsc/lsc_workflow.md') |
| 3126 | print('WARNING: This will auto-CC %s users.' % len(cc)) |
| 3127 | print('LSC may be more appropriate: %s' % lsc) |
| 3128 | print('You can also use the --no-autocc flag to disable auto-CC.') |
| 3129 | confirm_or_exit(action='continue') |
| 3130 | # Add cc's from the --cc flag. |
| 3131 | if options.cc: |
| 3132 | cc.extend(options.cc) |
| 3133 | cc = [email.strip() for email in cc if email.strip()] |
| 3134 | if change_desc.get_cced(): |
| 3135 | cc.extend(change_desc.get_cced()) |
| 3136 | if self.GetGerritHost() == 'chromium-review.googlesource.com': |
| 3137 | valid_accounts = set(reviewers + cc) |
| 3138 | # TODO(crbug/877717): relax this for all hosts. |
| 3139 | else: |
| 3140 | valid_accounts = gerrit_util.ValidAccounts(self.GetGerritHost(), |
| 3141 | reviewers + cc) |
| 3142 | logging.info('accounts %s are recognized, %s invalid', |
| 3143 | sorted(valid_accounts), |
| 3144 | set(reviewers + cc).difference(set(valid_accounts))) |
| 3145 | |
| 3146 | # Extra options that can be specified at push time. Doc: |
| 3147 | # https://gerrit-review.googlesource.com/Documentation/user-upload.html |
| 3148 | refspec_opts = self._GetRefSpecOptions(options, change_desc) |
| 3149 | |
| 3150 | for r in sorted(reviewers): |
| 3151 | if r in valid_accounts: |
| 3152 | refspec_opts.append('r=%s' % r) |
| 3153 | reviewers.remove(r) |
| 3154 | else: |
| 3155 | # TODO(tandrii): this should probably be a hard failure. |
| 3156 | print( |
| 3157 | 'WARNING: reviewer %s doesn\'t have a Gerrit account, skipping' |
| 3158 | % r) |
| 3159 | for c in sorted(cc): |
| 3160 | # refspec option will be rejected if cc doesn't correspond to an |
| 3161 | # account, even though REST call to add such arbitrary cc may |
| 3162 | # succeed. |
| 3163 | if c in valid_accounts: |
| 3164 | refspec_opts.append('cc=%s' % c) |
| 3165 | cc.remove(c) |
| 3166 | |
| 3167 | refspec_suffix = '' |
| 3168 | if refspec_opts: |
| 3169 | refspec_suffix = '%' + ','.join(refspec_opts) |
| 3170 | assert ' ' not in refspec_suffix, ( |
| 3171 | 'spaces not allowed in refspec: "%s"' % refspec_suffix) |
| 3172 | refspec = '%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix) |
| 3173 | |
| 3174 | git_push_metadata = { |
| 3175 | 'gerrit_host': self.GetGerritHost(), |
| 3176 | 'title': options.title or '<untitled>', |
| 3177 | 'change_id': change_id, |
| 3178 | 'description': change_desc.description, |
| 3179 | } |
| 3180 | |
| 3181 | # Gerrit may or may not update fast enough to return the correct |
| 3182 | # patchset number after we push. Get the pre-upload patchset and |
| 3183 | # increment later. |
| 3184 | latest_ps = self.GetMostRecentPatchset(update=False) or 0 |
| 3185 | |
| 3186 | push_stdout = self._RunGitPushWithTraces(refspec, refspec_opts, |
| 3187 | git_push_metadata, |
| 3188 | options.push_options) |
| 3189 | |
| 3190 | if options.squash: |
| 3191 | regex = re.compile(r'remote:\s+https?://[\w\-\.\+\/#]*/(\d+)\s.*') |
| 3192 | change_numbers = [ |
| 3193 | m.group(1) for m in map(regex.match, push_stdout.splitlines()) |
| 3194 | if m |
| 3195 | ] |
| 3196 | if len(change_numbers) != 1: |
| 3197 | DieWithError(( |
| 3198 | 'Created|Updated %d issues on Gerrit, but only 1 expected.\n' |
| 3199 | 'Change-Id: %s') % (len(change_numbers), change_id), |
| 3200 | change_desc) |
| 3201 | self.SetIssue(change_numbers[0]) |
| 3202 | self.SetPatchset(latest_ps + 1) |
| 3203 | self._GitSetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY, |
| 3204 | ref_to_push) |
| 3205 | |
| 3206 | if self.GetIssue() and (reviewers or cc): |
| 3207 | # GetIssue() is not set in case of non-squash uploads according to |
| 3208 | # tests. TODO(crbug.com/751901): non-squash uploads in git cl should |
| 3209 | # be removed. |
| 3210 | gerrit_util.AddReviewers(self.GetGerritHost(), |
| 3211 | self._GerritChangeIdentifier(), |
| 3212 | reviewers, |
| 3213 | cc, |
| 3214 | notify=bool(options.send_mail)) |
| 3215 | |
| 3216 | return 0 |
| 3217 | |
| 3218 | def _ComputeParent(self, remote, upstream_branch, custom_cl_base, force, |
| 3219 | change_desc): |
| 3220 | """Computes parent of the generated commit to be uploaded to Gerrit. |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 3221 | |
| 3222 | Returns revision or a ref name. |
| 3223 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3224 | if custom_cl_base: |
| 3225 | # Try to avoid creating additional unintended CLs when uploading, |
| 3226 | # unless user wants to take this risk. |
| 3227 | local_ref_of_target_remote = self.GetRemoteBranch()[1] |
| 3228 | code, _ = RunGitWithCode([ |
| 3229 | 'merge-base', '--is-ancestor', custom_cl_base, |
| 3230 | local_ref_of_target_remote |
| 3231 | ]) |
| 3232 | if code == 1: |
| 3233 | print( |
| 3234 | '\nWARNING: Manually specified base of this CL `%s` ' |
| 3235 | 'doesn\'t seem to belong to target remote branch `%s`.\n\n' |
| 3236 | 'If you proceed with upload, more than 1 CL may be created by ' |
| 3237 | 'Gerrit as a result, in turn confusing or crashing git cl.\n\n' |
| 3238 | 'If you are certain that specified base `%s` has already been ' |
| 3239 | 'uploaded to Gerrit as another CL, you may proceed.\n' % |
| 3240 | (custom_cl_base, local_ref_of_target_remote, |
| 3241 | custom_cl_base)) |
| 3242 | if not force: |
| 3243 | confirm_or_exit( |
| 3244 | 'Do you take responsibility for cleaning up potential mess ' |
| 3245 | 'resulting from proceeding with upload?', |
| 3246 | action='upload') |
| 3247 | return custom_cl_base |
Andrii Shyshkalov | 550e924 | 2017-04-12 17:14:49 +0200 | [diff] [blame] | 3248 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3249 | if remote != '.': |
| 3250 | return self.GetCommonAncestorWithUpstream() |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3251 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3252 | # If our upstream branch is local, we base our squashed commit on its |
| 3253 | # squashed version. |
| 3254 | upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch) |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3255 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3256 | if upstream_branch_name == 'master': |
| 3257 | return self.GetCommonAncestorWithUpstream() |
| 3258 | if upstream_branch_name == 'main': |
| 3259 | return self.GetCommonAncestorWithUpstream() |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3260 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3261 | # Check the squashed hash of the parent. |
| 3262 | # TODO(tandrii): consider checking parent change in Gerrit and using its |
| 3263 | # hash if tree hash of latest parent revision (patchset) in Gerrit |
| 3264 | # matches the tree hash of the parent branch. The upside is less likely |
| 3265 | # bogus requests to reupload parent change just because it's uploadhash |
| 3266 | # is missing, yet the downside likely exists, too (albeit unknown to me |
| 3267 | # yet). |
| 3268 | parent = scm.GIT.GetBranchConfig(settings.GetRoot(), |
| 3269 | upstream_branch_name, |
| 3270 | GERRIT_SQUASH_HASH_CONFIG_KEY) |
| 3271 | # Verify that the upstream branch has been uploaded too, otherwise |
| 3272 | # Gerrit will create additional CLs when uploading. |
| 3273 | if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) != |
| 3274 | RunGitSilent(['rev-parse', parent + ':'])): |
| 3275 | DieWithError( |
| 3276 | '\nUpload upstream branch %s first.\n' |
| 3277 | 'It is likely that this branch has been rebased since its last ' |
| 3278 | 'upload, so you just need to upload it again.\n' |
| 3279 | '(If you uploaded it with --no-squash, then branch dependencies ' |
| 3280 | 'are not supported, and you should reupload with --squash.)' % |
| 3281 | upstream_branch_name, change_desc) |
| 3282 | return parent |
Aaron Gable | f97e33d | 2017-03-30 15:44:27 -0700 | [diff] [blame] | 3283 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3284 | def _UpdateWithExternalChanges(self): |
| 3285 | """Updates workspace with external changes. |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3286 | |
| 3287 | Returns the commit hash that should be used as the merge base on upload. |
| 3288 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3289 | local_ps = self.GetPatchset() |
| 3290 | if local_ps is None: |
| 3291 | return |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3292 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3293 | external_ps = self.GetMostRecentPatchset(update=False) |
| 3294 | if external_ps is None or local_ps == external_ps or \ |
| 3295 | not self._IsPatchsetRangeSignificant(local_ps + 1, external_ps): |
| 3296 | return |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3297 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3298 | num_changes = external_ps - local_ps |
| 3299 | if num_changes > 1: |
| 3300 | change_words = 'changes were' |
| 3301 | else: |
| 3302 | change_words = 'change was' |
| 3303 | print('\n%d external %s published to %s:\n' % |
| 3304 | (num_changes, change_words, self.GetIssueURL(short=True))) |
Gavin Mak | 6f90547 | 2023-01-06 21:01:36 +0000 | [diff] [blame] | 3305 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3306 | # Print an overview of external changes. |
| 3307 | ps_to_commit = {} |
| 3308 | ps_to_info = {} |
| 3309 | revisions = self._GetChangeDetail(['ALL_REVISIONS']) |
| 3310 | for commit_id, revision_info in revisions.get('revisions', {}).items(): |
| 3311 | ps_num = revision_info['_number'] |
| 3312 | ps_to_commit[ps_num] = commit_id |
| 3313 | ps_to_info[ps_num] = revision_info |
Gavin Mak | 6f90547 | 2023-01-06 21:01:36 +0000 | [diff] [blame] | 3314 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3315 | for ps in range(external_ps, local_ps, -1): |
| 3316 | commit = ps_to_commit[ps][:8] |
| 3317 | desc = ps_to_info[ps].get('description', '') |
| 3318 | print('Patchset %d [%s] %s' % (ps, commit, desc)) |
Gavin Mak | 6f90547 | 2023-01-06 21:01:36 +0000 | [diff] [blame] | 3319 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3320 | print('\nSee diff at: %s/%d..%d' % |
| 3321 | (self.GetIssueURL(short=True), local_ps, external_ps)) |
| 3322 | print('\nUploading without applying patches will override them.') |
Josip Sokcevic | 43ceaf0 | 2023-05-25 15:56:00 +0000 | [diff] [blame] | 3323 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3324 | if not ask_for_explicit_yes('Get the latest changes and apply on top?'): |
| 3325 | return |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3326 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3327 | # Get latest Gerrit merge base. Use the first parent even if multiple |
| 3328 | # exist. |
| 3329 | external_parent = self._GetChangeCommit( |
| 3330 | revision=external_ps)['parents'][0] |
| 3331 | external_base = external_parent['commit'] |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3332 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3333 | branch = git_common.current_branch() |
| 3334 | local_base = self.GetCommonAncestorWithUpstream() |
| 3335 | if local_base != external_base: |
| 3336 | print('\nLocal merge base %s is different from Gerrit %s.\n' % |
| 3337 | (local_base, external_base)) |
| 3338 | if git_common.upstream(branch): |
| 3339 | confirm_or_exit( |
| 3340 | 'Can\'t apply the latest changes from Gerrit.\n' |
| 3341 | 'Continue with upload and override the latest changes?') |
| 3342 | return |
| 3343 | print( |
| 3344 | 'No upstream branch set. Continuing upload with Gerrit merge base.' |
| 3345 | ) |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3346 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3347 | external_parent_last_uploaded = self._GetChangeCommit( |
| 3348 | revision=local_ps)['parents'][0] |
| 3349 | external_base_last_uploaded = external_parent_last_uploaded['commit'] |
Josip Sokcevic | 2568d4c | 2023-05-24 03:37:42 +0000 | [diff] [blame] | 3350 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3351 | if external_base != external_base_last_uploaded: |
| 3352 | print('\nPatch set merge bases are different (%s, %s).\n' % |
| 3353 | (external_base_last_uploaded, external_base)) |
| 3354 | confirm_or_exit( |
| 3355 | 'Can\'t apply the latest changes from Gerrit.\n' |
| 3356 | 'Continue with upload and override the latest changes?') |
| 3357 | return |
Josip Sokcevic | 2568d4c | 2023-05-24 03:37:42 +0000 | [diff] [blame] | 3358 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3359 | # Fetch Gerrit's CL base if it doesn't exist locally. |
| 3360 | remote, _ = self.GetRemoteBranch() |
| 3361 | if not scm.GIT.IsValidRevision(settings.GetRoot(), external_base): |
| 3362 | RunGitSilent(['fetch', remote, external_base]) |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3363 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3364 | # Get the diff between local_ps and external_ps. |
| 3365 | print('Fetching changes...') |
| 3366 | issue = self.GetIssue() |
| 3367 | changes_ref = 'refs/changes/%02d/%d/' % (issue % 100, issue) |
| 3368 | RunGitSilent(['fetch', remote, changes_ref + str(local_ps)]) |
| 3369 | last_uploaded = RunGitSilent(['rev-parse', 'FETCH_HEAD']).strip() |
| 3370 | RunGitSilent(['fetch', remote, changes_ref + str(external_ps)]) |
| 3371 | latest_external = RunGitSilent(['rev-parse', 'FETCH_HEAD']).strip() |
Josip Sokcevic | 2568d4c | 2023-05-24 03:37:42 +0000 | [diff] [blame] | 3372 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3373 | # If the commit parents are different, don't apply the diff as it very |
| 3374 | # likely contains many more changes not relevant to this CL. |
| 3375 | parents = RunGitSilent( |
| 3376 | ['rev-parse', |
| 3377 | '%s~1' % (last_uploaded), |
| 3378 | '%s~1' % (latest_external)]).strip().split() |
| 3379 | assert len(parents) == 2, 'Expected two parents.' |
| 3380 | if parents[0] != parents[1]: |
| 3381 | confirm_or_exit( |
| 3382 | 'Can\'t apply the latest changes from Gerrit (parent mismatch ' |
| 3383 | 'between PS).\n' |
| 3384 | 'Continue with upload and override the latest changes?') |
| 3385 | return |
Josip Sokcevic | 2568d4c | 2023-05-24 03:37:42 +0000 | [diff] [blame] | 3386 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3387 | diff = RunGitSilent( |
| 3388 | ['diff', '%s..%s' % (last_uploaded, latest_external)]) |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3389 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3390 | # Diff can be empty in the case of trivial rebases. |
| 3391 | if not diff: |
| 3392 | return external_base |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3393 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3394 | # Apply the diff. |
| 3395 | with gclient_utils.temporary_file() as diff_tempfile: |
| 3396 | gclient_utils.FileWrite(diff_tempfile, diff) |
| 3397 | clean_patch = RunGitWithCode(['apply', '--check', |
| 3398 | diff_tempfile])[0] == 0 |
| 3399 | RunGitSilent(['apply', '-3', '--intent-to-add', diff_tempfile]) |
| 3400 | if not clean_patch: |
| 3401 | # Normally patchset is set after upload. But because we exit, |
| 3402 | # that never happens. Updating here makes sure that subsequent |
| 3403 | # uploads don't need to fetch/apply the same diff again. |
| 3404 | self.SetPatchset(external_ps) |
| 3405 | DieWithError( |
| 3406 | '\nPatch did not apply cleanly. Please resolve any ' |
| 3407 | 'conflicts and reupload.') |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3408 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3409 | message = 'Incorporate external changes from ' |
| 3410 | if num_changes == 1: |
| 3411 | message += 'patchset %d' % external_ps |
| 3412 | else: |
| 3413 | message += 'patchsets %d to %d' % (local_ps + 1, external_ps) |
| 3414 | RunGitSilent(['commit', '-am', message]) |
| 3415 | # TODO(crbug.com/1382528): Use the previous commit's message as a |
| 3416 | # default patchset title instead of this 'Incorporate' message. |
| 3417 | return external_base |
Gavin Mak | 4e5e399 | 2022-11-14 22:40:12 +0000 | [diff] [blame] | 3418 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3419 | def _AddChangeIdToCommitMessage(self, log_desc, args): |
| 3420 | """Re-commits using the current message, assumes the commit hook is in |
tandrii@chromium.org | 8930b3d | 2016-04-13 14:47:02 +0000 | [diff] [blame] | 3421 | place. |
| 3422 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3423 | RunGit(['commit', '--amend', '-m', log_desc]) |
| 3424 | new_log_desc = _create_description_from_log(args) |
| 3425 | if git_footers.get_footer_change_id(new_log_desc): |
| 3426 | print('git-cl: Added Change-Id to commit message.') |
| 3427 | return new_log_desc |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 3428 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3429 | DieWithError('ERROR: Gerrit commit-msg hook not installed.') |
tandrii@chromium.org | aa6235b | 2016-04-11 21:35:29 +0000 | [diff] [blame] | 3430 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3431 | def CannotTriggerTryJobReason(self): |
| 3432 | try: |
| 3433 | data = self._GetChangeDetail() |
| 3434 | except GerritChangeNotExists: |
| 3435 | return 'Gerrit doesn\'t know about your change %s' % self.GetIssue() |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3436 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3437 | if data['status'] in ('ABANDONED', 'MERGED'): |
| 3438 | return 'CL %s is closed' % self.GetIssue() |
tandrii | 8c5a353 | 2016-11-04 07:52:02 -0700 | [diff] [blame] | 3439 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3440 | def GetGerritChange(self, patchset=None): |
| 3441 | """Returns a buildbucket.v2.GerritChange message for the current issue.""" |
| 3442 | host = urllib.parse.urlparse(self.GetCodereviewServer()).hostname |
| 3443 | issue = self.GetIssue() |
| 3444 | patchset = int(patchset or self.GetPatchset()) |
| 3445 | data = self._GetChangeDetail(['ALL_REVISIONS']) |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 3446 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3447 | assert host and issue and patchset, 'CL must be uploaded first' |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 3448 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3449 | has_patchset = any( |
| 3450 | int(revision_data['_number']) == patchset |
| 3451 | for revision_data in data['revisions'].values()) |
| 3452 | if not has_patchset: |
| 3453 | raise Exception('Patchset %d is not known in Gerrit change %d' % |
| 3454 | (patchset, self.GetIssue())) |
Edward Lemur | d4d1ba4 | 2019-09-20 21:46:37 +0000 | [diff] [blame] | 3455 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3456 | return { |
| 3457 | 'host': host, |
| 3458 | 'change': issue, |
| 3459 | 'project': data['project'], |
| 3460 | 'patchset': patchset, |
| 3461 | } |
tandrii | e113dfd | 2016-10-11 10:20:12 -0700 | [diff] [blame] | 3462 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3463 | def GetIssueOwner(self): |
| 3464 | return self._GetChangeDetail(['DETAILED_ACCOUNTS'])['owner']['email'] |
tandrii | de281ae | 2016-10-12 06:02:30 -0700 | [diff] [blame] | 3465 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3466 | def GetReviewers(self): |
| 3467 | details = self._GetChangeDetail(['DETAILED_ACCOUNTS']) |
| 3468 | return [r['email'] for r in details['reviewers'].get('REVIEWER', [])] |
Edward Lemur | 707d70b | 2018-02-07 00:50:14 +0100 | [diff] [blame] | 3469 | |
tandrii@chromium.org | d68b62b | 2016-03-31 16:09:29 +0000 | [diff] [blame] | 3470 | |
Lei Zhang | 8a0efc1 | 2020-08-05 19:58:45 +0000 | [diff] [blame] | 3471 | def _get_bug_line_values(default_project_prefix, bugs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3472 | """Given default_project_prefix and comma separated list of bugs, yields bug |
Lei Zhang | 8a0efc1 | 2020-08-05 19:58:45 +0000 | [diff] [blame] | 3473 | line values. |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3474 | |
| 3475 | Each bug can be either: |
Lei Zhang | 8a0efc1 | 2020-08-05 19:58:45 +0000 | [diff] [blame] | 3476 | * a number, which is combined with default_project_prefix |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3477 | * string, which is left as is. |
| 3478 | |
| 3479 | This function may produce more than one line, because bugdroid expects one |
| 3480 | project per line. |
| 3481 | |
Lei Zhang | 8a0efc1 | 2020-08-05 19:58:45 +0000 | [diff] [blame] | 3482 | >>> list(_get_bug_line_values('v8:', '123,chromium:789')) |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3483 | ['v8:123', 'chromium:789'] |
| 3484 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3485 | default_bugs = [] |
| 3486 | others = [] |
| 3487 | for bug in bugs.split(','): |
| 3488 | bug = bug.strip() |
| 3489 | if bug: |
| 3490 | try: |
| 3491 | default_bugs.append(int(bug)) |
| 3492 | except ValueError: |
| 3493 | others.append(bug) |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3494 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3495 | if default_bugs: |
| 3496 | default_bugs = ','.join(map(str, default_bugs)) |
| 3497 | if default_project_prefix: |
| 3498 | if not default_project_prefix.endswith(':'): |
| 3499 | default_project_prefix += ':' |
| 3500 | yield '%s%s' % (default_project_prefix, default_bugs) |
| 3501 | else: |
| 3502 | yield default_bugs |
| 3503 | for other in sorted(others): |
| 3504 | # Don't bother finding common prefixes, CLs with >2 bugs are very very |
| 3505 | # rare. |
| 3506 | yield other |
tandrii | f9aefb7 | 2016-07-01 09:06:51 -0700 | [diff] [blame] | 3507 | |
| 3508 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3509 | def FindCodereviewSettingsFile(filename='codereview.settings'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3510 | """Finds the given file starting in the cwd and going up. |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3511 | |
| 3512 | Only looks up to the top of the repository unless an |
| 3513 | 'inherit-review-settings-ok' file exists in the root of the repository. |
| 3514 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3515 | inherit_ok_file = 'inherit-review-settings-ok' |
| 3516 | cwd = os.getcwd() |
| 3517 | root = settings.GetRoot() |
| 3518 | if os.path.isfile(os.path.join(root, inherit_ok_file)): |
| 3519 | root = None |
| 3520 | while True: |
| 3521 | if os.path.isfile(os.path.join(cwd, filename)): |
| 3522 | return open(os.path.join(cwd, filename)) |
| 3523 | if cwd == root: |
| 3524 | break |
| 3525 | parent_dir = os.path.dirname(cwd) |
| 3526 | if parent_dir == cwd: |
| 3527 | # We hit the system root directory. |
| 3528 | break |
| 3529 | cwd = parent_dir |
| 3530 | return None |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3531 | |
| 3532 | |
| 3533 | def LoadCodereviewSettingsFromFile(fileobj): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3534 | """Parses a codereview.settings file and updates hooks.""" |
| 3535 | keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read()) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3536 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3537 | def SetProperty(name, setting, unset_error_ok=False): |
| 3538 | fullname = 'rietveld.' + name |
| 3539 | if setting in keyvals: |
| 3540 | RunGit(['config', fullname, keyvals[setting]]) |
| 3541 | else: |
| 3542 | RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3543 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3544 | if not keyvals.get('GERRIT_HOST', False): |
| 3545 | SetProperty('server', 'CODE_REVIEW_SERVER') |
| 3546 | # Only server setting is required. Other settings can be absent. |
| 3547 | # In that case, we ignore errors raised during option deletion attempt. |
| 3548 | SetProperty('cc', 'CC_LIST', unset_error_ok=True) |
| 3549 | SetProperty('tree-status-url', 'STATUS', unset_error_ok=True) |
| 3550 | SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True) |
| 3551 | SetProperty('bug-prefix', 'BUG_PREFIX', unset_error_ok=True) |
| 3552 | SetProperty('cpplint-regex', 'LINT_REGEX', unset_error_ok=True) |
| 3553 | SetProperty('cpplint-ignore-regex', |
| 3554 | 'LINT_IGNORE_REGEX', |
| 3555 | unset_error_ok=True) |
| 3556 | SetProperty('run-post-upload-hook', |
| 3557 | 'RUN_POST_UPLOAD_HOOK', |
| 3558 | unset_error_ok=True) |
| 3559 | SetProperty('format-full-by-default', |
| 3560 | 'FORMAT_FULL_BY_DEFAULT', |
| 3561 | unset_error_ok=True) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3562 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3563 | if 'GERRIT_HOST' in keyvals: |
| 3564 | RunGit(['config', 'gerrit.host', keyvals['GERRIT_HOST']]) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 3565 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3566 | if 'GERRIT_SQUASH_UPLOADS' in keyvals: |
| 3567 | RunGit([ |
| 3568 | 'config', 'gerrit.squash-uploads', keyvals['GERRIT_SQUASH_UPLOADS'] |
| 3569 | ]) |
bauerb@chromium.org | 54b400c | 2016-01-14 10:08:25 +0000 | [diff] [blame] | 3570 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3571 | if 'GERRIT_SKIP_ENSURE_AUTHENTICATED' in keyvals: |
| 3572 | RunGit([ |
| 3573 | 'config', 'gerrit.skip-ensure-authenticated', |
| 3574 | keyvals['GERRIT_SKIP_ENSURE_AUTHENTICATED'] |
| 3575 | ]) |
tandrii@chromium.org | 2825353 | 2016-04-14 13:46:56 +0000 | [diff] [blame] | 3576 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3577 | if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals: |
| 3578 | # should be of the form |
| 3579 | # PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof |
| 3580 | # ORIGIN_URL_CONFIG: http://src.chromium.org/git |
| 3581 | RunGit([ |
| 3582 | 'config', keyvals['PUSH_URL_CONFIG'], keyvals['ORIGIN_URL_CONFIG'] |
| 3583 | ]) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3584 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 3585 | |
joshua.lock@intel.com | 426f69b | 2012-08-02 23:41:49 +0000 | [diff] [blame] | 3586 | def urlretrieve(source, destination): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3587 | """Downloads a network object to a local file, like urllib.urlretrieve. |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 3588 | |
| 3589 | This is necessary because urllib is broken for SSL connections via a proxy. |
| 3590 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3591 | with open(destination, 'wb') as f: |
| 3592 | f.write(urllib.request.urlopen(source).read()) |
joshua.lock@intel.com | 426f69b | 2012-08-02 23:41:49 +0000 | [diff] [blame] | 3593 | |
| 3594 | |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3595 | def hasSheBang(fname): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3596 | """Checks fname is a #! script.""" |
| 3597 | with open(fname) as f: |
| 3598 | return f.read(2).startswith('#!') |
ukai@chromium.org | 712d610 | 2013-11-27 00:52:58 +0000 | [diff] [blame] | 3599 | |
| 3600 | |
tandrii@chromium.org | 18630d6 | 2016-03-04 12:06:02 +0000 | [diff] [blame] | 3601 | def DownloadGerritHook(force): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3602 | """Downloads and installs a Gerrit commit-msg hook. |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3603 | |
| 3604 | Args: |
| 3605 | force: True to update hooks. False to install hooks if not present. |
| 3606 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3607 | src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg' |
| 3608 | dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg') |
| 3609 | if not os.access(dst, os.X_OK): |
| 3610 | if os.path.exists(dst): |
| 3611 | if not force: |
| 3612 | return |
| 3613 | try: |
| 3614 | urlretrieve(src, dst) |
| 3615 | if not hasSheBang(dst): |
| 3616 | DieWithError('Not a script: %s\n' |
| 3617 | 'You need to download from\n%s\n' |
| 3618 | 'into .git/hooks/commit-msg and ' |
| 3619 | 'chmod +x .git/hooks/commit-msg' % (dst, src)) |
| 3620 | os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) |
| 3621 | except Exception: |
| 3622 | if os.path.exists(dst): |
| 3623 | os.remove(dst) |
| 3624 | DieWithError('\nFailed to download hooks.\n' |
| 3625 | 'You need to download from\n%s\n' |
| 3626 | 'into .git/hooks/commit-msg and ' |
| 3627 | 'chmod +x .git/hooks/commit-msg' % src) |
ukai@chromium.org | 78c4b98 | 2012-02-14 02:20:26 +0000 | [diff] [blame] | 3628 | |
| 3629 | |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3630 | class _GitCookiesChecker(object): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3631 | """Provides facilities for validating and suggesting fixes to .gitcookies.""" |
| 3632 | def __init__(self): |
| 3633 | # Cached list of [host, identity, source], where source is either |
| 3634 | # .gitcookies or .netrc. |
| 3635 | self._all_hosts = None |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3636 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3637 | def ensure_configured_gitcookies(self): |
| 3638 | """Runs checks and suggests fixes to make git use .gitcookies from default |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3639 | path.""" |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3640 | default = gerrit_util.CookiesAuthenticator.get_gitcookies_path() |
| 3641 | configured_path = RunGitSilent( |
| 3642 | ['config', '--global', 'http.cookiefile']).strip() |
| 3643 | configured_path = os.path.expanduser(configured_path) |
| 3644 | if configured_path: |
| 3645 | self._ensure_default_gitcookies_path(configured_path, default) |
| 3646 | else: |
| 3647 | self._configure_gitcookies_path(default) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3648 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3649 | @staticmethod |
| 3650 | def _ensure_default_gitcookies_path(configured_path, default_path): |
| 3651 | assert configured_path |
| 3652 | if configured_path == default_path: |
| 3653 | print('git is already configured to use your .gitcookies from %s' % |
| 3654 | configured_path) |
| 3655 | return |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3656 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3657 | print('WARNING: You have configured custom path to .gitcookies: %s\n' |
| 3658 | 'Gerrit and other depot_tools expect .gitcookies at %s\n' % |
| 3659 | (configured_path, default_path)) |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3660 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3661 | if not os.path.exists(configured_path): |
| 3662 | print('However, your configured .gitcookies file is missing.') |
| 3663 | confirm_or_exit('Reconfigure git to use default .gitcookies?', |
| 3664 | action='reconfigure') |
| 3665 | RunGit(['config', '--global', 'http.cookiefile', default_path]) |
| 3666 | return |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3667 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3668 | if os.path.exists(default_path): |
| 3669 | print('WARNING: default .gitcookies file already exists %s' % |
| 3670 | default_path) |
| 3671 | DieWithError( |
| 3672 | 'Please delete %s manually and re-run git cl creds-check' % |
| 3673 | default_path) |
Andrii Shyshkalov | 517948b | 2017-03-15 15:51:59 +0100 | [diff] [blame] | 3674 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3675 | confirm_or_exit('Move existing .gitcookies to default location?', |
| 3676 | action='move') |
| 3677 | shutil.move(configured_path, default_path) |
| 3678 | RunGit(['config', '--global', 'http.cookiefile', default_path]) |
| 3679 | print('Moved and reconfigured git to use .gitcookies from %s' % |
| 3680 | default_path) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3681 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3682 | @staticmethod |
| 3683 | def _configure_gitcookies_path(default_path): |
| 3684 | netrc_path = gerrit_util.CookiesAuthenticator.get_netrc_path() |
| 3685 | if os.path.exists(netrc_path): |
| 3686 | print( |
| 3687 | 'You seem to be using outdated .netrc for git credentials: %s' % |
| 3688 | netrc_path) |
| 3689 | print( |
| 3690 | 'This tool will guide you through setting up recommended ' |
| 3691 | '.gitcookies store for git credentials.\n' |
| 3692 | '\n' |
| 3693 | 'IMPORTANT: If something goes wrong and you decide to go back, do:\n' |
| 3694 | ' git config --global --unset http.cookiefile\n' |
| 3695 | ' mv %s %s.backup\n\n' % (default_path, default_path)) |
| 3696 | confirm_or_exit(action='setup .gitcookies') |
| 3697 | RunGit(['config', '--global', 'http.cookiefile', default_path]) |
| 3698 | print('Configured git to use .gitcookies from %s' % default_path) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3699 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3700 | def get_hosts_with_creds(self, include_netrc=False): |
| 3701 | if self._all_hosts is None: |
| 3702 | a = gerrit_util.CookiesAuthenticator() |
| 3703 | self._all_hosts = [(h, u, s) for h, u, s in itertools.chain(( |
| 3704 | (h, u, '.netrc') for h, (u, _, _) in a.netrc.hosts.items()), ( |
| 3705 | (h, u, '.gitcookies') |
| 3706 | for h, (u, _) in a.gitcookies.items())) |
| 3707 | if h.endswith(_GOOGLESOURCE)] |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 3708 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3709 | if include_netrc: |
| 3710 | return self._all_hosts |
| 3711 | return [(h, u, s) for h, u, s in self._all_hosts if s != '.netrc'] |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 3712 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3713 | def print_current_creds(self, include_netrc=False): |
| 3714 | hosts = sorted(self.get_hosts_with_creds(include_netrc=include_netrc)) |
| 3715 | if not hosts: |
| 3716 | print('No Git/Gerrit credentials found') |
| 3717 | return |
| 3718 | lengths = [max(map(len, (row[i] for row in hosts))) for i in range(3)] |
| 3719 | header = [('Host', 'User', 'Which file'), ['=' * l for l in lengths]] |
| 3720 | for row in (header + hosts): |
| 3721 | print('\t'.join((('%%+%ds' % l) % s) for l, s in zip(lengths, row))) |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 3722 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3723 | @staticmethod |
| 3724 | def _parse_identity(identity): |
| 3725 | """Parses identity "git-<username>.domain" into <username> and domain.""" |
| 3726 | # Special case: usernames that contain ".", which are generally not |
| 3727 | # distinguishable from sub-domains. But we do know typical domains: |
| 3728 | if identity.endswith('.chromium.org'): |
| 3729 | domain = 'chromium.org' |
| 3730 | username = identity[:-len('.chromium.org')] |
| 3731 | else: |
| 3732 | username, domain = identity.split('.', 1) |
| 3733 | if username.startswith('git-'): |
| 3734 | username = username[len('git-'):] |
| 3735 | return username, domain |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3736 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3737 | def has_generic_host(self): |
| 3738 | """Returns whether generic .googlesource.com has been configured. |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3739 | |
| 3740 | Chrome Infra recommends to use explicit ${host}.googlesource.com instead. |
| 3741 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3742 | for host, _, _ in self.get_hosts_with_creds(include_netrc=False): |
| 3743 | if host == '.' + _GOOGLESOURCE: |
| 3744 | return True |
| 3745 | return False |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3746 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3747 | def _get_git_gerrit_identity_pairs(self): |
| 3748 | """Returns map from canonic host to pair of identities (Git, Gerrit). |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3749 | |
| 3750 | One of identities might be None, meaning not configured. |
| 3751 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3752 | host_to_identity_pairs = {} |
| 3753 | for host, identity, _ in self.get_hosts_with_creds(): |
| 3754 | canonical = _canonical_git_googlesource_host(host) |
| 3755 | pair = host_to_identity_pairs.setdefault(canonical, [None, None]) |
| 3756 | idx = 0 if canonical == host else 1 |
| 3757 | pair[idx] = identity |
| 3758 | return host_to_identity_pairs |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3759 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3760 | def get_partially_configured_hosts(self): |
| 3761 | return set( |
| 3762 | (host if i1 else _canonical_gerrit_googlesource_host(host)) |
| 3763 | for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items() |
| 3764 | if None in (i1, i2) and host != '.' + _GOOGLESOURCE) |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3765 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3766 | def get_conflicting_hosts(self): |
| 3767 | return set( |
| 3768 | host |
| 3769 | for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items() |
| 3770 | if None not in (i1, i2) and i1 != i2) |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3771 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3772 | def get_duplicated_hosts(self): |
| 3773 | counters = collections.Counter( |
| 3774 | h for h, _, _ in self.get_hosts_with_creds()) |
| 3775 | return set(host for host, count in counters.items() if count > 1) |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3776 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3777 | @staticmethod |
| 3778 | def _format_hosts(hosts, extra_column_func=None): |
| 3779 | hosts = sorted(hosts) |
| 3780 | assert hosts |
| 3781 | if extra_column_func is None: |
| 3782 | extras = [''] * len(hosts) |
| 3783 | else: |
| 3784 | extras = [extra_column_func(host) for host in hosts] |
| 3785 | tmpl = '%%-%ds %%-%ds' % (max(map(len, hosts)), max(map(len, |
| 3786 | extras))) |
| 3787 | lines = [] |
| 3788 | for he in zip(hosts, extras): |
| 3789 | lines.append(tmpl % he) |
| 3790 | return lines |
Andrii Shyshkalov | 9780050 | 2017-03-16 16:04:32 +0100 | [diff] [blame] | 3791 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3792 | def _find_problems(self): |
| 3793 | if self.has_generic_host(): |
| 3794 | yield ('.googlesource.com wildcard record detected', [ |
| 3795 | 'Chrome Infrastructure team recommends to list full host names ' |
| 3796 | 'explicitly.' |
| 3797 | ], None) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3798 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3799 | dups = self.get_duplicated_hosts() |
| 3800 | if dups: |
| 3801 | yield ('The following hosts were defined twice', |
| 3802 | self._format_hosts(dups), None) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3803 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3804 | partial = self.get_partially_configured_hosts() |
| 3805 | if partial: |
| 3806 | yield ('Credentials should come in pairs for Git and Gerrit hosts. ' |
| 3807 | 'These hosts are missing', |
| 3808 | self._format_hosts( |
| 3809 | partial, lambda host: 'but %s defined' % |
| 3810 | _get_counterpart_host(host)), partial) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3811 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3812 | conflicting = self.get_conflicting_hosts() |
| 3813 | if conflicting: |
| 3814 | yield ( |
| 3815 | 'The following Git hosts have differing credentials from their ' |
| 3816 | 'Gerrit counterparts', |
| 3817 | self._format_hosts( |
| 3818 | conflicting, lambda host: '%s vs %s' % tuple( |
| 3819 | self._get_git_gerrit_identity_pairs()[host])), |
| 3820 | conflicting) |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3821 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3822 | def find_and_report_problems(self): |
| 3823 | """Returns True if there was at least one problem, else False.""" |
| 3824 | found = False |
| 3825 | bad_hosts = set() |
| 3826 | for title, sublines, hosts in self._find_problems(): |
| 3827 | if not found: |
| 3828 | found = True |
| 3829 | print('\n\n.gitcookies problem report:\n') |
| 3830 | bad_hosts.update(hosts or []) |
| 3831 | print(' %s%s' % (title, (':' if sublines else ''))) |
| 3832 | if sublines: |
| 3833 | print() |
| 3834 | print(' %s' % '\n '.join(sublines)) |
| 3835 | print() |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3836 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3837 | if bad_hosts: |
| 3838 | assert found |
| 3839 | print( |
| 3840 | ' You can manually remove corresponding lines in your %s file and ' |
| 3841 | 'visit the following URLs with correct account to generate ' |
| 3842 | 'correct credential lines:\n' % |
| 3843 | gerrit_util.CookiesAuthenticator.get_gitcookies_path()) |
| 3844 | print(' %s' % '\n '.join( |
| 3845 | sorted( |
| 3846 | set(gerrit_util.CookiesAuthenticator().get_new_password_url( |
| 3847 | _canonical_git_googlesource_host(host)) |
| 3848 | for host in bad_hosts)))) |
| 3849 | return found |
Andrii Shyshkalov | 0a0b067 | 2017-03-16 16:27:48 +0100 | [diff] [blame] | 3850 | |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3851 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 3852 | @metrics.collector.collect_metrics('git cl creds-check') |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3853 | def CMDcreds_check(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3854 | """Checks credentials and suggests changes.""" |
| 3855 | _, _ = parser.parse_args(args) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3856 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3857 | # Code below checks .gitcookies. Abort if using something else. |
| 3858 | authn = gerrit_util.Authenticator.get() |
| 3859 | if not isinstance(authn, gerrit_util.CookiesAuthenticator): |
| 3860 | message = ( |
| 3861 | 'This command is not designed for bot environment. It checks ' |
| 3862 | '~/.gitcookies file not generally used on bots.') |
| 3863 | # TODO(crbug.com/1059384): Automatically detect when running on |
| 3864 | # cloudtop. |
| 3865 | if isinstance(authn, gerrit_util.GceAuthenticator): |
| 3866 | message += ( |
| 3867 | '\n' |
| 3868 | 'If you need to run this on GCE or a cloudtop instance, ' |
| 3869 | 'export SKIP_GCE_AUTH_FOR_GIT=1 in your env.') |
| 3870 | DieWithError(message) |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3871 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3872 | checker = _GitCookiesChecker() |
| 3873 | checker.ensure_configured_gitcookies() |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 3874 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3875 | print('Your .netrc and .gitcookies have credentials for these hosts:') |
| 3876 | checker.print_current_creds(include_netrc=True) |
Andrii Shyshkalov | 34924cd | 2017-03-15 17:08:32 +0100 | [diff] [blame] | 3877 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3878 | if not checker.find_and_report_problems(): |
| 3879 | print('\nNo problems detected in your .gitcookies file.') |
| 3880 | return 0 |
| 3881 | return 1 |
Andrii Shyshkalov | 353637c | 2017-03-14 16:52:18 +0100 | [diff] [blame] | 3882 | |
| 3883 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 3884 | @metrics.collector.collect_metrics('git cl baseurl') |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 3885 | def CMDbaseurl(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3886 | """Gets or sets base-url for this branch.""" |
| 3887 | _, args = parser.parse_args(args) |
| 3888 | branchref = scm.GIT.GetBranchRef(settings.GetRoot()) |
| 3889 | branch = scm.GIT.ShortBranchName(branchref) |
| 3890 | if not args: |
| 3891 | print('Current base-url:') |
| 3892 | return RunGit(['config', 'branch.%s.base-url' % branch], |
| 3893 | error_ok=False).strip() |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 3894 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3895 | print('Setting base-url to %s' % args[0]) |
| 3896 | return RunGit(['config', 'branch.%s.base-url' % branch, args[0]], |
| 3897 | error_ok=False).strip() |
kalmard@homejinni.com | 6b0051e | 2012-04-03 15:45:08 +0000 | [diff] [blame] | 3898 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 3899 | |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 3900 | def color_for_status(status): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3901 | """Maps a Changelist status to color, for CMDstatus and other tools.""" |
| 3902 | BOLD = '\033[1m' |
| 3903 | return { |
| 3904 | 'unsent': BOLD + Fore.YELLOW, |
| 3905 | 'waiting': BOLD + Fore.RED, |
| 3906 | 'reply': BOLD + Fore.YELLOW, |
| 3907 | 'not lgtm': BOLD + Fore.RED, |
| 3908 | 'lgtm': BOLD + Fore.GREEN, |
| 3909 | 'commit': BOLD + Fore.MAGENTA, |
| 3910 | 'closed': BOLD + Fore.CYAN, |
| 3911 | 'error': BOLD + Fore.WHITE, |
| 3912 | }.get(status, Fore.WHITE) |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 3913 | |
tandrii@chromium.org | 04ea846 | 2016-04-25 19:51:21 +0000 | [diff] [blame] | 3914 | |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 3915 | def get_cl_statuses(changes, fine_grained, max_processes=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3916 | """Returns a blocking iterable of (cl, status) for given branches. |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 3917 | |
| 3918 | If fine_grained is true, this will fetch CL statuses from the server. |
| 3919 | Otherwise, simply indicate if there's a matching url for the given branches. |
| 3920 | |
| 3921 | If max_processes is specified, it is used as the maximum number of processes |
| 3922 | to spawn to fetch CL status from the server. Otherwise 1 process per branch is |
| 3923 | spawned. |
calamity@chromium.org | cf19748 | 2016-04-29 20:15:53 +0000 | [diff] [blame] | 3924 | |
| 3925 | See GetStatus() for a list of possible statuses. |
calamity@chromium.org | ffde55c | 2015-03-12 00:44:17 +0000 | [diff] [blame] | 3926 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3927 | if not changes: |
| 3928 | return |
calamity@chromium.org | cf19748 | 2016-04-29 20:15:53 +0000 | [diff] [blame] | 3929 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3930 | if not fine_grained: |
| 3931 | # Fast path which doesn't involve querying codereview servers. |
| 3932 | # Do not use get_approving_reviewers(), since it requires an HTTP |
| 3933 | # request. |
| 3934 | for cl in changes: |
| 3935 | yield (cl, 'waiting' if cl.GetIssueURL() else 'error') |
| 3936 | return |
| 3937 | |
| 3938 | # First, sort out authentication issues. |
| 3939 | logging.debug('ensuring credentials exist') |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 3940 | for cl in changes: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3941 | cl.EnsureAuthenticated(force=False, refresh=True) |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 3942 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3943 | def fetch(cl): |
| 3944 | try: |
| 3945 | return (cl, cl.GetStatus()) |
| 3946 | except: |
| 3947 | # See http://crbug.com/629863. |
| 3948 | logging.exception('failed to fetch status for cl %s:', |
| 3949 | cl.GetIssue()) |
| 3950 | raise |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 3951 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3952 | threads_count = len(changes) |
| 3953 | if max_processes: |
| 3954 | threads_count = max(1, min(threads_count, max_processes)) |
| 3955 | logging.debug('querying %d CLs using %d threads', len(changes), |
| 3956 | threads_count) |
| 3957 | |
| 3958 | pool = multiprocessing.pool.ThreadPool(threads_count) |
| 3959 | fetched_cls = set() |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 3960 | try: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3961 | it = pool.imap_unordered(fetch, changes).__iter__() |
| 3962 | while True: |
| 3963 | try: |
| 3964 | cl, status = it.next(timeout=5) |
| 3965 | except (multiprocessing.TimeoutError, StopIteration): |
| 3966 | break |
| 3967 | fetched_cls.add(cl) |
| 3968 | yield cl, status |
| 3969 | finally: |
| 3970 | pool.close() |
Andrii Shyshkalov | 2f8e924 | 2017-01-23 19:20:19 +0100 | [diff] [blame] | 3971 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3972 | # Add any branches that failed to fetch. |
| 3973 | for cl in set(changes) - fetched_cls: |
| 3974 | yield (cl, 'error') |
jsbell@chromium.org | b99fbd9 | 2014-09-11 17:29:28 +0000 | [diff] [blame] | 3975 | |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 3976 | |
Jose Lopes | 3863fc5 | 2020-04-07 17:00:25 +0000 | [diff] [blame] | 3977 | def upload_branch_deps(cl, args, force=False): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3978 | """Uploads CLs of local branches that are dependents of the current branch. |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 3979 | |
| 3980 | If the local branch dependency tree looks like: |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 3981 | |
| 3982 | test1 -> test2.1 -> test3.1 |
| 3983 | -> test3.2 |
| 3984 | -> test2.2 -> test3.3 |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 3985 | |
| 3986 | and you run "git cl upload --dependencies" from test1 then "git cl upload" is |
| 3987 | run on the dependent branches in this order: |
| 3988 | test2.1, test3.1, test3.2, test2.2, test3.3 |
| 3989 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 3990 | Note: This function does not rebase your local dependent branches. Use it |
| 3991 | when you make a change to the parent branch that will not conflict |
| 3992 | with its dependent branches, and you would like their dependencies |
| 3993 | updated in Rietveld. |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 3994 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3995 | if git_common.is_dirty_git_tree('upload-branch-deps'): |
| 3996 | return 1 |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 3997 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 3998 | root_branch = cl.GetBranch() |
| 3999 | if root_branch is None: |
| 4000 | DieWithError('Can\'t find dependent branches from detached HEAD state. ' |
| 4001 | 'Get on a branch!') |
| 4002 | if not cl.GetIssue(): |
| 4003 | DieWithError( |
| 4004 | 'Current branch does not have an uploaded CL. We cannot set ' |
| 4005 | 'patchset dependencies without an uploaded CL.') |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4006 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4007 | branches = RunGit([ |
| 4008 | 'for-each-ref', '--format=%(refname:short) %(upstream:short)', |
| 4009 | 'refs/heads' |
| 4010 | ]) |
| 4011 | if not branches: |
| 4012 | print('No local branches found.') |
| 4013 | return 0 |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4014 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4015 | # Create a dictionary of all local branches to the branches that are |
| 4016 | # dependent on it. |
| 4017 | tracked_to_dependents = collections.defaultdict(list) |
| 4018 | for b in branches.splitlines(): |
| 4019 | tokens = b.split() |
| 4020 | if len(tokens) == 2: |
| 4021 | branch_name, tracked = tokens |
| 4022 | tracked_to_dependents[tracked].append(branch_name) |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4023 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4024 | print() |
| 4025 | print('The dependent local branches of %s are:' % root_branch) |
| 4026 | dependents = [] |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 4027 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4028 | def traverse_dependents_preorder(branch, padding=''): |
| 4029 | dependents_to_process = tracked_to_dependents.get(branch, []) |
| 4030 | padding += ' ' |
| 4031 | for dependent in dependents_to_process: |
| 4032 | print('%s%s' % (padding, dependent)) |
| 4033 | dependents.append(dependent) |
| 4034 | traverse_dependents_preorder(dependent, padding) |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 4035 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4036 | traverse_dependents_preorder(root_branch) |
| 4037 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4038 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4039 | if not dependents: |
| 4040 | print('There are no dependent local branches for %s' % root_branch) |
| 4041 | return 0 |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4042 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4043 | # Record all dependents that failed to upload. |
| 4044 | failures = {} |
| 4045 | # Go through all dependents, checkout the branch and upload. |
| 4046 | try: |
| 4047 | for dependent_branch in dependents: |
| 4048 | print() |
| 4049 | print('--------------------------------------') |
| 4050 | print('Running "git cl upload" from %s:' % dependent_branch) |
| 4051 | RunGit(['checkout', '-q', dependent_branch]) |
| 4052 | print() |
| 4053 | try: |
| 4054 | if CMDupload(OptionParser(), args) != 0: |
| 4055 | print('Upload failed for %s!' % dependent_branch) |
| 4056 | failures[dependent_branch] = 1 |
| 4057 | except: # pylint: disable=bare-except |
| 4058 | failures[dependent_branch] = 1 |
| 4059 | print() |
| 4060 | finally: |
| 4061 | # Swap back to the original root branch. |
| 4062 | RunGit(['checkout', '-q', root_branch]) |
| 4063 | |
| 4064 | print() |
| 4065 | print('Upload complete for dependent branches!') |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4066 | for dependent_branch in dependents: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4067 | upload_status = 'failed' if failures.get( |
| 4068 | dependent_branch) else 'succeeded' |
| 4069 | print(' %s : %s' % (dependent_branch, upload_status)) |
| 4070 | print() |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4071 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4072 | return 0 |
rmistry@google.com | 2dd9986 | 2015-06-22 12:22:18 +0000 | [diff] [blame] | 4073 | |
| 4074 | |
Tibor Goldschwendt | 7c5efb2 | 2020-03-25 01:23:54 +0000 | [diff] [blame] | 4075 | def GetArchiveTagForBranch(issue_num, branch_name, existing_tags, pattern): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4076 | """Given a proposed tag name, returns a tag name that is guaranteed to be |
Kevin Marshall | 0e60ecd | 2019-12-04 17:44:13 +0000 | [diff] [blame] | 4077 | unique. If 'foo' is proposed but already exists, then 'foo-2' is used, |
| 4078 | or 'foo-3', and so on.""" |
| 4079 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4080 | proposed_tag = pattern.format(**{'issue': issue_num, 'branch': branch_name}) |
| 4081 | for suffix_num in itertools.count(1): |
| 4082 | if suffix_num == 1: |
| 4083 | to_check = proposed_tag |
| 4084 | else: |
| 4085 | to_check = '%s-%d' % (proposed_tag, suffix_num) |
Kevin Marshall | 0e60ecd | 2019-12-04 17:44:13 +0000 | [diff] [blame] | 4086 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4087 | if to_check not in existing_tags: |
| 4088 | return to_check |
Kevin Marshall | 0e60ecd | 2019-12-04 17:44:13 +0000 | [diff] [blame] | 4089 | |
| 4090 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4091 | @metrics.collector.collect_metrics('git cl archive') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4092 | def CMDarchive(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4093 | """Archives and deletes branches associated with closed changelists.""" |
| 4094 | parser.add_option( |
| 4095 | '-j', |
| 4096 | '--maxjobs', |
| 4097 | action='store', |
| 4098 | type=int, |
| 4099 | help='The maximum number of jobs to use when retrieving review status.') |
| 4100 | parser.add_option('-f', |
| 4101 | '--force', |
| 4102 | action='store_true', |
| 4103 | help='Bypasses the confirmation prompt.') |
| 4104 | parser.add_option('-d', |
| 4105 | '--dry-run', |
| 4106 | action='store_true', |
| 4107 | help='Skip the branch tagging and removal steps.') |
| 4108 | parser.add_option('-t', |
| 4109 | '--notags', |
| 4110 | action='store_true', |
| 4111 | help='Do not tag archived branches. ' |
| 4112 | 'Note: local commit history may be lost.') |
| 4113 | parser.add_option('-p', |
| 4114 | '--pattern', |
| 4115 | default='git-cl-archived-{issue}-{branch}', |
| 4116 | help='Format string for archive tags. ' |
| 4117 | 'E.g. \'archived-{issue}-{branch}\'.') |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4118 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4119 | options, args = parser.parse_args(args) |
| 4120 | if args: |
| 4121 | parser.error('Unsupported args: %s' % ' '.join(args)) |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4122 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4123 | branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads']) |
| 4124 | if not branches: |
| 4125 | return 0 |
| 4126 | |
| 4127 | tags = RunGit(['for-each-ref', '--format=%(refname)', 'refs/tags' |
| 4128 | ]).splitlines() or [] |
| 4129 | tags = [t.split('/')[-1] for t in tags] |
| 4130 | |
| 4131 | print('Finding all branches associated with closed issues...') |
| 4132 | changes = [Changelist(branchref=b) for b in branches.splitlines()] |
| 4133 | alignment = max(5, max(len(c.GetBranch()) for c in changes)) |
| 4134 | statuses = get_cl_statuses(changes, |
| 4135 | fine_grained=True, |
| 4136 | max_processes=options.maxjobs) |
| 4137 | proposal = [(cl.GetBranch(), |
| 4138 | GetArchiveTagForBranch(cl.GetIssue(), cl.GetBranch(), tags, |
| 4139 | options.pattern)) |
| 4140 | for cl, status in statuses |
| 4141 | if status in ('closed', 'rietveld-not-supported')] |
| 4142 | proposal.sort() |
| 4143 | |
| 4144 | if not proposal: |
| 4145 | print('No branches with closed codereview issues found.') |
| 4146 | return 0 |
| 4147 | |
| 4148 | current_branch = scm.GIT.GetBranch(settings.GetRoot()) |
| 4149 | |
| 4150 | print('\nBranches with closed issues that will be archived:\n') |
| 4151 | if options.notags: |
| 4152 | for next_item in proposal: |
| 4153 | print(' ' + next_item[0]) |
| 4154 | else: |
| 4155 | print('%*s | %s' % (alignment, 'Branch name', 'Archival tag name')) |
| 4156 | for next_item in proposal: |
| 4157 | print('%*s %s' % (alignment, next_item[0], next_item[1])) |
| 4158 | |
| 4159 | # Quit now on precondition failure or if instructed by the user, either |
| 4160 | # via an interactive prompt or by command line flags. |
| 4161 | if options.dry_run: |
| 4162 | print('\nNo changes were made (dry run).\n') |
| 4163 | return 0 |
| 4164 | |
| 4165 | if any(branch == current_branch for branch, _ in proposal): |
| 4166 | print('You are currently on a branch \'%s\' which is associated with a ' |
| 4167 | 'closed codereview issue, so archive cannot proceed. Please ' |
| 4168 | 'checkout another branch and run this command again.' % |
| 4169 | current_branch) |
| 4170 | return 1 |
| 4171 | |
| 4172 | if not options.force: |
| 4173 | answer = gclient_utils.AskForData( |
| 4174 | '\nProceed with deletion (Y/n)? ').lower() |
| 4175 | if answer not in ('y', ''): |
| 4176 | print('Aborted.') |
| 4177 | return 1 |
| 4178 | |
| 4179 | for branch, tagname in proposal: |
| 4180 | if not options.notags: |
| 4181 | RunGit(['tag', tagname, branch]) |
| 4182 | |
| 4183 | if RunGitWithCode(['branch', '-D', branch])[0] != 0: |
| 4184 | # Clean up the tag if we failed to delete the branch. |
| 4185 | RunGit(['tag', '-d', tagname]) |
| 4186 | |
| 4187 | print('\nJob\'s done!') |
| 4188 | |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4189 | return 0 |
| 4190 | |
kmarshall | 3bff56b | 2016-06-06 18:31:47 -0700 | [diff] [blame] | 4191 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4192 | @metrics.collector.collect_metrics('git cl status') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4193 | def CMDstatus(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4194 | """Show status of changelists. |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4195 | |
| 4196 | 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] | 4197 | - Blue waiting for review |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4198 | - Yellow waiting for you to reply to review, or not yet sent |
jsbell@chromium.org | aeab41a | 2013-12-10 20:01:22 +0000 | [diff] [blame] | 4199 | - Green LGTM'ed |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4200 | - Red 'not LGTM'ed |
Andrii Shyshkalov | 0e889b7 | 2019-07-15 22:28:48 +0000 | [diff] [blame] | 4201 | - Magenta in the CQ |
jsbell@chromium.org | aeab41a | 2013-12-10 20:01:22 +0000 | [diff] [blame] | 4202 | - Cyan was committed, branch can be deleted |
Aaron Gable | 9ab38c6 | 2017-04-06 14:36:33 -0700 | [diff] [blame] | 4203 | - White error, or unknown status |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4204 | |
| 4205 | Also see 'git cl comments'. |
| 4206 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4207 | parser.add_option('--no-branch-color', |
| 4208 | action='store_true', |
| 4209 | help='Disable colorized branch names') |
| 4210 | parser.add_option( |
| 4211 | '--field', help='print only specific field (desc|id|patch|status|url)') |
| 4212 | parser.add_option('-f', |
| 4213 | '--fast', |
| 4214 | action='store_true', |
| 4215 | help='Do not retrieve review status') |
| 4216 | parser.add_option( |
| 4217 | '-j', |
| 4218 | '--maxjobs', |
| 4219 | action='store', |
| 4220 | type=int, |
| 4221 | help='The maximum number of jobs to use when retrieving review status') |
| 4222 | parser.add_option( |
| 4223 | '-i', |
| 4224 | '--issue', |
| 4225 | type=int, |
| 4226 | help='Operate on this issue instead of the current branch\'s implicit ' |
| 4227 | 'issue. Requires --field to be set.') |
| 4228 | parser.add_option('-d', |
| 4229 | '--date-order', |
| 4230 | action='store_true', |
| 4231 | help='Order branches by committer date.') |
| 4232 | options, args = parser.parse_args(args) |
| 4233 | if args: |
| 4234 | parser.error('Unsupported args: %s' % args) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4235 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4236 | if options.issue is not None and not options.field: |
| 4237 | parser.error('--field must be given when --issue is set.') |
iannucci | 3c972b9 | 2016-08-17 13:24:10 -0700 | [diff] [blame] | 4238 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4239 | if options.field: |
| 4240 | cl = Changelist(issue=options.issue) |
| 4241 | if options.field.startswith('desc'): |
| 4242 | if cl.GetIssue(): |
| 4243 | print(cl.FetchDescription()) |
| 4244 | elif options.field == 'id': |
| 4245 | issueid = cl.GetIssue() |
| 4246 | if issueid: |
| 4247 | print(issueid) |
| 4248 | elif options.field == 'patch': |
| 4249 | patchset = cl.GetMostRecentPatchset() |
| 4250 | if patchset: |
| 4251 | print(patchset) |
| 4252 | elif options.field == 'status': |
| 4253 | print(cl.GetStatus()) |
| 4254 | elif options.field == 'url': |
| 4255 | url = cl.GetIssueURL() |
| 4256 | if url: |
| 4257 | print(url) |
| 4258 | return 0 |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 4259 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4260 | branches = RunGit([ |
| 4261 | 'for-each-ref', '--format=%(refname) %(committerdate:unix)', |
| 4262 | 'refs/heads' |
| 4263 | ]) |
| 4264 | if not branches: |
| 4265 | print('No local branch found.') |
| 4266 | return 0 |
maruel@chromium.org | e25c75b | 2013-07-23 18:30:56 +0000 | [diff] [blame] | 4267 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4268 | changes = [ |
| 4269 | Changelist(branchref=b, commit_date=ct) |
| 4270 | for b, ct in map(lambda line: line.split(' '), branches.splitlines()) |
| 4271 | ] |
| 4272 | print('Branches associated with reviews:') |
| 4273 | output = get_cl_statuses(changes, |
| 4274 | fine_grained=not options.fast, |
| 4275 | max_processes=options.maxjobs) |
maruel@chromium.org | 1033efd | 2013-07-23 23:25:09 +0000 | [diff] [blame] | 4276 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4277 | current_branch = scm.GIT.GetBranch(settings.GetRoot()) |
Daniel McArdle | a23bf59 | 2019-02-12 00:25:12 +0000 | [diff] [blame] | 4278 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4279 | def FormatBranchName(branch, colorize=False): |
| 4280 | """Simulates 'git branch' behavior. Colorizes and prefixes branch name with |
Daniel McArdle | a23bf59 | 2019-02-12 00:25:12 +0000 | [diff] [blame] | 4281 | an asterisk when it is the current branch.""" |
| 4282 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4283 | asterisk = "" |
| 4284 | color = Fore.RESET |
| 4285 | if branch == current_branch: |
| 4286 | asterisk = "* " |
| 4287 | color = Fore.GREEN |
| 4288 | branch_name = scm.GIT.ShortBranchName(branch) |
Daniel McArdle | a23bf59 | 2019-02-12 00:25:12 +0000 | [diff] [blame] | 4289 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4290 | if colorize: |
| 4291 | return asterisk + color + branch_name + Fore.RESET |
| 4292 | return asterisk + branch_name |
Daniel McArdle | 452a49f | 2019-02-14 17:28:31 +0000 | [diff] [blame] | 4293 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4294 | branch_statuses = {} |
Daniel McArdle | a23bf59 | 2019-02-12 00:25:12 +0000 | [diff] [blame] | 4295 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4296 | alignment = max(5, |
| 4297 | max(len(FormatBranchName(c.GetBranch())) for c in changes)) |
Sigurd Schneider | 1bfda8e | 2021-06-30 14:46:25 +0000 | [diff] [blame] | 4298 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4299 | if options.date_order or settings.IsStatusCommitOrderByDate(): |
| 4300 | sorted_changes = sorted(changes, |
| 4301 | key=lambda c: c.GetCommitDate(), |
| 4302 | reverse=True) |
| 4303 | else: |
| 4304 | sorted_changes = sorted(changes, key=lambda c: c.GetBranch()) |
| 4305 | for cl in sorted_changes: |
| 4306 | branch = cl.GetBranch() |
| 4307 | while branch not in branch_statuses: |
| 4308 | c, status = next(output) |
| 4309 | branch_statuses[c.GetBranch()] = status |
| 4310 | status = branch_statuses.pop(branch) |
| 4311 | url = cl.GetIssueURL(short=True) |
| 4312 | if url and (not status or status == 'error'): |
| 4313 | # The issue probably doesn't exist anymore. |
| 4314 | url += ' (broken)' |
clemensh@chromium.org | cbd7dc3 | 2016-05-31 10:33:50 +0000 | [diff] [blame] | 4315 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4316 | color = color_for_status(status) |
| 4317 | # Turn off bold as well as colors. |
| 4318 | END = '\033[0m' |
| 4319 | reset = Fore.RESET + END |
| 4320 | if not setup_color.IS_TTY: |
| 4321 | color = '' |
| 4322 | reset = '' |
| 4323 | status_str = '(%s)' % status if status else '' |
Daniel McArdle | 452a49f | 2019-02-14 17:28:31 +0000 | [diff] [blame] | 4324 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4325 | branch_display = FormatBranchName(branch) |
| 4326 | padding = ' ' * (alignment - len(branch_display)) |
| 4327 | if not options.no_branch_color: |
| 4328 | branch_display = FormatBranchName(branch, colorize=True) |
Daniel McArdle | 452a49f | 2019-02-14 17:28:31 +0000 | [diff] [blame] | 4329 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4330 | print(' %s : %s%s %s%s' % |
| 4331 | (padding + branch_display, color, url, status_str, reset)) |
Andrii Shyshkalov | d0e1d9d | 2017-01-24 17:10:51 +0100 | [diff] [blame] | 4332 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4333 | print() |
| 4334 | print('Current branch: %s' % current_branch) |
| 4335 | for cl in changes: |
| 4336 | if cl.GetBranch() == current_branch: |
| 4337 | break |
| 4338 | if not cl.GetIssue(): |
| 4339 | print('No issue assigned.') |
| 4340 | return 0 |
| 4341 | print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())) |
| 4342 | if not options.fast: |
| 4343 | print('Issue description:') |
| 4344 | print(cl.FetchDescription(pretty=True)) |
dpranke@chromium.org | ee87f58 | 2015-07-31 18:46:25 +0000 | [diff] [blame] | 4345 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4346 | |
| 4347 | |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4348 | def colorize_CMDstatus_doc(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4349 | """To be called once in main() to add colors to git cl status help.""" |
| 4350 | colors = [i for i in dir(Fore) if i[0].isupper()] |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4351 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4352 | def colorize_line(line): |
| 4353 | for color in colors: |
| 4354 | if color in line.upper(): |
| 4355 | # Extract whitespace first and the leading '-'. |
| 4356 | indent = len(line) - len(line.lstrip(' ')) + 1 |
| 4357 | return line[:indent] + getattr( |
| 4358 | Fore, color) + line[indent:] + Fore.RESET |
| 4359 | return line |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4360 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4361 | lines = CMDstatus.__doc__.splitlines() |
| 4362 | CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines) |
maruel@chromium.org | 39c0b22 | 2013-08-17 16:57:01 +0000 | [diff] [blame] | 4363 | |
| 4364 | |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4365 | def write_json(path, contents): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4366 | if path == '-': |
| 4367 | json.dump(contents, sys.stdout) |
| 4368 | else: |
| 4369 | with open(path, 'w') as f: |
| 4370 | json.dump(contents, f) |
phajdan.jr | e328cf9 | 2016-08-22 04:12:17 -0700 | [diff] [blame] | 4371 | |
| 4372 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 4373 | @subcommand.usage('[issue_number]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4374 | @metrics.collector.collect_metrics('git cl issue') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4375 | def CMDissue(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4376 | """Sets or displays the current code review issue number. |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4377 | |
| 4378 | Pass issue number 0 to clear the current issue. |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 4379 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4380 | parser.add_option('-r', |
| 4381 | '--reverse', |
| 4382 | action='store_true', |
| 4383 | help='Lookup the branch(es) for the specified issues. If ' |
| 4384 | 'no issues are specified, all branches with mapped ' |
| 4385 | 'issues will be listed.') |
| 4386 | parser.add_option('--json', |
| 4387 | help='Path to JSON output file, or "-" for stdout.') |
| 4388 | options, args = parser.parse_args(args) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4389 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4390 | if options.reverse: |
| 4391 | branches = RunGit(['for-each-ref', 'refs/heads', |
| 4392 | '--format=%(refname)']).splitlines() |
| 4393 | # Reverse issue lookup. |
| 4394 | issue_branch_map = {} |
Arthur Milchior | 801a975 | 2023-04-07 10:33:54 +0000 | [diff] [blame] | 4395 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4396 | git_config = {} |
| 4397 | for config in RunGit(['config', '--get-regexp', |
| 4398 | r'branch\..*issue']).splitlines(): |
| 4399 | name, _space, val = config.partition(' ') |
| 4400 | git_config[name] = val |
Arthur Milchior | 801a975 | 2023-04-07 10:33:54 +0000 | [diff] [blame] | 4401 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4402 | for branch in branches: |
| 4403 | issue = git_config.get( |
| 4404 | 'branch.%s.%s' % |
| 4405 | (scm.GIT.ShortBranchName(branch), ISSUE_CONFIG_KEY)) |
| 4406 | if issue: |
| 4407 | issue_branch_map.setdefault(int(issue), []).append(branch) |
| 4408 | if not args: |
| 4409 | args = sorted(issue_branch_map.keys()) |
| 4410 | result = {} |
| 4411 | for issue in args: |
| 4412 | try: |
| 4413 | issue_num = int(issue) |
| 4414 | except ValueError: |
| 4415 | print('ERROR cannot parse issue number: %s' % issue, |
| 4416 | file=sys.stderr) |
| 4417 | continue |
| 4418 | result[issue_num] = issue_branch_map.get(issue_num) |
| 4419 | print('Branch for issue number %s: %s' % (issue, ', '.join( |
| 4420 | issue_branch_map.get(issue_num) or ('None', )))) |
| 4421 | if options.json: |
| 4422 | write_json(options.json, result) |
| 4423 | return 0 |
| 4424 | |
| 4425 | if len(args) > 0: |
| 4426 | issue = ParseIssueNumberArgument(args[0]) |
| 4427 | if not issue.valid: |
| 4428 | DieWithError( |
| 4429 | 'Pass a url or number to set the issue, 0 to unset it, ' |
| 4430 | 'or no argument to list it.\n' |
| 4431 | 'Maybe you want to run git cl status?') |
| 4432 | cl = Changelist() |
| 4433 | cl.SetIssue(issue.issue) |
| 4434 | else: |
| 4435 | cl = Changelist() |
| 4436 | print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())) |
Arthur Milchior | 801a975 | 2023-04-07 10:33:54 +0000 | [diff] [blame] | 4437 | if options.json: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4438 | write_json( |
| 4439 | options.json, { |
| 4440 | 'gerrit_host': cl.GetGerritHost(), |
| 4441 | 'gerrit_project': cl.GetGerritProject(), |
| 4442 | 'issue_url': cl.GetIssueURL(), |
| 4443 | 'issue': cl.GetIssue(), |
| 4444 | }) |
Arthur Milchior | 801a975 | 2023-04-07 10:33:54 +0000 | [diff] [blame] | 4445 | return 0 |
Aaron Gable | 78753da | 2017-06-15 10:35:49 -0700 | [diff] [blame] | 4446 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4447 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4448 | @metrics.collector.collect_metrics('git cl comments') |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 4449 | def CMDcomments(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4450 | """Shows or posts review comments for any changelist.""" |
| 4451 | parser.add_option('-a', |
| 4452 | '--add-comment', |
| 4453 | dest='comment', |
| 4454 | help='comment to add to an issue') |
| 4455 | parser.add_option('-p', |
| 4456 | '--publish', |
| 4457 | action='store_true', |
| 4458 | help='marks CL as ready and sends comment to reviewers') |
| 4459 | parser.add_option('-i', |
| 4460 | '--issue', |
| 4461 | dest='issue', |
| 4462 | help='review issue id (defaults to current issue).') |
| 4463 | parser.add_option('-m', |
| 4464 | '--machine-readable', |
| 4465 | dest='readable', |
| 4466 | action='store_false', |
| 4467 | default=True, |
| 4468 | help='output comments in a format compatible with ' |
| 4469 | 'editor parsing') |
| 4470 | parser.add_option('-j', |
| 4471 | '--json-file', |
| 4472 | help='File to write JSON summary to, or "-" for stdout') |
| 4473 | options, args = parser.parse_args(args) |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 4474 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4475 | issue = None |
| 4476 | if options.issue: |
| 4477 | try: |
| 4478 | issue = int(options.issue) |
| 4479 | except ValueError: |
| 4480 | DieWithError('A review issue ID is expected to be a number.') |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4481 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4482 | cl = Changelist(issue=issue) |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4483 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4484 | if options.comment: |
| 4485 | cl.AddComment(options.comment, options.publish) |
| 4486 | return 0 |
| 4487 | |
| 4488 | summary = sorted(cl.GetCommentsSummary(readable=options.readable), |
| 4489 | key=lambda c: c.date) |
| 4490 | for comment in summary: |
| 4491 | if comment.disapproval: |
| 4492 | color = Fore.RED |
| 4493 | elif comment.approval: |
| 4494 | color = Fore.GREEN |
| 4495 | elif comment.sender == cl.GetIssueOwner(): |
| 4496 | color = Fore.MAGENTA |
| 4497 | elif comment.autogenerated: |
| 4498 | color = Fore.CYAN |
| 4499 | else: |
| 4500 | color = Fore.BLUE |
| 4501 | print('\n%s%s %s%s\n%s' % |
| 4502 | (color, comment.date.strftime('%Y-%m-%d %H:%M:%S UTC'), |
| 4503 | comment.sender, Fore.RESET, '\n'.join( |
| 4504 | ' ' + l for l in comment.message.strip().splitlines()))) |
| 4505 | |
| 4506 | if options.json_file: |
| 4507 | |
| 4508 | def pre_serialize(c): |
| 4509 | dct = c._asdict().copy() |
| 4510 | dct['date'] = dct['date'].strftime('%Y-%m-%d %H:%M:%S.%f') |
| 4511 | return dct |
| 4512 | |
| 4513 | write_json(options.json_file, [pre_serialize(x) for x in summary]) |
apavlov@chromium.org | e4efd51 | 2014-11-05 09:05:29 +0000 | [diff] [blame] | 4514 | return 0 |
| 4515 | |
maruel@chromium.org | 9977a2e | 2012-06-06 22:30:56 +0000 | [diff] [blame] | 4516 | |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4517 | @subcommand.usage('[codereview url or issue id]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4518 | @metrics.collector.collect_metrics('git cl description') |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4519 | def CMDdescription(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4520 | """Brings up the editor for the current CL's description.""" |
| 4521 | parser.add_option( |
| 4522 | '-d', |
| 4523 | '--display', |
| 4524 | action='store_true', |
| 4525 | help='Display the description instead of opening an editor') |
| 4526 | parser.add_option( |
| 4527 | '-n', |
| 4528 | '--new-description', |
| 4529 | help='New description to set for this issue (- for stdin, ' |
| 4530 | '+ to load from local commit HEAD)') |
| 4531 | parser.add_option('-f', |
| 4532 | '--force', |
| 4533 | action='store_true', |
| 4534 | help='Delete any unpublished Gerrit edits for this issue ' |
| 4535 | 'without prompting') |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4536 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4537 | options, args = parser.parse_args(args) |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4538 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4539 | target_issue_arg = None |
| 4540 | if len(args) > 0: |
| 4541 | target_issue_arg = ParseIssueNumberArgument(args[0]) |
| 4542 | if not target_issue_arg.valid: |
| 4543 | parser.error('Invalid issue ID or URL.') |
martiniss@chromium.org | 2b55fe3 | 2016-04-26 20:28:54 +0000 | [diff] [blame] | 4544 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4545 | kwargs = {} |
| 4546 | if target_issue_arg: |
| 4547 | kwargs['issue'] = target_issue_arg.issue |
| 4548 | kwargs['codereview_host'] = target_issue_arg.hostname |
martiniss | 6eda05f | 2016-06-30 10:18:35 -0700 | [diff] [blame] | 4549 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4550 | cl = Changelist(**kwargs) |
| 4551 | if not cl.GetIssue(): |
| 4552 | DieWithError('This branch has no associated changelist.') |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4553 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4554 | if args and not args[0].isdigit(): |
| 4555 | logging.info('canonical issue/change URL: %s\n', cl.GetIssueURL()) |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 4556 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4557 | description = ChangeDescription(cl.FetchDescription()) |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4558 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4559 | if options.display: |
| 4560 | print(description.description) |
| 4561 | return 0 |
| 4562 | |
| 4563 | if options.new_description: |
| 4564 | text = options.new_description |
| 4565 | if text == '-': |
| 4566 | text = '\n'.join(l.rstrip() for l in sys.stdin) |
| 4567 | elif text == '+': |
| 4568 | base_branch = cl.GetCommonAncestorWithUpstream() |
| 4569 | text = _create_description_from_log([base_branch]) |
| 4570 | |
| 4571 | description.set_description(text) |
| 4572 | else: |
| 4573 | description.prompt() |
| 4574 | if cl.FetchDescription().strip() != description.description: |
| 4575 | cl.UpdateDescription(description.description, force=options.force) |
smut@google.com | 34fb6b1 | 2015-07-13 20:03:26 +0000 | [diff] [blame] | 4576 | return 0 |
martiniss@chromium.org | d6648e2 | 2016-04-29 19:22:16 +0000 | [diff] [blame] | 4577 | |
rsesek@chromium.org | eec7659 | 2013-05-20 16:27:57 +0000 | [diff] [blame] | 4578 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4579 | @metrics.collector.collect_metrics('git cl lint') |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4580 | def CMDlint(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4581 | """Runs cpplint on the current changelist.""" |
| 4582 | parser.add_option( |
| 4583 | '--filter', |
| 4584 | action='append', |
| 4585 | metavar='-x,+y', |
| 4586 | help='Comma-separated list of cpplint\'s category-filters') |
| 4587 | options, args = parser.parse_args(args) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4588 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4589 | # Access to a protected member _XX of a client class |
| 4590 | # pylint: disable=protected-access |
| 4591 | try: |
| 4592 | import cpplint |
| 4593 | import cpplint_chromium |
| 4594 | except ImportError: |
| 4595 | print( |
| 4596 | 'Your depot_tools is missing cpplint.py and/or cpplint_chromium.py.' |
| 4597 | ) |
| 4598 | return 1 |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4599 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4600 | # Change the current working directory before calling lint so that it |
| 4601 | # shows the correct base. |
| 4602 | previous_cwd = os.getcwd() |
| 4603 | os.chdir(settings.GetRoot()) |
| 4604 | try: |
| 4605 | cl = Changelist() |
| 4606 | files = cl.GetAffectedFiles(cl.GetCommonAncestorWithUpstream()) |
| 4607 | if not files: |
| 4608 | print('Cannot lint an empty CL') |
| 4609 | return 1 |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4610 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4611 | # Process cpplint arguments, if any. |
| 4612 | filters = presubmit_canned_checks.GetCppLintFilters(options.filter) |
| 4613 | command = ['--filter=' + ','.join(filters)] |
| 4614 | command.extend(args) |
| 4615 | command.extend(files) |
| 4616 | filenames = cpplint.ParseArguments(command) |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4617 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4618 | include_regex = re.compile(settings.GetLintRegex()) |
| 4619 | ignore_regex = re.compile(settings.GetLintIgnoreRegex()) |
| 4620 | extra_check_functions = [ |
| 4621 | cpplint_chromium.CheckPointerDeclarationWhitespace |
| 4622 | ] |
| 4623 | for filename in filenames: |
| 4624 | if not include_regex.match(filename): |
| 4625 | print('Skipping file %s' % filename) |
| 4626 | continue |
Lei Zhang | 379d1ad | 2020-07-15 19:40:06 +0000 | [diff] [blame] | 4627 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4628 | if ignore_regex.match(filename): |
| 4629 | print('Ignoring file %s' % filename) |
| 4630 | continue |
Lei Zhang | 379d1ad | 2020-07-15 19:40:06 +0000 | [diff] [blame] | 4631 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4632 | cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level, |
| 4633 | extra_check_functions) |
| 4634 | finally: |
| 4635 | os.chdir(previous_cwd) |
| 4636 | print('Total errors found: %d\n' % cpplint._cpplint_state.error_count) |
| 4637 | if cpplint._cpplint_state.error_count != 0: |
| 4638 | return 1 |
| 4639 | return 0 |
thestig@chromium.org | 44202a2 | 2014-03-11 19:22:18 +0000 | [diff] [blame] | 4640 | |
| 4641 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4642 | @metrics.collector.collect_metrics('git cl presubmit') |
mlcui | c601e36 | 2023-08-14 23:39:46 +0000 | [diff] [blame] | 4643 | @subcommand.usage('[base branch]') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4644 | def CMDpresubmit(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4645 | """Runs presubmit tests on the current changelist.""" |
| 4646 | parser.add_option('-u', |
| 4647 | '--upload', |
| 4648 | action='store_true', |
| 4649 | help='Run upload hook instead of the push hook') |
| 4650 | parser.add_option('-f', |
| 4651 | '--force', |
| 4652 | action='store_true', |
| 4653 | help='Run checks even if tree is dirty') |
| 4654 | parser.add_option( |
| 4655 | '--all', |
| 4656 | action='store_true', |
| 4657 | help='Run checks against all files, not just modified ones') |
| 4658 | parser.add_option('--files', |
| 4659 | nargs=1, |
| 4660 | help='Semicolon-separated list of files to be marked as ' |
| 4661 | 'modified when executing presubmit or post-upload hooks. ' |
| 4662 | 'fnmatch wildcards can also be used.') |
| 4663 | parser.add_option( |
| 4664 | '--parallel', |
| 4665 | action='store_true', |
| 4666 | help='Run all tests specified by input_api.RunTests in all ' |
| 4667 | 'PRESUBMIT files in parallel.') |
| 4668 | parser.add_option('--resultdb', |
| 4669 | action='store_true', |
| 4670 | help='Run presubmit checks in the ResultSink environment ' |
| 4671 | 'and send results to the ResultDB database.') |
| 4672 | parser.add_option('--realm', help='LUCI realm if reporting to ResultDB') |
| 4673 | options, args = parser.parse_args(args) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4674 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4675 | if not options.force and git_common.is_dirty_git_tree('presubmit'): |
| 4676 | print('use --force to check even if tree is dirty.') |
| 4677 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4678 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4679 | cl = Changelist() |
| 4680 | if args: |
| 4681 | base_branch = args[0] |
Bruce Dawson | eb8426e | 2022-08-05 23:58:15 +0000 | [diff] [blame] | 4682 | else: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4683 | # Default to diffing against the common ancestor of the upstream branch. |
| 4684 | base_branch = cl.GetCommonAncestorWithUpstream() |
Aaron Gable | 8076c28 | 2017-11-29 14:39:41 -0800 | [diff] [blame] | 4685 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4686 | start = time.time() |
| 4687 | try: |
| 4688 | if not 'PRESUBMIT_SKIP_NETWORK' in os.environ and cl.GetIssue(): |
| 4689 | description = cl.FetchDescription() |
| 4690 | else: |
| 4691 | description = _create_description_from_log([base_branch]) |
| 4692 | except Exception as e: |
| 4693 | print('Failed to fetch CL description - %s' % str(e)) |
| 4694 | description = _create_description_from_log([base_branch]) |
| 4695 | elapsed = time.time() - start |
| 4696 | if elapsed > 5: |
| 4697 | print('%.1f s to get CL description.' % elapsed) |
Bruce Dawson | 13acea3 | 2022-05-03 22:13:08 +0000 | [diff] [blame] | 4698 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4699 | if not base_branch: |
| 4700 | if not options.force: |
| 4701 | print('use --force to check even when not on a branch.') |
| 4702 | return 1 |
| 4703 | base_branch = 'HEAD' |
| 4704 | |
| 4705 | cl.RunHook(committing=not options.upload, |
| 4706 | may_prompt=False, |
| 4707 | verbose=options.verbose, |
| 4708 | parallel=options.parallel, |
| 4709 | upstream=base_branch, |
| 4710 | description=description, |
| 4711 | all_files=options.all, |
| 4712 | files=options.files, |
| 4713 | resultdb=options.resultdb, |
| 4714 | realm=options.realm) |
| 4715 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 4716 | |
| 4717 | |
tandrii@chromium.org | 65874e1 | 2016-03-04 12:03:02 +0000 | [diff] [blame] | 4718 | def GenerateGerritChangeId(message): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4719 | """Returns the Change ID footer value (Ixxxxxx...xxx). |
tandrii@chromium.org | 65874e1 | 2016-03-04 12:03:02 +0000 | [diff] [blame] | 4720 | |
| 4721 | Works the same way as |
| 4722 | https://gerrit-review.googlesource.com/tools/hooks/commit-msg |
| 4723 | but can be called on demand on all platforms. |
| 4724 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 4725 | The basic idea is to generate git hash of a state of the tree, original |
| 4726 | commit message, author/committer info and timestamps. |
tandrii@chromium.org | 65874e1 | 2016-03-04 12:03:02 +0000 | [diff] [blame] | 4727 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4728 | lines = [] |
| 4729 | tree_hash = RunGitSilent(['write-tree']) |
| 4730 | lines.append('tree %s' % tree_hash.strip()) |
| 4731 | code, parent = RunGitWithCode(['rev-parse', 'HEAD~0'], |
| 4732 | suppress_stderr=False) |
| 4733 | if code == 0: |
| 4734 | lines.append('parent %s' % parent.strip()) |
| 4735 | author = RunGitSilent(['var', 'GIT_AUTHOR_IDENT']) |
| 4736 | lines.append('author %s' % author.strip()) |
| 4737 | committer = RunGitSilent(['var', 'GIT_COMMITTER_IDENT']) |
| 4738 | lines.append('committer %s' % committer.strip()) |
| 4739 | lines.append('') |
| 4740 | # Note: Gerrit's commit-hook actually cleans message of some lines and |
| 4741 | # whitespace. This code is not doing this, but it clearly won't decrease |
| 4742 | # entropy. |
| 4743 | lines.append(message) |
| 4744 | change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'], |
| 4745 | stdin=('\n'.join(lines)).encode()) |
| 4746 | return 'I%s' % change_hash.strip() |
tandrii@chromium.org | 65874e1 | 2016-03-04 12:03:02 +0000 | [diff] [blame] | 4747 | |
| 4748 | |
Andrii Shyshkalov | f3a20ae | 2017-01-24 21:23:57 +0100 | [diff] [blame] | 4749 | def GetTargetRef(remote, remote_branch, target_branch): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4750 | """Computes the remote branch ref to use for the CL. |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4751 | |
| 4752 | Args: |
| 4753 | remote (str): The git remote for the CL. |
| 4754 | remote_branch (str): The git remote branch for the CL. |
| 4755 | target_branch (str): The target branch specified by the user. |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4756 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4757 | if not (remote and remote_branch): |
| 4758 | return None |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 4759 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4760 | if target_branch: |
| 4761 | # Canonicalize branch references to the equivalent local full symbolic |
| 4762 | # refs, which are then translated into the remote full symbolic refs |
| 4763 | # below. |
| 4764 | if '/' not in target_branch: |
| 4765 | remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch) |
| 4766 | else: |
| 4767 | prefix_replacements = ( |
| 4768 | ('^((refs/)?remotes/)?branch-heads/', |
| 4769 | 'refs/remotes/branch-heads/'), |
| 4770 | ('^((refs/)?remotes/)?%s/' % remote, |
| 4771 | 'refs/remotes/%s/' % remote), |
| 4772 | ('^(refs/)?heads/', 'refs/remotes/%s/' % remote), |
| 4773 | ) |
| 4774 | match = None |
| 4775 | for regex, replacement in prefix_replacements: |
| 4776 | match = re.search(regex, target_branch) |
| 4777 | if match: |
| 4778 | remote_branch = target_branch.replace( |
| 4779 | match.group(0), replacement) |
| 4780 | break |
| 4781 | if not match: |
| 4782 | # This is a branch path but not one we recognize; use as-is. |
| 4783 | remote_branch = target_branch |
| 4784 | # pylint: disable=consider-using-get |
| 4785 | elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS: |
| 4786 | # pylint: enable=consider-using-get |
| 4787 | # Handle the refs that need to land in different refs. |
| 4788 | remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch] |
bauerb@chromium.org | 27386dd | 2015-02-16 10:45:39 +0000 | [diff] [blame] | 4789 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4790 | # Create the true path to the remote branch. |
| 4791 | # Does the following translation: |
| 4792 | # * refs/remotes/origin/refs/diff/test -> refs/diff/test |
| 4793 | # * refs/remotes/origin/main -> refs/heads/main |
| 4794 | # * refs/remotes/branch-heads/test -> refs/branch-heads/test |
| 4795 | if remote_branch.startswith('refs/remotes/%s/refs/' % remote): |
| 4796 | remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '') |
| 4797 | elif remote_branch.startswith('refs/remotes/%s/' % remote): |
| 4798 | remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, |
| 4799 | 'refs/heads/') |
| 4800 | elif remote_branch.startswith('refs/remotes/branch-heads'): |
| 4801 | remote_branch = remote_branch.replace('refs/remotes/', 'refs/') |
Andrii Shyshkalov | 768f1d8 | 2016-12-08 15:10:13 +0100 | [diff] [blame] | 4802 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4803 | return remote_branch |
wittman@chromium.org | 455dc92 | 2015-01-26 20:15:50 +0000 | [diff] [blame] | 4804 | |
| 4805 | |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4806 | def cleanup_list(l): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4807 | """Fixes a list so that comma separated items are put as individual items. |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4808 | |
| 4809 | So that "--reviewers joe@c,john@c --reviewers joa@c" results in |
| 4810 | options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']). |
| 4811 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4812 | items = sum((i.split(',') for i in l), []) |
| 4813 | stripped_items = (i.strip() for i in items) |
| 4814 | return sorted(filter(None, stripped_items)) |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 4815 | |
| 4816 | |
Aaron Gable | 4db38df | 2017-11-03 14:59:07 -0700 | [diff] [blame] | 4817 | @subcommand.usage('[flags]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 4818 | @metrics.collector.collect_metrics('git cl upload') |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4819 | def CMDupload(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4820 | """Uploads the current changelist to codereview. |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 4821 | |
| 4822 | Can skip dependency patchset uploads for a branch by running: |
| 4823 | git config branch.branch_name.skip-deps-uploads True |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 4824 | To unset, run: |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 4825 | git config --unset branch.branch_name.skip-deps-uploads |
| 4826 | Can also set the above globally by using the --global flag. |
Dominic Battre | 7d1c484 | 2017-10-27 09:17:28 +0200 | [diff] [blame] | 4827 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 4828 | If the name of the checked out branch starts with "bug-" or "fix-" followed |
| 4829 | by a bug number, this bug number is automatically populated in the CL |
Dominic Battre | 7d1c484 | 2017-10-27 09:17:28 +0200 | [diff] [blame] | 4830 | description. |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 4831 | |
| 4832 | If subject contains text in square brackets or has "<text>: " prefix, such |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 4833 | text(s) is treated as Gerrit hashtags. For example, CLs with subjects: |
Nodir Turakulov | d0e2cd2 | 2017-11-15 10:22:06 -0800 | [diff] [blame] | 4834 | [git-cl] add support for hashtags |
| 4835 | Foo bar: implement foo |
| 4836 | will be hashtagged with "git-cl" and "foo-bar" respectively. |
rmistry@google.com | 78948ed | 2015-07-08 23:09:57 +0000 | [diff] [blame] | 4837 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4838 | parser.add_option('--bypass-hooks', |
| 4839 | action='store_true', |
| 4840 | dest='bypass_hooks', |
| 4841 | help='bypass upload presubmit hook') |
| 4842 | parser.add_option('--bypass-watchlists', |
| 4843 | action='store_true', |
| 4844 | dest='bypass_watchlists', |
| 4845 | help='bypass watchlists auto CC-ing reviewers') |
| 4846 | parser.add_option('-f', |
| 4847 | '--force', |
| 4848 | action='store_true', |
| 4849 | dest='force', |
| 4850 | help="force yes to questions (don't prompt)") |
| 4851 | parser.add_option('--message', |
| 4852 | '-m', |
| 4853 | dest='message', |
| 4854 | help='message for patchset') |
| 4855 | parser.add_option('-b', |
| 4856 | '--bug', |
| 4857 | help='pre-populate the bug number(s) for this issue. ' |
| 4858 | 'If several, separate with commas') |
| 4859 | parser.add_option('--message-file', |
| 4860 | dest='message_file', |
| 4861 | help='file which contains message for patchset') |
| 4862 | parser.add_option('--title', '-t', dest='title', help='title for patchset') |
| 4863 | parser.add_option('-T', |
| 4864 | '--skip-title', |
| 4865 | action='store_true', |
| 4866 | dest='skip_title', |
| 4867 | help='Use the most recent commit message as the title of ' |
| 4868 | 'the patchset') |
| 4869 | parser.add_option('-r', |
| 4870 | '--reviewers', |
| 4871 | action='append', |
| 4872 | default=[], |
| 4873 | help='reviewer email addresses') |
| 4874 | parser.add_option('--cc', |
| 4875 | action='append', |
| 4876 | default=[], |
| 4877 | help='cc email addresses') |
| 4878 | parser.add_option('--hashtag', |
| 4879 | dest='hashtags', |
| 4880 | action='append', |
| 4881 | default=[], |
| 4882 | help=('Gerrit hashtag for new CL; ' |
| 4883 | 'can be applied multiple times')) |
| 4884 | parser.add_option('-s', |
| 4885 | '--send-mail', |
| 4886 | '--send-email', |
| 4887 | dest='send_mail', |
| 4888 | action='store_true', |
| 4889 | help='send email to reviewer(s) and cc(s) immediately') |
| 4890 | parser.add_option('--target_branch', |
| 4891 | '--target-branch', |
| 4892 | metavar='TARGET', |
| 4893 | help='Apply CL to remote ref TARGET. ' + |
| 4894 | 'Default: remote branch head, or main') |
| 4895 | parser.add_option('--squash', |
| 4896 | action='store_true', |
| 4897 | help='Squash multiple commits into one') |
| 4898 | parser.add_option('--no-squash', |
| 4899 | action='store_false', |
| 4900 | dest='squash', |
| 4901 | help='Don\'t squash multiple commits into one') |
| 4902 | parser.add_option('--topic', |
| 4903 | default=None, |
| 4904 | help='Topic to specify when uploading') |
| 4905 | parser.add_option('--r-owners', |
| 4906 | dest='add_owners_to', |
| 4907 | action='store_const', |
| 4908 | const='R', |
| 4909 | help='add a set of OWNERS to R') |
| 4910 | parser.add_option('-c', |
| 4911 | '--use-commit-queue', |
| 4912 | action='store_true', |
| 4913 | default=False, |
| 4914 | help='tell the CQ to commit this patchset; ' |
| 4915 | 'implies --send-mail') |
| 4916 | parser.add_option('-d', |
| 4917 | '--cq-dry-run', |
| 4918 | action='store_true', |
| 4919 | default=False, |
| 4920 | help='Send the patchset to do a CQ dry run right after ' |
| 4921 | 'upload.') |
| 4922 | parser.add_option('--set-bot-commit', |
| 4923 | action='store_true', |
| 4924 | help=optparse.SUPPRESS_HELP) |
| 4925 | parser.add_option('--preserve-tryjobs', |
| 4926 | action='store_true', |
| 4927 | help='instruct the CQ to let tryjobs running even after ' |
| 4928 | 'new patchsets are uploaded instead of canceling ' |
| 4929 | 'prior patchset\' tryjobs') |
| 4930 | parser.add_option( |
| 4931 | '--dependencies', |
| 4932 | action='store_true', |
| 4933 | help='Uploads CLs of all the local branches that depend on ' |
| 4934 | 'the current branch') |
| 4935 | parser.add_option( |
| 4936 | '-a', |
| 4937 | '--enable-auto-submit', |
| 4938 | action='store_true', |
| 4939 | help='Sends your change to the CQ after an approval. Only ' |
| 4940 | 'works on repos that have the Auto-Submit label ' |
| 4941 | 'enabled') |
| 4942 | parser.add_option( |
| 4943 | '--parallel', |
| 4944 | action='store_true', |
| 4945 | help='Run all tests specified by input_api.RunTests in all ' |
| 4946 | 'PRESUBMIT files in parallel.') |
| 4947 | parser.add_option('--no-autocc', |
| 4948 | action='store_true', |
| 4949 | help='Disables automatic addition of CC emails') |
| 4950 | parser.add_option('--private', |
| 4951 | action='store_true', |
| 4952 | help='Set the review private. This implies --no-autocc.') |
| 4953 | parser.add_option('-R', |
| 4954 | '--retry-failed', |
| 4955 | action='store_true', |
| 4956 | help='Retry failed tryjobs from old patchset immediately ' |
| 4957 | 'after uploading new patchset. Cannot be used with ' |
| 4958 | '--use-commit-queue or --cq-dry-run.') |
| 4959 | parser.add_option('--fixed', |
| 4960 | '-x', |
| 4961 | help='List of bugs that will be commented on and marked ' |
| 4962 | 'fixed (pre-populates "Fixed:" tag). Same format as ' |
| 4963 | '-b option / "Bug:" tag. If fixing several issues, ' |
| 4964 | 'separate with commas.') |
| 4965 | parser.add_option('--edit-description', |
| 4966 | action='store_true', |
| 4967 | default=False, |
| 4968 | help='Modify description before upload. Cannot be used ' |
| 4969 | 'with --force. It is a noop when --no-squash is set ' |
| 4970 | 'or a new commit is created.') |
| 4971 | parser.add_option('--git-completion-helper', |
| 4972 | action="store_true", |
| 4973 | help=optparse.SUPPRESS_HELP) |
| 4974 | parser.add_option('-o', |
| 4975 | '--push-options', |
| 4976 | action='append', |
| 4977 | default=[], |
| 4978 | help='Transmit the given string to the server when ' |
| 4979 | 'performing git push (pass-through). See git-push ' |
| 4980 | 'documentation for more details.') |
| 4981 | parser.add_option('--no-add-changeid', |
| 4982 | action='store_true', |
| 4983 | dest='no_add_changeid', |
| 4984 | help='Do not add change-ids to messages.') |
| 4985 | parser.add_option('--cherry-pick-stacked', |
| 4986 | '--cp', |
| 4987 | dest='cherry_pick_stacked', |
| 4988 | action='store_true', |
| 4989 | help='If parent branch has un-uploaded updates, ' |
| 4990 | 'automatically skip parent branches and just upload ' |
| 4991 | 'the current branch cherry-pick on its parent\'s last ' |
| 4992 | 'uploaded commit. Allows users to skip the potential ' |
| 4993 | 'interactive confirmation step.') |
| 4994 | # TODO(b/265929888): Add --wip option of --cl-status option. |
Sergiy Byelozyorov | 1aa405f | 2018-09-18 17:38:43 +0000 | [diff] [blame] | 4995 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4996 | orig_args = args |
| 4997 | (options, args) = parser.parse_args(args) |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 4998 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 4999 | if options.git_completion_helper: |
| 5000 | print(' '.join(opt.get_opt_string() for opt in parser.option_list |
| 5001 | if opt.help != optparse.SUPPRESS_HELP)) |
| 5002 | return |
Ng Zhi An | cdaf0be | 2020-05-27 20:57:28 +0000 | [diff] [blame] | 5003 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5004 | # TODO(crbug.com/1475405): Warn users if the project uses submodules and |
| 5005 | # they have fsmonitor enabled. |
| 5006 | if os.path.isfile('.gitmodules'): |
| 5007 | git_common.warn_submodule() |
Aravind Vasudevan | b816418 | 2023-08-25 21:49:12 +0000 | [diff] [blame] | 5008 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5009 | if git_common.is_dirty_git_tree('upload'): |
| 5010 | return 1 |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 5011 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5012 | options.reviewers = cleanup_list(options.reviewers) |
| 5013 | options.cc = cleanup_list(options.cc) |
maruel@chromium.org | eb52a5c | 2013-04-10 23:17:09 +0000 | [diff] [blame] | 5014 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5015 | if options.edit_description and options.force: |
| 5016 | parser.error('Only one of --force and --edit-description allowed') |
Josip | e827b0f | 2020-01-30 00:07:20 +0000 | [diff] [blame] | 5017 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5018 | if options.message_file: |
| 5019 | if options.message: |
| 5020 | parser.error('Only one of --message and --message-file allowed.') |
| 5021 | options.message = gclient_utils.FileRead(options.message_file) |
tandrii | b80458a | 2016-06-23 12:20:07 -0700 | [diff] [blame] | 5022 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5023 | if ([options.cq_dry_run, options.use_commit_queue, options.retry_failed |
| 5024 | ].count(True) > 1): |
| 5025 | parser.error('Only one of --use-commit-queue, --cq-dry-run or ' |
| 5026 | '--retry-failed is allowed.') |
tandrii | 4d0545a | 2016-07-06 03:56:49 -0700 | [diff] [blame] | 5027 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5028 | if options.skip_title and options.title: |
| 5029 | parser.error('Only one of --title and --skip-title allowed.') |
Mario Bianucci | cebfb4e | 2020-07-22 23:08:16 +0000 | [diff] [blame] | 5030 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5031 | if options.use_commit_queue: |
| 5032 | options.send_mail = True |
Aaron Gable | edbc413 | 2017-09-11 13:22:28 -0700 | [diff] [blame] | 5033 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5034 | if options.squash is None: |
| 5035 | # Load default for user, repo, squash=true, in this order. |
| 5036 | options.squash = settings.GetSquashGerritUploads() |
Edward Lesmes | 0dd5482 | 2020-03-26 18:24:25 +0000 | [diff] [blame] | 5037 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5038 | cl = Changelist(branchref=options.target_branch) |
Joanna Wang | 5051ffe | 2023-03-01 22:24:07 +0000 | [diff] [blame] | 5039 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5040 | # Warm change details cache now to avoid RPCs later, reducing latency for |
| 5041 | # developers. |
| 5042 | if cl.GetIssue(): |
| 5043 | cl._GetChangeDetail([ |
| 5044 | 'DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS' |
| 5045 | ]) |
Joanna Wang | 5051ffe | 2023-03-01 22:24:07 +0000 | [diff] [blame] | 5046 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5047 | if options.retry_failed and not cl.GetIssue(): |
| 5048 | print('No previous patchsets, so --retry-failed has no effect.') |
| 5049 | options.retry_failed = False |
Joanna Wang | 5051ffe | 2023-03-01 22:24:07 +0000 | [diff] [blame] | 5050 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5051 | disable_dogfood_stacked_changes = os.environ.get( |
| 5052 | DOGFOOD_STACKED_CHANGES_VAR) == '0' |
| 5053 | dogfood_stacked_changes = os.environ.get(DOGFOOD_STACKED_CHANGES_VAR) == '1' |
Joanna Wang | 5051ffe | 2023-03-01 22:24:07 +0000 | [diff] [blame] | 5054 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5055 | # Only print message for folks who don't have DOGFOOD_STACKED_CHANGES set |
| 5056 | # to an expected value. |
| 5057 | if (options.squash and not dogfood_stacked_changes |
| 5058 | and not disable_dogfood_stacked_changes): |
| 5059 | print( |
| 5060 | 'This repo has been enrolled in the stacked changes dogfood.\n' |
| 5061 | '`git cl upload` now uploads the current branch and all upstream ' |
| 5062 | 'branches that have un-uploaded updates.\n' |
| 5063 | 'Patches can now be reapplied with --force:\n' |
| 5064 | '`git cl patch --reapply --force`.\n' |
| 5065 | 'Googlers may visit go/stacked-changes-dogfood for more information.\n' |
| 5066 | '\n' |
| 5067 | 'Depot Tools no longer sets new uploads to "WIP". Please update the\n' |
| 5068 | '"Set new changes to "work in progress" by default" checkbox at\n' |
| 5069 | 'https://<host>-review.googlesource.com/settings/\n' |
| 5070 | '\n' |
| 5071 | 'To opt-out use `export DOGFOOD_STACKED_CHANGES=0`.\n' |
| 5072 | 'To hide this message use `export DOGFOOD_STACKED_CHANGES=1`.\n' |
| 5073 | 'File bugs at https://bit.ly/3Y6opoI\n') |
Joanna Wang | 4786a41 | 2023-05-16 18:23:08 +0000 | [diff] [blame] | 5074 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5075 | if options.squash and not disable_dogfood_stacked_changes: |
| 5076 | if options.dependencies: |
| 5077 | parser.error( |
| 5078 | '--dependencies is not available for this dogfood workflow.') |
Joanna Wang | 5051ffe | 2023-03-01 22:24:07 +0000 | [diff] [blame] | 5079 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5080 | if options.cherry_pick_stacked: |
| 5081 | try: |
| 5082 | orig_args.remove('--cherry-pick-stacked') |
| 5083 | except ValueError: |
| 5084 | orig_args.remove('--cp') |
| 5085 | UploadAllSquashed(options, orig_args) |
| 5086 | return 0 |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5087 | |
Joanna Wang | d75fc88 | 2023-03-01 21:53:34 +0000 | [diff] [blame] | 5088 | if options.cherry_pick_stacked: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5089 | parser.error( |
| 5090 | '--cherry-pick-stacked is not available for this workflow.') |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5091 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5092 | # cl.GetMostRecentPatchset uses cached information, and can return the last |
| 5093 | # patchset before upload. Calling it here makes it clear that it's the |
| 5094 | # last patchset before upload. Note that GetMostRecentPatchset will fail |
| 5095 | # if no CL has been uploaded yet. |
| 5096 | if options.retry_failed: |
| 5097 | patchset = cl.GetMostRecentPatchset() |
Joanna Wang | d75fc88 | 2023-03-01 21:53:34 +0000 | [diff] [blame] | 5098 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5099 | ret = cl.CMDUpload(options, args, orig_args) |
Andrii Shyshkalov | 9f27443 | 2018-10-15 16:40:23 +0000 | [diff] [blame] | 5100 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5101 | if options.retry_failed: |
| 5102 | if ret != 0: |
| 5103 | print('Upload failed, so --retry-failed has no effect.') |
| 5104 | return ret |
| 5105 | builds, _ = _fetch_latest_builds(cl, |
| 5106 | DEFAULT_BUILDBUCKET_HOST, |
| 5107 | latest_patchset=patchset) |
| 5108 | jobs = _filter_failed_for_retry(builds) |
| 5109 | if len(jobs) == 0: |
| 5110 | print('No failed tryjobs, so --retry-failed has no effect.') |
| 5111 | return ret |
| 5112 | _trigger_tryjobs(cl, jobs, options, patchset + 1) |
Quinten Yearsley | a19d353 | 2019-09-30 21:54:39 +0000 | [diff] [blame] | 5113 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5114 | return ret |
ukai@chromium.org | e807781 | 2012-02-03 03:41:46 +0000 | [diff] [blame] | 5115 | |
| 5116 | |
Daniel Cheng | 66d0f15 | 2023-08-29 23:21:58 +0000 | [diff] [blame] | 5117 | def UploadAllSquashed(options: optparse.Values, |
| 5118 | orig_args: Sequence[str]) -> int: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5119 | """Uploads the current and upstream branches (if necessary).""" |
| 5120 | cls, cherry_pick_current = _UploadAllPrecheck(options, orig_args) |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5121 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5122 | # Create commits. |
| 5123 | uploads_by_cl: List[Tuple[Changelist, _NewUpload]] = [] |
| 5124 | if cherry_pick_current: |
| 5125 | parent = cls[1]._GitGetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY) |
| 5126 | new_upload = cls[0].PrepareCherryPickSquashedCommit(options, parent) |
| 5127 | uploads_by_cl.append((cls[0], new_upload)) |
| 5128 | else: |
| 5129 | ordered_cls = list(reversed(cls)) |
Joanna Wang | c710e2d | 2023-01-25 14:53:22 +0000 | [diff] [blame] | 5130 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5131 | cl = ordered_cls[0] |
| 5132 | # We can only support external changes when we're only uploading one |
| 5133 | # branch. |
| 5134 | parent = cl._UpdateWithExternalChanges() if len( |
| 5135 | ordered_cls) == 1 else None |
| 5136 | orig_parent = None |
| 5137 | if parent is None: |
| 5138 | origin = '.' |
| 5139 | branch = cl.GetBranch() |
Joanna Wang | 74c53b6 | 2023-03-01 22:00:22 +0000 | [diff] [blame] | 5140 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5141 | while origin == '.': |
| 5142 | # Search for cl's closest ancestor with a gerrit hash. |
| 5143 | origin, upstream_branch_ref = Changelist.FetchUpstreamTuple( |
| 5144 | branch) |
| 5145 | if origin == '.': |
| 5146 | upstream_branch = scm.GIT.ShortBranchName( |
| 5147 | upstream_branch_ref) |
Joanna Wang | 7603f04 | 2023-03-01 22:17:36 +0000 | [diff] [blame] | 5148 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5149 | # Support the `git merge` and `git pull` workflow. |
| 5150 | if upstream_branch in ['master', 'main']: |
| 5151 | parent = cl.GetCommonAncestorWithUpstream() |
| 5152 | else: |
| 5153 | orig_parent = scm.GIT.GetBranchConfig( |
| 5154 | settings.GetRoot(), upstream_branch, |
| 5155 | LAST_UPLOAD_HASH_CONFIG_KEY) |
| 5156 | parent = scm.GIT.GetBranchConfig( |
| 5157 | settings.GetRoot(), upstream_branch, |
| 5158 | GERRIT_SQUASH_HASH_CONFIG_KEY) |
| 5159 | if parent: |
| 5160 | break |
| 5161 | branch = upstream_branch |
| 5162 | else: |
| 5163 | # Either the root of the tree is the cl's direct parent and the |
| 5164 | # while loop above only found empty branches between cl and the |
| 5165 | # root of the tree. |
| 5166 | parent = cl.GetCommonAncestorWithUpstream() |
Joanna Wang | 6215dd0 | 2023-02-07 15:58:03 +0000 | [diff] [blame] | 5167 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5168 | if orig_parent is None: |
| 5169 | orig_parent = parent |
| 5170 | for i, cl in enumerate(ordered_cls): |
| 5171 | # If we're in the middle of the stack, set end_commit to |
| 5172 | # downstream's direct ancestor. |
| 5173 | if i + 1 < len(ordered_cls): |
| 5174 | child_base_commit = ordered_cls[ |
| 5175 | i + 1].GetCommonAncestorWithUpstream() |
| 5176 | else: |
| 5177 | child_base_commit = None |
| 5178 | new_upload = cl.PrepareSquashedCommit(options, |
| 5179 | parent, |
| 5180 | orig_parent, |
| 5181 | end_commit=child_base_commit) |
| 5182 | uploads_by_cl.append((cl, new_upload)) |
| 5183 | parent = new_upload.commit_to_push |
| 5184 | orig_parent = child_base_commit |
Joanna Wang | c710e2d | 2023-01-25 14:53:22 +0000 | [diff] [blame] | 5185 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5186 | # Create refspec options |
| 5187 | cl, new_upload = uploads_by_cl[-1] |
| 5188 | refspec_opts = cl._GetRefSpecOptions( |
| 5189 | options, |
| 5190 | new_upload.change_desc, |
| 5191 | multi_change_upload=len(uploads_by_cl) > 1, |
| 5192 | dogfood_path=True) |
| 5193 | refspec_suffix = '' |
| 5194 | if refspec_opts: |
| 5195 | refspec_suffix = '%' + ','.join(refspec_opts) |
| 5196 | assert ' ' not in refspec_suffix, ( |
| 5197 | 'spaces not allowed in refspec: "%s"' % refspec_suffix) |
Joanna Wang | c710e2d | 2023-01-25 14:53:22 +0000 | [diff] [blame] | 5198 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5199 | remote, remote_branch = cl.GetRemoteBranch() |
| 5200 | branch = GetTargetRef(remote, remote_branch, options.target_branch) |
| 5201 | refspec = '%s:refs/for/%s%s' % (new_upload.commit_to_push, branch, |
| 5202 | refspec_suffix) |
Joanna Wang | c710e2d | 2023-01-25 14:53:22 +0000 | [diff] [blame] | 5203 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5204 | # Git push |
| 5205 | git_push_metadata = { |
| 5206 | 'gerrit_host': |
| 5207 | cl.GetGerritHost(), |
| 5208 | 'title': |
| 5209 | options.title or '<untitled>', |
| 5210 | 'change_id': |
| 5211 | git_footers.get_footer_change_id(new_upload.change_desc.description), |
| 5212 | 'description': |
| 5213 | new_upload.change_desc.description, |
| 5214 | } |
| 5215 | push_stdout = cl._RunGitPushWithTraces(refspec, refspec_opts, |
| 5216 | git_push_metadata, |
| 5217 | options.push_options) |
Joanna Wang | c710e2d | 2023-01-25 14:53:22 +0000 | [diff] [blame] | 5218 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5219 | # Post push updates |
| 5220 | regex = re.compile(r'remote:\s+https?://[\w\-\.\+\/#]*/(\d+)\s.*') |
| 5221 | change_numbers = [ |
| 5222 | m.group(1) for m in map(regex.match, push_stdout.splitlines()) if m |
| 5223 | ] |
Joanna Wang | c710e2d | 2023-01-25 14:53:22 +0000 | [diff] [blame] | 5224 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5225 | for i, (cl, new_upload) in enumerate(uploads_by_cl): |
| 5226 | cl.PostUploadUpdates(options, new_upload, change_numbers[i]) |
Joanna Wang | c710e2d | 2023-01-25 14:53:22 +0000 | [diff] [blame] | 5227 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5228 | return 0 |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5229 | |
| 5230 | |
| 5231 | def _UploadAllPrecheck(options, orig_args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5232 | # type: (optparse.Values, Sequence[str]) -> Tuple[Sequence[Changelist], |
| 5233 | # bool] |
| 5234 | """Checks the state of the tree and gives the user uploading options |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5235 | |
| 5236 | Returns: A tuple of the ordered list of changes that have new commits |
| 5237 | since their last upload and a boolean of whether the user wants to |
| 5238 | cherry-pick and upload the current branch instead of uploading all cls. |
| 5239 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5240 | cl = Changelist() |
| 5241 | if cl.GetBranch() is None: |
| 5242 | DieWithError('Can\'t upload from detached HEAD state. Get on a branch!') |
Joanna Wang | 6b98cdc | 2023-02-16 00:37:20 +0000 | [diff] [blame] | 5243 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5244 | branch_ref = None |
| 5245 | cls = [] |
| 5246 | must_upload_upstream = False |
| 5247 | first_pass = True |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5248 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5249 | Changelist._GerritCommitMsgHookCheck(offer_removal=not options.force) |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5250 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5251 | while True: |
| 5252 | if len(cls) > _MAX_STACKED_BRANCHES_UPLOAD: |
| 5253 | DieWithError( |
| 5254 | 'More than %s branches in the stack have not been uploaded.\n' |
| 5255 | 'Are your branches in a misconfigured state?\n' |
| 5256 | 'If not, please upload some upstream changes first.' % |
| 5257 | (_MAX_STACKED_BRANCHES_UPLOAD)) |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5258 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5259 | cl = Changelist(branchref=branch_ref) |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5260 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5261 | # Only add CL if it has anything to commit. |
| 5262 | base_commit = cl.GetCommonAncestorWithUpstream() |
| 5263 | end_commit = RunGit(['rev-parse', cl.GetBranchRef()]).strip() |
Joanna Wang | 6215dd0 | 2023-02-07 15:58:03 +0000 | [diff] [blame] | 5264 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5265 | commit_summary = _GetCommitCountSummary(base_commit, end_commit) |
| 5266 | if commit_summary: |
| 5267 | cls.append(cl) |
| 5268 | if (not first_pass and |
| 5269 | cl._GitGetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY) |
| 5270 | is None): |
| 5271 | # We are mid-stack and the user must upload their upstream |
| 5272 | # branches. |
| 5273 | must_upload_upstream = True |
| 5274 | print(f'Found change with {commit_summary}...') |
| 5275 | elif first_pass: # The current branch has nothing to commit. Exit. |
| 5276 | DieWithError('Branch %s has nothing to commit' % cl.GetBranch()) |
| 5277 | # Else: A mid-stack branch has nothing to commit. We do not add it to |
| 5278 | # cls. |
| 5279 | first_pass = False |
Joanna Wang | 6215dd0 | 2023-02-07 15:58:03 +0000 | [diff] [blame] | 5280 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5281 | # Cases below determine if we should continue to traverse up the tree. |
| 5282 | origin, upstream_branch_ref = Changelist.FetchUpstreamTuple( |
| 5283 | cl.GetBranch()) |
| 5284 | branch_ref = upstream_branch_ref # set branch for next run. |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5285 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5286 | upstream_branch = scm.GIT.ShortBranchName(upstream_branch_ref) |
| 5287 | upstream_last_upload = scm.GIT.GetBranchConfig( |
| 5288 | settings.GetRoot(), upstream_branch, LAST_UPLOAD_HASH_CONFIG_KEY) |
Joanna Wang | 6215dd0 | 2023-02-07 15:58:03 +0000 | [diff] [blame] | 5289 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5290 | # Case 1: We've reached the beginning of the tree. |
| 5291 | if origin != '.': |
| 5292 | break |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5293 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5294 | # Case 2: If any upstream branches have never been uploaded, |
| 5295 | # the user MUST upload them unless they are empty. Continue to |
| 5296 | # next loop to add upstream if it is not empty. |
| 5297 | if not upstream_last_upload: |
| 5298 | continue |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5299 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5300 | # Case 3: If upstream's last_upload == cl.base_commit we do |
| 5301 | # not need to upload any more upstreams from this point on. |
| 5302 | # (Even if there may be diverged branches higher up the tree) |
| 5303 | if base_commit == upstream_last_upload: |
| 5304 | break |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5305 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5306 | # Case 4: If upstream's last_upload < cl.base_commit we are |
| 5307 | # uploading cl and upstream_cl. |
| 5308 | # Continue up the tree to check other branch relations. |
| 5309 | if scm.GIT.IsAncestor(upstream_last_upload, base_commit): |
| 5310 | continue |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5311 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5312 | # Case 5: If cl.base_commit < upstream's last_upload the user |
| 5313 | # must rebase before uploading. |
| 5314 | if scm.GIT.IsAncestor(base_commit, upstream_last_upload): |
| 5315 | DieWithError( |
| 5316 | 'At least one branch in the stack has diverged from its upstream ' |
| 5317 | 'branch and does not contain its upstream\'s last upload.\n' |
| 5318 | 'Please rebase the stack with `git rebase-update` before uploading.' |
| 5319 | ) |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5320 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5321 | # The tree went through a rebase. LAST_UPLOAD_HASH_CONFIG_KEY no longer |
| 5322 | # has any relation to commits in the tree. Continue up the tree until we |
| 5323 | # hit the root. |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5324 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5325 | # We assume all cls in the stack have the same auth requirements and only |
| 5326 | # check this once. |
| 5327 | cls[0].EnsureAuthenticated(force=options.force) |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5328 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5329 | cherry_pick = False |
| 5330 | if len(cls) > 1: |
| 5331 | opt_message = '' |
| 5332 | branches = ', '.join([cl.branch for cl in cls]) |
| 5333 | if len(orig_args): |
| 5334 | opt_message = ('options %s will be used for all uploads.\n' % |
| 5335 | orig_args) |
| 5336 | if must_upload_upstream: |
| 5337 | msg = ('At least one parent branch in `%s` has never been uploaded ' |
| 5338 | 'and must be uploaded before/with `%s`.\n' % |
| 5339 | (branches, cls[1].branch)) |
| 5340 | if options.cherry_pick_stacked: |
| 5341 | DieWithError(msg) |
| 5342 | if not options.force: |
| 5343 | confirm_or_exit('\n' + opt_message + msg) |
| 5344 | else: |
| 5345 | if options.cherry_pick_stacked: |
| 5346 | print('cherry-picking `%s` on %s\'s last upload' % |
| 5347 | (cls[0].branch, cls[1].branch)) |
| 5348 | cherry_pick = True |
| 5349 | elif not options.force: |
| 5350 | answer = gclient_utils.AskForData( |
| 5351 | '\n' + opt_message + |
| 5352 | 'Press enter to update branches %s.\nOr type `n` to upload only ' |
| 5353 | '`%s` cherry-picked on %s\'s last upload:' % |
| 5354 | (branches, cls[0].branch, cls[1].branch)) |
| 5355 | if answer.lower() == 'n': |
| 5356 | cherry_pick = True |
| 5357 | return cls, cherry_pick |
Joanna Wang | 18de1f6 | 2023-01-21 01:24:24 +0000 | [diff] [blame] | 5358 | |
| 5359 | |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5360 | @subcommand.usage('--description=<description file>') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5361 | @metrics.collector.collect_metrics('git cl split') |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5362 | def CMDsplit(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5363 | """Splits a branch into smaller branches and uploads CLs. |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5364 | |
| 5365 | Creates a branch and uploads a CL for each group of files modified in the |
| 5366 | current branch that share a common OWNERS file. In the CL description and |
Edward Lemur | ac5c55f | 2020-02-29 00:17:16 +0000 | [diff] [blame] | 5367 | comment, the string '$directory', is replaced with the directory containing |
| 5368 | the shared OWNERS file. |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5369 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5370 | parser.add_option('-d', |
| 5371 | '--description', |
| 5372 | dest='description_file', |
| 5373 | help='A text file containing a CL description in which ' |
| 5374 | '$directory will be replaced by each CL\'s directory.') |
| 5375 | parser.add_option('-c', |
| 5376 | '--comment', |
| 5377 | dest='comment_file', |
| 5378 | help='A text file containing a CL comment.') |
| 5379 | parser.add_option( |
| 5380 | '-n', |
| 5381 | '--dry-run', |
| 5382 | dest='dry_run', |
| 5383 | action='store_true', |
| 5384 | default=False, |
| 5385 | help='List the files and reviewers for each CL that would ' |
| 5386 | 'be created, but don\'t create branches or CLs.') |
| 5387 | parser.add_option('--cq-dry-run', |
| 5388 | action='store_true', |
| 5389 | help='If set, will do a cq dry run for each uploaded CL. ' |
| 5390 | 'Please be careful when doing this; more than ~10 CLs ' |
| 5391 | 'has the potential to overload our build ' |
| 5392 | 'infrastructure. Try to upload these not during high ' |
| 5393 | 'load times (usually 11-3 Mountain View time). Email ' |
| 5394 | 'infra-dev@chromium.org with any questions.') |
| 5395 | parser.add_option( |
| 5396 | '-a', |
| 5397 | '--enable-auto-submit', |
| 5398 | action='store_true', |
| 5399 | dest='enable_auto_submit', |
| 5400 | default=True, |
| 5401 | help='Sends your change to the CQ after an approval. Only ' |
| 5402 | 'works on repos that have the Auto-Submit label ' |
| 5403 | 'enabled') |
| 5404 | parser.add_option( |
| 5405 | '--disable-auto-submit', |
| 5406 | action='store_false', |
| 5407 | dest='enable_auto_submit', |
| 5408 | help='Disables automatic sending of the changes to the CQ ' |
| 5409 | 'after approval. Note that auto-submit only works for ' |
| 5410 | 'repos that have the Auto-Submit label enabled.') |
| 5411 | parser.add_option('--max-depth', |
| 5412 | type='int', |
| 5413 | default=0, |
| 5414 | help='The max depth to look for OWNERS files. Useful for ' |
| 5415 | 'controlling the granularity of the split CLs, e.g. ' |
| 5416 | '--max-depth=1 will only split by top-level ' |
| 5417 | 'directory. Specifying a value less than 1 means no ' |
| 5418 | 'limit on max depth.') |
| 5419 | parser.add_option('--topic', |
| 5420 | default=None, |
| 5421 | help='Topic to specify when uploading') |
| 5422 | options, _ = parser.parse_args(args) |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5423 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5424 | if not options.description_file: |
| 5425 | parser.error('No --description flag specified.') |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5426 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5427 | def WrappedCMDupload(args): |
| 5428 | return CMDupload(OptionParser(), args) |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5429 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5430 | return split_cl.SplitCl(options.description_file, options.comment_file, |
| 5431 | Changelist, WrappedCMDupload, options.dry_run, |
| 5432 | options.cq_dry_run, options.enable_auto_submit, |
| 5433 | options.max_depth, options.topic, |
| 5434 | settings.GetRoot()) |
Francois Doray | d42c681 | 2017-05-30 15:10:20 -0400 | [diff] [blame] | 5435 | |
| 5436 | |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5437 | @subcommand.usage('DEPRECATED') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5438 | @metrics.collector.collect_metrics('git cl commit') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5439 | def CMDdcommit(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5440 | """DEPRECATED: Used to commit the current changelist via git-svn.""" |
| 5441 | message = ('git-cl no longer supports committing to SVN repositories via ' |
| 5442 | 'git-svn. You probably want to use `git cl land` instead.') |
| 5443 | print(message) |
| 5444 | return 1 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5445 | |
| 5446 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 5447 | @subcommand.usage('[upstream branch to apply against]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5448 | @metrics.collector.collect_metrics('git cl land') |
pgervais@chromium.org | cee6dc4 | 2014-05-07 17:04:03 +0000 | [diff] [blame] | 5449 | def CMDland(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5450 | """Commits the current changelist via git. |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5451 | |
| 5452 | In case of Gerrit, uses Gerrit REST api to "submit" the issue, which pushes |
| 5453 | upstream and closes the issue automatically and atomically. |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5454 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5455 | parser.add_option('--bypass-hooks', |
| 5456 | action='store_true', |
| 5457 | dest='bypass_hooks', |
| 5458 | help='bypass upload presubmit hook') |
| 5459 | parser.add_option('-f', |
| 5460 | '--force', |
| 5461 | action='store_true', |
| 5462 | dest='force', |
| 5463 | help="force yes to questions (don't prompt)") |
| 5464 | parser.add_option( |
| 5465 | '--parallel', |
| 5466 | action='store_true', |
| 5467 | help='Run all tests specified by input_api.RunTests in all ' |
| 5468 | 'PRESUBMIT files in parallel.') |
| 5469 | parser.add_option('--resultdb', |
| 5470 | action='store_true', |
| 5471 | help='Run presubmit checks in the ResultSink environment ' |
| 5472 | 'and send results to the ResultDB database.') |
| 5473 | parser.add_option('--realm', help='LUCI realm if reporting to ResultDB') |
| 5474 | (options, args) = parser.parse_args(args) |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5475 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5476 | cl = Changelist() |
Aaron Gable | 1bc7bfe | 2016-12-19 10:08:14 -0800 | [diff] [blame] | 5477 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5478 | if not cl.GetIssue(): |
| 5479 | DieWithError('You must upload the change first to Gerrit.\n' |
| 5480 | ' If you would rather have `git cl land` upload ' |
| 5481 | 'automatically for you, see http://crbug.com/642759') |
| 5482 | return cl.CMDLand(options.force, options.bypass_hooks, options.verbose, |
| 5483 | options.parallel, options.resultdb, options.realm) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5484 | |
| 5485 | |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 5486 | @subcommand.usage('<patch url or issue id or issue url>') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5487 | @metrics.collector.collect_metrics('git cl patch') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5488 | def CMDpatch(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5489 | """Applies (cherry-picks) a Gerrit changelist locally.""" |
| 5490 | parser.add_option('-b', |
| 5491 | dest='newbranch', |
| 5492 | help='create a new branch off trunk for the patch') |
| 5493 | parser.add_option('-f', |
| 5494 | '--force', |
| 5495 | action='store_true', |
| 5496 | help='overwrite state on the current or chosen branch') |
| 5497 | parser.add_option('-n', |
| 5498 | '--no-commit', |
| 5499 | action='store_true', |
| 5500 | dest='nocommit', |
| 5501 | help='don\'t commit after patch applies.') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5502 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5503 | group = optparse.OptionGroup( |
| 5504 | parser, |
| 5505 | 'Options for continuing work on the current issue uploaded from a ' |
| 5506 | 'different clone (e.g. different machine). Must be used independently ' |
| 5507 | 'from the other options. No issue number should be specified, and the ' |
| 5508 | 'branch must have an issue number associated with it') |
| 5509 | group.add_option('--reapply', |
| 5510 | action='store_true', |
| 5511 | dest='reapply', |
| 5512 | help='Reset the branch and reapply the issue.\n' |
| 5513 | 'CAUTION: This will undo any local changes in this ' |
| 5514 | 'branch') |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5515 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5516 | group.add_option('--pull', |
| 5517 | action='store_true', |
| 5518 | dest='pull', |
| 5519 | help='Performs a pull before reapplying.') |
| 5520 | parser.add_option_group(group) |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5521 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5522 | (options, args) = parser.parse_args(args) |
vadimsh@chromium.org | cf6a5d2 | 2015-04-09 22:02:00 +0000 | [diff] [blame] | 5523 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5524 | if options.reapply: |
| 5525 | if options.newbranch: |
| 5526 | parser.error('--reapply works on the current branch only.') |
| 5527 | if len(args) > 0: |
| 5528 | parser.error('--reapply implies no additional arguments.') |
| 5529 | |
| 5530 | cl = Changelist() |
| 5531 | if not cl.GetIssue(): |
| 5532 | parser.error('Current branch must have an associated issue.') |
| 5533 | |
| 5534 | upstream = cl.GetUpstreamBranch() |
| 5535 | if upstream is None: |
| 5536 | parser.error('No upstream branch specified. Cannot reset branch.') |
| 5537 | |
| 5538 | RunGit(['reset', '--hard', upstream]) |
| 5539 | if options.pull: |
| 5540 | RunGit(['pull']) |
| 5541 | |
| 5542 | target_issue_arg = ParseIssueNumberArgument(cl.GetIssue()) |
| 5543 | return cl.CMDPatchWithParsedIssue(target_issue_arg, options.nocommit, |
| 5544 | options.force, False) |
| 5545 | |
| 5546 | if len(args) != 1 or not args[0]: |
| 5547 | parser.error('Must specify issue number or URL.') |
| 5548 | |
| 5549 | target_issue_arg = ParseIssueNumberArgument(args[0]) |
| 5550 | if not target_issue_arg.valid: |
| 5551 | parser.error('Invalid issue ID or URL.') |
| 5552 | |
| 5553 | # We don't want uncommitted changes mixed up with the patch. |
| 5554 | if git_common.is_dirty_git_tree('patch'): |
| 5555 | return 1 |
| 5556 | |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5557 | if options.newbranch: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5558 | if options.force: |
| 5559 | RunGit(['branch', '-D', options.newbranch], |
| 5560 | stderr=subprocess2.PIPE, |
| 5561 | error_ok=True) |
| 5562 | git_new_branch.create_new_branch(options.newbranch) |
dsinclair@chromium.org | fbed656 | 2015-09-25 21:22:36 +0000 | [diff] [blame] | 5563 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5564 | cl = Changelist(codereview_host=target_issue_arg.hostname, |
| 5565 | issue=target_issue_arg.issue) |
tandrii@chromium.org | c2786d9 | 2016-05-31 19:53:50 +0000 | [diff] [blame] | 5566 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5567 | if not args[0].isdigit(): |
| 5568 | print('canonical issue/change URL: %s\n' % cl.GetIssueURL()) |
mtrofin@chromium.org | 1d88dd3 | 2016-02-04 16:25:12 +0000 | [diff] [blame] | 5569 | |
Joanna Wang | 44e9bee | 2023-01-25 21:51:42 +0000 | [diff] [blame] | 5570 | return cl.CMDPatchWithParsedIssue(target_issue_arg, options.nocommit, |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5571 | options.force, options.newbranch) |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5572 | |
| 5573 | |
jochen@chromium.org | 3ec0d54 | 2014-01-14 20:00:03 +0000 | [diff] [blame] | 5574 | def GetTreeStatus(url=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5575 | """Fetches the tree status and returns either 'open', 'closed', |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5576 | 'unknown' or 'unset'.""" |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5577 | url = url or settings.GetTreeStatusUrl(error_ok=True) |
| 5578 | if url: |
| 5579 | status = str(urllib.request.urlopen(url).read().lower()) |
| 5580 | if status.find('closed') != -1 or status == '0': |
| 5581 | return 'closed' |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 5582 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5583 | if status.find('open') != -1 or status == '1': |
| 5584 | return 'open' |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 5585 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5586 | return 'unknown' |
| 5587 | return 'unset' |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5588 | |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 5589 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5590 | def GetTreeStatusReason(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5591 | """Fetches the tree status from a json url and returns the message |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5592 | with the reason for the tree to be opened or closed.""" |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5593 | url = settings.GetTreeStatusUrl() |
| 5594 | json_url = urllib.parse.urljoin(url, '/current?format=json') |
| 5595 | connection = urllib.request.urlopen(json_url) |
| 5596 | status = json.loads(connection.read()) |
| 5597 | connection.close() |
| 5598 | return status['message'] |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5599 | |
dpranke@chromium.org | 970c522 | 2011-03-12 00:32:24 +0000 | [diff] [blame] | 5600 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5601 | @metrics.collector.collect_metrics('git cl tree') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5602 | def CMDtree(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5603 | """Shows the status of the tree.""" |
| 5604 | _, args = parser.parse_args(args) |
| 5605 | status = GetTreeStatus() |
| 5606 | if 'unset' == status: |
| 5607 | print( |
| 5608 | 'You must configure your tree status URL by running "git cl config".' |
| 5609 | ) |
| 5610 | return 2 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5611 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5612 | print('The tree is %s' % status) |
| 5613 | print() |
| 5614 | print(GetTreeStatusReason()) |
| 5615 | if status != 'open': |
| 5616 | return 1 |
| 5617 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5618 | |
| 5619 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5620 | @metrics.collector.collect_metrics('git cl try') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5621 | def CMDtry(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5622 | """Triggers tryjobs using either Buildbucket or CQ dry run.""" |
| 5623 | group = optparse.OptionGroup(parser, 'Tryjob options') |
| 5624 | group.add_option( |
| 5625 | '-b', |
| 5626 | '--bot', |
| 5627 | action='append', |
| 5628 | help=('IMPORTANT: specify ONE builder per --bot flag. Use it multiple ' |
| 5629 | 'times to specify multiple builders. ex: ' |
| 5630 | '"-b win_rel -b win_layout". See ' |
| 5631 | 'the try server waterfall for the builders name and the tests ' |
| 5632 | 'available.')) |
| 5633 | group.add_option( |
| 5634 | '-B', |
| 5635 | '--bucket', |
| 5636 | default='', |
| 5637 | help=('Buildbucket bucket to send the try requests. Format: ' |
| 5638 | '"luci.$LUCI_PROJECT.$LUCI_BUCKET". eg: "luci.chromium.try"')) |
| 5639 | group.add_option( |
| 5640 | '-r', |
| 5641 | '--revision', |
| 5642 | help='Revision to use for the tryjob; default: the revision will ' |
| 5643 | 'be determined by the try recipe that builder runs, which usually ' |
| 5644 | 'defaults to HEAD of origin/master or origin/main') |
| 5645 | group.add_option( |
| 5646 | '-c', |
| 5647 | '--clobber', |
| 5648 | action='store_true', |
| 5649 | default=False, |
| 5650 | help='Force a clobber before building; that is don\'t do an ' |
| 5651 | 'incremental build') |
| 5652 | group.add_option('--category', |
| 5653 | default='git_cl_try', |
| 5654 | help='Specify custom build category.') |
| 5655 | group.add_option( |
| 5656 | '--project', |
| 5657 | help='Override which project to use. Projects are defined ' |
| 5658 | 'in recipe to determine to which repository or directory to ' |
| 5659 | 'apply the patch') |
| 5660 | group.add_option( |
| 5661 | '-p', |
| 5662 | '--property', |
| 5663 | dest='properties', |
| 5664 | action='append', |
| 5665 | default=[], |
| 5666 | help='Specify generic properties in the form -p key1=value1 -p ' |
| 5667 | 'key2=value2 etc. The value will be treated as ' |
| 5668 | 'json if decodable, or as string otherwise. ' |
| 5669 | 'NOTE: using this may make your tryjob not usable for CQ, ' |
| 5670 | 'which will then schedule another tryjob with default properties') |
| 5671 | group.add_option('--buildbucket-host', |
| 5672 | default='cr-buildbucket.appspot.com', |
| 5673 | help='Host of buildbucket. The default host is %default.') |
| 5674 | parser.add_option_group(group) |
| 5675 | parser.add_option('-R', |
| 5676 | '--retry-failed', |
| 5677 | action='store_true', |
| 5678 | default=False, |
| 5679 | help='Retry failed jobs from the latest set of tryjobs. ' |
| 5680 | 'Not allowed with --bucket and --bot options.') |
| 5681 | parser.add_option( |
| 5682 | '-i', |
| 5683 | '--issue', |
| 5684 | type=int, |
| 5685 | help='Operate on this issue instead of the current branch\'s implicit ' |
| 5686 | 'issue.') |
| 5687 | options, args = parser.parse_args(args) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5688 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5689 | # Make sure that all properties are prop=value pairs. |
| 5690 | bad_params = [x for x in options.properties if '=' not in x] |
| 5691 | if bad_params: |
| 5692 | parser.error('Got properties with missing "=": %s' % bad_params) |
machenbach@chromium.org | 4545314 | 2015-09-15 08:45:22 +0000 | [diff] [blame] | 5693 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5694 | if args: |
| 5695 | parser.error('Unknown arguments: %s' % args) |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5696 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5697 | cl = Changelist(issue=options.issue) |
| 5698 | if not cl.GetIssue(): |
| 5699 | parser.error('Need to upload first.') |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5700 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5701 | # HACK: warm up Gerrit change detail cache to save on RPCs. |
| 5702 | cl._GetChangeDetail(['DETAILED_ACCOUNTS', 'ALL_REVISIONS']) |
Andrii Shyshkalov | eadad92 | 2017-01-26 09:38:30 +0100 | [diff] [blame] | 5703 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5704 | error_message = cl.CannotTriggerTryJobReason() |
| 5705 | if error_message: |
| 5706 | parser.error('Can\'t trigger tryjobs: %s' % error_message) |
jrobbins@chromium.org | 16f10f7 | 2014-06-24 22:14:36 +0000 | [diff] [blame] | 5707 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5708 | if options.bot: |
| 5709 | if options.retry_failed: |
| 5710 | parser.error('--bot is not compatible with --retry-failed.') |
| 5711 | if not options.bucket: |
| 5712 | parser.error('A bucket (e.g. "chromium/try") is required.') |
Edward Lemur | 4576851 | 2020-03-02 19:03:14 +0000 | [diff] [blame] | 5713 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5714 | triggered = [b for b in options.bot if 'triggered' in b] |
| 5715 | if triggered: |
| 5716 | parser.error( |
| 5717 | 'Cannot schedule builds on triggered bots: %s.\n' |
| 5718 | 'This type of bot requires an initial job from a parent (usually a ' |
| 5719 | 'builder). Schedule a job on the parent instead.\n' % triggered) |
Edward Lemur | 4576851 | 2020-03-02 19:03:14 +0000 | [diff] [blame] | 5720 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5721 | if options.bucket.startswith('.master'): |
| 5722 | parser.error('Buildbot masters are not supported.') |
Edward Lemur | 4576851 | 2020-03-02 19:03:14 +0000 | [diff] [blame] | 5723 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5724 | project, bucket = _parse_bucket(options.bucket) |
| 5725 | if project is None or bucket is None: |
| 5726 | parser.error('Invalid bucket: %s.' % options.bucket) |
| 5727 | jobs = sorted((project, bucket, bot) for bot in options.bot) |
| 5728 | elif options.retry_failed: |
| 5729 | print('Searching for failed tryjobs...') |
| 5730 | builds, patchset = _fetch_latest_builds(cl, DEFAULT_BUILDBUCKET_HOST) |
| 5731 | if options.verbose: |
| 5732 | print('Got %d builds in patchset #%d' % (len(builds), patchset)) |
| 5733 | jobs = _filter_failed_for_retry(builds) |
| 5734 | if not jobs: |
| 5735 | print('There are no failed jobs in the latest set of jobs ' |
| 5736 | '(patchset #%d), doing nothing.' % patchset) |
| 5737 | return 0 |
| 5738 | num_builders = len(jobs) |
| 5739 | if num_builders > 10: |
| 5740 | confirm_or_exit('There are %d builders with failed builds.' % |
| 5741 | num_builders, |
| 5742 | action='continue') |
| 5743 | else: |
| 5744 | if options.verbose: |
| 5745 | print('git cl try with no bots now defaults to CQ dry run.') |
| 5746 | print('Scheduling CQ dry run on: %s' % cl.GetIssueURL()) |
| 5747 | return cl.SetCQState(_CQState.DRY_RUN) |
stip@chromium.org | 43064fd | 2013-12-18 20:07:44 +0000 | [diff] [blame] | 5748 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5749 | patchset = cl.GetMostRecentPatchset() |
| 5750 | try: |
| 5751 | _trigger_tryjobs(cl, jobs, options, patchset) |
| 5752 | except BuildbucketResponseException as ex: |
| 5753 | print('ERROR: %s' % ex) |
| 5754 | return 1 |
| 5755 | return 0 |
maruel@chromium.org | 1519240 | 2012-09-06 12:38:29 +0000 | [diff] [blame] | 5756 | |
| 5757 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5758 | @metrics.collector.collect_metrics('git cl try-results') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5759 | def CMDtry_results(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5760 | """Prints info about results for tryjobs associated with the current CL.""" |
| 5761 | group = optparse.OptionGroup(parser, 'Tryjob results options') |
| 5762 | group.add_option('-p', |
| 5763 | '--patchset', |
| 5764 | type=int, |
| 5765 | help='patchset number if not current.') |
| 5766 | group.add_option('--print-master', |
| 5767 | action='store_true', |
| 5768 | help='print master name as well.') |
| 5769 | group.add_option('--color', |
| 5770 | action='store_true', |
| 5771 | default=setup_color.IS_TTY, |
| 5772 | help='force color output, useful when piping output.') |
| 5773 | group.add_option('--buildbucket-host', |
| 5774 | default='cr-buildbucket.appspot.com', |
| 5775 | help='Host of buildbucket. The default host is %default.') |
| 5776 | group.add_option( |
| 5777 | '--json', |
| 5778 | help=('Path of JSON output file to write tryjob results to,' |
| 5779 | 'or "-" for stdout.')) |
| 5780 | parser.add_option_group(group) |
| 5781 | parser.add_option( |
| 5782 | '-i', |
| 5783 | '--issue', |
| 5784 | type=int, |
| 5785 | help='Operate on this issue instead of the current branch\'s implicit ' |
| 5786 | 'issue.') |
| 5787 | options, args = parser.parse_args(args) |
| 5788 | if args: |
| 5789 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5790 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5791 | cl = Changelist(issue=options.issue) |
| 5792 | if not cl.GetIssue(): |
| 5793 | parser.error('Need to upload first.') |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5794 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5795 | patchset = options.patchset |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 5796 | if not patchset: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5797 | patchset = cl.GetMostRecentDryRunPatchset() |
| 5798 | if not patchset: |
| 5799 | parser.error('Code review host doesn\'t know about issue %s. ' |
| 5800 | 'No access to issue or wrong issue number?\n' |
| 5801 | 'Either upload first, or pass --patchset explicitly.' % |
| 5802 | cl.GetIssue()) |
tandrii | 221ab25 | 2016-10-06 08:12:04 -0700 | [diff] [blame] | 5803 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5804 | try: |
| 5805 | jobs = _fetch_tryjobs(cl, DEFAULT_BUILDBUCKET_HOST, patchset) |
| 5806 | except BuildbucketResponseException as ex: |
| 5807 | print('Buildbucket error: %s' % ex) |
| 5808 | return 1 |
| 5809 | if options.json: |
| 5810 | write_json(options.json, jobs) |
| 5811 | else: |
| 5812 | _print_tryjobs(options, jobs) |
| 5813 | return 0 |
tandrii@chromium.org | b015fac | 2016-02-26 14:52:01 +0000 | [diff] [blame] | 5814 | |
| 5815 | |
maruel@chromium.org | 0633fb4 | 2013-08-16 20:06:14 +0000 | [diff] [blame] | 5816 | @subcommand.usage('[new upstream branch]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5817 | @metrics.collector.collect_metrics('git cl upstream') |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5818 | def CMDupstream(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5819 | """Prints or sets the name of the upstream branch, if any.""" |
| 5820 | _, args = parser.parse_args(args) |
| 5821 | if len(args) > 1: |
| 5822 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5823 | |
brettw@chromium.org | ac0ba33 | 2012-08-09 23:42:53 +0000 | [diff] [blame] | 5824 | cl = Changelist() |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5825 | if args: |
| 5826 | # One arg means set upstream branch. |
| 5827 | branch = cl.GetBranch() |
| 5828 | RunGit(['branch', '--set-upstream-to', args[0], branch]) |
| 5829 | cl = Changelist() |
| 5830 | print('Upstream branch set to %s' % (cl.GetUpstreamBranch(), )) |
bauerb@chromium.org | c9cf90a | 2014-04-28 20:32:31 +0000 | [diff] [blame] | 5831 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5832 | # Clear configured merge-base, if there is one. |
| 5833 | git_common.remove_merge_base(branch) |
| 5834 | else: |
| 5835 | print(cl.GetUpstreamBranch()) |
| 5836 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 5837 | |
| 5838 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5839 | @metrics.collector.collect_metrics('git cl web') |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 5840 | def CMDweb(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5841 | """Opens the current CL in the web browser.""" |
| 5842 | parser.add_option('-p', |
| 5843 | '--print-only', |
| 5844 | action='store_true', |
| 5845 | dest='print_only', |
| 5846 | help='Only print the Gerrit URL, don\'t open it in the ' |
| 5847 | 'browser.') |
| 5848 | (options, args) = parser.parse_args(args) |
| 5849 | if args: |
| 5850 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 5851 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5852 | issue_url = Changelist().GetIssueURL() |
| 5853 | if not issue_url: |
| 5854 | print('ERROR No issue to open', file=sys.stderr) |
| 5855 | return 1 |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 5856 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5857 | if options.print_only: |
| 5858 | print(issue_url) |
| 5859 | return 0 |
| 5860 | |
| 5861 | # Redirect I/O before invoking browser to hide its output. For example, this |
| 5862 | # allows us to hide the "Created new window in existing browser session." |
| 5863 | # message from Chrome. Based on https://stackoverflow.com/a/2323563. |
| 5864 | saved_stdout = os.dup(1) |
| 5865 | saved_stderr = os.dup(2) |
| 5866 | os.close(1) |
| 5867 | os.close(2) |
| 5868 | os.open(os.devnull, os.O_RDWR) |
| 5869 | try: |
| 5870 | webbrowser.open(issue_url) |
| 5871 | finally: |
| 5872 | os.dup2(saved_stdout, 1) |
| 5873 | os.dup2(saved_stderr, 2) |
Orr Bernstein | 0b96058 | 2022-12-22 20:16:18 +0000 | [diff] [blame] | 5874 | return 0 |
| 5875 | |
thestig@chromium.org | 00858c8 | 2013-12-02 23:08:03 +0000 | [diff] [blame] | 5876 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5877 | @metrics.collector.collect_metrics('git cl set-commit') |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5878 | def CMDset_commit(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5879 | """Sets the commit bit to trigger the CQ.""" |
| 5880 | parser.add_option('-d', |
| 5881 | '--dry-run', |
| 5882 | action='store_true', |
| 5883 | help='trigger in dry run mode') |
| 5884 | parser.add_option('-c', |
| 5885 | '--clear', |
| 5886 | action='store_true', |
| 5887 | help='stop CQ run, if any') |
| 5888 | parser.add_option( |
| 5889 | '-i', |
| 5890 | '--issue', |
| 5891 | type=int, |
| 5892 | help='Operate on this issue instead of the current branch\'s implicit ' |
| 5893 | 'issue.') |
| 5894 | options, args = parser.parse_args(args) |
| 5895 | if args: |
| 5896 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
| 5897 | if [options.dry_run, options.clear].count(True) > 1: |
| 5898 | parser.error('Only one of --dry-run, and --clear are allowed.') |
tandrii@chromium.org | fa330e8 | 2016-04-13 17:09:52 +0000 | [diff] [blame] | 5899 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5900 | cl = Changelist(issue=options.issue) |
| 5901 | if not cl.GetIssue(): |
| 5902 | parser.error('Must upload the issue first.') |
Greg Guterman | be5fccd | 2021-06-14 17:58:20 +0000 | [diff] [blame] | 5903 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5904 | if options.clear: |
| 5905 | state = _CQState.NONE |
| 5906 | elif options.dry_run: |
| 5907 | state = _CQState.DRY_RUN |
| 5908 | else: |
| 5909 | state = _CQState.COMMIT |
| 5910 | cl.SetCQState(state) |
| 5911 | return 0 |
maruel@chromium.org | 27bb387 | 2011-05-30 20:33:19 +0000 | [diff] [blame] | 5912 | |
| 5913 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5914 | @metrics.collector.collect_metrics('git cl set-close') |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 5915 | def CMDset_close(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5916 | """Closes the issue.""" |
| 5917 | parser.add_option( |
| 5918 | '-i', |
| 5919 | '--issue', |
| 5920 | type=int, |
| 5921 | help='Operate on this issue instead of the current branch\'s implicit ' |
| 5922 | 'issue.') |
| 5923 | options, args = parser.parse_args(args) |
| 5924 | if args: |
| 5925 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
| 5926 | cl = Changelist(issue=options.issue) |
| 5927 | # Ensure there actually is an issue to close. |
| 5928 | if not cl.GetIssue(): |
| 5929 | DieWithError('ERROR: No issue to close.') |
| 5930 | cl.CloseIssue() |
| 5931 | return 0 |
groby@chromium.org | 411034a | 2013-02-26 15:12:01 +0000 | [diff] [blame] | 5932 | |
| 5933 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5934 | @metrics.collector.collect_metrics('git cl diff') |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5935 | def CMDdiff(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5936 | """Shows differences between local tree and last upload.""" |
| 5937 | parser.add_option('--stat', |
| 5938 | action='store_true', |
| 5939 | dest='stat', |
| 5940 | help='Generate a diffstat') |
| 5941 | options, args = parser.parse_args(args) |
| 5942 | if args: |
| 5943 | parser.error('Unrecognized args: %s' % ' '.join(args)) |
wychen@chromium.org | 46309bf | 2015-04-03 21:04:49 +0000 | [diff] [blame] | 5944 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5945 | cl = Changelist() |
| 5946 | issue = cl.GetIssue() |
| 5947 | branch = cl.GetBranch() |
| 5948 | if not issue: |
| 5949 | DieWithError('No issue found for current branch (%s)' % branch) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5950 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5951 | base = cl._GitGetBranchConfigValue(LAST_UPLOAD_HASH_CONFIG_KEY) |
| 5952 | if not base: |
| 5953 | base = cl._GitGetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY) |
| 5954 | if not base: |
| 5955 | detail = cl._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT']) |
| 5956 | revision_info = detail['revisions'][detail['current_revision']] |
| 5957 | fetch_info = revision_info['fetch']['http'] |
| 5958 | RunGit(['fetch', fetch_info['url'], fetch_info['ref']]) |
| 5959 | base = 'FETCH_HEAD' |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5960 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5961 | cmd = ['git', 'diff'] |
| 5962 | if options.stat: |
| 5963 | cmd.append('--stat') |
| 5964 | cmd.append(base) |
| 5965 | subprocess2.check_call(cmd) |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5966 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5967 | return 0 |
sbc@chromium.org | 87b9bf0 | 2013-09-26 20:35:15 +0000 | [diff] [blame] | 5968 | |
| 5969 | |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 5970 | @metrics.collector.collect_metrics('git cl owners') |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5971 | def CMDowners(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5972 | """Finds potential owners for reviewing.""" |
| 5973 | parser.add_option( |
| 5974 | '--ignore-current', |
| 5975 | action='store_true', |
| 5976 | help='Ignore the CL\'s current reviewers and start from scratch.') |
| 5977 | parser.add_option('--ignore-self', |
| 5978 | action='store_true', |
| 5979 | help='Do not consider CL\'s author as an owners.') |
| 5980 | parser.add_option('--no-color', |
| 5981 | action='store_true', |
| 5982 | help='Use this option to disable color output') |
| 5983 | parser.add_option('--batch', |
| 5984 | action='store_true', |
| 5985 | help='Do not run interactively, just suggest some') |
| 5986 | # TODO: Consider moving this to another command, since other |
| 5987 | # git-cl owners commands deal with owners for a given CL. |
| 5988 | parser.add_option('--show-all', |
| 5989 | action='store_true', |
| 5990 | help='Show all owners for a particular file') |
| 5991 | options, args = parser.parse_args(args) |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5992 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5993 | cl = Changelist() |
| 5994 | author = cl.GetAuthor() |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 5995 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 5996 | if options.show_all: |
| 5997 | if len(args) == 0: |
| 5998 | print('No files specified for --show-all. Nothing to do.') |
| 5999 | return 0 |
| 6000 | owners_by_path = cl.owners_client.BatchListOwners(args) |
| 6001 | for path in args: |
| 6002 | print('Owners for %s:' % path) |
| 6003 | print('\n'.join( |
| 6004 | ' - %s' % owner |
| 6005 | for owner in owners_by_path.get(path, ['No owners found']))) |
| 6006 | return 0 |
Yang Guo | 6e269a0 | 2019-06-26 11:17:02 +0000 | [diff] [blame] | 6007 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6008 | if args: |
| 6009 | if len(args) > 1: |
| 6010 | parser.error('Unknown args.') |
| 6011 | base_branch = args[0] |
| 6012 | else: |
| 6013 | # Default to diffing against the common ancestor of the upstream branch. |
| 6014 | base_branch = cl.GetCommonAncestorWithUpstream() |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 6015 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6016 | affected_files = cl.GetAffectedFiles(base_branch) |
Dirk Pranke | bf98088 | 2017-09-02 15:08:00 -0700 | [diff] [blame] | 6017 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6018 | if options.batch: |
| 6019 | owners = cl.owners_client.SuggestOwners(affected_files, |
| 6020 | exclude=[author]) |
| 6021 | print('\n'.join(owners)) |
| 6022 | return 0 |
Dirk Pranke | bf98088 | 2017-09-02 15:08:00 -0700 | [diff] [blame] | 6023 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6024 | return owners_finder.OwnersFinder( |
| 6025 | affected_files, |
| 6026 | author, [] if options.ignore_current else cl.GetReviewers(), |
| 6027 | cl.owners_client, |
| 6028 | disable_color=options.no_color, |
| 6029 | ignore_author=options.ignore_self).run() |
ikarienator@chromium.org | faf3fdf | 2013-09-20 02:11:48 +0000 | [diff] [blame] | 6030 | |
| 6031 | |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 6032 | def BuildGitDiffCmd(diff_type, upstream_commit, args, allow_prefix=False): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6033 | """Generates a diff command.""" |
| 6034 | # Generate diff for the current branch's changes. |
| 6035 | diff_cmd = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff'] |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 6036 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6037 | if allow_prefix: |
| 6038 | # explicitly setting --src-prefix and --dst-prefix is necessary in the |
| 6039 | # case that diff.noprefix is set in the user's git config. |
| 6040 | diff_cmd += ['--src-prefix=a/', '--dst-prefix=b/'] |
| 6041 | else: |
| 6042 | diff_cmd += ['--no-prefix'] |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 6043 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6044 | diff_cmd += [diff_type, upstream_commit, '--'] |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 6045 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6046 | if args: |
| 6047 | for arg in args: |
| 6048 | if os.path.isdir(arg) or os.path.isfile(arg): |
| 6049 | diff_cmd.append(arg) |
| 6050 | else: |
| 6051 | DieWithError('Argument "%s" is not a file or a directory' % arg) |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 6052 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6053 | return diff_cmd |
erg@chromium.org | e0a7c5d | 2015-02-23 20:30:08 +0000 | [diff] [blame] | 6054 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 6055 | |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6056 | def _RunClangFormatDiff(opts, clang_diff_files, top_dir, upstream_commit): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6057 | """Runs clang-format-diff and sets a return value if necessary.""" |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6058 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6059 | if not clang_diff_files: |
| 6060 | return 0 |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6061 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6062 | # Set to 2 to signal to CheckPatchFormatted() that this patch isn't |
| 6063 | # formatted. This is used to block during the presubmit. |
| 6064 | return_value = 0 |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6065 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6066 | # Locate the clang-format binary in the checkout |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6067 | try: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6068 | clang_format_tool = clang_format.FindClangFormatToolInChromiumTree() |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6069 | except clang_format.NotFoundError as e: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6070 | DieWithError(e) |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6071 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6072 | if opts.full or settings.GetFormatFullByDefault(): |
| 6073 | cmd = [clang_format_tool] |
| 6074 | if not opts.dry_run and not opts.diff: |
| 6075 | cmd.append('-i') |
| 6076 | if opts.dry_run: |
| 6077 | for diff_file in clang_diff_files: |
| 6078 | with open(diff_file, 'r') as myfile: |
| 6079 | code = myfile.read().replace('\r\n', '\n') |
| 6080 | stdout = RunCommand(cmd + [diff_file], cwd=top_dir) |
| 6081 | stdout = stdout.replace('\r\n', '\n') |
| 6082 | if opts.diff: |
| 6083 | sys.stdout.write(stdout) |
| 6084 | if code != stdout: |
| 6085 | return_value = 2 |
| 6086 | else: |
| 6087 | stdout = RunCommand(cmd + clang_diff_files, cwd=top_dir) |
| 6088 | if opts.diff: |
| 6089 | sys.stdout.write(stdout) |
| 6090 | else: |
| 6091 | try: |
| 6092 | script = clang_format.FindClangFormatScriptInChromiumTree( |
| 6093 | 'clang-format-diff.py') |
| 6094 | except clang_format.NotFoundError as e: |
| 6095 | DieWithError(e) |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6096 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6097 | cmd = ['vpython3', script, '-p0'] |
| 6098 | if not opts.dry_run and not opts.diff: |
| 6099 | cmd.append('-i') |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6100 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6101 | diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, clang_diff_files) |
| 6102 | diff_output = RunGit(diff_cmd).encode('utf-8') |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6103 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6104 | env = os.environ.copy() |
| 6105 | env['PATH'] = (str(os.path.dirname(clang_format_tool)) + os.pathsep + |
| 6106 | env['PATH']) |
| 6107 | stdout = RunCommand(cmd, |
| 6108 | stdin=diff_output, |
| 6109 | cwd=top_dir, |
| 6110 | env=env, |
| 6111 | shell=sys.platform.startswith('win32')) |
| 6112 | if opts.diff: |
| 6113 | sys.stdout.write(stdout) |
| 6114 | if opts.dry_run and len(stdout) > 0: |
| 6115 | return_value = 2 |
| 6116 | |
| 6117 | return return_value |
Jamie Madill | 5e96ad1 | 2020-01-13 16:08:35 +0000 | [diff] [blame] | 6118 | |
| 6119 | |
Lukasz Anforowicz | b4d3954 | 2021-09-30 23:39:25 +0000 | [diff] [blame] | 6120 | def _RunRustFmt(opts, rust_diff_files, top_dir, upstream_commit): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6121 | """Runs rustfmt. Just like _RunClangFormatDiff returns 2 to indicate that |
Lukasz Anforowicz | b4d3954 | 2021-09-30 23:39:25 +0000 | [diff] [blame] | 6122 | presubmit checks have failed (and returns 0 otherwise).""" |
| 6123 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6124 | if not rust_diff_files: |
| 6125 | return 0 |
| 6126 | |
| 6127 | # Locate the rustfmt binary. |
| 6128 | try: |
| 6129 | rustfmt_tool = rustfmt.FindRustfmtToolInChromiumTree() |
| 6130 | except rustfmt.NotFoundError as e: |
| 6131 | DieWithError(e) |
| 6132 | |
| 6133 | # TODO(crbug.com/1440869): Support formatting only the changed lines |
| 6134 | # if `opts.full or settings.GetFormatFullByDefault()` is False. |
| 6135 | cmd = [rustfmt_tool] |
| 6136 | if opts.dry_run: |
| 6137 | cmd.append('--check') |
| 6138 | cmd += rust_diff_files |
| 6139 | rustfmt_exitcode = subprocess2.call(cmd) |
| 6140 | |
| 6141 | if opts.presubmit and rustfmt_exitcode != 0: |
| 6142 | return 2 |
| 6143 | |
Lukasz Anforowicz | b4d3954 | 2021-09-30 23:39:25 +0000 | [diff] [blame] | 6144 | return 0 |
| 6145 | |
Lukasz Anforowicz | b4d3954 | 2021-09-30 23:39:25 +0000 | [diff] [blame] | 6146 | |
Olivier Robin | 0a6b544 | 2022-04-07 07:25:04 +0000 | [diff] [blame] | 6147 | def _RunSwiftFormat(opts, swift_diff_files, top_dir, upstream_commit): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6148 | """Runs swift-format. Just like _RunClangFormatDiff returns 2 to indicate |
Olivier Robin | 0a6b544 | 2022-04-07 07:25:04 +0000 | [diff] [blame] | 6149 | that presubmit checks have failed (and returns 0 otherwise).""" |
| 6150 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6151 | if not swift_diff_files: |
| 6152 | return 0 |
| 6153 | |
| 6154 | # Locate the swift-format binary. |
| 6155 | try: |
| 6156 | swift_format_tool = swift_format.FindSwiftFormatToolInChromiumTree() |
| 6157 | except swift_format.NotFoundError as e: |
| 6158 | DieWithError(e) |
| 6159 | |
| 6160 | cmd = [swift_format_tool] |
| 6161 | if opts.dry_run: |
| 6162 | cmd += ['lint', '-s'] |
| 6163 | else: |
| 6164 | cmd += ['format', '-i'] |
| 6165 | cmd += swift_diff_files |
| 6166 | swift_format_exitcode = subprocess2.call(cmd) |
| 6167 | |
| 6168 | if opts.presubmit and swift_format_exitcode != 0: |
| 6169 | return 2 |
| 6170 | |
Olivier Robin | 0a6b544 | 2022-04-07 07:25:04 +0000 | [diff] [blame] | 6171 | return 0 |
| 6172 | |
Olivier Robin | 0a6b544 | 2022-04-07 07:25:04 +0000 | [diff] [blame] | 6173 | |
jkarlin@chromium.org | 6f7fa5e | 2016-01-20 19:32:21 +0000 | [diff] [blame] | 6174 | def MatchingFileType(file_name, extensions): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6175 | """Returns True if the file name ends with one of the given extensions.""" |
| 6176 | 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] | 6177 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 6178 | |
enne@chromium.org | 555cfe4 | 2014-01-29 18:21:39 +0000 | [diff] [blame] | 6179 | @subcommand.usage('[files or directories to diff]') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 6180 | @metrics.collector.collect_metrics('git cl format') |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 6181 | def CMDformat(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6182 | """Runs auto-formatting tools (clang-format etc.) on the diff.""" |
| 6183 | CLANG_EXTS = ['.cc', '.cpp', '.h', '.m', '.mm', '.proto', '.java'] |
| 6184 | GN_EXTS = ['.gn', '.gni', '.typemap'] |
| 6185 | RUST_EXTS = ['.rs'] |
| 6186 | SWIFT_EXTS = ['.swift'] |
| 6187 | parser.add_option('--full', |
| 6188 | action='store_true', |
| 6189 | help='Reformat the full content of all touched files') |
| 6190 | parser.add_option('--upstream', help='Branch to check against') |
| 6191 | parser.add_option('--dry-run', |
| 6192 | action='store_true', |
| 6193 | help='Don\'t modify any file on disk.') |
| 6194 | parser.add_option( |
| 6195 | '--no-clang-format', |
| 6196 | dest='clang_format', |
| 6197 | action='store_false', |
| 6198 | default=True, |
| 6199 | help='Disables formatting of various file types using clang-format.') |
| 6200 | parser.add_option('--python', |
| 6201 | action='store_true', |
| 6202 | default=None, |
| 6203 | help='Enables python formatting on all python files.') |
| 6204 | parser.add_option( |
| 6205 | '--no-python', |
| 6206 | action='store_true', |
| 6207 | default=False, |
| 6208 | help='Disables python formatting on all python files. ' |
| 6209 | 'If neither --python or --no-python are set, python files that have a ' |
| 6210 | '.style.yapf file in an ancestor directory will be formatted. ' |
| 6211 | 'It is an error to set both.') |
| 6212 | parser.add_option('--js', |
| 6213 | action='store_true', |
| 6214 | help='Format javascript code with clang-format. ' |
| 6215 | 'Has no effect if --no-clang-format is set.') |
| 6216 | parser.add_option('--diff', |
| 6217 | action='store_true', |
| 6218 | help='Print diff to stdout rather than modifying files.') |
| 6219 | parser.add_option('--presubmit', |
| 6220 | action='store_true', |
| 6221 | help='Used when running the script from a presubmit.') |
Lukasz Anforowicz | b4d3954 | 2021-09-30 23:39:25 +0000 | [diff] [blame] | 6222 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6223 | parser.add_option( |
| 6224 | '--rust-fmt', |
| 6225 | dest='use_rust_fmt', |
| 6226 | action='store_true', |
| 6227 | default=rustfmt.IsRustfmtSupported(), |
| 6228 | help='Enables formatting of Rust file types using rustfmt.') |
| 6229 | parser.add_option( |
| 6230 | '--no-rust-fmt', |
| 6231 | dest='use_rust_fmt', |
| 6232 | action='store_false', |
| 6233 | help='Disables formatting of Rust file types using rustfmt.') |
Lukasz Anforowicz | b4d3954 | 2021-09-30 23:39:25 +0000 | [diff] [blame] | 6234 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6235 | parser.add_option( |
| 6236 | '--swift-format', |
| 6237 | dest='use_swift_format', |
| 6238 | action='store_true', |
| 6239 | default=swift_format.IsSwiftFormatSupported(), |
| 6240 | help='Enables formatting of Swift file types using swift-format ' |
| 6241 | '(macOS host only).') |
| 6242 | parser.add_option( |
| 6243 | '--no-swift-format', |
| 6244 | dest='use_swift_format', |
| 6245 | action='store_false', |
| 6246 | help='Disables formatting of Swift file types using swift-format.') |
Olivier Robin | 0a6b544 | 2022-04-07 07:25:04 +0000 | [diff] [blame] | 6247 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6248 | opts, args = parser.parse_args(args) |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 6249 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6250 | if opts.python is not None and opts.no_python: |
| 6251 | raise parser.error('Cannot set both --python and --no-python') |
| 6252 | if opts.no_python: |
| 6253 | opts.python = False |
Garrett Beaty | 91a6f33 | 2020-01-06 16:57:24 +0000 | [diff] [blame] | 6254 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6255 | # Normalize any remaining args against the current path, so paths relative |
| 6256 | # to the current directory are still resolved as expected. |
| 6257 | args = [os.path.join(os.getcwd(), arg) for arg in args] |
Daniel Cheng | c55eecf | 2016-12-30 03:11:02 -0800 | [diff] [blame] | 6258 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6259 | # git diff generates paths against the root of the repository. Change |
| 6260 | # to that directory so clang-format can find files even within subdirs. |
| 6261 | rel_base_path = settings.GetRelativeRoot() |
| 6262 | if rel_base_path: |
| 6263 | os.chdir(rel_base_path) |
enne@chromium.org | ff7a1fb | 2013-12-10 19:21:41 +0000 | [diff] [blame] | 6264 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6265 | # Grab the merge-base commit, i.e. the upstream commit of the current |
| 6266 | # branch when it was created or the last time it was rebased. This is |
| 6267 | # to cover the case where the user may have called "git fetch origin", |
| 6268 | # moving the origin branch to a newer commit, but hasn't rebased yet. |
| 6269 | upstream_commit = None |
| 6270 | upstream_branch = opts.upstream |
| 6271 | if not upstream_branch: |
| 6272 | cl = Changelist() |
| 6273 | upstream_branch = cl.GetUpstreamBranch() |
| 6274 | if upstream_branch: |
| 6275 | upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch]) |
| 6276 | upstream_commit = upstream_commit.strip() |
digit@chromium.org | 29e4727 | 2013-05-17 17:01:46 +0000 | [diff] [blame] | 6277 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6278 | if not upstream_commit: |
| 6279 | DieWithError('Could not find base commit for this branch. ' |
| 6280 | 'Are you in detached state?') |
digit@chromium.org | 29e4727 | 2013-05-17 17:01:46 +0000 | [diff] [blame] | 6281 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6282 | changed_files_cmd = BuildGitDiffCmd('--name-only', upstream_commit, args) |
| 6283 | diff_output = RunGit(changed_files_cmd) |
| 6284 | diff_files = diff_output.splitlines() |
| 6285 | # Filter out files deleted by this CL |
| 6286 | 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] | 6287 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6288 | if opts.js: |
| 6289 | CLANG_EXTS.extend(['.js', '.ts']) |
Christopher Lam | c5ba692 | 2017-01-24 11:19:14 +1100 | [diff] [blame] | 6290 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6291 | clang_diff_files = [] |
| 6292 | if opts.clang_format: |
| 6293 | clang_diff_files = [ |
| 6294 | x for x in diff_files if MatchingFileType(x, CLANG_EXTS) |
| 6295 | ] |
| 6296 | python_diff_files = [x for x in diff_files if MatchingFileType(x, ['.py'])] |
| 6297 | rust_diff_files = [x for x in diff_files if MatchingFileType(x, RUST_EXTS)] |
| 6298 | swift_diff_files = [ |
| 6299 | x for x in diff_files if MatchingFileType(x, SWIFT_EXTS) |
Garrett Beaty | ed0cc5f | 2020-01-06 17:26:13 +0000 | [diff] [blame] | 6300 | ] |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6301 | 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] | 6302 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6303 | top_dir = settings.GetRoot() |
nick@chromium.org | 3ac1c4e | 2014-01-16 02:44:42 +0000 | [diff] [blame] | 6304 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6305 | return_value = _RunClangFormatDiff(opts, clang_diff_files, top_dir, |
| 6306 | upstream_commit) |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 6307 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6308 | if opts.use_rust_fmt: |
| 6309 | rust_fmt_return_value = _RunRustFmt(opts, rust_diff_files, top_dir, |
| 6310 | upstream_commit) |
| 6311 | if rust_fmt_return_value == 2: |
| 6312 | return_value = 2 |
Lukasz Anforowicz | b4d3954 | 2021-09-30 23:39:25 +0000 | [diff] [blame] | 6313 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6314 | if opts.use_swift_format: |
| 6315 | if sys.platform != 'darwin': |
| 6316 | DieWithError('swift-format is only supported on macOS.') |
| 6317 | swift_format_return_value = _RunSwiftFormat(opts, swift_diff_files, |
| 6318 | top_dir, upstream_commit) |
| 6319 | if swift_format_return_value == 2: |
| 6320 | return_value = 2 |
Olivier Robin | 0a6b544 | 2022-04-07 07:25:04 +0000 | [diff] [blame] | 6321 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6322 | # Similar code to above, but using yapf on .py files rather than |
| 6323 | # clang-format on C/C++ files |
| 6324 | py_explicitly_disabled = opts.python is not None and not opts.python |
| 6325 | if python_diff_files and not py_explicitly_disabled: |
| 6326 | depot_tools_path = os.path.dirname(os.path.abspath(__file__)) |
| 6327 | yapf_tool = os.path.join(depot_tools_path, 'yapf') |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 6328 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6329 | # Used for caching. |
| 6330 | yapf_configs = {} |
| 6331 | for f in python_diff_files: |
| 6332 | # Find the yapf style config for the current file, defaults to depot |
| 6333 | # tools default. |
| 6334 | _FindYapfConfigFile(f, yapf_configs, top_dir) |
Aiden Benner | 99b0ccb | 2018-11-20 19:53:31 +0000 | [diff] [blame] | 6335 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6336 | # Turn on python formatting by default if a yapf config is specified. |
| 6337 | # This breaks in the case of this repo though since the specified |
| 6338 | # style file is also the global default. |
| 6339 | if opts.python is None: |
| 6340 | filtered_py_files = [] |
| 6341 | for f in python_diff_files: |
| 6342 | if _FindYapfConfigFile(f, yapf_configs, top_dir) is not None: |
| 6343 | filtered_py_files.append(f) |
Andrew Grieve | b9e694c | 2021-11-15 19:04:46 +0000 | [diff] [blame] | 6344 | else: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6345 | filtered_py_files = python_diff_files |
Peter Wen | d939992 | 2020-06-17 17:33:49 +0000 | [diff] [blame] | 6346 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6347 | # Note: yapf still seems to fix indentation of the entire file |
| 6348 | # even if line ranges are specified. |
| 6349 | # See https://github.com/google/yapf/issues/499 |
| 6350 | if not opts.full and filtered_py_files: |
| 6351 | py_line_diffs = _ComputeDiffLineRanges(filtered_py_files, |
| 6352 | upstream_commit) |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 6353 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6354 | yapfignore_patterns = _GetYapfIgnorePatterns(top_dir) |
| 6355 | filtered_py_files = _FilterYapfIgnoredFiles(filtered_py_files, |
| 6356 | yapfignore_patterns) |
Aiden Benner | c08566e | 2018-10-03 17:52:42 +0000 | [diff] [blame] | 6357 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6358 | for f in filtered_py_files: |
| 6359 | yapf_style = _FindYapfConfigFile(f, yapf_configs, top_dir) |
| 6360 | # Default to pep8 if not .style.yapf is found. |
| 6361 | if not yapf_style: |
| 6362 | yapf_style = 'pep8' |
sbc@chromium.org | 9d0644d | 2015-06-05 23:16:54 +0000 | [diff] [blame] | 6363 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6364 | with open(f, 'r') as py_f: |
| 6365 | if 'python2' in py_f.readline(): |
| 6366 | vpython_script = 'vpython' |
| 6367 | else: |
| 6368 | vpython_script = 'vpython3' |
kylechar@chromium.org | 8b61f11 | 2016-02-05 13:28:58 +0000 | [diff] [blame] | 6369 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6370 | cmd = [vpython_script, yapf_tool, '--style', yapf_style, f] |
Wenhan (Han) Zhang | 3bd3c99 | 2020-08-14 16:27:39 +0000 | [diff] [blame] | 6371 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6372 | has_formattable_lines = False |
| 6373 | if not opts.full: |
| 6374 | # Only run yapf over changed line ranges. |
| 6375 | for diff_start, diff_len in py_line_diffs[f]: |
| 6376 | diff_end = diff_start + diff_len - 1 |
| 6377 | # Yapf errors out if diff_end < diff_start but this |
| 6378 | # is a valid line range diff for a removal. |
| 6379 | if diff_end >= diff_start: |
| 6380 | has_formattable_lines = True |
| 6381 | cmd += ['-l', '{}-{}'.format(diff_start, diff_end)] |
| 6382 | # If all line diffs were removals we have nothing to format. |
| 6383 | if not has_formattable_lines: |
| 6384 | continue |
Wenhan (Han) Zhang | 3bd3c99 | 2020-08-14 16:27:39 +0000 | [diff] [blame] | 6385 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6386 | if opts.diff or opts.dry_run: |
| 6387 | cmd += ['--diff'] |
| 6388 | # Will return non-zero exit code if non-empty diff. |
| 6389 | stdout = RunCommand(cmd, |
| 6390 | error_ok=True, |
| 6391 | stderr=subprocess2.PIPE, |
| 6392 | cwd=top_dir, |
| 6393 | shell=sys.platform.startswith('win32')) |
| 6394 | if opts.diff: |
| 6395 | sys.stdout.write(stdout) |
| 6396 | elif len(stdout) > 0: |
| 6397 | return_value = 2 |
| 6398 | else: |
| 6399 | cmd += ['-i'] |
| 6400 | RunCommand(cmd, |
| 6401 | cwd=top_dir, |
| 6402 | shell=sys.platform.startswith('win32')) |
Wenhan (Han) Zhang | 3bd3c99 | 2020-08-14 16:27:39 +0000 | [diff] [blame] | 6403 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6404 | # Format GN build files. Always run on full build files for canonical form. |
| 6405 | if gn_diff_files: |
| 6406 | cmd = ['gn', 'format'] |
| 6407 | if opts.dry_run or opts.diff: |
| 6408 | cmd.append('--dry-run') |
| 6409 | for gn_diff_file in gn_diff_files: |
| 6410 | gn_ret = subprocess2.call(cmd + [gn_diff_file], |
| 6411 | shell=sys.platform.startswith('win'), |
| 6412 | cwd=top_dir) |
| 6413 | if opts.dry_run and gn_ret == 2: |
| 6414 | return_value = 2 # Not formatted. |
| 6415 | elif opts.diff and gn_ret == 2: |
| 6416 | # TODO this should compute and print the actual diff. |
| 6417 | print('This change has GN build file diff for ' + gn_diff_file) |
| 6418 | elif gn_ret != 0: |
| 6419 | # For non-dry run cases (and non-2 return values for dry-run), a |
| 6420 | # nonzero error code indicates a failure, probably because the |
| 6421 | # file doesn't parse. |
| 6422 | DieWithError('gn format failed on ' + gn_diff_file + |
| 6423 | '\nTry running `gn format` on this file manually.') |
Wenhan (Han) Zhang | 3bd3c99 | 2020-08-14 16:27:39 +0000 | [diff] [blame] | 6424 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6425 | # Skip the metrics formatting from the global presubmit hook. These files |
| 6426 | # have a separate presubmit hook that issues an error if the files need |
| 6427 | # formatting, whereas the top-level presubmit script merely issues a |
| 6428 | # warning. Formatting these files is somewhat slow, so it's important not to |
| 6429 | # duplicate the work. |
| 6430 | if not opts.presubmit: |
| 6431 | for diff_xml in GetDiffXMLs(diff_files): |
| 6432 | xml_dir = GetMetricsDir(diff_xml) |
| 6433 | if not xml_dir: |
| 6434 | continue |
Wenhan (Han) Zhang | 3bd3c99 | 2020-08-14 16:27:39 +0000 | [diff] [blame] | 6435 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6436 | tool_dir = os.path.join(top_dir, xml_dir) |
| 6437 | pretty_print_tool = os.path.join(tool_dir, 'pretty_print.py') |
Gavin Mak | 7f5b53f | 2023-09-07 18:13:01 +0000 | [diff] [blame] | 6438 | cmd = [ |
| 6439 | shutil.which('vpython3'), pretty_print_tool, '--non-interactive' |
| 6440 | ] |
Alexei Svitkine | f3cac41 | 2017-02-06 11:08:50 -0500 | [diff] [blame] | 6441 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6442 | # If the XML file is histograms.xml or enums.xml, add the xml path |
| 6443 | # to the command as histograms/pretty_print.py now needs a relative |
| 6444 | # path argument after splitting the histograms into multiple |
| 6445 | # directories. For example, in tools/metrics/ukm, pretty-print could |
| 6446 | # be run using: $ python pretty_print.py But in |
| 6447 | # tools/metrics/histogrmas, pretty-print should be run with an |
| 6448 | # additional relative path argument, like: $ python pretty_print.py |
| 6449 | # metadata/UMA/histograms.xml $ python pretty_print.py enums.xml |
| 6450 | |
| 6451 | if xml_dir == os.path.join('tools', 'metrics', 'histograms'): |
| 6452 | if os.path.basename(diff_xml) not in ( |
| 6453 | 'histograms.xml', 'enums.xml', |
| 6454 | 'histogram_suffixes_list.xml'): |
| 6455 | # Skip this XML file if it's not one of the known types. |
| 6456 | continue |
| 6457 | cmd.append(diff_xml) |
| 6458 | |
| 6459 | if opts.dry_run or opts.diff: |
| 6460 | cmd.append('--diff') |
| 6461 | |
Gavin Mak | 7f5b53f | 2023-09-07 18:13:01 +0000 | [diff] [blame] | 6462 | stdout = RunCommand(cmd, cwd=top_dir) |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6463 | if opts.diff: |
| 6464 | sys.stdout.write(stdout) |
| 6465 | if opts.dry_run and stdout: |
| 6466 | return_value = 2 # Not formatted. |
| 6467 | |
| 6468 | return return_value |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 6469 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 6470 | |
Wenhan (Han) Zhang | 3bd3c99 | 2020-08-14 16:27:39 +0000 | [diff] [blame] | 6471 | def GetDiffXMLs(diff_files): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6472 | return [ |
| 6473 | os.path.normpath(x) for x in diff_files |
| 6474 | if MatchingFileType(x, ['.xml']) |
| 6475 | ] |
Wenhan (Han) Zhang | 3bd3c99 | 2020-08-14 16:27:39 +0000 | [diff] [blame] | 6476 | |
| 6477 | |
| 6478 | def GetMetricsDir(diff_xml): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6479 | metrics_xml_dirs = [ |
| 6480 | os.path.join('tools', 'metrics', 'actions'), |
| 6481 | os.path.join('tools', 'metrics', 'histograms'), |
| 6482 | os.path.join('tools', 'metrics', 'structured'), |
| 6483 | os.path.join('tools', 'metrics', 'ukm'), |
| 6484 | ] |
| 6485 | for xml_dir in metrics_xml_dirs: |
| 6486 | if diff_xml.startswith(xml_dir): |
| 6487 | return xml_dir |
| 6488 | return None |
Steven Holte | 2e664bf | 2017-04-21 13:10:47 -0700 | [diff] [blame] | 6489 | |
agable@chromium.org | fab8f82 | 2013-05-06 17:43:09 +0000 | [diff] [blame] | 6490 | |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6491 | @subcommand.usage('<codereview url or issue id>') |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 6492 | @metrics.collector.collect_metrics('git cl checkout') |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6493 | def CMDcheckout(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6494 | """Checks out a branch associated with a given Gerrit issue.""" |
| 6495 | _, args = parser.parse_args(args) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6496 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6497 | if len(args) != 1: |
| 6498 | parser.print_help() |
| 6499 | return 1 |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6500 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6501 | issue_arg = ParseIssueNumberArgument(args[0]) |
| 6502 | if not issue_arg.valid: |
| 6503 | parser.error('Invalid issue ID or URL.') |
Andrii Shyshkalov | c971239 | 2017-04-11 13:35:21 +0200 | [diff] [blame] | 6504 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6505 | target_issue = str(issue_arg.issue) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6506 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6507 | output = RunGit([ |
| 6508 | 'config', '--local', '--get-regexp', r'branch\..*\.' + ISSUE_CONFIG_KEY |
| 6509 | ], |
| 6510 | error_ok=True) |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6511 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6512 | branches = [] |
| 6513 | for key, issue in [x.split() for x in output.splitlines()]: |
| 6514 | if issue == target_issue: |
| 6515 | branches.append( |
| 6516 | re.sub(r'branch\.(.*)\.' + ISSUE_CONFIG_KEY, r'\1', key)) |
Edward Lemur | 52969c9 | 2020-02-06 18:15:28 +0000 | [diff] [blame] | 6517 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6518 | if len(branches) == 0: |
| 6519 | print('No branch found for issue %s.' % target_issue) |
| 6520 | return 1 |
| 6521 | if len(branches) == 1: |
| 6522 | RunGit(['checkout', branches[0]]) |
| 6523 | else: |
| 6524 | print('Multiple branches match issue %s:' % target_issue) |
| 6525 | for i in range(len(branches)): |
| 6526 | print('%d: %s' % (i, branches[i])) |
| 6527 | which = gclient_utils.AskForData('Choose by index: ') |
| 6528 | try: |
| 6529 | RunGit(['checkout', branches[int(which)]]) |
| 6530 | except (IndexError, ValueError): |
| 6531 | print('Invalid selection, not checking out any branch.') |
| 6532 | return 1 |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6533 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6534 | return 0 |
scottmg@chromium.org | 84a80c4 | 2015-09-22 20:40:37 +0000 | [diff] [blame] | 6535 | |
| 6536 | |
maruel@chromium.org | 29404b5 | 2014-09-08 22:58:00 +0000 | [diff] [blame] | 6537 | def CMDlol(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6538 | # This command is intentionally undocumented. |
| 6539 | print( |
| 6540 | zlib.decompress( |
| 6541 | base64.b64decode( |
| 6542 | 'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE' |
| 6543 | 'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9' |
| 6544 | 'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W' |
| 6545 | 'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY')).decode('utf-8')) |
| 6546 | return 0 |
maruel@chromium.org | 29404b5 | 2014-09-08 22:58:00 +0000 | [diff] [blame] | 6547 | |
| 6548 | |
Josip Sokcevic | 0399e17 | 2022-03-21 23:11:51 +0000 | [diff] [blame] | 6549 | def CMDversion(parser, args): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6550 | import utils |
| 6551 | print(utils.depot_tools_version()) |
Josip Sokcevic | 0399e17 | 2022-03-21 23:11:51 +0000 | [diff] [blame] | 6552 | |
| 6553 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 6554 | class OptionParser(optparse.OptionParser): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6555 | """Creates the option parse and add --verbose support.""" |
| 6556 | def __init__(self, *args, **kwargs): |
| 6557 | optparse.OptionParser.__init__(self, |
| 6558 | *args, |
| 6559 | prog='git cl', |
| 6560 | version=__version__, |
| 6561 | **kwargs) |
| 6562 | self.add_option('-v', |
| 6563 | '--verbose', |
| 6564 | action='count', |
| 6565 | default=0, |
| 6566 | help='Use 2 times for more debugging info') |
Sigurd Schneider | 9abde8c | 2020-11-17 08:44:52 +0000 | [diff] [blame] | 6567 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6568 | def parse_args(self, args=None, _values=None): |
Joanna Wang | c5b3832 | 2023-03-15 20:38:46 +0000 | [diff] [blame] | 6569 | try: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6570 | return self._parse_args(args) |
| 6571 | finally: |
| 6572 | # Regardless of success or failure of args parsing, we want to |
| 6573 | # report metrics, but only after logging has been initialized (if |
| 6574 | # parsing succeeded). |
| 6575 | global settings |
| 6576 | settings = Settings() |
Andrii Shyshkalov | 46f20cd | 2018-10-30 06:42:54 +0000 | [diff] [blame] | 6577 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6578 | if metrics.collector.config.should_collect_metrics: |
| 6579 | try: |
| 6580 | # GetViewVCUrl ultimately calls logging method. |
| 6581 | project_url = settings.GetViewVCUrl().strip('/+') |
| 6582 | if project_url in metrics_utils.KNOWN_PROJECT_URLS: |
| 6583 | metrics.collector.add('project_urls', [project_url]) |
| 6584 | except subprocess2.CalledProcessError: |
| 6585 | # Occurs when command is not executed in a git repository |
| 6586 | # We should not fail here. If the command needs to be |
| 6587 | # executed in a repo, it will be raised later. |
| 6588 | pass |
Edward Lemur | 5ba1e9c | 2018-07-23 18:19:02 +0000 | [diff] [blame] | 6589 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6590 | def _parse_args(self, args=None): |
| 6591 | # Create an optparse.Values object that will store only the actual |
| 6592 | # passed options, without the defaults. |
| 6593 | actual_options = optparse.Values() |
| 6594 | _, args = optparse.OptionParser.parse_args(self, args, actual_options) |
| 6595 | # Create an optparse.Values object with the default options. |
| 6596 | options = optparse.Values(self.get_default_values().__dict__) |
| 6597 | # Update it with the options passed by the user. |
| 6598 | options._update_careful(actual_options.__dict__) |
| 6599 | # Store the options passed by the user in an _actual_options attribute. |
| 6600 | # We store only the keys, and not the values, since the values can |
| 6601 | # contain arbitrary information, which might be PII. |
| 6602 | metrics.collector.add('arguments', list(actual_options.__dict__.keys())) |
Edward Lemur | 83bd7f4 | 2018-10-10 00:14:21 +0000 | [diff] [blame] | 6603 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6604 | levels = [logging.WARNING, logging.INFO, logging.DEBUG] |
| 6605 | logging.basicConfig( |
| 6606 | level=levels[min(options.verbose, |
| 6607 | len(levels) - 1)], |
| 6608 | format='[%(levelname).1s%(asctime)s %(process)d %(thread)d ' |
| 6609 | '%(filename)s] %(message)s') |
| 6610 | |
| 6611 | return options, args |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 6612 | |
iannucci@chromium.org | d9c1b20 | 2013-07-24 23:52:11 +0000 | [diff] [blame] | 6613 | |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 6614 | def main(argv): |
Gavin Mak | 7f5b53f | 2023-09-07 18:13:01 +0000 | [diff] [blame] | 6615 | if sys.version_info[0] < 3: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6616 | print('\nYour Python version %s is unsupported, please upgrade.\n' % |
| 6617 | (sys.version.split(' ', 1)[0], ), |
| 6618 | file=sys.stderr) |
| 6619 | return 2 |
maruel@chromium.org | 2e23ce3 | 2013-05-07 12:42:28 +0000 | [diff] [blame] | 6620 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6621 | colorize_CMDstatus_doc() |
| 6622 | dispatcher = subcommand.CommandDispatcher(__name__) |
| 6623 | try: |
| 6624 | return dispatcher.execute(OptionParser(), argv) |
| 6625 | except auth.LoginRequiredError as e: |
| 6626 | DieWithError(str(e)) |
| 6627 | except urllib.error.HTTPError as e: |
| 6628 | if e.code != 500: |
| 6629 | raise |
| 6630 | DieWithError(( |
| 6631 | 'App Engine is misbehaving and returned HTTP %d, again. Keep faith ' |
| 6632 | 'and retry or visit go/isgaeup.\n%s') % (e.code, str(e))) |
| 6633 | return 0 |
chase@chromium.org | cc51cd0 | 2010-12-23 00:48:39 +0000 | [diff] [blame] | 6634 | |
| 6635 | |
| 6636 | if __name__ == '__main__': |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 6637 | # These affect sys.stdout, so do it outside of main() to simplify mocks in |
| 6638 | # the unit tests. |
| 6639 | fix_encoding.fix_encoding() |
| 6640 | setup_color.init() |
| 6641 | with metrics.collector.print_notice_and_exit(): |
| 6642 | sys.exit(main(sys.argv[1:])) |