presubmit_support.py 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185
  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 typing import Mapping
  36. from warnings import warn
  37. # Local imports.
  38. import fix_encoding
  39. import gclient_paths # Exposed through the API
  40. import gclient_utils
  41. import git_footers
  42. import gerrit_util
  43. import owners_client
  44. import owners_finder
  45. import presubmit_canned_checks
  46. import rdb_wrapper
  47. import scm
  48. import subprocess2 as subprocess # Exposed through the API.
  49. # TODO: Should fix these warnings.
  50. # pylint: disable=line-too-long
  51. # Ask for feedback only once in program lifetime.
  52. _ASKED_FOR_FEEDBACK = False
  53. # Set if super-verbose mode is requested, for tracking where presubmit messages
  54. # are coming from.
  55. _SHOW_CALLSTACKS = False
  56. def time_time():
  57. # Use this so that it can be mocked in tests without interfering with python
  58. # system machinery.
  59. return time.time()
  60. class PresubmitFailure(Exception):
  61. pass
  62. class CommandData(object):
  63. def __init__(self, name, cmd, kwargs, message, python3=True):
  64. # The python3 argument is ignored but has to be retained because of the
  65. # many callers in other repos that pass it in.
  66. del python3
  67. self.name = name
  68. self.cmd = cmd
  69. self.stdin = kwargs.get('stdin', None)
  70. self.kwargs = kwargs.copy()
  71. self.kwargs['stdout'] = subprocess.PIPE
  72. self.kwargs['stderr'] = subprocess.STDOUT
  73. self.kwargs['stdin'] = subprocess.PIPE
  74. self.message = message
  75. self.info = None
  76. # Adapted from
  77. # https://github.com/google/gtest-parallel/blob/master/gtest_parallel.py#L37
  78. #
  79. # An object that catches SIGINT sent to the Python process and notices
  80. # if processes passed to wait() die by SIGINT (we need to look for
  81. # both of those cases, because pressing Ctrl+C can result in either
  82. # the main process or one of the subprocesses getting the signal).
  83. #
  84. # Before a SIGINT is seen, wait(p) will simply call p.wait() and
  85. # return the result. Once a SIGINT has been seen (in the main process
  86. # or a subprocess, including the one the current call is waiting for),
  87. # wait(p) will call p.terminate().
  88. class SigintHandler(object):
  89. sigint_returncodes = {
  90. -signal.SIGINT, # Unix
  91. -1073741510, # Windows
  92. }
  93. def __init__(self):
  94. self.__lock = threading.Lock()
  95. self.__processes = set()
  96. self.__got_sigint = False
  97. self.__previous_signal = signal.signal(signal.SIGINT, self.interrupt)
  98. def __on_sigint(self):
  99. self.__got_sigint = True
  100. while self.__processes:
  101. try:
  102. self.__processes.pop().terminate()
  103. except OSError:
  104. pass
  105. def interrupt(self, signal_num, frame):
  106. with self.__lock:
  107. self.__on_sigint()
  108. self.__previous_signal(signal_num, frame)
  109. def got_sigint(self):
  110. with self.__lock:
  111. return self.__got_sigint
  112. def wait(self, p, stdin):
  113. with self.__lock:
  114. if self.__got_sigint:
  115. p.terminate()
  116. self.__processes.add(p)
  117. stdout, stderr = p.communicate(stdin)
  118. code = p.returncode
  119. with self.__lock:
  120. self.__processes.discard(p)
  121. if code in self.sigint_returncodes:
  122. self.__on_sigint()
  123. return stdout, stderr
  124. sigint_handler = SigintHandler()
  125. class Timer(object):
  126. def __init__(self, timeout, fn):
  127. self.completed = False
  128. self._fn = fn
  129. self._timer = threading.Timer(timeout,
  130. self._onTimer) if timeout else None
  131. def __enter__(self):
  132. if self._timer:
  133. self._timer.start()
  134. return self
  135. def __exit__(self, _type, _value, _traceback):
  136. if self._timer:
  137. self._timer.cancel()
  138. def _onTimer(self):
  139. self._fn()
  140. self.completed = True
  141. class ThreadPool(object):
  142. def __init__(self, pool_size=None, timeout=None):
  143. self.timeout = timeout
  144. self._pool_size = pool_size or multiprocessing.cpu_count()
  145. if sys.platform == 'win32':
  146. # TODO(crbug.com/1190269) - we can't use more than 56 child
  147. # processes on Windows or Python3 may hang.
  148. self._pool_size = min(self._pool_size, 56)
  149. self._messages = []
  150. self._messages_lock = threading.Lock()
  151. self._tests = []
  152. self._tests_lock = threading.Lock()
  153. self._nonparallel_tests = []
  154. def _GetCommand(self, test):
  155. vpython = 'vpython3'
  156. if sys.platform == 'win32':
  157. vpython += '.bat'
  158. cmd = test.cmd
  159. if cmd[0] == 'python':
  160. cmd = list(cmd)
  161. cmd[0] = vpython
  162. elif cmd[0].endswith('.py'):
  163. cmd = [vpython] + cmd
  164. # On Windows, scripts on the current directory take precedence over
  165. # PATH, so that when testing depot_tools on Windows, calling
  166. # `vpython.bat` will execute the copy of vpython of the depot_tools
  167. # under test instead of the one in the bot. As a workaround, we run the
  168. # tests from the parent directory instead.
  169. if (cmd[0] == vpython and 'cwd' in test.kwargs
  170. and os.path.basename(test.kwargs['cwd']) == 'depot_tools'):
  171. test.kwargs['cwd'] = os.path.dirname(test.kwargs['cwd'])
  172. cmd[1] = os.path.join('depot_tools', cmd[1])
  173. return cmd
  174. def _RunWithTimeout(self, cmd, stdin, kwargs):
  175. p = subprocess.Popen(cmd, **kwargs)
  176. with Timer(self.timeout, p.terminate) as timer:
  177. stdout, _ = sigint_handler.wait(p, stdin)
  178. stdout = stdout.decode('utf-8', 'ignore')
  179. if timer.completed:
  180. stdout = 'Process timed out after %ss\n%s' % (self.timeout,
  181. stdout)
  182. return p.returncode, stdout
  183. def CallCommand(self, test, show_callstack=None):
  184. """Runs an external program.
  185. This function converts invocation of .py files and invocations of 'python'
  186. to vpython invocations.
  187. """
  188. cmd = self._GetCommand(test)
  189. try:
  190. start = time_time()
  191. returncode, stdout = self._RunWithTimeout(cmd, test.stdin,
  192. test.kwargs)
  193. duration = time_time() - start
  194. except Exception:
  195. duration = time_time() - start
  196. return test.message(
  197. '%s\n%s exec failure (%4.2fs)\n%s' %
  198. (test.name, ' '.join(cmd), duration, traceback.format_exc()),
  199. show_callstack=show_callstack)
  200. if returncode != 0:
  201. return test.message('%s\n%s (%4.2fs) failed\n%s' %
  202. (test.name, ' '.join(cmd), duration, stdout),
  203. show_callstack=show_callstack)
  204. if test.info:
  205. return test.info('%s\n%s (%4.2fs)' %
  206. (test.name, ' '.join(cmd), duration),
  207. show_callstack=show_callstack)
  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, show_callstack=False)
  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. # Top level object so multiprocessing can pickle
  261. # Public access through OutputApi object.
  262. class _PresubmitResult(object):
  263. """Base class for result objects."""
  264. fatal = False
  265. should_prompt = False
  266. def __init__(self, message, items=None, long_text='', show_callstack=None):
  267. """
  268. message: A short one-line message to indicate errors.
  269. items: A list of short strings to indicate where errors occurred.
  270. long_text: multi-line text output, e.g. from another tool
  271. """
  272. self._message = _PresubmitResult._ensure_str(message)
  273. self._items = items or []
  274. self._long_text = _PresubmitResult._ensure_str(long_text.rstrip())
  275. if show_callstack is None:
  276. show_callstack = _SHOW_CALLSTACKS
  277. if show_callstack:
  278. self._long_text += 'Presubmit result call stack is:\n'
  279. self._long_text += ''.join(traceback.format_stack(None, 8))
  280. @staticmethod
  281. def _ensure_str(val):
  282. """
  283. val: A "stringish" value. Can be any of str or bytes.
  284. returns: A str after applying encoding/decoding as needed.
  285. Assumes/uses UTF-8 for relevant inputs/outputs.
  286. """
  287. if isinstance(val, str):
  288. return val
  289. if isinstance(val, bytes):
  290. return val.decode()
  291. raise ValueError("Unknown string type %s" % type(val))
  292. def handle(self):
  293. sys.stdout.write(self._message)
  294. sys.stdout.write('\n')
  295. for item in self._items:
  296. sys.stdout.write(' ')
  297. # Write separately in case it's unicode.
  298. sys.stdout.write(str(item))
  299. sys.stdout.write('\n')
  300. if self._long_text:
  301. sys.stdout.write('\n***************\n')
  302. # Write separately in case it's unicode.
  303. sys.stdout.write(self._long_text)
  304. sys.stdout.write('\n***************\n')
  305. def json_format(self):
  306. return {
  307. 'message': self._message,
  308. 'items': [str(item) for item in self._items],
  309. 'long_text': self._long_text,
  310. 'fatal': self.fatal
  311. }
  312. # Top level object so multiprocessing can pickle
  313. # Public access through OutputApi object.
  314. class _PresubmitError(_PresubmitResult):
  315. """A hard presubmit error."""
  316. fatal = True
  317. # Top level object so multiprocessing can pickle
  318. # Public access through OutputApi object.
  319. class _PresubmitPromptWarning(_PresubmitResult):
  320. """An warning that prompts the user if they want to continue."""
  321. should_prompt = True
  322. # Top level object so multiprocessing can pickle
  323. # Public access through OutputApi object.
  324. class _PresubmitNotifyResult(_PresubmitResult):
  325. """Just print something to the screen -- but it's not even a warning."""
  326. # Top level object so multiprocessing can pickle
  327. # Public access through OutputApi object.
  328. class _MailTextResult(_PresubmitResult):
  329. """A warning that should be included in the review request email."""
  330. def __init__(self, *args, **kwargs):
  331. super(_MailTextResult, self).__init__()
  332. raise NotImplementedError()
  333. class GerritAccessor(object):
  334. """Limited Gerrit functionality for canned presubmit checks to work.
  335. To avoid excessive Gerrit calls, caches the results.
  336. """
  337. def __init__(self, url=None, project=None, branch=None):
  338. self.host = urlparse.urlparse(url).netloc if url else None
  339. self.project = project
  340. self.branch = branch
  341. self.cache = {}
  342. self.code_owners_enabled = None
  343. def _FetchChangeDetail(self, issue):
  344. # Separate function to be easily mocked in tests.
  345. try:
  346. return gerrit_util.GetChangeDetail(
  347. self.host, str(issue),
  348. ['ALL_REVISIONS', 'DETAILED_LABELS', 'ALL_COMMITS'])
  349. except gerrit_util.GerritError as e:
  350. if e.http_status == 404:
  351. raise Exception('Either Gerrit issue %s doesn\'t exist, or '
  352. 'no credentials to fetch issue details' % issue)
  353. raise
  354. def GetChangeInfo(self, issue):
  355. """Returns labels and all revisions (patchsets) for this issue.
  356. The result is a dictionary according to Gerrit REST Api.
  357. https://gerrit-review.googlesource.com/Documentation/rest-api.html
  358. However, API isn't very clear what's inside, so see tests for example.
  359. """
  360. assert issue
  361. cache_key = int(issue)
  362. if cache_key not in self.cache:
  363. self.cache[cache_key] = self._FetchChangeDetail(issue)
  364. return self.cache[cache_key]
  365. def GetChangeDescription(self, issue, patchset=None):
  366. """If patchset is none, fetches current patchset."""
  367. info = self.GetChangeInfo(issue)
  368. # info is a reference to cache. We'll modify it here adding description
  369. # to it to the right patchset, if it is not yet there.
  370. # Find revision info for the patchset we want.
  371. if patchset is not None:
  372. for rev, rev_info in info['revisions'].items():
  373. if str(rev_info['_number']) == str(patchset):
  374. break
  375. else:
  376. raise Exception('patchset %s doesn\'t exist in issue %s' %
  377. (patchset, issue))
  378. else:
  379. rev = info['current_revision']
  380. rev_info = info['revisions'][rev]
  381. return rev_info['commit']['message']
  382. def GetDestRef(self, issue):
  383. ref = self.GetChangeInfo(issue)['branch']
  384. if not ref.startswith('refs/'):
  385. # NOTE: it is possible to create 'refs/x' branch,
  386. # aka 'refs/heads/refs/x'. However, this is ill-advised.
  387. ref = 'refs/heads/%s' % ref
  388. return ref
  389. def _GetApproversForLabel(self, issue, label):
  390. change_info = self.GetChangeInfo(issue)
  391. label_info = change_info.get('labels', {}).get(label, {})
  392. values = label_info.get('values', {}).keys()
  393. if not values:
  394. return []
  395. max_value = max(int(v) for v in values)
  396. return [
  397. v for v in label_info.get('all', [])
  398. if v.get('value', 0) == max_value
  399. ]
  400. def IsBotCommitApproved(self, issue):
  401. return bool(self._GetApproversForLabel(issue, 'Bot-Commit'))
  402. def IsOwnersOverrideApproved(self, issue):
  403. return bool(self._GetApproversForLabel(issue, 'Owners-Override'))
  404. def GetChangeOwner(self, issue):
  405. return self.GetChangeInfo(issue)['owner']['email']
  406. def GetChangeReviewers(self, issue, approving_only=True):
  407. changeinfo = self.GetChangeInfo(issue)
  408. if approving_only:
  409. reviewers = self._GetApproversForLabel(issue, 'Code-Review')
  410. else:
  411. reviewers = changeinfo.get('reviewers', {}).get('REVIEWER', [])
  412. return [r.get('email') for r in reviewers]
  413. def UpdateDescription(self, description, issue):
  414. gerrit_util.SetCommitMessage(self.host,
  415. issue,
  416. description,
  417. notify='NONE')
  418. def IsCodeOwnersEnabledOnRepo(self):
  419. if self.code_owners_enabled is None:
  420. self.code_owners_enabled = gerrit_util.IsCodeOwnersEnabledOnRepo(
  421. self.host, self.project)
  422. return self.code_owners_enabled
  423. class OutputApi(object):
  424. """An instance of OutputApi gets passed to presubmit scripts so that they
  425. can output various types of results.
  426. """
  427. PresubmitResult = _PresubmitResult
  428. PresubmitError = _PresubmitError
  429. PresubmitPromptWarning = _PresubmitPromptWarning
  430. PresubmitNotifyResult = _PresubmitNotifyResult
  431. MailTextResult = _MailTextResult
  432. def __init__(self, is_committing):
  433. self.is_committing = is_committing
  434. self.more_cc = []
  435. def AppendCC(self, cc):
  436. """Appends a user to cc for this change."""
  437. self.more_cc.append(cc)
  438. def PresubmitPromptOrNotify(self, *args, **kwargs):
  439. """Warn the user when uploading, but only notify if committing."""
  440. if self.is_committing:
  441. return self.PresubmitNotifyResult(*args, **kwargs)
  442. return self.PresubmitPromptWarning(*args, **kwargs)
  443. class InputApi(object):
  444. """An instance of this object is passed to presubmit scripts so they can
  445. know stuff about the change they're looking at.
  446. """
  447. # Method could be a function
  448. # pylint: disable=no-self-use
  449. # File extensions that are considered source files from a style guide
  450. # perspective. Don't modify this list from a presubmit script!
  451. #
  452. # Files without an extension aren't included in the list. If you want to
  453. # filter them as source files, add r'(^|.*?[\\\/])[^.]+$' to the allow list.
  454. # Note that ALL CAPS files are skipped in DEFAULT_FILES_TO_SKIP below.
  455. DEFAULT_FILES_TO_CHECK = (
  456. # C++ and friends
  457. r'.+\.c$',
  458. r'.+\.cc$',
  459. r'.+\.cpp$',
  460. r'.+\.h$',
  461. r'.+\.m$',
  462. r'.+\.mm$',
  463. r'.+\.inl$',
  464. r'.+\.asm$',
  465. r'.+\.hxx$',
  466. r'.+\.hpp$',
  467. r'.+\.s$',
  468. r'.+\.S$',
  469. # Scripts
  470. r'.+\.js$',
  471. r'.+\.ts$',
  472. r'.+\.py$',
  473. r'.+\.sh$',
  474. r'.+\.rb$',
  475. r'.+\.pl$',
  476. r'.+\.pm$',
  477. # Other
  478. r'.+\.java$',
  479. r'.+\.mk$',
  480. r'.+\.am$',
  481. r'.+\.css$',
  482. r'.+\.mojom$',
  483. r'.+\.fidl$',
  484. r'.+\.rs$',
  485. )
  486. # Path regexp that should be excluded from being considered containing
  487. # source files. Don't modify this list from a presubmit script!
  488. DEFAULT_FILES_TO_SKIP = (
  489. r'testing_support[\\\/]google_appengine[\\\/].*',
  490. r'.*\bexperimental[\\\/].*',
  491. # Exclude third_party/.* but NOT third_party/{WebKit,blink}
  492. # (crbug.com/539768 and crbug.com/836555).
  493. r'.*\bthird_party[\\\/](?!(WebKit|blink)[\\\/]).*',
  494. # Output directories (just in case)
  495. r'.*\bDebug[\\\/].*',
  496. r'.*\bRelease[\\\/].*',
  497. r'.*\bxcodebuild[\\\/].*',
  498. r'.*\bout[\\\/].*',
  499. # All caps files like README and LICENCE.
  500. r'.*\b[A-Z0-9_]{2,}$',
  501. # SCM (can happen in dual SCM configuration). (Slightly over aggressive)
  502. r'(|.*[\\\/])\.git[\\\/].*',
  503. r'(|.*[\\\/])\.svn[\\\/].*',
  504. # There is no point in processing a patch file.
  505. r'.+\.diff$',
  506. r'.+\.patch$',
  507. )
  508. def __init__(self,
  509. change,
  510. presubmit_path,
  511. is_committing,
  512. verbose,
  513. gerrit_obj,
  514. dry_run=None,
  515. thread_pool=None,
  516. parallel=False,
  517. no_diffs=False):
  518. """Builds an InputApi object.
  519. Args:
  520. change: A presubmit.Change object.
  521. presubmit_path: The path to the presubmit script being processed.
  522. is_committing: True if the change is about to be committed.
  523. gerrit_obj: provides basic Gerrit codereview functionality.
  524. dry_run: if true, some Checks will be skipped.
  525. parallel: if true, all tests reported via input_api.RunTests for all
  526. PRESUBMIT files will be run in parallel.
  527. no_diffs: if true, implies that --files or --all was specified so some
  528. checks can be skipped, and some errors will be messages.
  529. """
  530. # Version number of the presubmit_support script.
  531. self.version = [int(x) for x in __version__.split('.')]
  532. self.change = change
  533. self.is_committing = is_committing
  534. self.gerrit = gerrit_obj
  535. self.dry_run = dry_run
  536. self.no_diffs = no_diffs
  537. self.parallel = parallel
  538. self.thread_pool = thread_pool or ThreadPool()
  539. # We expose various modules and functions as attributes of the input_api
  540. # so that presubmit scripts don't have to import them.
  541. self.ast = ast
  542. self.basename = os.path.basename
  543. self.cpplint = cpplint
  544. self.fnmatch = fnmatch
  545. self.gclient_paths = gclient_paths
  546. self.glob = glob.glob
  547. self.json = json
  548. self.logging = logging.getLogger('PRESUBMIT')
  549. self.os_listdir = os.listdir
  550. self.os_path = os.path
  551. self.os_stat = os.stat
  552. self.os_walk = os.walk
  553. self.re = re
  554. self.subprocess = subprocess
  555. self.sys = sys
  556. self.tempfile = tempfile
  557. self.time = time
  558. self.unittest = unittest
  559. self.urllib_request = urllib_request
  560. self.urllib_error = urllib_error
  561. self.is_windows = sys.platform == 'win32'
  562. # Set python_executable to 'vpython3' in order to allow scripts in other
  563. # repos (e.g. src.git) to automatically pick up that repo's .vpython
  564. # file, instead of inheriting the one in depot_tools.
  565. self.python_executable = 'vpython3'
  566. # Offer a python 3 executable for use during the migration off of python
  567. # 2.
  568. self.python3_executable = 'vpython3'
  569. self.environ = os.environ
  570. # InputApi.platform is the platform you're currently running on.
  571. self.platform = sys.platform
  572. self.cpu_count = multiprocessing.cpu_count()
  573. if self.is_windows:
  574. # TODO(crbug.com/1190269) - we can't use more than 56 child
  575. # processes on Windows or Python3 may hang.
  576. self.cpu_count = min(self.cpu_count, 56)
  577. # The local path of the currently-being-processed presubmit script.
  578. self._current_presubmit_path = os.path.dirname(presubmit_path)
  579. # We carry the canned checks so presubmit scripts can easily use them.
  580. self.canned_checks = presubmit_canned_checks
  581. # Temporary files we must manually remove at the end of a run.
  582. self._named_temporary_files = []
  583. self.owners_client = None
  584. if self.gerrit and not 'PRESUBMIT_SKIP_NETWORK' in self.environ:
  585. try:
  586. self.owners_client = owners_client.GetCodeOwnersClient(
  587. host=self.gerrit.host,
  588. project=self.gerrit.project,
  589. branch=self.gerrit.branch)
  590. except Exception as e:
  591. print('Failed to set owners_client - %s' % str(e))
  592. self.owners_finder = owners_finder.OwnersFinder
  593. self.verbose = verbose
  594. self.Command = CommandData
  595. # Replace <hash_map> and <hash_set> as headers that need to be included
  596. # with 'base/containers/hash_tables.h' instead.
  597. # Access to a protected member _XX of a client class
  598. # pylint: disable=protected-access
  599. self.cpplint._re_pattern_templates = [
  600. (a, b,
  601. 'base/containers/hash_tables.h') if header in ('<hash_map>',
  602. '<hash_set>') else
  603. (a, b, header) for (a, b, header) in cpplint._re_pattern_templates
  604. ]
  605. def SetTimeout(self, timeout):
  606. self.thread_pool.timeout = timeout
  607. def PresubmitLocalPath(self):
  608. """Returns the local path of the presubmit script currently being run.
  609. This is useful if you don't want to hard-code absolute paths in the
  610. presubmit script. For example, It can be used to find another file
  611. relative to the PRESUBMIT.py script, so the whole tree can be branched and
  612. the presubmit script still works, without editing its content.
  613. """
  614. return self._current_presubmit_path
  615. def AffectedFiles(self, include_deletes=True, file_filter=None):
  616. """Same as input_api.change.AffectedFiles() except only lists files
  617. (and optionally directories) in the same directory as the current presubmit
  618. script, or subdirectories thereof. Note that files are listed using the OS
  619. path separator, so backslashes are used as separators on Windows.
  620. """
  621. dir_with_slash = normpath(self.PresubmitLocalPath())
  622. # normpath strips trailing path separators, so the trailing separator
  623. # has to be added after the normpath call.
  624. if len(dir_with_slash) > 0:
  625. dir_with_slash += os.path.sep
  626. return list(
  627. filter(
  628. lambda x: normpath(x.AbsoluteLocalPath()).startswith(
  629. dir_with_slash),
  630. self.change.AffectedFiles(include_deletes, file_filter)))
  631. def LocalPaths(self):
  632. """Returns local paths of input_api.AffectedFiles()."""
  633. paths = [af.LocalPath() for af in self.AffectedFiles()]
  634. logging.debug('LocalPaths: %s', paths)
  635. return paths
  636. def AbsoluteLocalPaths(self):
  637. """Returns absolute local paths of input_api.AffectedFiles()."""
  638. return [af.AbsoluteLocalPath() for af in self.AffectedFiles()]
  639. def AffectedTestableFiles(self, include_deletes=None, **kwargs):
  640. """Same as input_api.change.AffectedTestableFiles() except only lists files
  641. in the same directory as the current presubmit script, or subdirectories
  642. thereof.
  643. """
  644. if include_deletes is not None:
  645. warn('AffectedTestableFiles(include_deletes=%s)'
  646. ' is deprecated and ignored' % str(include_deletes),
  647. category=DeprecationWarning,
  648. stacklevel=2)
  649. # pylint: disable=consider-using-generator
  650. return [
  651. x for x in self.AffectedFiles(include_deletes=False, **kwargs)
  652. if x.IsTestableFile()
  653. ]
  654. def AffectedTextFiles(self, include_deletes=None):
  655. """An alias to AffectedTestableFiles for backwards compatibility."""
  656. return self.AffectedTestableFiles(include_deletes=include_deletes)
  657. def FilterSourceFile(self,
  658. affected_file,
  659. files_to_check=None,
  660. files_to_skip=None,
  661. allow_list=None,
  662. block_list=None):
  663. """Filters out files that aren't considered 'source file'.
  664. If files_to_check or files_to_skip is None, InputApi.DEFAULT_FILES_TO_CHECK
  665. and InputApi.DEFAULT_FILES_TO_SKIP is used respectively.
  666. affected_file.LocalPath() needs to re.match an entry in the files_to_check
  667. list and not re.match any entries in the files_to_skip list.
  668. '/' path separators should be used in the regular expressions and will work
  669. on Windows as well as other platforms.
  670. Note: Copy-paste this function to suit your needs or use a lambda function.
  671. """
  672. if files_to_check is None:
  673. files_to_check = self.DEFAULT_FILES_TO_CHECK
  674. if files_to_skip is None:
  675. files_to_skip = self.DEFAULT_FILES_TO_SKIP
  676. def Find(affected_file, items):
  677. local_path = affected_file.LocalPath()
  678. for item in items:
  679. if self.re.match(item, local_path):
  680. return True
  681. # Handle the cases where the files regex only handles /, but the
  682. # local path uses \.
  683. if self.is_windows and self.re.match(
  684. item, local_path.replace('\\', '/')):
  685. return True
  686. return False
  687. return (Find(affected_file, files_to_check)
  688. and not Find(affected_file, files_to_skip))
  689. def AffectedSourceFiles(self, source_file):
  690. """Filter the list of AffectedTestableFiles by the function source_file.
  691. If source_file is None, InputApi.FilterSourceFile() is used.
  692. """
  693. if not source_file:
  694. source_file = self.FilterSourceFile
  695. return list(filter(source_file, self.AffectedTestableFiles()))
  696. def RightHandSideLines(self, source_file_filter=None):
  697. """An iterator over all text lines in 'new' version of changed files.
  698. Only lists lines from new or modified text files in the change that are
  699. contained by the directory of the currently executing presubmit script.
  700. This is useful for doing line-by-line regex checks, like checking for
  701. trailing whitespace.
  702. Yields:
  703. a 3 tuple:
  704. the AffectedFile instance of the current file;
  705. integer line number (1-based); and
  706. the contents of the line as a string.
  707. Note: The carriage return (LF or CR) is stripped off.
  708. """
  709. files = self.AffectedSourceFiles(source_file_filter)
  710. return _RightHandSideLinesImpl(files)
  711. def ReadFile(self, file_item, mode='r'):
  712. """Reads an arbitrary file.
  713. Deny reading anything outside the repository.
  714. """
  715. if isinstance(file_item, AffectedFile):
  716. file_item = file_item.AbsoluteLocalPath()
  717. if not file_item.startswith(self.change.RepositoryRoot()):
  718. raise IOError('Access outside the repository root is denied.')
  719. return gclient_utils.FileRead(file_item, mode)
  720. def CreateTemporaryFile(self, **kwargs):
  721. """Returns a named temporary file that must be removed with a call to
  722. RemoveTemporaryFiles().
  723. All keyword arguments are forwarded to tempfile.NamedTemporaryFile(),
  724. except for |delete|, which is always set to False.
  725. Presubmit checks that need to create a temporary file and pass it for
  726. reading should use this function instead of NamedTemporaryFile(), as
  727. Windows fails to open a file that is already open for writing.
  728. with input_api.CreateTemporaryFile() as f:
  729. f.write('xyz')
  730. input_api.subprocess.check_output(['script-that', '--reads-from',
  731. f.name])
  732. Note that callers of CreateTemporaryFile() should not worry about removing
  733. any temporary file; this is done transparently by the presubmit handling
  734. code.
  735. """
  736. if 'delete' in kwargs:
  737. # Prevent users from passing |delete|; we take care of file deletion
  738. # ourselves and this prevents unintuitive error messages when we
  739. # pass delete=False and 'delete' is also in kwargs.
  740. raise TypeError(
  741. 'CreateTemporaryFile() does not take a "delete" '
  742. 'argument, file deletion is handled automatically by '
  743. 'the same presubmit_support code that creates InputApi '
  744. 'objects.')
  745. temp_file = self.tempfile.NamedTemporaryFile(delete=False, **kwargs)
  746. self._named_temporary_files.append(temp_file.name)
  747. return temp_file
  748. @property
  749. def tbr(self):
  750. """Returns if a change is TBR'ed."""
  751. return 'TBR' in self.change.tags or self.change.TBRsFromDescription()
  752. def RunTests(self, tests_mix, parallel=True):
  753. tests = []
  754. msgs = []
  755. for t in tests_mix:
  756. if isinstance(t, OutputApi.PresubmitResult) and t:
  757. msgs.append(t)
  758. else:
  759. assert issubclass(t.message, _PresubmitResult)
  760. tests.append(t)
  761. if self.verbose:
  762. t.info = _PresubmitNotifyResult
  763. if not t.kwargs.get('cwd'):
  764. t.kwargs['cwd'] = self.PresubmitLocalPath()
  765. self.thread_pool.AddTests(tests, parallel)
  766. # When self.parallel is True (i.e. --parallel is passed as an option)
  767. # RunTests doesn't actually run tests. It adds them to a ThreadPool that
  768. # will run all tests once all PRESUBMIT files are processed.
  769. # Otherwise, it will run them and return the results.
  770. if not self.parallel:
  771. msgs.extend(self.thread_pool.RunAsync())
  772. return msgs
  773. class _DiffCache(object):
  774. """Caches diffs retrieved from a particular SCM."""
  775. def __init__(self, upstream=None):
  776. """Stores the upstream revision against which all diffs will be computed."""
  777. self._upstream = upstream
  778. def GetDiff(self, path, local_root):
  779. """Get the diff for a particular path."""
  780. raise NotImplementedError()
  781. def GetOldContents(self, path, local_root):
  782. """Get the old version for a particular path."""
  783. raise NotImplementedError()
  784. class _GitDiffCache(_DiffCache):
  785. """DiffCache implementation for git; gets all file diffs at once."""
  786. def __init__(self, upstream):
  787. super(_GitDiffCache, self).__init__(upstream=upstream)
  788. self._diffs_by_file = None
  789. def GetDiff(self, path, local_root):
  790. # Compare against None to distinguish between None and an initialized
  791. # but empty dictionary.
  792. if self._diffs_by_file == None:
  793. # Compute a single diff for all files and parse the output; should
  794. # with git this is much faster than computing one diff for each
  795. # file.
  796. diffs = {}
  797. # Don't specify any filenames below, because there are command line
  798. # length limits on some platforms and GenerateDiff would fail.
  799. unified_diff = scm.GIT.GenerateDiff(local_root,
  800. files=[],
  801. full_move=True,
  802. branch=self._upstream)
  803. # This regex matches the path twice, separated by a space. Note that
  804. # filename itself may contain spaces.
  805. file_marker = re.compile(
  806. '^diff --git (?P<filename>.*) (?P=filename)$')
  807. current_diff = []
  808. keep_line_endings = True
  809. for x in unified_diff.splitlines(keep_line_endings):
  810. match = file_marker.match(x)
  811. if match:
  812. # Marks the start of a new per-file section.
  813. diffs[match.group('filename')] = current_diff = [x]
  814. elif x.startswith('diff --git'):
  815. raise PresubmitFailure('Unexpected diff line: %s' % x)
  816. else:
  817. current_diff.append(x)
  818. self._diffs_by_file = dict(
  819. (normpath(path), ''.join(diff)) for path, diff in diffs.items())
  820. if path not in self._diffs_by_file:
  821. # SCM didn't have any diff on this file. It could be that the file
  822. # was not modified at all (e.g. user used --all flag in git cl
  823. # presubmit). Intead of failing, return empty string. See:
  824. # https://crbug.com/808346.
  825. return ''
  826. return self._diffs_by_file[path]
  827. def GetOldContents(self, path, local_root):
  828. return scm.GIT.GetOldContents(local_root, path, branch=self._upstream)
  829. class AffectedFile(object):
  830. """Representation of a file in a change."""
  831. DIFF_CACHE = _DiffCache
  832. # Method could be a function
  833. # pylint: disable=no-self-use
  834. def __init__(self, path, action, repository_root, diff_cache):
  835. self._path = path
  836. self._action = action
  837. self._local_root = repository_root
  838. self._is_directory = None
  839. self._cached_changed_contents = None
  840. self._cached_new_contents = None
  841. self._diff_cache = diff_cache
  842. logging.debug('%s(%s)', self.__class__.__name__, self._path)
  843. def LocalPath(self):
  844. """Returns the path of this file on the local disk relative to client root.
  845. This should be used for error messages but not for accessing files,
  846. because presubmit checks are run with CWD=PresubmitLocalPath() (which is
  847. often != client root).
  848. """
  849. return normpath(self._path)
  850. def AbsoluteLocalPath(self):
  851. """Returns the absolute path of this file on the local disk."""
  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
  1301. 'git cl upload' is.
  1302. gerrit_obj: provides basic Gerrit codereview functionality.
  1303. dry_run: if true, some Checks will be skipped.
  1304. parallel: if true, all tests reported via input_api.RunTests for all
  1305. PRESUBMIT files will be run in parallel.
  1306. no_diffs: if true, implies that --files or --all was specified so some
  1307. checks can be skipped, and some errors will be messages.
  1308. """
  1309. self.change = change
  1310. self.committing = committing
  1311. self.gerrit = gerrit_obj
  1312. self.verbose = verbose
  1313. self.dry_run = dry_run
  1314. self.more_cc = []
  1315. self.thread_pool = thread_pool
  1316. self.parallel = parallel
  1317. self.no_diffs = no_diffs
  1318. def ExecPresubmitScript(self, script_text, presubmit_path):
  1319. """Executes a single presubmit script.
  1320. Caller is responsible for validating whether the hook should be executed
  1321. and should only call this function if it should be.
  1322. Args:
  1323. script_text: The text of the presubmit script.
  1324. presubmit_path: The path to the presubmit file (this will be
  1325. reported via input_api.PresubmitLocalPath()).
  1326. Return:
  1327. A list of result objects, empty if no problems.
  1328. """
  1329. # Change to the presubmit file's directory to support local imports.
  1330. presubmit_dir = os.path.dirname(presubmit_path)
  1331. main_path = os.getcwd()
  1332. try:
  1333. os.chdir(presubmit_dir)
  1334. return self._execute_with_local_working_directory(
  1335. script_text, presubmit_dir, presubmit_path)
  1336. finally:
  1337. # Return the process to the original working directory.
  1338. os.chdir(main_path)
  1339. def _execute_with_local_working_directory(self, script_text, presubmit_dir,
  1340. presubmit_path):
  1341. # Load the presubmit script into context.
  1342. input_api = InputApi(self.change,
  1343. presubmit_path,
  1344. self.committing,
  1345. self.verbose,
  1346. gerrit_obj=self.gerrit,
  1347. dry_run=self.dry_run,
  1348. thread_pool=self.thread_pool,
  1349. parallel=self.parallel,
  1350. no_diffs=self.no_diffs)
  1351. output_api = OutputApi(self.committing)
  1352. context = {}
  1353. try:
  1354. exec(
  1355. compile(script_text, presubmit_path, 'exec', dont_inherit=True),
  1356. context)
  1357. except Exception as e:
  1358. raise PresubmitFailure('"%s" had an exception.\n%s' %
  1359. (presubmit_path, e))
  1360. context['__args'] = (input_api, output_api)
  1361. # Get path of presubmit directory relative to repository root.
  1362. # Always use forward slashes, so that path is same in *nix and Windows
  1363. root = input_api.change.RepositoryRoot()
  1364. rel_path = os.path.relpath(presubmit_dir, root)
  1365. rel_path = rel_path.replace(os.path.sep, '/')
  1366. # Get the URL of git remote origin and use it to identify host and
  1367. # project
  1368. host = project = ''
  1369. if self.gerrit:
  1370. host = self.gerrit.host or ''
  1371. project = self.gerrit.project or ''
  1372. # Prefix for test names
  1373. prefix = 'presubmit:%s/%s:%s/' % (host, project, rel_path)
  1374. # Perform all the desired presubmit checks.
  1375. results = []
  1376. try:
  1377. version = [
  1378. int(x)
  1379. for x in context.get('PRESUBMIT_VERSION', '0.0.0').split('.')
  1380. ]
  1381. with rdb_wrapper.client(prefix) as sink:
  1382. if version >= [2, 0, 0]:
  1383. # Copy the keys to prevent "dictionary changed size during
  1384. # iteration" exception if checks add globals to context.
  1385. # E.g. sometimes the Python runtime will add
  1386. # __warningregistry__.
  1387. for function_name in list(context.keys()):
  1388. if not function_name.startswith('Check'):
  1389. continue
  1390. if function_name.endswith(
  1391. 'Commit') and not self.committing:
  1392. continue
  1393. if function_name.endswith('Upload') and self.committing:
  1394. continue
  1395. logging.debug('Running %s in %s', function_name,
  1396. presubmit_path)
  1397. results.extend(
  1398. self._run_check_function(function_name, context,
  1399. sink, presubmit_path))
  1400. logging.debug('Running %s done.', function_name)
  1401. self.more_cc.extend(output_api.more_cc)
  1402. # Clear the CC list between running each presubmit check
  1403. # to prevent CCs from being repeatedly appended.
  1404. output_api.more_cc = []
  1405. else: # Old format
  1406. if self.committing:
  1407. function_name = 'CheckChangeOnCommit'
  1408. else:
  1409. function_name = 'CheckChangeOnUpload'
  1410. if function_name in list(context.keys()):
  1411. logging.debug('Running %s in %s', function_name,
  1412. presubmit_path)
  1413. results.extend(
  1414. self._run_check_function(function_name, context,
  1415. sink, presubmit_path))
  1416. logging.debug('Running %s done.', function_name)
  1417. self.more_cc.extend(output_api.more_cc)
  1418. # Clear the CC list between running each presubmit check
  1419. # to prevent CCs from being repeatedly appended.
  1420. output_api.more_cc = []
  1421. finally:
  1422. for f in input_api._named_temporary_files:
  1423. os.remove(f)
  1424. self.more_cc = sorted(set(self.more_cc))
  1425. return results
  1426. def _run_check_function(self, function_name, context, sink, presubmit_path):
  1427. """Evaluates and returns the result of a given presubmit function.
  1428. If sink is given, the result of the presubmit function will be reported
  1429. to the ResultSink.
  1430. Args:
  1431. function_name: the name of the presubmit function to evaluate
  1432. context: a context dictionary in which the function will be evaluated
  1433. sink: an instance of ResultSink. None, by default.
  1434. Returns:
  1435. the result of the presubmit function call.
  1436. """
  1437. start_time = time_time()
  1438. try:
  1439. result = eval(function_name + '(*__args)', context)
  1440. self._check_result_type(result)
  1441. except Exception:
  1442. _, e_value, _ = sys.exc_info()
  1443. result = [
  1444. OutputApi.PresubmitError(
  1445. 'Evaluation of %s failed: %s, %s' %
  1446. (function_name, e_value, traceback.format_exc()))
  1447. ]
  1448. elapsed_time = time_time() - start_time
  1449. if elapsed_time > 10.0:
  1450. sys.stdout.write('%6.1fs to run %s from %s.\n' %
  1451. (elapsed_time, function_name, presubmit_path))
  1452. if sink:
  1453. status, failure_reason = RDBStatusFrom(result)
  1454. sink.report(function_name, status, elapsed_time, failure_reason)
  1455. return result
  1456. def _check_result_type(self, result):
  1457. """Helper function which ensures result is a list, and all elements are
  1458. instances of OutputApi.PresubmitResult"""
  1459. if not isinstance(result, (tuple, list)):
  1460. raise PresubmitFailure(
  1461. 'Presubmit functions must return a tuple or list')
  1462. if not all(
  1463. isinstance(res, OutputApi.PresubmitResult) for res in result):
  1464. raise PresubmitFailure(
  1465. 'All presubmit results must be of types derived from '
  1466. 'output_api.PresubmitResult')
  1467. def RDBStatusFrom(result):
  1468. """Returns the status and failure reason for a PresubmitResult."""
  1469. failure_reason = None
  1470. status = rdb_wrapper.STATUS_PASS
  1471. if any(r.fatal for r in result):
  1472. status = rdb_wrapper.STATUS_FAIL
  1473. failure_reasons = []
  1474. for r in result:
  1475. fields = r.json_format()
  1476. message = fields['message']
  1477. items = '\n'.join(' %s' % item for item in fields['items'])
  1478. failure_reasons.append('\n'.join([message, items]))
  1479. if failure_reasons:
  1480. failure_reason = '\n'.join(failure_reasons)
  1481. return status, failure_reason
  1482. def DoPresubmitChecks(change,
  1483. committing,
  1484. verbose,
  1485. default_presubmit,
  1486. may_prompt,
  1487. gerrit_obj,
  1488. dry_run=None,
  1489. parallel=False,
  1490. json_output=None,
  1491. no_diffs=False):
  1492. """Runs all presubmit checks that apply to the files in the change.
  1493. This finds all PRESUBMIT.py files in directories enclosing the files in the
  1494. change (up to the repository root) and calls the relevant entrypoint function
  1495. depending on whether the change is being committed or uploaded.
  1496. Prints errors, warnings and notifications. Prompts the user for warnings
  1497. when needed.
  1498. Args:
  1499. change: The Change object.
  1500. committing: True if 'git cl land' is running, False if 'git cl upload' is.
  1501. verbose: Prints debug info.
  1502. default_presubmit: A default presubmit script to execute in any case.
  1503. may_prompt: Enable (y/n) questions on warning or error. If False,
  1504. any questions are answered with yes by default.
  1505. gerrit_obj: provides basic Gerrit codereview functionality.
  1506. dry_run: if true, some Checks will be skipped.
  1507. parallel: if true, all tests specified by input_api.RunTests in all
  1508. PRESUBMIT files will be run in parallel.
  1509. no_diffs: if true, implies that --files or --all was specified so some
  1510. checks can be skipped, and some errors will be messages.
  1511. Return:
  1512. 1 if presubmit checks failed or 0 otherwise.
  1513. """
  1514. with setup_environ({'PYTHONDONTWRITEBYTECODE': '1'}):
  1515. python_version = 'Python %s' % sys.version_info.major
  1516. if committing:
  1517. sys.stdout.write('Running %s presubmit commit checks ...\n' %
  1518. python_version)
  1519. else:
  1520. sys.stdout.write('Running %s presubmit upload checks ...\n' %
  1521. python_version)
  1522. start_time = time_time()
  1523. presubmit_files = ListRelevantPresubmitFiles(
  1524. change.AbsoluteLocalPaths(), change.RepositoryRoot())
  1525. if not presubmit_files and verbose:
  1526. sys.stdout.write('Warning, no PRESUBMIT.py found.\n')
  1527. results = []
  1528. thread_pool = ThreadPool()
  1529. executer = PresubmitExecuter(change, committing, verbose, gerrit_obj,
  1530. dry_run, thread_pool, parallel, no_diffs)
  1531. if default_presubmit:
  1532. if verbose:
  1533. sys.stdout.write('Running default presubmit script.\n')
  1534. fake_path = os.path.join(change.RepositoryRoot(), 'PRESUBMIT.py')
  1535. results += executer.ExecPresubmitScript(default_presubmit,
  1536. fake_path)
  1537. for filename in presubmit_files:
  1538. filename = os.path.abspath(filename)
  1539. # Accept CRLF presubmit script.
  1540. presubmit_script = gclient_utils.FileRead(filename).replace(
  1541. '\r\n', '\n')
  1542. if verbose:
  1543. sys.stdout.write('Running %s\n' % filename)
  1544. results += executer.ExecPresubmitScript(presubmit_script, filename)
  1545. results += thread_pool.RunAsync()
  1546. messages = {}
  1547. should_prompt = False
  1548. presubmits_failed = False
  1549. for result in results:
  1550. if result.fatal:
  1551. presubmits_failed = True
  1552. messages.setdefault('ERRORS', []).append(result)
  1553. elif result.should_prompt:
  1554. should_prompt = True
  1555. messages.setdefault('Warnings', []).append(result)
  1556. else:
  1557. messages.setdefault('Messages', []).append(result)
  1558. # Print the different message types in a consistent order. ERRORS go
  1559. # last so that they will be most visible in the local-presubmit output.
  1560. for name in ['Messages', 'Warnings', 'ERRORS']:
  1561. if name in messages:
  1562. items = messages[name]
  1563. sys.stdout.write('** Presubmit %s: %d **\n' %
  1564. (name, len(items)))
  1565. for item in items:
  1566. item.handle()
  1567. sys.stdout.write('\n')
  1568. total_time = time_time() - start_time
  1569. if total_time > 1.0:
  1570. sys.stdout.write('Presubmit checks took %.1fs to calculate.\n' %
  1571. total_time)
  1572. if not should_prompt and not presubmits_failed:
  1573. sys.stdout.write('%s presubmit checks passed.\n\n' % python_version)
  1574. elif should_prompt and not presubmits_failed:
  1575. sys.stdout.write('There were %s presubmit warnings. ' %
  1576. python_version)
  1577. if may_prompt:
  1578. presubmits_failed = not prompt_should_continue(
  1579. 'Are you sure you wish to continue? (y/N): ')
  1580. else:
  1581. sys.stdout.write('\n')
  1582. else:
  1583. sys.stdout.write('There were %s presubmit errors.\n' %
  1584. python_version)
  1585. if json_output:
  1586. # Write the presubmit results to json output
  1587. presubmit_results = {
  1588. 'errors':
  1589. [error.json_format() for error in messages.get('ERRORS', [])],
  1590. 'notifications': [
  1591. notification.json_format()
  1592. for notification in messages.get('Messages', [])
  1593. ],
  1594. 'warnings': [
  1595. warning.json_format()
  1596. for warning in messages.get('Warnings', [])
  1597. ],
  1598. 'more_cc':
  1599. executer.more_cc,
  1600. }
  1601. gclient_utils.FileWrite(
  1602. json_output, json.dumps(presubmit_results, sort_keys=True))
  1603. global _ASKED_FOR_FEEDBACK
  1604. # Ask for feedback one time out of 5.
  1605. if (results and random.randint(0, 4) == 0 and not _ASKED_FOR_FEEDBACK):
  1606. sys.stdout.write(
  1607. 'Was the presubmit check useful? If not, run "git cl presubmit -v"\n'
  1608. 'to figure out which PRESUBMIT.py was run, then run git blame\n'
  1609. 'on the file to figure out who to ask for help.\n')
  1610. _ASKED_FOR_FEEDBACK = True
  1611. return 1 if presubmits_failed else 0
  1612. def _scan_sub_dirs(mask, recursive):
  1613. if not recursive:
  1614. return [x for x in glob.glob(mask) if x not in ('.svn', '.git')]
  1615. results = []
  1616. for root, dirs, files in os.walk('.'):
  1617. if '.svn' in dirs:
  1618. dirs.remove('.svn')
  1619. if '.git' in dirs:
  1620. dirs.remove('.git')
  1621. for name in files:
  1622. if fnmatch.fnmatch(name, mask):
  1623. results.append(os.path.join(root, name))
  1624. return results
  1625. def _parse_files(args, recursive):
  1626. logging.debug('Searching for %s', args)
  1627. files = []
  1628. for arg in args:
  1629. files.extend([('M', f) for f in _scan_sub_dirs(arg, recursive)])
  1630. return files
  1631. def _parse_change(parser, options):
  1632. """Process change options.
  1633. Args:
  1634. parser: The parser used to parse the arguments from command line.
  1635. options: The arguments parsed from command line.
  1636. Returns:
  1637. A GitChange if the change root is a git repository, or a Change otherwise.
  1638. """
  1639. if options.files and options.all_files:
  1640. parser.error('<files> cannot be specified when --all-files is set.')
  1641. change_scm = scm.determine_scm(options.root)
  1642. if change_scm != 'git' and not options.files:
  1643. parser.error('<files> is not optional for unversioned directories.')
  1644. if options.files:
  1645. if options.source_controlled_only:
  1646. # Get the filtered set of files from SCM.
  1647. change_files = []
  1648. for name in scm.GIT.GetAllFiles(options.root):
  1649. for mask in options.files:
  1650. if fnmatch.fnmatch(name, mask):
  1651. change_files.append(('M', name))
  1652. break
  1653. else:
  1654. # Get the filtered set of files from a directory scan.
  1655. change_files = _parse_files(options.files, options.recursive)
  1656. elif options.all_files:
  1657. change_files = [('M', f) for f in scm.GIT.GetAllFiles(options.root)]
  1658. else:
  1659. change_files = scm.GIT.CaptureStatus(options.root, options.upstream
  1660. or None)
  1661. logging.info('Found %d file(s).', len(change_files))
  1662. change_class = GitChange if change_scm == 'git' else Change
  1663. return change_class(options.name,
  1664. options.description,
  1665. options.root,
  1666. change_files,
  1667. options.issue,
  1668. options.patchset,
  1669. options.author,
  1670. upstream=options.upstream)
  1671. def _parse_gerrit_options(parser, options):
  1672. """Process gerrit options.
  1673. SIDE EFFECTS: Modifies options.author and options.description from Gerrit if
  1674. options.gerrit_fetch is set.
  1675. Args:
  1676. parser: The parser used to parse the arguments from command line.
  1677. options: The arguments parsed from command line.
  1678. Returns:
  1679. A GerritAccessor object if options.gerrit_url is set, or None otherwise.
  1680. """
  1681. gerrit_obj = None
  1682. if options.gerrit_url:
  1683. gerrit_obj = GerritAccessor(url=options.gerrit_url,
  1684. project=options.gerrit_project,
  1685. branch=options.gerrit_branch)
  1686. if not options.gerrit_fetch:
  1687. return gerrit_obj
  1688. if not options.gerrit_url or not options.issue or not options.patchset:
  1689. parser.error(
  1690. '--gerrit_fetch requires --gerrit_url, --issue and --patchset.')
  1691. options.author = gerrit_obj.GetChangeOwner(options.issue)
  1692. options.description = gerrit_obj.GetChangeDescription(
  1693. options.issue, options.patchset)
  1694. logging.info('Got author: "%s"', options.author)
  1695. logging.info('Got description: """\n%s\n"""', options.description)
  1696. return gerrit_obj
  1697. @contextlib.contextmanager
  1698. def setup_environ(kv: Mapping[str, str]):
  1699. """Update environment while in context, and reset back to original on exit.
  1700. Example usage:
  1701. with setup_environ({"key": "value"}):
  1702. # os.environ now has key set to value.
  1703. pass
  1704. """
  1705. old_kv = {}
  1706. for k, v in kv.items():
  1707. old_kv[k] = os.environ.get(k, None)
  1708. os.environ[k] = v
  1709. yield
  1710. for k, v in old_kv.items():
  1711. if v:
  1712. os.environ[k] = v
  1713. else:
  1714. os.environ.pop(k, None)
  1715. @contextlib.contextmanager
  1716. def canned_check_filter(method_names):
  1717. filtered = {}
  1718. try:
  1719. for method_name in method_names:
  1720. if not hasattr(presubmit_canned_checks, method_name):
  1721. logging.warning('Skipping unknown "canned" check %s' %
  1722. method_name)
  1723. continue
  1724. filtered[method_name] = getattr(presubmit_canned_checks,
  1725. method_name)
  1726. setattr(presubmit_canned_checks, method_name, lambda *_a, **_kw: [])
  1727. yield
  1728. finally:
  1729. for name, method in filtered.items():
  1730. setattr(presubmit_canned_checks, name, method)
  1731. def main(argv=None):
  1732. parser = argparse.ArgumentParser(usage='%(prog)s [options] <files...>')
  1733. hooks = parser.add_mutually_exclusive_group()
  1734. hooks.add_argument('-c',
  1735. '--commit',
  1736. action='store_true',
  1737. help='Use commit instead of upload checks.')
  1738. hooks.add_argument('-u',
  1739. '--upload',
  1740. action='store_false',
  1741. dest='commit',
  1742. help='Use upload instead of commit checks.')
  1743. hooks.add_argument('--post_upload',
  1744. action='store_true',
  1745. help='Run post-upload commit hooks.')
  1746. parser.add_argument('-r',
  1747. '--recursive',
  1748. action='store_true',
  1749. help='Act recursively.')
  1750. parser.add_argument('-v',
  1751. '--verbose',
  1752. action='count',
  1753. default=0,
  1754. help='Use 2 times for more debug info.')
  1755. parser.add_argument('--name', default='no name')
  1756. parser.add_argument('--author')
  1757. desc = parser.add_mutually_exclusive_group()
  1758. desc.add_argument('--description',
  1759. default='',
  1760. help='The change description.')
  1761. desc.add_argument('--description_file',
  1762. help='File to read change description from.')
  1763. parser.add_argument('--issue', type=int, default=0)
  1764. parser.add_argument('--patchset', type=int, default=0)
  1765. parser.add_argument('--root',
  1766. default=os.getcwd(),
  1767. help='Search for PRESUBMIT.py up to this directory. '
  1768. 'If inherit-review-settings-ok is present in this '
  1769. 'directory, parent directories up to the root file '
  1770. 'system directories will also be searched.')
  1771. parser.add_argument(
  1772. '--upstream',
  1773. help='Git only: the base ref or upstream branch against '
  1774. 'which the diff should be computed.')
  1775. parser.add_argument('--default_presubmit')
  1776. parser.add_argument('--may_prompt', action='store_true', default=False)
  1777. parser.add_argument(
  1778. '--skip_canned',
  1779. action='append',
  1780. default=[],
  1781. help='A list of checks to skip which appear in '
  1782. 'presubmit_canned_checks. Can be provided multiple times '
  1783. 'to skip multiple canned checks.')
  1784. parser.add_argument('--dry_run',
  1785. action='store_true',
  1786. help=argparse.SUPPRESS)
  1787. parser.add_argument('--gerrit_url', help=argparse.SUPPRESS)
  1788. parser.add_argument('--gerrit_project', help=argparse.SUPPRESS)
  1789. parser.add_argument('--gerrit_branch', help=argparse.SUPPRESS)
  1790. parser.add_argument('--gerrit_fetch',
  1791. action='store_true',
  1792. help=argparse.SUPPRESS)
  1793. parser.add_argument('--parallel',
  1794. action='store_true',
  1795. help='Run all tests specified by input_api.RunTests in '
  1796. 'all PRESUBMIT files in parallel.')
  1797. parser.add_argument('--json_output',
  1798. help='Write presubmit errors to json output.')
  1799. parser.add_argument('--all_files',
  1800. action='store_true',
  1801. help='Mark all files under source control as modified.')
  1802. parser.add_argument('files',
  1803. nargs='*',
  1804. help='List of files to be marked as modified when '
  1805. 'executing presubmit or post-upload hooks. fnmatch '
  1806. 'wildcards can also be used.')
  1807. parser.add_argument('--source_controlled_only',
  1808. action='store_true',
  1809. help='Constrain \'files\' to those in source control.')
  1810. parser.add_argument('--no_diffs',
  1811. action='store_true',
  1812. help='Assume that all "modified" files have no diffs.')
  1813. options = parser.parse_args(argv)
  1814. log_level = logging.ERROR
  1815. if options.verbose >= 2:
  1816. log_level = logging.DEBUG
  1817. elif options.verbose:
  1818. log_level = logging.INFO
  1819. log_format = ('[%(levelname).1s%(asctime)s %(process)d %(thread)d '
  1820. '%(filename)s] %(message)s')
  1821. logging.basicConfig(format=log_format, level=log_level)
  1822. # Print call stacks when _PresubmitResult objects are created with -v -v is
  1823. # specified. This helps track down where presubmit messages are coming from.
  1824. if options.verbose >= 2:
  1825. global _SHOW_CALLSTACKS
  1826. _SHOW_CALLSTACKS = True
  1827. if options.description_file:
  1828. options.description = gclient_utils.FileRead(options.description_file)
  1829. gerrit_obj = _parse_gerrit_options(parser, options)
  1830. change = _parse_change(parser, options)
  1831. try:
  1832. if options.post_upload:
  1833. return DoPostUploadExecuter(change, gerrit_obj, options.verbose)
  1834. with canned_check_filter(options.skip_canned):
  1835. return DoPresubmitChecks(change, options.commit, options.verbose,
  1836. options.default_presubmit,
  1837. options.may_prompt, gerrit_obj,
  1838. options.dry_run, options.parallel,
  1839. options.json_output, options.no_diffs)
  1840. except PresubmitFailure as e:
  1841. import utils
  1842. print(e, file=sys.stderr)
  1843. print('Maybe your depot_tools is out of date?', file=sys.stderr)
  1844. print('depot_tools version: %s' % utils.depot_tools_version(),
  1845. file=sys.stderr)
  1846. return 2
  1847. if __name__ == '__main__':
  1848. fix_encoding.fix_encoding()
  1849. try:
  1850. sys.exit(main())
  1851. except KeyboardInterrupt:
  1852. sys.stderr.write('interrupted\n')
  1853. sys.exit(2)