presubmit_support.py 76 KB

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