presubmit_support.py 74 KB

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