presubmit_support.py 61 KB

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