blob: 8312bbac724eb84d08ef6401ee1dacf363c92501 [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
Gavin Mak42674f52023-08-24 20:39:59 +000011from __future__ import print_function
12from __future__ import unicode_literals
13
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
Gavin Mak42674f52023-08-24 20:39:59 +000036from third_party import six
Edward Lemur4ba192e2019-10-28 20:19:37 +000037from six.moves import urllib
38
Gavin Mak42674f52023-08-24 20:39:59 +000039if 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
Edward Lemur4ba192e2019-10-28 20:19:37 +000045
szager@chromium.orgb4696232013-10-16 19:45:35 +000046LOGGER = logging.getLogger()
Gavin Makfc75af32023-06-20 20:06:27 +000047# With a starting sleep time of 12.0 seconds, x <= [1.8-2.2]x backoff, and six
48# total tries, the sleep time between the first and last tries will be ~6 min
49# (excluding time for each try).
50TRY_LIMIT = 6
51SLEEP_TIME = 12.0
George Engelbrecht888c0fe2020-04-17 15:00:20 +000052MAX_BACKOFF = 2.2
53MIN_BACKOFF = 1.8
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +000054
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +000055# Controls the transport protocol used to communicate with Gerrit.
szager@chromium.orgb4696232013-10-16 19:45:35 +000056# This is parameterized primarily to enable GerritTestCase.
57GERRIT_PROTOCOL = 'https'
58
59
Edward Lemur4ba192e2019-10-28 20:19:37 +000060def time_sleep(seconds):
61 # Use this so that it can be mocked in tests without interfering with python
62 # system machinery.
63 return time.sleep(seconds)
64
65
Edward Lemura3b6fd02020-03-02 22:16:15 +000066def time_time():
67 # Use this so that it can be mocked in tests without interfering with python
68 # system machinery.
69 return time.time()
70
71
Ben Pastene9519fc12023-04-12 22:15:43 +000072def log_retry_and_sleep(seconds, attempt):
73 LOGGER.info('Will retry in %d seconds (%d more times)...', seconds,
74 TRY_LIMIT - attempt - 1)
75 time_sleep(seconds)
76 return seconds * random.uniform(MIN_BACKOFF, MAX_BACKOFF)
77
78
szager@chromium.orgb4696232013-10-16 19:45:35 +000079class GerritError(Exception):
80 """Exception class for errors commuicating with the gerrit-on-borg service."""
Edward Lemur4ba192e2019-10-28 20:19:37 +000081 def __init__(self, http_status, message, *args, **kwargs):
szager@chromium.orgb4696232013-10-16 19:45:35 +000082 super(GerritError, self).__init__(*args, **kwargs)
83 self.http_status = http_status
Edward Lemur4ba192e2019-10-28 20:19:37 +000084 self.message = '(%d) %s' % (self.http_status, message)
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000085
Josip Sokcevicdf9a8022020-12-08 00:10:19 +000086 def __str__(self):
87 return self.message
88
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +000089
Michael Achenbach6fbf12f2017-07-06 10:54:11 +020090def _QueryString(params, first_param=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +000091 """Encodes query parameters in the key:val[+key:val...] format specified here:
92
93 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
94 """
Edward Lemur4ba192e2019-10-28 20:19:37 +000095 q = [urllib.parse.quote(first_param)] if first_param else []
Josip Sokcevicf5c6d8a2021-05-12 18:23:24 +000096 q.extend(['%s:%s' % (key, val.replace(" ", "+")) for key, val in params])
szager@chromium.orgb4696232013-10-16 19:45:35 +000097 return '+'.join(q)
98
99
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000100class Authenticator(object):
101 """Base authenticator class for authenticator implementations to subclass."""
102
103 def get_auth_header(self, host):
104 raise NotImplementedError()
105
106 @staticmethod
107 def get():
108 """Returns: (Authenticator) The identified Authenticator to use.
109
110 Probes the local system and its environment and identifies the
111 Authenticator instance to use.
112 """
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700113 # LUCI Context takes priority since it's normally present only on bots,
114 # which then must use it.
115 if LuciContextAuthenticator.is_luci():
116 return LuciContextAuthenticator()
Edward Lemur57d47422020-03-06 20:43:07 +0000117 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop,
118 # and use CookiesAuthenticator instead.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000119 if GceAuthenticator.is_gce():
120 return GceAuthenticator()
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000121 return CookiesAuthenticator()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000122
123
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000124class CookiesAuthenticator(Authenticator):
125 """Authenticator implementation that uses ".netrc" or ".gitcookies" for token.
126
127 Expected case for developer workstations.
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000128 """
129
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000130 _EMPTY = object()
131
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000132 def __init__(self):
Vadim Shtayurab250ec12018-10-04 00:21:08 +0000133 # Credentials will be loaded lazily on first use. This ensures Authenticator
134 # get() can always construct an authenticator, even if something is broken.
135 # This allows 'creds-check' to proceed to actually checking creds later,
136 # rigorously (instead of blowing up with a cryptic error if they are wrong).
137 self._netrc = self._EMPTY
138 self._gitcookies = self._EMPTY
139
140 @property
141 def netrc(self):
142 if self._netrc is self._EMPTY:
143 self._netrc = self._get_netrc()
144 return self._netrc
145
146 @property
147 def gitcookies(self):
148 if self._gitcookies is self._EMPTY:
149 self._gitcookies = self._get_gitcookies()
150 return self._gitcookies
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000151
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000152 @classmethod
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200153 def get_new_password_url(cls, host):
154 assert not host.startswith('http')
155 # Assume *.googlesource.com pattern.
156 parts = host.split('.')
Aravind Vasudevana02b4bf2023-02-03 17:52:03 +0000157
158 # remove -review suffix if present.
159 if parts[0].endswith('-review'):
160 parts[0] = parts[0][:-len('-review')]
161
Andrii Shyshkalovc8173822017-07-10 12:10:53 +0200162 return 'https://%s/new-password' % ('.'.join(parts))
163
164 @classmethod
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000165 def get_new_password_message(cls, host):
William Hessee9e89e32019-03-03 19:02:32 +0000166 if host is None:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000167 return ('Git host for Gerrit upload is unknown. Check your remote '
William Hessee9e89e32019-03-03 19:02:32 +0000168 'and the branch your branch is tracking. This tool assumes '
169 'that you are using a git server at *.googlesource.com.')
Edward Lemur67fccdf2019-10-22 22:17:10 +0000170 url = cls.get_new_password_url(host)
Andrii Shyshkalov0a0b0672017-03-16 16:27:48 +0100171 return 'You can (re)generate your credentials by visiting %s' % url
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000172
173 @classmethod
174 def get_netrc_path(cls):
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000175 path = '_netrc' if sys.platform.startswith('win') else '.netrc'
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000176 return os.path.expanduser(os.path.join('~', path))
177
178 @classmethod
179 def _get_netrc(cls):
Dan Jacques8d11e482016-11-15 14:25:56 -0800180 # Buffer the '.netrc' path. Use an empty file if it doesn't exist.
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000181 path = cls.get_netrc_path()
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000182 if not os.path.exists(path):
183 return netrc.netrc(os.devnull)
184
185 st = os.stat(path)
186 if st.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
Raul Tambre80ee78e2019-05-06 22:41:05 +0000187 print(
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000188 'WARNING: netrc file %s cannot be used because its file '
189 'permissions are insecure. netrc file permissions should be '
Raul Tambre80ee78e2019-05-06 22:41:05 +0000190 '600.' % path, file=sys.stderr)
Sylvain Defresne2b138f72018-07-12 08:34:48 +0000191 with open(path) as fd:
192 content = fd.read()
Dan Jacques8d11e482016-11-15 14:25:56 -0800193
194 # Load the '.netrc' file. We strip comments from it because processing them
195 # can trigger a bug in Windows. See crbug.com/664664.
196 content = '\n'.join(l for l in content.splitlines()
197 if l.strip() and not l.strip().startswith('#'))
198 with tempdir() as tdir:
199 netrc_path = os.path.join(tdir, 'netrc')
200 with open(netrc_path, 'w') as fd:
201 fd.write(content)
202 os.chmod(netrc_path, (stat.S_IRUSR | stat.S_IWUSR))
203 return cls._get_netrc_from_path(netrc_path)
204
205 @classmethod
206 def _get_netrc_from_path(cls, path):
207 try:
208 return netrc.netrc(path)
209 except IOError:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000210 print('WARNING: Could not read netrc file %s' % path, file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800211 return netrc.netrc(os.devnull)
212 except netrc.NetrcParseError as e:
Raul Tambre80ee78e2019-05-06 22:41:05 +0000213 print('ERROR: Cannot use netrc file %s due to a parsing error: %s' %
214 (path, e), file=sys.stderr)
Dan Jacques8d11e482016-11-15 14:25:56 -0800215 return netrc.netrc(os.devnull)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000216
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000217 @classmethod
218 def get_gitcookies_path(cls):
Ravi Mistry0bfa9ad2016-11-21 12:58:31 -0500219 if os.getenv('GIT_COOKIES_PATH'):
220 return os.getenv('GIT_COOKIES_PATH')
Aaron Gable8797cab2018-03-06 13:55:00 -0800221 try:
Edward Lesmes5a5537d2020-04-01 20:52:30 +0000222 path = subprocess2.check_output(
223 ['git', 'config', '--path', 'http.cookiefile'])
224 return path.decode('utf-8', 'ignore').strip()
Aaron Gable8797cab2018-03-06 13:55:00 -0800225 except subprocess2.CalledProcessError:
Josip Sokcevic464e9ff2020-03-18 23:48:55 +0000226 return os.path.expanduser(os.path.join('~', '.gitcookies'))
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000227
228 @classmethod
229 def _get_gitcookies(cls):
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000230 gitcookies = {}
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000231 path = cls.get_gitcookies_path()
232 if not os.path.exists(path):
233 return gitcookies
234
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000235 try:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000236 f = gclient_utils.FileRead(path, 'rb').splitlines()
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000237 except IOError:
238 return gitcookies
239
Edward Lemur67fccdf2019-10-22 22:17:10 +0000240 for line in f:
241 try:
242 fields = line.strip().split('\t')
243 if line.strip().startswith('#') or len(fields) != 7:
244 continue
245 domain, xpath, key, value = fields[0], fields[2], fields[5], fields[6]
246 if xpath == '/' and key == 'o':
247 if value.startswith('git-'):
248 login, secret_token = value.split('=', 1)
249 gitcookies[domain] = (login, secret_token)
250 else:
251 gitcookies[domain] = ('', value)
252 except (IndexError, ValueError, TypeError) as exc:
253 LOGGER.warning(exc)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000254 return gitcookies
255
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100256 def _get_auth_for_host(self, host):
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000257 for domain, creds in self.gitcookies.items():
Gavin Mak42674f52023-08-24 20:39:59 +0000258 if cookielib.domain_match(host, domain):
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100259 return (creds[0], None, creds[1])
260 return self.netrc.authenticators(host)
phajdan.jr@chromium.orgff7840a2015-11-04 16:35:22 +0000261
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100262 def get_auth_header(self, host):
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700263 a = self._get_auth_for_host(host)
264 if a:
Eric Boren2fb63102018-10-05 13:05:03 +0000265 if a[0]:
Edward Lemur67fccdf2019-10-22 22:17:10 +0000266 secret = base64.b64encode(('%s:%s' % (a[0], a[2])).encode('utf-8'))
267 return 'Basic %s' % secret.decode('utf-8')
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000268
269 return 'Bearer %s' % a[2]
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000270 return None
271
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100272 def get_auth_email(self, host):
273 """Best effort parsing of email to be used for auth for the given host."""
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700274 a = self._get_auth_for_host(host)
275 if not a:
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100276 return None
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700277 login = a[0]
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +0100278 # login typically looks like 'git-xxx.example.com'
279 if not login.startswith('git-') or '.' not in login:
280 return None
281 username, domain = login[len('git-'):].split('.', 1)
282 return '%s@%s' % (username, domain)
283
Andrii Shyshkalov18975322017-01-25 16:44:13 +0100284
tandrii@chromium.orgfe30f182016-04-13 12:15:04 +0000285# Backwards compatibility just in case somebody imports this outside of
286# depot_tools.
287NetrcAuthenticator = CookiesAuthenticator
288
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000289
290class GceAuthenticator(Authenticator):
291 """Authenticator implementation that uses GCE metadata service for token.
292 """
293
294 _INFO_URL = 'http://metadata.google.internal'
smut5e9401b2017-08-10 15:22:20 -0700295 _ACQUIRE_URL = ('%s/computeMetadata/v1/instance/'
296 'service-accounts/default/token' % _INFO_URL)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000297 _ACQUIRE_HEADERS = {"Metadata-Flavor": "Google"}
298
299 _cache_is_gce = None
300 _token_cache = None
301 _token_expiration = None
302
303 @classmethod
304 def is_gce(cls):
Ravi Mistryfad941b2016-11-15 13:00:47 -0500305 if os.getenv('SKIP_GCE_AUTH_FOR_GIT'):
306 return False
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000307 if cls._cache_is_gce is None:
308 cls._cache_is_gce = cls._test_is_gce()
309 return cls._cache_is_gce
310
311 @classmethod
312 def _test_is_gce(cls):
313 # Based on https://cloud.google.com/compute/docs/metadata#runninggce
Edward Lemura3b6fd02020-03-02 22:16:15 +0000314 resp, _ = cls._get(cls._INFO_URL)
315 if resp is None:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000316 return False
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100317 return resp.get('metadata-flavor') == 'Google'
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000318
319 @staticmethod
320 def _get(url, **kwargs):
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000321 next_delay_sec = 1.0
Edward Lemura3b6fd02020-03-02 22:16:15 +0000322 for i in range(TRY_LIMIT):
Edward Lemur4ba192e2019-10-28 20:19:37 +0000323 p = urllib.parse.urlparse(url)
324 if p.scheme not in ('http', 'https'):
325 raise RuntimeError(
326 "Don't know how to work with protocol '%s'" % protocol)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000327 try:
328 resp, contents = httplib2.Http().request(url, 'GET', **kwargs)
Raphael Kubo da Costa9f6aa1b2021-06-24 16:59:31 +0000329 except (socket.error, httplib2.HttpLib2Error,
330 httplib2.socks.ProxyError) as e:
Edward Lemura3b6fd02020-03-02 22:16:15 +0000331 LOGGER.debug('GET [%s] raised %s', url, e)
332 return None, None
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000333 LOGGER.debug('GET [%s] #%d/%d (%d)', url, i+1, TRY_LIMIT, resp.status)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000334 if resp.status < 500:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100335 return (resp, contents)
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000336
Aaron Gable92e9f382017-12-07 11:47:41 -0800337 # Retry server error status codes.
338 LOGGER.warn('Encountered server error')
339 if TRY_LIMIT - i > 1:
Ben Pastene9519fc12023-04-12 22:15:43 +0000340 next_delay_sec = log_retry_and_sleep(next_delay_sec, i)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000341 return None, None
Aaron Gable92e9f382017-12-07 11:47:41 -0800342
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000343 @classmethod
344 def _get_token_dict(cls):
Edward Lemura3b6fd02020-03-02 22:16:15 +0000345 # If cached token is valid for at least 25 seconds, return it.
346 if cls._token_cache and time_time() + 25 < cls._token_expiration:
347 return cls._token_cache
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000348
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100349 resp, contents = cls._get(cls._ACQUIRE_URL, headers=cls._ACQUIRE_HEADERS)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000350 if resp is None or resp.status != 200:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000351 return None
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100352 cls._token_cache = json.loads(contents)
Edward Lemura3b6fd02020-03-02 22:16:15 +0000353 cls._token_expiration = cls._token_cache['expires_in'] + time_time()
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000354 return cls._token_cache
355
356 def get_auth_header(self, _host):
357 token_dict = self._get_token_dict()
358 if not token_dict:
359 return None
360 return '%(token_type)s %(access_token)s' % token_dict
361
362
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700363class LuciContextAuthenticator(Authenticator):
364 """Authenticator implementation that uses LUCI_CONTEXT ambient local auth.
365 """
366
367 @staticmethod
368 def is_luci():
369 return auth.has_luci_context_local_auth()
370
371 def __init__(self):
Edward Lemur5b929a42019-10-21 17:57:39 +0000372 self._authenticator = auth.Authenticator(
373 ' '.join([auth.OAUTH_SCOPE_EMAIL, auth.OAUTH_SCOPE_GERRIT]))
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700374
375 def get_auth_header(self, _host):
Edward Lemur5b929a42019-10-21 17:57:39 +0000376 return 'Bearer %s' % self._authenticator.get_access_token().token
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700377
378
Ben Pastene04182552023-04-13 20:10:21 +0000379def CreateHttpConn(host,
380 path,
381 reqtype='GET',
382 headers=None,
383 body=None,
Xinan Lin1344a3c2023-05-02 21:55:43 +0000384 timeout=300):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000385 """Opens an HTTPS connection to a Gerrit service, and sends a request."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000386 headers = headers or {}
387 bare_host = host.partition(':')[0]
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000388
Edward Lemur447507e2020-03-31 17:33:54 +0000389 a = Authenticator.get()
390 # TODO(crbug.com/1059384): Automatically detect when running on cloudtop.
391 if isinstance(a, GceAuthenticator):
392 print('If you\'re on a cloudtop instance, export '
393 'SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
394
395 a = a.get_auth_header(bare_host)
Andrii Shyshkalov733d4ec2018-04-19 11:48:58 -0700396 if a:
397 headers.setdefault('Authorization', a)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000398 else:
dnj@chromium.orga5a2c8a2015-09-29 16:22:55 +0000399 LOGGER.debug('No authorization found for %s.' % bare_host)
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000400
Dan Jacques6d5bcc22016-11-14 15:32:04 -0800401 url = path
402 if not url.startswith('/'):
403 url = '/' + url
404 if 'Authorization' in headers and not url.startswith('/a/'):
405 url = '/a%s' % url
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000406
szager@chromium.orgb4696232013-10-16 19:45:35 +0000407 if body:
Edward Lemur4ba192e2019-10-28 20:19:37 +0000408 body = json.dumps(body, sort_keys=True)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000409 headers.setdefault('Content-Type', 'application/json')
410 if LOGGER.isEnabledFor(logging.DEBUG):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000411 LOGGER.debug('%s %s://%s%s' % (reqtype, GERRIT_PROTOCOL, host, url))
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000412 for key, val in headers.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000413 if key == 'Authorization':
414 val = 'HIDDEN'
415 LOGGER.debug('%s: %s' % (key, val))
416 if body:
417 LOGGER.debug(body)
Ben Pastene04182552023-04-13 20:10:21 +0000418 conn = httplib2.Http(timeout=timeout)
Edward Lemur4ba192e2019-10-28 20:19:37 +0000419 # HACK: httplib2.Http has no such attribute; we store req_host here for later
Andrii Shyshkalov86c823e2018-09-18 19:51:33 +0000420 # use in ReadHttpResponse.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000421 conn.req_host = host
422 conn.req_params = {
Edward Lemur4ba192e2019-10-28 20:19:37 +0000423 'uri': urllib.parse.urljoin('%s://%s' % (GERRIT_PROTOCOL, host), url),
szager@chromium.orgb4696232013-10-16 19:45:35 +0000424 'method': reqtype,
425 'headers': headers,
426 'body': body,
427 }
szager@chromium.orgb4696232013-10-16 19:45:35 +0000428 return conn
429
430
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700431def ReadHttpResponse(conn, accept_statuses=frozenset([200])):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000432 """Reads an HTTP response from a connection into a string buffer.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000433
434 Args:
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100435 conn: An Http object created by CreateHttpConn above.
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700436 accept_statuses: Treat any of these statuses as success. Default: [200]
437 Common additions include 204, 400, and 404.
szager@chromium.orgb4696232013-10-16 19:45:35 +0000438 Returns: A string buffer containing the connection's reply.
439 """
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000440 sleep_time = SLEEP_TIME
szager@chromium.orgb4696232013-10-16 19:45:35 +0000441 for idx in range(TRY_LIMIT):
Edward Lemur5a9ff432018-10-30 19:00:22 +0000442 before_response = time.time()
Ben Pastene9519fc12023-04-12 22:15:43 +0000443 try:
444 response, contents = conn.request(**conn.req_params)
445 except socket.timeout:
446 if idx < TRY_LIMIT - 1:
447 sleep_time = log_retry_and_sleep(sleep_time, idx)
448 continue
449 raise
Edward Lemur4ba192e2019-10-28 20:19:37 +0000450 contents = contents.decode('utf-8', 'replace')
nodir@chromium.orgce32b6e2014-05-12 20:31:32 +0000451
Edward Lemur5a9ff432018-10-30 19:00:22 +0000452 response_time = time.time() - before_response
453 metrics.collector.add_repeated(
454 'http_requests',
455 metrics_utils.extract_http_metrics(
456 conn.req_params['uri'], conn.req_params['method'], response.status,
457 response_time))
458
Edward Lemur4ba192e2019-10-28 20:19:37 +0000459 # If response.status is an accepted status,
460 # or response.status < 500 then the result is final; break retry loop.
461 # If the response is 404/409 it might be because of replication lag,
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000462 # so keep trying anyway. If it is 429, it is generally ok to retry after
463 # a backoff.
Edward Lemur4ba192e2019-10-28 20:19:37 +0000464 if (response.status in accept_statuses
George Engelbrecht888c0fe2020-04-17 15:00:20 +0000465 or response.status < 500 and response.status not in [404, 409, 429]):
Andrii Shyshkalov5b04a572017-01-23 17:44:41 +0100466 LOGGER.debug('got response %d for %s %s', response.status,
Raphael Kubo da Costa89d04852017-03-23 19:04:31 +0100467 conn.req_params['method'], conn.req_params['uri'])
Michael Mossb40a4512017-10-10 11:07:17 -0700468 # If 404 was in accept_statuses, then it's expected that the file might
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000469 # not exist, so don't return the gitiles error page because that's not
470 # the "content" that was actually requested.
Michael Mossb40a4512017-10-10 11:07:17 -0700471 if response.status == 404:
472 contents = ''
szager@chromium.orgb4696232013-10-16 19:45:35 +0000473 break
Edward Lemur4ba192e2019-10-28 20:19:37 +0000474
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000475 # A status >=500 is assumed to be a possible transient error; retry.
476 http_version = 'HTTP/%s' % ('1.1' if response.version == 11 else '1.0')
477 LOGGER.warn('A transient error occurred while querying %s:\n'
478 '%s %s %s\n'
Edward Lesmesb0739992020-10-09 23:15:44 +0000479 '%s %d %s\n'
480 '%s',
Edward Lemur49c8eaf2018-11-07 22:13:12 +0000481 conn.req_host, conn.req_params['method'],
482 conn.req_params['uri'],
Edward Lesmesb0739992020-10-09 23:15:44 +0000483 http_version, http_version, response.status, response.reason,
484 contents)
Andrii Shyshkalovd4c86732018-09-25 04:29:31 +0000485
Edward Lemur4ba192e2019-10-28 20:19:37 +0000486 if idx < TRY_LIMIT - 1:
Ben Pastene9519fc12023-04-12 22:15:43 +0000487 sleep_time = log_retry_and_sleep(sleep_time, idx)
Edward Lemur83bd7f42018-10-10 00:14:21 +0000488 # end of retries loop
Edward Lemur4ba192e2019-10-28 20:19:37 +0000489
490 if response.status in accept_statuses:
491 return StringIO(contents)
492
493 if response.status in (302, 401, 403):
494 www_authenticate = response.get('www-authenticate')
495 if not www_authenticate:
496 print('Your Gerrit credentials might be misconfigured.')
497 else:
498 auth_match = re.search('realm="([^"]+)"', www_authenticate, re.I)
499 host = auth_match.group(1) if auth_match else conn.req_host
500 print('Authentication failed. Please make sure your .gitcookies '
501 'file has credentials for %s.' % host)
502 print('Try:\n git cl creds-check')
503
504 reason = '%s: %s' % (response.reason, contents)
505 raise GerritError(response.status, reason)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000506
507
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700508def ReadHttpJsonResponse(conn, accept_statuses=frozenset([200])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000509 """Parses an https response as json."""
Aaron Gable19ee16c2017-04-18 11:56:35 -0700510 fh = ReadHttpResponse(conn, accept_statuses)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000511 # The first line of the response should always be: )]}'
512 s = fh.readline()
513 if s and s.rstrip() != ")]}'":
514 raise GerritError(200, 'Unexpected json output: %s' % s)
515 s = fh.read()
516 if not s:
517 return None
518 return json.loads(s)
519
520
Michael Moss9c28af42021-10-25 16:59:05 +0000521def CallGerritApi(host, path, **kwargs):
522 """Helper for calling a Gerrit API that returns a JSON response."""
523 conn_kwargs = {}
524 conn_kwargs.update(
525 (k, kwargs[k]) for k in ['reqtype', 'headers', 'body'] if k in kwargs)
526 conn = CreateHttpConn(host, path, **conn_kwargs)
527 read_kwargs = {}
528 read_kwargs.update((k, kwargs[k]) for k in ['accept_statuses'] if k in kwargs)
529 return ReadHttpJsonResponse(conn, **read_kwargs)
530
531
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200532def QueryChanges(host, params, first_param=None, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100533 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000534 """
535 Queries a gerrit-on-borg server for changes matching query terms.
536
537 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200538 params: A list of key:value pairs for search parameters, as documented
539 here (e.g. ('is', 'owner') for a parameter 'is:owner'):
540 https://gerrit-review.googlesource.com/Documentation/user-search.html#search-operators
szager@chromium.orgb4696232013-10-16 19:45:35 +0000541 first_param: A change identifier
542 limit: Maximum number of results to return.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100543 start: how many changes to skip (starting with the most recent)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000544 o_params: A list of additional output specifiers, as documented here:
545 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#list-changes
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000546
szager@chromium.orgb4696232013-10-16 19:45:35 +0000547 Returns:
548 A list of json-decoded query results.
549 """
550 # Note that no attempt is made to escape special characters; YMMV.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200551 if not params and not first_param:
szager@chromium.orgb4696232013-10-16 19:45:35 +0000552 raise RuntimeError('QueryChanges requires search parameters')
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200553 path = 'changes/?q=%s' % _QueryString(params, first_param)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100554 if start:
555 path = '%s&start=%s' % (path, start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000556 if limit:
557 path = '%s&n=%d' % (path, limit)
558 if o_params:
559 path = '%s&%s' % (path, '&'.join(['o=%s' % p for p in o_params]))
Ben Pastene97dadd02023-04-14 21:55:38 +0000560 return ReadHttpJsonResponse(CreateHttpConn(host, path, timeout=30.0))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000561
562
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200563def GenerateAllChanges(host, params, first_param=None, limit=500,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100564 o_params=None, start=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000565 """Queries a gerrit-on-borg server for all the changes matching the query
566 terms.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000567
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100568 WARNING: this is unreliable if a change matching the query is modified while
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000569 this function is being called.
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100570
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000571 A single query to gerrit-on-borg is limited on the number of results by the
572 limit parameter on the request (see QueryChanges) and the server maximum
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100573 limit.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000574
575 Args:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200576 params, first_param: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000577 limit: Maximum number of requested changes per query.
578 o_params: Refer to QueryChanges().
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100579 start: Refer to QueryChanges().
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000580
581 Returns:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100582 A generator object to the list of returned changes.
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000583 """
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100584 already_returned = set()
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000585
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100586 def at_most_once(cls):
587 for cl in cls:
588 if cl['_number'] not in already_returned:
589 already_returned.add(cl['_number'])
590 yield cl
591
592 start = start or 0
593 cur_start = start
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000594 more_changes = True
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100595
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000596 while more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100597 # This will fetch changes[start..start+limit] sorted by most recently
598 # updated. Since the rank of any change in this list can be changed any time
599 # (say user posting comment), subsequent calls may overalp like this:
600 # > initial order ABCDEFGH
601 # query[0..3] => ABC
Quinten Yearsley925cedb2020-04-13 17:49:39 +0000602 # > E gets updated. New order: EABCDFGH
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100603 # query[3..6] => CDF # C is a dup
604 # query[6..9] => GH # E is missed.
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200605 page = QueryChanges(host, params, first_param, limit, o_params,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100606 cur_start)
607 for cl in at_most_once(page):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000608 yield cl
609
610 more_changes = [cl for cl in page if '_more_changes' in cl]
611 if len(more_changes) > 1:
612 raise GerritError(
613 200,
614 'Received %d changes with a _more_changes attribute set but should '
615 'receive at most one.' % len(more_changes))
616 if more_changes:
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100617 cur_start += len(page)
618
619 # If we paged through, query again the first page which in most circumstances
620 # will fetch all changes that were modified while this function was run.
621 if start != cur_start:
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200622 page = QueryChanges(host, params, first_param, limit, o_params, start)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100623 for cl in at_most_once(page):
624 yield cl
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000625
626
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200627def MultiQueryChanges(host, params, change_list, limit=None, o_params=None,
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100628 start=None):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000629 """Initiate a query composed of multiple sets of query parameters."""
630 if not change_list:
631 raise RuntimeError(
632 "MultiQueryChanges requires a list of change numbers/id's")
Edward Lemur4ba192e2019-10-28 20:19:37 +0000633 q = ['q=%s' % '+OR+'.join([urllib.parse.quote(str(x)) for x in change_list])]
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200634 if params:
635 q.append(_QueryString(params))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000636 if limit:
637 q.append('n=%d' % limit)
Andrii Shyshkalov892e9c22017-03-08 16:21:21 +0100638 if start:
639 q.append('S=%s' % start)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000640 if o_params:
641 q.extend(['o=%s' % p for p in o_params])
642 path = 'changes/?%s' % '&'.join(q)
643 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700644 result = ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000645 except GerritError as e:
646 msg = '%s:\n%s' % (e.message, path)
647 raise GerritError(e.http_status, msg)
648 return result
649
650
651def GetGerritFetchUrl(host):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000652 """Given a Gerrit host name returns URL of a Gerrit instance to fetch from."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000653 return '%s://%s/' % (GERRIT_PROTOCOL, host)
654
655
Edward Lemur687ca902018-12-05 02:30:30 +0000656def GetCodeReviewTbrScore(host, project):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000657 """Given a Gerrit host name and project, return the Code-Review score for TBR.
Edward Lemur687ca902018-12-05 02:30:30 +0000658 """
Edward Lemur4ba192e2019-10-28 20:19:37 +0000659 conn = CreateHttpConn(
660 host, '/projects/%s' % urllib.parse.quote(project, ''))
Edward Lemur687ca902018-12-05 02:30:30 +0000661 project = ReadHttpJsonResponse(conn)
662 if ('labels' not in project
663 or 'Code-Review' not in project['labels']
664 or 'values' not in project['labels']['Code-Review']):
665 return 1
666 return max([int(x) for x in project['labels']['Code-Review']['values']])
667
668
szager@chromium.orgb4696232013-10-16 19:45:35 +0000669def GetChangePageUrl(host, change_number):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000670 """Given a Gerrit host name and change number, returns change page URL."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000671 return '%s://%s/#/c/%d/' % (GERRIT_PROTOCOL, host, change_number)
672
673
674def GetChangeUrl(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000675 """Given a Gerrit host name and change ID, returns a URL for the change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000676 return '%s://%s/a/changes/%s' % (GERRIT_PROTOCOL, host, change)
677
678
679def GetChange(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000680 """Queries a Gerrit server for information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000681 path = 'changes/%s' % change
682 return ReadHttpJsonResponse(CreateHttpConn(host, path))
683
684
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700685def GetChangeDetail(host, change, o_params=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000686 """Queries a Gerrit server for extended information about a single change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000687 path = 'changes/%s/detail' % change
688 if o_params:
689 path += '?%s' % '&'.join(['o=%s' % p for p in o_params])
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700690 return ReadHttpJsonResponse(CreateHttpConn(host, path))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000691
692
agable32978d92016-11-01 12:55:02 -0700693def GetChangeCommit(host, change, revision='current'):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000694 """Query a Gerrit server for a revision associated with a change."""
agable32978d92016-11-01 12:55:02 -0700695 path = 'changes/%s/revisions/%s/commit?links' % (change, revision)
696 return ReadHttpJsonResponse(CreateHttpConn(host, path))
697
698
szager@chromium.orgb4696232013-10-16 19:45:35 +0000699def GetChangeCurrentRevision(host, change):
700 """Get information about the latest revision for a given change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200701 return QueryChanges(host, [], change, o_params=('CURRENT_REVISION',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000702
703
704def GetChangeRevisions(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000705 """Gets information about all revisions associated with a change."""
Michael Achenbach6fbf12f2017-07-06 10:54:11 +0200706 return QueryChanges(host, [], change, o_params=('ALL_REVISIONS',))
szager@chromium.orgb4696232013-10-16 19:45:35 +0000707
708
709def GetChangeReview(host, change, revision=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000710 """Gets the current review information for a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000711 if not revision:
712 jmsg = GetChangeRevisions(host, change)
713 if not jmsg:
714 return None
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +0000715
716 if len(jmsg) > 1:
szager@chromium.orgb4696232013-10-16 19:45:35 +0000717 raise GerritError(200, 'Multiple changes found for ChangeId %s.' % change)
718 revision = jmsg[0]['current_revision']
719 path = 'changes/%s/revisions/%s/review'
720 return ReadHttpJsonResponse(CreateHttpConn(host, path))
721
722
Aaron Gable0ffdf2d2017-06-05 13:01:17 -0700723def GetChangeComments(host, change):
724 """Get the line- and file-level comments on a change."""
725 path = 'changes/%s/comments' % change
726 return ReadHttpJsonResponse(CreateHttpConn(host, path))
727
728
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000729def GetChangeRobotComments(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000730 """Gets the line- and file-level robot comments on a change."""
Quinten Yearsley0e617c02019-02-20 00:37:03 +0000731 path = 'changes/%s/robotcomments' % change
732 return ReadHttpJsonResponse(CreateHttpConn(host, path))
733
734
Marco Georgaklis85557a02021-06-03 15:56:54 +0000735def GetRelatedChanges(host, change, revision='current'):
736 """Gets the related changes for a given change and revision."""
737 path = 'changes/%s/revisions/%s/related' % (change, revision)
738 return ReadHttpJsonResponse(CreateHttpConn(host, path))
739
740
szager@chromium.orgb4696232013-10-16 19:45:35 +0000741def AbandonChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000742 """Abandons a Gerrit change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000743 path = 'changes/%s/abandon' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000744 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000745 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700746 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000747
748
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000749def MoveChange(host, change, destination_branch):
750 """Move a Gerrit change to different destination branch."""
751 path = 'changes/%s/move' % change
Mike Frysingerf1c7d0d2020-12-15 20:05:36 +0000752 body = {'destination_branch': destination_branch,
753 'keep_all_votes': True}
Josip Sokcevicc39ab992020-09-24 20:09:15 +0000754 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
755 return ReadHttpJsonResponse(conn)
756
757
758
szager@chromium.orgb4696232013-10-16 19:45:35 +0000759def RestoreChange(host, change, msg=''):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000760 """Restores a previously abandoned change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000761 path = 'changes/%s/restore' % change
tandrii@chromium.orgc7da66a2016-03-24 09:52:24 +0000762 body = {'message': msg} if msg else {}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000763 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700764 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000765
766
Xinan Lin1bd4ffa2021-07-28 00:54:22 +0000767def SubmitChange(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000768 """Submits a Gerrit change via Gerrit."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000769 path = 'changes/%s/submit' % change
Xinan Lin1bd4ffa2021-07-28 00:54:22 +0000770 conn = CreateHttpConn(host, path, reqtype='POST')
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700771 return ReadHttpJsonResponse(conn)
szager@chromium.orgb4696232013-10-16 19:45:35 +0000772
773
Xinan Lin2b4ec952021-08-20 17:35:29 +0000774def GetChangesSubmittedTogether(host, change):
775 """Get all changes submitted with the given one."""
776 path = 'changes/%s/submitted_together?o=NON_VISIBLE_CHANGES' % change
777 conn = CreateHttpConn(host, path, reqtype='GET')
778 return ReadHttpJsonResponse(conn)
779
780
LaMont Jones9eed4232021-04-02 16:29:49 +0000781def PublishChangeEdit(host, change, notify=True):
782 """Publish a Gerrit change edit."""
783 path = 'changes/%s/edit:publish' % change
784 body = {'notify': 'ALL' if notify else 'NONE'}
785 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
786 return ReadHttpJsonResponse(conn, accept_statuses=(204, ))
787
788
789def ChangeEdit(host, change, path, data):
790 """Puts content of a file into a change edit."""
791 path = 'changes/%s/edit/%s' % (change, urllib.parse.quote(path, ''))
792 body = {
793 'binary_content':
Leszek Swirski4c0c3fb2022-06-08 17:04:02 +0000794 'data:text/plain;base64,%s' %
795 base64.b64encode(data.encode('utf-8')).decode('utf-8')
LaMont Jones9eed4232021-04-02 16:29:49 +0000796 }
797 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
798 return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
799
800
Leszek Swirskic1c45f82022-06-09 16:21:07 +0000801def SetChangeEditMessage(host, change, message):
802 """Sets the commit message of a change edit."""
803 path = 'changes/%s/edit:message' % change
804 body = {'message': message}
805 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
806 return ReadHttpJsonResponse(conn, accept_statuses=(204, 409))
807
808
dsansomee2d6fd92016-09-08 00:10:47 -0700809def HasPendingChangeEdit(host, change):
810 conn = CreateHttpConn(host, 'changes/%s/edit' % change)
811 try:
Aaron Gable6f5a8d92017-04-18 14:49:05 -0700812 ReadHttpResponse(conn)
dsansomee2d6fd92016-09-08 00:10:47 -0700813 except GerritError as e:
Aaron Gable19ee16c2017-04-18 11:56:35 -0700814 # 204 No Content means no pending change.
815 if e.http_status == 204:
816 return False
817 raise
818 return True
dsansomee2d6fd92016-09-08 00:10:47 -0700819
820
821def DeletePendingChangeEdit(host, change):
822 conn = CreateHttpConn(host, 'changes/%s/edit' % change, reqtype='DELETE')
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000823 # On success, Gerrit returns status 204; if the edit was already deleted it
Aaron Gable19ee16c2017-04-18 11:56:35 -0700824 # returns 404. Anything else is an error.
825 ReadHttpResponse(conn, accept_statuses=[204, 404])
dsansomee2d6fd92016-09-08 00:10:47 -0700826
827
Leszek Swirskic1c45f82022-06-09 16:21:07 +0000828def CherryPick(host, change, destination, revision='current'):
829 """Create a cherry-pick commit from the given change, onto the given
830 destination.
831 """
832 path = 'changes/%s/revisions/%s/cherrypick' % (change, revision)
833 body = {'destination': destination}
834 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
835 return ReadHttpJsonResponse(conn)
836
837
838def GetFileContents(host, change, path):
839 """Get the contents of a file with the given path in the given revision.
840
841 Returns:
842 A bytes object with the file's contents.
843 """
844 path = 'changes/%s/revisions/current/files/%s/content' % (
845 change, urllib.parse.quote(path, ''))
846 conn = CreateHttpConn(host, path, reqtype='GET')
847 return base64.b64decode(ReadHttpResponse(conn).read())
848
849
Andrii Shyshkalovea4fc832016-12-01 14:53:23 +0100850def SetCommitMessage(host, change, description, notify='ALL'):
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000851 """Updates a commit message."""
Aaron Gable7625d882017-06-26 09:47:26 -0700852 assert notify in ('ALL', 'NONE')
853 path = 'changes/%s/message' % change
Aaron Gable5a4ef452017-08-24 13:19:56 -0700854 body = {'message': description, 'notify': notify}
Aaron Gable7625d882017-06-26 09:47:26 -0700855 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000856 try:
Aaron Gable7625d882017-06-26 09:47:26 -0700857 ReadHttpResponse(conn, accept_statuses=[200, 204])
858 except GerritError as e:
859 raise GerritError(
860 e.http_status,
861 'Received unexpected http status while editing message '
862 'in change %s' % change)
scottmg@chromium.org6d1266e2016-04-26 11:12:26 +0000863
864
Xinan Linc2fb26a2021-07-27 18:01:55 +0000865def GetCommitIncludedIn(host, project, commit):
866 """Retrieves the branches and tags for a given commit.
867
868 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-included-in
869
870 Returns:
871 A JSON object with keys of 'branches' and 'tags'.
872 """
873 path = 'projects/%s/commits/%s/in' % (urllib.parse.quote(project, ''), commit)
874 conn = CreateHttpConn(host, path, reqtype='GET')
875 return ReadHttpJsonResponse(conn, accept_statuses=[200])
876
877
Edward Lesmes8170c292021-03-19 20:04:43 +0000878def IsCodeOwnersEnabledOnHost(host):
Edward Lesmes110823b2021-02-05 21:42:27 +0000879 """Check if the code-owners plugin is enabled for the host."""
880 path = 'config/server/capabilities'
881 capabilities = ReadHttpJsonResponse(CreateHttpConn(host, path))
882 return 'code-owners-checkCodeOwner' in capabilities
883
884
Edward Lesmes8170c292021-03-19 20:04:43 +0000885def IsCodeOwnersEnabledOnRepo(host, repo):
886 """Check if the code-owners plugin is enabled for the repo."""
887 repo = PercentEncodeForGitRef(repo)
888 path = '/projects/%s/code_owners.project_config' % repo
889 config = ReadHttpJsonResponse(CreateHttpConn(host, path))
Edward Lesmes743e98c2021-03-22 18:00:54 +0000890 return not config['status'].get('disabled', False)
Edward Lesmes8170c292021-03-19 20:04:43 +0000891
892
Gavin Make0fee9f2022-08-10 23:41:55 +0000893def GetOwnersForFile(host,
894 project,
895 branch,
896 path,
897 limit=100,
898 resolve_all_users=True,
899 highest_score_only=False,
900 seed=None,
901 o_params=('DETAILS',)):
Gavin Makc94b21d2020-12-10 20:27:32 +0000902 """Gets information about owners attached to a file."""
903 path = 'projects/%s/branches/%s/code_owners/%s' % (
904 urllib.parse.quote(project, ''),
905 urllib.parse.quote(branch, ''),
906 urllib.parse.quote(path, ''))
Gavin Mak7d690052021-02-25 19:14:22 +0000907 q = ['resolve-all-users=%s' % json.dumps(resolve_all_users)]
Gavin Make0fee9f2022-08-10 23:41:55 +0000908 if highest_score_only:
909 q.append('highest-score-only=%s' % json.dumps(highest_score_only))
Edward Lesmes23c3bdc2021-03-11 20:37:32 +0000910 if seed:
911 q.append('seed=%d' % seed)
Gavin Makc94b21d2020-12-10 20:27:32 +0000912 if limit:
913 q.append('n=%d' % limit)
914 if o_params:
915 q.extend(['o=%s' % p for p in o_params])
916 if q:
917 path = '%s?%s' % (path, '&'.join(q))
918 return ReadHttpJsonResponse(CreateHttpConn(host, path))
919
920
szager@chromium.orgb4696232013-10-16 19:45:35 +0000921def GetReviewers(host, change):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000922 """Gets information about all reviewers attached to a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000923 path = 'changes/%s/reviewers' % change
924 return ReadHttpJsonResponse(CreateHttpConn(host, path))
925
926
927def GetReview(host, change, revision):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000928 """Gets review information about a specific revision of a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000929 path = 'changes/%s/revisions/%s/review' % (change, revision)
930 return ReadHttpJsonResponse(CreateHttpConn(host, path))
931
932
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700933def AddReviewers(host, change, reviewers=None, ccs=None, notify=True,
934 accept_statuses=frozenset([200, 400, 422])):
szager@chromium.orgb4696232013-10-16 19:45:35 +0000935 """Add reviewers to a change."""
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700936 if not reviewers and not ccs:
Aaron Gabledf86e302016-11-08 10:48:03 -0800937 return None
Wiktor Garbacz6d0d0442017-05-15 12:34:40 +0200938 if not change:
939 return None
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700940 reviewers = frozenset(reviewers or [])
941 ccs = frozenset(ccs or [])
942 path = 'changes/%s/revisions/current/review' % change
943
944 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800945 'drafts': 'KEEP',
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700946 'reviewers': [],
947 'notify': 'ALL' if notify else 'NONE',
948 }
949 for r in sorted(reviewers | ccs):
950 state = 'REVIEWER' if r in reviewers else 'CC'
951 body['reviewers'].append({
952 'reviewer': r,
953 'state': state,
954 'notify': 'NONE', # We handled `notify` argument above.
Raul Tambre80ee78e2019-05-06 22:41:05 +0000955 })
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700956
957 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
958 # Gerrit will return 400 if one or more of the requested reviewers are
959 # unprocessable. We read the response object to see which were rejected,
960 # warn about them, and retry with the remainder.
961 resp = ReadHttpJsonResponse(conn, accept_statuses=accept_statuses)
962
963 errored = set()
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000964 for result in resp.get('reviewers', {}).values():
Aaron Gable6dadfbf2017-05-09 14:27:58 -0700965 r = result.get('input')
966 state = 'REVIEWER' if r in reviewers else 'CC'
967 if result.get('error'):
968 errored.add(r)
969 LOGGER.warn('Note: "%s" not added as a %s' % (r, state.lower()))
970 if errored:
971 # Try again, adding only those that didn't fail, and only accepting 200.
972 AddReviewers(host, change, reviewers=(reviewers-errored),
973 ccs=(ccs-errored), notify=notify, accept_statuses=[200])
szager@chromium.orgb4696232013-10-16 19:45:35 +0000974
975
Aaron Gable636b13f2017-07-14 10:42:48 -0700976def SetReview(host, change, msg=None, labels=None, notify=None, ready=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +0000977 """Sets labels and/or adds a message to a code review."""
szager@chromium.orgb4696232013-10-16 19:45:35 +0000978 if not msg and not labels:
979 return
980 path = 'changes/%s/revisions/current/review' % change
Jonathan Nieder1ea21322017-11-10 11:45:42 -0800981 body = {'drafts': 'KEEP'}
szager@chromium.orgb4696232013-10-16 19:45:35 +0000982 if msg:
983 body['message'] = msg
984 if labels:
985 body['labels'] = labels
Aaron Gablefc62f762017-07-17 11:12:07 -0700986 if notify is not None:
Aaron Gable75e78722017-06-09 10:40:16 -0700987 body['notify'] = 'ALL' if notify else 'NONE'
Aaron Gable636b13f2017-07-14 10:42:48 -0700988 if ready:
989 body['ready'] = True
szager@chromium.orgb4696232013-10-16 19:45:35 +0000990 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
991 response = ReadHttpJsonResponse(conn)
992 if labels:
Marc-Antoine Ruel8e57b4b2019-10-11 01:01:36 +0000993 for key, val in labels.items():
szager@chromium.orgb4696232013-10-16 19:45:35 +0000994 if ('labels' not in response or key not in response['labels'] or
995 int(response['labels'][key] != int(val))):
996 raise GerritError(200, 'Unable to set "%s" label on change %s.' % (
997 key, change))
Xinan Lin0b0738d2021-07-27 19:13:49 +0000998 return response
szager@chromium.orgb4696232013-10-16 19:45:35 +0000999
1000def ResetReviewLabels(host, change, label, value='0', message=None,
1001 notify=None):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001002 """Resets the value of a given label for all reviewers on a change."""
szager@chromium.orgb4696232013-10-16 19:45:35 +00001003 # This is tricky, because we want to work on the "current revision", but
1004 # there's always the risk that "current revision" will change in between
1005 # API calls. So, we check "current revision" at the beginning and end; if
1006 # it has changed, raise an exception.
1007 jmsg = GetChangeCurrentRevision(host, change)
1008 if not jmsg:
1009 raise GerritError(
1010 200, 'Could not get review information for change "%s"' % change)
1011 value = str(value)
1012 revision = jmsg[0]['current_revision']
1013 path = 'changes/%s/revisions/%s/review' % (change, revision)
1014 message = message or (
1015 '%s label set to %s programmatically.' % (label, value))
1016 jmsg = GetReview(host, change, revision)
1017 if not jmsg:
Quinten Yearsley925cedb2020-04-13 17:49:39 +00001018 raise GerritError(200, 'Could not get review information for revision %s '
szager@chromium.orgb4696232013-10-16 19:45:35 +00001019 'of change %s' % (revision, change))
1020 for review in jmsg.get('labels', {}).get(label, {}).get('all', []):
1021 if str(review.get('value', value)) != value:
1022 body = {
Jonathan Nieder1ea21322017-11-10 11:45:42 -08001023 'drafts': 'KEEP',
szager@chromium.orgb4696232013-10-16 19:45:35 +00001024 'message': message,
1025 'labels': {label: value},
1026 'on_behalf_of': review['_account_id'],
1027 }
1028 if notify:
1029 body['notify'] = notify
1030 conn = CreateHttpConn(
1031 host, path, reqtype='POST', body=body)
1032 response = ReadHttpJsonResponse(conn)
1033 if str(response['labels'][label]) != value:
1034 username = review.get('email', jmsg.get('name', ''))
1035 raise GerritError(200, 'Unable to set %s label for user "%s"'
1036 ' on change %s.' % (label, username, change))
1037 jmsg = GetChangeCurrentRevision(host, change)
1038 if not jmsg:
1039 raise GerritError(
1040 200, 'Could not get review information for change "%s"' % change)
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00001041
1042 if jmsg[0]['current_revision'] != revision:
szager@chromium.orgb4696232013-10-16 19:45:35 +00001043 raise GerritError(200, 'While resetting labels on change "%s", '
1044 'a new patchset was uploaded.' % change)
Dan Jacques8d11e482016-11-15 14:25:56 -08001045
1046
LaMont Jones9eed4232021-04-02 16:29:49 +00001047def CreateChange(host, project, branch='main', subject='', params=()):
1048 """
1049 Creates a new change.
1050
1051 Args:
1052 params: A list of additional ChangeInput specifiers, as documented here:
1053 (e.g. ('is_private', 'true') to mark the change private.
1054 https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#change-input
1055
1056 Returns:
1057 ChangeInfo for the new change.
1058 """
1059 path = 'changes/'
1060 body = {'project': project, 'branch': branch, 'subject': subject}
Aravind Vasudevanc5f0cbb2022-01-24 23:56:57 +00001061 body.update(dict(params))
LaMont Jones9eed4232021-04-02 16:29:49 +00001062 for key in 'project', 'branch', 'subject':
1063 if not body[key]:
1064 raise GerritError(200, '%s is required' % key.title())
1065
Ben Pastene97dadd02023-04-14 21:55:38 +00001066 conn = CreateHttpConn(host, path, reqtype='POST', body=body)
LaMont Jones9eed4232021-04-02 16:29:49 +00001067 return ReadHttpJsonResponse(conn, accept_statuses=[201])
1068
1069
dimu833c94c2017-01-18 17:36:15 -08001070def CreateGerritBranch(host, project, branch, commit):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001071 """Creates a new branch from given project and commit
1072
dimu833c94c2017-01-18 17:36:15 -08001073 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-branch
1074
1075 Returns:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001076 A JSON object with 'ref' key.
dimu833c94c2017-01-18 17:36:15 -08001077 """
1078 path = 'projects/%s/branches/%s' % (project, branch)
1079 body = {'revision': commit}
1080 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
Xinan Lindbcecc92023-05-03 18:29:00 +00001081 response = ReadHttpJsonResponse(conn, accept_statuses=[201, 409])
dimu833c94c2017-01-18 17:36:15 -08001082 if response:
1083 return response
1084 raise GerritError(200, 'Unable to create gerrit branch')
1085
1086
Michael Mossb6ce2442021-10-20 04:36:24 +00001087def CreateGerritTag(host, project, tag, commit):
1088 """Creates a new tag at the given commit.
1089
1090 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#create-tag
1091
1092 Returns:
1093 A JSON object with 'ref' key.
1094 """
1095 path = 'projects/%s/tags/%s' % (project, tag)
1096 body = {'revision': commit}
1097 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
1098 response = ReadHttpJsonResponse(conn, accept_statuses=[201])
1099 if response:
1100 return response
1101 raise GerritError(200, 'Unable to create gerrit tag')
1102
1103
Josip Sokcevicdf9a8022020-12-08 00:10:19 +00001104def GetHead(host, project):
1105 """Retrieves current HEAD of Gerrit project
1106
1107 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-head
1108
1109 Returns:
1110 A JSON object with 'ref' key.
1111 """
1112 path = 'projects/%s/HEAD' % (project)
1113 conn = CreateHttpConn(host, path, reqtype='GET')
1114 response = ReadHttpJsonResponse(conn, accept_statuses=[200])
1115 if response:
1116 return response
1117 raise GerritError(200, 'Unable to update gerrit HEAD')
1118
1119
1120def UpdateHead(host, project, branch):
1121 """Updates Gerrit HEAD to point to branch
1122
1123 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#set-head
1124
1125 Returns:
1126 A JSON object with 'ref' key.
1127 """
1128 path = 'projects/%s/HEAD' % (project)
1129 body = {'ref': branch}
1130 conn = CreateHttpConn(host, path, reqtype='PUT', body=body)
1131 response = ReadHttpJsonResponse(conn, accept_statuses=[200])
1132 if response:
1133 return response
1134 raise GerritError(200, 'Unable to update gerrit HEAD')
1135
1136
dimu833c94c2017-01-18 17:36:15 -08001137def GetGerritBranch(host, project, branch):
Xinan Linaf79f242021-08-09 21:23:58 +00001138 """Gets a branch info from given project and branch name.
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001139
1140 See:
dimu833c94c2017-01-18 17:36:15 -08001141 https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-branch
1142
1143 Returns:
Xinan Linaf79f242021-08-09 21:23:58 +00001144 A JSON object with 'revision' key if the branch exists, otherwise None.
dimu833c94c2017-01-18 17:36:15 -08001145 """
1146 path = 'projects/%s/branches/%s' % (project, branch)
1147 conn = CreateHttpConn(host, path, reqtype='GET')
Xinan Linaf79f242021-08-09 21:23:58 +00001148 return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
dimu833c94c2017-01-18 17:36:15 -08001149
1150
Josip Sokcevicf736cab2020-10-20 23:41:38 +00001151def GetProjectHead(host, project):
1152 conn = CreateHttpConn(host,
1153 '/projects/%s/HEAD' % urllib.parse.quote(project, ''))
1154 return ReadHttpJsonResponse(conn, accept_statuses=[200])
1155
1156
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001157def GetAccountDetails(host, account_id='self'):
1158 """Returns details of the account.
1159
1160 If account_id is not given, uses magic value 'self' which corresponds to
1161 whichever account user is authenticating as.
1162
1163 Documentation:
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001164 https://gerrit-review.googlesource.com/Documentation/rest-api-accounts.html#get-account
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001165
1166 Returns None if account is not found (i.e., Gerrit returned 404).
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001167 """
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001168 conn = CreateHttpConn(host, '/accounts/%s' % account_id)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001169 return ReadHttpJsonResponse(conn, accept_statuses=[200, 404])
1170
1171
1172def ValidAccounts(host, accounts, max_threads=10):
1173 """Returns a mapping from valid account to its details.
1174
1175 Invalid accounts, either not existing or without unique match,
1176 are not present as returned dictionary keys.
1177 """
Edward Lemur0db01f02019-11-12 22:01:51 +00001178 assert not isinstance(accounts, str), type(accounts)
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001179 accounts = list(set(accounts))
1180 if not accounts:
1181 return {}
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001182
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001183 def get_one(account):
1184 try:
1185 return account, GetAccountDetails(host, account)
1186 except GerritError:
1187 return None, None
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001188
Andrii Shyshkalovba7b0a42018-10-15 03:20:35 +00001189 valid = {}
1190 with contextlib.closing(ThreadPool(min(max_threads, len(accounts)))) as pool:
1191 for account, details in pool.map(get_one, accounts):
1192 if account and details:
1193 valid[account] = details
1194 return valid
Andrii Shyshkalovbb86fbb2017-03-24 14:59:28 +01001195
1196
Nick Carter8692b182017-11-06 16:30:38 -08001197def PercentEncodeForGitRef(original):
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001198 """Applies percent-encoding for strings sent to Gerrit via git ref metadata.
Nick Carter8692b182017-11-06 16:30:38 -08001199
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001200 The encoding used is based on but stricter than URL encoding (Section 2.1 of
1201 RFC 3986). The only non-escaped characters are alphanumerics, and 'SPACE'
1202 (U+0020) can be represented as 'LOW LINE' (U+005F) or 'PLUS SIGN' (U+002B).
Nick Carter8692b182017-11-06 16:30:38 -08001203
1204 For more information, see the Gerrit docs here:
1205
1206 https://gerrit-review.googlesource.com/Documentation/user-upload.html#message
1207 """
1208 safe = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
1209 encoded = ''.join(c if c in safe else '%%%02X' % ord(c) for c in original)
1210
Quinten Yearsleyd9cbe7a2019-09-03 16:49:11 +00001211 # Spaces are not allowed in git refs; gerrit will interpret either '_' or
Nick Carter8692b182017-11-06 16:30:38 -08001212 # '+' (or '%20') as space. Use '_' since that has been supported the longest.
1213 return encoded.replace(' ', '_')
1214
1215
Dan Jacques8d11e482016-11-15 14:25:56 -08001216@contextlib.contextmanager
1217def tempdir():
1218 tdir = None
1219 try:
1220 tdir = tempfile.mkdtemp(suffix='gerrit_util')
1221 yield tdir
1222 finally:
1223 if tdir:
1224 gclient_utils.rmtree(tdir)
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001225
1226
1227def ChangeIdentifier(project, change_number):
Edward Lemur687ca902018-12-05 02:30:30 +00001228 """Returns change identifier "project~number" suitable for |change| arg of
Andrii Shyshkalov0ec9d152018-08-23 00:22:58 +00001229 this module API.
1230
1231 Such format is allows for more efficient Gerrit routing of HTTP requests,
1232 comparing to specifying just change_number.
1233 """
1234 assert int(change_number)
Edward Lemur4ba192e2019-10-28 20:19:37 +00001235 return '%s~%s' % (urllib.parse.quote(project, ''), change_number)