szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 1 | # Copyright (c) 2013 The Chromium OS Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 4 | """ |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 5 | Utilities for requesting information for a Gerrit server via HTTPS. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 6 | |
| 7 | https://gerrit-review.googlesource.com/Documentation/rest-api.html |
| 8 | """ |
| 9 | |
| 10 | import base64 |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 11 | import contextlib |
Edward Lemur | 202c559 | 2019-10-21 22:44:52 +0000 | [diff] [blame] | 12 | import httplib2 |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 13 | import json |
| 14 | import logging |
| 15 | import netrc |
| 16 | import os |
Andrii Shyshkalov | d4c8673 | 2018-09-25 04:29:31 +0000 | [diff] [blame] | 17 | import random |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 18 | import re |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 19 | import socket |
szager@chromium.org | f202a25 | 2014-05-27 18:55:52 +0000 | [diff] [blame] | 20 | import stat |
| 21 | import sys |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 22 | import tempfile |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 23 | import time |
Gavin Mak | 7f5b53f | 2023-09-07 18:13:01 +0000 | [diff] [blame] | 24 | import urllib.parse |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 25 | from multiprocessing.pool import ThreadPool |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 26 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 27 | import auth |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 28 | import gclient_utils |
Edward Lemur | 5a9ff43 | 2018-10-30 19:00:22 +0000 | [diff] [blame] | 29 | import metrics |
| 30 | import metrics_utils |
Aaron Gable | 8797cab | 2018-03-06 13:55:00 -0800 | [diff] [blame] | 31 | import subprocess2 |
szager@chromium.org | f202a25 | 2014-05-27 18:55:52 +0000 | [diff] [blame] | 32 | |
Gavin Mak | cc97655 | 2023-08-28 17:01:52 +0000 | [diff] [blame] | 33 | import http.cookiejar |
| 34 | from io import StringIO |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 35 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 36 | # TODO: Should fix these warnings. |
| 37 | # pylint: disable=line-too-long |
| 38 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 39 | LOGGER = logging.getLogger() |
Gavin Mak | fc75af3 | 2023-06-20 20:06:27 +0000 | [diff] [blame] | 40 | # With a starting sleep time of 12.0 seconds, x <= [1.8-2.2]x backoff, and six |
| 41 | # total tries, the sleep time between the first and last tries will be ~6 min |
| 42 | # (excluding time for each try). |
| 43 | TRY_LIMIT = 6 |
| 44 | SLEEP_TIME = 12.0 |
George Engelbrecht | 888c0fe | 2020-04-17 15:00:20 +0000 | [diff] [blame] | 45 | MAX_BACKOFF = 2.2 |
| 46 | MIN_BACKOFF = 1.8 |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 47 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 48 | # Controls the transport protocol used to communicate with Gerrit. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 49 | # This is parameterized primarily to enable GerritTestCase. |
| 50 | GERRIT_PROTOCOL = 'https' |
| 51 | |
| 52 | |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 53 | def time_sleep(seconds): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 54 | # Use this so that it can be mocked in tests without interfering with python |
| 55 | # system machinery. |
| 56 | return time.sleep(seconds) |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 57 | |
| 58 | |
Edward Lemur | a3b6fd0 | 2020-03-02 22:16:15 +0000 | [diff] [blame] | 59 | def time_time(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 60 | # Use this so that it can be mocked in tests without interfering with python |
| 61 | # system machinery. |
| 62 | return time.time() |
Edward Lemur | a3b6fd0 | 2020-03-02 22:16:15 +0000 | [diff] [blame] | 63 | |
| 64 | |
Ben Pastene | 9519fc1 | 2023-04-12 22:15:43 +0000 | [diff] [blame] | 65 | def log_retry_and_sleep(seconds, attempt): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 66 | LOGGER.info('Will retry in %d seconds (%d more times)...', seconds, |
| 67 | TRY_LIMIT - attempt - 1) |
| 68 | time_sleep(seconds) |
| 69 | return seconds * random.uniform(MIN_BACKOFF, MAX_BACKOFF) |
Ben Pastene | 9519fc1 | 2023-04-12 22:15:43 +0000 | [diff] [blame] | 70 | |
| 71 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 72 | class GerritError(Exception): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 73 | """Exception class for errors commuicating with the gerrit-on-borg service.""" |
| 74 | def __init__(self, http_status, message, *args, **kwargs): |
| 75 | super(GerritError, self).__init__(*args, **kwargs) |
| 76 | self.http_status = http_status |
| 77 | self.message = '(%d) %s' % (self.http_status, message) |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 78 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 79 | def __str__(self): |
| 80 | return self.message |
Josip Sokcevic | df9a802 | 2020-12-08 00:10:19 +0000 | [diff] [blame] | 81 | |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 82 | |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 83 | def _QueryString(params, first_param=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 84 | """Encodes query parameters in the key:val[+key:val...] format specified here: |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 85 | |
| 86 | https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes |
| 87 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 88 | q = [urllib.parse.quote(first_param)] if first_param else [] |
| 89 | q.extend(['%s:%s' % (key, val.replace(" ", "+")) for key, val in params]) |
| 90 | return '+'.join(q) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 91 | |
| 92 | |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 93 | class Authenticator(object): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 94 | """Base authenticator class for authenticator implementations to subclass.""" |
| 95 | def get_auth_header(self, host): |
| 96 | raise NotImplementedError() |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 97 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 98 | @staticmethod |
| 99 | def get(): |
| 100 | """Returns: (Authenticator) The identified Authenticator to use. |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 101 | |
| 102 | Probes the local system and its environment and identifies the |
| 103 | Authenticator instance to use. |
| 104 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 105 | # LUCI Context takes priority since it's normally present only on bots, |
| 106 | # which then must use it. |
| 107 | if LuciContextAuthenticator.is_luci(): |
| 108 | return LuciContextAuthenticator() |
| 109 | # TODO(crbug.com/1059384): Automatically detect when running on |
| 110 | # cloudtop, and use CookiesAuthenticator instead. |
| 111 | if GceAuthenticator.is_gce(): |
| 112 | return GceAuthenticator() |
| 113 | return CookiesAuthenticator() |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 114 | |
| 115 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 116 | class CookiesAuthenticator(Authenticator): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 117 | """Authenticator implementation that uses ".netrc" or ".gitcookies" for token. |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 118 | |
| 119 | Expected case for developer workstations. |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 120 | """ |
| 121 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 122 | _EMPTY = object() |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 123 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 124 | def __init__(self): |
| 125 | # Credentials will be loaded lazily on first use. This ensures |
| 126 | # Authenticator get() can always construct an authenticator, even if |
| 127 | # something is broken. This allows 'creds-check' to proceed to actually |
| 128 | # checking creds later, rigorously (instead of blowing up with a cryptic |
| 129 | # error if they are wrong). |
| 130 | self._netrc = self._EMPTY |
| 131 | self._gitcookies = self._EMPTY |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 132 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 133 | @property |
| 134 | def netrc(self): |
| 135 | if self._netrc is self._EMPTY: |
| 136 | self._netrc = self._get_netrc() |
| 137 | return self._netrc |
Vadim Shtayura | b250ec1 | 2018-10-04 00:21:08 +0000 | [diff] [blame] | 138 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 139 | @property |
| 140 | def gitcookies(self): |
| 141 | if self._gitcookies is self._EMPTY: |
| 142 | self._gitcookies = self._get_gitcookies() |
| 143 | return self._gitcookies |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 144 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 145 | @classmethod |
| 146 | def get_new_password_url(cls, host): |
| 147 | assert not host.startswith('http') |
| 148 | # Assume *.googlesource.com pattern. |
| 149 | parts = host.split('.') |
Aravind Vasudevan | a02b4bf | 2023-02-03 17:52:03 +0000 | [diff] [blame] | 150 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 151 | # remove -review suffix if present. |
| 152 | if parts[0].endswith('-review'): |
| 153 | parts[0] = parts[0][:-len('-review')] |
Aravind Vasudevan | a02b4bf | 2023-02-03 17:52:03 +0000 | [diff] [blame] | 154 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 155 | return 'https://%s/new-password' % ('.'.join(parts)) |
Andrii Shyshkalov | c817382 | 2017-07-10 12:10:53 +0200 | [diff] [blame] | 156 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 157 | @classmethod |
| 158 | def get_new_password_message(cls, host): |
| 159 | if host is None: |
| 160 | return ('Git host for Gerrit upload is unknown. Check your remote ' |
| 161 | 'and the branch your branch is tracking. This tool assumes ' |
| 162 | 'that you are using a git server at *.googlesource.com.') |
| 163 | url = cls.get_new_password_url(host) |
| 164 | return 'You can (re)generate your credentials by visiting %s' % url |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 165 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 166 | @classmethod |
| 167 | def get_netrc_path(cls): |
| 168 | path = '_netrc' if sys.platform.startswith('win') else '.netrc' |
| 169 | return os.path.expanduser(os.path.join('~', path)) |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 170 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 171 | @classmethod |
| 172 | def _get_netrc(cls): |
| 173 | # Buffer the '.netrc' path. Use an empty file if it doesn't exist. |
| 174 | path = cls.get_netrc_path() |
| 175 | if not os.path.exists(path): |
| 176 | return netrc.netrc(os.devnull) |
Sylvain Defresne | 2b138f7 | 2018-07-12 08:34:48 +0000 | [diff] [blame] | 177 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 178 | st = os.stat(path) |
| 179 | if st.st_mode & (stat.S_IRWXG | stat.S_IRWXO): |
| 180 | print('WARNING: netrc file %s cannot be used because its file ' |
| 181 | 'permissions are insecure. netrc file permissions should be ' |
| 182 | '600.' % path, |
| 183 | file=sys.stderr) |
| 184 | with open(path) as fd: |
| 185 | content = fd.read() |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 186 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 187 | # Load the '.netrc' file. We strip comments from it because processing |
| 188 | # them can trigger a bug in Windows. See crbug.com/664664. |
| 189 | content = '\n'.join(l for l in content.splitlines() |
| 190 | if l.strip() and not l.strip().startswith('#')) |
| 191 | with tempdir() as tdir: |
| 192 | netrc_path = os.path.join(tdir, 'netrc') |
| 193 | with open(netrc_path, 'w') as fd: |
| 194 | fd.write(content) |
| 195 | os.chmod(netrc_path, (stat.S_IRUSR | stat.S_IWUSR)) |
| 196 | return cls._get_netrc_from_path(netrc_path) |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 197 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 198 | @classmethod |
| 199 | def _get_netrc_from_path(cls, path): |
| 200 | try: |
| 201 | return netrc.netrc(path) |
| 202 | except IOError: |
| 203 | print('WARNING: Could not read netrc file %s' % path, |
| 204 | file=sys.stderr) |
| 205 | return netrc.netrc(os.devnull) |
| 206 | except netrc.NetrcParseError as e: |
| 207 | print('ERROR: Cannot use netrc file %s due to a parsing error: %s' % |
| 208 | (path, e), |
| 209 | file=sys.stderr) |
| 210 | return netrc.netrc(os.devnull) |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 211 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 212 | @classmethod |
| 213 | def get_gitcookies_path(cls): |
| 214 | if os.getenv('GIT_COOKIES_PATH'): |
| 215 | return os.getenv('GIT_COOKIES_PATH') |
| 216 | try: |
| 217 | path = subprocess2.check_output( |
| 218 | ['git', 'config', '--path', 'http.cookiefile']) |
| 219 | return path.decode('utf-8', 'ignore').strip() |
| 220 | except subprocess2.CalledProcessError: |
| 221 | return os.path.expanduser(os.path.join('~', '.gitcookies')) |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 222 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 223 | @classmethod |
| 224 | def _get_gitcookies(cls): |
| 225 | gitcookies = {} |
| 226 | path = cls.get_gitcookies_path() |
| 227 | if not os.path.exists(path): |
| 228 | return gitcookies |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 229 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 230 | try: |
| 231 | f = gclient_utils.FileRead(path, 'rb').splitlines() |
| 232 | except IOError: |
| 233 | return gitcookies |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 234 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 235 | for line in f: |
| 236 | try: |
| 237 | fields = line.strip().split('\t') |
| 238 | if line.strip().startswith('#') or len(fields) != 7: |
| 239 | continue |
| 240 | domain, xpath, key, value = fields[0], fields[2], fields[ |
| 241 | 5], fields[6] |
| 242 | if xpath == '/' and key == 'o': |
| 243 | if value.startswith('git-'): |
| 244 | login, secret_token = value.split('=', 1) |
| 245 | gitcookies[domain] = (login, secret_token) |
| 246 | else: |
| 247 | gitcookies[domain] = ('', value) |
| 248 | except (IndexError, ValueError, TypeError) as exc: |
| 249 | LOGGER.warning(exc) |
| 250 | return gitcookies |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 251 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 252 | def _get_auth_for_host(self, host): |
| 253 | for domain, creds in self.gitcookies.items(): |
| 254 | if http.cookiejar.domain_match(host, domain): |
| 255 | return (creds[0], None, creds[1]) |
| 256 | return self.netrc.authenticators(host) |
phajdan.jr@chromium.org | ff7840a | 2015-11-04 16:35:22 +0000 | [diff] [blame] | 257 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 258 | def get_auth_header(self, host): |
| 259 | a = self._get_auth_for_host(host) |
| 260 | if a: |
| 261 | if a[0]: |
| 262 | secret = base64.b64encode( |
| 263 | ('%s:%s' % (a[0], a[2])).encode('utf-8')) |
| 264 | return 'Basic %s' % secret.decode('utf-8') |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 265 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 266 | return 'Bearer %s' % a[2] |
| 267 | return None |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 268 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 269 | def get_auth_email(self, host): |
| 270 | """Best effort parsing of email to be used for auth for the given host.""" |
| 271 | a = self._get_auth_for_host(host) |
| 272 | if not a: |
| 273 | return None |
| 274 | login = a[0] |
| 275 | # login typically looks like 'git-xxx.example.com' |
| 276 | if not login.startswith('git-') or '.' not in login: |
| 277 | return None |
| 278 | username, domain = login[len('git-'):].split('.', 1) |
| 279 | return '%s@%s' % (username, domain) |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 280 | |
Andrii Shyshkalov | 1897532 | 2017-01-25 16:44:13 +0100 | [diff] [blame] | 281 | |
tandrii@chromium.org | fe30f18 | 2016-04-13 12:15:04 +0000 | [diff] [blame] | 282 | # Backwards compatibility just in case somebody imports this outside of |
| 283 | # depot_tools. |
| 284 | NetrcAuthenticator = CookiesAuthenticator |
| 285 | |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 286 | |
| 287 | class GceAuthenticator(Authenticator): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 288 | """Authenticator implementation that uses GCE metadata service for token. |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 289 | """ |
| 290 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 291 | _INFO_URL = 'http://metadata.google.internal' |
| 292 | _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/' |
| 293 | 'service-accounts/default/token' % _INFO_URL) |
| 294 | _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"} |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 295 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 296 | _cache_is_gce = None |
| 297 | _token_cache = None |
| 298 | _token_expiration = None |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 299 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 300 | @classmethod |
| 301 | def is_gce(cls): |
| 302 | if os.getenv('SKIP_GCE_AUTH_FOR_GIT'): |
| 303 | return False |
| 304 | if cls._cache_is_gce is None: |
| 305 | cls._cache_is_gce = cls._test_is_gce() |
| 306 | return cls._cache_is_gce |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 307 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 308 | @classmethod |
| 309 | def _test_is_gce(cls): |
| 310 | # Based on https://cloud.google.com/compute/docs/metadata#runninggce |
| 311 | resp, _ = cls._get(cls._INFO_URL) |
| 312 | if resp is None: |
| 313 | return False |
| 314 | return resp.get('metadata-flavor') == 'Google' |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 315 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 316 | @staticmethod |
| 317 | def _get(url, **kwargs): |
| 318 | next_delay_sec = 1.0 |
| 319 | for i in range(TRY_LIMIT): |
| 320 | p = urllib.parse.urlparse(url) |
| 321 | if p.scheme not in ('http', 'https'): |
| 322 | raise RuntimeError("Don't know how to work with protocol '%s'" % |
| 323 | protocol) |
| 324 | try: |
| 325 | resp, contents = httplib2.Http().request(url, 'GET', **kwargs) |
| 326 | except (socket.error, httplib2.HttpLib2Error, |
| 327 | httplib2.socks.ProxyError) as e: |
| 328 | LOGGER.debug('GET [%s] raised %s', url, e) |
| 329 | return None, None |
| 330 | LOGGER.debug('GET [%s] #%d/%d (%d)', url, i + 1, TRY_LIMIT, |
| 331 | resp.status) |
| 332 | if resp.status < 500: |
| 333 | return (resp, contents) |
| 334 | |
| 335 | # Retry server error status codes. |
| 336 | LOGGER.warn('Encountered server error') |
| 337 | if TRY_LIMIT - i > 1: |
| 338 | next_delay_sec = log_retry_and_sleep(next_delay_sec, i) |
Edward Lemur | a3b6fd0 | 2020-03-02 22:16:15 +0000 | [diff] [blame] | 339 | return None, None |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 340 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 341 | @classmethod |
| 342 | def _get_token_dict(cls): |
| 343 | # If cached token is valid for at least 25 seconds, return it. |
| 344 | if cls._token_cache and time_time() + 25 < cls._token_expiration: |
| 345 | return cls._token_cache |
Aaron Gable | 92e9f38 | 2017-12-07 11:47:41 -0800 | [diff] [blame] | 346 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 347 | resp, contents = cls._get(cls._ACQUIRE_URL, |
| 348 | headers=cls._ACQUIRE_HEADERS) |
| 349 | if resp is None or resp.status != 200: |
| 350 | return None |
| 351 | cls._token_cache = json.loads(contents) |
| 352 | cls._token_expiration = cls._token_cache['expires_in'] + time_time() |
| 353 | return cls._token_cache |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 354 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 355 | def get_auth_header(self, _host): |
| 356 | token_dict = self._get_token_dict() |
| 357 | if not token_dict: |
| 358 | return None |
| 359 | return '%(token_type)s %(access_token)s' % token_dict |
dnj@chromium.org | a5a2c8a | 2015-09-29 16:22:55 +0000 | [diff] [blame] | 360 | |
| 361 | |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 362 | class LuciContextAuthenticator(Authenticator): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 363 | """Authenticator implementation that uses LUCI_CONTEXT ambient local auth. |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 364 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 365 | @staticmethod |
| 366 | def is_luci(): |
| 367 | return auth.has_luci_context_local_auth() |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 368 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 369 | def __init__(self): |
| 370 | self._authenticator = auth.Authenticator(' '.join( |
| 371 | [auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT])) |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 372 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 373 | def get_auth_header(self, _host): |
| 374 | return 'Bearer %s' % self._authenticator.get_access_token().token |
Andrii Shyshkalov | 733d4ec | 2018-04-19 11:48:58 -0700 | [diff] [blame] | 375 | |
| 376 | |
Ben Pastene | 0418255 | 2023-04-13 20:10:21 +0000 | [diff] [blame] | 377 | def CreateHttpConn(host, |
| 378 | path, |
| 379 | reqtype='GET', |
| 380 | headers=None, |
| 381 | body=None, |
Xinan Lin | 1344a3c | 2023-05-02 21:55:43 +0000 | [diff] [blame] | 382 | timeout=300): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 383 | """Opens an HTTPS connection to a Gerrit service, and sends a request.""" |
| 384 | headers = headers or {} |
| 385 | bare_host = host.partition(':')[0] |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 386 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 387 | a = Authenticator.get() |
| 388 | # TODO(crbug.com/1059384): Automatically detect when running on cloudtop. |
| 389 | if isinstance(a, GceAuthenticator): |
| 390 | print('If you\'re on a cloudtop instance, export ' |
| 391 | 'SKIP_GCE_AUTH_FOR_GIT=1 in your env.') |
Edward Lemur | 447507e | 2020-03-31 17:33:54 +0000 | [diff] [blame] | 392 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 393 | a = a.get_auth_header(bare_host) |
| 394 | if a: |
| 395 | headers.setdefault('Authorization', a) |
| 396 | else: |
| 397 | LOGGER.debug('No authorization found for %s.' % bare_host) |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 398 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 399 | url = path |
| 400 | if not url.startswith('/'): |
| 401 | url = '/' + url |
| 402 | if 'Authorization' in headers and not url.startswith('/a/'): |
| 403 | url = '/a%s' % url |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 404 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 405 | if body: |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 406 | body = json.dumps(body, sort_keys=True) |
| 407 | headers.setdefault('Content-Type', 'application/json') |
| 408 | if LOGGER.isEnabledFor(logging.DEBUG): |
| 409 | LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url)) |
| 410 | for key, val in headers.items(): |
| 411 | if key == 'Authorization': |
| 412 | val = 'HIDDEN' |
| 413 | LOGGER.debug('%s: %s' % (key, val)) |
| 414 | if body: |
| 415 | LOGGER.debug(body) |
| 416 | conn = httplib2.Http(timeout=timeout) |
| 417 | # HACK: httplib2.Http has no such attribute; we store req_host here for |
| 418 | # later use in ReadHttpResponse. |
| 419 | conn.req_host = host |
| 420 | conn.req_params = { |
| 421 | 'uri': urllib.parse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url), |
| 422 | 'method': reqtype, |
| 423 | 'headers': headers, |
| 424 | 'body': body, |
| 425 | } |
| 426 | return conn |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 427 | |
| 428 | |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 429 | def ReadHttpResponse(conn, accept_statuses=frozenset([200])): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 430 | """Reads an HTTP response from a connection into a string buffer. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 431 | |
| 432 | Args: |
Raphael Kubo da Costa | 89d0485 | 2017-03-23 19:04:31 +0100 | [diff] [blame] | 433 | conn: An Http object created by CreateHttpConn above. |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 434 | accept_statuses: Treat any of these statuses as success. Default: [200] |
| 435 | Common additions include 204, 400, and 404. |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 436 | Returns: A string buffer containing the connection's reply. |
| 437 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 438 | sleep_time = SLEEP_TIME |
| 439 | for idx in range(TRY_LIMIT): |
| 440 | before_response = time.time() |
| 441 | try: |
| 442 | response, contents = conn.request(**conn.req_params) |
| 443 | except socket.timeout: |
| 444 | if idx < TRY_LIMIT - 1: |
| 445 | sleep_time = log_retry_and_sleep(sleep_time, idx) |
| 446 | continue |
| 447 | raise |
| 448 | contents = contents.decode('utf-8', 'replace') |
nodir@chromium.org | ce32b6e | 2014-05-12 20:31:32 +0000 | [diff] [blame] | 449 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 450 | response_time = time.time() - before_response |
| 451 | metrics.collector.add_repeated( |
| 452 | 'http_requests', |
| 453 | metrics_utils.extract_http_metrics(conn.req_params['uri'], |
| 454 | conn.req_params['method'], |
| 455 | response.status, response_time)) |
Edward Lemur | 5a9ff43 | 2018-10-30 19:00:22 +0000 | [diff] [blame] | 456 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 457 | # If response.status is an accepted status, |
| 458 | # or response.status < 500 then the result is final; break retry loop. |
| 459 | # If the response is 404/409 it might be because of replication lag, |
| 460 | # so keep trying anyway. If it is 429, it is generally ok to retry after |
| 461 | # a backoff. |
| 462 | if (response.status in accept_statuses or response.status < 500 |
| 463 | and response.status not in [404, 409, 429]): |
| 464 | LOGGER.debug('got response %d for %s %s', response.status, |
| 465 | conn.req_params['method'], conn.req_params['uri']) |
| 466 | # If 404 was in accept_statuses, then it's expected that the file |
| 467 | # might not exist, so don't return the gitiles error page because |
| 468 | # that's not the "content" that was actually requested. |
| 469 | if response.status == 404: |
| 470 | contents = '' |
| 471 | break |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 472 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 473 | # A status >=500 is assumed to be a possible transient error; retry. |
| 474 | http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0') |
| 475 | LOGGER.warn( |
| 476 | 'A transient error occurred while querying %s:\n' |
| 477 | '%s %s %s\n' |
| 478 | '%s %d %s\n' |
| 479 | '%s', conn.req_host, conn.req_params['method'], |
| 480 | conn.req_params['uri'], http_version, http_version, response.status, |
| 481 | response.reason, contents) |
Andrii Shyshkalov | d4c8673 | 2018-09-25 04:29:31 +0000 | [diff] [blame] | 482 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 483 | if idx < TRY_LIMIT - 1: |
| 484 | sleep_time = log_retry_and_sleep(sleep_time, idx) |
| 485 | # end of retries loop |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 486 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 487 | if response.status in accept_statuses: |
| 488 | return StringIO(contents) |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 489 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 490 | if response.status in (302, 401, 403): |
| 491 | www_authenticate = response.get('www-authenticate') |
| 492 | if not www_authenticate: |
| 493 | print('Your Gerrit credentials might be misconfigured.') |
| 494 | else: |
| 495 | auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I) |
| 496 | host = auth_match.group(1) if auth_match else conn.req_host |
| 497 | print('Authentication failed. Please make sure your .gitcookies ' |
| 498 | 'file has credentials for %s.' % host) |
| 499 | print('Try:\n git cl creds-check') |
Edward Lemur | 4ba192e | 2019-10-28 20:19:37 +0000 | [diff] [blame] | 500 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 501 | reason = '%s: %s' % (response.reason, contents) |
| 502 | raise GerritError(response.status, reason) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 503 | |
| 504 | |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 505 | def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 506 | """Parses an https response as json.""" |
| 507 | fh = ReadHttpResponse(conn, accept_statuses) |
| 508 | # The first line of the response should always be: )]}' |
| 509 | s = fh.readline() |
| 510 | if s and s.rstrip() != ")]}'": |
| 511 | raise GerritError(200, 'Unexpected json output: %s' % s) |
| 512 | s = fh.read() |
| 513 | if not s: |
| 514 | return None |
| 515 | return json.loads(s) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 516 | |
| 517 | |
Michael Moss | 9c28af4 | 2021-10-25 16:59:05 +0000 | [diff] [blame] | 518 | def CallGerritApi(host, path, **kwargs): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 519 | """Helper for calling a Gerrit API that returns a JSON response.""" |
| 520 | conn_kwargs = {} |
| 521 | conn_kwargs.update( |
| 522 | (k, kwargs[k]) for k in ['reqtype', 'headers', 'body'] if k in kwargs) |
| 523 | conn = CreateHttpConn(host, path, **conn_kwargs) |
| 524 | read_kwargs = {} |
| 525 | read_kwargs.update( |
| 526 | (k, kwargs[k]) for k in ['accept_statuses'] if k in kwargs) |
| 527 | return ReadHttpJsonResponse(conn, **read_kwargs) |
Michael Moss | 9c28af4 | 2021-10-25 16:59:05 +0000 | [diff] [blame] | 528 | |
| 529 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 530 | def QueryChanges(host, |
| 531 | params, |
| 532 | first_param=None, |
| 533 | limit=None, |
| 534 | o_params=None, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 535 | start=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 536 | """ |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 537 | Queries a gerrit-on-borg server for changes matching query terms. |
| 538 | |
| 539 | Args: |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 540 | params: A list of key:value pairs for search parameters, as documented |
| 541 | here (e.g. ('is', 'owner') for a parameter 'is:owner'): |
| 542 | https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 543 | first_param: A change identifier |
| 544 | limit: Maximum number of results to return. |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 545 | start: how many changes to skip (starting with the most recent) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 546 | o_params: A list of additional output specifiers, as documented here: |
| 547 | https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 548 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 549 | Returns: |
| 550 | A list of json-decoded query results. |
| 551 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 552 | # Note that no attempt is made to escape special characters; YMMV. |
| 553 | if not params and not first_param: |
| 554 | raise RuntimeError('QueryChanges requires search parameters') |
| 555 | path = 'changes/?q=%s' % _QueryString(params, first_param) |
| 556 | if start: |
| 557 | path = '%s&start=%s' % (path, start) |
| 558 | if limit: |
| 559 | path = '%s&n=%d' % (path, limit) |
| 560 | if o_params: |
| 561 | path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params])) |
| 562 | return ReadHttpJsonResponse(CreateHttpConn(host, path, timeout=30.0)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 563 | |
| 564 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 565 | def GenerateAllChanges(host, |
| 566 | params, |
| 567 | first_param=None, |
| 568 | limit=500, |
| 569 | o_params=None, |
| 570 | start=None): |
| 571 | """Queries a gerrit-on-borg server for all the changes matching the query |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 572 | terms. |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 573 | |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 574 | WARNING: this is unreliable if a change matching the query is modified while |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 575 | this function is being called. |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 576 | |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 577 | A single query to gerrit-on-borg is limited on the number of results by the |
| 578 | limit parameter on the request (see QueryChanges) and the server maximum |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 579 | limit. |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 580 | |
| 581 | Args: |
Michael Achenbach | 6fbf12f | 2017-07-06 10:54:11 +0200 | [diff] [blame] | 582 | params, first_param: Refer to QueryChanges(). |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 583 | limit: Maximum number of requested changes per query. |
| 584 | o_params: Refer to QueryChanges(). |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 585 | start: Refer to QueryChanges(). |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 586 | |
| 587 | Returns: |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 588 | A generator object to the list of returned changes. |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 589 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 590 | already_returned = set() |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 591 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 592 | def at_most_once(cls): |
| 593 | for cl in cls: |
| 594 | if cl['_number'] not in already_returned: |
| 595 | already_returned.add(cl['_number']) |
| 596 | yield cl |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 597 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 598 | start = start or 0 |
| 599 | cur_start = start |
| 600 | more_changes = True |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 601 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 602 | while more_changes: |
| 603 | # This will fetch changes[start..start+limit] sorted by most recently |
| 604 | # updated. Since the rank of any change in this list can be changed any |
| 605 | # time (say user posting comment), subsequent calls may overalp like |
| 606 | # this: > initial order ABCDEFGH query[0..3] => ABC > E gets updated. |
| 607 | # New order: EABCDFGH query[3..6] => CDF # C is a dup query[6..9] => |
| 608 | # GH # E is missed. |
| 609 | page = QueryChanges(host, params, first_param, limit, o_params, |
| 610 | cur_start) |
| 611 | for cl in at_most_once(page): |
| 612 | yield cl |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 613 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 614 | more_changes = [cl for cl in page if '_more_changes' in cl] |
| 615 | if len(more_changes) > 1: |
| 616 | raise GerritError( |
| 617 | 200, |
| 618 | 'Received %d changes with a _more_changes attribute set but should ' |
| 619 | 'receive at most one.' % len(more_changes)) |
| 620 | if more_changes: |
| 621 | cur_start += len(page) |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 622 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 623 | # If we paged through, query again the first page which in most |
| 624 | # circumstances will fetch all changes that were modified while this |
| 625 | # function was run. |
| 626 | if start != cur_start: |
| 627 | page = QueryChanges(host, params, first_param, limit, o_params, start) |
| 628 | for cl in at_most_once(page): |
| 629 | yield cl |
deymo@chromium.org | f8be276 | 2013-11-06 01:01:59 +0000 | [diff] [blame] | 630 | |
| 631 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 632 | def MultiQueryChanges(host, |
| 633 | params, |
| 634 | change_list, |
| 635 | limit=None, |
| 636 | o_params=None, |
Andrii Shyshkalov | 892e9c2 | 2017-03-08 16:21:21 +0100 | [diff] [blame] | 637 | start=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 638 | """Initiate a query composed of multiple sets of query parameters.""" |
| 639 | if not change_list: |
| 640 | raise RuntimeError( |
| 641 | "MultiQueryChanges requires a list of change numbers/id's") |
| 642 | q = [ |
| 643 | 'q=%s' % '+OR+'.join([urllib.parse.quote(str(x)) for x in change_list]) |
| 644 | ] |
| 645 | if params: |
| 646 | q.append(_QueryString(params)) |
| 647 | if limit: |
| 648 | q.append('n=%d' % limit) |
| 649 | if start: |
| 650 | q.append('S=%s' % start) |
| 651 | if o_params: |
| 652 | q.extend(['o=%s' % p for p in o_params]) |
| 653 | path = 'changes/?%s' % '&'.join(q) |
| 654 | try: |
| 655 | result = ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 656 | except GerritError as e: |
| 657 | msg = '%s:\n%s' % (e.message, path) |
| 658 | raise GerritError(e.http_status, msg) |
| 659 | return result |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 660 | |
| 661 | |
| 662 | def GetGerritFetchUrl(host): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 663 | """Given a Gerrit host name returns URL of a Gerrit instance to fetch from.""" |
| 664 | return '%s://%s/' % (GERRIT_PROTOCOL, host) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 665 | |
| 666 | |
Edward Lemur | 687ca90 | 2018-12-05 02:30:30 +0000 | [diff] [blame] | 667 | def GetCodeReviewTbrScore(host, project): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 668 | """Given a Gerrit host name and project, return the Code-Review score for TBR. |
Edward Lemur | 687ca90 | 2018-12-05 02:30:30 +0000 | [diff] [blame] | 669 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 670 | conn = CreateHttpConn(host, |
| 671 | '/projects/%s' % urllib.parse.quote(project, '')) |
| 672 | project = ReadHttpJsonResponse(conn) |
| 673 | if ('labels' not in project or 'Code-Review' not in project['labels'] |
| 674 | or 'values' not in project['labels']['Code-Review']): |
| 675 | return 1 |
| 676 | return max([int(x) for x in project['labels']['Code-Review']['values']]) |
Edward Lemur | 687ca90 | 2018-12-05 02:30:30 +0000 | [diff] [blame] | 677 | |
| 678 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 679 | def GetChangePageUrl(host, change_number): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 680 | """Given a Gerrit host name and change number, returns change page URL.""" |
| 681 | return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 682 | |
| 683 | |
| 684 | def GetChangeUrl(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 685 | """Given a Gerrit host name and change ID, returns a URL for the change.""" |
| 686 | return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 687 | |
| 688 | |
| 689 | def GetChange(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 690 | """Queries a Gerrit server for information about a single change.""" |
| 691 | path = 'changes/%s' % change |
| 692 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 693 | |
| 694 | |
Aaron Gable | 6f5a8d9 | 2017-04-18 14:49:05 -0700 | [diff] [blame] | 695 | def GetChangeDetail(host, change, o_params=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 696 | """Queries a Gerrit server for extended information about a single change.""" |
| 697 | path = 'changes/%s/detail' % change |
| 698 | if o_params: |
| 699 | path += '?%s' % '&'.join(['o=%s' % p for p in o_params]) |
| 700 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 701 | |
| 702 | |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 703 | def GetChangeCommit(host, change, revision='current'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 704 | """Query a Gerrit server for a revision associated with a change.""" |
| 705 | path = 'changes/%s/revisions/%s/commit?links' % (change, revision) |
| 706 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
agable | 32978d9 | 2016-11-01 12:55:02 -0700 | [diff] [blame] | 707 | |
| 708 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 709 | def GetChangeCurrentRevision(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 710 | """Get information about the latest revision for a given change.""" |
| 711 | return QueryChanges(host, [], change, o_params=('CURRENT_REVISION', )) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 712 | |
| 713 | |
| 714 | def GetChangeRevisions(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 715 | """Gets information about all revisions associated with a change.""" |
| 716 | return QueryChanges(host, [], change, o_params=('ALL_REVISIONS', )) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 717 | |
| 718 | |
| 719 | def GetChangeReview(host, change, revision=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 720 | """Gets the current review information for a change.""" |
| 721 | if not revision: |
| 722 | jmsg = GetChangeRevisions(host, change) |
| 723 | if not jmsg: |
| 724 | return None |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 725 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 726 | if len(jmsg) > 1: |
| 727 | raise GerritError( |
| 728 | 200, 'Multiple changes found for ChangeId %s.' % change) |
| 729 | revision = jmsg[0]['current_revision'] |
| 730 | path = 'changes/%s/revisions/%s/review' |
| 731 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 732 | |
| 733 | |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 734 | def GetChangeComments(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 735 | """Get the line- and file-level comments on a change.""" |
| 736 | path = 'changes/%s/comments' % change |
| 737 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
Aaron Gable | 0ffdf2d | 2017-06-05 13:01:17 -0700 | [diff] [blame] | 738 | |
| 739 | |
Quinten Yearsley | 0e617c0 | 2019-02-20 00:37:03 +0000 | [diff] [blame] | 740 | def GetChangeRobotComments(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 741 | """Gets the line- and file-level robot comments on a change.""" |
| 742 | path = 'changes/%s/robotcomments' % change |
| 743 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
Quinten Yearsley | 0e617c0 | 2019-02-20 00:37:03 +0000 | [diff] [blame] | 744 | |
| 745 | |
Marco Georgaklis | 85557a0 | 2021-06-03 15:56:54 +0000 | [diff] [blame] | 746 | def GetRelatedChanges(host, change, revision='current'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 747 | """Gets the related changes for a given change and revision.""" |
| 748 | path = 'changes/%s/revisions/%s/related' % (change, revision) |
| 749 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
Marco Georgaklis | 85557a0 | 2021-06-03 15:56:54 +0000 | [diff] [blame] | 750 | |
| 751 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 752 | def AbandonChange(host, change, msg=''): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 753 | """Abandons a Gerrit change.""" |
| 754 | path = 'changes/%s/abandon' % change |
| 755 | body = {'message': msg} if msg else {} |
| 756 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 757 | return ReadHttpJsonResponse(conn) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 758 | |
| 759 | |
Josip Sokcevic | c39ab99 | 2020-09-24 20:09:15 +0000 | [diff] [blame] | 760 | def MoveChange(host, change, destination_branch): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 761 | """Move a Gerrit change to different destination branch.""" |
| 762 | path = 'changes/%s/move' % change |
| 763 | body = {'destination_branch': destination_branch, 'keep_all_votes': True} |
| 764 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 765 | return ReadHttpJsonResponse(conn) |
Josip Sokcevic | c39ab99 | 2020-09-24 20:09:15 +0000 | [diff] [blame] | 766 | |
| 767 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 768 | def RestoreChange(host, change, msg=''): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 769 | """Restores a previously abandoned change.""" |
| 770 | path = 'changes/%s/restore' % change |
| 771 | body = {'message': msg} if msg else {} |
| 772 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 773 | return ReadHttpJsonResponse(conn) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 774 | |
| 775 | |
Xinan Lin | 1bd4ffa | 2021-07-28 00:54:22 +0000 | [diff] [blame] | 776 | def SubmitChange(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 777 | """Submits a Gerrit change via Gerrit.""" |
| 778 | path = 'changes/%s/submit' % change |
| 779 | conn = CreateHttpConn(host, path, reqtype='POST') |
| 780 | return ReadHttpJsonResponse(conn) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 781 | |
| 782 | |
Xinan Lin | 2b4ec95 | 2021-08-20 17:35:29 +0000 | [diff] [blame] | 783 | def GetChangesSubmittedTogether(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 784 | """Get all changes submitted with the given one.""" |
| 785 | path = 'changes/%s/submitted_together?o=NON_VISIBLE_CHANGES' % change |
| 786 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 787 | return ReadHttpJsonResponse(conn) |
Xinan Lin | 2b4ec95 | 2021-08-20 17:35:29 +0000 | [diff] [blame] | 788 | |
| 789 | |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 790 | def PublishChangeEdit(host, change, notify=True): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 791 | """Publish a Gerrit change edit.""" |
| 792 | path = 'changes/%s/edit:publish' % change |
| 793 | body = {'notify': 'ALL' if notify else 'NONE'} |
| 794 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 795 | return ReadHttpJsonResponse(conn, accept_statuses=(204, )) |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 796 | |
| 797 | |
| 798 | def ChangeEdit(host, change, path, data): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 799 | """Puts content of a file into a change edit.""" |
| 800 | path = 'changes/%s/edit/%s' % (change, urllib.parse.quote(path, '')) |
| 801 | body = { |
| 802 | 'binary_content': |
| 803 | 'data:text/plain;base64,%s' % |
| 804 | base64.b64encode(data.encode('utf-8')).decode('utf-8') |
| 805 | } |
| 806 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 807 | return ReadHttpJsonResponse(conn, accept_statuses=(204, 409)) |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 808 | |
| 809 | |
Leszek Swirski | c1c45f8 | 2022-06-09 16:21:07 +0000 | [diff] [blame] | 810 | def SetChangeEditMessage(host, change, message): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 811 | """Sets the commit message of a change edit.""" |
| 812 | path = 'changes/%s/edit:message' % change |
| 813 | body = {'message': message} |
| 814 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 815 | return ReadHttpJsonResponse(conn, accept_statuses=(204, 409)) |
Leszek Swirski | c1c45f8 | 2022-06-09 16:21:07 +0000 | [diff] [blame] | 816 | |
| 817 | |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 818 | def HasPendingChangeEdit(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 819 | conn = CreateHttpConn(host, 'changes/%s/edit' % change) |
| 820 | try: |
| 821 | ReadHttpResponse(conn) |
| 822 | except GerritError as e: |
| 823 | # 204 No Content means no pending change. |
| 824 | if e.http_status == 204: |
| 825 | return False |
| 826 | raise |
| 827 | return True |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 828 | |
| 829 | |
| 830 | def DeletePendingChangeEdit(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 831 | conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE') |
| 832 | # On success, Gerrit returns status 204; if the edit was already deleted it |
| 833 | # returns 404. Anything else is an error. |
| 834 | ReadHttpResponse(conn, accept_statuses=[204, 404]) |
dsansome | e2d6fd9 | 2016-09-08 00:10:47 -0700 | [diff] [blame] | 835 | |
| 836 | |
Leszek Swirski | c1c45f8 | 2022-06-09 16:21:07 +0000 | [diff] [blame] | 837 | def CherryPick(host, change, destination, revision='current'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 838 | """Create a cherry-pick commit from the given change, onto the given |
Leszek Swirski | c1c45f8 | 2022-06-09 16:21:07 +0000 | [diff] [blame] | 839 | destination. |
| 840 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 841 | path = 'changes/%s/revisions/%s/cherrypick' % (change, revision) |
| 842 | body = {'destination': destination} |
| 843 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 844 | return ReadHttpJsonResponse(conn) |
Leszek Swirski | c1c45f8 | 2022-06-09 16:21:07 +0000 | [diff] [blame] | 845 | |
| 846 | |
| 847 | def GetFileContents(host, change, path): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 848 | """Get the contents of a file with the given path in the given revision. |
Leszek Swirski | c1c45f8 | 2022-06-09 16:21:07 +0000 | [diff] [blame] | 849 | |
| 850 | Returns: |
| 851 | A bytes object with the file's contents. |
| 852 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 853 | path = 'changes/%s/revisions/current/files/%s/content' % ( |
| 854 | change, urllib.parse.quote(path, '')) |
| 855 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 856 | return base64.b64decode(ReadHttpResponse(conn).read()) |
Leszek Swirski | c1c45f8 | 2022-06-09 16:21:07 +0000 | [diff] [blame] | 857 | |
| 858 | |
Andrii Shyshkalov | ea4fc83 | 2016-12-01 14:53:23 +0100 | [diff] [blame] | 859 | def SetCommitMessage(host, change, description, notify='ALL'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 860 | """Updates a commit message.""" |
| 861 | assert notify in ('ALL', 'NONE') |
| 862 | path = 'changes/%s/message' % change |
| 863 | body = {'message': description, 'notify': notify} |
| 864 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 865 | try: |
| 866 | ReadHttpResponse(conn, accept_statuses=[200, 204]) |
| 867 | except GerritError as e: |
| 868 | raise GerritError( |
| 869 | e.http_status, |
| 870 | 'Received unexpected http status while editing message ' |
| 871 | 'in change %s' % change) |
scottmg@chromium.org | 6d1266e | 2016-04-26 11:12:26 +0000 | [diff] [blame] | 872 | |
| 873 | |
Xinan Lin | c2fb26a | 2021-07-27 18:01:55 +0000 | [diff] [blame] | 874 | def GetCommitIncludedIn(host, project, commit): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 875 | """Retrieves the branches and tags for a given commit. |
Xinan Lin | c2fb26a | 2021-07-27 18:01:55 +0000 | [diff] [blame] | 876 | |
| 877 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-included-in |
| 878 | |
| 879 | Returns: |
| 880 | A JSON object with keys of 'branches' and 'tags'. |
| 881 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 882 | path = 'projects/%s/commits/%s/in' % (urllib.parse.quote(project, |
| 883 | ''), commit) |
| 884 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 885 | return ReadHttpJsonResponse(conn, accept_statuses=[200]) |
Xinan Lin | c2fb26a | 2021-07-27 18:01:55 +0000 | [diff] [blame] | 886 | |
| 887 | |
Edward Lesmes | 8170c29 | 2021-03-19 20:04:43 +0000 | [diff] [blame] | 888 | def IsCodeOwnersEnabledOnHost(host): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 889 | """Check if the code-owners plugin is enabled for the host.""" |
| 890 | path = 'config/server/capabilities' |
| 891 | capabilities = ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 892 | return 'code-owners-checkCodeOwner' in capabilities |
Edward Lesmes | 110823b | 2021-02-05 21:42:27 +0000 | [diff] [blame] | 893 | |
| 894 | |
Edward Lesmes | 8170c29 | 2021-03-19 20:04:43 +0000 | [diff] [blame] | 895 | def IsCodeOwnersEnabledOnRepo(host, repo): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 896 | """Check if the code-owners plugin is enabled for the repo.""" |
| 897 | repo = PercentEncodeForGitRef(repo) |
| 898 | path = '/projects/%s/code_owners.project_config' % repo |
| 899 | config = ReadHttpJsonResponse(CreateHttpConn(host, path)) |
| 900 | return not config['status'].get('disabled', False) |
Edward Lesmes | 8170c29 | 2021-03-19 20:04:43 +0000 | [diff] [blame] | 901 | |
| 902 | |
Gavin Mak | e0fee9f | 2022-08-10 23:41:55 +0000 | [diff] [blame] | 903 | def GetOwnersForFile(host, |
| 904 | project, |
| 905 | branch, |
| 906 | path, |
| 907 | limit=100, |
| 908 | resolve_all_users=True, |
| 909 | highest_score_only=False, |
| 910 | seed=None, |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 911 | o_params=('DETAILS', )): |
| 912 | """Gets information about owners attached to a file.""" |
| 913 | path = 'projects/%s/branches/%s/code_owners/%s' % (urllib.parse.quote( |
| 914 | project, ''), urllib.parse.quote(branch, |
| 915 | ''), urllib.parse.quote(path, '')) |
| 916 | q = ['resolve-all-users=%s' % json.dumps(resolve_all_users)] |
| 917 | if highest_score_only: |
| 918 | q.append('highest-score-only=%s' % json.dumps(highest_score_only)) |
| 919 | if seed: |
| 920 | q.append('seed=%d' % seed) |
| 921 | if limit: |
| 922 | q.append('n=%d' % limit) |
| 923 | if o_params: |
| 924 | q.extend(['o=%s' % p for p in o_params]) |
| 925 | if q: |
| 926 | path = '%s?%s' % (path, '&'.join(q)) |
| 927 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
Gavin Mak | c94b21d | 2020-12-10 20:27:32 +0000 | [diff] [blame] | 928 | |
| 929 | |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 930 | def GetReviewers(host, change): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 931 | """Gets information about all reviewers attached to a change.""" |
| 932 | path = 'changes/%s/reviewers' % change |
| 933 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 934 | |
| 935 | |
| 936 | def GetReview(host, change, revision): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 937 | """Gets review information about a specific revision of a change.""" |
| 938 | path = 'changes/%s/revisions/%s/review' % (change, revision) |
| 939 | return ReadHttpJsonResponse(CreateHttpConn(host, path)) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 940 | |
| 941 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 942 | def AddReviewers(host, |
| 943 | change, |
| 944 | reviewers=None, |
| 945 | ccs=None, |
| 946 | notify=True, |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 947 | accept_statuses=frozenset([200, 400, 422])): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 948 | """Add reviewers to a change.""" |
| 949 | if not reviewers and not ccs: |
| 950 | return None |
| 951 | if not change: |
| 952 | return None |
| 953 | reviewers = frozenset(reviewers or []) |
| 954 | ccs = frozenset(ccs or []) |
| 955 | path = 'changes/%s/revisions/current/review' % change |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 956 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 957 | body = { |
| 958 | 'drafts': 'KEEP', |
| 959 | 'reviewers': [], |
| 960 | 'notify': 'ALL' if notify else 'NONE', |
| 961 | } |
| 962 | for r in sorted(reviewers | ccs): |
| 963 | state = 'REVIEWER' if r in reviewers else 'CC' |
| 964 | body['reviewers'].append({ |
| 965 | 'reviewer': r, |
| 966 | 'state': state, |
| 967 | 'notify': 'NONE', # We handled `notify` argument above. |
| 968 | }) |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 969 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 970 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 971 | # Gerrit will return 400 if one or more of the requested reviewers are |
| 972 | # unprocessable. We read the response object to see which were rejected, |
| 973 | # warn about them, and retry with the remainder. |
| 974 | resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses) |
Aaron Gable | 6dadfbf | 2017-05-09 14:27:58 -0700 | [diff] [blame] | 975 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 976 | errored = set() |
| 977 | for result in resp.get('reviewers', {}).values(): |
| 978 | r = result.get('input') |
| 979 | state = 'REVIEWER' if r in reviewers else 'CC' |
| 980 | if result.get('error'): |
| 981 | errored.add(r) |
| 982 | LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower())) |
| 983 | if errored: |
| 984 | # Try again, adding only those that didn't fail, and only accepting 200. |
| 985 | AddReviewers(host, |
| 986 | change, |
| 987 | reviewers=(reviewers - errored), |
| 988 | ccs=(ccs - errored), |
| 989 | notify=notify, |
| 990 | accept_statuses=[200]) |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 991 | |
| 992 | |
Aaron Gable | 636b13f | 2017-07-14 10:42:48 -0700 | [diff] [blame] | 993 | def SetReview(host, change, msg=None, labels=None, notify=None, ready=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 994 | """Sets labels and/or adds a message to a code review.""" |
| 995 | if not msg and not labels: |
| 996 | return |
| 997 | path = 'changes/%s/revisions/current/review' % change |
| 998 | body = {'drafts': 'KEEP'} |
| 999 | if msg: |
| 1000 | body['message'] = msg |
| 1001 | if labels: |
| 1002 | body['labels'] = labels |
| 1003 | if notify is not None: |
| 1004 | body['notify'] = 'ALL' if notify else 'NONE' |
| 1005 | if ready: |
| 1006 | body['ready'] = True |
| 1007 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 1008 | response = ReadHttpJsonResponse(conn) |
| 1009 | if labels: |
| 1010 | for key, val in labels.items(): |
| 1011 | if ('labels' not in response or key not in response['labels'] |
| 1012 | or int(response['labels'][key] != int(val))): |
| 1013 | raise GerritError( |
| 1014 | 200, |
| 1015 | 'Unable to set "%s" label on change %s.' % (key, change)) |
| 1016 | return response |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 1017 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1018 | |
| 1019 | def ResetReviewLabels(host, |
| 1020 | change, |
| 1021 | label, |
| 1022 | value='0', |
| 1023 | message=None, |
szager@chromium.org | b469623 | 2013-10-16 19:45:35 +0000 | [diff] [blame] | 1024 | notify=None): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1025 | """Resets the value of a given label for all reviewers on a change.""" |
| 1026 | # This is tricky, because we want to work on the "current revision", but |
| 1027 | # there's always the risk that "current revision" will change in between |
| 1028 | # API calls. So, we check "current revision" at the beginning and end; if |
| 1029 | # it has changed, raise an exception. |
| 1030 | jmsg = GetChangeCurrentRevision(host, change) |
| 1031 | if not jmsg: |
| 1032 | raise GerritError( |
| 1033 | 200, 'Could not get review information for change "%s"' % change) |
| 1034 | value = str(value) |
| 1035 | revision = jmsg[0]['current_revision'] |
| 1036 | path = 'changes/%s/revisions/%s/review' % (change, revision) |
| 1037 | message = message or ('%s label set to %s programmatically.' % |
| 1038 | (label, value)) |
| 1039 | jmsg = GetReview(host, change, revision) |
| 1040 | if not jmsg: |
| 1041 | raise GerritError( |
| 1042 | 200, 'Could not get review information for revision %s ' |
| 1043 | 'of change %s' % (revision, change)) |
| 1044 | for review in jmsg.get('labels', {}).get(label, {}).get('all', []): |
| 1045 | if str(review.get('value', value)) != value: |
| 1046 | body = { |
| 1047 | 'drafts': 'KEEP', |
| 1048 | 'message': message, |
| 1049 | 'labels': { |
| 1050 | label: value |
| 1051 | }, |
| 1052 | 'on_behalf_of': review['_account_id'], |
| 1053 | } |
| 1054 | if notify: |
| 1055 | body['notify'] = notify |
| 1056 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 1057 | response = ReadHttpJsonResponse(conn) |
| 1058 | if str(response['labels'][label]) != value: |
| 1059 | username = review.get('email', jmsg.get('name', '')) |
| 1060 | raise GerritError( |
| 1061 | 200, 'Unable to set %s label for user "%s"' |
| 1062 | ' on change %s.' % (label, username, change)) |
| 1063 | jmsg = GetChangeCurrentRevision(host, change) |
| 1064 | if not jmsg: |
| 1065 | raise GerritError( |
| 1066 | 200, 'Could not get review information for change "%s"' % change) |
Aravind Vasudevan | c5f0cbb | 2022-01-24 23:56:57 +0000 | [diff] [blame] | 1067 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1068 | if jmsg[0]['current_revision'] != revision: |
| 1069 | raise GerritError( |
| 1070 | 200, 'While resetting labels on change "%s", ' |
| 1071 | 'a new patchset was uploaded.' % change) |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 1072 | |
| 1073 | |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 1074 | def CreateChange(host, project, branch='main', subject='', params=()): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1075 | """ |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 1076 | Creates a new change. |
| 1077 | |
| 1078 | Args: |
| 1079 | params: A list of additional ChangeInput specifiers, as documented here: |
| 1080 | (e.g. ('is_private', 'true') to mark the change private. |
| 1081 | https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-input |
| 1082 | |
| 1083 | Returns: |
| 1084 | ChangeInfo for the new change. |
| 1085 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1086 | path = 'changes/' |
| 1087 | body = {'project': project, 'branch': branch, 'subject': subject} |
| 1088 | body.update(dict(params)) |
| 1089 | for key in 'project', 'branch', 'subject': |
| 1090 | if not body[key]: |
| 1091 | raise GerritError(200, '%s is required' % key.title()) |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 1092 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1093 | conn = CreateHttpConn(host, path, reqtype='POST', body=body) |
| 1094 | return ReadHttpJsonResponse(conn, accept_statuses=[201]) |
LaMont Jones | 9eed423 | 2021-04-02 16:29:49 +0000 | [diff] [blame] | 1095 | |
| 1096 | |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1097 | def CreateGerritBranch(host, project, branch, commit): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1098 | """Creates a new branch from given project and commit |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1099 | |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1100 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch |
| 1101 | |
| 1102 | Returns: |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1103 | A JSON object with 'ref' key. |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1104 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1105 | path = 'projects/%s/branches/%s' % (project, branch) |
| 1106 | body = {'revision': commit} |
| 1107 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 1108 | response = ReadHttpJsonResponse(conn, accept_statuses=[201, 409]) |
| 1109 | if response: |
| 1110 | return response |
| 1111 | raise GerritError(200, 'Unable to create gerrit branch') |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1112 | |
| 1113 | |
Michael Moss | b6ce244 | 2021-10-20 04:36:24 +0000 | [diff] [blame] | 1114 | def CreateGerritTag(host, project, tag, commit): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1115 | """Creates a new tag at the given commit. |
Michael Moss | b6ce244 | 2021-10-20 04:36:24 +0000 | [diff] [blame] | 1116 | |
| 1117 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-tag |
| 1118 | |
| 1119 | Returns: |
| 1120 | A JSON object with 'ref' key. |
| 1121 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1122 | path = 'projects/%s/tags/%s' % (project, tag) |
| 1123 | body = {'revision': commit} |
| 1124 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 1125 | response = ReadHttpJsonResponse(conn, accept_statuses=[201]) |
| 1126 | if response: |
| 1127 | return response |
| 1128 | raise GerritError(200, 'Unable to create gerrit tag') |
Michael Moss | b6ce244 | 2021-10-20 04:36:24 +0000 | [diff] [blame] | 1129 | |
| 1130 | |
Josip Sokcevic | df9a802 | 2020-12-08 00:10:19 +0000 | [diff] [blame] | 1131 | def GetHead(host, project): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1132 | """Retrieves current HEAD of Gerrit project |
Josip Sokcevic | df9a802 | 2020-12-08 00:10:19 +0000 | [diff] [blame] | 1133 | |
| 1134 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head |
| 1135 | |
| 1136 | Returns: |
| 1137 | A JSON object with 'ref' key. |
| 1138 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1139 | path = 'projects/%s/HEAD' % (project) |
| 1140 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 1141 | response = ReadHttpJsonResponse(conn, accept_statuses=[200]) |
| 1142 | if response: |
| 1143 | return response |
| 1144 | raise GerritError(200, 'Unable to update gerrit HEAD') |
Josip Sokcevic | df9a802 | 2020-12-08 00:10:19 +0000 | [diff] [blame] | 1145 | |
| 1146 | |
| 1147 | def UpdateHead(host, project, branch): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1148 | """Updates Gerrit HEAD to point to branch |
Josip Sokcevic | df9a802 | 2020-12-08 00:10:19 +0000 | [diff] [blame] | 1149 | |
| 1150 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head |
| 1151 | |
| 1152 | Returns: |
| 1153 | A JSON object with 'ref' key. |
| 1154 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1155 | path = 'projects/%s/HEAD' % (project) |
| 1156 | body = {'ref': branch} |
| 1157 | conn = CreateHttpConn(host, path, reqtype='PUT', body=body) |
| 1158 | response = ReadHttpJsonResponse(conn, accept_statuses=[200]) |
| 1159 | if response: |
| 1160 | return response |
| 1161 | raise GerritError(200, 'Unable to update gerrit HEAD') |
Josip Sokcevic | df9a802 | 2020-12-08 00:10:19 +0000 | [diff] [blame] | 1162 | |
| 1163 | |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1164 | def GetGerritBranch(host, project, branch): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1165 | """Gets a branch info from given project and branch name. |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1166 | |
| 1167 | See: |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1168 | https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch |
| 1169 | |
| 1170 | Returns: |
Xinan Lin | af79f24 | 2021-08-09 21:23:58 +0000 | [diff] [blame] | 1171 | A JSON object with 'revision' key if the branch exists, otherwise None. |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1172 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1173 | path = 'projects/%s/branches/%s' % (project, branch) |
| 1174 | conn = CreateHttpConn(host, path, reqtype='GET') |
| 1175 | return ReadHttpJsonResponse(conn, accept_statuses=[200, 404]) |
dimu | 833c94c | 2017-01-18 17:36:15 -0800 | [diff] [blame] | 1176 | |
| 1177 | |
Josip Sokcevic | f736cab | 2020-10-20 23:41:38 +0000 | [diff] [blame] | 1178 | def GetProjectHead(host, project): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1179 | conn = CreateHttpConn(host, |
| 1180 | '/projects/%s/HEAD' % urllib.parse.quote(project, '')) |
| 1181 | return ReadHttpJsonResponse(conn, accept_statuses=[200]) |
Josip Sokcevic | f736cab | 2020-10-20 23:41:38 +0000 | [diff] [blame] | 1182 | |
| 1183 | |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1184 | def GetAccountDetails(host, account_id='self'): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1185 | """Returns details of the account. |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1186 | |
| 1187 | If account_id is not given, uses magic value 'self' which corresponds to |
| 1188 | whichever account user is authenticating as. |
| 1189 | |
| 1190 | Documentation: |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1191 | https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 1192 | |
| 1193 | Returns None if account is not found (i.e., Gerrit returned 404). |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1194 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1195 | conn = CreateHttpConn(host, '/accounts/%s' % account_id) |
| 1196 | return ReadHttpJsonResponse(conn, accept_statuses=[200, 404]) |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 1197 | |
| 1198 | |
| 1199 | def ValidAccounts(host, accounts, max_threads=10): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1200 | """Returns a mapping from valid account to its details. |
Andrii Shyshkalov | ba7b0a4 | 2018-10-15 03:20:35 +0000 | [diff] [blame] | 1201 | |
| 1202 | Invalid accounts, either not existing or without unique match, |
| 1203 | are not present as returned dictionary keys. |
| 1204 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1205 | assert not isinstance(accounts, str), type(accounts) |
| 1206 | accounts = list(set(accounts)) |
| 1207 | if not accounts: |
| 1208 | return {} |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1209 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1210 | def get_one(account): |
| 1211 | try: |
| 1212 | return account, GetAccountDetails(host, account) |
| 1213 | except GerritError: |
| 1214 | return None, None |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1215 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1216 | valid = {} |
| 1217 | with contextlib.closing(ThreadPool(min(max_threads, |
| 1218 | len(accounts)))) as pool: |
| 1219 | for account, details in pool.map(get_one, accounts): |
| 1220 | if account and details: |
| 1221 | valid[account] = details |
| 1222 | return valid |
Andrii Shyshkalov | bb86fbb | 2017-03-24 14:59:28 +0100 | [diff] [blame] | 1223 | |
| 1224 | |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame] | 1225 | def PercentEncodeForGitRef(original): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1226 | """Applies percent-encoding for strings sent to Gerrit via git ref metadata. |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame] | 1227 | |
Quinten Yearsley | d9cbe7a | 2019-09-03 16:49:11 +0000 | [diff] [blame] | 1228 | The encoding used is based on but stricter than URL encoding (Section 2.1 of |
| 1229 | RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE' |
| 1230 | (U+0020) can be represented as 'LOW LINE' (U+005F) or 'PLUS SIGN' (U+002B). |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame] | 1231 | |
| 1232 | For more information, see the Gerrit docs here: |
| 1233 | |
| 1234 | https://gerrit-review.googlesource.com/Documentation/user-upload.html#message |
| 1235 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1236 | safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ' |
| 1237 | encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original) |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame] | 1238 | |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1239 | # Spaces are not allowed in git refs; gerrit will interpret either '_' or |
| 1240 | # '+' (or '%20') as space. Use '_' since that has been supported the |
| 1241 | # longest. |
| 1242 | return encoded.replace(' ', '_') |
Nick Carter | 8692b18 | 2017-11-06 16:30:38 -0800 | [diff] [blame] | 1243 | |
| 1244 | |
Dan Jacques | 8d11e48 | 2016-11-15 14:25:56 -0800 | [diff] [blame] | 1245 | @contextlib.contextmanager |
| 1246 | def tempdir(): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1247 | tdir = None |
| 1248 | try: |
| 1249 | tdir = tempfile.mkdtemp(suffix='gerrit_util') |
| 1250 | yield tdir |
| 1251 | finally: |
| 1252 | if tdir: |
| 1253 | gclient_utils.rmtree(tdir) |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 1254 | |
| 1255 | |
| 1256 | def ChangeIdentifier(project, change_number): |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1257 | """Returns change identifier "project~number" suitable for |change| arg of |
Andrii Shyshkalov | 0ec9d15 | 2018-08-23 00:22:58 +0000 | [diff] [blame] | 1258 | this module API. |
| 1259 | |
| 1260 | Such format is allows for more efficient Gerrit routing of HTTP requests, |
| 1261 | comparing to specifying just change_number. |
| 1262 | """ |
Mike Frysinger | 124bb8e | 2023-09-06 05:48:55 +0000 | [diff] [blame] | 1263 | assert int(change_number) |
| 1264 | return '%s~%s' % (urllib.parse.quote(project, ''), change_number) |