presubmit_support.py 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Enables directory-specific presubmit checks to run at upload and/or commit.
  6. """
  7. from __future__ import print_function
  8. __version__ = '2.0.0'
  9. # TODO(joi) Add caching where appropriate/needed. The API is designed to allow
  10. # caching (between all different invocations of presubmit scripts for a given
  11. # change). We should add it as our presubmit scripts start feeling slow.
  12. import argparse
  13. import ast # Exposed through the API.
  14. import contextlib
  15. import cpplint
  16. import fnmatch # Exposed through the API.
  17. import glob
  18. import inspect
  19. import itertools
  20. import json # Exposed through the API.
  21. import logging
  22. import multiprocessing
  23. import os # Somewhat exposed through the API.
  24. import random
  25. import re # Exposed through the API.
  26. import signal
  27. import six
  28. import sys # Parts exposed through API.
  29. import tempfile # Exposed through the API.
  30. import threading
  31. import time
  32. import traceback
  33. import unittest # Exposed through the API.
  34. from warnings import warn
  35. # Local imports.
  36. import fix_encoding
  37. import gclient_paths # Exposed through the API
  38. import gclient_utils
  39. import git_footers
  40. import gerrit_util
  41. import owners_client
  42. import owners_finder
  43. import presubmit_canned_checks
  44. import rdb_wrapper
  45. import scm
  46. import subprocess2 as subprocess # Exposed through the API.
  47. if sys.version_info.major == 2:
  48. # TODO(1009814): Expose urllib2 only through urllib_request and urllib_error
  49. import urllib2 # Exposed through the API.
  50. import urlparse
  51. import urllib2 as urllib_request
  52. import urllib2 as urllib_error
  53. else:
  54. import urllib.parse as urlparse
  55. import urllib.request as urllib_request
  56. import urllib.error as urllib_error
  57. # Ask for feedback only once in program lifetime.
  58. _ASKED_FOR_FEEDBACK = False
  59. # Set if super-verbose mode is requested, for tracking where presubmit messages
  60. # are coming from.
  61. _SHOW_CALLSTACKS = False
  62. def time_time():
  63. # Use this so that it can be mocked in tests without interfering with python
  64. # system machinery.
  65. return time.time()
  66. class PresubmitFailure(Exception):
  67. pass
  68. class CommandData(object):
  69. def __init__(self, name, cmd, kwargs, message, python3=False):
  70. self.name = name
  71. self.cmd = cmd
  72. self.stdin = kwargs.get('stdin', None)
  73. self.kwargs = kwargs.copy()
  74. self.kwargs['stdout'] = subprocess.PIPE
  75. self.kwargs['stderr'] = subprocess.STDOUT
  76. self.kwargs['stdin'] = subprocess.PIPE
  77. self.message = message
  78. self.info = None
  79. self.python3 = python3
  80. # Adapted from
  81. # https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
  82. #
  83. # An object that catches SIGINT sent to the Python process and notices
  84. # if processes passed to wait() die by SIGINT (we need to look for
  85. # both of those cases, because pressing Ctrl+C can result in either
  86. # the main process or one of the subprocesses getting the signal).
  87. #
  88. # Before a SIGINT is seen, wait(p) will simply call p.wait() and
  89. # return the result. Once a SIGINT has been seen (in the main process
  90. # or a subprocess, including the one the current call is waiting for),
  91. # wait(p) will call p.terminate().
  92. class SigintHandler(object):
  93. sigint_returncodes = {-signal.SIGINT, # Unix
  94. -1073741510, # Windows
  95. }
  96. def __init__(self):
  97. self.__lock = threading.Lock()
  98. self.__processes = set()
  99. self.__got_sigint = False
  100. self.__previous_signal = signal.signal(signal.SIGINT, self.interrupt)
  101. def __on_sigint(self):
  102. self.__got_sigint = True
  103. while self.__processes:
  104. try:
  105. self.__processes.pop().terminate()
  106. except OSError:
  107. pass
  108. def interrupt(self, signal_num, frame):
  109. with self.__lock:
  110. self.__on_sigint()
  111. self.__previous_signal(signal_num, frame)
  112. def got_sigint(self):
  113. with self.__lock:
  114. return self.__got_sigint
  115. def wait(self, p, stdin):
  116. with self.__lock:
  117. if self.__got_sigint:
  118. p.terminate()
  119. self.__processes.add(p)
  120. stdout, stderr = p.communicate(stdin)
  121. code = p.returncode
  122. with self.__lock:
  123. self.__processes.discard(p)
  124. if code in self.sigint_returncodes:
  125. self.__on_sigint()
  126. return stdout, stderr
  127. sigint_handler = SigintHandler()
  128. class Timer(object):
  129. def __init__(self, timeout, fn):
  130. self.completed = False
  131. self._fn = fn
  132. self._timer = threading.Timer(timeout, self._onTimer) if timeout else None
  133. def __enter__(self):
  134. if self._timer:
  135. self._timer.start()
  136. return self
  137. def __exit__(self, _type, _value, _traceback):
  138. if self._timer:
  139. self._timer.cancel()
  140. def _onTimer(self):
  141. self._fn()
  142. self.completed = True
  143. class ThreadPool(object):
  144. def __init__(self, pool_size=None, timeout=None):
  145. self.timeout = timeout
  146. self._pool_size = pool_size or multiprocessing.cpu_count()
  147. if sys.platform == 'win32':
  148. # TODO(crbug.com/1190269) - we can't use more than 56 child processes on
  149. # Windows or Python3 may hang.
  150. self._pool_size = min(self._pool_size, 56)
  151. self._messages = []
  152. self._messages_lock = threading.Lock()
  153. self._tests = []
  154. self._tests_lock = threading.Lock()
  155. self._nonparallel_tests = []
  156. def _GetCommand(self, test):
  157. vpython = 'vpython'
  158. if test.python3:
  159. vpython += '3'
  160. if sys.platform == 'win32':
  161. vpython += '.bat'
  162. cmd = test.cmd
  163. if cmd[0] == 'python':
  164. cmd = list(cmd)
  165. cmd[0] = vpython
  166. elif cmd[0].endswith('.py'):
  167. cmd = [vpython] + cmd
  168. # On Windows, scripts on the current directory take precedence over PATH, so
  169. # that when testing depot_tools on Windows, calling `vpython.bat` will
  170. # execute the copy of vpython of the depot_tools under test instead of the
  171. # one in the bot.
  172. # As a workaround, we run the tests from the parent directory instead.
  173. if (cmd[0] == vpython and
  174. 'cwd' in test.kwargs and
  175. os.path.basename(test.kwargs['cwd']) == 'depot_tools'):
  176. test.kwargs['cwd'] = os.path.dirname(test.kwargs['cwd'])
  177. cmd[1] = os.path.join('depot_tools', cmd[1])
  178. return cmd
  179. def _RunWithTimeout(self, cmd, stdin, kwargs):
  180. p = subprocess.Popen(cmd, **kwargs)
  181. with Timer(self.timeout, p.terminate) as timer:
  182. stdout, _ = sigint_handler.wait(p, stdin)
  183. stdout = stdout.decode('utf-8', 'ignore')
  184. if timer.completed:
  185. stdout = 'Process timed out after %ss\n%s' % (self.timeout, stdout)
  186. return p.returncode, stdout
  187. def CallCommand(self, test):
  188. """Runs an external program.
  189. This function converts invocation of .py files and invocations of 'python'
  190. to vpython invocations.
  191. """
  192. cmd = self._GetCommand(test)
  193. try:
  194. start = time_time()
  195. returncode, stdout = self._RunWithTimeout(cmd, test.stdin, test.kwargs)
  196. duration = time_time() - start
  197. except Exception:
  198. duration = time_time() - start
  199. return test.message(
  200. '%s\n%s exec failure (%4.2fs)\n%s' % (
  201. test.name, ' '.join(cmd), duration, traceback.format_exc()))
  202. if returncode != 0:
  203. return test.message(
  204. '%s\n%s (%4.2fs) failed\n%s' % (
  205. test.name, ' '.join(cmd), duration, stdout))
  206. if test.info:
  207. return test.info('%s\n%s (%4.2fs)' % (test.name, ' '.join(cmd), duration))
  208. def AddTests(self, tests, parallel=True):
  209. if parallel:
  210. self._tests.extend(tests)
  211. else:
  212. self._nonparallel_tests.extend(tests)
  213. def RunAsync(self):
  214. self._messages = []
  215. def _WorkerFn():
  216. while True:
  217. test = None
  218. with self._tests_lock:
  219. if not self._tests:
  220. break
  221. test = self._tests.pop()
  222. result = self.CallCommand(test)
  223. if result:
  224. with self._messages_lock:
  225. self._messages.append(result)
  226. def _StartDaemon():
  227. t = threading.Thread(target=_WorkerFn)
  228. t.daemon = True
  229. t.start()
  230. return t
  231. while self._nonparallel_tests:
  232. test = self._nonparallel_tests.pop()
  233. result = self.CallCommand(test)
  234. if result:
  235. self._messages.append(result)
  236. if self._tests:
  237. threads = [_StartDaemon() for _ in range(self._pool_size)]
  238. for worker in threads:
  239. worker.join()
  240. return self._messages
  241. def normpath(path):
  242. '''Version of os.path.normpath that also changes backward slashes to
  243. forward slashes when not running on Windows.
  244. '''
  245. # This is safe to always do because the Windows version of os.path.normpath
  246. # will replace forward slashes with backward slashes.
  247. path = path.replace(os.sep, '/')
  248. return os.path.normpath(path)
  249. def _RightHandSideLinesImpl(affected_files):
  250. """Implements RightHandSideLines for InputApi and GclChange."""
  251. for af in affected_files:
  252. lines = af.ChangedContents()
  253. for line in lines:
  254. yield (af, line[0], line[1])
  255. def prompt_should_continue(prompt_string):
  256. sys.stdout.write(prompt_string)
  257. sys.stdout.flush()
  258. response = sys.stdin.readline().strip().lower()
  259. return response in ('y', 'yes')
  260. def _ShouldRunPresubmit(script_text, use_python3):
  261. """Try to figure out whether these presubmit checks should be run under
  262. python2 or python3. We need to do this without actually trying to
  263. compile the text, since the text might compile in one but not the
  264. other.
  265. Args:
  266. script_text: The text of the presubmit script.
  267. use_python3: if true, will use python3 instead of python2 by default
  268. if USE_PYTHON3 is not specified.
  269. Return:
  270. A boolean if presubmit should be executed
  271. """
  272. m = re.search('^USE_PYTHON3 = (True|False)$', script_text, flags=re.MULTILINE)
  273. if m:
  274. use_python3 = m.group(1) == 'True'
  275. return ((sys.version_info.major == 2) and not use_python3) or \
  276. ((sys.version_info.major == 3) and use_python3)
  277. # Top level object so multiprocessing can pickle
  278. # Public access through OutputApi object.
  279. class _PresubmitResult(object):
  280. """Base class for result objects."""
  281. fatal = False
  282. should_prompt = False
  283. def __init__(self, message, items=None, long_text=''):
  284. """
  285. message: A short one-line message to indicate errors.
  286. items: A list of short strings to indicate where errors occurred.
  287. long_text: multi-line text output, e.g. from another tool
  288. """
  289. self._message = _PresubmitResult._ensure_str(message)
  290. self._items = items or []
  291. self._long_text = _PresubmitResult._ensure_str(long_text.rstrip())
  292. if _SHOW_CALLSTACKS:
  293. self._long_text += 'Presubmit result call stack is:\n'
  294. self._long_text += ''.join(traceback.format_stack(None, 8))
  295. @staticmethod
  296. def _ensure_str(val):
  297. """
  298. val: A "stringish" value. Can be any of str, unicode or bytes.
  299. returns: A str after applying encoding/decoding as needed.
  300. Assumes/uses UTF-8 for relevant inputs/outputs.
  301. We'd prefer to use six.ensure_str but our copy of six is old :(
  302. """
  303. if isinstance(val, str):
  304. return val
  305. if six.PY2 and isinstance(val, unicode):
  306. return val.encode()
  307. if six.PY3 and isinstance(val, bytes):
  308. return val.decode()
  309. raise ValueError("Unknown string type %s" % type(val))
  310. def handle(self):
  311. sys.stdout.write(self._message)
  312. sys.stdout.write('\n')
  313. for item in self._items:
  314. sys.stdout.write(' ')
  315. # Write separately in case it's unicode.
  316. sys.stdout.write(str(item))
  317. sys.stdout.write('\n')
  318. if self._long_text:
  319. sys.stdout.write('\n***************\n')
  320. # Write separately in case it's unicode.
  321. sys.stdout.write(self._long_text)
  322. sys.stdout.write('\n***************\n')
  323. def json_format(self):
  324. return {
  325. 'message': self._message,
  326. 'items': [str(item) for item in self._items],
  327. 'long_text': self._long_text,
  328. 'fatal': self.fatal
  329. }
  330. # Top level object so multiprocessing can pickle
  331. # Public access through OutputApi object.
  332. class _PresubmitError(_PresubmitResult):
  333. """A hard presubmit error."""
  334. fatal = True
  335. # Top level object so multiprocessing can pickle
  336. # Public access through OutputApi object.
  337. class _PresubmitPromptWarning(_PresubmitResult):
  338. """An warning that prompts the user if they want to continue."""
  339. should_prompt = True
  340. # Top level object so multiprocessing can pickle
  341. # Public access through OutputApi object.
  342. class _PresubmitNotifyResult(_PresubmitResult):
  343. """Just print something to the screen -- but it's not even a warning."""
  344. # Top level object so multiprocessing can pickle
  345. # Public access through OutputApi object.
  346. class _MailTextResult(_PresubmitResult):
  347. """A warning that should be included in the review request email."""
  348. def __init__(self, *args, **kwargs):
  349. super(_MailTextResult, self).__init__()
  350. raise NotImplementedError()
  351. class GerritAccessor(object):
  352. """Limited Gerrit functionality for canned presubmit checks to work.
  353. To avoid excessive Gerrit calls, caches the results.
  354. """
  355. def __init__(self, url=None, project=None, branch=None):
  356. self.host = urlparse.urlparse(url).netloc if url else None
  357. self.project = project
  358. self.branch = branch
  359. self.cache = {}
  360. self.code_owners_enabled = None
  361. def _FetchChangeDetail(self, issue):
  362. # Separate function to be easily mocked in tests.
  363. try:
  364. return gerrit_util.GetChangeDetail(
  365. self.host, str(issue),
  366. ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
  367. except gerrit_util.GerritError as e:
  368. if e.http_status == 404:
  369. raise Exception('Either Gerrit issue %s doesn\'t exist, or '
  370. 'no credentials to fetch issue details' % issue)
  371. raise
  372. def GetChangeInfo(self, issue):
  373. """Returns labels and all revisions (patchsets) for this issue.
  374. The result is a dictionary according to Gerrit REST Api.
  375. https://gerrit-review.googlesource.com/Documentation/rest-api.html
  376. However, API isn't very clear what's inside, so see tests for example.
  377. """
  378. assert issue
  379. cache_key = int(issue)
  380. if cache_key not in self.cache:
  381. self.cache[cache_key] = self._FetchChangeDetail(issue)
  382. return self.cache[cache_key]
  383. def GetChangeDescription(self, issue, patchset=None):
  384. """If patchset is none, fetches current patchset."""
  385. info = self.GetChangeInfo(issue)
  386. # info is a reference to cache. We'll modify it here adding description to
  387. # it to the right patchset, if it is not yet there.
  388. # Find revision info for the patchset we want.
  389. if patchset is not None:
  390. for rev, rev_info in info['revisions'].items():
  391. if str(rev_info['_number']) == str(patchset):
  392. break
  393. else:
  394. raise Exception('patchset %s doesn\'t exist in issue %s' % (
  395. patchset, issue))
  396. else:
  397. rev = info['current_revision']
  398. rev_info = info['revisions'][rev]
  399. return rev_info['commit']['message']
  400. def GetDestRef(self, issue):
  401. ref = self.GetChangeInfo(issue)['branch']
  402. if not ref.startswith('refs/'):
  403. # NOTE: it is possible to create 'refs/x' branch,
  404. # aka 'refs/heads/refs/x'. However, this is ill-advised.
  405. ref = 'refs/heads/%s' % ref
  406. return ref
  407. def _GetApproversForLabel(self, issue, label):
  408. change_info = self.GetChangeInfo(issue)
  409. label_info = change_info.get('labels', {}).get(label, {})
  410. values = label_info.get('values', {}).keys()
  411. if not values:
  412. return []
  413. max_value = max(int(v) for v in values)
  414. return [v for v in label_info.get('all', [])
  415. if v.get('value', 0) == max_value]
  416. def IsBotCommitApproved(self, issue):
  417. return bool(self._GetApproversForLabel(issue, 'Bot-Commit'))
  418. def IsOwnersOverrideApproved(self, issue):
  419. return bool(self._GetApproversForLabel(issue, 'Owners-Override'))
  420. def GetChangeOwner(self, issue):
  421. return self.GetChangeInfo(issue)['owner']['email']
  422. def GetChangeReviewers(self, issue, approving_only=True):
  423. changeinfo = self.GetChangeInfo(issue)
  424. if approving_only:
  425. reviewers = self._GetApproversForLabel(issue, 'Code-Review')
  426. else:
  427. reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
  428. return [r.get('email') for r in reviewers]
  429. def UpdateDescription(self, description, issue):
  430. gerrit_util.SetCommitMessage(self.host, issue, description, notify='NONE')
  431. def IsCodeOwnersEnabledOnRepo(self):
  432. if self.code_owners_enabled is None:
  433. self.code_owners_enabled = gerrit_util.IsCodeOwnersEnabledOnRepo(
  434. self.host, self.project)
  435. return self.code_owners_enabled
  436. class OutputApi(object):
  437. """An instance of OutputApi gets passed to presubmit scripts so that they
  438. can output various types of results.
  439. """
  440. PresubmitResult = _PresubmitResult
  441. PresubmitError = _PresubmitError
  442. PresubmitPromptWarning = _PresubmitPromptWarning
  443. PresubmitNotifyResult = _PresubmitNotifyResult
  444. MailTextResult = _MailTextResult
  445. def __init__(self, is_committing):
  446. self.is_committing = is_committing
  447. self.more_cc = []
  448. def AppendCC(self, cc):
  449. """Appends a user to cc for this change."""
  450. if cc not in self.more_cc:
  451. self.more_cc.append(cc)
  452. def PresubmitPromptOrNotify(self, *args, **kwargs):
  453. """Warn the user when uploading, but only notify if committing."""
  454. if self.is_committing:
  455. return self.PresubmitNotifyResult(*args, **kwargs)
  456. return self.PresubmitPromptWarning(*args, **kwargs)
  457. class InputApi(object):
  458. """An instance of this object is passed to presubmit scripts so they can
  459. know stuff about the change they're looking at.
  460. """
  461. # Method could be a function
  462. # pylint: disable=no-self-use
  463. # File extensions that are considered source files from a style guide
  464. # perspective. Don't modify this list from a presubmit script!
  465. #
  466. # Files without an extension aren't included in the list. If you want to
  467. # filter them as source files, add r'(^|.*?[\\\/])[^.]+$' to the allow list.
  468. # Note that ALL CAPS files are skipped in DEFAULT_FILES_TO_SKIP below.
  469. DEFAULT_FILES_TO_CHECK = (
  470. # C++ and friends
  471. r'.+\.c$', r'.+\.cc$', r'.+\.cpp$', r'.+\.h$', r'.+\.m$', r'.+\.mm$',
  472. r'.+\.inl$', r'.+\.asm$', r'.+\.hxx$', r'.+\.hpp$', r'.+\.s$', r'.+\.S$',
  473. # Scripts
  474. r'.+\.js$', r'.+\.ts$', r'.+\.py$', r'.+\.sh$', r'.+\.rb$', r'.+\.pl$',
  475. r'.+\.pm$',
  476. # Other
  477. r'.+\.java$', r'.+\.mk$', r'.+\.am$', r'.+\.css$', r'.+\.mojom$',
  478. r'.+\.fidl$'
  479. )
  480. # Path regexp that should be excluded from being considered containing source
  481. # files. Don't modify this list from a presubmit script!
  482. DEFAULT_FILES_TO_SKIP = (
  483. r'testing_support[\\\/]google_appengine[\\\/].*',
  484. r'.*\bexperimental[\\\/].*',
  485. # Exclude third_party/.* but NOT third_party/{WebKit,blink}
  486. # (crbug.com/539768 and crbug.com/836555).
  487. r'.*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*',
  488. # Output directories (just in case)
  489. r'.*\bDebug[\\\/].*',
  490. r'.*\bRelease[\\\/].*',
  491. r'.*\bxcodebuild[\\\/].*',
  492. r'.*\bout[\\\/].*',
  493. # All caps files like README and LICENCE.
  494. r'.*\b[A-Z0-9_]{2,}$',
  495. # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
  496. r'(|.*[\\\/])\.git[\\\/].*',
  497. r'(|.*[\\\/])\.svn[\\\/].*',
  498. # There is no point in processing a patch file.
  499. r'.+\.diff$',
  500. r'.+\.patch$',
  501. )
  502. def __init__(self, change, presubmit_path, is_committing,
  503. verbose, gerrit_obj, dry_run=None, thread_pool=None, parallel=False,
  504. no_diffs=False):
  505. """Builds an InputApi object.
  506. Args:
  507. change: A presubmit.Change object.
  508. presubmit_path: The path to the presubmit script being processed.
  509. is_committing: True if the change is about to be committed.
  510. gerrit_obj: provides basic Gerrit codereview functionality.
  511. dry_run: if true, some Checks will be skipped.
  512. parallel: if true, all tests reported via input_api.RunTests for all
  513. PRESUBMIT files will be run in parallel.
  514. no_diffs: if true, implies that --files or --all was specified so some
  515. checks can be skipped, and some errors will be messages.
  516. """
  517. # Version number of the presubmit_support script.
  518. self.version = [int(x) for x in __version__.split('.')]
  519. self.change = change
  520. self.is_committing = is_committing
  521. self.gerrit = gerrit_obj
  522. self.dry_run = dry_run
  523. self.no_diffs = no_diffs
  524. self.parallel = parallel
  525. self.thread_pool = thread_pool or ThreadPool()
  526. # We expose various modules and functions as attributes of the input_api
  527. # so that presubmit scripts don't have to import them.
  528. self.ast = ast
  529. self.basename = os.path.basename
  530. self.cpplint = cpplint
  531. self.fnmatch = fnmatch
  532. self.gclient_paths = gclient_paths
  533. # TODO(yyanagisawa): stop exposing this when python3 become default.
  534. # Since python3's tempfile has TemporaryDirectory, we do not need this.
  535. self.temporary_directory = gclient_utils.temporary_directory
  536. self.glob = glob.glob
  537. self.json = json
  538. self.logging = logging.getLogger('PRESUBMIT')
  539. self.os_listdir = os.listdir
  540. self.os_path = os.path
  541. self.os_stat = os.stat
  542. self.os_walk = os.walk
  543. self.re = re
  544. self.subprocess = subprocess
  545. self.sys = sys
  546. self.tempfile = tempfile
  547. self.time = time
  548. self.unittest = unittest
  549. if sys.version_info.major == 2:
  550. self.urllib2 = urllib2
  551. self.urllib_request = urllib_request
  552. self.urllib_error = urllib_error
  553. self.is_windows = sys.platform == 'win32'
  554. # Set python_executable to 'vpython' in order to allow scripts in other
  555. # repos (e.g. src.git) to automatically pick up that repo's .vpython file,
  556. # instead of inheriting the one in depot_tools.
  557. self.python_executable = 'vpython'
  558. # Offer a python 3 executable for use during the migration off of python 2.
  559. self.python3_executable = 'vpython3'
  560. self.environ = os.environ
  561. # InputApi.platform is the platform you're currently running on.
  562. self.platform = sys.platform
  563. self.cpu_count = multiprocessing.cpu_count()
  564. if self.is_windows:
  565. # TODO(crbug.com/1190269) - we can't use more than 56 child processes on
  566. # Windows or Python3 may hang.
  567. self.cpu_count = min(self.cpu_count, 56)
  568. # The local path of the currently-being-processed presubmit script.
  569. self._current_presubmit_path = os.path.dirname(presubmit_path)
  570. # We carry the canned checks so presubmit scripts can easily use them.
  571. self.canned_checks = presubmit_canned_checks
  572. # Temporary files we must manually remove at the end of a run.
  573. self._named_temporary_files = []
  574. self.owners_client = None
  575. if self.gerrit and not 'PRESUBMIT_SKIP_NETWORK' in self.environ:
  576. try:
  577. self.owners_client = owners_client.GetCodeOwnersClient(
  578. host=self.gerrit.host,
  579. project=self.gerrit.project,
  580. branch=self.gerrit.branch)
  581. except Exception as e:
  582. print('Failed to set owners_client - %s' % str(e))
  583. self.owners_finder = owners_finder.OwnersFinder
  584. self.verbose = verbose
  585. self.Command = CommandData
  586. # Replace <hash_map> and <hash_set> as headers that need to be included
  587. # with 'base/containers/hash_tables.h' instead.
  588. # Access to a protected member _XX of a client class
  589. # pylint: disable=protected-access
  590. self.cpplint._re_pattern_templates = [
  591. (a, b, 'base/containers/hash_tables.h')
  592. if header in ('<hash_map>', '<hash_set>') else (a, b, header)
  593. for (a, b, header) in cpplint._re_pattern_templates
  594. ]
  595. def SetTimeout(self, timeout):
  596. self.thread_pool.timeout = timeout
  597. def PresubmitLocalPath(self):
  598. """Returns the local path of the presubmit script currently being run.
  599. This is useful if you don't want to hard-code absolute paths in the
  600. presubmit script. For example, It can be used to find another file
  601. relative to the PRESUBMIT.py script, so the whole tree can be branched and
  602. the presubmit script still works, without editing its content.
  603. """
  604. return self._current_presubmit_path
  605. def AffectedFiles(self, include_deletes=True, file_filter=None):
  606. """Same as input_api.change.AffectedFiles() except only lists files
  607. (and optionally directories) in the same directory as the current presubmit
  608. script, or subdirectories thereof. Note that files are listed using the OS
  609. path separator, so backslashes are used as separators on Windows.
  610. """
  611. dir_with_slash = normpath(self.PresubmitLocalPath())
  612. # normpath strips trailing path separators, so the trailing separator has to
  613. # be added after the normpath call.
  614. if len(dir_with_slash) > 0:
  615. dir_with_slash += os.path.sep
  616. return list(filter(
  617. lambda x: normpath(x.AbsoluteLocalPath()).startswith(dir_with_slash),
  618. self.change.AffectedFiles(include_deletes, file_filter)))
  619. def LocalPaths(self):
  620. """Returns local paths of input_api.AffectedFiles()."""
  621. paths = [af.LocalPath() for af in self.AffectedFiles()]
  622. logging.debug('LocalPaths: %s', paths)
  623. return paths
  624. def AbsoluteLocalPaths(self):
  625. """Returns absolute local paths of input_api.AffectedFiles()."""
  626. return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
  627. def AffectedTestableFiles(self, include_deletes=None, **kwargs):
  628. """Same as input_api.change.AffectedTestableFiles() except only lists files
  629. in the same directory as the current presubmit script, or subdirectories
  630. thereof.
  631. """
  632. if include_deletes is not None:
  633. warn('AffectedTestableFiles(include_deletes=%s)'
  634. ' is deprecated and ignored' % str(include_deletes),
  635. category=DeprecationWarning,
  636. stacklevel=2)
  637. # pylint: disable=consider-using-generator
  638. return [
  639. x for x in self.AffectedFiles(include_deletes=False, **kwargs)
  640. if x.IsTestableFile()
  641. ]
  642. def AffectedTextFiles(self, include_deletes=None):
  643. """An alias to AffectedTestableFiles for backwards compatibility."""
  644. return self.AffectedTestableFiles(include_deletes=include_deletes)
  645. def FilterSourceFile(self,
  646. affected_file,
  647. files_to_check=None,
  648. files_to_skip=None,
  649. allow_list=None,
  650. block_list=None):
  651. """Filters out files that aren't considered 'source file'.
  652. If files_to_check or files_to_skip is None, InputApi.DEFAULT_FILES_TO_CHECK
  653. and InputApi.DEFAULT_FILES_TO_SKIP is used respectively.
  654. affected_file.LocalPath() needs to re.match an entry in the files_to_check
  655. list and not re.match any entries in the files_to_skip list.
  656. '/' path separators should be used in the regular expressions and will work
  657. on Windows as well as other platforms.
  658. Note: Copy-paste this function to suit your needs or use a lambda function.
  659. """
  660. if files_to_check is None:
  661. files_to_check = self.DEFAULT_FILES_TO_CHECK
  662. if files_to_skip is None:
  663. files_to_skip = self.DEFAULT_FILES_TO_SKIP
  664. def Find(affected_file, items):
  665. local_path = affected_file.LocalPath()
  666. for item in items:
  667. if self.re.match(item, local_path):
  668. return True
  669. # Handle the cases where the files regex only handles /, but the local
  670. # path uses \.
  671. if self.is_windows and self.re.match(item, local_path.replace(
  672. '\\', '/')):
  673. return True
  674. return False
  675. return (Find(affected_file, files_to_check) and
  676. not Find(affected_file, files_to_skip))
  677. def AffectedSourceFiles(self, source_file):
  678. """Filter the list of AffectedTestableFiles by the function source_file.
  679. If source_file is None, InputApi.FilterSourceFile() is used.
  680. """
  681. if not source_file:
  682. source_file = self.FilterSourceFile
  683. return list(filter(source_file, self.AffectedTestableFiles()))
  684. def RightHandSideLines(self, source_file_filter=None):
  685. """An iterator over all text lines in 'new' version of changed files.
  686. Only lists lines from new or modified text files in the change that are
  687. contained by the directory of the currently executing presubmit script.
  688. This is useful for doing line-by-line regex checks, like checking for
  689. trailing whitespace.
  690. Yields:
  691. a 3 tuple:
  692. the AffectedFile instance of the current file;
  693. integer line number (1-based); and
  694. the contents of the line as a string.
  695. Note: The carriage return (LF or CR) is stripped off.
  696. """
  697. files = self.AffectedSourceFiles(source_file_filter)
  698. return _RightHandSideLinesImpl(files)
  699. def ReadFile(self, file_item, mode='r'):
  700. """Reads an arbitrary file.
  701. Deny reading anything outside the repository.
  702. """
  703. if isinstance(file_item, AffectedFile):
  704. file_item = file_item.AbsoluteLocalPath()
  705. if not file_item.startswith(self.change.RepositoryRoot()):
  706. raise IOError('Access outside the repository root is denied.')
  707. return gclient_utils.FileRead(file_item, mode)
  708. def CreateTemporaryFile(self, **kwargs):
  709. """Returns a named temporary file that must be removed with a call to
  710. RemoveTemporaryFiles().
  711. All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
  712. except for |delete|, which is always set to False.
  713. Presubmit checks that need to create a temporary file and pass it for
  714. reading should use this function instead of NamedTemporaryFile(), as
  715. Windows fails to open a file that is already open for writing.
  716. with input_api.CreateTemporaryFile() as f:
  717. f.write('xyz')
  718. f.close()
  719. input_api.subprocess.check_output(['script-that', '--reads-from',
  720. f.name])
  721. Note that callers of CreateTemporaryFile() should not worry about removing
  722. any temporary file; this is done transparently by the presubmit handling
  723. code.
  724. """
  725. if 'delete' in kwargs:
  726. # Prevent users from passing |delete|; we take care of file deletion
  727. # ourselves and this prevents unintuitive error messages when we pass
  728. # delete=False and 'delete' is also in kwargs.
  729. raise TypeError('CreateTemporaryFile() does not take a "delete" '
  730. 'argument, file deletion is handled automatically by '
  731. 'the same presubmit_support code that creates InputApi '
  732. 'objects.')
  733. temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
  734. self._named_temporary_files.append(temp_file.name)
  735. return temp_file
  736. @property
  737. def tbr(self):
  738. """Returns if a change is TBR'ed."""
  739. return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
  740. def RunTests(self, tests_mix, parallel=True):
  741. tests = []
  742. msgs = []
  743. for t in tests_mix:
  744. if isinstance(t, OutputApi.PresubmitResult) and t:
  745. msgs.append(t)
  746. else:
  747. assert issubclass(t.message, _PresubmitResult)
  748. tests.append(t)
  749. if self.verbose:
  750. t.info = _PresubmitNotifyResult
  751. if not t.kwargs.get('cwd'):
  752. t.kwargs['cwd'] = self.PresubmitLocalPath()
  753. self.thread_pool.AddTests(tests, parallel)
  754. # When self.parallel is True (i.e. --parallel is passed as an option)
  755. # RunTests doesn't actually run tests. It adds them to a ThreadPool that
  756. # will run all tests once all PRESUBMIT files are processed.
  757. # Otherwise, it will run them and return the results.
  758. if not self.parallel:
  759. msgs.extend(self.thread_pool.RunAsync())
  760. return msgs
  761. class _DiffCache(object):
  762. """Caches diffs retrieved from a particular SCM."""
  763. def __init__(self, upstream=None):
  764. """Stores the upstream revision against which all diffs will be computed."""
  765. self._upstream = upstream
  766. def GetDiff(self, path, local_root):
  767. """Get the diff for a particular path."""
  768. raise NotImplementedError()
  769. def GetOldContents(self, path, local_root):
  770. """Get the old version for a particular path."""
  771. raise NotImplementedError()
  772. class _GitDiffCache(_DiffCache):
  773. """DiffCache implementation for git; gets all file diffs at once."""
  774. def __init__(self, upstream):
  775. super(_GitDiffCache, self).__init__(upstream=upstream)
  776. self._diffs_by_file = None
  777. def GetDiff(self, path, local_root):
  778. # Compare against None to distinguish between None and an initialized but
  779. # empty dictionary.
  780. if self._diffs_by_file == None:
  781. # Compute a single diff for all files and parse the output; should
  782. # with git this is much faster than computing one diff for each file.
  783. diffs = {}
  784. # Don't specify any filenames below, because there are command line length
  785. # limits on some platforms and GenerateDiff would fail.
  786. unified_diff = scm.GIT.GenerateDiff(local_root, files=[], full_move=True,
  787. branch=self._upstream)
  788. # This regex matches the path twice, separated by a space. Note that
  789. # filename itself may contain spaces.
  790. file_marker = re.compile('^diff --git (?P<filename>.*) (?P=filename)$')
  791. current_diff = []
  792. keep_line_endings = True
  793. for x in unified_diff.splitlines(keep_line_endings):
  794. match = file_marker.match(x)
  795. if match:
  796. # Marks the start of a new per-file section.
  797. diffs[match.group('filename')] = current_diff = [x]
  798. elif x.startswith('diff --git'):
  799. raise PresubmitFailure('Unexpected diff line: %s' % x)
  800. else:
  801. current_diff.append(x)
  802. self._diffs_by_file = dict(
  803. (normpath(path), ''.join(diff)) for path, diff in diffs.items())
  804. if path not in self._diffs_by_file:
  805. # SCM didn't have any diff on this file. It could be that the file was not
  806. # modified at all (e.g. user used --all flag in git cl presubmit).
  807. # Intead of failing, return empty string.
  808. # See: https://crbug.com/808346.
  809. return ''
  810. return self._diffs_by_file[path]
  811. def GetOldContents(self, path, local_root):
  812. return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
  813. class AffectedFile(object):
  814. """Representation of a file in a change."""
  815. DIFF_CACHE = _DiffCache
  816. # Method could be a function
  817. # pylint: disable=no-self-use
  818. def __init__(self, path, action, repository_root, diff_cache):
  819. self._path = path
  820. self._action = action
  821. self._local_root = repository_root
  822. self._is_directory = None
  823. self._cached_changed_contents = None
  824. self._cached_new_contents = None
  825. self._diff_cache = diff_cache
  826. logging.debug('%s(%s)', self.__class__.__name__, self._path)
  827. def LocalPath(self):
  828. """Returns the path of this file on the local disk relative to client root.
  829. This should be used for error messages but not for accessing files,
  830. because presubmit checks are run with CWD=PresubmitLocalPath() (which is
  831. often != client root).
  832. """
  833. return normpath(self._path)
  834. def AbsoluteLocalPath(self):
  835. """Returns the absolute path of this file on the local disk.
  836. """
  837. return os.path.abspath(os.path.join(self._local_root, self.LocalPath()))
  838. def Action(self):
  839. """Returns the action on this opened file, e.g. A, M, D, etc."""
  840. return self._action
  841. def IsTestableFile(self):
  842. """Returns True if the file is a text file and not a binary file.
  843. Deleted files are not text file."""
  844. raise NotImplementedError() # Implement when needed
  845. def IsTextFile(self):
  846. """An alias to IsTestableFile for backwards compatibility."""
  847. return self.IsTestableFile()
  848. def OldContents(self):
  849. """Returns an iterator over the lines in the old version of file.
  850. The old version is the file before any modifications in the user's
  851. workspace, i.e. the 'left hand side'.
  852. Contents will be empty if the file is a directory or does not exist.
  853. Note: The carriage returns (LF or CR) are stripped off.
  854. """
  855. return self._diff_cache.GetOldContents(self.LocalPath(),
  856. self._local_root).splitlines()
  857. def NewContents(self):
  858. """Returns an iterator over the lines in the new version of file.
  859. The new version is the file in the user's workspace, i.e. the 'right hand
  860. side'.
  861. Contents will be empty if the file is a directory or does not exist.
  862. Note: The carriage returns (LF or CR) are stripped off.
  863. """
  864. if self._cached_new_contents is None:
  865. self._cached_new_contents = []
  866. try:
  867. self._cached_new_contents = gclient_utils.FileRead(
  868. self.AbsoluteLocalPath(), 'rU').splitlines()
  869. except IOError:
  870. pass # File not found? That's fine; maybe it was deleted.
  871. except UnicodeDecodeError as e:
  872. # log the filename since we're probably trying to read a binary
  873. # file, and shouldn't be.
  874. print('Error reading %s: %s' % (self.AbsoluteLocalPath(), e))
  875. raise
  876. return self._cached_new_contents[:]
  877. def ChangedContents(self, keeplinebreaks=False):
  878. """Returns a list of tuples (line number, line text) of all new lines.
  879. This relies on the scm diff output describing each changed code section
  880. with a line of the form
  881. ^@@ <old line num>,<old size> <new line num>,<new size> @@$
  882. """
  883. # Don't return cached results when line breaks are requested.
  884. if not keeplinebreaks and self._cached_changed_contents is not None:
  885. return self._cached_changed_contents[:]
  886. result = []
  887. line_num = 0
  888. # The keeplinebreaks parameter to splitlines must be True or else the
  889. # CheckForWindowsLineEndings presubmit will be a NOP.
  890. for line in self.GenerateScmDiff().splitlines(keeplinebreaks):
  891. m = re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@', line)
  892. if m:
  893. line_num = int(m.groups(1)[0])
  894. continue
  895. if line.startswith('+') and not line.startswith('++'):
  896. result.append((line_num, line[1:]))
  897. if not line.startswith('-'):
  898. line_num += 1
  899. # Don't cache results with line breaks.
  900. if keeplinebreaks:
  901. return result;
  902. self._cached_changed_contents = result
  903. return self._cached_changed_contents[:]
  904. def __str__(self):
  905. return self.LocalPath()
  906. def GenerateScmDiff(self):
  907. return self._diff_cache.GetDiff(self.LocalPath(), self._local_root)
  908. class GitAffectedFile(AffectedFile):
  909. """Representation of a file in a change out of a git checkout."""
  910. # Method 'NNN' is abstract in class 'NNN' but is not overridden
  911. # pylint: disable=abstract-method
  912. DIFF_CACHE = _GitDiffCache
  913. def __init__(self, *args, **kwargs):
  914. AffectedFile.__init__(self, *args, **kwargs)
  915. self._server_path = None
  916. self._is_testable_file = None
  917. def IsTestableFile(self):
  918. if self._is_testable_file is None:
  919. if self.Action() == 'D':
  920. # A deleted file is not testable.
  921. self._is_testable_file = False
  922. else:
  923. self._is_testable_file = os.path.isfile(self.AbsoluteLocalPath())
  924. return self._is_testable_file
  925. class Change(object):
  926. """Describe a change.
  927. Used directly by the presubmit scripts to query the current change being
  928. tested.
  929. Instance members:
  930. tags: Dictionary of KEY=VALUE pairs found in the change description.
  931. self.KEY: equivalent to tags['KEY']
  932. """
  933. _AFFECTED_FILES = AffectedFile
  934. # Matches key/value (or 'tag') lines in changelist descriptions.
  935. TAG_LINE_RE = re.compile(
  936. '^[ \t]*(?P<key>[A-Z][A-Z_0-9]*)[ \t]*=[ \t]*(?P<value>.*?)[ \t]*$')
  937. scm = ''
  938. def __init__(
  939. self, name, description, local_root, files, issue, patchset, author,
  940. upstream=None):
  941. if files is None:
  942. files = []
  943. self._name = name
  944. # Convert root into an absolute path.
  945. self._local_root = os.path.abspath(local_root)
  946. self._upstream = upstream
  947. self.issue = issue
  948. self.patchset = patchset
  949. self.author_email = author
  950. self._full_description = ''
  951. self.tags = {}
  952. self._description_without_tags = ''
  953. self.SetDescriptionText(description)
  954. assert all(
  955. (isinstance(f, (list, tuple)) and len(f) == 2) for f in files), files
  956. diff_cache = self._AFFECTED_FILES.DIFF_CACHE(self._upstream)
  957. self._affected_files = [
  958. self._AFFECTED_FILES(path, action.strip(), self._local_root, diff_cache)
  959. for action, path in files
  960. ]
  961. def UpstreamBranch(self):
  962. """Returns the upstream branch for the change."""
  963. return self._upstream
  964. def Name(self):
  965. """Returns the change name."""
  966. return self._name
  967. def DescriptionText(self):
  968. """Returns the user-entered changelist description, minus tags.
  969. Any line in the user-provided description starting with e.g. 'FOO='
  970. (whitespace permitted before and around) is considered a tag line. Such
  971. lines are stripped out of the description this function returns.
  972. """
  973. return self._description_without_tags
  974. def FullDescriptionText(self):
  975. """Returns the complete changelist description including tags."""
  976. return self._full_description
  977. def SetDescriptionText(self, description):
  978. """Sets the full description text (including tags) to |description|.
  979. Also updates the list of tags."""
  980. self._full_description = description
  981. # From the description text, build up a dictionary of key/value pairs
  982. # plus the description minus all key/value or 'tag' lines.
  983. description_without_tags = []
  984. self.tags = {}
  985. for line in self._full_description.splitlines():
  986. m = self.TAG_LINE_RE.match(line)
  987. if m:
  988. self.tags[m.group('key')] = m.group('value')
  989. else:
  990. description_without_tags.append(line)
  991. # Change back to text and remove whitespace at end.
  992. self._description_without_tags = (
  993. '\n'.join(description_without_tags).rstrip())
  994. def AddDescriptionFooter(self, key, value):
  995. """Adds the given footer to the change description.
  996. Args:
  997. key: A string with the key for the git footer. It must conform to
  998. the git footers format (i.e. 'List-Of-Tokens') and will be case
  999. normalized so that each token is title-cased.
  1000. value: A string with the value for the git footer.
  1001. """
  1002. description = git_footers.add_footer(
  1003. self.FullDescriptionText(), git_footers.normalize_name(key), value)
  1004. self.SetDescriptionText(description)
  1005. def RepositoryRoot(self):
  1006. """Returns the repository (checkout) root directory for this change,
  1007. as an absolute path.
  1008. """
  1009. return self._local_root
  1010. def __getattr__(self, attr):
  1011. """Return tags directly as attributes on the object."""
  1012. if not re.match(r'^[A-Z_]*$', attr):
  1013. raise AttributeError(self, attr)
  1014. return self.tags.get(attr)
  1015. def GitFootersFromDescription(self):
  1016. """Return the git footers present in the description.
  1017. Returns:
  1018. footers: A dict of {footer: [values]} containing a multimap of the footers
  1019. in the change description.
  1020. """
  1021. return git_footers.parse_footers(self.FullDescriptionText())
  1022. def BugsFromDescription(self):
  1023. """Returns all bugs referenced in the commit description."""
  1024. bug_tags = ['BUG', 'FIXED']
  1025. tags = []
  1026. for tag in bug_tags:
  1027. values = self.tags.get(tag)
  1028. if values:
  1029. tags += [value.strip() for value in values.split(',')]
  1030. footers = []
  1031. parsed = self.GitFootersFromDescription()
  1032. unsplit_footers = parsed.get('Bug', []) + parsed.get('Fixed', [])
  1033. for unsplit_footer in unsplit_footers:
  1034. footers += [b.strip() for b in unsplit_footer.split(',')]
  1035. return sorted(set(tags + footers))
  1036. def ReviewersFromDescription(self):
  1037. """Returns all reviewers listed in the commit description."""
  1038. # We don't support a 'R:' git-footer for reviewers; that is in metadata.
  1039. tags = [r.strip() for r in self.tags.get('R', '').split(',') if r.strip()]
  1040. return sorted(set(tags))
  1041. def TBRsFromDescription(self):
  1042. """Returns all TBR reviewers listed in the commit description."""
  1043. tags = [r.strip() for r in self.tags.get('TBR', '').split(',') if r.strip()]
  1044. # TODO(crbug.com/839208): Remove support for 'Tbr:' when TBRs are
  1045. # programmatically determined by self-CR+1s.
  1046. footers = self.GitFootersFromDescription().get('Tbr', [])
  1047. return sorted(set(tags + footers))
  1048. # TODO(crbug.com/753425): Delete these once we're sure they're unused.
  1049. @property
  1050. def BUG(self):
  1051. return ','.join(self.BugsFromDescription())
  1052. @property
  1053. def R(self):
  1054. return ','.join(self.ReviewersFromDescription())
  1055. @property
  1056. def TBR(self):
  1057. return ','.join(self.TBRsFromDescription())
  1058. def AllFiles(self, root=None):
  1059. """List all files under source control in the repo."""
  1060. raise NotImplementedError()
  1061. def AffectedFiles(self, include_deletes=True, file_filter=None):
  1062. """Returns a list of AffectedFile instances for all files in the change.
  1063. Args:
  1064. include_deletes: If false, deleted files will be filtered out.
  1065. file_filter: An additional filter to apply.
  1066. Returns:
  1067. [AffectedFile(path, action), AffectedFile(path, action)]
  1068. """
  1069. affected = list(filter(file_filter, self._affected_files))
  1070. if include_deletes:
  1071. return affected
  1072. return list(filter(lambda x: x.Action() != 'D', affected))
  1073. def AffectedTestableFiles(self, include_deletes=None, **kwargs):
  1074. """Return a list of the existing text files in a change."""
  1075. if include_deletes is not None:
  1076. warn('AffectedTeestableFiles(include_deletes=%s)'
  1077. ' is deprecated and ignored' % str(include_deletes),
  1078. category=DeprecationWarning,
  1079. stacklevel=2)
  1080. return list(filter(
  1081. lambda x: x.IsTestableFile(),
  1082. self.AffectedFiles(include_deletes=False, **kwargs)))
  1083. def AffectedTextFiles(self, include_deletes=None):
  1084. """An alias to AffectedTestableFiles for backwards compatibility."""
  1085. return self.AffectedTestableFiles(include_deletes=include_deletes)
  1086. def LocalPaths(self):
  1087. """Convenience function."""
  1088. return [af.LocalPath() for af in self.AffectedFiles()]
  1089. def AbsoluteLocalPaths(self):
  1090. """Convenience function."""
  1091. return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
  1092. def RightHandSideLines(self):
  1093. """An iterator over all text lines in 'new' version of changed files.
  1094. Lists lines from new or modified text files in the change.
  1095. This is useful for doing line-by-line regex checks, like checking for
  1096. trailing whitespace.
  1097. Yields:
  1098. a 3 tuple:
  1099. the AffectedFile instance of the current file;
  1100. integer line number (1-based); and
  1101. the contents of the line as a string.
  1102. """
  1103. return _RightHandSideLinesImpl(
  1104. x for x in self.AffectedFiles(include_deletes=False)
  1105. if x.IsTestableFile())
  1106. def OriginalOwnersFiles(self):
  1107. """A map from path names of affected OWNERS files to their old content."""
  1108. def owners_file_filter(f):
  1109. return 'OWNERS' in os.path.split(f.LocalPath())[1]
  1110. files = self.AffectedFiles(file_filter=owners_file_filter)
  1111. return {f.LocalPath(): f.OldContents() for f in files}
  1112. class GitChange(Change):
  1113. _AFFECTED_FILES = GitAffectedFile
  1114. scm = 'git'
  1115. def AllFiles(self, root=None):
  1116. """List all files under source control in the repo."""
  1117. root = root or self.RepositoryRoot()
  1118. return subprocess.check_output(
  1119. ['git', '-c', 'core.quotePath=false', 'ls-files', '--', '.'],
  1120. cwd=root).decode('utf-8', 'ignore').splitlines()
  1121. def ListRelevantPresubmitFiles(files, root):
  1122. """Finds all presubmit files that apply to a given set of source files.
  1123. If inherit-review-settings-ok is present right under root, looks for
  1124. PRESUBMIT.py in directories enclosing root.
  1125. Args:
  1126. files: An iterable container containing file paths.
  1127. root: Path where to stop searching.
  1128. Return:
  1129. List of absolute paths of the existing PRESUBMIT.py scripts.
  1130. """
  1131. files = [normpath(os.path.join(root, f)) for f in files]
  1132. # List all the individual directories containing files.
  1133. directories = {os.path.dirname(f) for f in files}
  1134. # Ignore root if inherit-review-settings-ok is present.
  1135. if os.path.isfile(os.path.join(root, 'inherit-review-settings-ok')):
  1136. root = None
  1137. # Collect all unique directories that may contain PRESUBMIT.py.
  1138. candidates = set()
  1139. for directory in directories:
  1140. while True:
  1141. if directory in candidates:
  1142. break
  1143. candidates.add(directory)
  1144. if directory == root:
  1145. break
  1146. parent_dir = os.path.dirname(directory)
  1147. if parent_dir == directory:
  1148. # We hit the system root directory.
  1149. break
  1150. directory = parent_dir
  1151. # Look for PRESUBMIT.py in all candidate directories.
  1152. results = []
  1153. for directory in sorted(list(candidates)):
  1154. try:
  1155. for f in os.listdir(directory):
  1156. p = os.path.join(directory, f)
  1157. if os.path.isfile(p) and re.match(
  1158. r'PRESUBMIT.*\.py$', f) and not f.startswith('PRESUBMIT_test'):
  1159. results.append(p)
  1160. except OSError:
  1161. pass
  1162. logging.debug('Presubmit files: %s', ','.join(results))
  1163. return results
  1164. class GetPostUploadExecuter(object):
  1165. def __init__(self, use_python3):
  1166. """
  1167. Args:
  1168. use_python3: if true, will use python3 instead of python2 by default
  1169. if USE_PYTHON3 is not specified.
  1170. """
  1171. self.use_python3 = use_python3
  1172. def ExecPresubmitScript(self, script_text, presubmit_path, gerrit_obj,
  1173. change):
  1174. """Executes PostUploadHook() from a single presubmit script.
  1175. Caller is responsible for validating whether the hook should be executed
  1176. and should only call this function if it should be.
  1177. Args:
  1178. script_text: The text of the presubmit script.
  1179. presubmit_path: Project script to run.
  1180. gerrit_obj: The GerritAccessor object.
  1181. change: The Change object.
  1182. Return:
  1183. A list of results objects.
  1184. """
  1185. context = {}
  1186. try:
  1187. exec(compile(script_text, 'PRESUBMIT.py', 'exec', dont_inherit=True),
  1188. context)
  1189. except Exception as e:
  1190. raise PresubmitFailure('"%s" had an exception.\n%s'
  1191. % (presubmit_path, e))
  1192. function_name = 'PostUploadHook'
  1193. if function_name not in context:
  1194. return {}
  1195. post_upload_hook = context[function_name]
  1196. if not len(inspect.getargspec(post_upload_hook)[0]) == 3:
  1197. raise PresubmitFailure(
  1198. 'Expected function "PostUploadHook" to take three arguments.')
  1199. return post_upload_hook(gerrit_obj, change, OutputApi(False))
  1200. def _MergeMasters(masters1, masters2):
  1201. """Merges two master maps. Merges also the tests of each builder."""
  1202. result = {}
  1203. for (master, builders) in itertools.chain(masters1.items(),
  1204. masters2.items()):
  1205. new_builders = result.setdefault(master, {})
  1206. for (builder, tests) in builders.items():
  1207. new_builders.setdefault(builder, set([])).update(tests)
  1208. return result
  1209. def DoPostUploadExecuter(change, gerrit_obj, verbose, use_python3=False):
  1210. """Execute the post upload hook.
  1211. Args:
  1212. change: The Change object.
  1213. gerrit_obj: The GerritAccessor object.
  1214. verbose: Prints debug info.
  1215. use_python3: if true, default to using Python3 for presubmit checks
  1216. rather than Python2.
  1217. """
  1218. python_version = 'Python %s' % sys.version_info.major
  1219. sys.stdout.write('Running %s post upload checks ...\n' % python_version)
  1220. presubmit_files = ListRelevantPresubmitFiles(
  1221. change.LocalPaths(), change.RepositoryRoot())
  1222. if not presubmit_files and verbose:
  1223. sys.stdout.write('Warning, no PRESUBMIT.py found.\n')
  1224. results = []
  1225. executer = GetPostUploadExecuter(use_python3)
  1226. # The root presubmit file should be executed after the ones in subdirectories.
  1227. # i.e. the specific post upload hooks should run before the general ones.
  1228. # Thus, reverse the order provided by ListRelevantPresubmitFiles.
  1229. presubmit_files.reverse()
  1230. for filename in presubmit_files:
  1231. filename = os.path.abspath(filename)
  1232. # Accept CRLF presubmit script.
  1233. presubmit_script = gclient_utils.FileRead(filename).replace('\r\n', '\n')
  1234. if _ShouldRunPresubmit(presubmit_script, use_python3):
  1235. if sys.version_info[0] == 2:
  1236. sys.stdout.write(
  1237. 'Running %s under Python 2. Add USE_PYTHON3 = True to prevent '
  1238. 'this.\n' % filename)
  1239. elif verbose:
  1240. sys.stdout.write('Running %s\n' % filename)
  1241. results.extend(executer.ExecPresubmitScript(
  1242. presubmit_script, filename, gerrit_obj, change))
  1243. if not results:
  1244. return 0
  1245. sys.stdout.write('\n')
  1246. sys.stdout.write('** Post Upload Hook Messages **\n')
  1247. exit_code = 0
  1248. for result in results:
  1249. if result.fatal:
  1250. exit_code = 1
  1251. result.handle()
  1252. sys.stdout.write('\n')
  1253. return exit_code
  1254. class PresubmitExecuter(object):
  1255. def __init__(self, change, committing, verbose, gerrit_obj, dry_run=None,
  1256. thread_pool=None, parallel=False, use_python3=False,
  1257. no_diffs=False):
  1258. """
  1259. Args:
  1260. change: The Change object.
  1261. committing: True if 'git cl land' is running, False if 'git cl upload' is.
  1262. gerrit_obj: provides basic Gerrit codereview functionality.
  1263. dry_run: if true, some Checks will be skipped.
  1264. parallel: if true, all tests reported via input_api.RunTests for all
  1265. PRESUBMIT files will be run in parallel.
  1266. use_python3: if true, will use python3 instead of python2 by default
  1267. if USE_PYTHON3 is not specified.
  1268. no_diffs: if true, implies that --files or --all was specified so some
  1269. checks can be skipped, and some errors will be messages.
  1270. """
  1271. self.change = change
  1272. self.committing = committing
  1273. self.gerrit = gerrit_obj
  1274. self.verbose = verbose
  1275. self.dry_run = dry_run
  1276. self.more_cc = []
  1277. self.thread_pool = thread_pool
  1278. self.parallel = parallel
  1279. self.use_python3 = use_python3
  1280. self.no_diffs = no_diffs
  1281. def ExecPresubmitScript(self, script_text, presubmit_path):
  1282. """Executes a single presubmit script.
  1283. Caller is responsible for validating whether the hook should be executed
  1284. and should only call this function if it should be.
  1285. Args:
  1286. script_text: The text of the presubmit script.
  1287. presubmit_path: The path to the presubmit file (this will be reported via
  1288. input_api.PresubmitLocalPath()).
  1289. Return:
  1290. A list of result objects, empty if no problems.
  1291. """
  1292. # Change to the presubmit file's directory to support local imports.
  1293. main_path = os.getcwd()
  1294. presubmit_dir = os.path.dirname(presubmit_path)
  1295. os.chdir(presubmit_dir)
  1296. # Load the presubmit script into context.
  1297. input_api = InputApi(self.change, presubmit_path, self.committing,
  1298. self.verbose, gerrit_obj=self.gerrit,
  1299. dry_run=self.dry_run, thread_pool=self.thread_pool,
  1300. parallel=self.parallel, no_diffs=self.no_diffs)
  1301. output_api = OutputApi(self.committing)
  1302. context = {}
  1303. try:
  1304. exec(compile(script_text, presubmit_path, 'exec', dont_inherit=True),
  1305. context)
  1306. except Exception as e:
  1307. raise PresubmitFailure('"%s" had an exception.\n%s' % (presubmit_path, e))
  1308. context['__args'] = (input_api, output_api)
  1309. # Get path of presubmit directory relative to repository root.
  1310. # Always use forward slashes, so that path is same in *nix and Windows
  1311. root = input_api.change.RepositoryRoot()
  1312. rel_path = os.path.relpath(presubmit_dir, root)
  1313. rel_path = rel_path.replace(os.path.sep, '/')
  1314. # Get the URL of git remote origin and use it to identify host and project
  1315. host = project = ''
  1316. if self.gerrit:
  1317. host = self.gerrit.host or ''
  1318. project = self.gerrit.project or ''
  1319. # Prefix for test names
  1320. prefix = 'presubmit:%s/%s:%s/' % (host, project, rel_path)
  1321. # Perform all the desired presubmit checks.
  1322. results = []
  1323. try:
  1324. version = [
  1325. int(x) for x in context.get('PRESUBMIT_VERSION', '0.0.0').split('.')
  1326. ]
  1327. with rdb_wrapper.client(prefix) as sink:
  1328. if version >= [2, 0, 0]:
  1329. # Copy the keys to prevent "dictionary changed size during iteration"
  1330. # exception if checks add globals to context. E.g. sometimes the
  1331. # Python runtime will add __warningregistry__.
  1332. for function_name in list(context.keys()):
  1333. if not function_name.startswith('Check'):
  1334. continue
  1335. if function_name.endswith('Commit') and not self.committing:
  1336. continue
  1337. if function_name.endswith('Upload') and self.committing:
  1338. continue
  1339. logging.debug('Running %s in %s', function_name, presubmit_path)
  1340. results.extend(
  1341. self._run_check_function(function_name, context, sink,
  1342. presubmit_path))
  1343. logging.debug('Running %s done.', function_name)
  1344. self.more_cc.extend(output_api.more_cc)
  1345. else: # Old format
  1346. if self.committing:
  1347. function_name = 'CheckChangeOnCommit'
  1348. else:
  1349. function_name = 'CheckChangeOnUpload'
  1350. if function_name in list(context.keys()):
  1351. logging.debug('Running %s in %s', function_name, presubmit_path)
  1352. results.extend(
  1353. self._run_check_function(function_name, context, sink,
  1354. presubmit_path))
  1355. logging.debug('Running %s done.', function_name)
  1356. self.more_cc.extend(output_api.more_cc)
  1357. finally:
  1358. for f in input_api._named_temporary_files:
  1359. os.remove(f)
  1360. # Return the process to the original working directory.
  1361. os.chdir(main_path)
  1362. return results
  1363. def _run_check_function(self, function_name, context, sink, presubmit_path):
  1364. """Evaluates and returns the result of a given presubmit function.
  1365. If sink is given, the result of the presubmit function will be reported
  1366. to the ResultSink.
  1367. Args:
  1368. function_name: the name of the presubmit function to evaluate
  1369. context: a context dictionary in which the function will be evaluated
  1370. sink: an instance of ResultSink. None, by default.
  1371. Returns:
  1372. the result of the presubmit function call.
  1373. """
  1374. start_time = time_time()
  1375. try:
  1376. result = eval(function_name + '(*__args)', context)
  1377. self._check_result_type(result)
  1378. except Exception:
  1379. _, e_value, _ = sys.exc_info()
  1380. result = [
  1381. OutputApi.PresubmitError(
  1382. 'Evaluation of %s failed: %s, %s' %
  1383. (function_name, e_value, traceback.format_exc()))
  1384. ]
  1385. elapsed_time = time_time() - start_time
  1386. if elapsed_time > 10.0:
  1387. sys.stdout.write('%6.1fs to run %s from %s.\n' %
  1388. (elapsed_time, function_name, presubmit_path))
  1389. if sink:
  1390. failure_reason = None
  1391. status = rdb_wrapper.STATUS_PASS
  1392. if any(r.fatal for r in result):
  1393. status = rdb_wrapper.STATUS_FAIL
  1394. failure_reasons = []
  1395. for r in result:
  1396. fields = r.json_format()
  1397. message = fields['message']
  1398. items = '\n'.join(' %s' % item for item in fields['items'])
  1399. failure_reasons.append('\n'.join([message, items]))
  1400. if failure_reasons:
  1401. failure_reason = '\n'.join(failure_reasons)
  1402. sink.report(function_name, status, elapsed_time, failure_reason)
  1403. return result
  1404. def _check_result_type(self, result):
  1405. """Helper function which ensures result is a list, and all elements are
  1406. instances of OutputApi.PresubmitResult"""
  1407. if not isinstance(result, (tuple, list)):
  1408. raise PresubmitFailure('Presubmit functions must return a tuple or list')
  1409. if not all(isinstance(res, OutputApi.PresubmitResult) for res in result):
  1410. raise PresubmitFailure(
  1411. 'All presubmit results must be of types derived from '
  1412. 'output_api.PresubmitResult')
  1413. def DoPresubmitChecks(change,
  1414. committing,
  1415. verbose,
  1416. default_presubmit,
  1417. may_prompt,
  1418. gerrit_obj,
  1419. dry_run=None,
  1420. parallel=False,
  1421. json_output=None,
  1422. use_python3=False,
  1423. no_diffs=False):
  1424. """Runs all presubmit checks that apply to the files in the change.
  1425. This finds all PRESUBMIT.py files in directories enclosing the files in the
  1426. change (up to the repository root) and calls the relevant entrypoint function
  1427. depending on whether the change is being committed or uploaded.
  1428. Prints errors, warnings and notifications. Prompts the user for warnings
  1429. when needed.
  1430. Args:
  1431. change: The Change object.
  1432. committing: True if 'git cl land' is running, False if 'git cl upload' is.
  1433. verbose: Prints debug info.
  1434. default_presubmit: A default presubmit script to execute in any case.
  1435. may_prompt: Enable (y/n) questions on warning or error. If False,
  1436. any questions are answered with yes by default.
  1437. gerrit_obj: provides basic Gerrit codereview functionality.
  1438. dry_run: if true, some Checks will be skipped.
  1439. parallel: if true, all tests specified by input_api.RunTests in all
  1440. PRESUBMIT files will be run in parallel.
  1441. use_python3: if true, default to using Python3 for presubmit checks
  1442. rather than Python2.
  1443. no_diffs: if true, implies that --files or --all was specified so some
  1444. checks can be skipped, and some errors will be messages.
  1445. Return:
  1446. 1 if presubmit checks failed or 0 otherwise.
  1447. """
  1448. old_environ = os.environ
  1449. try:
  1450. # Make sure python subprocesses won't generate .pyc files.
  1451. os.environ = os.environ.copy()
  1452. os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
  1453. python_version = 'Python %s' % sys.version_info.major
  1454. if committing:
  1455. sys.stdout.write('Running %s presubmit commit checks ...\n' %
  1456. python_version)
  1457. else:
  1458. sys.stdout.write('Running %s presubmit upload checks ...\n' %
  1459. python_version)
  1460. start_time = time_time()
  1461. presubmit_files = ListRelevantPresubmitFiles(
  1462. change.AbsoluteLocalPaths(), change.RepositoryRoot())
  1463. if not presubmit_files and verbose:
  1464. sys.stdout.write('Warning, no PRESUBMIT.py found.\n')
  1465. results = []
  1466. if sys.platform == 'win32':
  1467. temp = os.environ['TEMP']
  1468. else:
  1469. temp = '/tmp'
  1470. python2_usage_log_file = os.path.join(temp, 'python2_usage.txt')
  1471. if os.path.exists(python2_usage_log_file):
  1472. os.remove(python2_usage_log_file)
  1473. thread_pool = ThreadPool()
  1474. executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
  1475. dry_run, thread_pool, parallel, use_python3,
  1476. no_diffs)
  1477. skipped_count = 0;
  1478. if default_presubmit:
  1479. if verbose:
  1480. sys.stdout.write('Running default presubmit script.\n')
  1481. fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
  1482. if _ShouldRunPresubmit(default_presubmit, use_python3):
  1483. results += executer.ExecPresubmitScript(default_presubmit, fake_path)
  1484. else:
  1485. skipped_count += 1
  1486. for filename in presubmit_files:
  1487. filename = os.path.abspath(filename)
  1488. # Accept CRLF presubmit script.
  1489. presubmit_script = gclient_utils.FileRead(filename).replace('\r\n', '\n')
  1490. if _ShouldRunPresubmit(presubmit_script, use_python3):
  1491. if sys.version_info[0] == 2:
  1492. sys.stdout.write(
  1493. 'Running %s under Python 2. Add USE_PYTHON3 = True to prevent '
  1494. 'this.\n' % filename)
  1495. elif verbose:
  1496. sys.stdout.write('Running %s\n' % filename)
  1497. results += executer.ExecPresubmitScript(presubmit_script, filename)
  1498. else:
  1499. skipped_count += 1
  1500. results += thread_pool.RunAsync()
  1501. if os.path.exists(python2_usage_log_file):
  1502. with open(python2_usage_log_file) as f:
  1503. python2_usage = [x.strip() for x in f.readlines()]
  1504. results.append(
  1505. OutputApi(committing).PresubmitPromptWarning(
  1506. 'Python 2 scripts were run during %s presubmits. Please see '
  1507. 'https://bugs.chromium.org/p/chromium/issues/detail?id=1313804'
  1508. '#c61 for tips on resolving this.'
  1509. % python_version,
  1510. items=python2_usage))
  1511. messages = {}
  1512. should_prompt = False
  1513. presubmits_failed = False
  1514. for result in results:
  1515. if result.fatal:
  1516. presubmits_failed = True
  1517. messages.setdefault('ERRORS', []).append(result)
  1518. elif result.should_prompt:
  1519. should_prompt = True
  1520. messages.setdefault('Warnings', []).append(result)
  1521. else:
  1522. messages.setdefault('Messages', []).append(result)
  1523. # Print the different message types in a consistent order. ERRORS go last
  1524. # so that they will be most visible in the local-presubmit output.
  1525. for name in ['Messages', 'Warnings', 'ERRORS']:
  1526. if name in messages:
  1527. items = messages[name]
  1528. sys.stdout.write('** Presubmit %s: %d **\n' % (name, len(items)))
  1529. for item in items:
  1530. item.handle()
  1531. sys.stdout.write('\n')
  1532. total_time = time_time() - start_time
  1533. if total_time > 1.0:
  1534. sys.stdout.write(
  1535. 'Presubmit checks took %.1fs to calculate.\n' % total_time)
  1536. if not should_prompt and not presubmits_failed:
  1537. sys.stdout.write('%s presubmit checks passed.\n\n' % python_version)
  1538. elif should_prompt and not presubmits_failed:
  1539. sys.stdout.write('There were %s presubmit warnings. ' % python_version)
  1540. if may_prompt:
  1541. presubmits_failed = not prompt_should_continue(
  1542. 'Are you sure you wish to continue? (y/N): ')
  1543. else:
  1544. sys.stdout.write('\n')
  1545. else:
  1546. sys.stdout.write('There were %s presubmit errors.\n' % python_version)
  1547. if json_output:
  1548. # Write the presubmit results to json output
  1549. presubmit_results = {
  1550. 'errors': [
  1551. error.json_format()
  1552. for error in messages.get('ERRORS', [])
  1553. ],
  1554. 'notifications': [
  1555. notification.json_format()
  1556. for notification in messages.get('Messages', [])
  1557. ],
  1558. 'warnings': [
  1559. warning.json_format()
  1560. for warning in messages.get('Warnings', [])
  1561. ],
  1562. 'more_cc': executer.more_cc,
  1563. 'skipped_presubmits': skipped_count,
  1564. }
  1565. gclient_utils.FileWrite(
  1566. json_output, json.dumps(presubmit_results, sort_keys=True))
  1567. global _ASKED_FOR_FEEDBACK
  1568. # Ask for feedback one time out of 5.
  1569. if (results and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
  1570. sys.stdout.write(
  1571. 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
  1572. 'to figure out which PRESUBMIT.py was run, then run git blame\n'
  1573. 'on the file to figure out who to ask for help.\n')
  1574. _ASKED_FOR_FEEDBACK = True
  1575. return 1 if presubmits_failed else 0
  1576. finally:
  1577. os.environ = old_environ
  1578. def _scan_sub_dirs(mask, recursive):
  1579. if not recursive:
  1580. return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
  1581. results = []
  1582. for root, dirs, files in os.walk('.'):
  1583. if '.svn' in dirs:
  1584. dirs.remove('.svn')
  1585. if '.git' in dirs:
  1586. dirs.remove('.git')
  1587. for name in files:
  1588. if fnmatch.fnmatch(name, mask):
  1589. results.append(os.path.join(root, name))
  1590. return results
  1591. def _parse_files(args, recursive):
  1592. logging.debug('Searching for %s', args)
  1593. files = []
  1594. for arg in args:
  1595. files.extend([('M', f) for f in _scan_sub_dirs(arg, recursive)])
  1596. return files
  1597. def _parse_change(parser, options):
  1598. """Process change options.
  1599. Args:
  1600. parser: The parser used to parse the arguments from command line.
  1601. options: The arguments parsed from command line.
  1602. Returns:
  1603. A GitChange if the change root is a git repository, or a Change otherwise.
  1604. """
  1605. if options.files and options.all_files:
  1606. parser.error('<files> cannot be specified when --all-files is set.')
  1607. change_scm = scm.determine_scm(options.root)
  1608. if change_scm != 'git' and not options.files:
  1609. parser.error('<files> is not optional for unversioned directories.')
  1610. if options.files:
  1611. if options.source_controlled_only:
  1612. # Get the filtered set of files from SCM.
  1613. change_files = []
  1614. for name in scm.GIT.GetAllFiles(options.root):
  1615. for mask in options.files:
  1616. if fnmatch.fnmatch(name, mask):
  1617. change_files.append(('M', name))
  1618. break
  1619. else:
  1620. # Get the filtered set of files from a directory scan.
  1621. change_files = _parse_files(options.files, options.recursive)
  1622. elif options.all_files:
  1623. change_files = [('M', f) for f in scm.GIT.GetAllFiles(options.root)]
  1624. else:
  1625. change_files = scm.GIT.CaptureStatus(
  1626. options.root, options.upstream or None)
  1627. logging.info('Found %d file(s).', len(change_files))
  1628. change_class = GitChange if change_scm == 'git' else Change
  1629. return change_class(
  1630. options.name,
  1631. options.description,
  1632. options.root,
  1633. change_files,
  1634. options.issue,
  1635. options.patchset,
  1636. options.author,
  1637. upstream=options.upstream)
  1638. def _parse_gerrit_options(parser, options):
  1639. """Process gerrit options.
  1640. SIDE EFFECTS: Modifies options.author and options.description from Gerrit if
  1641. options.gerrit_fetch is set.
  1642. Args:
  1643. parser: The parser used to parse the arguments from command line.
  1644. options: The arguments parsed from command line.
  1645. Returns:
  1646. A GerritAccessor object if options.gerrit_url is set, or None otherwise.
  1647. """
  1648. gerrit_obj = None
  1649. if options.gerrit_url:
  1650. gerrit_obj = GerritAccessor(
  1651. url=options.gerrit_url,
  1652. project=options.gerrit_project,
  1653. branch=options.gerrit_branch)
  1654. if not options.gerrit_fetch:
  1655. return gerrit_obj
  1656. if not options.gerrit_url or not options.issue or not options.patchset:
  1657. parser.error(
  1658. '--gerrit_fetch requires --gerrit_url, --issue and --patchset.')
  1659. options.author = gerrit_obj.GetChangeOwner(options.issue)
  1660. options.description = gerrit_obj.GetChangeDescription(
  1661. options.issue, options.patchset)
  1662. logging.info('Got author: "%s"', options.author)
  1663. logging.info('Got description: """\n%s\n"""', options.description)
  1664. return gerrit_obj
  1665. @contextlib.contextmanager
  1666. def canned_check_filter(method_names):
  1667. filtered = {}
  1668. try:
  1669. for method_name in method_names:
  1670. if not hasattr(presubmit_canned_checks, method_name):
  1671. logging.warning('Skipping unknown "canned" check %s' % method_name)
  1672. continue
  1673. filtered[method_name] = getattr(presubmit_canned_checks, method_name)
  1674. setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
  1675. yield
  1676. finally:
  1677. for name, method in filtered.items():
  1678. setattr(presubmit_canned_checks, name, method)
  1679. def main(argv=None):
  1680. parser = argparse.ArgumentParser(usage='%(prog)s [options] <files...>')
  1681. hooks = parser.add_mutually_exclusive_group()
  1682. hooks.add_argument('-c', '--commit', action='store_true',
  1683. help='Use commit instead of upload checks.')
  1684. hooks.add_argument('-u', '--upload', action='store_false', dest='commit',
  1685. help='Use upload instead of commit checks.')
  1686. hooks.add_argument('--post_upload', action='store_true',
  1687. help='Run post-upload commit hooks.')
  1688. parser.add_argument('-r', '--recursive', action='store_true',
  1689. help='Act recursively.')
  1690. parser.add_argument('-v', '--verbose', action='count', default=0,
  1691. help='Use 2 times for more debug info.')
  1692. parser.add_argument('--name', default='no name')
  1693. parser.add_argument('--author')
  1694. desc = parser.add_mutually_exclusive_group()
  1695. desc.add_argument('--description', default='', help='The change description.')
  1696. desc.add_argument('--description_file',
  1697. help='File to read change description from.')
  1698. parser.add_argument('--issue', type=int, default=0)
  1699. parser.add_argument('--patchset', type=int, default=0)
  1700. parser.add_argument('--root', default=os.getcwd(),
  1701. help='Search for PRESUBMIT.py up to this directory. '
  1702. 'If inherit-review-settings-ok is present in this '
  1703. 'directory, parent directories up to the root file '
  1704. 'system directories will also be searched.')
  1705. parser.add_argument('--upstream',
  1706. help='Git only: the base ref or upstream branch against '
  1707. 'which the diff should be computed.')
  1708. parser.add_argument('--default_presubmit')
  1709. parser.add_argument('--may_prompt', action='store_true', default=False)
  1710. parser.add_argument('--skip_canned', action='append', default=[],
  1711. help='A list of checks to skip which appear in '
  1712. 'presubmit_canned_checks. Can be provided multiple times '
  1713. 'to skip multiple canned checks.')
  1714. parser.add_argument('--dry_run', action='store_true', help=argparse.SUPPRESS)
  1715. parser.add_argument('--gerrit_url', help=argparse.SUPPRESS)
  1716. parser.add_argument('--gerrit_project', help=argparse.SUPPRESS)
  1717. parser.add_argument('--gerrit_branch', help=argparse.SUPPRESS)
  1718. parser.add_argument('--gerrit_fetch', action='store_true',
  1719. help=argparse.SUPPRESS)
  1720. parser.add_argument('--parallel', action='store_true',
  1721. help='Run all tests specified by input_api.RunTests in '
  1722. 'all PRESUBMIT files in parallel.')
  1723. parser.add_argument('--json_output',
  1724. help='Write presubmit errors to json output.')
  1725. parser.add_argument('--all_files', action='store_true',
  1726. help='Mark all files under source control as modified.')
  1727. parser.add_argument('files', nargs='*',
  1728. help='List of files to be marked as modified when '
  1729. 'executing presubmit or post-upload hooks. fnmatch '
  1730. 'wildcards can also be used.')
  1731. parser.add_argument('--source_controlled_only', action='store_true',
  1732. help='Constrain \'files\' to those in source control.')
  1733. parser.add_argument('--use-python3', action='store_true',
  1734. help='Use python3 for presubmit checks by default')
  1735. parser.add_argument('--no_diffs', action='store_true',
  1736. help='Assume that all "modified" files have no diffs.')
  1737. options = parser.parse_args(argv)
  1738. log_level = logging.ERROR
  1739. if options.verbose >= 2:
  1740. log_level = logging.DEBUG
  1741. elif options.verbose:
  1742. log_level = logging.INFO
  1743. log_format = ('[%(levelname).1s%(asctime)s %(process)d %(thread)d '
  1744. '%(filename)s] %(message)s')
  1745. logging.basicConfig(format=log_format, level=log_level)
  1746. # Print call stacks when _PresubmitResult objects are created with -v -v is
  1747. # specified. This helps track down where presubmit messages are coming from.
  1748. if options.verbose >= 2:
  1749. global _SHOW_CALLSTACKS
  1750. _SHOW_CALLSTACKS = True
  1751. if options.description_file:
  1752. options.description = gclient_utils.FileRead(options.description_file)
  1753. gerrit_obj = _parse_gerrit_options(parser, options)
  1754. change = _parse_change(parser, options)
  1755. try:
  1756. if options.post_upload:
  1757. return DoPostUploadExecuter(change, gerrit_obj, options.verbose,
  1758. options.use_python3)
  1759. with canned_check_filter(options.skip_canned):
  1760. return DoPresubmitChecks(
  1761. change,
  1762. options.commit,
  1763. options.verbose,
  1764. options.default_presubmit,
  1765. options.may_prompt,
  1766. gerrit_obj,
  1767. options.dry_run,
  1768. options.parallel,
  1769. options.json_output,
  1770. options.use_python3,
  1771. options.no_diffs)
  1772. except PresubmitFailure as e:
  1773. import utils
  1774. print(e, file=sys.stderr)
  1775. print('Maybe your depot_tools is out of date?', file=sys.stderr)
  1776. print('depot_tools version: %s' % utils.depot_tools_version(),
  1777. file=sys.stderr)
  1778. return 2
  1779. if __name__ == '__main__':
  1780. fix_encoding.fix_encoding()
  1781. try:
  1782. sys.exit(main())
  1783. except KeyboardInterrupt:
  1784. sys.stderr.write('interrupted\n')
  1785. sys.exit(2)