blob: 9aa6e949cc33353e8c2244d1c0bcb4b85a88d43a [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
Raul Tambre80ee78e2019-05-06 22:41:05 +000011from __future__ import print_function
Edward Lemur4ba192e2019-10-28 20:19:37 +000012from __future__ import unicode_literals
Raul Tambre80ee78e2019-05-06 22:41:05 +000013
szager@chromium.orgb4696232013-10-16 19:45:35 +000014import base64
Dan Jacques8d11e482016-11-15 14:25:56 -080015import contextlib
Edward Lemur202c5592019-10-21 22:44:52 +000016import httplib2
szager@chromium.orgb4696232013-10-16 19:45:35 +000017import json
18import logging
19import netrc
20import os
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +000021import random
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000022import re
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000023import socket
szager@chromium.orgf202a252014-05-27 18:55:52 +000024import stat
25import sys
Dan Jacques8d11e482016-11-15 14:25:56 -080026import tempfile
szager@chromium.orgb4696232013-10-16 19:45:35 +000027import time
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +000028from multiprocessing.pool import ThreadPool
szager@chromium.orgb4696232013-10-16 19:45:35 +000029
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -070030import auth
Dan Jacques8d11e482016-11-15 14:25:56 -080031import gclient_utils
Edward Lemur5a9ff432018-10-30 19:00:22 +000032import metrics
33import metrics_utils
Aaron Gable8797cab2018-03-06 13:55:00 -080034import subprocess2
szager@chromium.orgf202a252014-05-27 18:55:52 +000035
Edward Lemur4ba192e2019-10-28 20:19:37 +000036from third_party import six
37from six.moves import urllib
38
39if sys.version_info.major == 2:
40 import cookielib
41 from StringIO import StringIO
42else:
43 import http.cookiejar as cookielib
44 from io import StringIO
45
szager@chromium.orgb4696232013-10-16 19:45:35 +000046LOGGER = logging.getLogger()
George Engelbrecht888c0fe2020-04-17 15:00:20 +000047# With a starting sleep time of 10.0 seconds, x <= [1.8-2.2]x backoff, and five
48# total tries, the sleep time between the first and last tries will be ~7 min.
49TRY_LIMIT = 5
50SLEEP_TIME = 10.0
51MAX_BACKOFF = 2.2
52MIN_BACKOFF = 1.8
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000053
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000054# Controls the transport protocol used to communicate with Gerrit.
szager@chromium.orgb4696232013-10-16 19:45:35 +000055# This is parameterized primarily to enable GerritTestCase.
56GERRIT_PROTOCOL = 'https'
57
58
Edward Lemur4ba192e2019-10-28 20:19:37 +000059def time_sleep(seconds):
60 # Use this so that it can be mocked in tests without interfering with python
61 # system machinery.
62 return time.sleep(seconds)
63
64
Edward Lemura3b6fd02020-03-02 22:16:15 +000065def time_time():
66 # Use this so that it can be mocked in tests without interfering with python
67 # system machinery.
68 return time.time()
69
70
Ben Pastene9519fc12023-04-12 22:15:43 +000071def log_retry_and_sleep(seconds, attempt):
72 LOGGER.info('Will retry in %d seconds (%d more times)...', seconds,
73 TRY_LIMIT - attempt - 1)
74 time_sleep(seconds)
75 return seconds * random.uniform(MIN_BACKOFF, MAX_BACKOFF)
76
77
szager@chromium.orgb4696232013-10-16 19:45:35 +000078class GerritError(Exception):
79 """Exception class for errors commuicating with the gerrit-on-borg service."""
Edward Lemur4ba192e2019-10-28 20:19:37 +000080 def __init__(self, http_status, message, *args, **kwargs):
szager@chromium.orgb4696232013-10-16 19:45:35 +000081 super(GerritError, self).__init__(*args, **kwargs)
82 self.http_status = http_status
Edward Lemur4ba192e2019-10-28 20:19:37 +000083 self.message = '(%d) %s' % (self.http_status, message)
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000084
Josip Sokcevicdf9a8022020-12-08 00:10:19 +000085 def __str__(self):
86 return self.message
87
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000088
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020089def _QueryString(params, first_param=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +000090 """Encodes query parameters in the key:val[+key:val...] format specified here:
91
92 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
93 """
Edward Lemur4ba192e2019-10-28 20:19:37 +000094 q = [urllib.parse.quote(first_param)] if first_param else []
Josip Sokcevicf5c6d8a2021-05-12 18:23:24 +000095 q.extend(['%s:%s' % (key, val.replace(" ", "+")) for key, val in params])
szager@chromium.orgb4696232013-10-16 19:45:35 +000096 return '+'.join(q)
97
98
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000099class Authenticator(object):
100 """Base authenticator class for authenticator implementations to subclass."""
101
102 def get_auth_header(self, host):
103 raise NotImplementedError()
104
105 @staticmethod
106 def get():
107 """Returns: (Authenticator) The identified Authenticator to use.
108
109 Probes the local system and its environment and identifies the
110 Authenticator instance to use.
111 """
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700112 # LUCI Context takes priority since it's normally present only on bots,
113 # which then must use it.
114 if LuciContextAuthenticator.is_luci():
115 return LuciContextAuthenticator()
Edward Lemur57d47422020-03-06 20:43:07 +0000116 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop,
117 # and use CookiesAuthenticator instead.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000118 if GceAuthenticator.is_gce():
119 return GceAuthenticator()
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000120 return CookiesAuthenticator()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000121
122
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000123class CookiesAuthenticator(Authenticator):
124 """Authenticator implementation that uses ".netrc" or ".gitcookies" for token.
125
126 Expected case for developer workstations.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000127 """
128
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000129 _EMPTY = object()
130
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000131 def __init__(self):
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000132 # Credentials will be loaded lazily on first use. This ensures Authenticator
133 # get() can always construct an authenticator, even if something is broken.
134 # This allows 'creds-check' to proceed to actually checking creds later,
135 # rigorously (instead of blowing up with a cryptic error if they are wrong).
136 self._netrc = self._EMPTY
137 self._gitcookies = self._EMPTY
138
139 @property
140 def netrc(self):
141 if self._netrc is self._EMPTY:
142 self._netrc = self._get_netrc()
143 return self._netrc
144
145 @property
146 def gitcookies(self):
147 if self._gitcookies is self._EMPTY:
148 self._gitcookies = self._get_gitcookies()
149 return self._gitcookies
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000150
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000151 @classmethod
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200152 def get_new_password_url(cls, host):
153 assert not host.startswith('http')
154 # Assume *.googlesource.com pattern.
155 parts = host.split('.')
Aravind Vasudevana02b4bf2023-02-03 17:52:03 +0000156
157 # remove -review suffix if present.
158 if parts[0].endswith('-review'):
159 parts[0] = parts[0][:-len('-review')]
160
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200161 return 'https://%s/new-password' % ('.'.join(parts))
162
163 @classmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000164 def get_new_password_message(cls, host):
William Hessee9e89e32019-03-03 19:02:32 +0000165 if host is None:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000166 return ('Git host for Gerrit upload is unknown. Check your remote '
William Hessee9e89e32019-03-03 19:02:32 +0000167 'and the branch your branch is tracking. This tool assumes '
168 'that you are using a git server at *.googlesource.com.')
Edward Lemur67fccdf2019-10-22 22:17:10 +0000169 url = cls.get_new_password_url(host)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100170 return 'You can (re)generate your credentials by visiting %s' % url
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000171
172 @classmethod
173 def get_netrc_path(cls):
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000174 path = '_netrc' if sys.platform.startswith('win') else '.netrc'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000175 return os.path.expanduser(os.path.join('~', path))
176
177 @classmethod
178 def _get_netrc(cls):
Dan Jacques8d11e482016-11-15 14:25:56 -0800179 # Buffer the '.netrc' path. Use an empty file if it doesn't exist.
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000180 path = cls.get_netrc_path()
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000181 if not os.path.exists(path):
182 return netrc.netrc(os.devnull)
183
184 st = os.stat(path)
185 if st.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000186 print(
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000187 'WARNING: netrc file %s cannot be used because its file '
188 'permissions are insecure. netrc file permissions should be '
Raul Tambre80ee78e2019-05-06 22:41:05 +0000189 '600.' % path, file=sys.stderr)
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000190 with open(path) as fd:
191 content = fd.read()
Dan Jacques8d11e482016-11-15 14:25:56 -0800192
193 # Load the '.netrc' file. We strip comments from it because processing them
194 # can trigger a bug in Windows. See crbug.com/664664.
195 content = '\n'.join(l for l in content.splitlines()
196 if l.strip() and not l.strip().startswith('#'))
197 with tempdir() as tdir:
198 netrc_path = os.path.join(tdir, 'netrc')
199 with open(netrc_path, 'w') as fd:
200 fd.write(content)
201 os.chmod(netrc_path, (stat.S_IRUSR | stat.S_IWUSR))
202 return cls._get_netrc_from_path(netrc_path)
203
204 @classmethod
205 def _get_netrc_from_path(cls, path):
206 try:
207 return netrc.netrc(path)
208 except IOError:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000209 print('WARNING: Could not read netrc file %s' % path, file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800210 return netrc.netrc(os.devnull)
211 except netrc.NetrcParseError as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000212 print('ERROR: Cannot use netrc file %s due to a parsing error: %s' %
213 (path, e), file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800214 return netrc.netrc(os.devnull)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000215
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000216 @classmethod
217 def get_gitcookies_path(cls):
Ravi Mistry0bfa9ad2016-11-21 12:58:31 -0500218 if os.getenv('GIT_COOKIES_PATH'):
219 return os.getenv('GIT_COOKIES_PATH')
Aaron Gable8797cab2018-03-06 13:55:00 -0800220 try:
Edward Lesmes5a5537d2020-04-01 20:52:30 +0000221 path = subprocess2.check_output(
222 ['git', 'config', '--path', 'http.cookiefile'])
223 return path.decode('utf-8', 'ignore').strip()
Aaron Gable8797cab2018-03-06 13:55:00 -0800224 except subprocess2.CalledProcessError:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000225 return os.path.expanduser(os.path.join('~', '.gitcookies'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000226
227 @classmethod
228 def _get_gitcookies(cls):
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000229 gitcookies = {}
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000230 path = cls.get_gitcookies_path()
231 if not os.path.exists(path):
232 return gitcookies
233
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000234 try:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000235 f = gclient_utils.FileRead(path, 'rb').splitlines()
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000236 except IOError:
237 return gitcookies
238
Edward Lemur67fccdf2019-10-22 22:17:10 +0000239 for line in f:
240 try:
241 fields = line.strip().split('\t')
242 if line.strip().startswith('#') or len(fields) != 7:
243 continue
244 domain, xpath, key, value = fields[0], fields[2], fields[5], fields[6]
245 if xpath == '/' and key == 'o':
246 if value.startswith('git-'):
247 login, secret_token = value.split('=', 1)
248 gitcookies[domain] = (login, secret_token)
249 else:
250 gitcookies[domain] = ('', value)
251 except (IndexError, ValueError, TypeError) as exc:
252 LOGGER.warning(exc)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000253 return gitcookies
254
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100255 def _get_auth_for_host(self, host):
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000256 for domain, creds in self.gitcookies.items():
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000257 if cookielib.domain_match(host, domain):
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100258 return (creds[0], None, creds[1])
259 return self.netrc.authenticators(host)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000260
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100261 def get_auth_header(self, host):
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700262 a = self._get_auth_for_host(host)
263 if a:
Eric Boren2fb63102018-10-05 13:05:03 +0000264 if a[0]:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000265 secret = base64.b64encode(('%s:%s' % (a[0], a[2])).encode('utf-8'))
266 return 'Basic %s' % secret.decode('utf-8')
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000267
268 return 'Bearer %s' % a[2]
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000269 return None
270
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100271 def get_auth_email(self, host):
272 """Best effort parsing of email to be used for auth for the given host."""
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700273 a = self._get_auth_for_host(host)
274 if not a:
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100275 return None
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700276 login = a[0]
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100277 # login typically looks like 'git-xxx.example.com'
278 if not login.startswith('git-') or '.' not in login:
279 return None
280 username, domain = login[len('git-'):].split('.', 1)
281 return '%s@%s' % (username, domain)
282
Andrii Shyshkalov18975322017-01-25 16:44:13 +0100283
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000284# Backwards compatibility just in case somebody imports this outside of
285# depot_tools.
286NetrcAuthenticator = CookiesAuthenticator
287
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000288
289class GceAuthenticator(Authenticator):
290 """Authenticator implementation that uses GCE metadata service for token.
291 """
292
293 _INFO_URL = 'http://metadata.google.internal'
smut5e9401b2017-08-10 15:22:20 -0700294 _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/'
295 'service-accounts/default/token' % _INFO_URL)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000296 _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"}
297
298 _cache_is_gce = None
299 _token_cache = None
300 _token_expiration = None
301
302 @classmethod
303 def is_gce(cls):
Ravi Mistryfad941b2016-11-15 13:00:47 -0500304 if os.getenv('SKIP_GCE_AUTH_FOR_GIT'):
305 return False
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000306 if cls._cache_is_gce is None:
307 cls._cache_is_gce = cls._test_is_gce()
308 return cls._cache_is_gce
309
310 @classmethod
311 def _test_is_gce(cls):
312 # Based on https://cloud.google.com/compute/docs/metadata#runninggce
Edward Lemura3b6fd02020-03-02 22:16:15 +0000313 resp, _ = cls._get(cls._INFO_URL)
314 if resp is None:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000315 return False
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100316 return resp.get('metadata-flavor') == 'Google'
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000317
318 @staticmethod
319 def _get(url, **kwargs):
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000320 next_delay_sec = 1.0
Edward Lemura3b6fd02020-03-02 22:16:15 +0000321 for i in range(TRY_LIMIT):
Edward Lemur4ba192e2019-10-28 20:19:37 +0000322 p = urllib.parse.urlparse(url)
323 if p.scheme not in ('http', 'https'):
324 raise RuntimeError(
325 "Don't know how to work with protocol '%s'" % protocol)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000326 try:
327 resp, contents = httplib2.Http().request(url, 'GET', **kwargs)
Raphael Kubo da Costa9f6aa1b2021-06-24 16:59:31 +0000328 except (socket.error, httplib2.HttpLib2Error,
329 httplib2.socks.ProxyError) as e:
Edward Lemura3b6fd02020-03-02 22:16:15 +0000330 LOGGER.debug('GET [%s] raised %s', url, e)
331 return None, None
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000332 LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000333 if resp.status < 500:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100334 return (resp, contents)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000335
Aaron Gable92e9f382017-12-07 11:47:41 -0800336 # Retry server error status codes.
337 LOGGER.warn('Encountered server error')
338 if TRY_LIMIT - i > 1:
Ben Pastene9519fc12023-04-12 22:15:43 +0000339 next_delay_sec = log_retry_and_sleep(next_delay_sec, i)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000340 return None, None
Aaron Gable92e9f382017-12-07 11:47:41 -0800341
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000342 @classmethod
343 def _get_token_dict(cls):
Edward Lemura3b6fd02020-03-02 22:16:15 +0000344 # If cached token is valid for at least 25 seconds, return it.
345 if cls._token_cache and time_time() + 25 < cls._token_expiration:
346 return cls._token_cache
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000347
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100348 resp, contents = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000349 if resp is None or resp.status != 200:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000350 return None
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100351 cls._token_cache = json.loads(contents)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000352 cls._token_expiration = cls._token_cache['expires_in'] + time_time()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000353 return cls._token_cache
354
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
360
361
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700362class LuciContextAuthenticator(Authenticator):
363 """Authenticator implementation that uses LUCI_CONTEXT ambient local auth.
364 """
365
366 @staticmethod
367 def is_luci():
368 return auth.has_luci_context_local_auth()
369
370 def __init__(self):
Edward Lemur5b929a42019-10-21 17:57:39 +0000371 self._authenticator = auth.Authenticator(
372 ' '.join([auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700373
374 def get_auth_header(self, _host):
Edward Lemur5b929a42019-10-21 17:57:39 +0000375 return 'Bearer %s' % self._authenticator.get_access_token().token
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700376
377
szager@chromium.orgb4696232013-10-16 19:45:35 +0000378def CreateHttpConn(host, path, reqtype='GET', headers=None, body=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000379 """Opens an HTTPS connection to a Gerrit service, and sends a request."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000380 headers = headers or {}
381 bare_host = host.partition(':')[0]
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000382
Edward Lemur447507e2020-03-31 17:33:54 +0000383 a = Authenticator.get()
384 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop.
385 if isinstance(a, GceAuthenticator):
386 print('If you\'re on a cloudtop instance, export '
387 'SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
388
389 a = a.get_auth_header(bare_host)
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700390 if a:
391 headers.setdefault('Authorization', a)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000392 else:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000393 LOGGER.debug('No authorization found for %s.' % bare_host)
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000394
Dan Jacques6d5bcc22016-11-14 15:32:04 -0800395 url = path
396 if not url.startswith('/'):
397 url = '/' + url
398 if 'Authorization' in headers and not url.startswith('/a/'):
399 url = '/a%s' % url
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000400
szager@chromium.orgb4696232013-10-16 19:45:35 +0000401 if body:
Edward Lemur4ba192e2019-10-28 20:19:37 +0000402 body = json.dumps(body, sort_keys=True)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000403 headers.setdefault('Content-Type', 'application/json')
404 if LOGGER.isEnabledFor(logging.DEBUG):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000405 LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url))
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000406 for key, val in headers.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000407 if key == 'Authorization':
408 val = 'HIDDEN'
409 LOGGER.debug('%s: %s' % (key, val))
410 if body:
411 LOGGER.debug(body)
Ben Pastene9519fc12023-04-12 22:15:43 +0000412 conn = httplib2.Http(timeout=10.0)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000413 # HACK: httplib2.Http has no such attribute; we store req_host here for later
Andrii Shyshkalov86c823e2018-09-18 19:51:33 +0000414 # use in ReadHttpResponse.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000415 conn.req_host = host
416 conn.req_params = {
Edward Lemur4ba192e2019-10-28 20:19:37 +0000417 'uri': urllib.parse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url),
szager@chromium.orgb4696232013-10-16 19:45:35 +0000418 'method': reqtype,
419 'headers': headers,
420 'body': body,
421 }
szager@chromium.orgb4696232013-10-16 19:45:35 +0000422 return conn
423
424
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700425def ReadHttpResponse(conn, accept_statuses=frozenset([200])):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000426 """Reads an HTTP response from a connection into a string buffer.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000427
428 Args:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100429 conn: An Http object created by CreateHttpConn above.
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700430 accept_statuses: Treat any of these statuses as success. Default: [200]
431 Common additions include 204, 400, and 404.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000432 Returns: A string buffer containing the connection's reply.
433 """
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000434 sleep_time = SLEEP_TIME
szager@chromium.orgb4696232013-10-16 19:45:35 +0000435 for idx in range(TRY_LIMIT):
Edward Lemur5a9ff432018-10-30 19:00:22 +0000436 before_response = time.time()
Ben Pastene9519fc12023-04-12 22:15:43 +0000437 try:
438 response, contents = conn.request(**conn.req_params)
439 except socket.timeout:
440 if idx < TRY_LIMIT - 1:
441 sleep_time = log_retry_and_sleep(sleep_time, idx)
442 continue
443 raise
Edward Lemur4ba192e2019-10-28 20:19:37 +0000444 contents = contents.decode('utf-8', 'replace')
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +0000445
Edward Lemur5a9ff432018-10-30 19:00:22 +0000446 response_time = time.time() - before_response
447 metrics.collector.add_repeated(
448 'http_requests',
449 metrics_utils.extract_http_metrics(
450 conn.req_params['uri'], conn.req_params['method'], response.status,
451 response_time))
452
Edward Lemur4ba192e2019-10-28 20:19:37 +0000453 # If response.status is an accepted status,
454 # or response.status < 500 then the result is final; break retry loop.
455 # If the response is 404/409 it might be because of replication lag,
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000456 # so keep trying anyway. If it is 429, it is generally ok to retry after
457 # a backoff.
Edward Lemur4ba192e2019-10-28 20:19:37 +0000458 if (response.status in accept_statuses
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000459 or response.status < 500 and response.status not in [404, 409, 429]):
Andrii Shyshkalov5b04a572017-01-23 17:44:41 +0100460 LOGGER.debug('got response %d for %s %s', response.status,
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100461 conn.req_params['method'], conn.req_params['uri'])
Michael Mossb40a4512017-10-10 11:07:17 -0700462 # If 404 was in accept_statuses, then it's expected that the file might
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000463 # not exist, so don't return the gitiles error page because that's not
464 # the "content" that was actually requested.
Michael Mossb40a4512017-10-10 11:07:17 -0700465 if response.status == 404:
466 contents = ''
szager@chromium.orgb4696232013-10-16 19:45:35 +0000467 break
Edward Lemur4ba192e2019-10-28 20:19:37 +0000468
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000469 # A status >=500 is assumed to be a possible transient error; retry.
470 http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0')
471 LOGGER.warn('A transient error occurred while querying %s:\n'
472 '%s %s %s\n'
Edward Lesmesb0739992020-10-09 23:15:44 +0000473 '%s %d %s\n'
474 '%s',
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000475 conn.req_host, conn.req_params['method'],
476 conn.req_params['uri'],
Edward Lesmesb0739992020-10-09 23:15:44 +0000477 http_version, http_version, response.status, response.reason,
478 contents)
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +0000479
Edward Lemur4ba192e2019-10-28 20:19:37 +0000480 if idx < TRY_LIMIT - 1:
Ben Pastene9519fc12023-04-12 22:15:43 +0000481 sleep_time = log_retry_and_sleep(sleep_time, idx)
Edward Lemur83bd7f42018-10-10 00:14:21 +0000482 # end of retries loop
Edward Lemur4ba192e2019-10-28 20:19:37 +0000483
484 if response.status in accept_statuses:
485 return StringIO(contents)
486
487 if response.status in (302, 401, 403):
488 www_authenticate = response.get('www-authenticate')
489 if not www_authenticate:
490 print('Your Gerrit credentials might be misconfigured.')
491 else:
492 auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I)
493 host = auth_match.group(1) if auth_match else conn.req_host
494 print('Authentication failed. Please make sure your .gitcookies '
495 'file has credentials for %s.' % host)
496 print('Try:\n git cl creds-check')
497
498 reason = '%s: %s' % (response.reason, contents)
499 raise GerritError(response.status, reason)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000500
501
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700502def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000503 """Parses an https response as json."""
Aaron Gable19ee16c2017-04-18 11:56:35 -0700504 fh = ReadHttpResponse(conn, accept_statuses)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000505 # The first line of the response should always be: )]}'
506 s = fh.readline()
507 if s and s.rstrip() != ")]}'":
508 raise GerritError(200, 'Unexpected json output: %s' % s)
509 s = fh.read()
510 if not s:
511 return None
512 return json.loads(s)
513
514
Michael Moss9c28af42021-10-25 16:59:05 +0000515def CallGerritApi(host, path, **kwargs):
516 """Helper for calling a Gerrit API that returns a JSON response."""
517 conn_kwargs = {}
518 conn_kwargs.update(
519 (k, kwargs[k]) for k in ['reqtype', 'headers', 'body'] if k in kwargs)
520 conn = CreateHttpConn(host, path, **conn_kwargs)
521 read_kwargs = {}
522 read_kwargs.update((k, kwargs[k]) for k in ['accept_statuses'] if k in kwargs)
523 return ReadHttpJsonResponse(conn, **read_kwargs)
524
525
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200526def QueryChanges(host, params, first_param=None, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100527 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000528 """
529 Queries a gerrit-on-borg server for changes matching query terms.
530
531 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200532 params: A list of key:value pairs for search parameters, as documented
533 here (e.g. ('is', 'owner') for a parameter 'is:owner'):
534 https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators
szager@chromium.orgb4696232013-10-16 19:45:35 +0000535 first_param: A change identifier
536 limit: Maximum number of results to return.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100537 start: how many changes to skip (starting with the most recent)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000538 o_params: A list of additional output specifiers, as documented here:
539 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000540
szager@chromium.orgb4696232013-10-16 19:45:35 +0000541 Returns:
542 A list of json-decoded query results.
543 """
544 # Note that no attempt is made to escape special characters; YMMV.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200545 if not params and not first_param:
szager@chromium.orgb4696232013-10-16 19:45:35 +0000546 raise RuntimeError('QueryChanges requires search parameters')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200547 path = 'changes/?q=%s' % _QueryString(params, first_param)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100548 if start:
549 path = '%s&start=%s' % (path, start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000550 if limit:
551 path = '%s&n=%d' % (path, limit)
552 if o_params:
553 path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params]))
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700554 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000555
556
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200557def GenerateAllChanges(host, params, first_param=None, limit=500,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100558 o_params=None, start=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000559 """Queries a gerrit-on-borg server for all the changes matching the query
560 terms.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000561
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100562 WARNING: this is unreliable if a change matching the query is modified while
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000563 this function is being called.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100564
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000565 A single query to gerrit-on-borg is limited on the number of results by the
566 limit parameter on the request (see QueryChanges) and the server maximum
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100567 limit.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000568
569 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200570 params, first_param: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000571 limit: Maximum number of requested changes per query.
572 o_params: Refer to QueryChanges().
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100573 start: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000574
575 Returns:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100576 A generator object to the list of returned changes.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000577 """
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100578 already_returned = set()
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000579
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100580 def at_most_once(cls):
581 for cl in cls:
582 if cl['_number'] not in already_returned:
583 already_returned.add(cl['_number'])
584 yield cl
585
586 start = start or 0
587 cur_start = start
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000588 more_changes = True
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100589
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000590 while more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100591 # This will fetch changes[start..start+limit] sorted by most recently
592 # updated. Since the rank of any change in this list can be changed any time
593 # (say user posting comment), subsequent calls may overalp like this:
594 # > initial order ABCDEFGH
595 # query[0..3] => ABC
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000596 # > E gets updated. New order: EABCDFGH
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100597 # query[3..6] => CDF # C is a dup
598 # query[6..9] => GH # E is missed.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200599 page = QueryChanges(host, params, first_param, limit, o_params,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100600 cur_start)
601 for cl in at_most_once(page):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000602 yield cl
603
604 more_changes = [cl for cl in page if '_more_changes' in cl]
605 if len(more_changes) > 1:
606 raise GerritError(
607 200,
608 'Received %d changes with a _more_changes attribute set but should '
609 'receive at most one.' % len(more_changes))
610 if more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100611 cur_start += len(page)
612
613 # If we paged through, query again the first page which in most circumstances
614 # will fetch all changes that were modified while this function was run.
615 if start != cur_start:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200616 page = QueryChanges(host, params, first_param, limit, o_params, start)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100617 for cl in at_most_once(page):
618 yield cl
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000619
620
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200621def MultiQueryChanges(host, params, change_list, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100622 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000623 """Initiate a query composed of multiple sets of query parameters."""
624 if not change_list:
625 raise RuntimeError(
626 "MultiQueryChanges requires a list of change numbers/id's")
Edward Lemur4ba192e2019-10-28 20:19:37 +0000627 q = ['q=%s' % '+OR+'.join([urllib.parse.quote(str(x)) for x in change_list])]
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200628 if params:
629 q.append(_QueryString(params))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000630 if limit:
631 q.append('n=%d' % limit)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100632 if start:
633 q.append('S=%s' % start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000634 if o_params:
635 q.extend(['o=%s' % p for p in o_params])
636 path = 'changes/?%s' % '&'.join(q)
637 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700638 result = ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000639 except GerritError as e:
640 msg = '%s:\n%s' % (e.message, path)
641 raise GerritError(e.http_status, msg)
642 return result
643
644
645def GetGerritFetchUrl(host):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000646 """Given a Gerrit host name returns URL of a Gerrit instance to fetch from."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000647 return '%s://%s/' % (GERRIT_PROTOCOL, host)
648
649
Edward Lemur687ca902018-12-05 02:30:30 +0000650def GetCodeReviewTbrScore(host, project):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000651 """Given a Gerrit host name and project, return the Code-Review score for TBR.
Edward Lemur687ca902018-12-05 02:30:30 +0000652 """
Edward Lemur4ba192e2019-10-28 20:19:37 +0000653 conn = CreateHttpConn(
654 host, '/projects/%s' % urllib.parse.quote(project, ''))
Edward Lemur687ca902018-12-05 02:30:30 +0000655 project = ReadHttpJsonResponse(conn)
656 if ('labels' not in project
657 or 'Code-Review' not in project['labels']
658 or 'values' not in project['labels']['Code-Review']):
659 return 1
660 return max([int(x) for x in project['labels']['Code-Review']['values']])
661
662
szager@chromium.orgb4696232013-10-16 19:45:35 +0000663def GetChangePageUrl(host, change_number):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000664 """Given a Gerrit host name and change number, returns change page URL."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000665 return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number)
666
667
668def GetChangeUrl(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000669 """Given a Gerrit host name and change ID, returns a URL for the change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000670 return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change)
671
672
673def GetChange(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000674 """Queries a Gerrit server for information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000675 path = 'changes/%s' % change
676 return ReadHttpJsonResponse(CreateHttpConn(host, path))
677
678
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700679def GetChangeDetail(host, change, o_params=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000680 """Queries a Gerrit server for extended information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000681 path = 'changes/%s/detail' % change
682 if o_params:
683 path += '?%s' % '&'.join(['o=%s' % p for p in o_params])
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700684 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000685
686
agable32978d92016-11-01 12:55:02 -0700687def GetChangeCommit(host, change, revision='current'):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000688 """Query a Gerrit server for a revision associated with a change."""
agable32978d92016-11-01 12:55:02 -0700689 path = 'changes/%s/revisions/%s/commit?links' % (change, revision)
690 return ReadHttpJsonResponse(CreateHttpConn(host, path))
691
692
szager@chromium.orgb4696232013-10-16 19:45:35 +0000693def GetChangeCurrentRevision(host, change):
694 """Get information about the latest revision for a given change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200695 return QueryChanges(host, [], change, o_params=('CURRENT_REVISION',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000696
697
698def GetChangeRevisions(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000699 """Gets information about all revisions associated with a change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200700 return QueryChanges(host, [], change, o_params=('ALL_REVISIONS',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000701
702
703def GetChangeReview(host, change, revision=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000704 """Gets the current review information for a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000705 if not revision:
706 jmsg = GetChangeRevisions(host, change)
707 if not jmsg:
708 return None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000709
710 if len(jmsg) > 1:
szager@chromium.orgb4696232013-10-16 19:45:35 +0000711 raise GerritError(200, 'Multiple changes found for ChangeId %s.' % change)
712 revision = jmsg[0]['current_revision']
713 path = 'changes/%s/revisions/%s/review'
714 return ReadHttpJsonResponse(CreateHttpConn(host, path))
715
716
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700717def GetChangeComments(host, change):
718 """Get the line- and file-level comments on a change."""
719 path = 'changes/%s/comments' % change
720 return ReadHttpJsonResponse(CreateHttpConn(host, path))
721
722
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000723def GetChangeRobotComments(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000724 """Gets the line- and file-level robot comments on a change."""
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000725 path = 'changes/%s/robotcomments' % change
726 return ReadHttpJsonResponse(CreateHttpConn(host, path))
727
728
Marco Georgaklis85557a02021-06-03 15:56:54 +0000729def GetRelatedChanges(host, change, revision='current'):
730 """Gets the related changes for a given change and revision."""
731 path = 'changes/%s/revisions/%s/related' % (change, revision)
732 return ReadHttpJsonResponse(CreateHttpConn(host, path))
733
734
szager@chromium.orgb4696232013-10-16 19:45:35 +0000735def AbandonChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000736 """Abandons a Gerrit change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000737 path = 'changes/%s/abandon' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000738 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000739 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700740 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000741
742
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000743def MoveChange(host, change, destination_branch):
744 """Move a Gerrit change to different destination branch."""
745 path = 'changes/%s/move' % change
Mike Frysingerf1c7d0d2020-12-15 20:05:36 +0000746 body = {'destination_branch': destination_branch,
747 'keep_all_votes': True}
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000748 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
749 return ReadHttpJsonResponse(conn)
750
751
752
szager@chromium.orgb4696232013-10-16 19:45:35 +0000753def RestoreChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000754 """Restores a previously abandoned change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000755 path = 'changes/%s/restore' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000756 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000757 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700758 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000759
760
Xinan Lin1bd4ffa2021-07-28 00:54:22 +0000761def SubmitChange(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000762 """Submits a Gerrit change via Gerrit."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000763 path = 'changes/%s/submit' % change
Xinan Lin1bd4ffa2021-07-28 00:54:22 +0000764 conn = CreateHttpConn(host, path, reqtype='POST')
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700765 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000766
767
Xinan Lin2b4ec952021-08-20 17:35:29 +0000768def GetChangesSubmittedTogether(host, change):
769 """Get all changes submitted with the given one."""
770 path = 'changes/%s/submitted_together?o=NON_VISIBLE_CHANGES' % change
771 conn = CreateHttpConn(host, path, reqtype='GET')
772 return ReadHttpJsonResponse(conn)
773
774
LaMont Jones9eed4232021-04-02 16:29:49 +0000775def PublishChangeEdit(host, change, notify=True):
776 """Publish a Gerrit change edit."""
777 path = 'changes/%s/edit:publish' % change
778 body = {'notify': 'ALL' if notify else 'NONE'}
779 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
780 return ReadHttpJsonResponse(conn, accept_statuses=(204, ))
781
782
783def ChangeEdit(host, change, path, data):
784 """Puts content of a file into a change edit."""
785 path = 'changes/%s/edit/%s' % (change, urllib.parse.quote(path, ''))
786 body = {
787 'binary_content':
Leszek Swirski4c0c3fb2022-06-08 17:04:02 +0000788 'data:text/plain;base64,%s' %
789 base64.b64encode(data.encode('utf-8')).decode('utf-8')
LaMont Jones9eed4232021-04-02 16:29:49 +0000790 }
791 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
792 return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
793
794
Leszek Swirskic1c45f82022-06-09 16:21:07 +0000795def SetChangeEditMessage(host, change, message):
796 """Sets the commit message of a change edit."""
797 path = 'changes/%s/edit:message' % change
798 body = {'message': message}
799 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
800 return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
801
802
dsansomee2d6fd92016-09-08 00:10:47 -0700803def HasPendingChangeEdit(host, change):
804 conn = CreateHttpConn(host, 'changes/%s/edit' % change)
805 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700806 ReadHttpResponse(conn)
dsansomee2d6fd92016-09-08 00:10:47 -0700807 except GerritError as e:
Aaron Gable19ee16c2017-04-18 11:56:35 -0700808 # 204 No Content means no pending change.
809 if e.http_status == 204:
810 return False
811 raise
812 return True
dsansomee2d6fd92016-09-08 00:10:47 -0700813
814
815def DeletePendingChangeEdit(host, change):
816 conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000817 # On success, Gerrit returns status 204; if the edit was already deleted it
Aaron Gable19ee16c2017-04-18 11:56:35 -0700818 # returns 404. Anything else is an error.
819 ReadHttpResponse(conn, accept_statuses=[204, 404])
dsansomee2d6fd92016-09-08 00:10:47 -0700820
821
Leszek Swirskic1c45f82022-06-09 16:21:07 +0000822def CherryPick(host, change, destination, revision='current'):
823 """Create a cherry-pick commit from the given change, onto the given
824 destination.
825 """
826 path = 'changes/%s/revisions/%s/cherrypick' % (change, revision)
827 body = {'destination': destination}
828 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
829 return ReadHttpJsonResponse(conn)
830
831
832def GetFileContents(host, change, path):
833 """Get the contents of a file with the given path in the given revision.
834
835 Returns:
836 A bytes object with the file's contents.
837 """
838 path = 'changes/%s/revisions/current/files/%s/content' % (
839 change, urllib.parse.quote(path, ''))
840 conn = CreateHttpConn(host, path, reqtype='GET')
841 return base64.b64decode(ReadHttpResponse(conn).read())
842
843
Andrii Shyshkalovea4fc832016-12-01 14:53:23 +0100844def SetCommitMessage(host, change, description, notify='ALL'):
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000845 """Updates a commit message."""
Aaron Gable7625d882017-06-26 09:47:26 -0700846 assert notify in ('ALL', 'NONE')
847 path = 'changes/%s/message' % change
Aaron Gable5a4ef452017-08-24 13:19:56 -0700848 body = {'message': description, 'notify': notify}
Aaron Gable7625d882017-06-26 09:47:26 -0700849 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000850 try:
Aaron Gable7625d882017-06-26 09:47:26 -0700851 ReadHttpResponse(conn, accept_statuses=[200, 204])
852 except GerritError as e:
853 raise GerritError(
854 e.http_status,
855 'Received unexpected http status while editing message '
856 'in change %s' % change)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000857
858
Xinan Linc2fb26a2021-07-27 18:01:55 +0000859def GetCommitIncludedIn(host, project, commit):
860 """Retrieves the branches and tags for a given commit.
861
862 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-included-in
863
864 Returns:
865 A JSON object with keys of 'branches' and 'tags'.
866 """
867 path = 'projects/%s/commits/%s/in' % (urllib.parse.quote(project, ''), commit)
868 conn = CreateHttpConn(host, path, reqtype='GET')
869 return ReadHttpJsonResponse(conn, accept_statuses=[200])
870
871
Edward Lesmes8170c292021-03-19 20:04:43 +0000872def IsCodeOwnersEnabledOnHost(host):
Edward Lesmes110823b2021-02-05 21:42:27 +0000873 """Check if the code-owners plugin is enabled for the host."""
874 path = 'config/server/capabilities'
875 capabilities = ReadHttpJsonResponse(CreateHttpConn(host, path))
876 return 'code-owners-checkCodeOwner' in capabilities
877
878
Edward Lesmes8170c292021-03-19 20:04:43 +0000879def IsCodeOwnersEnabledOnRepo(host, repo):
880 """Check if the code-owners plugin is enabled for the repo."""
881 repo = PercentEncodeForGitRef(repo)
882 path = '/projects/%s/code_owners.project_config' % repo
883 config = ReadHttpJsonResponse(CreateHttpConn(host, path))
Edward Lesmes743e98c2021-03-22 18:00:54 +0000884 return not config['status'].get('disabled', False)
Edward Lesmes8170c292021-03-19 20:04:43 +0000885
886
Gavin Make0fee9f2022-08-10 23:41:55 +0000887def GetOwnersForFile(host,
888 project,
889 branch,
890 path,
891 limit=100,
892 resolve_all_users=True,
893 highest_score_only=False,
894 seed=None,
895 o_params=('DETAILS',)):
Gavin Makc94b21d2020-12-10 20:27:32 +0000896 """Gets information about owners attached to a file."""
897 path = 'projects/%s/branches/%s/code_owners/%s' % (
898 urllib.parse.quote(project, ''),
899 urllib.parse.quote(branch, ''),
900 urllib.parse.quote(path, ''))
Gavin Mak7d690052021-02-25 19:14:22 +0000901 q = ['resolve-all-users=%s' % json.dumps(resolve_all_users)]
Gavin Make0fee9f2022-08-10 23:41:55 +0000902 if highest_score_only:
903 q.append('highest-score-only=%s' % json.dumps(highest_score_only))
Edward Lesmes23c3bdc2021-03-11 20:37:32 +0000904 if seed:
905 q.append('seed=%d' % seed)
Gavin Makc94b21d2020-12-10 20:27:32 +0000906 if limit:
907 q.append('n=%d' % limit)
908 if o_params:
909 q.extend(['o=%s' % p for p in o_params])
910 if q:
911 path = '%s?%s' % (path, '&'.join(q))
912 return ReadHttpJsonResponse(CreateHttpConn(host, path))
913
914
szager@chromium.orgb4696232013-10-16 19:45:35 +0000915def GetReviewers(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000916 """Gets information about all reviewers attached to a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000917 path = 'changes/%s/reviewers' % change
918 return ReadHttpJsonResponse(CreateHttpConn(host, path))
919
920
921def GetReview(host, change, revision):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000922 """Gets review information about a specific revision of a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000923 path = 'changes/%s/revisions/%s/review' % (change, revision)
924 return ReadHttpJsonResponse(CreateHttpConn(host, path))
925
926
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700927def AddReviewers(host, change, reviewers=None, ccs=None, notify=True,
928 accept_statuses=frozenset([200, 400, 422])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000929 """Add reviewers to a change."""
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700930 if not reviewers and not ccs:
Aaron Gabledf86e302016-11-08 10:48:03 -0800931 return None
Wiktor Garbacz6d0d0442017-05-15 12:34:40 +0200932 if not change:
933 return None
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700934 reviewers = frozenset(reviewers or [])
935 ccs = frozenset(ccs or [])
936 path = 'changes/%s/revisions/current/review' % change
937
938 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800939 'drafts': 'KEEP',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700940 'reviewers': [],
941 'notify': 'ALL' if notify else 'NONE',
942 }
943 for r in sorted(reviewers | ccs):
944 state = 'REVIEWER' if r in reviewers else 'CC'
945 body['reviewers'].append({
946 'reviewer': r,
947 'state': state,
948 'notify': 'NONE', # We handled `notify` argument above.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000949 })
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700950
951 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
952 # Gerrit will return 400 if one or more of the requested reviewers are
953 # unprocessable. We read the response object to see which were rejected,
954 # warn about them, and retry with the remainder.
955 resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses)
956
957 errored = set()
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000958 for result in resp.get('reviewers', {}).values():
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700959 r = result.get('input')
960 state = 'REVIEWER' if r in reviewers else 'CC'
961 if result.get('error'):
962 errored.add(r)
963 LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower()))
964 if errored:
965 # Try again, adding only those that didn't fail, and only accepting 200.
966 AddReviewers(host, change, reviewers=(reviewers-errored),
967 ccs=(ccs-errored), notify=notify, accept_statuses=[200])
szager@chromium.orgb4696232013-10-16 19:45:35 +0000968
969
Aaron Gable636b13f2017-07-14 10:42:48 -0700970def SetReview(host, change, msg=None, labels=None, notify=None, ready=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000971 """Sets labels and/or adds a message to a code review."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000972 if not msg and not labels:
973 return
974 path = 'changes/%s/revisions/current/review' % change
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800975 body = {'drafts': 'KEEP'}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000976 if msg:
977 body['message'] = msg
978 if labels:
979 body['labels'] = labels
Aaron Gablefc62f762017-07-17 11:12:07 -0700980 if notify is not None:
Aaron Gable75e78722017-06-09 10:40:16 -0700981 body['notify'] = 'ALL' if notify else 'NONE'
Aaron Gable636b13f2017-07-14 10:42:48 -0700982 if ready:
983 body['ready'] = True
szager@chromium.orgb4696232013-10-16 19:45:35 +0000984 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
985 response = ReadHttpJsonResponse(conn)
986 if labels:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000987 for key, val in labels.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000988 if ('labels' not in response or key not in response['labels'] or
989 int(response['labels'][key] != int(val))):
990 raise GerritError(200, 'Unable to set "%s" label on change %s.' % (
991 key, change))
Xinan Lin0b0738d2021-07-27 19:13:49 +0000992 return response
szager@chromium.orgb4696232013-10-16 19:45:35 +0000993
994def ResetReviewLabels(host, change, label, value='0', message=None,
995 notify=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000996 """Resets the value of a given label for all reviewers on a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000997 # This is tricky, because we want to work on the "current revision", but
998 # there's always the risk that "current revision" will change in between
999 # API calls. So, we check "current revision" at the beginning and end; if
1000 # it has changed, raise an exception.
1001 jmsg = GetChangeCurrentRevision(host, change)
1002 if not jmsg:
1003 raise GerritError(
1004 200, 'Could not get review information for change "%s"' % change)
1005 value = str(value)
1006 revision = jmsg[0]['current_revision']
1007 path = 'changes/%s/revisions/%s/review' % (change, revision)
1008 message = message or (
1009 '%s label set to %s programmatically.' % (label, value))
1010 jmsg = GetReview(host, change, revision)
1011 if not jmsg:
Quinten Yearsley925cedb2020-04-13 17:49:39 +00001012 raise GerritError(200, 'Could not get review information for revision %s '
szager@chromium.orgb4696232013-10-16 19:45:35 +00001013 'of change %s' % (revision, change))
1014 for review in jmsg.get('labels', {}).get(label, {}).get('all', []):
1015 if str(review.get('value', value)) != value:
1016 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -08001017 'drafts': 'KEEP',
szager@chromium.orgb4696232013-10-16 19:45:35 +00001018 'message': message,
1019 'labels': {label: value},
1020 'on_behalf_of': review['_account_id'],
1021 }
1022 if notify:
1023 body['notify'] = notify
1024 conn = CreateHttpConn(
1025 host, path, reqtype='POST', body=body)
1026 response = ReadHttpJsonResponse(conn)
1027 if str(response['labels'][label]) != value:
1028 username = review.get('email', jmsg.get('name', ''))
1029 raise GerritError(200, 'Unable to set %s label for user "%s"'
1030 ' on change %s.' % (label, username, change))
1031 jmsg = GetChangeCurrentRevision(host, change)
1032 if not jmsg:
1033 raise GerritError(
1034 200, 'Could not get review information for change "%s"' % change)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00001035
1036 if jmsg[0]['current_revision'] != revision:
szager@chromium.orgb4696232013-10-16 19:45:35 +00001037 raise GerritError(200, 'While resetting labels on change "%s", '
1038 'a new patchset was uploaded.' % change)
Dan Jacques8d11e482016-11-15 14:25:56 -08001039
1040
LaMont Jones9eed4232021-04-02 16:29:49 +00001041def CreateChange(host, project, branch='main', subject='', params=()):
1042 """
1043 Creates a new change.
1044
1045 Args:
1046 params: A list of additional ChangeInput specifiers, as documented here:
1047 (e.g. ('is_private', 'true') to mark the change private.
1048 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-input
1049
1050 Returns:
1051 ChangeInfo for the new change.
1052 """
1053 path = 'changes/'
1054 body = {'project': project, 'branch': branch, 'subject': subject}
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00001055 body.update(dict(params))
LaMont Jones9eed4232021-04-02 16:29:49 +00001056 for key in 'project', 'branch', 'subject':
1057 if not body[key]:
1058 raise GerritError(200, '%s is required' % key.title())
1059
1060 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
1061 return ReadHttpJsonResponse(conn, accept_statuses=[201])
1062
1063
dimu833c94c2017-01-18 17:36:15 -08001064def CreateGerritBranch(host, project, branch, commit):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001065 """Creates a new branch from given project and commit
1066
dimu833c94c2017-01-18 17:36:15 -08001067 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch
1068
1069 Returns:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001070 A JSON object with 'ref' key.
dimu833c94c2017-01-18 17:36:15 -08001071 """
1072 path = 'projects/%s/branches/%s' % (project, branch)
1073 body = {'revision': commit}
1074 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
dimu7d1af2b2017-04-19 16:01:17 -07001075 response = ReadHttpJsonResponse(conn, accept_statuses=[201])
dimu833c94c2017-01-18 17:36:15 -08001076 if response:
1077 return response
1078 raise GerritError(200, 'Unable to create gerrit branch')
1079
1080
Michael Mossb6ce2442021-10-20 04:36:24 +00001081def CreateGerritTag(host, project, tag, commit):
1082 """Creates a new tag at the given commit.
1083
1084 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-tag
1085
1086 Returns:
1087 A JSON object with 'ref' key.
1088 """
1089 path = 'projects/%s/tags/%s' % (project, tag)
1090 body = {'revision': commit}
1091 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
1092 response = ReadHttpJsonResponse(conn, accept_statuses=[201])
1093 if response:
1094 return response
1095 raise GerritError(200, 'Unable to create gerrit tag')
1096
1097
Josip Sokcevicdf9a8022020-12-08 00:10:19 +00001098def GetHead(host, project):
1099 """Retrieves current HEAD of Gerrit project
1100
1101 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head
1102
1103 Returns:
1104 A JSON object with 'ref' key.
1105 """
1106 path = 'projects/%s/HEAD' % (project)
1107 conn = CreateHttpConn(host, path, reqtype='GET')
1108 response = ReadHttpJsonResponse(conn, accept_statuses=[200])
1109 if response:
1110 return response
1111 raise GerritError(200, 'Unable to update gerrit HEAD')
1112
1113
1114def UpdateHead(host, project, branch):
1115 """Updates Gerrit HEAD to point to branch
1116
1117 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head
1118
1119 Returns:
1120 A JSON object with 'ref' key.
1121 """
1122 path = 'projects/%s/HEAD' % (project)
1123 body = {'ref': branch}
1124 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
1125 response = ReadHttpJsonResponse(conn, accept_statuses=[200])
1126 if response:
1127 return response
1128 raise GerritError(200, 'Unable to update gerrit HEAD')
1129
1130
dimu833c94c2017-01-18 17:36:15 -08001131def GetGerritBranch(host, project, branch):
Xinan Linaf79f242021-08-09 21:23:58 +00001132 """Gets a branch info from given project and branch name.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001133
1134 See:
dimu833c94c2017-01-18 17:36:15 -08001135 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch
1136
1137 Returns:
Xinan Linaf79f242021-08-09 21:23:58 +00001138 A JSON object with 'revision' key if the branch exists, otherwise None.
dimu833c94c2017-01-18 17:36:15 -08001139 """
1140 path = 'projects/%s/branches/%s' % (project, branch)
1141 conn = CreateHttpConn(host, path, reqtype='GET')
Xinan Linaf79f242021-08-09 21:23:58 +00001142 return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
dimu833c94c2017-01-18 17:36:15 -08001143
1144
Josip Sokcevicf736cab2020-10-20 23:41:38 +00001145def GetProjectHead(host, project):
1146 conn = CreateHttpConn(host,
1147 '/projects/%s/HEAD' % urllib.parse.quote(project, ''))
1148 return ReadHttpJsonResponse(conn, accept_statuses=[200])
1149
1150
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001151def GetAccountDetails(host, account_id='self'):
1152 """Returns details of the account.
1153
1154 If account_id is not given, uses magic value 'self' which corresponds to
1155 whichever account user is authenticating as.
1156
1157 Documentation:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001158 https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001159
1160 Returns None if account is not found (i.e., Gerrit returned 404).
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001161 """
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001162 conn = CreateHttpConn(host, '/accounts/%s' % account_id)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001163 return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
1164
1165
1166def ValidAccounts(host, accounts, max_threads=10):
1167 """Returns a mapping from valid account to its details.
1168
1169 Invalid accounts, either not existing or without unique match,
1170 are not present as returned dictionary keys.
1171 """
Edward Lemur0db01f02019-11-12 22:01:51 +00001172 assert not isinstance(accounts, str), type(accounts)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001173 accounts = list(set(accounts))
1174 if not accounts:
1175 return {}
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001176
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001177 def get_one(account):
1178 try:
1179 return account, GetAccountDetails(host, account)
1180 except GerritError:
1181 return None, None
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001182
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001183 valid = {}
1184 with contextlib.closing(ThreadPool(min(max_threads, len(accounts)))) as pool:
1185 for account, details in pool.map(get_one, accounts):
1186 if account and details:
1187 valid[account] = details
1188 return valid
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001189
1190
Nick Carter8692b182017-11-06 16:30:38 -08001191def PercentEncodeForGitRef(original):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001192 """Applies percent-encoding for strings sent to Gerrit via git ref metadata.
Nick Carter8692b182017-11-06 16:30:38 -08001193
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001194 The encoding used is based on but stricter than URL encoding (Section 2.1 of
1195 RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE'
1196 (U+0020) can be represented as 'LOW LINE' (U+005F) or 'PLUS SIGN' (U+002B).
Nick Carter8692b182017-11-06 16:30:38 -08001197
1198 For more information, see the Gerrit docs here:
1199
1200 https://gerrit-review.googlesource.com/Documentation/user-upload.html#message
1201 """
1202 safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
1203 encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original)
1204
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001205 # Spaces are not allowed in git refs; gerrit will interpret either '_' or
Nick Carter8692b182017-11-06 16:30:38 -08001206 # '+' (or '%20') as space. Use '_' since that has been supported the longest.
1207 return encoded.replace(' ', '_')
1208
1209
Dan Jacques8d11e482016-11-15 14:25:56 -08001210@contextlib.contextmanager
1211def tempdir():
1212 tdir = None
1213 try:
1214 tdir = tempfile.mkdtemp(suffix='gerrit_util')
1215 yield tdir
1216 finally:
1217 if tdir:
1218 gclient_utils.rmtree(tdir)
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001219
1220
1221def ChangeIdentifier(project, change_number):
Edward Lemur687ca902018-12-05 02:30:30 +00001222 """Returns change identifier "project~number" suitable for |change| arg of
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001223 this module API.
1224
1225 Such format is allows for more efficient Gerrit routing of HTTP requests,
1226 comparing to specifying just change_number.
1227 """
1228 assert int(change_number)
Edward Lemur4ba192e2019-10-28 20:19:37 +00001229 return '%s~%s' % (urllib.parse.quote(project, ''), change_number)