presubmit_support.py 98 KB

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