gerrit_util.py 45 KB

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