presubmit_support.py 81 KB

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