presubmit_canned_checks.py 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847
  1. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Generic presubmit checks that can be reused by other presubmit checks."""
  5. import datetime
  6. import functools
  7. import io as _io
  8. import os as _os
  9. import time
  10. import metadata.discover
  11. import metadata.validate
  12. # TODO: Should fix these warnings.
  13. # pylint: disable=line-too-long
  14. _HERE = _os.path.dirname(_os.path.abspath(__file__))
  15. # These filters will be disabled if callers do not explicitly supply a
  16. # (possibly-empty) list. Ideally over time this list could be driven to zero.
  17. # TODO(pkasting): If some of these look like "should never enable", move them
  18. # to OFF_UNLESS_MANUALLY_ENABLED_LINT_FILTERS.
  19. #
  20. # Justifications for each filter:
  21. #
  22. # - build/include : Too many; fix in the future
  23. # TODO(pkasting): Try enabling subcategories
  24. # - build/include_order : Not happening; #ifdefed includes
  25. # - build/namespaces : TODO(pkasting): Try re-enabling
  26. # - readability/casting : Mistakes a whole bunch of function pointers
  27. # - runtime/int : Can be fixed long term; volume of errors too high
  28. # - whitespace/braces : We have a lot of explicit scoping in chrome code
  29. OFF_BY_DEFAULT_LINT_FILTERS = [
  30. '-build/include',
  31. '-build/include_order',
  32. '-build/namespaces',
  33. '-readability/casting',
  34. '-runtime/int',
  35. '-whitespace/braces',
  36. ]
  37. # These filters will be disabled unless callers explicitly enable them, because
  38. # they are undesirable in some way.
  39. #
  40. # Justifications for each filter:
  41. # - build/c++11 : Include file and feature blocklists are
  42. # google3-specific
  43. # - build/header_guard : Checked by CheckForIncludeGuards
  44. # - readability/todo : Chromium puts bug links, not usernames, in TODOs
  45. # - runtime/references : No longer banned by Google style guide
  46. # - whitespace/... : Most whitespace issues handled by clang-format
  47. OFF_UNLESS_MANUALLY_ENABLED_LINT_FILTERS = [
  48. '-build/c++11',
  49. '-build/header_guard',
  50. '-readability/todo',
  51. '-runtime/references',
  52. '-whitespace/braces',
  53. '-whitespace/comma',
  54. '-whitespace/end_of_line',
  55. '-whitespace/forcolon',
  56. '-whitespace/indent',
  57. '-whitespace/line_length',
  58. '-whitespace/newline',
  59. '-whitespace/operators',
  60. '-whitespace/parens',
  61. '-whitespace/semicolon',
  62. '-whitespace/tab',
  63. ]
  64. _CORP_LINK_KEYWORD = '.corp.google'
  65. ### Description checks
  66. def CheckChangeHasBugFieldFromChange(change, output_api, show_suggestions=True):
  67. """Requires that the changelist have a Bug: field. If show_suggestions is
  68. False then only report on incorrect tags, not missing tags."""
  69. bugs = change.BugsFromDescription()
  70. results = []
  71. if bugs:
  72. if any(b.startswith('b/') for b in bugs):
  73. results.append(
  74. output_api.PresubmitNotifyResult(
  75. 'Buganizer bugs should be prefixed with b:, not b/.'))
  76. elif show_suggestions:
  77. results.append(
  78. output_api.PresubmitNotifyResult(
  79. 'If this change has an associated bug, add Bug: [bug number] '
  80. 'or Fixed: [bug number].'))
  81. if 'Fixes' in change.GitFootersFromDescription():
  82. results.append(
  83. output_api.PresubmitError(
  84. 'Fixes: is the wrong footer tag, use Fixed: instead.'))
  85. return results
  86. def CheckChangeHasBugField(input_api, output_api):
  87. return CheckChangeHasBugFieldFromChange(input_api.change, output_api)
  88. def CheckChangeHasNoUnwantedTagsFromChange(change, output_api):
  89. UNWANTED_TAGS = {
  90. 'FIXED': {
  91. 'why': 'is not supported',
  92. 'instead': 'Use "Fixed:" instead.'
  93. },
  94. # TODO: BUG, ISSUE
  95. }
  96. errors = []
  97. for tag, desc in UNWANTED_TAGS.items():
  98. if tag in change.tags:
  99. subs = tag, desc['why'], desc.get('instead', '')
  100. errors.append(('%s= %s. %s' % subs).rstrip())
  101. return [output_api.PresubmitError('\n'.join(errors))] if errors else []
  102. def CheckChangeHasNoUnwantedTags(input_api, output_api):
  103. return CheckChangeHasNoUnwantedTagsFromChange(input_api.change, output_api)
  104. def CheckDoNotSubmitInDescription(input_api, output_api):
  105. """Checks that the user didn't add 'DO NOT ''SUBMIT' to the CL description.
  106. """
  107. # Keyword is concatenated to avoid presubmit check rejecting the CL.
  108. keyword = 'DO NOT ' + 'SUBMIT'
  109. if keyword in input_api.change.DescriptionText():
  110. return [
  111. output_api.PresubmitError(
  112. keyword + ' is present in the changelist description.')
  113. ]
  114. return []
  115. def CheckCorpLinksInDescription(input_api, output_api):
  116. """Checks that the description doesn't contain corp links."""
  117. if _CORP_LINK_KEYWORD in input_api.change.DescriptionText():
  118. return [
  119. output_api.PresubmitPromptWarning(
  120. 'Corp link is present in the changelist description.')
  121. ]
  122. return []
  123. def CheckChangeHasDescription(input_api, output_api):
  124. """Checks the CL description is not empty."""
  125. text = input_api.change.DescriptionText()
  126. if text.strip() == '':
  127. if input_api.is_committing and not input_api.no_diffs:
  128. return [output_api.PresubmitError('Add a description to the CL.')]
  129. return [
  130. output_api.PresubmitNotifyResult('Add a description to the CL.')
  131. ]
  132. return []
  133. def CheckChangeWasUploaded(input_api, output_api):
  134. """Checks that the issue was uploaded before committing."""
  135. if input_api.is_committing and not input_api.change.issue:
  136. message = 'Issue wasn\'t uploaded. Please upload first.'
  137. if input_api.no_diffs:
  138. # Make this just a message with presubmit --all and --files
  139. return [output_api.PresubmitNotifyResult(message)]
  140. return [output_api.PresubmitError(message)]
  141. return []
  142. def CheckDescriptionUsesColonInsteadOfEquals(input_api, output_api):
  143. """Checks that the CL description uses a colon after 'Bug' and 'Fixed' tags
  144. instead of equals.
  145. crbug.com only interprets the lines "Bug: xyz" and "Fixed: xyz" but not
  146. "Bug=xyz" or "Fixed=xyz".
  147. """
  148. text = input_api.change.DescriptionText()
  149. if input_api.re.search(r'^(Bug|Fixed)=',
  150. text,
  151. flags=input_api.re.IGNORECASE
  152. | input_api.re.MULTILINE):
  153. return [
  154. output_api.PresubmitError('Use Bug:/Fixed: instead of Bug=/Fixed=')
  155. ]
  156. return []
  157. ### Content checks
  158. def CheckAuthorizedAuthor(input_api, output_api, bot_allowlist=None):
  159. """For non-googler/chromites committers, verify the author's email address is
  160. in AUTHORS.
  161. """
  162. if input_api.is_committing or input_api.no_diffs:
  163. error_type = output_api.PresubmitError
  164. else:
  165. error_type = output_api.PresubmitPromptWarning
  166. author = input_api.change.author_email
  167. if not author:
  168. input_api.logging.info('No author, skipping AUTHOR check')
  169. return []
  170. # This is used for CLs created by trusted robot accounts.
  171. if bot_allowlist and author in bot_allowlist:
  172. return []
  173. authors_path = input_api.os_path.join(input_api.PresubmitLocalPath(),
  174. 'AUTHORS')
  175. author_re = input_api.re.compile(r'[^#]+\s+\<(.+?)\>\s*$')
  176. valid_authors = []
  177. with _io.open(authors_path, encoding='utf-8') as fp:
  178. for line in fp:
  179. m = author_re.match(line)
  180. if m:
  181. valid_authors.append(m.group(1).lower())
  182. if not any(
  183. input_api.fnmatch.fnmatch(author.lower(), valid)
  184. for valid in valid_authors):
  185. input_api.logging.info('Valid authors are %s', ', '.join(valid_authors))
  186. return [
  187. error_type((
  188. # pylint: disable=line-too-long
  189. '%s is not in AUTHORS file. If you are a new contributor, please visit\n'
  190. 'https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/contributing.md#Legal-stuff\n'
  191. # pylint: enable=line-too-long
  192. 'and read the "Legal stuff" section.\n'
  193. 'If you are a chromite, verify that the contributor signed the '
  194. 'CLA.') % author)
  195. ]
  196. return []
  197. def CheckDoNotSubmitInFiles(input_api, output_api):
  198. """Checks that the user didn't add 'DO NOT ''SUBMIT' to any files."""
  199. # We want to check every text file, not just source files.
  200. file_filter = lambda x: x
  201. # Keyword is concatenated to avoid presubmit check rejecting the CL.
  202. keyword = 'DO NOT ' + 'SUBMIT'
  203. def DoNotSubmitRule(extension, line):
  204. try:
  205. return keyword not in line
  206. # Fallback to True for non-text content
  207. except UnicodeDecodeError:
  208. return True
  209. errors = _FindNewViolationsOfRule(DoNotSubmitRule, input_api, file_filter)
  210. text = '\n'.join('Found %s in %s' % (keyword, loc) for loc in errors)
  211. if text:
  212. return [output_api.PresubmitError(text)]
  213. return []
  214. def CheckCorpLinksInFiles(input_api, output_api, source_file_filter=None):
  215. """Checks that files do not contain a corp link."""
  216. errors = _FindNewViolationsOfRule(
  217. lambda _, line: _CORP_LINK_KEYWORD not in line, input_api,
  218. source_file_filter)
  219. text = '\n'.join('Found corp link in %s' % loc for loc in errors)
  220. if text:
  221. return [output_api.PresubmitPromptWarning(text)]
  222. return []
  223. def CheckLargeScaleChange(input_api, output_api):
  224. """Checks if the change should go through the LSC process."""
  225. size = len(input_api.AffectedFiles())
  226. if size <= 100:
  227. return []
  228. return [
  229. output_api.PresubmitPromptWarning(
  230. f'This change contains {size} files.\n'
  231. 'Consider using the LSC (large scale change) process.\n'
  232. 'See https://chromium.googlesource.com/chromium/src/+/HEAD/docs/process/lsc/lsc_workflow.md.' # pylint: disable=line-too-long
  233. )
  234. ]
  235. def GetCppLintFilters(lint_filters=None):
  236. filters = OFF_UNLESS_MANUALLY_ENABLED_LINT_FILTERS[:]
  237. if lint_filters is None:
  238. lint_filters = OFF_BY_DEFAULT_LINT_FILTERS
  239. filters.extend(lint_filters)
  240. return filters
  241. def CheckChangeLintsClean(input_api,
  242. output_api,
  243. source_file_filter=None,
  244. lint_filters=None,
  245. verbose_level=None):
  246. """Checks that all '.cc' and '.h' files pass cpplint.py."""
  247. _RE_IS_TEST = input_api.re.compile(r'.*tests?.(cc|h)$')
  248. result = []
  249. cpplint = input_api.cpplint
  250. # Access to a protected member _XX of a client class
  251. # pylint: disable=protected-access
  252. cpplint._cpplint_state.ResetErrorCounts()
  253. cpplint._SetFilters(','.join(GetCppLintFilters(lint_filters)))
  254. # Use VS error format on Windows to make it easier to step through the
  255. # results.
  256. if input_api.platform == 'win32':
  257. cpplint._SetOutputFormat('vs7')
  258. if source_file_filter == None:
  259. # The only valid extensions for cpplint are .cc, .h, .cpp, .cu, and .ch.
  260. # Only process those extensions which are used in Chromium.
  261. INCLUDE_CPP_FILES_ONLY = (r'.*\.(cc|h|cpp)$', )
  262. source_file_filter = lambda x: input_api.FilterSourceFile(
  263. x,
  264. files_to_check=INCLUDE_CPP_FILES_ONLY,
  265. files_to_skip=input_api.DEFAULT_FILES_TO_SKIP)
  266. # We currently are more strict with normal code than unit tests; 4 and 5 are
  267. # the verbosity level that would normally be passed to cpplint.py through
  268. # --verbose=#. Hopefully, in the future, we can be more verbose.
  269. files = [
  270. f.AbsoluteLocalPath()
  271. for f in input_api.AffectedSourceFiles(source_file_filter)
  272. ]
  273. for file_name in files:
  274. if _RE_IS_TEST.match(file_name):
  275. level = 5
  276. else:
  277. level = 4
  278. verbose_level = verbose_level or level
  279. cpplint.ProcessFile(file_name, verbose_level)
  280. if cpplint._cpplint_state.error_count > 0:
  281. # cpplint errors currently cannot be counted as errors during upload
  282. # presubmits because some directories only run cpplint during upload and
  283. # therefore are far from cpplint clean.
  284. if input_api.is_committing:
  285. res_type = output_api.PresubmitError
  286. else:
  287. res_type = output_api.PresubmitPromptWarning
  288. result = [
  289. res_type('Changelist failed cpplint.py check. '
  290. 'Search the output for "(cpplint)"')
  291. ]
  292. return result
  293. def CheckChangeHasNoCR(input_api, output_api, source_file_filter=None):
  294. """Checks no '\r' (CR) character is in any source files."""
  295. cr_files = []
  296. for f in input_api.AffectedSourceFiles(source_file_filter):
  297. if '\r' in input_api.ReadFile(f, 'rb'):
  298. cr_files.append(f.LocalPath())
  299. if cr_files:
  300. return [
  301. output_api.PresubmitPromptWarning(
  302. 'Found a CR character in these files:', items=cr_files)
  303. ]
  304. return []
  305. def CheckChangeHasOnlyOneEol(input_api, output_api, source_file_filter=None):
  306. """Checks the files ends with one and only one \n (LF)."""
  307. eof_files = []
  308. for f in input_api.AffectedSourceFiles(source_file_filter):
  309. contents = input_api.ReadFile(f, 'rb')
  310. # Check that the file ends in one and only one newline character.
  311. if len(contents) > 1 and (contents[-1:] != '\n'
  312. or contents[-2:-1] == '\n'):
  313. eof_files.append(f.LocalPath())
  314. if eof_files:
  315. return [
  316. output_api.PresubmitPromptWarning(
  317. 'These files should end in one (and only one) newline character:',
  318. items=eof_files)
  319. ]
  320. return []
  321. def CheckChangeHasNoCrAndHasOnlyOneEol(input_api,
  322. output_api,
  323. source_file_filter=None):
  324. """Runs both CheckChangeHasNoCR and CheckChangeHasOnlyOneEOL in one pass.
  325. It is faster because it is reading the file only once.
  326. """
  327. cr_files = []
  328. eof_files = []
  329. for f in input_api.AffectedSourceFiles(source_file_filter):
  330. contents = input_api.ReadFile(f, 'rb')
  331. if '\r' in contents:
  332. cr_files.append(f.LocalPath())
  333. # Check that the file ends in one and only one newline character.
  334. if len(contents) > 1 and (contents[-1:] != '\n'
  335. or contents[-2:-1] == '\n'):
  336. eof_files.append(f.LocalPath())
  337. outputs = []
  338. if cr_files:
  339. outputs.append(
  340. output_api.PresubmitPromptWarning(
  341. 'Found a CR character in these files:', items=cr_files))
  342. if eof_files:
  343. outputs.append(
  344. output_api.PresubmitPromptWarning(
  345. 'These files should end in one (and only one) newline character:',
  346. items=eof_files))
  347. return outputs
  348. def CheckGenderNeutral(input_api, output_api, source_file_filter=None):
  349. """Checks that there are no gendered pronouns in any of the text files to be
  350. submitted.
  351. """
  352. if input_api.no_diffs:
  353. return []
  354. gendered_re = input_api.re.compile(
  355. r'(^|\s|\(|\[)([Hh]e|[Hh]is|[Hh]ers?|[Hh]im|[Ss]he|[Gg]uys?)\\b')
  356. errors = []
  357. for f in input_api.AffectedFiles(include_deletes=False,
  358. file_filter=source_file_filter):
  359. for line_num, line in f.ChangedContents():
  360. if gendered_re.search(line):
  361. errors.append('%s (%d): %s' % (f.LocalPath(), line_num, line))
  362. if errors:
  363. return [
  364. output_api.PresubmitPromptWarning('Found a gendered pronoun in:',
  365. long_text='\n'.join(errors))
  366. ]
  367. return []
  368. def _ReportErrorFileAndLine(filename, line_num, dummy_line):
  369. """Default error formatter for _FindNewViolationsOfRule."""
  370. return '%s:%s' % (filename, line_num)
  371. def _GenerateAffectedFileExtList(input_api, source_file_filter):
  372. """Generate a list of (file, extension) tuples from affected files.
  373. The result can be fed to _FindNewViolationsOfRule() directly, or
  374. could be filtered before doing that.
  375. Args:
  376. input_api: object to enumerate the affected files.
  377. source_file_filter: a filter to be passed to the input api.
  378. Yields:
  379. A list of (file, extension) tuples, where |file| is an affected
  380. file, and |extension| its file path extension.
  381. """
  382. for f in input_api.AffectedFiles(include_deletes=False,
  383. file_filter=source_file_filter):
  384. extension = str(f.LocalPath()).rsplit('.', 1)[-1]
  385. yield (f, extension)
  386. def _FindNewViolationsOfRuleForList(callable_rule,
  387. file_ext_list,
  388. error_formatter=_ReportErrorFileAndLine):
  389. """Find all newly introduced violations of a per-line rule (a callable).
  390. Prefer calling _FindNewViolationsOfRule() instead of this function, unless
  391. the list of affected files need to be filtered in a special way.
  392. Arguments:
  393. callable_rule: a callable taking a file extension and line of input and
  394. returning True if the rule is satisfied and False if there was a problem.
  395. file_ext_list: a list of input (file, extension) tuples, as returned by
  396. _GenerateAffectedFileExtList().
  397. error_formatter: a callable taking (filename, line_number, line) and
  398. returning a formatted error string.
  399. Returns:
  400. A list of the newly-introduced violations reported by the rule.
  401. """
  402. errors = []
  403. for f, extension in file_ext_list:
  404. # For speed, we do two passes, checking first the full file. Shelling
  405. # out to the SCM to determine the changed region can be quite expensive
  406. # on Win32. Assuming that most files will be kept problem-free, we can
  407. # skip the SCM operations most of the time.
  408. if all(callable_rule(extension, line) for line in f.NewContents()):
  409. continue # No violation found in full text: can skip considering diff.
  410. for line_num, line in f.ChangedContents():
  411. if not callable_rule(extension, line):
  412. errors.append(error_formatter(f.LocalPath(), line_num, line))
  413. return errors
  414. def _FindNewViolationsOfRule(callable_rule,
  415. input_api,
  416. source_file_filter=None,
  417. error_formatter=_ReportErrorFileAndLine):
  418. """Find all newly introduced violations of a per-line rule (a callable).
  419. Arguments:
  420. callable_rule: a callable taking a file extension and line of input and
  421. returning True if the rule is satisfied and False if there was a problem.
  422. input_api: object to enumerate the affected files.
  423. source_file_filter: a filter to be passed to the input api.
  424. error_formatter: a callable taking (filename, line_number, line) and
  425. returning a formatted error string.
  426. Returns:
  427. A list of the newly-introduced violations reported by the rule.
  428. """
  429. if input_api.no_diffs:
  430. return []
  431. return _FindNewViolationsOfRuleForList(
  432. callable_rule,
  433. _GenerateAffectedFileExtList(input_api, source_file_filter),
  434. error_formatter)
  435. def CheckChangeHasNoTabs(input_api, output_api, source_file_filter=None):
  436. """Checks that there are no tab characters in any of the text files to be
  437. submitted.
  438. """
  439. # In addition to the filter, make sure that makefiles are skipped.
  440. if not source_file_filter:
  441. # It's the default filter.
  442. source_file_filter = input_api.FilterSourceFile
  443. def filter_more(affected_file):
  444. basename = input_api.os_path.basename(affected_file.LocalPath())
  445. return (not (basename in ('Makefile', 'makefile')
  446. or basename.endswith('.mk'))
  447. and source_file_filter(affected_file))
  448. tabs = _FindNewViolationsOfRule(lambda _, line: '\t' not in line, input_api,
  449. filter_more)
  450. if tabs:
  451. return [
  452. output_api.PresubmitPromptWarning('Found a tab character in:',
  453. long_text='\n'.join(tabs))
  454. ]
  455. return []
  456. def CheckChangeTodoHasOwner(input_api, output_api, source_file_filter=None):
  457. """Checks that the user didn't add `TODO(name)` or `TODO: name -` without
  458. an owner.
  459. """
  460. legacyTODO = '\\s*\\(.+\\)\\s*:'
  461. modernTODO = ':\\s*[^\\s]+\\s*\\-'
  462. unowned_todo = input_api.re.compile('TODO(?!(%s|%s))' %
  463. (legacyTODO, modernTODO))
  464. errors = _FindNewViolationsOfRule(lambda _, x: not unowned_todo.search(x),
  465. input_api, source_file_filter)
  466. errors = ['Found TODO with no owner in ' + x for x in errors]
  467. if errors:
  468. return [output_api.PresubmitPromptWarning('\n'.join(errors))]
  469. return []
  470. def CheckChangeHasNoStrayWhitespace(input_api,
  471. output_api,
  472. source_file_filter=None):
  473. """Checks that there is no stray whitespace at source lines end."""
  474. errors = _FindNewViolationsOfRule(lambda _, line: line.rstrip() == line,
  475. input_api, source_file_filter)
  476. if errors:
  477. return [
  478. output_api.PresubmitPromptWarning(
  479. 'Found line ending with white spaces in:',
  480. long_text='\n'.join(errors))
  481. ]
  482. return []
  483. def CheckLongLines(input_api, output_api, maxlen, source_file_filter=None):
  484. """Checks that there aren't any lines longer than maxlen characters in any of
  485. the text files to be submitted.
  486. """
  487. if input_api.no_diffs:
  488. return []
  489. maxlens = {
  490. 'java': 100,
  491. # This is specifically for Android's handwritten makefiles (Android.mk).
  492. 'mk': 200,
  493. 'rs': 100,
  494. '': maxlen,
  495. }
  496. # To avoid triggering on the magic string, break it up.
  497. LINT_THEN_CHANGE_EXCEPTION = ('LI'
  498. 'NT.ThenChange(')
  499. # Language specific exceptions to max line length.
  500. # '.h' is considered an obj-c file extension, since OBJC_EXCEPTIONS are a
  501. # superset of CPP_EXCEPTIONS.
  502. CPP_FILE_EXTS = ('c', 'cc')
  503. CPP_EXCEPTIONS = ('#define', '#endif', '#if', '#include', '#pragma',
  504. '// ' + LINT_THEN_CHANGE_EXCEPTION)
  505. HTML_FILE_EXTS = ('html', )
  506. HTML_EXCEPTIONS = ('<g ', '<link ', '<path ',
  507. '<!-- ' + LINT_THEN_CHANGE_EXCEPTION)
  508. JAVA_FILE_EXTS = ('java', )
  509. JAVA_EXCEPTIONS = ('import ', 'package ',
  510. '// ' + LINT_THEN_CHANGE_EXCEPTION)
  511. JS_FILE_EXTS = ('js', )
  512. JS_EXCEPTIONS = ("GEN('#include", 'import ',
  513. '// ' + LINT_THEN_CHANGE_EXCEPTION)
  514. TS_FILE_EXTS = ('ts', )
  515. TS_EXCEPTIONS = ('import ', '// ' + LINT_THEN_CHANGE_EXCEPTION)
  516. OBJC_FILE_EXTS = ('h', 'm', 'mm')
  517. OBJC_EXCEPTIONS = ('#define', '#endif', '#if', '#import', '#include',
  518. '#pragma', '// ' + LINT_THEN_CHANGE_EXCEPTION)
  519. PY_FILE_EXTS = ('py', )
  520. PY_EXCEPTIONS = ('import', 'from', '# ' + LINT_THEN_CHANGE_EXCEPTION)
  521. LANGUAGE_EXCEPTIONS = [
  522. (CPP_FILE_EXTS, CPP_EXCEPTIONS),
  523. (HTML_FILE_EXTS, HTML_EXCEPTIONS),
  524. (JAVA_FILE_EXTS, JAVA_EXCEPTIONS),
  525. (JS_FILE_EXTS, JS_EXCEPTIONS),
  526. (TS_FILE_EXTS, TS_EXCEPTIONS),
  527. (OBJC_FILE_EXTS, OBJC_EXCEPTIONS),
  528. (PY_FILE_EXTS, PY_EXCEPTIONS),
  529. ]
  530. def no_long_lines(file_extension, line):
  531. """Returns True if the line length is okay."""
  532. # Check for language specific exceptions.
  533. if any(file_extension in exts and line.lstrip().startswith(exceptions)
  534. for exts, exceptions in LANGUAGE_EXCEPTIONS):
  535. return True
  536. file_maxlen = maxlens.get(file_extension, maxlens[''])
  537. # Stupidly long symbols that needs to be worked around if takes 66% of
  538. # line.
  539. long_symbol = file_maxlen * 2 / 3
  540. # Hard line length limit at 50% more.
  541. extra_maxlen = file_maxlen * 3 / 2
  542. line_len = len(line)
  543. if line_len <= file_maxlen:
  544. return True
  545. # Allow long URLs of any length.
  546. if any((url in line) for url in ('file://', 'http://', 'https://')):
  547. return True
  548. if 'presubmit: ignore-long-line' in line:
  549. return True
  550. if line_len > extra_maxlen:
  551. return False
  552. if 'url(' in line and file_extension == 'css':
  553. return True
  554. if '<include' in line and file_extension in ('css', 'html', 'js'):
  555. return True
  556. return input_api.re.match(
  557. r'.*[A-Za-z][A-Za-z_0-9]{%d,}.*' % long_symbol, line)
  558. def is_global_pylint_directive(line, pos):
  559. """True iff the pylint directive starting at line[pos] is global."""
  560. # Any character before |pos| that is not whitespace or '#' indidcates
  561. # this is a local directive.
  562. return not any(c not in " \t#" for c in line[:pos])
  563. def check_python_long_lines(affected_files, error_formatter):
  564. errors = []
  565. global_check_enabled = True
  566. for f in affected_files:
  567. file_path = f.LocalPath()
  568. for idx, line in enumerate(f.NewContents()):
  569. line_num = idx + 1
  570. line_is_short = no_long_lines(PY_FILE_EXTS[0], line)
  571. pos = line.find('pylint: disable=line-too-long')
  572. if pos >= 0:
  573. if is_global_pylint_directive(line, pos):
  574. global_check_enabled = False # Global disable
  575. else:
  576. continue # Local disable.
  577. do_check = global_check_enabled
  578. pos = line.find('pylint: enable=line-too-long')
  579. if pos >= 0:
  580. if is_global_pylint_directive(line, pos):
  581. global_check_enabled = True # Global enable
  582. do_check = True # Ensure it applies to current line as well.
  583. else:
  584. do_check = True # Local enable
  585. if do_check and not line_is_short:
  586. errors.append(error_formatter(file_path, line_num, line))
  587. return errors
  588. def format_error(filename, line_num, line):
  589. return '%s, line %s, %s chars' % (filename, line_num, len(line))
  590. file_ext_list = list(
  591. _GenerateAffectedFileExtList(input_api, source_file_filter))
  592. errors = []
  593. # For non-Python files, a simple line-based rule check is enough.
  594. non_py_file_ext_list = [
  595. x for x in file_ext_list if x[1] not in PY_FILE_EXTS
  596. ]
  597. if non_py_file_ext_list:
  598. errors += _FindNewViolationsOfRuleForList(no_long_lines,
  599. non_py_file_ext_list,
  600. error_formatter=format_error)
  601. # However, Python files need more sophisticated checks that need parsing
  602. # the whole source file.
  603. py_file_list = [x[0] for x in file_ext_list if x[1] in PY_FILE_EXTS]
  604. if py_file_list:
  605. errors += check_python_long_lines(py_file_list,
  606. error_formatter=format_error)
  607. if errors:
  608. msg = 'Found %d lines longer than %s characters (first 5 shown).' % (
  609. len(errors), maxlen)
  610. return [output_api.PresubmitPromptWarning(msg, items=errors[:5])]
  611. return []
  612. def CheckLicense(input_api,
  613. output_api,
  614. license_re_param=None,
  615. project_name=None,
  616. source_file_filter=None,
  617. accept_empty_files=True):
  618. """Verifies the license header."""
  619. # Early-out if the license_re is guaranteed to match everything.
  620. if license_re_param and license_re_param == '.*':
  621. return []
  622. current_year = int(input_api.time.strftime('%Y'))
  623. if license_re_param:
  624. new_license_re = license_re = license_re_param
  625. else:
  626. project_name = project_name or 'Chromium'
  627. # Accept any year number from 2006 to the current year, or the special
  628. # 2006-20xx string used on the oldest files. 2006-20xx is deprecated,
  629. # but tolerated on old files. On new files the current year must be
  630. # specified.
  631. allowed_years = (str(s)
  632. for s in reversed(range(2006, current_year + 1)))
  633. years_re = '(' + '|'.join(
  634. allowed_years) + '|2006-2008|2006-2009|2006-2010)'
  635. # Reduce duplication between the two regex expressions.
  636. key_line = (
  637. 'Use of this source code is governed by a BSD-style license '
  638. 'that can be')
  639. # The (c) is deprecated, but tolerate it until it's removed from all
  640. # files. "All rights reserved" is also deprecated, but tolerate it until
  641. # it's removed from all files.
  642. license_re = (
  643. r'(?:.+ )?Copyright (\(c\) )?%(year)s The %(project)s Authors'
  644. r'(\. All rights reserved\.)?\n'
  645. r'(?:.+ )?%(key_line)s\n'
  646. r'(?:.+ )?found in the LICENSE file\.(?: \*/)?\n') % {
  647. 'year': years_re,
  648. 'project': project_name,
  649. 'key_line': key_line,
  650. }
  651. # On new files don't tolerate any digression from the ideal.
  652. new_license_re = (
  653. r'(?:.+ )?Copyright %(year)s The %(project)s Authors\n'
  654. r'(?:.+ )?%(key_line)s\n'
  655. r'(?:.+ )?found in the LICENSE file\.(?: \*/)?\n') % {
  656. 'year': years_re,
  657. 'project': project_name,
  658. 'key_line': key_line,
  659. }
  660. license_re = input_api.re.compile(license_re, input_api.re.MULTILINE)
  661. new_license_re = input_api.re.compile(new_license_re,
  662. input_api.re.MULTILINE)
  663. bad_files = []
  664. wrong_year_new_files = []
  665. bad_new_files = []
  666. for f in input_api.AffectedSourceFiles(source_file_filter):
  667. # Only examine the first 1,000 bytes of the file to avoid expensive and
  668. # fruitless regex searches over long files with no license.
  669. # re.match would also avoid this but can't be used because some files
  670. # have a shebang line ahead of the license. The \r\n fixup is because it
  671. # is possible on Windows to copy/paste the license in such a way that
  672. # \r\n line endings are inserted. This leads to confusing license error
  673. # messages - it's better to let the separate \r\n check handle those.
  674. contents = input_api.ReadFile(f, 'r')[:1000].replace('\r\n', '\n')
  675. if accept_empty_files and not contents:
  676. continue
  677. if f.Action() == 'A':
  678. # Stricter checking for new files (but might actually be moved).
  679. match = new_license_re.search(contents)
  680. if not match:
  681. # License is totally wrong.
  682. bad_new_files.append(f.LocalPath())
  683. elif not license_re_param and match.groups()[0] != str(
  684. current_year):
  685. # If we're using the built-in license_re on a new file then make
  686. # sure the year is correct.
  687. wrong_year_new_files.append(f.LocalPath())
  688. elif not license_re.search(contents):
  689. bad_files.append(f.LocalPath())
  690. results = []
  691. if bad_new_files:
  692. # We can't distinguish between Google and thirty-party files, so this has to be a
  693. # warning rather than an error.
  694. if license_re_param:
  695. warning_message = ('License on new files must match:\n\n%s\n' %
  696. license_re_param)
  697. else:
  698. # Verbatim text that can be copy-pasted into new files (possibly
  699. # adjusting the leading comment delimiter).
  700. new_license_text = (
  701. '// Copyright %(year)s The %(project)s Authors\n'
  702. '// %(key_line)s\n'
  703. '// found in the LICENSE file.\n') % {
  704. 'year': current_year,
  705. 'project': project_name,
  706. 'key_line': key_line,
  707. }
  708. warning_message = (
  709. 'License on new files must be:\n\n%s\n' % new_license_text +
  710. '(adjusting the comment delimiter accordingly).\n\n' +
  711. 'If this is a moved file, then update the license but do not ' +
  712. 'update the year.\n\n' +
  713. 'If this is a third-party file then ignore this warning.\n\n')
  714. warning_message += 'Found a bad license header in these new or moved files:'
  715. results.append(
  716. output_api.PresubmitPromptWarning(warning_message,
  717. items=bad_new_files))
  718. if wrong_year_new_files:
  719. # We can't distinguish between new and moved files, so this has to be a
  720. # warning rather than an error.
  721. results.append(
  722. output_api.PresubmitPromptWarning(
  723. 'License doesn\'t list the current year. If this is a new file, '
  724. 'use the current year. If this is a moved file then ignore this '
  725. 'warning.',
  726. items=wrong_year_new_files))
  727. if bad_files:
  728. results.append(
  729. output_api.PresubmitPromptWarning(
  730. 'License must match:\n%s\n' % license_re.pattern +
  731. 'Found a bad license header in these files:',
  732. items=bad_files))
  733. return results
  734. def CheckChromiumDependencyMetadata(input_api, output_api, file_filter=None):
  735. """Check files for Chromium third party dependency metadata have sufficient
  736. information, and are correctly formatted.
  737. See the README.chromium.template at
  738. https://chromium.googlesource.com/chromium/src/+/main/third_party/README.chromium.template
  739. """
  740. # If the file filter is unspecified, filter to known Chromium metadata
  741. # files.
  742. if file_filter is None:
  743. file_filter = lambda f: metadata.discover.is_metadata_file(f.LocalPath(
  744. ))
  745. # The repo's root directory is required to check license files.
  746. repo_root_dir = input_api.change.RepositoryRoot()
  747. outputs = []
  748. for f in input_api.AffectedFiles(file_filter=file_filter):
  749. if f.Action() == 'D':
  750. # No need to validate a deleted file.
  751. continue
  752. errors, warnings = metadata.validate.check_file(
  753. filepath=f.AbsoluteLocalPath(),
  754. repo_root_dir=repo_root_dir,
  755. reader=input_api.ReadFile,
  756. is_open_source_project=True,
  757. )
  758. for warning in warnings:
  759. outputs.append(output_api.PresubmitPromptWarning(warning, [f]))
  760. for error in errors:
  761. outputs.append(output_api.PresubmitError(error, [f]))
  762. return outputs
  763. ### Other checks
  764. _IGNORE_FREEZE_FOOTER = 'Ignore-Freeze'
  765. _FREEZE_TZ = datetime.timezone(-datetime.timedelta(hours=8), 'PST')
  766. _CHROMIUM_FREEZE_START = datetime.datetime(
  767. 2024, 12, 20, 17, 1, tzinfo=_FREEZE_TZ)
  768. _CHROMIUM_FREEZE_END = datetime.datetime(2025, 1, 5, 17, 0, tzinfo=_FREEZE_TZ)
  769. _CHROMIUM_FREEZE_DETAILS = 'Holiday freeze'
  770. def CheckInfraFreeze(input_api,
  771. output_api,
  772. files_to_include=None,
  773. files_to_exclude=None):
  774. return CheckChromiumInfraFreeze(input_api, output_api, files_to_include,
  775. files_to_exclude)
  776. def CheckChromiumInfraFreeze(input_api,
  777. output_api,
  778. files_to_include=None,
  779. files_to_exclude=None):
  780. """Prevent modifications during infra code freeze.
  781. Args:
  782. input_api: The InputApi.
  783. output_api: The OutputApi.
  784. files_to_include: A list of regexes identifying the files to
  785. include in the freeze if not matched by a regex in
  786. files_to_exclude. The regexes will be matched against the
  787. paths of the affected files under the directory containing
  788. the PRESUBMIT.py relative to the client root, using / as the
  789. path separator. If not provided, all files under the
  790. directory containing the PRESUBMIT.py will be included.
  791. files_to_exclude: A list of regexes identifying the files to
  792. exclude from the freeze. The regexes will be matched against
  793. the paths of the affected files under the directory
  794. containing the PRESUBMIT.py relative to the client root,
  795. using / as the path separator. If not provided, no files
  796. will be excluded.
  797. """
  798. # Not in the freeze time range
  799. now = datetime.datetime.now(_FREEZE_TZ)
  800. if now < _CHROMIUM_FREEZE_START or now >= _CHROMIUM_FREEZE_END:
  801. input_api.logging.info('No freeze is in effect')
  802. return []
  803. # The CL is ignoring the freeze
  804. if _IGNORE_FREEZE_FOOTER in input_api.change.GitFootersFromDescription():
  805. input_api.logging.info('Freeze is being ignored')
  806. return []
  807. def file_filter(affected_file):
  808. files_to_check = files_to_include or ['.*']
  809. files_to_skip = files_to_exclude or []
  810. return input_api.FilterSourceFile(affected_file,
  811. files_to_check=files_to_check,
  812. files_to_skip=files_to_skip)
  813. # Compute the affected files that are covered by the freeze
  814. files = [
  815. af.LocalPath()
  816. for af in input_api.AffectedFiles(file_filter=file_filter)
  817. ]
  818. # The Cl does not touch ny files covered by the freeze
  819. if not files:
  820. input_api.logging.info('No affected files are covered by freeze')
  821. return []
  822. # Don't report errors when on the presubmit --all bot or when testing with
  823. # presubmit --files.
  824. if input_api.no_diffs:
  825. report_type = output_api.PresubmitPromptWarning
  826. else:
  827. report_type = output_api.PresubmitError
  828. return [
  829. report_type(
  830. 'There is a prod infra freeze in effect from {} until {}:\n'
  831. '\t{}\n\n'
  832. 'The following files cannot be modified:\n {}.\n\n'
  833. 'Add "{}: <reason>" to the end of your commit message to override.'.
  834. format(_CHROMIUM_FREEZE_START, _CHROMIUM_FREEZE_END,
  835. _CHROMIUM_FREEZE_DETAILS, '\n '.join(files),
  836. _IGNORE_FREEZE_FOOTER))
  837. ]
  838. def CheckDoNotSubmit(input_api, output_api):
  839. return (CheckDoNotSubmitInDescription(input_api, output_api) +
  840. CheckDoNotSubmitInFiles(input_api, output_api))
  841. def CheckTreeIsOpen(input_api,
  842. output_api,
  843. url=None,
  844. closed=None,
  845. json_url=None):
  846. """Check whether to allow commit without prompt.
  847. Supports two styles:
  848. 1. Checks that an url's content doesn't match a regexp that would mean that
  849. the tree is closed. (old)
  850. 2. Check the json_url to decide whether to allow commit without prompt.
  851. Args:
  852. input_api: input related apis.
  853. output_api: output related apis.
  854. url: url to use for regex based tree status.
  855. closed: regex to match for closed status.
  856. json_url: url to download json style status.
  857. """
  858. if not input_api.is_committing or \
  859. 'PRESUBMIT_SKIP_NETWORK' in _os.environ:
  860. return []
  861. try:
  862. if json_url:
  863. connection = input_api.urllib_request.urlopen(json_url)
  864. status = input_api.json.loads(connection.read())
  865. connection.close()
  866. if not status['can_commit_freely']:
  867. short_text = 'Tree state is: ' + status['general_state']
  868. long_text = status['message'] + '\n' + json_url
  869. if input_api.no_diffs:
  870. return [
  871. output_api.PresubmitPromptWarning(short_text,
  872. long_text=long_text)
  873. ]
  874. return [
  875. output_api.PresubmitError(short_text, long_text=long_text)
  876. ]
  877. else:
  878. # TODO(bradnelson): drop this once all users are gone.
  879. connection = input_api.urllib_request.urlopen(url)
  880. status = connection.read()
  881. connection.close()
  882. if input_api.re.match(closed, status):
  883. long_text = status + '\n' + url
  884. return [
  885. output_api.PresubmitError('The tree is closed.',
  886. long_text=long_text)
  887. ]
  888. except IOError as e:
  889. return [
  890. output_api.PresubmitError('Error fetching tree status.',
  891. long_text=str(e))
  892. ]
  893. return []
  894. def GetUnitTestsInDirectory(input_api,
  895. output_api,
  896. directory,
  897. files_to_check=None,
  898. files_to_skip=None,
  899. env=None,
  900. run_on_python2=False,
  901. run_on_python3=True,
  902. skip_shebang_check=True):
  903. """Lists all files in a directory and runs them. Doesn't recurse.
  904. It's mainly a wrapper for RunUnitTests. Use files_to_check and files_to_skip
  905. to filter tests accordingly. run_on_python2, run_on_python3, and
  906. skip_shebang_check are no longer used but have to be retained because of the
  907. many callers in other repos that pass them in.
  908. """
  909. del run_on_python2
  910. del run_on_python3
  911. del skip_shebang_check
  912. unit_tests = []
  913. test_path = input_api.os_path.abspath(
  914. input_api.os_path.join(input_api.PresubmitLocalPath(), directory))
  915. def check(filename, filters):
  916. return any(True for i in filters if input_api.re.match(i, filename))
  917. to_run = found = 0
  918. for filename in input_api.os_listdir(test_path):
  919. found += 1
  920. fullpath = input_api.os_path.join(test_path, filename)
  921. if not input_api.os_path.isfile(fullpath):
  922. continue
  923. if files_to_check and not check(filename, files_to_check):
  924. continue
  925. if files_to_skip and check(filename, files_to_skip):
  926. continue
  927. unit_tests.append(input_api.os_path.join(directory, filename))
  928. to_run += 1
  929. input_api.logging.debug('Found %d files, running %d unit tests' %
  930. (found, to_run))
  931. if not to_run:
  932. return [
  933. output_api.PresubmitPromptWarning(
  934. 'Out of %d files, found none that matched c=%r, s=%r in directory %s'
  935. % (found, files_to_check, files_to_skip, directory))
  936. ]
  937. return GetUnitTests(input_api, output_api, unit_tests, env)
  938. def GetUnitTests(input_api,
  939. output_api,
  940. unit_tests,
  941. env=None,
  942. run_on_python2=False,
  943. run_on_python3=True,
  944. skip_shebang_check=True):
  945. """Runs all unit tests in a directory.
  946. On Windows, sys.executable is used for unit tests ending with ".py".
  947. run_on_python2, run_on_python3, and skip_shebang_check are no longer used but
  948. have to be retained because of the many callers in other repos that pass them
  949. in.
  950. """
  951. del run_on_python2
  952. del run_on_python3
  953. del skip_shebang_check
  954. # We don't want to hinder users from uploading incomplete patches, but we do
  955. # want to report errors as errors when doing presubmit --all testing.
  956. if input_api.is_committing or input_api.no_diffs:
  957. message_type = output_api.PresubmitError
  958. else:
  959. message_type = output_api.PresubmitPromptWarning
  960. results = []
  961. for unit_test in unit_tests:
  962. cmd = [unit_test]
  963. if input_api.verbose:
  964. cmd.append('--verbose')
  965. kwargs = {'cwd': input_api.PresubmitLocalPath()}
  966. if env:
  967. kwargs['env'] = env
  968. if not unit_test.endswith('.py'):
  969. results.append(
  970. input_api.Command(name=unit_test,
  971. cmd=cmd,
  972. kwargs=kwargs,
  973. message=message_type))
  974. else:
  975. results.append(
  976. input_api.Command(name=unit_test,
  977. cmd=cmd,
  978. kwargs=kwargs,
  979. message=message_type))
  980. return results
  981. def GetUnitTestsRecursively(input_api,
  982. output_api,
  983. directory,
  984. files_to_check,
  985. files_to_skip,
  986. run_on_python2=False,
  987. run_on_python3=True,
  988. skip_shebang_check=True):
  989. """Gets all files in the directory tree (git repo) that match files_to_check.
  990. Restricts itself to only find files within the Change's source repo, not
  991. dependencies. run_on_python2, run_on_python3, and skip_shebang_check are no
  992. longer used but have to be retained because of the many callers in other repos
  993. that pass them in.
  994. """
  995. del run_on_python2
  996. del run_on_python3
  997. del skip_shebang_check
  998. def check(filename):
  999. return (any(input_api.re.match(f, filename) for f in files_to_check) and
  1000. not any(input_api.re.match(f, filename) for f in files_to_skip))
  1001. tests = []
  1002. to_run = found = 0
  1003. for filepath in input_api.change.AllFiles(directory):
  1004. found += 1
  1005. if check(filepath):
  1006. to_run += 1
  1007. tests.append(filepath)
  1008. input_api.logging.debug('Found %d files, running %d' % (found, to_run))
  1009. if not to_run:
  1010. return [
  1011. output_api.PresubmitPromptWarning(
  1012. 'Out of %d files, found none that matched c=%r, s=%r in directory %s'
  1013. % (found, files_to_check, files_to_skip, directory))
  1014. ]
  1015. return GetUnitTests(input_api, output_api, tests)
  1016. def GetPythonUnitTests(input_api, output_api, unit_tests, python3=False):
  1017. """Run the unit tests out of process, capture the output and use the result
  1018. code to determine success.
  1019. DEPRECATED.
  1020. """
  1021. # We don't want to hinder users from uploading incomplete patches.
  1022. if input_api.is_committing or input_api.no_diffs:
  1023. message_type = output_api.PresubmitError
  1024. else:
  1025. message_type = output_api.PresubmitNotifyResult
  1026. results = []
  1027. for unit_test in unit_tests:
  1028. # Run the unit tests out of process. This is because some unit tests
  1029. # stub out base libraries and don't clean up their mess. It's too easy
  1030. # to get subtle bugs.
  1031. cwd = None
  1032. env = None
  1033. unit_test_name = unit_test
  1034. # 'python -m test.unit_test' doesn't work. We need to change to the
  1035. # right directory instead.
  1036. if '.' in unit_test:
  1037. # Tests imported in submodules (subdirectories) assume that the
  1038. # current directory is in the PYTHONPATH. Manually fix that.
  1039. unit_test = unit_test.replace('.', '/')
  1040. cwd = input_api.os_path.dirname(unit_test)
  1041. unit_test = input_api.os_path.basename(unit_test)
  1042. env = input_api.environ.copy()
  1043. # At least on Windows, it seems '.' must explicitly be in PYTHONPATH
  1044. backpath = [
  1045. '.',
  1046. input_api.os_path.pathsep.join(['..'] * (cwd.count('/') + 1))
  1047. ]
  1048. if env.get('PYTHONPATH'):
  1049. backpath.append(env.get('PYTHONPATH'))
  1050. env['PYTHONPATH'] = input_api.os_path.pathsep.join((backpath))
  1051. env.pop('VPYTHON_CLEAR_PYTHONPATH', None)
  1052. cmd = [input_api.python3_executable, '-m', '%s' % unit_test]
  1053. results.append(
  1054. input_api.Command(name=unit_test_name,
  1055. cmd=cmd,
  1056. kwargs={
  1057. 'env': env,
  1058. 'cwd': cwd
  1059. },
  1060. message=message_type))
  1061. return results
  1062. def RunUnitTestsInDirectory(input_api, *args, **kwargs):
  1063. """Run tests in a directory serially.
  1064. For better performance, use GetUnitTestsInDirectory and then
  1065. pass to input_api.RunTests.
  1066. """
  1067. return input_api.RunTests(
  1068. GetUnitTestsInDirectory(input_api, *args, **kwargs), False)
  1069. def RunUnitTests(input_api, *args, **kwargs):
  1070. """Run tests serially.
  1071. For better performance, use GetUnitTests and then pass to
  1072. input_api.RunTests.
  1073. """
  1074. return input_api.RunTests(GetUnitTests(input_api, *args, **kwargs), False)
  1075. def RunPythonUnitTests(input_api, *args, **kwargs):
  1076. """Run python tests in a directory serially.
  1077. DEPRECATED
  1078. """
  1079. return input_api.RunTests(GetPythonUnitTests(input_api, *args, **kwargs),
  1080. False)
  1081. def _FetchAllFiles(input_api, files_to_check, files_to_skip):
  1082. """Hack to fetch all files."""
  1083. # We cannot use AffectedFiles here because we want to test every python
  1084. # file on each single python change. It's because a change in a python file
  1085. # can break another unmodified file.
  1086. # Use code similar to InputApi.FilterSourceFile()
  1087. def Find(filepath, filters):
  1088. if input_api.platform == 'win32':
  1089. filepath = filepath.replace('\\', '/')
  1090. for item in filters:
  1091. if input_api.re.match(item, filepath):
  1092. return True
  1093. return False
  1094. files = []
  1095. path_len = len(input_api.PresubmitLocalPath())
  1096. for dirpath, dirnames, filenames in input_api.os_walk(
  1097. input_api.PresubmitLocalPath()):
  1098. # Passes dirnames in block list to speed up search.
  1099. for item in dirnames[:]:
  1100. filepath = input_api.os_path.join(dirpath, item)[path_len + 1:]
  1101. if Find(filepath, files_to_skip):
  1102. dirnames.remove(item)
  1103. for item in filenames:
  1104. filepath = input_api.os_path.join(dirpath, item)[path_len + 1:]
  1105. if Find(filepath,
  1106. files_to_check) and not Find(filepath, files_to_skip):
  1107. files.append(filepath)
  1108. return files
  1109. def GetPylint(input_api,
  1110. output_api,
  1111. files_to_check=None,
  1112. files_to_skip=None,
  1113. disabled_warnings=None,
  1114. extra_paths_list=None,
  1115. pylintrc=None,
  1116. version='2.7'):
  1117. """Run pylint on python files.
  1118. The default files_to_check enforces looking only at *.py files.
  1119. Currently only pylint version '2.6' and '2.7' are supported.
  1120. """
  1121. files_to_check = tuple(files_to_check or (r'.*\.py$', ))
  1122. files_to_skip = tuple(files_to_skip or input_api.DEFAULT_FILES_TO_SKIP)
  1123. extra_paths_list = extra_paths_list or []
  1124. assert version in ('2.6', '2.7', '2.17', '3.2'), \
  1125. 'Unsupported pylint version: %s' % version
  1126. if input_api.is_committing or input_api.no_diffs:
  1127. error_type = output_api.PresubmitError
  1128. else:
  1129. error_type = output_api.PresubmitPromptWarning
  1130. # Only trigger if there is at least one python file affected.
  1131. def rel_path(regex):
  1132. """Modifies a regex for a subject to accept paths relative to root."""
  1133. def samefile(a, b):
  1134. # Default implementation for platforms lacking os.path.samefile
  1135. # (like Windows).
  1136. return input_api.os_path.abspath(a) == input_api.os_path.abspath(b)
  1137. samefile = getattr(input_api.os_path, 'samefile', samefile)
  1138. if samefile(input_api.PresubmitLocalPath(),
  1139. input_api.change.RepositoryRoot()):
  1140. return regex
  1141. prefix = input_api.os_path.join(
  1142. input_api.os_path.relpath(input_api.PresubmitLocalPath(),
  1143. input_api.change.RepositoryRoot()), '')
  1144. return input_api.re.escape(prefix) + regex
  1145. src_filter = lambda x: input_api.FilterSourceFile(
  1146. x, map(rel_path, files_to_check), map(rel_path, files_to_skip))
  1147. if not input_api.AffectedSourceFiles(src_filter):
  1148. input_api.logging.info('Skipping pylint: no matching changes.')
  1149. return []
  1150. if pylintrc is not None:
  1151. pylintrc = input_api.os_path.join(input_api.PresubmitLocalPath(),
  1152. pylintrc)
  1153. else:
  1154. pylintrc = input_api.os_path.join(_HERE, 'pylintrc')
  1155. if input_api.os_path.exists(f'{pylintrc}-{version}'):
  1156. pylintrc += f'-{version}'
  1157. extra_args = ['--rcfile=%s' % pylintrc]
  1158. if disabled_warnings:
  1159. extra_args.extend(['-d', ','.join(disabled_warnings)])
  1160. files = _FetchAllFiles(input_api, files_to_check, files_to_skip)
  1161. if not files:
  1162. return []
  1163. files.sort()
  1164. input_api.logging.info('Running pylint %s on %d files', version, len(files))
  1165. input_api.logging.debug('Running pylint on: %s', files)
  1166. env = input_api.environ.copy()
  1167. env['PYTHONPATH'] = input_api.os_path.pathsep.join(extra_paths_list)
  1168. env.pop('VPYTHON_CLEAR_PYTHONPATH', None)
  1169. input_api.logging.debug(' with extra PYTHONPATH: %r', extra_paths_list)
  1170. files_per_job = 10
  1171. def GetPylintCmd(flist, extra, parallel):
  1172. # Windows needs help running python files so we explicitly specify
  1173. # the interpreter to use. It also has limitations on the size of
  1174. # the command-line, so we pass arguments via a pipe.
  1175. tool = input_api.os_path.join(_HERE, 'pylint-' + version)
  1176. kwargs = {'env': env}
  1177. if input_api.platform == 'win32':
  1178. # On Windows, scripts on the current directory take precedence over
  1179. # PATH. When `pylint.bat` calls `vpython3`, it will execute the
  1180. # `vpython3` of the depot_tools under test instead of the one in the
  1181. # bot. As a workaround, we run the tests from the parent directory
  1182. # instead.
  1183. cwd = input_api.change.RepositoryRoot()
  1184. if input_api.os_path.basename(cwd) == 'depot_tools':
  1185. kwargs['cwd'] = input_api.os_path.dirname(cwd)
  1186. flist = [
  1187. input_api.os_path.join('depot_tools', f) for f in flist
  1188. ]
  1189. tool += '.bat'
  1190. cmd = [tool, '--args-on-stdin']
  1191. if len(flist) == 1:
  1192. description = flist[0]
  1193. else:
  1194. description = '%s files' % len(flist)
  1195. args = extra_args[:]
  1196. if extra:
  1197. args.extend(extra)
  1198. description += ' using %s' % (extra, )
  1199. if parallel:
  1200. # Make sure we don't request more parallelism than is justified for
  1201. # the number of files we have to process. PyLint child-process
  1202. # startup time is significant.
  1203. jobs = min(input_api.cpu_count, 1 + len(flist) // files_per_job)
  1204. if jobs > 1:
  1205. args.append('--jobs=%s' % jobs)
  1206. description += ' on %d processes' % jobs
  1207. kwargs['stdin'] = '\n'.join(args + flist).encode('utf-8')
  1208. return input_api.Command(name='Pylint (%s)' % description,
  1209. cmd=cmd,
  1210. kwargs=kwargs,
  1211. message=error_type,
  1212. python3=True)
  1213. # pylint's cycle detection doesn't work in parallel, so spawn a second,
  1214. # single-threaded job for just that check. However, only do this if there
  1215. # are actually enough files to process to justify parallelism in the first
  1216. # place. Some PRESUBMITs explicitly mention cycle detection.
  1217. if len(files) >= files_per_job and not any(
  1218. 'R0401' in a or 'cyclic-import' in a for a in extra_args):
  1219. return [
  1220. GetPylintCmd(files, ["--disable=cyclic-import"], True),
  1221. GetPylintCmd(files, ["--disable=all", "--enable=cyclic-import"],
  1222. False),
  1223. ]
  1224. return [
  1225. GetPylintCmd(files, [], True),
  1226. ]
  1227. def RunPylint(input_api, *args, **kwargs):
  1228. """Legacy presubmit function.
  1229. For better performance, get all tests and then pass to
  1230. input_api.RunTests.
  1231. """
  1232. return input_api.RunTests(GetPylint(input_api, *args, **kwargs), False)
  1233. def CheckDirMetadataFormat(input_api, output_api, dirmd_bin=None):
  1234. # TODO(crbug.com/1102997): Remove OWNERS once DIR_METADATA migration is
  1235. # complete.
  1236. file_filter = lambda f: (input_api.basename(f.LocalPath()) in
  1237. ('DIR_METADATA', 'OWNERS'))
  1238. affected_files = {
  1239. f.AbsoluteLocalPath()
  1240. for f in input_api.change.AffectedFiles(include_deletes=False,
  1241. file_filter=file_filter)
  1242. }
  1243. if not affected_files:
  1244. return []
  1245. name = 'Validate metadata in OWNERS and DIR_METADATA files'
  1246. if dirmd_bin is None:
  1247. dirmd_bin = input_api.os_path.join(
  1248. _HERE, 'dirmd.bat' if input_api.is_windows else 'dirmd')
  1249. # When running git cl presubmit --all this presubmit may be asked to check
  1250. # ~7,500 files, leading to a command line that is about 500,000 characters.
  1251. # This goes past the Windows 8191 character cmd.exe limit and causes cryptic
  1252. # failures. To avoid these we break the command up into smaller pieces. The
  1253. # non-Windows limit is chosen so that the code that splits up commands will
  1254. # get some exercise on other platforms.
  1255. # Depending on how long the command is on Windows the error may be:
  1256. # The command line is too long.
  1257. # Or it may be:
  1258. # OSError: Execution failed with error: [WinError 206] The filename or
  1259. # extension is too long.
  1260. # I suspect that the latter error comes from CreateProcess hitting its 32768
  1261. # character limit.
  1262. files_per_command = 50 if input_api.is_windows else 1000
  1263. affected_files = sorted(affected_files)
  1264. results = []
  1265. for i in range(0, len(affected_files), files_per_command):
  1266. kwargs = {}
  1267. cmd = [dirmd_bin, 'validate'] + affected_files[i:i + files_per_command]
  1268. results.extend(
  1269. [input_api.Command(name, cmd, kwargs, output_api.PresubmitError)])
  1270. return results
  1271. def CheckNoNewMetadataInOwners(input_api, output_api):
  1272. """Check that no metadata is added to OWNERS files."""
  1273. if input_api.no_diffs:
  1274. return []
  1275. _METADATA_LINE_RE = input_api.re.compile(
  1276. r'^#\s*(TEAM|COMPONENT|OS|WPT-NOTIFY)+\s*:\s*\S+$',
  1277. input_api.re.MULTILINE | input_api.re.IGNORECASE)
  1278. affected_files = input_api.change.AffectedFiles(
  1279. include_deletes=False,
  1280. file_filter=lambda f: input_api.basename(f.LocalPath()) == 'OWNERS')
  1281. errors = []
  1282. for f in affected_files:
  1283. for _, line in f.ChangedContents():
  1284. if _METADATA_LINE_RE.search(line):
  1285. errors.append(f.AbsoluteLocalPath())
  1286. break
  1287. if not errors:
  1288. return []
  1289. return [
  1290. output_api.PresubmitError(
  1291. 'New metadata was added to the following OWNERS files, but should '
  1292. 'have been added to DIR_METADATA files instead:\n' +
  1293. '\n'.join(errors) + '\n' +
  1294. 'See https://source.chromium.org/chromium/infra/infra/+/HEAD:'
  1295. 'go/src/infra/tools/dirmd/proto/dir_metadata.proto for details.')
  1296. ]
  1297. def CheckOwnersDirMetadataExclusive(input_api, output_api):
  1298. """Check that metadata in OWNERS files and DIR_METADATA files are mutually
  1299. exclusive.
  1300. """
  1301. _METADATA_LINE_RE = input_api.re.compile(
  1302. r'^#\s*(TEAM|COMPONENT|OS|WPT-NOTIFY)+\s*:\s*\S+$',
  1303. input_api.re.MULTILINE)
  1304. file_filter = (lambda f: input_api.basename(f.LocalPath()) in
  1305. ('OWNERS', 'DIR_METADATA'))
  1306. affected_dirs = {
  1307. input_api.os_path.dirname(f.AbsoluteLocalPath())
  1308. for f in input_api.change.AffectedFiles(include_deletes=False,
  1309. file_filter=file_filter)
  1310. }
  1311. errors = []
  1312. for path in affected_dirs:
  1313. owners_path = input_api.os_path.join(path, 'OWNERS')
  1314. dir_metadata_path = input_api.os_path.join(path, 'DIR_METADATA')
  1315. if (not input_api.os_path.isfile(dir_metadata_path)
  1316. or not input_api.os_path.isfile(owners_path)):
  1317. continue
  1318. if _METADATA_LINE_RE.search(input_api.ReadFile(owners_path)):
  1319. errors.append(owners_path)
  1320. if not errors:
  1321. return []
  1322. return [
  1323. output_api.PresubmitError(
  1324. 'The following OWNERS files should contain no metadata, as there is a '
  1325. 'DIR_METADATA file present in the same directory:\n' +
  1326. '\n'.join(errors))
  1327. ]
  1328. def CheckOwnersFormat(input_api, output_api):
  1329. if input_api.gerrit and input_api.gerrit.IsCodeOwnersEnabledOnRepo():
  1330. return []
  1331. host = "none"
  1332. project = "none"
  1333. if input_api.gerrit:
  1334. host = input_api.gerrit.host
  1335. project = input_api.gerrit.project
  1336. return [
  1337. output_api.PresubmitError(
  1338. f'code-owners is not enabled on {host}/{project}. '
  1339. 'Ask your host enable it on your gerrit '
  1340. 'host. Read more about code-owners at '
  1341. 'https://chromium-review.googlesource.com/'
  1342. 'plugins/code-owners/Documentation/index.html.')
  1343. ]
  1344. def CheckOwners(input_api, output_api, source_file_filter=None, allow_tbr=True):
  1345. # Skip OWNERS check when Owners-Override label is approved. This is intended
  1346. # for global owners, trusted bots, and on-call sheriffs. Review is still
  1347. # required for these changes.
  1348. if (input_api.change.issue and input_api.gerrit.IsOwnersOverrideApproved(
  1349. input_api.change.issue)):
  1350. return []
  1351. if input_api.gerrit and input_api.gerrit.IsCodeOwnersEnabledOnRepo():
  1352. return []
  1353. host = "none"
  1354. project = "none"
  1355. if input_api.gerrit:
  1356. host = input_api.gerrit.host
  1357. project = input_api.gerrit.project
  1358. return [
  1359. output_api.PresubmitError(
  1360. f'code-owners is not enabled on {host}/{project}. '
  1361. 'Ask your host enable it on your gerrit '
  1362. 'host. Read more about code-owners at '
  1363. 'https://chromium-review.googlesource.com/'
  1364. 'plugins/code-owners/Documentation/index.html.')
  1365. ]
  1366. def GetCodereviewOwnerAndReviewers(input_api,
  1367. _email_regexp=None,
  1368. approval_needed=True):
  1369. """Return the owner and reviewers of a change, if any.
  1370. If approval_needed is True, only reviewers who have approved the change
  1371. will be returned.
  1372. """
  1373. # Recognizes 'X@Y' email addresses. Very simplistic.
  1374. EMAIL_REGEXP = input_api.re.compile(r'^[\w\-\+\%\.]+\@[\w\-\+\%\.]+$')
  1375. issue = input_api.change.issue
  1376. if not issue:
  1377. return None, (set() if approval_needed else _ReviewersFromChange(
  1378. input_api.change))
  1379. owner_email = input_api.gerrit.GetChangeOwner(issue)
  1380. reviewers = set(
  1381. r for r in input_api.gerrit.GetChangeReviewers(issue, approval_needed)
  1382. if _match_reviewer_email(r, owner_email, EMAIL_REGEXP))
  1383. input_api.logging.debug('owner: %s; approvals given by: %s', owner_email,
  1384. ', '.join(sorted(reviewers)))
  1385. return owner_email, reviewers
  1386. def _ReviewersFromChange(change):
  1387. """Return the reviewers specified in the |change|, if any."""
  1388. reviewers = set()
  1389. reviewers.update(change.ReviewersFromDescription())
  1390. reviewers.update(change.TBRsFromDescription())
  1391. # Drop reviewers that aren't specified in email address format.
  1392. return set(reviewer for reviewer in reviewers if '@' in reviewer)
  1393. def _match_reviewer_email(r, owner_email, email_regexp):
  1394. return email_regexp.match(r) and r != owner_email
  1395. def CheckSingletonInHeaders(input_api, output_api, source_file_filter=None):
  1396. """Deprecated, must be removed."""
  1397. return [
  1398. output_api.PresubmitNotifyResult(
  1399. 'CheckSingletonInHeaders is deprecated, please remove it.')
  1400. ]
  1401. def PanProjectChecks(input_api,
  1402. output_api,
  1403. excluded_paths=None,
  1404. text_files=None,
  1405. license_header=None,
  1406. project_name=None,
  1407. owners_check=True,
  1408. maxlen=80,
  1409. global_checks=True):
  1410. """Checks that ALL chromium orbit projects should use.
  1411. These are checks to be run on all Chromium orbit project, including:
  1412. Chromium
  1413. Native Client
  1414. V8
  1415. When you update this function, please take this broad scope into account.
  1416. Args:
  1417. input_api: Bag of input related interfaces.
  1418. output_api: Bag of output related interfaces.
  1419. excluded_paths: Don't include these paths in common checks.
  1420. text_files: Which file are to be treated as documentation text files.
  1421. license_header: What license header should be on files.
  1422. project_name: What is the name of the project as it appears in the license.
  1423. global_checks: If True run checks that are unaffected by other options or by
  1424. the PRESUBMIT script's location, such as CheckChangeHasDescription.
  1425. global_checks should be passed as False when this function is called from
  1426. locations other than the project's root PRESUBMIT.py, to avoid redundant
  1427. checking.
  1428. Returns:
  1429. A list of warning or error objects.
  1430. """
  1431. excluded_paths = tuple(excluded_paths or [])
  1432. text_files = tuple(text_files or (
  1433. r'.+\.txt$',
  1434. r'.+\.json$',
  1435. ))
  1436. results = []
  1437. # This code loads the default skip list (e.g. third_party, experimental,
  1438. # etc) and add our skip list (breakpad, skia and v8 are still not following
  1439. # google style and are not really living this repository). See
  1440. # presubmit_support.py InputApi.FilterSourceFile for the (simple) usage.
  1441. files_to_skip = input_api.DEFAULT_FILES_TO_SKIP + excluded_paths
  1442. files_to_check = input_api.DEFAULT_FILES_TO_CHECK + text_files
  1443. sources = lambda x: input_api.FilterSourceFile(x,
  1444. files_to_skip=files_to_skip)
  1445. text_files = lambda x: input_api.FilterSourceFile(
  1446. x, files_to_skip=files_to_skip, files_to_check=files_to_check)
  1447. snapshot_memory = []
  1448. def snapshot(msg):
  1449. """Measures & prints performance warning if a rule is running slow."""
  1450. dt2 = input_api.time.time()
  1451. if snapshot_memory:
  1452. delta_s = dt2 - snapshot_memory[0]
  1453. if delta_s > 0.5:
  1454. print(" %s took a long time: %.1fs" %
  1455. (snapshot_memory[1], delta_s))
  1456. snapshot_memory[:] = (dt2, msg)
  1457. snapshot("checking owners files format")
  1458. try:
  1459. if not 'PRESUBMIT_SKIP_NETWORK' in _os.environ and owners_check:
  1460. snapshot("checking owners")
  1461. results.extend(
  1462. input_api.canned_checks.CheckOwnersFormat(
  1463. input_api, output_api))
  1464. results.extend(
  1465. input_api.canned_checks.CheckOwners(input_api,
  1466. output_api,
  1467. source_file_filter=None))
  1468. except Exception as e:
  1469. print('Failed to check owners - %s' % str(e))
  1470. snapshot("checking long lines")
  1471. results.extend(
  1472. input_api.canned_checks.CheckLongLines(input_api,
  1473. output_api,
  1474. maxlen,
  1475. source_file_filter=sources))
  1476. snapshot("checking tabs")
  1477. results.extend(
  1478. input_api.canned_checks.CheckChangeHasNoTabs(
  1479. input_api, output_api, source_file_filter=sources))
  1480. snapshot("checking stray whitespace")
  1481. results.extend(
  1482. input_api.canned_checks.CheckChangeHasNoStrayWhitespace(
  1483. input_api, output_api, source_file_filter=sources))
  1484. snapshot("checking license")
  1485. results.extend(
  1486. input_api.canned_checks.CheckLicense(input_api,
  1487. output_api,
  1488. license_header,
  1489. project_name,
  1490. source_file_filter=sources))
  1491. snapshot("checking corp links in files")
  1492. results.extend(
  1493. input_api.canned_checks.CheckCorpLinksInFiles(
  1494. input_api, output_api, source_file_filter=sources))
  1495. snapshot("checking large scale change")
  1496. results.extend(
  1497. input_api.canned_checks.CheckLargeScaleChange(input_api, output_api))
  1498. if input_api.is_committing:
  1499. if global_checks:
  1500. # These changes verify state that is global to the tree and can
  1501. # therefore be skipped when run from PRESUBMIT.py scripts deeper in
  1502. # the tree. Skipping these saves a bit of time and avoids having
  1503. # redundant output. This was initially designed for use by
  1504. # third_party/blink/PRESUBMIT.py.
  1505. snapshot("checking was uploaded")
  1506. results.extend(
  1507. input_api.canned_checks.CheckChangeWasUploaded(
  1508. input_api, output_api))
  1509. snapshot("checking description")
  1510. results.extend(
  1511. input_api.canned_checks.CheckChangeHasDescription(
  1512. input_api, output_api))
  1513. results.extend(
  1514. input_api.canned_checks.CheckDoNotSubmitInDescription(
  1515. input_api, output_api))
  1516. results.extend(
  1517. input_api.canned_checks.CheckCorpLinksInDescription(
  1518. input_api, output_api))
  1519. snapshot("checking do not submit in files")
  1520. results.extend(
  1521. input_api.canned_checks.CheckDoNotSubmitInFiles(
  1522. input_api, output_api))
  1523. if global_checks:
  1524. results.extend(
  1525. input_api.canned_checks.CheckNoNewGitFilesAddedInDependencies(
  1526. input_api, output_api))
  1527. if input_api.change.scm == 'git':
  1528. snapshot("checking for commit objects in tree")
  1529. results.extend(
  1530. input_api.canned_checks.CheckForCommitObjects(
  1531. input_api, output_api))
  1532. results.extend(
  1533. input_api.canned_checks.CheckForRecursedeps(
  1534. input_api, output_api))
  1535. snapshot("done")
  1536. return results
  1537. def CheckPatchFormatted(input_api,
  1538. output_api,
  1539. bypass_warnings=True,
  1540. check_clang_format=True,
  1541. check_js=False,
  1542. check_python=None,
  1543. result_factory=None):
  1544. result_factory = result_factory or output_api.PresubmitPromptWarning
  1545. import git_cl
  1546. display_args = []
  1547. if not check_clang_format:
  1548. display_args.append('--no-clang-format')
  1549. if check_js:
  1550. display_args.append('--js')
  1551. # Explicitly setting check_python to will enable/disable python formatting
  1552. # on all files. Leaving it as None will enable checking patch formatting
  1553. # on files that have a .style.yapf file in a parent directory.
  1554. if check_python is not None:
  1555. if check_python:
  1556. display_args.append('--python')
  1557. else:
  1558. display_args.append('--no-python')
  1559. cmd = [
  1560. '-C',
  1561. input_api.change.RepositoryRoot(), 'cl', 'format', '--dry-run',
  1562. '--presubmit'
  1563. ] + display_args
  1564. # Make sure the passed --upstream branch is applied to a dry run.
  1565. if input_api.change.UpstreamBranch():
  1566. cmd.extend(['--upstream', input_api.change.UpstreamBranch()])
  1567. presubmit_subdir = input_api.os_path.relpath(
  1568. input_api.PresubmitLocalPath(), input_api.change.RepositoryRoot())
  1569. if presubmit_subdir.startswith('..') or presubmit_subdir == '.':
  1570. presubmit_subdir = ''
  1571. # If the PRESUBMIT.py is in a parent repository, then format the entire
  1572. # subrepository. Otherwise, format only the code in the directory that
  1573. # contains the PRESUBMIT.py.
  1574. if presubmit_subdir:
  1575. cmd.append(input_api.PresubmitLocalPath())
  1576. code, _ = git_cl.RunGitWithCode(cmd, suppress_stderr=bypass_warnings)
  1577. # bypass_warnings? Only fail with code 2.
  1578. # As this is just a warning, ignore all other errors if the user
  1579. # happens to have a broken clang-format, doesn't use git, etc etc.
  1580. if code == 2 or (code and not bypass_warnings):
  1581. if presubmit_subdir:
  1582. short_path = presubmit_subdir
  1583. else:
  1584. short_path = input_api.basename(input_api.change.RepositoryRoot())
  1585. display_args.append(presubmit_subdir)
  1586. return [
  1587. result_factory('The %s directory requires source formatting. '
  1588. 'Please run: git cl format %s' %
  1589. (short_path, ' '.join(display_args)))
  1590. ]
  1591. return []
  1592. def CheckGNFormatted(input_api, output_api):
  1593. import gn
  1594. affected_files = input_api.AffectedFiles(
  1595. include_deletes=False,
  1596. file_filter=lambda x: x.LocalPath().endswith('.gn') or x.LocalPath(
  1597. ).endswith('.gni') or x.LocalPath().endswith('.typemap'))
  1598. warnings = []
  1599. for f in affected_files:
  1600. cmd = [
  1601. input_api.python3_executable,
  1602. input_api.os_path.join(_HERE, 'gn.py'), 'format', '--dry-run',
  1603. f.AbsoluteLocalPath()
  1604. ]
  1605. rc = gn.main(cmd)
  1606. if rc == 2:
  1607. warnings.append(
  1608. output_api.PresubmitPromptWarning(
  1609. '%s requires formatting. Please run:\n gn format %s' %
  1610. (f.AbsoluteLocalPath(), f.LocalPath())))
  1611. # It's just a warning, so ignore other types of failures assuming they'll be
  1612. # caught elsewhere.
  1613. return warnings
  1614. def CheckCIPDManifest(input_api, output_api, path=None, content=None):
  1615. """Verifies that a CIPD ensure file manifest is valid against all platforms.
  1616. Exactly one of "path" or "content" must be provided. An assertion will occur
  1617. if neither or both are provided.
  1618. Args:
  1619. path (str): If provided, the filesystem path to the manifest to verify.
  1620. content (str): If provided, the raw content of the manifest to veirfy.
  1621. """
  1622. cipd_bin = 'cipd' if not input_api.is_windows else 'cipd.bat'
  1623. cmd = [cipd_bin, 'ensure-file-verify']
  1624. kwargs = {}
  1625. if input_api.is_windows:
  1626. # Needs to be able to resolve "cipd.bat".
  1627. kwargs['shell'] = True
  1628. if input_api.verbose:
  1629. cmd += ['-log-level', 'debug']
  1630. if path:
  1631. assert content is None, 'Cannot provide both "path" and "content".'
  1632. cmd += ['-ensure-file', path]
  1633. name = 'Check CIPD manifest %r' % path
  1634. elif content:
  1635. assert path is None, 'Cannot provide both "path" and "content".'
  1636. cmd += ['-ensure-file=-']
  1637. kwargs['stdin'] = content.encode('utf-8')
  1638. # quick and dirty parser to extract checked packages.
  1639. packages = [
  1640. l.split()[0] for l in (ll.strip() for ll in content.splitlines())
  1641. if ' ' in l and not l.startswith('$')
  1642. ]
  1643. name = 'Check CIPD packages from string: %r' % (packages, )
  1644. else:
  1645. raise Exception('Exactly one of "path" or "content" must be provided.')
  1646. return input_api.Command(name, cmd, kwargs, output_api.PresubmitError)
  1647. def CheckCIPDPackages(input_api, output_api, platforms, packages):
  1648. """Verifies that all named CIPD packages can be resolved against all supplied
  1649. platforms.
  1650. Args:
  1651. platforms (list): List of CIPD platforms to verify.
  1652. packages (dict): Mapping of package name to version.
  1653. """
  1654. manifest = []
  1655. for p in platforms:
  1656. manifest.append('$VerifiedPlatform %s' % (p, ))
  1657. for k, v in packages.items():
  1658. manifest.append('%s %s' % (k, v))
  1659. return CheckCIPDManifest(input_api, output_api, content='\n'.join(manifest))
  1660. def CheckCIPDClientDigests(input_api, output_api, client_version_file):
  1661. """Verifies that *.digests file was correctly regenerated.
  1662. <client_version_file>.digests file contains pinned hashes of the CIPD client.
  1663. It is consulted during CIPD client bootstrap and self-update. It should be
  1664. regenerated each time CIPD client version file changes.
  1665. Args:
  1666. client_version_file (str): Path to a text file with CIPD client version.
  1667. """
  1668. cmd = [
  1669. 'cipd' if not input_api.is_windows else 'cipd.bat',
  1670. 'selfupdate-roll',
  1671. '-check',
  1672. '-version-file',
  1673. client_version_file,
  1674. ]
  1675. if input_api.verbose:
  1676. cmd += ['-log-level', 'debug']
  1677. return input_api.Command(
  1678. 'Check CIPD client_version_file.digests file',
  1679. cmd,
  1680. {'shell': True} if input_api.is_windows else {}, # to resolve cipd.bat
  1681. output_api.PresubmitError)
  1682. def CheckForCommitObjects(input_api, output_api):
  1683. """Validates that commit objects match DEPS.
  1684. Commit objects are put into the git tree typically by submodule tooling.
  1685. Because we use gclient to handle external repository references instead,
  1686. we want to ensure DEPS content and Git are in sync when desired.
  1687. Args:
  1688. input_api: Bag of input related interfaces.
  1689. output_api: Bag of output related interfaces.
  1690. Returns:
  1691. A presubmit error if a commit object is not expected.
  1692. """
  1693. if input_api.change.scm != 'git':
  1694. return [
  1695. output_api.PresubmitNotifyResult(
  1696. 'Non-git workspace detected, skipping CheckForCommitObjects.')
  1697. ]
  1698. # Get DEPS file.
  1699. try:
  1700. deps_content = input_api.subprocess.check_output(
  1701. ['git', 'show', 'HEAD:DEPS'], cwd=input_api.PresubmitLocalPath())
  1702. deps = _ParseDeps(deps_content)
  1703. except Exception:
  1704. # No DEPS file, so skip this check.
  1705. return []
  1706. # set default
  1707. if 'deps' not in deps:
  1708. deps['deps'] = {}
  1709. if 'git_dependencies' not in deps:
  1710. deps['git_dependencies'] = 'DEPS'
  1711. if deps['git_dependencies'] == 'SUBMODULES':
  1712. # git submodule is source of truth, so no further action needed.
  1713. return []
  1714. def parse_tree_entry(ent):
  1715. """Splits a tree entry into components
  1716. Args:
  1717. ent: a tree entry in the form "filemode type hash\tname"
  1718. Returns:
  1719. The tree entry split into component parts
  1720. """
  1721. tabparts = ent.split('\t', 1)
  1722. spaceparts = tabparts[0].split(' ', 2)
  1723. return (spaceparts[0], spaceparts[1], spaceparts[2], tabparts[1])
  1724. full_tree = input_api.subprocess.check_output(
  1725. ['git', 'ls-tree', '-r', '--full-tree', '-z', 'HEAD'],
  1726. cwd=input_api.PresubmitLocalPath())
  1727. # commit_tree_entries holds all commit entries (ie gitlink, submodule
  1728. # record).
  1729. commit_tree_entries = []
  1730. for entry in full_tree.strip().split(b'\00'):
  1731. if not entry.startswith(b'160000'):
  1732. # Remove entries that we don't care about. 160000 indicates a
  1733. # gitlink.
  1734. continue
  1735. tree_entry = parse_tree_entry(entry.decode('utf-8'))
  1736. if tree_entry[1] == 'commit':
  1737. commit_tree_entries.append(tree_entry)
  1738. # No gitlinks found, return early.
  1739. if len(commit_tree_entries) == 0:
  1740. return []
  1741. if deps['git_dependencies'] == 'DEPS':
  1742. commit_tree_entries = [x[3] for x in commit_tree_entries]
  1743. return [
  1744. output_api.PresubmitError(
  1745. 'Commit objects present within tree.\n'
  1746. 'This may be due to submodule-related interactions;\n'
  1747. 'the presence of a commit object in the tree may lead to odd\n'
  1748. 'situations where files are inconsistently checked-out.\n'
  1749. 'Remove these commit entries and validate your changeset '
  1750. 'again:\n', commit_tree_entries)
  1751. ]
  1752. assert deps['git_dependencies'] == 'SYNC', 'unexpected git_dependencies.'
  1753. # Create mapping HASH -> PATH
  1754. git_submodules = {}
  1755. for commit_tree_entry in commit_tree_entries:
  1756. git_submodules[commit_tree_entry[2]] = commit_tree_entry[3]
  1757. gitmodules_file = input_api.os_path.join(input_api.PresubmitLocalPath(),
  1758. '.gitmodules')
  1759. import configparser
  1760. config = configparser.ConfigParser()
  1761. config.read(gitmodules_file)
  1762. gitmodule_paths = set([])
  1763. for name, section in config.items():
  1764. if not name.startswith('submodule '):
  1765. continue
  1766. if 'path' not in section:
  1767. continue
  1768. gitmodule_paths.add(section['path'])
  1769. mismatch_entries = []
  1770. deps_msg = ""
  1771. for dep_path, dep in deps['deps'].items():
  1772. if 'dep_type' in dep and dep['dep_type'] != 'git':
  1773. continue
  1774. url = dep if isinstance(dep, str) else dep['url']
  1775. commit_hash = url.split('@')[-1]
  1776. # One exception is made prior to this check enforcement.
  1777. #
  1778. # We need to address this exception, but in the meantime we can't fail
  1779. # this global presubmit check.
  1780. #
  1781. # https://chromium.googlesource.com/angle/angle/+/refs/heads/main/DEPS#412
  1782. if dep_path == 'third_party/dummy_chromium':
  1783. continue
  1784. if commit_hash in git_submodules:
  1785. submodule_path = git_submodules.pop(commit_hash)
  1786. if not dep_path.endswith(submodule_path):
  1787. # DEPS entry path doesn't point to a gitlink.
  1788. return [
  1789. output_api.PresubmitError(
  1790. f'Unexpected DEPS entry {dep_path}.\n'
  1791. f'Expected path to end with {submodule_path}.\n'
  1792. 'Make sure DEPS paths match those in .gitmodules \n'
  1793. f'and a gitlink exists at {dep_path}.')
  1794. ]
  1795. try:
  1796. gitmodule_paths.remove(submodule_path)
  1797. except KeyError:
  1798. return [
  1799. output_api.PresubmitError(
  1800. f'No submodule with path {submodule_path} in '
  1801. '.gitmodules.\nMake sure entries in .gitmodules match '
  1802. 'gitlink locations in the tree.')
  1803. ]
  1804. else:
  1805. mismatch_entries.append(dep_path)
  1806. deps_msg += f"\n [DEPS] {dep_path} -> {commit_hash}"
  1807. for commit_hash, path in git_submodules.items():
  1808. mismatch_entries.append(path)
  1809. deps_msg += f"\n [gitlink] {path} -> {commit_hash}"
  1810. if mismatch_entries:
  1811. return [
  1812. output_api.PresubmitError(
  1813. 'DEPS file indicates git submodule migration is in progress,\n'
  1814. 'but the commit objects do not match DEPS entries.\n\n'
  1815. 'To reset all git submodule git entries to match DEPS, run\n'
  1816. 'the following command in the root of this repository:\n'
  1817. ' gclient gitmodules\n'
  1818. 'This will update AND stage the entries to the correct revisions.\n'
  1819. 'Then commit these staged changes only (`git commit` without -a).\n'
  1820. '\n\n'
  1821. 'The following entries diverged: ' + deps_msg)
  1822. ]
  1823. if len(gitmodule_paths) > 0:
  1824. return [
  1825. output_api.PresubmitError(
  1826. '.gitmodules file contains submodules that no longer exist\n'
  1827. 'in DEPS or Git (gitlink).\n'
  1828. 'Remove the following entries from .gitmodules:\n'
  1829. '\n\t' + '\n\t'.join(gitmodule_paths) +
  1830. '\n\nor run the following command:\n'
  1831. ' gclient gitmodules\n')
  1832. ]
  1833. return []
  1834. def CheckForRecursedeps(input_api, output_api):
  1835. """Checks that DEPS entries in recursedeps exist in deps."""
  1836. # Run only if DEPS has been modified.
  1837. if all(f.LocalPath() != 'DEPS' for f in input_api.AffectedFiles()):
  1838. return []
  1839. # Get DEPS file.
  1840. deps_file = input_api.os_path.join(input_api.change.RepositoryRoot(),
  1841. 'DEPS')
  1842. if not input_api.os_path.isfile(deps_file):
  1843. # No DEPS file, carry on!
  1844. return []
  1845. with open(deps_file) as f:
  1846. deps_content = f.read()
  1847. deps = _ParseDeps(deps_content)
  1848. if 'recursedeps' not in deps:
  1849. # No recursedeps entry, carry on!
  1850. return []
  1851. existing_deps: set[str] = set()
  1852. # If git_dependencies is SYNC or SUBMODULES, prefer the submodule data.
  1853. if deps.get('git_dependencies', 'DEPS') == 'DEPS':
  1854. existing_deps = set(deps.get('deps', {}))
  1855. else:
  1856. existing_deps = input_api.change.AllLocalSubmodules()
  1857. # existing_deps is 'local paths' i.e. repo-relative. However, if deps is
  1858. # NOT use_relative_paths, then we need to adjust these to be
  1859. # client-root-relative.
  1860. #
  1861. # Sadly, as of 25Q1, the default is still False.
  1862. if not deps.get('use_relative_paths', False):
  1863. # Find the relative path between the gclient root and the repo root.
  1864. gclient_relpath: str = input_api.os_path.relpath(
  1865. input_api.change.RepositoryRoot(),
  1866. start=input_api.gclient_paths.FindGclientRoot(
  1867. input_api.change.RepositoryRoot()))
  1868. # relpath will use native os.path.sep, so split and clean it.
  1869. #
  1870. # NOTE: relpath can make ./path/to/something, so trim off the '.'
  1871. gclient_relpath_toks = tuple(
  1872. gclient_relpath.split(input_api.os_path.sep))
  1873. if gclient_relpath_toks[0] == '.':
  1874. gclient_relpath_toks = gclient_relpath_toks[1:]
  1875. # All submodules are relative to the repo root, so join
  1876. #
  1877. # gclient-to-repo ++ repo-to-submodule
  1878. #
  1879. # To get path strings which should appear in recursedeps.
  1880. #
  1881. # We must join with '/', not os_path.sep, because the paths in
  1882. # DEPS.recursedeps always use forward slashes.
  1883. existing_deps = set(
  1884. '/'.join(gclient_relpath_toks +
  1885. (p.replace(input_api.os_path.sep, '/'), ))
  1886. for p in existing_deps)
  1887. errors = []
  1888. for check_dep in deps['recursedeps']:
  1889. if check_dep not in existing_deps:
  1890. errors.append(
  1891. output_api.PresubmitError(
  1892. f'Found recuredep entry {check_dep} but it is not found '
  1893. 'in\n deps itself. Remove it from recurcedeps or add '
  1894. 'deps entry.'))
  1895. return errors
  1896. def _readDeps(input_api):
  1897. """Read DEPS file from the checkout disk. Extracted for testability."""
  1898. deps_file = input_api.os_path.join(input_api.PresubmitLocalPath(), 'DEPS')
  1899. with open(deps_file) as f:
  1900. return f.read()
  1901. def CheckNoNewGitFilesAddedInDependencies(input_api, output_api):
  1902. """Check if there are Git files in any DEPS dependencies. Error is returned
  1903. if there are."""
  1904. try:
  1905. deps = _ParseDeps(_readDeps(input_api))
  1906. except FileNotFoundError:
  1907. # If there's no DEPS file, there is nothing to check.
  1908. return []
  1909. dependency_paths = set()
  1910. for path, dep in deps.get('deps', {}).items():
  1911. if 'condition' in dep and 'non_git_source' in dep['condition']:
  1912. # TODO(crbug.com/40738689): Remove src/ prefix
  1913. dependency_paths.add(path[4:]) # 4 == len('src/')
  1914. errors = []
  1915. for file in input_api.AffectedFiles(include_deletes=False):
  1916. path = file.LocalPath()
  1917. # We are checking path, and all paths below up to root. E.g. if path is
  1918. # a/b/c, we start with path == "a/b/c", followed by "a/b" and "a".
  1919. while path:
  1920. if path in dependency_paths:
  1921. errors.append(
  1922. output_api.PresubmitError(
  1923. 'You cannot place files tracked by Git inside a '
  1924. 'first-party DEPS dependency (deps).\n'
  1925. f'Dependency: {path}\n'
  1926. f'File: {file.LocalPath()}'))
  1927. path = _os.path.dirname(path)
  1928. return errors
  1929. def CheckNewDEPSHooksHasRequiredReviewers(input_api, output_api):
  1930. """Ensures proper review of CLs adding new DEPS hooks.
  1931. This check verifies that any CL adding a new DEPS hook is reviewed and
  1932. approved by the required reviewer(s). If the required reviewers haven't
  1933. been added, an error will be raised.
  1934. Required Reviewers are computed from the OWNERS file. It looks for DEPS
  1935. owners annotated `For new DEPS hook`. Example:
  1936. `per-file DEPS=foo@chromium.org # For new DEPS hook`
  1937. This check is skipped if:
  1938. * The Gerrit CL hasn't been uploaded yet.
  1939. * The CL doesn't involve adding new hooks to the DEPS file.
  1940. * No required reviewers are found in the OWNERS file.
  1941. """
  1942. if not input_api.change.issue:
  1943. return [] # Gerrit CL not yet uploaded.
  1944. deps_affected_files = [
  1945. f for f in input_api.AffectedFiles() if f.LocalPath() == 'DEPS'
  1946. ]
  1947. if not deps_affected_files:
  1948. return [] # Not a DEPS change.
  1949. dep_file = deps_affected_files[0]
  1950. def _get_hooks_names(dep_contents):
  1951. deps = _ParseDeps('\n'.join(dep_contents))
  1952. hooks = deps.get('hooks', [])
  1953. return set(hook.get('name') for hook in hooks)
  1954. old_hooks = _get_hooks_names(dep_file.OldContents())
  1955. new_hooks = _get_hooks_names(dep_file.NewContents())
  1956. if new_hooks.issubset(old_hooks):
  1957. return [] # No new hooks added.
  1958. required_reviewer_re = input_api.re.compile(
  1959. r"^per-file\s+DEPS\s*=\s*({email_re}(\s*,\s*{email_re})*)\s*# For new DEPS hook$"
  1960. .format(email_re=r'[^ @]+@[^ #]+'))
  1961. required_reviewers = []
  1962. for line in input_api.ReadFile(
  1963. input_api.os_path.join(input_api.change.RepositoryRoot(),
  1964. 'OWNERS')).splitlines():
  1965. if (m := required_reviewer_re.match(line)):
  1966. required_reviewers.extend(r.strip() for r in m.group(1).split(','))
  1967. if not required_reviewers:
  1968. return []
  1969. submitting = input_api.is_committing and not input_api.dry_run
  1970. reviewers = input_api.gerrit.GetChangeReviewers(input_api.change.issue,
  1971. approving_only=submitting)
  1972. if set(r for r in reviewers if r in required_reviewers):
  1973. return [] # passing the check
  1974. added_hooks = new_hooks - old_hooks
  1975. msg = (f'New DEPS {"hook" if len(added_hooks) == 1 else "hooks"} '
  1976. f'({", ".join(sorted(new_hooks-old_hooks))}) '
  1977. f'{"is" if len(added_hooks) == 1 else "are"} found. ')
  1978. if submitting:
  1979. msg += 'The CL must be approved by one of the following reviewers:'
  1980. else:
  1981. msg += 'Please request review from one of the following reviewers:'
  1982. for r in required_reviewers:
  1983. msg += f'\n * {r}'
  1984. return [output_api.PresubmitError(msg)]
  1985. @functools.lru_cache(maxsize=None)
  1986. def _ParseDeps(contents):
  1987. """Simple helper for parsing DEPS files."""
  1988. # Stubs for handling special syntax in the root DEPS file.
  1989. class _VarImpl:
  1990. def __init__(self, local_scope):
  1991. self._local_scope = local_scope
  1992. def Lookup(self, var_name):
  1993. """Implements the Var syntax."""
  1994. try:
  1995. return self._local_scope['vars'][var_name]
  1996. except KeyError:
  1997. raise Exception('Var is not defined: %s' % var_name)
  1998. local_scope = {}
  1999. global_scope = {
  2000. 'Var': _VarImpl(local_scope).Lookup,
  2001. 'Str': str,
  2002. }
  2003. exec(contents, global_scope, local_scope)
  2004. return local_scope
  2005. def CheckVPythonSpec(input_api, output_api, file_filter=None):
  2006. """Validates any changed .vpython and .vpython3 files with vpython
  2007. verification tool.
  2008. Args:
  2009. input_api: Bag of input related interfaces.
  2010. output_api: Bag of output related interfaces.
  2011. file_filter: Custom function that takes a path (relative to client root) and
  2012. returns boolean, which is used to filter files for which to apply the
  2013. verification to. Defaults to any path ending with .vpython(3), which captures
  2014. both global .vpython(3) and <script>.vpython(3) files.
  2015. Returns:
  2016. A list of input_api.Command objects containing verification commands.
  2017. """
  2018. file_filter = file_filter or (lambda f: f.LocalPath().endswith('.vpython')
  2019. or f.LocalPath().endswith('.vpython3'))
  2020. affected_files = input_api.AffectedTestableFiles(file_filter=file_filter)
  2021. affected_files = map(lambda f: f.AbsoluteLocalPath(), affected_files)
  2022. commands = []
  2023. for f in affected_files:
  2024. commands.append(
  2025. input_api.Command('Verify %s' % f, [
  2026. input_api.python3_executable, '-vpython-spec', f,
  2027. '-vpython-tool', 'verify'
  2028. ], {'stderr': input_api.subprocess.STDOUT},
  2029. output_api.PresubmitError))
  2030. return commands
  2031. def CheckChangedLUCIConfigs(input_api, output_api):
  2032. """Validates the changed config file against LUCI Config.
  2033. Only return the warning and/or error for files in input_api.AffectedFiles().
  2034. Assumes `lucicfg` binary is in PATH and the user is logged in.
  2035. Returns:
  2036. A list presubmit errors and/or warnings from the validation result of files
  2037. in input_api.AffectedFiles()
  2038. """
  2039. import json
  2040. import logging
  2041. import auth
  2042. import git_cl
  2043. LUCI_CONFIG_HOST_NAME = 'config.luci.app'
  2044. cl = git_cl.Changelist()
  2045. if input_api.gerrit:
  2046. if input_api.change.issue:
  2047. remote_branch = input_api.gerrit.GetDestRef(input_api.change.issue)
  2048. else:
  2049. remote_branch = input_api.gerrit.branch
  2050. else:
  2051. remote, remote_branch = cl.GetRemoteBranch()
  2052. if remote_branch.startswith('refs/remotes/%s/' % remote):
  2053. remote_branch = remote_branch.replace('refs/remotes/%s/' % remote,
  2054. 'refs/heads/', 1)
  2055. if remote_branch.startswith('refs/remotes/branch-heads/'):
  2056. remote_branch = remote_branch.replace('refs/remotes/branch-heads/',
  2057. 'refs/branch-heads/', 1)
  2058. if input_api.gerrit:
  2059. host = input_api.gerrit.host
  2060. project = input_api.gerrit.project
  2061. gerrit_url = f'https://{host}/{project}'
  2062. remote_host_url = gerrit_url.replace('-review.googlesource',
  2063. '.googlesource')
  2064. else:
  2065. remote_host_url = cl.GetRemoteUrl()
  2066. if not remote_host_url:
  2067. return [
  2068. output_api.PresubmitError(
  2069. 'Remote host url for git has not been defined')
  2070. ]
  2071. remote_host_url = remote_host_url.rstrip('/')
  2072. if remote_host_url.endswith('.git'):
  2073. remote_host_url = remote_host_url[:-len('.git')]
  2074. # authentication
  2075. try:
  2076. acc_tkn = auth.Authenticator(audience='https://%s' %
  2077. LUCI_CONFIG_HOST_NAME).get_id_token()
  2078. except auth.LoginRequiredError as e:
  2079. return [
  2080. output_api.PresubmitError('Error in authenticating user.',
  2081. long_text=str(e))
  2082. ]
  2083. def request(method, body, max_attempts=3):
  2084. """"Calls luci-config v2 method and returns a parsed json response."""
  2085. api_url = 'https://%s/prpc/config.service.v2.Configs/%s' % (
  2086. LUCI_CONFIG_HOST_NAME, method)
  2087. req = input_api.urllib_request.Request(api_url)
  2088. req.add_header('Authorization', 'Bearer %s' % acc_tkn.token)
  2089. req.data = json.dumps(body).encode('utf-8')
  2090. req.add_header('Accept', 'application/json')
  2091. req.add_header('Content-Type', 'application/json')
  2092. attempt = 0
  2093. res = None
  2094. time_to_sleep = 1
  2095. while True:
  2096. try:
  2097. res = input_api.urllib_request.urlopen(req)
  2098. break
  2099. except input_api.urllib_error.HTTPError as e:
  2100. if attempt < max_attempts and e.code >= 500:
  2101. attempt += 1
  2102. logging.debug('error when calling %s: %s\n'
  2103. 'Sleeping for %d seconds and retrying...' %
  2104. (api_url, e, time_to_sleep))
  2105. time.sleep(time_to_sleep)
  2106. time_to_sleep *= 2
  2107. continue
  2108. raise
  2109. assert res, 'response from luci-config v2 is impossible to be None'
  2110. # The JSON response has a XSSI protection prefix )]}'
  2111. return json.loads(res.read().decode('utf-8')[len(")]}'"):].strip())
  2112. def format_config_set(cs):
  2113. """convert luci-config v2 config_set object to v1 format."""
  2114. rev = cs.get('revision', {})
  2115. return {
  2116. 'config_set': cs.get('name'),
  2117. 'location': cs.get('url'),
  2118. 'revision': {
  2119. 'id': rev.get('id'),
  2120. 'url': rev.get('url'),
  2121. 'timestamp': rev.get('timestamp'),
  2122. 'committer_email': rev.get('committerEmail')
  2123. }
  2124. }
  2125. try:
  2126. config_sets = request('ListConfigSets', {}).get('configSets')
  2127. except input_api.urllib_error.HTTPError as e:
  2128. return [
  2129. output_api.PresubmitError(
  2130. 'Config set request to luci-config failed', long_text=str(e))
  2131. ]
  2132. config_sets = [format_config_set(cs) for cs in config_sets]
  2133. if not config_sets:
  2134. return [
  2135. output_api.PresubmitPromptWarning('No config_sets were returned')
  2136. ]
  2137. loc_pref = '%s/+/%s/' % (remote_host_url, remote_branch)
  2138. logging.debug('Derived location prefix: %s', loc_pref)
  2139. dir_to_config_set = {}
  2140. for cs in config_sets:
  2141. if cs['location'].startswith(loc_pref) or ('%s/' %
  2142. cs['location']) == loc_pref:
  2143. path = cs['location'][len(loc_pref):].rstrip('/')
  2144. d = input_api.os_path.join(*path.split('/')) if path else '.'
  2145. dir_to_config_set[d] = cs['config_set']
  2146. if not dir_to_config_set:
  2147. warning_long_text_lines = [
  2148. 'No config_set found for %s.' % loc_pref,
  2149. 'Found the following:',
  2150. ]
  2151. for loc in sorted(cs['location'] for cs in config_sets):
  2152. warning_long_text_lines.append(' %s' % loc)
  2153. warning_long_text_lines.append('')
  2154. warning_long_text_lines.append('If the requested location is internal,'
  2155. ' the requester may not have access.')
  2156. return [
  2157. output_api.PresubmitPromptWarning(
  2158. warning_long_text_lines[0],
  2159. long_text='\n'.join(warning_long_text_lines))
  2160. ]
  2161. dir_to_fileSet = {}
  2162. for f in input_api.AffectedFiles(include_deletes=False):
  2163. for d in dir_to_config_set:
  2164. if d != '.' and not f.LocalPath().startswith(d):
  2165. continue # file doesn't belong to this config set
  2166. rel_path = f.LocalPath() if d == '.' else input_api.os_path.relpath(
  2167. f.LocalPath(), start=d)
  2168. fileSet = dir_to_fileSet.setdefault(d, set())
  2169. fileSet.add(rel_path.replace(_os.sep, '/'))
  2170. dir_to_fileSet[d] = fileSet
  2171. outputs = []
  2172. lucicfg = 'lucicfg' if not input_api.is_windows else 'lucicfg.bat'
  2173. log_level = 'debug' if input_api.verbose else 'warning'
  2174. repo_root = input_api.change.RepositoryRoot()
  2175. for d, fileSet in dir_to_fileSet.items():
  2176. config_set = dir_to_config_set[d]
  2177. with input_api.CreateTemporaryFile() as f:
  2178. cmd = [
  2179. lucicfg, 'validate', d, '-config-set', config_set, '-log-level',
  2180. log_level, '-json-output', f.name
  2181. ]
  2182. # return code is not important as the validation failure will be
  2183. # retrieved from the output json file.
  2184. out, _ = input_api.subprocess.communicate(
  2185. cmd,
  2186. stderr=input_api.subprocess.PIPE,
  2187. shell=input_api.is_windows, # to resolve *.bat
  2188. cwd=repo_root,
  2189. )
  2190. logging.debug('running %s\nSTDOUT:\n%s\nSTDERR:\n%s', cmd, out[0],
  2191. out[1])
  2192. try:
  2193. result = json.load(f)
  2194. except json.JSONDecodeError as e:
  2195. outputs.append(
  2196. output_api.PresubmitError(
  2197. 'Error when parsing lucicfg validate output',
  2198. long_text=str(e)))
  2199. else:
  2200. result = result.get('result', None)
  2201. if result:
  2202. non_affected_file_msg_count = 0
  2203. for validation_result in (result.get('validation', None)
  2204. or []):
  2205. for msg in (validation_result.get('messages', None)
  2206. or []):
  2207. if d != '.' and msg['path'] not in fileSet:
  2208. non_affected_file_msg_count += 1
  2209. continue
  2210. sev = msg['severity']
  2211. if sev == 'WARNING':
  2212. out_f = output_api.PresubmitPromptWarning
  2213. elif sev in ('ERROR', 'CRITICAL'):
  2214. out_f = output_api.PresubmitError
  2215. else:
  2216. out_f = output_api.PresubmitNotifyResult
  2217. outputs.append(
  2218. out_f('Config validation for file(%s): %s' %
  2219. (msg['path'], msg['text'])))
  2220. if non_affected_file_msg_count:
  2221. reproduce_cmd = [
  2222. lucicfg, 'validate',
  2223. repo_root if d == '.' else input_api.os_path.join(
  2224. repo_root, d), '-config-set', config_set
  2225. ]
  2226. outputs.append(
  2227. output_api.PresubmitPromptWarning(
  2228. 'Found %d additional errors/warnings in files that are not '
  2229. 'modified, run `%s` to reveal them' %
  2230. (non_affected_file_msg_count,
  2231. ' '.join(reproduce_cmd))))
  2232. return outputs
  2233. def CheckLucicfgGenOutput(input_api, output_api, entry_script):
  2234. """Verifies configs produced by `lucicfg` are up-to-date and pass validation.
  2235. Runs the check unconditionally, regardless of what files are modified. Examine
  2236. input_api.AffectedFiles() yourself before using CheckLucicfgGenOutput if this
  2237. is a concern.
  2238. Assumes `lucicfg` binary is in PATH and the user is logged in.
  2239. Args:
  2240. entry_script: path to the entry-point *.star script responsible for
  2241. generating a single config set. Either absolute or relative to the
  2242. currently running PRESUBMIT.py script.
  2243. Returns:
  2244. A list of input_api.Command objects containing verification commands.
  2245. """
  2246. return [
  2247. input_api.Command(
  2248. 'lucicfg validate "%s"' % entry_script,
  2249. [
  2250. 'lucicfg' if not input_api.is_windows else 'lucicfg.bat',
  2251. 'validate',
  2252. entry_script,
  2253. '-log-level',
  2254. 'debug' if input_api.verbose else 'warning',
  2255. ],
  2256. {
  2257. 'stderr': input_api.subprocess.STDOUT,
  2258. 'shell': input_api.is_windows, # to resolve *.bat
  2259. 'cwd': input_api.PresubmitLocalPath(),
  2260. },
  2261. output_api.PresubmitError)
  2262. ]
  2263. def CheckJsonParses(input_api, output_api, file_filter=None):
  2264. """Verifies that all JSON files at least parse as valid JSON. By default,
  2265. file_filter will look for all files that end with .json"""
  2266. import json
  2267. if file_filter is None:
  2268. file_filter = lambda x: x.LocalPath().endswith('.json')
  2269. affected_files = input_api.AffectedFiles(include_deletes=False,
  2270. file_filter=file_filter)
  2271. warnings = []
  2272. for f in affected_files:
  2273. with _io.open(f.AbsoluteLocalPath(), encoding='utf-8') as j:
  2274. try:
  2275. json.load(j)
  2276. except json.JSONDecodeError:
  2277. # Just a warning for now, in case people are using JSON5
  2278. # somewhere.
  2279. warnings.append(
  2280. output_api.PresubmitPromptWarning(
  2281. f"{f.LocalPath()} doesn't appear to be valid JSON.",
  2282. locations=[
  2283. output_api.PresubmitResultLocation(
  2284. file_path=f.LocalPath()),
  2285. ]))
  2286. return warnings
  2287. # string pattern, sequence of strings to show when pattern matches,
  2288. # error flag. True if match is a presubmit error, otherwise it's a warning.
  2289. _NON_INCLUSIVE_TERMS = (
  2290. (
  2291. # Note that \b pattern in python re is pretty particular. In this
  2292. # regexp, 'class WhiteList ...' will match, but 'class FooWhiteList
  2293. # ...' will not. This may require some tweaking to catch these cases
  2294. # without triggering a lot of false positives. Leaving it naive and
  2295. # less matchy for now.
  2296. r'/(?i)\b((black|white)list|slave)\b', # nocheck
  2297. (
  2298. 'Please don\'t use blacklist, whitelist, ' # nocheck
  2299. 'or slave in your', # nocheck
  2300. 'code and make every effort to use other terms. Using "// nocheck"',
  2301. '"# nocheck" or "<!-- nocheck -->"',
  2302. 'at the end of the offending line will bypass this PRESUBMIT error',
  2303. 'but avoid using this whenever possible. Reach out to',
  2304. 'community@chromium.org if you have questions'),
  2305. True), )
  2306. def _GetMessageForMatchingTerm(input_api, affected_file, line_number, line,
  2307. term, message):
  2308. """Helper method for CheckInclusiveLanguage.
  2309. Returns an string composed of the name of the file, the line number where the
  2310. match has been found and the additional text passed as |message| in case the
  2311. target type name matches the text inside the line passed as parameter.
  2312. """
  2313. result = []
  2314. # A // nocheck comment will bypass this error.
  2315. if line.endswith(" nocheck") or line.endswith("<!-- nocheck -->"):
  2316. return result
  2317. # Ignore C-style single-line comments about banned terms.
  2318. if input_api.re.search(r"//.*$", line):
  2319. line = input_api.re.sub(r"//.*$", "", line)
  2320. # Ignore lines from C-style multi-line comments.
  2321. if input_api.re.search(r"^\s*\*", line):
  2322. return result
  2323. # Ignore Python-style comments about banned terms.
  2324. # This actually removes comment text from the first # on.
  2325. if input_api.re.search(r"#.*$", line):
  2326. line = input_api.re.sub(r"#.*$", "", line)
  2327. matched = False
  2328. if term[0:1] == '/':
  2329. regex = term[1:]
  2330. if input_api.re.search(regex, line):
  2331. matched = True
  2332. elif term in line:
  2333. matched = True
  2334. if matched:
  2335. result.append(' %s:%d:' % (affected_file.LocalPath(), line_number))
  2336. for message_line in message:
  2337. result.append(' %s' % message_line)
  2338. return result
  2339. def CheckInclusiveLanguage(input_api,
  2340. output_api,
  2341. excluded_directories_relative_path=None,
  2342. non_inclusive_terms=_NON_INCLUSIVE_TERMS):
  2343. """Make sure that banned non-inclusive terms are not used."""
  2344. # Presubmit checks may run on a bot where the changes are actually
  2345. # in a repo that isn't chromium/src (e.g., when testing src + tip-of-tree
  2346. # ANGLE), but this particular check only makes sense for changes to
  2347. # chromium/src.
  2348. if input_api.change.RepositoryRoot() != input_api.PresubmitLocalPath():
  2349. return []
  2350. if input_api.no_diffs:
  2351. return []
  2352. warnings = []
  2353. errors = []
  2354. if excluded_directories_relative_path is None:
  2355. excluded_directories_relative_path = [
  2356. 'infra', 'inclusive_language_presubmit_exempt_dirs.txt'
  2357. ]
  2358. # Note that this matches exact path prefixes, and does not match
  2359. # subdirectories. Only files directly in an excluded path will
  2360. # match.
  2361. def IsExcludedFile(affected_file, excluded_paths):
  2362. local_dir = input_api.os_path.dirname(affected_file.LocalPath())
  2363. # Excluded paths use forward slashes.
  2364. if input_api.platform == 'win32':
  2365. local_dir = local_dir.replace('\\', '/')
  2366. return local_dir in excluded_paths
  2367. def CheckForMatch(affected_file, line_num, line, term, message, error):
  2368. problems = _GetMessageForMatchingTerm(input_api, affected_file,
  2369. line_num, line, term, message)
  2370. if problems:
  2371. if error:
  2372. errors.extend(problems)
  2373. else:
  2374. warnings.extend(problems)
  2375. excluded_paths = []
  2376. excluded_directories_relative_path = input_api.os_path.join(
  2377. *excluded_directories_relative_path)
  2378. dirs_file_path = input_api.os_path.join(input_api.change.RepositoryRoot(),
  2379. excluded_directories_relative_path)
  2380. f = input_api.ReadFile(dirs_file_path)
  2381. for line in f.splitlines():
  2382. words = line.split()
  2383. # if a line starts with #, followed by a whitespace or line-end,
  2384. # it's a comment line.
  2385. if len(words) == 0 or words[0] == '#' or words[0] == '':
  2386. continue
  2387. # The first word in each line is a path.
  2388. # Some exempt_dirs.txt files may have additional words in each line
  2389. # (e.g., "third_party 1 2")
  2390. #
  2391. ## The additional words are present in legacy files for historical
  2392. # reasons only. DO NOT parse or require these additional words.
  2393. excluded_paths.append(words[0])
  2394. excluded_paths = set(excluded_paths)
  2395. for f in input_api.AffectedFiles():
  2396. for line_num, line in f.ChangedContents():
  2397. for term, message, error in non_inclusive_terms:
  2398. if IsExcludedFile(f, excluded_paths):
  2399. continue
  2400. CheckForMatch(f, line_num, line, term, message, error)
  2401. result = []
  2402. if (warnings):
  2403. result.append(
  2404. output_api.PresubmitPromptWarning(
  2405. 'Banned non-inclusive language was used.\n\n' +
  2406. 'If this is third-party code, please consider updating ' +
  2407. excluded_directories_relative_path + ' if appropriate.\n\n' +
  2408. '\n'.join(warnings)))
  2409. if (errors):
  2410. result.append(
  2411. output_api.PresubmitError(
  2412. 'Banned non-inclusive language was used.\n\n' +
  2413. 'If this is third-party code, please consider updating ' +
  2414. excluded_directories_relative_path + ' if appropriate.\n\n' +
  2415. '\n'.join(errors)))
  2416. return result
  2417. def CheckUpdateOwnersFileReferences(input_api, output_api):
  2418. """Checks whether an OWNERS file is being (re)moved and if so asks the
  2419. contributor to update any file:// references to it."""
  2420. files = []
  2421. # AffectedFiles() includes owner files, not AffectedSourceFiles().
  2422. for f in input_api.AffectedFiles():
  2423. # Moved files appear here as one deletion and one addition.
  2424. if f.LocalPath().endswith('OWNERS') and f.Action() == 'D':
  2425. files.append(f.LocalPath())
  2426. if not files:
  2427. return []
  2428. return [
  2429. output_api.PresubmitPromptWarning(
  2430. 'OWNERS files being moved/removed, please update any file:// ' +
  2431. 'references to them in other OWNERS files', files)
  2432. ]