blob: 1aeb94c51a47ec5b7415ebe55af2a17f14d2dbab [file] [log] [blame]
szager@chromium.orgb4696232013-10-16 19:45:35 +00001# 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.
4
5"""
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00006Utilities for requesting information for a Gerrit server via HTTPS.
szager@chromium.orgb4696232013-10-16 19:45:35 +00007
8https://gerrit-review.googlesource.com/Documentation/rest-api.html
9"""
10
11import base64
Dan Jacques8d11e482016-11-15 14:25:56 -080012import contextlib
Edward Lemur202c5592019-10-21 22:44:52 +000013import httplib2
szager@chromium.orgb4696232013-10-16 19:45:35 +000014import json
15import logging
16import netrc
17import os
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +000018import random
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000019import re
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000020import socket
szager@chromium.orgf202a252014-05-27 18:55:52 +000021import stat
22import sys
Dan Jacques8d11e482016-11-15 14:25:56 -080023import tempfile
szager@chromium.orgb4696232013-10-16 19:45:35 +000024import time
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +000025from multiprocessing.pool import ThreadPool
szager@chromium.orgb4696232013-10-16 19:45:35 +000026
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -070027import auth
Dan Jacques8d11e482016-11-15 14:25:56 -080028import gclient_utils
Edward Lemur5a9ff432018-10-30 19:00:22 +000029import metrics
30import metrics_utils
Aaron Gable8797cab2018-03-06 13:55:00 -080031import subprocess2
szager@chromium.orgf202a252014-05-27 18:55:52 +000032
Edward Lemur4ba192e2019-10-28 20:19:37 +000033from six.moves import urllib
34
Gavin Makcc976552023-08-28 17:01:52 +000035import http.cookiejar
36from io import StringIO
Edward Lemur4ba192e2019-10-28 20:19:37 +000037
szager@chromium.orgb4696232013-10-16 19:45:35 +000038LOGGER = logging.getLogger()
Gavin Makfc75af32023-06-20 20:06:27 +000039# With a starting sleep time of 12.0 seconds, x <= [1.8-2.2]x backoff, and six
40# total tries, the sleep time between the first and last tries will be ~6 min
41# (excluding time for each try).
42TRY_LIMIT = 6
43SLEEP_TIME = 12.0
George Engelbrecht888c0fe2020-04-17 15:00:20 +000044MAX_BACKOFF = 2.2
45MIN_BACKOFF = 1.8
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000046
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000047# Controls the transport protocol used to communicate with Gerrit.
szager@chromium.orgb4696232013-10-16 19:45:35 +000048# This is parameterized primarily to enable GerritTestCase.
49GERRIT_PROTOCOL = 'https'
50
51
Edward Lemur4ba192e2019-10-28 20:19:37 +000052def time_sleep(seconds):
53 # Use this so that it can be mocked in tests without interfering with python
54 # system machinery.
55 return time.sleep(seconds)
56
57
Edward Lemura3b6fd02020-03-02 22:16:15 +000058def time_time():
59 # Use this so that it can be mocked in tests without interfering with python
60 # system machinery.
61 return time.time()
62
63
Ben Pastene9519fc12023-04-12 22:15:43 +000064def log_retry_and_sleep(seconds, attempt):
65 LOGGER.info('Will retry in %d seconds (%d more times)...', seconds,
66 TRY_LIMIT - attempt - 1)
67 time_sleep(seconds)
68 return seconds * random.uniform(MIN_BACKOFF, MAX_BACKOFF)
69
70
szager@chromium.orgb4696232013-10-16 19:45:35 +000071class GerritError(Exception):
72 """Exception class for errors commuicating with the gerrit-on-borg service."""
Edward Lemur4ba192e2019-10-28 20:19:37 +000073 def __init__(self, http_status, message, *args, **kwargs):
szager@chromium.orgb4696232013-10-16 19:45:35 +000074 super(GerritError, self).__init__(*args, **kwargs)
75 self.http_status = http_status
Edward Lemur4ba192e2019-10-28 20:19:37 +000076 self.message = '(%d) %s' % (self.http_status, message)
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000077
Josip Sokcevicdf9a8022020-12-08 00:10:19 +000078 def __str__(self):
79 return self.message
80
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000081
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020082def _QueryString(params, first_param=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +000083 """Encodes query parameters in the key:val[+key:val...] format specified here:
84
85 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
86 """
Edward Lemur4ba192e2019-10-28 20:19:37 +000087 q = [urllib.parse.quote(first_param)] if first_param else []
Josip Sokcevicf5c6d8a2021-05-12 18:23:24 +000088 q.extend(['%s:%s' % (key, val.replace(" ", "+")) for key, val in params])
szager@chromium.orgb4696232013-10-16 19:45:35 +000089 return '+'.join(q)
90
91
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000092class Authenticator(object):
93 """Base authenticator class for authenticator implementations to subclass."""
94
95 def get_auth_header(self, host):
96 raise NotImplementedError()
97
98 @staticmethod
99 def get():
100 """Returns: (Authenticator) The identified Authenticator to use.
101
102 Probes the local system and its environment and identifies the
103 Authenticator instance to use.
104 """
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700105 # 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()
Edward Lemur57d47422020-03-06 20:43:07 +0000109 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop,
110 # and use CookiesAuthenticator instead.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000111 if GceAuthenticator.is_gce():
112 return GceAuthenticator()
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000113 return CookiesAuthenticator()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000114
115
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000116class CookiesAuthenticator(Authenticator):
117 """Authenticator implementation that uses ".netrc" or ".gitcookies" for token.
118
119 Expected case for developer workstations.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000120 """
121
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000122 _EMPTY = object()
123
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000124 def __init__(self):
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000125 # Credentials will be loaded lazily on first use. This ensures Authenticator
126 # get() can always construct an authenticator, even if something is broken.
127 # This allows 'creds-check' to proceed to actually checking creds later,
128 # rigorously (instead of blowing up with a cryptic error if they are wrong).
129 self._netrc = self._EMPTY
130 self._gitcookies = self._EMPTY
131
132 @property
133 def netrc(self):
134 if self._netrc is self._EMPTY:
135 self._netrc = self._get_netrc()
136 return self._netrc
137
138 @property
139 def gitcookies(self):
140 if self._gitcookies is self._EMPTY:
141 self._gitcookies = self._get_gitcookies()
142 return self._gitcookies
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000143
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000144 @classmethod
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200145 def get_new_password_url(cls, host):
146 assert not host.startswith('http')
147 # Assume *.googlesource.com pattern.
148 parts = host.split('.')
Aravind Vasudevana02b4bf2023-02-03 17:52:03 +0000149
150 # remove -review suffix if present.
151 if parts[0].endswith('-review'):
152 parts[0] = parts[0][:-len('-review')]
153
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200154 return 'https://%s/new-password' % ('.'.join(parts))
155
156 @classmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000157 def get_new_password_message(cls, host):
William Hessee9e89e32019-03-03 19:02:32 +0000158 if host is None:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000159 return ('Git host for Gerrit upload is unknown. Check your remote '
William Hessee9e89e32019-03-03 19:02:32 +0000160 'and the branch your branch is tracking. This tool assumes '
161 'that you are using a git server at *.googlesource.com.')
Edward Lemur67fccdf2019-10-22 22:17:10 +0000162 url = cls.get_new_password_url(host)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100163 return 'You can (re)generate your credentials by visiting %s' % url
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000164
165 @classmethod
166 def get_netrc_path(cls):
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000167 path = '_netrc' if sys.platform.startswith('win') else '.netrc'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000168 return os.path.expanduser(os.path.join('~', path))
169
170 @classmethod
171 def _get_netrc(cls):
Dan Jacques8d11e482016-11-15 14:25:56 -0800172 # Buffer the '.netrc' path. Use an empty file if it doesn't exist.
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000173 path = cls.get_netrc_path()
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000174 if not os.path.exists(path):
175 return netrc.netrc(os.devnull)
176
177 st = os.stat(path)
178 if st.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000179 print(
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000180 'WARNING: netrc file %s cannot be used because its file '
181 'permissions are insecure. netrc file permissions should be '
Raul Tambre80ee78e2019-05-06 22:41:05 +0000182 '600.' % path, file=sys.stderr)
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000183 with open(path) as fd:
184 content = fd.read()
Dan Jacques8d11e482016-11-15 14:25:56 -0800185
186 # Load the '.netrc' file. We strip comments from it because processing them
187 # can trigger a bug in Windows. See crbug.com/664664.
188 content = '\n'.join(l for l in content.splitlines()
189 if l.strip() and not l.strip().startswith('#'))
190 with tempdir() as tdir:
191 netrc_path = os.path.join(tdir, 'netrc')
192 with open(netrc_path, 'w') as fd:
193 fd.write(content)
194 os.chmod(netrc_path, (stat.S_IRUSR | stat.S_IWUSR))
195 return cls._get_netrc_from_path(netrc_path)
196
197 @classmethod
198 def _get_netrc_from_path(cls, path):
199 try:
200 return netrc.netrc(path)
201 except IOError:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000202 print('WARNING: Could not read netrc file %s' % path, file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800203 return netrc.netrc(os.devnull)
204 except netrc.NetrcParseError as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000205 print('ERROR: Cannot use netrc file %s due to a parsing error: %s' %
206 (path, e), file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800207 return netrc.netrc(os.devnull)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000208
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000209 @classmethod
210 def get_gitcookies_path(cls):
Ravi Mistry0bfa9ad2016-11-21 12:58:31 -0500211 if os.getenv('GIT_COOKIES_PATH'):
212 return os.getenv('GIT_COOKIES_PATH')
Aaron Gable8797cab2018-03-06 13:55:00 -0800213 try:
Edward Lesmes5a5537d2020-04-01 20:52:30 +0000214 path = subprocess2.check_output(
215 ['git', 'config', '--path', 'http.cookiefile'])
216 return path.decode('utf-8', 'ignore').strip()
Aaron Gable8797cab2018-03-06 13:55:00 -0800217 except subprocess2.CalledProcessError:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000218 return os.path.expanduser(os.path.join('~', '.gitcookies'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000219
220 @classmethod
221 def _get_gitcookies(cls):
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000222 gitcookies = {}
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000223 path = cls.get_gitcookies_path()
224 if not os.path.exists(path):
225 return gitcookies
226
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000227 try:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000228 f = gclient_utils.FileRead(path, 'rb').splitlines()
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000229 except IOError:
230 return gitcookies
231
Edward Lemur67fccdf2019-10-22 22:17:10 +0000232 for line in f:
233 try:
234 fields = line.strip().split('\t')
235 if line.strip().startswith('#') or len(fields) != 7:
236 continue
237 domain, xpath, key, value = fields[0], fields[2], fields[5], fields[6]
238 if xpath == '/' and key == 'o':
239 if value.startswith('git-'):
240 login, secret_token = value.split('=', 1)
241 gitcookies[domain] = (login, secret_token)
242 else:
243 gitcookies[domain] = ('', value)
244 except (IndexError, ValueError, TypeError) as exc:
245 LOGGER.warning(exc)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000246 return gitcookies
247
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100248 def _get_auth_for_host(self, host):
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000249 for domain, creds in self.gitcookies.items():
Gavin Makcc976552023-08-28 17:01:52 +0000250 if http.cookiejar.domain_match(host, domain):
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100251 return (creds[0], None, creds[1])
252 return self.netrc.authenticators(host)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000253
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100254 def get_auth_header(self, host):
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700255 a = self._get_auth_for_host(host)
256 if a:
Eric Boren2fb63102018-10-05 13:05:03 +0000257 if a[0]:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000258 secret = base64.b64encode(('%s:%s' % (a[0], a[2])).encode('utf-8'))
259 return 'Basic %s' % secret.decode('utf-8')
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000260
261 return 'Bearer %s' % a[2]
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000262 return None
263
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100264 def get_auth_email(self, host):
265 """Best effort parsing of email to be used for auth for the given host."""
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700266 a = self._get_auth_for_host(host)
267 if not a:
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100268 return None
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700269 login = a[0]
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100270 # login typically looks like 'git-xxx.example.com'
271 if not login.startswith('git-') or '.' not in login:
272 return None
273 username, domain = login[len('git-'):].split('.', 1)
274 return '%s@%s' % (username, domain)
275
Andrii Shyshkalov18975322017-01-25 16:44:13 +0100276
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000277# Backwards compatibility just in case somebody imports this outside of
278# depot_tools.
279NetrcAuthenticator = CookiesAuthenticator
280
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000281
282class GceAuthenticator(Authenticator):
283 """Authenticator implementation that uses GCE metadata service for token.
284 """
285
286 _INFO_URL = 'http://metadata.google.internal'
smut5e9401b2017-08-10 15:22:20 -0700287 _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/'
288 'service-accounts/default/token' % _INFO_URL)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000289 _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"}
290
291 _cache_is_gce = None
292 _token_cache = None
293 _token_expiration = None
294
295 @classmethod
296 def is_gce(cls):
Ravi Mistryfad941b2016-11-15 13:00:47 -0500297 if os.getenv('SKIP_GCE_AUTH_FOR_GIT'):
298 return False
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000299 if cls._cache_is_gce is None:
300 cls._cache_is_gce = cls._test_is_gce()
301 return cls._cache_is_gce
302
303 @classmethod
304 def _test_is_gce(cls):
305 # Based on https://cloud.google.com/compute/docs/metadata#runninggce
Edward Lemura3b6fd02020-03-02 22:16:15 +0000306 resp, _ = cls._get(cls._INFO_URL)
307 if resp is None:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000308 return False
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100309 return resp.get('metadata-flavor') == 'Google'
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000310
311 @staticmethod
312 def _get(url, **kwargs):
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000313 next_delay_sec = 1.0
Edward Lemura3b6fd02020-03-02 22:16:15 +0000314 for i in range(TRY_LIMIT):
Edward Lemur4ba192e2019-10-28 20:19:37 +0000315 p = urllib.parse.urlparse(url)
316 if p.scheme not in ('http', 'https'):
317 raise RuntimeError(
318 "Don't know how to work with protocol '%s'" % protocol)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000319 try:
320 resp, contents = httplib2.Http().request(url, 'GET', **kwargs)
Raphael Kubo da Costa9f6aa1b2021-06-24 16:59:31 +0000321 except (socket.error, httplib2.HttpLib2Error,
322 httplib2.socks.ProxyError) as e:
Edward Lemura3b6fd02020-03-02 22:16:15 +0000323 LOGGER.debug('GET [%s] raised %s', url, e)
324 return None, None
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000325 LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000326 if resp.status < 500:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100327 return (resp, contents)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000328
Aaron Gable92e9f382017-12-07 11:47:41 -0800329 # Retry server error status codes.
330 LOGGER.warn('Encountered server error')
331 if TRY_LIMIT - i > 1:
Ben Pastene9519fc12023-04-12 22:15:43 +0000332 next_delay_sec = log_retry_and_sleep(next_delay_sec, i)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000333 return None, None
Aaron Gable92e9f382017-12-07 11:47:41 -0800334
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000335 @classmethod
336 def _get_token_dict(cls):
Edward Lemura3b6fd02020-03-02 22:16:15 +0000337 # If cached token is valid for at least 25 seconds, return it.
338 if cls._token_cache and time_time() + 25 < cls._token_expiration:
339 return cls._token_cache
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000340
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100341 resp, contents = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000342 if resp is None or resp.status != 200:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000343 return None
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100344 cls._token_cache = json.loads(contents)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000345 cls._token_expiration = cls._token_cache['expires_in'] + time_time()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000346 return cls._token_cache
347
348 def get_auth_header(self, _host):
349 token_dict = self._get_token_dict()
350 if not token_dict:
351 return None
352 return '%(token_type)s %(access_token)s' % token_dict
353
354
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700355class LuciContextAuthenticator(Authenticator):
356 """Authenticator implementation that uses LUCI_CONTEXT ambient local auth.
357 """
358
359 @staticmethod
360 def is_luci():
361 return auth.has_luci_context_local_auth()
362
363 def __init__(self):
Edward Lemur5b929a42019-10-21 17:57:39 +0000364 self._authenticator = auth.Authenticator(
365 ' '.join([auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700366
367 def get_auth_header(self, _host):
Edward Lemur5b929a42019-10-21 17:57:39 +0000368 return 'Bearer %s' % self._authenticator.get_access_token().token
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700369
370
Ben Pastene04182552023-04-13 20:10:21 +0000371def CreateHttpConn(host,
372 path,
373 reqtype='GET',
374 headers=None,
375 body=None,
Xinan Lin1344a3c2023-05-02 21:55:43 +0000376 timeout=300):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000377 """Opens an HTTPS connection to a Gerrit service, and sends a request."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000378 headers = headers or {}
379 bare_host = host.partition(':')[0]
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000380
Edward Lemur447507e2020-03-31 17:33:54 +0000381 a = Authenticator.get()
382 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop.
383 if isinstance(a, GceAuthenticator):
384 print('If you\'re on a cloudtop instance, export '
385 'SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
386
387 a = a.get_auth_header(bare_host)
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700388 if a:
389 headers.setdefault('Authorization', a)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000390 else:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000391 LOGGER.debug('No authorization found for %s.' % bare_host)
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000392
Dan Jacques6d5bcc22016-11-14 15:32:04 -0800393 url = path
394 if not url.startswith('/'):
395 url = '/' + url
396 if 'Authorization' in headers and not url.startswith('/a/'):
397 url = '/a%s' % url
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000398
szager@chromium.orgb4696232013-10-16 19:45:35 +0000399 if body:
Edward Lemur4ba192e2019-10-28 20:19:37 +0000400 body = json.dumps(body, sort_keys=True)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000401 headers.setdefault('Content-Type', 'application/json')
402 if LOGGER.isEnabledFor(logging.DEBUG):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000403 LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url))
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000404 for key, val in headers.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000405 if key == 'Authorization':
406 val = 'HIDDEN'
407 LOGGER.debug('%s: %s' % (key, val))
408 if body:
409 LOGGER.debug(body)
Ben Pastene04182552023-04-13 20:10:21 +0000410 conn = httplib2.Http(timeout=timeout)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000411 # HACK: httplib2.Http has no such attribute; we store req_host here for later
Andrii Shyshkalov86c823e2018-09-18 19:51:33 +0000412 # use in ReadHttpResponse.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000413 conn.req_host = host
414 conn.req_params = {
Edward Lemur4ba192e2019-10-28 20:19:37 +0000415 'uri': urllib.parse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url),
szager@chromium.orgb4696232013-10-16 19:45:35 +0000416 'method': reqtype,
417 'headers': headers,
418 'body': body,
419 }
szager@chromium.orgb4696232013-10-16 19:45:35 +0000420 return conn
421
422
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700423def ReadHttpResponse(conn, accept_statuses=frozenset([200])):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000424 """Reads an HTTP response from a connection into a string buffer.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000425
426 Args:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100427 conn: An Http object created by CreateHttpConn above.
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700428 accept_statuses: Treat any of these statuses as success. Default: [200]
429 Common additions include 204, 400, and 404.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000430 Returns: A string buffer containing the connection's reply.
431 """
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000432 sleep_time = SLEEP_TIME
szager@chromium.orgb4696232013-10-16 19:45:35 +0000433 for idx in range(TRY_LIMIT):
Edward Lemur5a9ff432018-10-30 19:00:22 +0000434 before_response = time.time()
Ben Pastene9519fc12023-04-12 22:15:43 +0000435 try:
436 response, contents = conn.request(**conn.req_params)
437 except socket.timeout:
438 if idx < TRY_LIMIT - 1:
439 sleep_time = log_retry_and_sleep(sleep_time, idx)
440 continue
441 raise
Edward Lemur4ba192e2019-10-28 20:19:37 +0000442 contents = contents.decode('utf-8', 'replace')
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +0000443
Edward Lemur5a9ff432018-10-30 19:00:22 +0000444 response_time = time.time() - before_response
445 metrics.collector.add_repeated(
446 'http_requests',
447 metrics_utils.extract_http_metrics(
448 conn.req_params['uri'], conn.req_params['method'], response.status,
449 response_time))
450
Edward Lemur4ba192e2019-10-28 20:19:37 +0000451 # If response.status is an accepted status,
452 # or response.status < 500 then the result is final; break retry loop.
453 # If the response is 404/409 it might be because of replication lag,
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000454 # so keep trying anyway. If it is 429, it is generally ok to retry after
455 # a backoff.
Edward Lemur4ba192e2019-10-28 20:19:37 +0000456 if (response.status in accept_statuses
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000457 or response.status < 500 and response.status not in [404, 409, 429]):
Andrii Shyshkalov5b04a572017-01-23 17:44:41 +0100458 LOGGER.debug('got response %d for %s %s', response.status,
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100459 conn.req_params['method'], conn.req_params['uri'])
Michael Mossb40a4512017-10-10 11:07:17 -0700460 # If 404 was in accept_statuses, then it's expected that the file might
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000461 # not exist, so don't return the gitiles error page because that's not
462 # the "content" that was actually requested.
Michael Mossb40a4512017-10-10 11:07:17 -0700463 if response.status == 404:
464 contents = ''
szager@chromium.orgb4696232013-10-16 19:45:35 +0000465 break
Edward Lemur4ba192e2019-10-28 20:19:37 +0000466
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000467 # A status >=500 is assumed to be a possible transient error; retry.
468 http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0')
469 LOGGER.warn('A transient error occurred while querying %s:\n'
470 '%s %s %s\n'
Edward Lesmesb0739992020-10-09 23:15:44 +0000471 '%s %d %s\n'
472 '%s',
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000473 conn.req_host, conn.req_params['method'],
474 conn.req_params['uri'],
Edward Lesmesb0739992020-10-09 23:15:44 +0000475 http_version, http_version, response.status, response.reason,
476 contents)
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +0000477
Edward Lemur4ba192e2019-10-28 20:19:37 +0000478 if idx < TRY_LIMIT - 1:
Ben Pastene9519fc12023-04-12 22:15:43 +0000479 sleep_time = log_retry_and_sleep(sleep_time, idx)
Edward Lemur83bd7f42018-10-10 00:14:21 +0000480 # end of retries loop
Edward Lemur4ba192e2019-10-28 20:19:37 +0000481
482 if response.status in accept_statuses:
483 return StringIO(contents)
484
485 if response.status in (302, 401, 403):
486 www_authenticate = response.get('www-authenticate')
487 if not www_authenticate:
488 print('Your Gerrit credentials might be misconfigured.')
489 else:
490 auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I)
491 host = auth_match.group(1) if auth_match else conn.req_host
492 print('Authentication failed. Please make sure your .gitcookies '
493 'file has credentials for %s.' % host)
494 print('Try:\n git cl creds-check')
495
496 reason = '%s: %s' % (response.reason, contents)
497 raise GerritError(response.status, reason)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000498
499
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700500def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000501 """Parses an https response as json."""
Aaron Gable19ee16c2017-04-18 11:56:35 -0700502 fh = ReadHttpResponse(conn, accept_statuses)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000503 # The first line of the response should always be: )]}'
504 s = fh.readline()
505 if s and s.rstrip() != ")]}'":
506 raise GerritError(200, 'Unexpected json output: %s' % s)
507 s = fh.read()
508 if not s:
509 return None
510 return json.loads(s)
511
512
Michael Moss9c28af42021-10-25 16:59:05 +0000513def CallGerritApi(host, path, **kwargs):
514 """Helper for calling a Gerrit API that returns a JSON response."""
515 conn_kwargs = {}
516 conn_kwargs.update(
517 (k, kwargs[k]) for k in ['reqtype', 'headers', 'body'] if k in kwargs)
518 conn = CreateHttpConn(host, path, **conn_kwargs)
519 read_kwargs = {}
520 read_kwargs.update((k, kwargs[k]) for k in ['accept_statuses'] if k in kwargs)
521 return ReadHttpJsonResponse(conn, **read_kwargs)
522
523
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200524def QueryChanges(host, params, first_param=None, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100525 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000526 """
527 Queries a gerrit-on-borg server for changes matching query terms.
528
529 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200530 params: A list of key:value pairs for search parameters, as documented
531 here (e.g. ('is', 'owner') for a parameter 'is:owner'):
532 https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators
szager@chromium.orgb4696232013-10-16 19:45:35 +0000533 first_param: A change identifier
534 limit: Maximum number of results to return.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100535 start: how many changes to skip (starting with the most recent)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000536 o_params: A list of additional output specifiers, as documented here:
537 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000538
szager@chromium.orgb4696232013-10-16 19:45:35 +0000539 Returns:
540 A list of json-decoded query results.
541 """
542 # Note that no attempt is made to escape special characters; YMMV.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200543 if not params and not first_param:
szager@chromium.orgb4696232013-10-16 19:45:35 +0000544 raise RuntimeError('QueryChanges requires search parameters')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200545 path = 'changes/?q=%s' % _QueryString(params, first_param)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100546 if start:
547 path = '%s&start=%s' % (path, start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000548 if limit:
549 path = '%s&n=%d' % (path, limit)
550 if o_params:
551 path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params]))
Ben Pastene97dadd02023-04-14 21:55:38 +0000552 return ReadHttpJsonResponse(CreateHttpConn(host, path, timeout=30.0))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000553
554
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200555def GenerateAllChanges(host, params, first_param=None, limit=500,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100556 o_params=None, start=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000557 """Queries a gerrit-on-borg server for all the changes matching the query
558 terms.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000559
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100560 WARNING: this is unreliable if a change matching the query is modified while
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000561 this function is being called.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100562
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000563 A single query to gerrit-on-borg is limited on the number of results by the
564 limit parameter on the request (see QueryChanges) and the server maximum
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100565 limit.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000566
567 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200568 params, first_param: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000569 limit: Maximum number of requested changes per query.
570 o_params: Refer to QueryChanges().
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100571 start: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000572
573 Returns:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100574 A generator object to the list of returned changes.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000575 """
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100576 already_returned = set()
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000577
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100578 def at_most_once(cls):
579 for cl in cls:
580 if cl['_number'] not in already_returned:
581 already_returned.add(cl['_number'])
582 yield cl
583
584 start = start or 0
585 cur_start = start
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000586 more_changes = True
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100587
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000588 while more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100589 # This will fetch changes[start..start+limit] sorted by most recently
590 # updated. Since the rank of any change in this list can be changed any time
591 # (say user posting comment), subsequent calls may overalp like this:
592 # > initial order ABCDEFGH
593 # query[0..3] => ABC
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000594 # > E gets updated. New order: EABCDFGH
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100595 # query[3..6] => CDF # C is a dup
596 # query[6..9] => GH # E is missed.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200597 page = QueryChanges(host, params, first_param, limit, o_params,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100598 cur_start)
599 for cl in at_most_once(page):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000600 yield cl
601
602 more_changes = [cl for cl in page if '_more_changes' in cl]
603 if len(more_changes) > 1:
604 raise GerritError(
605 200,
606 'Received %d changes with a _more_changes attribute set but should '
607 'receive at most one.' % len(more_changes))
608 if more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100609 cur_start += len(page)
610
611 # If we paged through, query again the first page which in most circumstances
612 # will fetch all changes that were modified while this function was run.
613 if start != cur_start:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200614 page = QueryChanges(host, params, first_param, limit, o_params, start)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100615 for cl in at_most_once(page):
616 yield cl
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000617
618
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200619def MultiQueryChanges(host, params, change_list, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100620 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000621 """Initiate a query composed of multiple sets of query parameters."""
622 if not change_list:
623 raise RuntimeError(
624 "MultiQueryChanges requires a list of change numbers/id's")
Edward Lemur4ba192e2019-10-28 20:19:37 +0000625 q = ['q=%s' % '+OR+'.join([urllib.parse.quote(str(x)) for x in change_list])]
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200626 if params:
627 q.append(_QueryString(params))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000628 if limit:
629 q.append('n=%d' % limit)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100630 if start:
631 q.append('S=%s' % start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000632 if o_params:
633 q.extend(['o=%s' % p for p in o_params])
634 path = 'changes/?%s' % '&'.join(q)
635 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700636 result = ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000637 except GerritError as e:
638 msg = '%s:\n%s' % (e.message, path)
639 raise GerritError(e.http_status, msg)
640 return result
641
642
643def GetGerritFetchUrl(host):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000644 """Given a Gerrit host name returns URL of a Gerrit instance to fetch from."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000645 return '%s://%s/' % (GERRIT_PROTOCOL, host)
646
647
Edward Lemur687ca902018-12-05 02:30:30 +0000648def GetCodeReviewTbrScore(host, project):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000649 """Given a Gerrit host name and project, return the Code-Review score for TBR.
Edward Lemur687ca902018-12-05 02:30:30 +0000650 """
Edward Lemur4ba192e2019-10-28 20:19:37 +0000651 conn = CreateHttpConn(
652 host, '/projects/%s' % urllib.parse.quote(project, ''))
Edward Lemur687ca902018-12-05 02:30:30 +0000653 project = ReadHttpJsonResponse(conn)
654 if ('labels' not in project
655 or 'Code-Review' not in project['labels']
656 or 'values' not in project['labels']['Code-Review']):
657 return 1
658 return max([int(x) for x in project['labels']['Code-Review']['values']])
659
660
szager@chromium.orgb4696232013-10-16 19:45:35 +0000661def GetChangePageUrl(host, change_number):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000662 """Given a Gerrit host name and change number, returns change page URL."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000663 return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number)
664
665
666def GetChangeUrl(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000667 """Given a Gerrit host name and change ID, returns a URL for the change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000668 return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change)
669
670
671def GetChange(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000672 """Queries a Gerrit server for information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000673 path = 'changes/%s' % change
674 return ReadHttpJsonResponse(CreateHttpConn(host, path))
675
676
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700677def GetChangeDetail(host, change, o_params=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000678 """Queries a Gerrit server for extended information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000679 path = 'changes/%s/detail' % change
680 if o_params:
681 path += '?%s' % '&'.join(['o=%s' % p for p in o_params])
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700682 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000683
684
agable32978d92016-11-01 12:55:02 -0700685def GetChangeCommit(host, change, revision='current'):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000686 """Query a Gerrit server for a revision associated with a change."""
agable32978d92016-11-01 12:55:02 -0700687 path = 'changes/%s/revisions/%s/commit?links' % (change, revision)
688 return ReadHttpJsonResponse(CreateHttpConn(host, path))
689
690
szager@chromium.orgb4696232013-10-16 19:45:35 +0000691def GetChangeCurrentRevision(host, change):
692 """Get information about the latest revision for a given change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200693 return QueryChanges(host, [], change, o_params=('CURRENT_REVISION',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000694
695
696def GetChangeRevisions(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000697 """Gets information about all revisions associated with a change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200698 return QueryChanges(host, [], change, o_params=('ALL_REVISIONS',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000699
700
701def GetChangeReview(host, change, revision=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000702 """Gets the current review information for a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000703 if not revision:
704 jmsg = GetChangeRevisions(host, change)
705 if not jmsg:
706 return None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000707
708 if len(jmsg) > 1:
szager@chromium.orgb4696232013-10-16 19:45:35 +0000709 raise GerritError(200, 'Multiple changes found for ChangeId %s.' % change)
710 revision = jmsg[0]['current_revision']
711 path = 'changes/%s/revisions/%s/review'
712 return ReadHttpJsonResponse(CreateHttpConn(host, path))
713
714
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700715def GetChangeComments(host, change):
716 """Get the line- and file-level comments on a change."""
717 path = 'changes/%s/comments' % change
718 return ReadHttpJsonResponse(CreateHttpConn(host, path))
719
720
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000721def GetChangeRobotComments(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000722 """Gets the line- and file-level robot comments on a change."""
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000723 path = 'changes/%s/robotcomments' % change
724 return ReadHttpJsonResponse(CreateHttpConn(host, path))
725
726
Marco Georgaklis85557a02021-06-03 15:56:54 +0000727def GetRelatedChanges(host, change, revision='current'):
728 """Gets the related changes for a given change and revision."""
729 path = 'changes/%s/revisions/%s/related' % (change, revision)
730 return ReadHttpJsonResponse(CreateHttpConn(host, path))
731
732
szager@chromium.orgb4696232013-10-16 19:45:35 +0000733def AbandonChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000734 """Abandons a Gerrit change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000735 path = 'changes/%s/abandon' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000736 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000737 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700738 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000739
740
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000741def MoveChange(host, change, destination_branch):
742 """Move a Gerrit change to different destination branch."""
743 path = 'changes/%s/move' % change
Mike Frysingerf1c7d0d2020-12-15 20:05:36 +0000744 body = {'destination_branch': destination_branch,
745 'keep_all_votes': True}
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000746 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
747 return ReadHttpJsonResponse(conn)
748
749
750
szager@chromium.orgb4696232013-10-16 19:45:35 +0000751def RestoreChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000752 """Restores a previously abandoned change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000753 path = 'changes/%s/restore' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000754 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000755 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700756 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000757
758
Xinan Lin1bd4ffa2021-07-28 00:54:22 +0000759def SubmitChange(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000760 """Submits a Gerrit change via Gerrit."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000761 path = 'changes/%s/submit' % change
Xinan Lin1bd4ffa2021-07-28 00:54:22 +0000762 conn = CreateHttpConn(host, path, reqtype='POST')
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700763 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000764
765
Xinan Lin2b4ec952021-08-20 17:35:29 +0000766def GetChangesSubmittedTogether(host, change):
767 """Get all changes submitted with the given one."""
768 path = 'changes/%s/submitted_together?o=NON_VISIBLE_CHANGES' % change
769 conn = CreateHttpConn(host, path, reqtype='GET')
770 return ReadHttpJsonResponse(conn)
771
772
LaMont Jones9eed4232021-04-02 16:29:49 +0000773def PublishChangeEdit(host, change, notify=True):
774 """Publish a Gerrit change edit."""
775 path = 'changes/%s/edit:publish' % change
776 body = {'notify': 'ALL' if notify else 'NONE'}
777 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
778 return ReadHttpJsonResponse(conn, accept_statuses=(204, ))
779
780
781def ChangeEdit(host, change, path, data):
782 """Puts content of a file into a change edit."""
783 path = 'changes/%s/edit/%s' % (change, urllib.parse.quote(path, ''))
784 body = {
785 'binary_content':
Leszek Swirski4c0c3fb2022-06-08 17:04:02 +0000786 'data:text/plain;base64,%s' %
787 base64.b64encode(data.encode('utf-8')).decode('utf-8')
LaMont Jones9eed4232021-04-02 16:29:49 +0000788 }
789 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
790 return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
791
792
Leszek Swirskic1c45f82022-06-09 16:21:07 +0000793def SetChangeEditMessage(host, change, message):
794 """Sets the commit message of a change edit."""
795 path = 'changes/%s/edit:message' % change
796 body = {'message': message}
797 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
798 return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
799
800
dsansomee2d6fd92016-09-08 00:10:47 -0700801def HasPendingChangeEdit(host, change):
802 conn = CreateHttpConn(host, 'changes/%s/edit' % change)
803 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700804 ReadHttpResponse(conn)
dsansomee2d6fd92016-09-08 00:10:47 -0700805 except GerritError as e:
Aaron Gable19ee16c2017-04-18 11:56:35 -0700806 # 204 No Content means no pending change.
807 if e.http_status == 204:
808 return False
809 raise
810 return True
dsansomee2d6fd92016-09-08 00:10:47 -0700811
812
813def DeletePendingChangeEdit(host, change):
814 conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000815 # On success, Gerrit returns status 204; if the edit was already deleted it
Aaron Gable19ee16c2017-04-18 11:56:35 -0700816 # returns 404. Anything else is an error.
817 ReadHttpResponse(conn, accept_statuses=[204, 404])
dsansomee2d6fd92016-09-08 00:10:47 -0700818
819
Leszek Swirskic1c45f82022-06-09 16:21:07 +0000820def CherryPick(host, change, destination, revision='current'):
821 """Create a cherry-pick commit from the given change, onto the given
822 destination.
823 """
824 path = 'changes/%s/revisions/%s/cherrypick' % (change, revision)
825 body = {'destination': destination}
826 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
827 return ReadHttpJsonResponse(conn)
828
829
830def GetFileContents(host, change, path):
831 """Get the contents of a file with the given path in the given revision.
832
833 Returns:
834 A bytes object with the file's contents.
835 """
836 path = 'changes/%s/revisions/current/files/%s/content' % (
837 change, urllib.parse.quote(path, ''))
838 conn = CreateHttpConn(host, path, reqtype='GET')
839 return base64.b64decode(ReadHttpResponse(conn).read())
840
841
Andrii Shyshkalovea4fc832016-12-01 14:53:23 +0100842def SetCommitMessage(host, change, description, notify='ALL'):
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000843 """Updates a commit message."""
Aaron Gable7625d882017-06-26 09:47:26 -0700844 assert notify in ('ALL', 'NONE')
845 path = 'changes/%s/message' % change
Aaron Gable5a4ef452017-08-24 13:19:56 -0700846 body = {'message': description, 'notify': notify}
Aaron Gable7625d882017-06-26 09:47:26 -0700847 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000848 try:
Aaron Gable7625d882017-06-26 09:47:26 -0700849 ReadHttpResponse(conn, accept_statuses=[200, 204])
850 except GerritError as e:
851 raise GerritError(
852 e.http_status,
853 'Received unexpected http status while editing message '
854 'in change %s' % change)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000855
856
Xinan Linc2fb26a2021-07-27 18:01:55 +0000857def GetCommitIncludedIn(host, project, commit):
858 """Retrieves the branches and tags for a given commit.
859
860 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-included-in
861
862 Returns:
863 A JSON object with keys of 'branches' and 'tags'.
864 """
865 path = 'projects/%s/commits/%s/in' % (urllib.parse.quote(project, ''), commit)
866 conn = CreateHttpConn(host, path, reqtype='GET')
867 return ReadHttpJsonResponse(conn, accept_statuses=[200])
868
869
Edward Lesmes8170c292021-03-19 20:04:43 +0000870def IsCodeOwnersEnabledOnHost(host):
Edward Lesmes110823b2021-02-05 21:42:27 +0000871 """Check if the code-owners plugin is enabled for the host."""
872 path = 'config/server/capabilities'
873 capabilities = ReadHttpJsonResponse(CreateHttpConn(host, path))
874 return 'code-owners-checkCodeOwner' in capabilities
875
876
Edward Lesmes8170c292021-03-19 20:04:43 +0000877def IsCodeOwnersEnabledOnRepo(host, repo):
878 """Check if the code-owners plugin is enabled for the repo."""
879 repo = PercentEncodeForGitRef(repo)
880 path = '/projects/%s/code_owners.project_config' % repo
881 config = ReadHttpJsonResponse(CreateHttpConn(host, path))
Edward Lesmes743e98c2021-03-22 18:00:54 +0000882 return not config['status'].get('disabled', False)
Edward Lesmes8170c292021-03-19 20:04:43 +0000883
884
Gavin Make0fee9f2022-08-10 23:41:55 +0000885def GetOwnersForFile(host,
886 project,
887 branch,
888 path,
889 limit=100,
890 resolve_all_users=True,
891 highest_score_only=False,
892 seed=None,
893 o_params=('DETAILS',)):
Gavin Makc94b21d2020-12-10 20:27:32 +0000894 """Gets information about owners attached to a file."""
895 path = 'projects/%s/branches/%s/code_owners/%s' % (
896 urllib.parse.quote(project, ''),
897 urllib.parse.quote(branch, ''),
898 urllib.parse.quote(path, ''))
Gavin Mak7d690052021-02-25 19:14:22 +0000899 q = ['resolve-all-users=%s' % json.dumps(resolve_all_users)]
Gavin Make0fee9f2022-08-10 23:41:55 +0000900 if highest_score_only:
901 q.append('highest-score-only=%s' % json.dumps(highest_score_only))
Edward Lesmes23c3bdc2021-03-11 20:37:32 +0000902 if seed:
903 q.append('seed=%d' % seed)
Gavin Makc94b21d2020-12-10 20:27:32 +0000904 if limit:
905 q.append('n=%d' % limit)
906 if o_params:
907 q.extend(['o=%s' % p for p in o_params])
908 if q:
909 path = '%s?%s' % (path, '&'.join(q))
910 return ReadHttpJsonResponse(CreateHttpConn(host, path))
911
912
szager@chromium.orgb4696232013-10-16 19:45:35 +0000913def GetReviewers(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000914 """Gets information about all reviewers attached to a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000915 path = 'changes/%s/reviewers' % change
916 return ReadHttpJsonResponse(CreateHttpConn(host, path))
917
918
919def GetReview(host, change, revision):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000920 """Gets review information about a specific revision of a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000921 path = 'changes/%s/revisions/%s/review' % (change, revision)
922 return ReadHttpJsonResponse(CreateHttpConn(host, path))
923
924
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700925def AddReviewers(host, change, reviewers=None, ccs=None, notify=True,
926 accept_statuses=frozenset([200, 400, 422])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000927 """Add reviewers to a change."""
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700928 if not reviewers and not ccs:
Aaron Gabledf86e302016-11-08 10:48:03 -0800929 return None
Wiktor Garbacz6d0d0442017-05-15 12:34:40 +0200930 if not change:
931 return None
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700932 reviewers = frozenset(reviewers or [])
933 ccs = frozenset(ccs or [])
934 path = 'changes/%s/revisions/current/review' % change
935
936 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800937 'drafts': 'KEEP',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700938 'reviewers': [],
939 'notify': 'ALL' if notify else 'NONE',
940 }
941 for r in sorted(reviewers | ccs):
942 state = 'REVIEWER' if r in reviewers else 'CC'
943 body['reviewers'].append({
944 'reviewer': r,
945 'state': state,
946 'notify': 'NONE', # We handled `notify` argument above.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000947 })
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700948
949 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
950 # Gerrit will return 400 if one or more of the requested reviewers are
951 # unprocessable. We read the response object to see which were rejected,
952 # warn about them, and retry with the remainder.
953 resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses)
954
955 errored = set()
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000956 for result in resp.get('reviewers', {}).values():
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700957 r = result.get('input')
958 state = 'REVIEWER' if r in reviewers else 'CC'
959 if result.get('error'):
960 errored.add(r)
961 LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower()))
962 if errored:
963 # Try again, adding only those that didn't fail, and only accepting 200.
964 AddReviewers(host, change, reviewers=(reviewers-errored),
965 ccs=(ccs-errored), notify=notify, accept_statuses=[200])
szager@chromium.orgb4696232013-10-16 19:45:35 +0000966
967
Aaron Gable636b13f2017-07-14 10:42:48 -0700968def SetReview(host, change, msg=None, labels=None, notify=None, ready=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000969 """Sets labels and/or adds a message to a code review."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000970 if not msg and not labels:
971 return
972 path = 'changes/%s/revisions/current/review' % change
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800973 body = {'drafts': 'KEEP'}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000974 if msg:
975 body['message'] = msg
976 if labels:
977 body['labels'] = labels
Aaron Gablefc62f762017-07-17 11:12:07 -0700978 if notify is not None:
Aaron Gable75e78722017-06-09 10:40:16 -0700979 body['notify'] = 'ALL' if notify else 'NONE'
Aaron Gable636b13f2017-07-14 10:42:48 -0700980 if ready:
981 body['ready'] = True
szager@chromium.orgb4696232013-10-16 19:45:35 +0000982 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
983 response = ReadHttpJsonResponse(conn)
984 if labels:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000985 for key, val in labels.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000986 if ('labels' not in response or key not in response['labels'] or
987 int(response['labels'][key] != int(val))):
988 raise GerritError(200, 'Unable to set "%s" label on change %s.' % (
989 key, change))
Xinan Lin0b0738d2021-07-27 19:13:49 +0000990 return response
szager@chromium.orgb4696232013-10-16 19:45:35 +0000991
992def ResetReviewLabels(host, change, label, value='0', message=None,
993 notify=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000994 """Resets the value of a given label for all reviewers on a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000995 # This is tricky, because we want to work on the "current revision", but
996 # there's always the risk that "current revision" will change in between
997 # API calls. So, we check "current revision" at the beginning and end; if
998 # it has changed, raise an exception.
999 jmsg = GetChangeCurrentRevision(host, change)
1000 if not jmsg:
1001 raise GerritError(
1002 200, 'Could not get review information for change "%s"' % change)
1003 value = str(value)
1004 revision = jmsg[0]['current_revision']
1005 path = 'changes/%s/revisions/%s/review' % (change, revision)
1006 message = message or (
1007 '%s label set to %s programmatically.' % (label, value))
1008 jmsg = GetReview(host, change, revision)
1009 if not jmsg:
Quinten Yearsley925cedb2020-04-13 17:49:39 +00001010 raise GerritError(200, 'Could not get review information for revision %s '
szager@chromium.orgb4696232013-10-16 19:45:35 +00001011 'of change %s' % (revision, change))
1012 for review in jmsg.get('labels', {}).get(label, {}).get('all', []):
1013 if str(review.get('value', value)) != value:
1014 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -08001015 'drafts': 'KEEP',
szager@chromium.orgb4696232013-10-16 19:45:35 +00001016 'message': message,
1017 'labels': {label: value},
1018 'on_behalf_of': review['_account_id'],
1019 }
1020 if notify:
1021 body['notify'] = notify
1022 conn = CreateHttpConn(
1023 host, path, reqtype='POST', body=body)
1024 response = ReadHttpJsonResponse(conn)
1025 if str(response['labels'][label]) != value:
1026 username = review.get('email', jmsg.get('name', ''))
1027 raise GerritError(200, 'Unable to set %s label for user "%s"'
1028 ' on change %s.' % (label, username, change))
1029 jmsg = GetChangeCurrentRevision(host, change)
1030 if not jmsg:
1031 raise GerritError(
1032 200, 'Could not get review information for change "%s"' % change)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00001033
1034 if jmsg[0]['current_revision'] != revision:
szager@chromium.orgb4696232013-10-16 19:45:35 +00001035 raise GerritError(200, 'While resetting labels on change "%s", '
1036 'a new patchset was uploaded.' % change)
Dan Jacques8d11e482016-11-15 14:25:56 -08001037
1038
LaMont Jones9eed4232021-04-02 16:29:49 +00001039def CreateChange(host, project, branch='main', subject='', params=()):
1040 """
1041 Creates a new change.
1042
1043 Args:
1044 params: A list of additional ChangeInput specifiers, as documented here:
1045 (e.g. ('is_private', 'true') to mark the change private.
1046 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-input
1047
1048 Returns:
1049 ChangeInfo for the new change.
1050 """
1051 path = 'changes/'
1052 body = {'project': project, 'branch': branch, 'subject': subject}
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00001053 body.update(dict(params))
LaMont Jones9eed4232021-04-02 16:29:49 +00001054 for key in 'project', 'branch', 'subject':
1055 if not body[key]:
1056 raise GerritError(200, '%s is required' % key.title())
1057
Ben Pastene97dadd02023-04-14 21:55:38 +00001058 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
LaMont Jones9eed4232021-04-02 16:29:49 +00001059 return ReadHttpJsonResponse(conn, accept_statuses=[201])
1060
1061
dimu833c94c2017-01-18 17:36:15 -08001062def CreateGerritBranch(host, project, branch, commit):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001063 """Creates a new branch from given project and commit
1064
dimu833c94c2017-01-18 17:36:15 -08001065 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch
1066
1067 Returns:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001068 A JSON object with 'ref' key.
dimu833c94c2017-01-18 17:36:15 -08001069 """
1070 path = 'projects/%s/branches/%s' % (project, branch)
1071 body = {'revision': commit}
1072 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
Xinan Lindbcecc92023-05-03 18:29:00 +00001073 response = ReadHttpJsonResponse(conn, accept_statuses=[201, 409])
dimu833c94c2017-01-18 17:36:15 -08001074 if response:
1075 return response
1076 raise GerritError(200, 'Unable to create gerrit branch')
1077
1078
Michael Mossb6ce2442021-10-20 04:36:24 +00001079def CreateGerritTag(host, project, tag, commit):
1080 """Creates a new tag at the given commit.
1081
1082 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-tag
1083
1084 Returns:
1085 A JSON object with 'ref' key.
1086 """
1087 path = 'projects/%s/tags/%s' % (project, tag)
1088 body = {'revision': commit}
1089 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
1090 response = ReadHttpJsonResponse(conn, accept_statuses=[201])
1091 if response:
1092 return response
1093 raise GerritError(200, 'Unable to create gerrit tag')
1094
1095
Josip Sokcevicdf9a8022020-12-08 00:10:19 +00001096def GetHead(host, project):
1097 """Retrieves current HEAD of Gerrit project
1098
1099 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head
1100
1101 Returns:
1102 A JSON object with 'ref' key.
1103 """
1104 path = 'projects/%s/HEAD' % (project)
1105 conn = CreateHttpConn(host, path, reqtype='GET')
1106 response = ReadHttpJsonResponse(conn, accept_statuses=[200])
1107 if response:
1108 return response
1109 raise GerritError(200, 'Unable to update gerrit HEAD')
1110
1111
1112def UpdateHead(host, project, branch):
1113 """Updates Gerrit HEAD to point to branch
1114
1115 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head
1116
1117 Returns:
1118 A JSON object with 'ref' key.
1119 """
1120 path = 'projects/%s/HEAD' % (project)
1121 body = {'ref': branch}
1122 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
1123 response = ReadHttpJsonResponse(conn, accept_statuses=[200])
1124 if response:
1125 return response
1126 raise GerritError(200, 'Unable to update gerrit HEAD')
1127
1128
dimu833c94c2017-01-18 17:36:15 -08001129def GetGerritBranch(host, project, branch):
Xinan Linaf79f242021-08-09 21:23:58 +00001130 """Gets a branch info from given project and branch name.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001131
1132 See:
dimu833c94c2017-01-18 17:36:15 -08001133 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch
1134
1135 Returns:
Xinan Linaf79f242021-08-09 21:23:58 +00001136 A JSON object with 'revision' key if the branch exists, otherwise None.
dimu833c94c2017-01-18 17:36:15 -08001137 """
1138 path = 'projects/%s/branches/%s' % (project, branch)
1139 conn = CreateHttpConn(host, path, reqtype='GET')
Xinan Linaf79f242021-08-09 21:23:58 +00001140 return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
dimu833c94c2017-01-18 17:36:15 -08001141
1142
Josip Sokcevicf736cab2020-10-20 23:41:38 +00001143def GetProjectHead(host, project):
1144 conn = CreateHttpConn(host,
1145 '/projects/%s/HEAD' % urllib.parse.quote(project, ''))
1146 return ReadHttpJsonResponse(conn, accept_statuses=[200])
1147
1148
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001149def GetAccountDetails(host, account_id='self'):
1150 """Returns details of the account.
1151
1152 If account_id is not given, uses magic value 'self' which corresponds to
1153 whichever account user is authenticating as.
1154
1155 Documentation:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001156 https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001157
1158 Returns None if account is not found (i.e., Gerrit returned 404).
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001159 """
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001160 conn = CreateHttpConn(host, '/accounts/%s' % account_id)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001161 return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
1162
1163
1164def ValidAccounts(host, accounts, max_threads=10):
1165 """Returns a mapping from valid account to its details.
1166
1167 Invalid accounts, either not existing or without unique match,
1168 are not present as returned dictionary keys.
1169 """
Edward Lemur0db01f02019-11-12 22:01:51 +00001170 assert not isinstance(accounts, str), type(accounts)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001171 accounts = list(set(accounts))
1172 if not accounts:
1173 return {}
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001174
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001175 def get_one(account):
1176 try:
1177 return account, GetAccountDetails(host, account)
1178 except GerritError:
1179 return None, None
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001180
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001181 valid = {}
1182 with contextlib.closing(ThreadPool(min(max_threads, len(accounts)))) as pool:
1183 for account, details in pool.map(get_one, accounts):
1184 if account and details:
1185 valid[account] = details
1186 return valid
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001187
1188
Nick Carter8692b182017-11-06 16:30:38 -08001189def PercentEncodeForGitRef(original):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001190 """Applies percent-encoding for strings sent to Gerrit via git ref metadata.
Nick Carter8692b182017-11-06 16:30:38 -08001191
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001192 The encoding used is based on but stricter than URL encoding (Section 2.1 of
1193 RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE'
1194 (U+0020) can be represented as 'LOW LINE' (U+005F) or 'PLUS SIGN' (U+002B).
Nick Carter8692b182017-11-06 16:30:38 -08001195
1196 For more information, see the Gerrit docs here:
1197
1198 https://gerrit-review.googlesource.com/Documentation/user-upload.html#message
1199 """
1200 safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
1201 encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original)
1202
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001203 # Spaces are not allowed in git refs; gerrit will interpret either '_' or
Nick Carter8692b182017-11-06 16:30:38 -08001204 # '+' (or '%20') as space. Use '_' since that has been supported the longest.
1205 return encoded.replace(' ', '_')
1206
1207
Dan Jacques8d11e482016-11-15 14:25:56 -08001208@contextlib.contextmanager
1209def tempdir():
1210 tdir = None
1211 try:
1212 tdir = tempfile.mkdtemp(suffix='gerrit_util')
1213 yield tdir
1214 finally:
1215 if tdir:
1216 gclient_utils.rmtree(tdir)
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001217
1218
1219def ChangeIdentifier(project, change_number):
Edward Lemur687ca902018-12-05 02:30:30 +00001220 """Returns change identifier "project~number" suitable for |change| arg of
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001221 this module API.
1222
1223 Such format is allows for more efficient Gerrit routing of HTTP requests,
1224 comparing to specifying just change_number.
1225 """
1226 assert int(change_number)
Edward Lemur4ba192e2019-10-28 20:19:37 +00001227 return '%s~%s' % (urllib.parse.quote(project, ''), change_number)