PRESUBMIT.py 225 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847
  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. """Top-level presubmit script for Chromium.
  5. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
  6. for more details about the presubmit API built into depot_tools.
  7. """
  8. from typing import Optional
  9. from typing import Sequence
  10. from dataclasses import dataclass
  11. PRESUBMIT_VERSION = '2.0.0'
  12. # This line is 'magic' in that git-cl looks for it to decide whether to
  13. # use Python3 instead of Python2 when running the code in this file.
  14. USE_PYTHON3 = True
  15. _EXCLUDED_PATHS = (
  16. # File needs to write to stdout to emulate a tool it's replacing.
  17. r"chrome[\\/]updater[\\/]mac[\\/]keystone[\\/]ksadmin.mm",
  18. # Generated file.
  19. (r"^components[\\/]variations[\\/]proto[\\/]devtools[\\/]"
  20. r"client_variations.js"),
  21. r"^native_client_sdksrc[\\/]build_tools[\\/]make_rules.py",
  22. r"^native_client_sdk[\\/]src[\\/]build_tools[\\/]make_simple.py",
  23. r"^native_client_sdk[\\/]src[\\/]tools[\\/].*.mk",
  24. r"^net[\\/]tools[\\/]spdyshark[\\/].*",
  25. r"^skia[\\/].*",
  26. r"^third_party[\\/]blink[\\/].*",
  27. r"^third_party[\\/]breakpad[\\/].*",
  28. # sqlite is an imported third party dependency.
  29. r"^third_party[\\/]sqlite[\\/].*",
  30. r"^v8[\\/].*",
  31. r".*MakeFile$",
  32. r".+_autogen\.h$",
  33. r".+_pb2\.py$",
  34. r".+[\\/]pnacl_shim\.c$",
  35. r"^gpu[\\/]config[\\/].*_list_json\.cc$",
  36. r"tools[\\/]md_browser[\\/].*\.css$",
  37. # Test pages for Maps telemetry tests.
  38. r"tools[\\/]perf[\\/]page_sets[\\/]maps_perf_test.*",
  39. # Test pages for WebRTC telemetry tests.
  40. r"tools[\\/]perf[\\/]page_sets[\\/]webrtc_cases.*",
  41. )
  42. _EXCLUDED_SET_NO_PARENT_PATHS = (
  43. # It's for historical reasons that blink isn't a top level directory, where
  44. # it would be allowed to have "set noparent" to avoid top level owners
  45. # accidentally +1ing changes.
  46. 'third_party/blink/OWNERS',
  47. )
  48. # Fragment of a regular expression that matches C++ and Objective-C++
  49. # implementation files.
  50. _IMPLEMENTATION_EXTENSIONS = r'\.(cc|cpp|cxx|mm)$'
  51. # Fragment of a regular expression that matches C++ and Objective-C++
  52. # header files.
  53. _HEADER_EXTENSIONS = r'\.(h|hpp|hxx)$'
  54. # Regular expression that matches code only used for test binaries
  55. # (best effort).
  56. _TEST_CODE_EXCLUDED_PATHS = (
  57. r'.*[\\/](fake_|test_|mock_).+%s' % _IMPLEMENTATION_EXTENSIONS,
  58. r'.+_test_(base|support|util)%s' % _IMPLEMENTATION_EXTENSIONS,
  59. # Test suite files, like:
  60. # foo_browsertest.cc
  61. # bar_unittest_mac.cc (suffix)
  62. # baz_unittests.cc (plural)
  63. r'.+_(api|browser|eg|int|perf|pixel|unit|ui)?test(s)?(_[a-z]+)?%s' %
  64. _IMPLEMENTATION_EXTENSIONS,
  65. r'.+_(fuzz|fuzzer)(_[a-z]+)?%s' % _IMPLEMENTATION_EXTENSIONS,
  66. r'.+sync_service_impl_harness%s' % _IMPLEMENTATION_EXTENSIONS,
  67. r'.*[\\/](test|tool(s)?)[\\/].*',
  68. # content_shell is used for running content_browsertests.
  69. r'content[\\/]shell[\\/].*',
  70. # Web test harness.
  71. r'content[\\/]web_test[\\/].*',
  72. # Non-production example code.
  73. r'mojo[\\/]examples[\\/].*',
  74. # Launcher for running iOS tests on the simulator.
  75. r'testing[\\/]iossim[\\/]iossim\.mm$',
  76. # EarlGrey app side code for tests.
  77. r'ios[\\/].*_app_interface\.mm$',
  78. # Views Examples code
  79. r'ui[\\/]views[\\/]examples[\\/].*',
  80. # Chromium Codelab
  81. r'codelabs[\\/]*'
  82. )
  83. _THIRD_PARTY_EXCEPT_BLINK = 'third_party/(?!blink/)'
  84. _TEST_ONLY_WARNING = (
  85. 'You might be calling functions intended only for testing from\n'
  86. 'production code. If you are doing this from inside another method\n'
  87. 'named as *ForTesting(), then consider exposing things to have tests\n'
  88. 'make that same call directly.\n'
  89. 'If that is not possible, you may put a comment on the same line with\n'
  90. ' // IN-TEST \n'
  91. 'to tell the PRESUBMIT script that the code is inside a *ForTesting()\n'
  92. 'method and can be ignored. Do not do this inside production code.\n'
  93. 'The android-binary-size trybot will block if the method exists in the\n'
  94. 'release apk.')
  95. @dataclass
  96. class BanRule:
  97. # String pattern. If the pattern begins with a slash, the pattern will be
  98. # treated as a regular expression instead.
  99. pattern: str
  100. # Explanation as a sequence of strings. Each string in the sequence will be
  101. # printed on its own line.
  102. explanation: Sequence[str]
  103. # Whether or not to treat this ban as a fatal error. If unspecified, defaults
  104. # to true.
  105. treat_as_error: Optional[bool] = None
  106. # Paths that should be excluded from the ban check. Each string is a regular
  107. # expression that will be matched against the path of the file being checked
  108. # relative to the root of the source tree.
  109. excluded_paths: Optional[Sequence[str]] = None
  110. _BANNED_JAVA_IMPORTS : Sequence[BanRule] = (
  111. BanRule(
  112. 'import java.net.URI;',
  113. (
  114. 'Use org.chromium.url.GURL instead of java.net.URI, where possible.',
  115. ),
  116. excluded_paths=(
  117. (r'net/android/javatests/src/org/chromium/net/'
  118. 'AndroidProxySelectorTest\.java'),
  119. r'components/cronet/',
  120. r'third_party/robolectric/local/',
  121. ),
  122. ),
  123. BanRule(
  124. 'import android.annotation.TargetApi;',
  125. (
  126. 'Do not use TargetApi, use @androidx.annotation.RequiresApi instead. '
  127. 'RequiresApi ensures that any calls are guarded by the appropriate '
  128. 'SDK_INT check. See https://crbug.com/1116486.',
  129. ),
  130. ),
  131. BanRule(
  132. 'import android.support.test.rule.UiThreadTestRule;',
  133. (
  134. 'Do not use UiThreadTestRule, just use '
  135. '@org.chromium.base.test.UiThreadTest on test methods that should run '
  136. 'on the UI thread. See https://crbug.com/1111893.',
  137. ),
  138. ),
  139. BanRule(
  140. 'import android.support.test.annotation.UiThreadTest;',
  141. ('Do not use android.support.test.annotation.UiThreadTest, use '
  142. 'org.chromium.base.test.UiThreadTest instead. See '
  143. 'https://crbug.com/1111893.',
  144. ),
  145. ),
  146. BanRule(
  147. 'import android.support.test.rule.ActivityTestRule;',
  148. (
  149. 'Do not use ActivityTestRule, use '
  150. 'org.chromium.base.test.BaseActivityTestRule instead.',
  151. ),
  152. excluded_paths=(
  153. 'components/cronet/',
  154. ),
  155. ),
  156. )
  157. _BANNED_JAVA_FUNCTIONS : Sequence[BanRule] = (
  158. BanRule(
  159. 'StrictMode.allowThreadDiskReads()',
  160. (
  161. 'Prefer using StrictModeContext.allowDiskReads() to using StrictMode '
  162. 'directly.',
  163. ),
  164. False,
  165. ),
  166. BanRule(
  167. 'StrictMode.allowThreadDiskWrites()',
  168. (
  169. 'Prefer using StrictModeContext.allowDiskWrites() to using StrictMode '
  170. 'directly.',
  171. ),
  172. False,
  173. ),
  174. BanRule(
  175. '.waitForIdleSync()',
  176. (
  177. 'Do not use waitForIdleSync as it masks underlying issues. There is '
  178. 'almost always something else you should wait on instead.',
  179. ),
  180. False,
  181. ),
  182. )
  183. _BANNED_OBJC_FUNCTIONS : Sequence[BanRule] = (
  184. BanRule(
  185. 'addTrackingRect:',
  186. (
  187. 'The use of -[NSView addTrackingRect:owner:userData:assumeInside:] is'
  188. 'prohibited. Please use CrTrackingArea instead.',
  189. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  190. ),
  191. False,
  192. ),
  193. BanRule(
  194. r'/NSTrackingArea\W',
  195. (
  196. 'The use of NSTrackingAreas is prohibited. Please use CrTrackingArea',
  197. 'instead.',
  198. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  199. ),
  200. False,
  201. ),
  202. BanRule(
  203. 'convertPointFromBase:',
  204. (
  205. 'The use of -[NSView convertPointFromBase:] is almost certainly wrong.',
  206. 'Please use |convertPoint:(point) fromView:nil| instead.',
  207. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  208. ),
  209. True,
  210. ),
  211. BanRule(
  212. 'convertPointToBase:',
  213. (
  214. 'The use of -[NSView convertPointToBase:] is almost certainly wrong.',
  215. 'Please use |convertPoint:(point) toView:nil| instead.',
  216. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  217. ),
  218. True,
  219. ),
  220. BanRule(
  221. 'convertRectFromBase:',
  222. (
  223. 'The use of -[NSView convertRectFromBase:] is almost certainly wrong.',
  224. 'Please use |convertRect:(point) fromView:nil| instead.',
  225. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  226. ),
  227. True,
  228. ),
  229. BanRule(
  230. 'convertRectToBase:',
  231. (
  232. 'The use of -[NSView convertRectToBase:] is almost certainly wrong.',
  233. 'Please use |convertRect:(point) toView:nil| instead.',
  234. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  235. ),
  236. True,
  237. ),
  238. BanRule(
  239. 'convertSizeFromBase:',
  240. (
  241. 'The use of -[NSView convertSizeFromBase:] is almost certainly wrong.',
  242. 'Please use |convertSize:(point) fromView:nil| instead.',
  243. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  244. ),
  245. True,
  246. ),
  247. BanRule(
  248. 'convertSizeToBase:',
  249. (
  250. 'The use of -[NSView convertSizeToBase:] is almost certainly wrong.',
  251. 'Please use |convertSize:(point) toView:nil| instead.',
  252. 'http://dev.chromium.org/developers/coding-style/cocoa-dos-and-donts',
  253. ),
  254. True,
  255. ),
  256. BanRule(
  257. r"/\s+UTF8String\s*]",
  258. (
  259. 'The use of -[NSString UTF8String] is dangerous as it can return null',
  260. 'even if |canBeConvertedToEncoding:NSUTF8StringEncoding| returns YES.',
  261. 'Please use |SysNSStringToUTF8| instead.',
  262. ),
  263. True,
  264. ),
  265. BanRule(
  266. r'__unsafe_unretained',
  267. (
  268. 'The use of __unsafe_unretained is almost certainly wrong, unless',
  269. 'when interacting with NSFastEnumeration or NSInvocation.',
  270. 'Please use __weak in files build with ARC, nothing otherwise.',
  271. ),
  272. False,
  273. ),
  274. BanRule(
  275. 'freeWhenDone:NO',
  276. (
  277. 'The use of "freeWhenDone:NO" with the NoCopy creation of ',
  278. 'Foundation types is prohibited.',
  279. ),
  280. True,
  281. ),
  282. )
  283. _BANNED_IOS_OBJC_FUNCTIONS = (
  284. BanRule(
  285. r'/\bTEST[(]',
  286. (
  287. 'TEST() macro should not be used in Objective-C++ code as it does not ',
  288. 'drain the autorelease pool at the end of the test. Use TEST_F() ',
  289. 'macro instead with a fixture inheriting from PlatformTest (or a ',
  290. 'typedef).'
  291. ),
  292. True,
  293. ),
  294. BanRule(
  295. r'/\btesting::Test\b',
  296. (
  297. 'testing::Test should not be used in Objective-C++ code as it does ',
  298. 'not drain the autorelease pool at the end of the test. Use ',
  299. 'PlatformTest instead.'
  300. ),
  301. True,
  302. ),
  303. )
  304. _BANNED_IOS_EGTEST_FUNCTIONS : Sequence[BanRule] = (
  305. BanRule(
  306. r'/\bEXPECT_OCMOCK_VERIFY\b',
  307. (
  308. 'EXPECT_OCMOCK_VERIFY should not be used in EarlGrey tests because ',
  309. 'it is meant for GTests. Use [mock verify] instead.'
  310. ),
  311. True,
  312. ),
  313. )
  314. _BANNED_CPP_FUNCTIONS : Sequence[BanRule] = (
  315. BanRule(
  316. r'/\busing namespace ',
  317. (
  318. 'Using directives ("using namespace x") are banned by the Google Style',
  319. 'Guide ( http://google.github.io/styleguide/cppguide.html#Namespaces ).',
  320. 'Explicitly qualify symbols or use using declarations ("using x::foo").',
  321. ),
  322. True,
  323. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  324. ),
  325. # Make sure that gtest's FRIEND_TEST() macro is not used; the
  326. # FRIEND_TEST_ALL_PREFIXES() macro from base/gtest_prod_util.h should be
  327. # used instead since that allows for FLAKY_ and DISABLED_ prefixes.
  328. BanRule(
  329. 'FRIEND_TEST(',
  330. (
  331. 'Chromium code should not use gtest\'s FRIEND_TEST() macro. Include',
  332. 'base/gtest_prod_util.h and use FRIEND_TEST_ALL_PREFIXES() instead.',
  333. ),
  334. False,
  335. (),
  336. ),
  337. BanRule(
  338. 'setMatrixClip',
  339. (
  340. 'Overriding setMatrixClip() is prohibited; ',
  341. 'the base function is deprecated. ',
  342. ),
  343. True,
  344. (),
  345. ),
  346. BanRule(
  347. 'SkRefPtr',
  348. (
  349. 'The use of SkRefPtr is prohibited. ',
  350. 'Please use sk_sp<> instead.'
  351. ),
  352. True,
  353. (),
  354. ),
  355. BanRule(
  356. 'SkAutoRef',
  357. (
  358. 'The indirect use of SkRefPtr via SkAutoRef is prohibited. ',
  359. 'Please use sk_sp<> instead.'
  360. ),
  361. True,
  362. (),
  363. ),
  364. BanRule(
  365. 'SkAutoTUnref',
  366. (
  367. 'The use of SkAutoTUnref is dangerous because it implicitly ',
  368. 'converts to a raw pointer. Please use sk_sp<> instead.'
  369. ),
  370. True,
  371. (),
  372. ),
  373. BanRule(
  374. 'SkAutoUnref',
  375. (
  376. 'The indirect use of SkAutoTUnref through SkAutoUnref is dangerous ',
  377. 'because it implicitly converts to a raw pointer. ',
  378. 'Please use sk_sp<> instead.'
  379. ),
  380. True,
  381. (),
  382. ),
  383. BanRule(
  384. r'/HANDLE_EINTR\(.*close',
  385. (
  386. 'HANDLE_EINTR(close) is invalid. If close fails with EINTR, the file',
  387. 'descriptor will be closed, and it is incorrect to retry the close.',
  388. 'Either call close directly and ignore its return value, or wrap close',
  389. 'in IGNORE_EINTR to use its return value. See http://crbug.com/269623'
  390. ),
  391. True,
  392. (),
  393. ),
  394. BanRule(
  395. r'/IGNORE_EINTR\((?!.*close)',
  396. (
  397. 'IGNORE_EINTR is only valid when wrapping close. To wrap other system',
  398. 'calls, use HANDLE_EINTR. See http://crbug.com/269623',
  399. ),
  400. True,
  401. (
  402. # Files that #define IGNORE_EINTR.
  403. r'^base[\\/]posix[\\/]eintr_wrapper\.h$',
  404. r'^ppapi[\\/]tests[\\/]test_broker\.cc$',
  405. ),
  406. ),
  407. BanRule(
  408. r'/v8::Extension\(',
  409. (
  410. 'Do not introduce new v8::Extensions into the code base, use',
  411. 'gin::Wrappable instead. See http://crbug.com/334679',
  412. ),
  413. True,
  414. (
  415. r'extensions[\\/]renderer[\\/]safe_builtins\.*',
  416. ),
  417. ),
  418. BanRule(
  419. '#pragma comment(lib,',
  420. (
  421. 'Specify libraries to link with in build files and not in the source.',
  422. ),
  423. True,
  424. (
  425. r'^base[\\/]third_party[\\/]symbolize[\\/].*',
  426. r'^third_party[\\/]abseil-cpp[\\/].*',
  427. ),
  428. ),
  429. BanRule(
  430. r'/base::SequenceChecker\b',
  431. (
  432. 'Consider using SEQUENCE_CHECKER macros instead of the class directly.',
  433. ),
  434. False,
  435. (),
  436. ),
  437. BanRule(
  438. r'/base::ThreadChecker\b',
  439. (
  440. 'Consider using THREAD_CHECKER macros instead of the class directly.',
  441. ),
  442. False,
  443. (),
  444. ),
  445. BanRule(
  446. r'/(Time(|Delta|Ticks)|ThreadTicks)::FromInternalValue|ToInternalValue',
  447. (
  448. 'base::TimeXXX::FromInternalValue() and ToInternalValue() are',
  449. 'deprecated (http://crbug.com/634507). Please avoid converting away',
  450. 'from the Time types in Chromium code, especially if any math is',
  451. 'being done on time values. For interfacing with platform/library',
  452. 'APIs, use FromMicroseconds() or InMicroseconds(), or one of the other',
  453. 'type converter methods instead. For faking TimeXXX values (for unit',
  454. 'testing only), use TimeXXX() + Microseconds(N). For',
  455. 'other use cases, please contact base/time/OWNERS.',
  456. ),
  457. False,
  458. (),
  459. ),
  460. BanRule(
  461. 'CallJavascriptFunctionUnsafe',
  462. (
  463. "Don't use CallJavascriptFunctionUnsafe() in new code. Instead, use",
  464. 'AllowJavascript(), OnJavascriptAllowed()/OnJavascriptDisallowed(),',
  465. 'and CallJavascriptFunction(). See https://goo.gl/qivavq.',
  466. ),
  467. False,
  468. (
  469. r'^content[\\/]browser[\\/]webui[\\/]web_ui_impl\.(cc|h)$',
  470. r'^content[\\/]public[\\/]browser[\\/]web_ui\.h$',
  471. r'^content[\\/]public[\\/]test[\\/]test_web_ui\.(cc|h)$',
  472. ),
  473. ),
  474. BanRule(
  475. 'leveldb::DB::Open',
  476. (
  477. 'Instead of leveldb::DB::Open() use leveldb_env::OpenDB() from',
  478. 'third_party/leveldatabase/env_chromium.h. It exposes databases to',
  479. "Chrome's tracing, making their memory usage visible.",
  480. ),
  481. True,
  482. (
  483. r'^third_party/leveldatabase/.*\.(cc|h)$',
  484. ),
  485. ),
  486. BanRule(
  487. 'leveldb::NewMemEnv',
  488. (
  489. 'Instead of leveldb::NewMemEnv() use leveldb_chrome::NewMemEnv() from',
  490. 'third_party/leveldatabase/leveldb_chrome.h. It exposes environments',
  491. "to Chrome's tracing, making their memory usage visible.",
  492. ),
  493. True,
  494. (
  495. r'^third_party/leveldatabase/.*\.(cc|h)$',
  496. ),
  497. ),
  498. BanRule(
  499. 'RunLoop::QuitCurrent',
  500. (
  501. 'Please migrate away from RunLoop::QuitCurrent*() methods. Use member',
  502. 'methods of a specific RunLoop instance instead.',
  503. ),
  504. False,
  505. (),
  506. ),
  507. BanRule(
  508. 'base::ScopedMockTimeMessageLoopTaskRunner',
  509. (
  510. 'ScopedMockTimeMessageLoopTaskRunner is deprecated. Prefer',
  511. 'TaskEnvironment::TimeSource::MOCK_TIME. There are still a',
  512. 'few cases that may require a ScopedMockTimeMessageLoopTaskRunner',
  513. '(i.e. mocking the main MessageLoopForUI in browser_tests), but check',
  514. 'with gab@ first if you think you need it)',
  515. ),
  516. False,
  517. (),
  518. ),
  519. BanRule(
  520. 'std::regex',
  521. (
  522. 'Using std::regex adds unnecessary binary size to Chrome. Please use',
  523. 're2::RE2 instead (crbug.com/755321)',
  524. ),
  525. True,
  526. # Abseil's benchmarks never linked into chrome.
  527. ['third_party/abseil-cpp/.*_benchmark.cc'],
  528. ),
  529. BanRule(
  530. r'/\bstd::stoi\b',
  531. (
  532. 'std::stoi uses exceptions to communicate results. ',
  533. 'Use base::StringToInt() instead.',
  534. ),
  535. True,
  536. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  537. ),
  538. BanRule(
  539. r'/\bstd::stol\b',
  540. (
  541. 'std::stol uses exceptions to communicate results. ',
  542. 'Use base::StringToInt() instead.',
  543. ),
  544. True,
  545. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  546. ),
  547. BanRule(
  548. r'/\bstd::stoul\b',
  549. (
  550. 'std::stoul uses exceptions to communicate results. ',
  551. 'Use base::StringToUint() instead.',
  552. ),
  553. True,
  554. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  555. ),
  556. BanRule(
  557. r'/\bstd::stoll\b',
  558. (
  559. 'std::stoll uses exceptions to communicate results. ',
  560. 'Use base::StringToInt64() instead.',
  561. ),
  562. True,
  563. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  564. ),
  565. BanRule(
  566. r'/\bstd::stoull\b',
  567. (
  568. 'std::stoull uses exceptions to communicate results. ',
  569. 'Use base::StringToUint64() instead.',
  570. ),
  571. True,
  572. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  573. ),
  574. BanRule(
  575. r'/\bstd::stof\b',
  576. (
  577. 'std::stof uses exceptions to communicate results. ',
  578. 'For locale-independent values, e.g. reading numbers from disk',
  579. 'profiles, use base::StringToDouble().',
  580. 'For user-visible values, parse using ICU.',
  581. ),
  582. True,
  583. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  584. ),
  585. BanRule(
  586. r'/\bstd::stod\b',
  587. (
  588. 'std::stod uses exceptions to communicate results. ',
  589. 'For locale-independent values, e.g. reading numbers from disk',
  590. 'profiles, use base::StringToDouble().',
  591. 'For user-visible values, parse using ICU.',
  592. ),
  593. True,
  594. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  595. ),
  596. BanRule(
  597. r'/\bstd::stold\b',
  598. (
  599. 'std::stold uses exceptions to communicate results. ',
  600. 'For locale-independent values, e.g. reading numbers from disk',
  601. 'profiles, use base::StringToDouble().',
  602. 'For user-visible values, parse using ICU.',
  603. ),
  604. True,
  605. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  606. ),
  607. BanRule(
  608. r'/\bstd::to_string\b',
  609. (
  610. 'std::to_string is locale dependent and slower than alternatives.',
  611. 'For locale-independent strings, e.g. writing numbers to disk',
  612. 'profiles, use base::NumberToString().',
  613. 'For user-visible strings, use base::FormatNumber() and',
  614. 'the related functions in base/i18n/number_formatting.h.',
  615. ),
  616. False, # Only a warning since it is already used.
  617. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  618. ),
  619. BanRule(
  620. r'/\bstd::shared_ptr\b',
  621. (
  622. 'std::shared_ptr should not be used. Use scoped_refptr instead.',
  623. ),
  624. True,
  625. [
  626. # Needed for interop with third-party library.
  627. '^third_party/blink/renderer/core/typed_arrays/array_buffer/' +
  628. 'array_buffer_contents\.(cc|h)',
  629. '^third_party/blink/renderer/bindings/core/v8/' +
  630. 'v8_wasm_response_extensions.cc',
  631. '^gin/array_buffer\.(cc|h)',
  632. '^chrome/services/sharing/nearby/',
  633. # gRPC provides some C++ libraries that use std::shared_ptr<>.
  634. '^chromeos/services/libassistant/grpc/',
  635. '^chromecast/cast_core/grpc',
  636. '^chromecast/cast_core/runtime/browser',
  637. # Fuchsia provides C++ libraries that use std::shared_ptr<>.
  638. '.*fuchsia.*test\.(cc|h)',
  639. # Needed for clang plugin tests
  640. '^tools/clang/plugins/tests/',
  641. _THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  642. ),
  643. BanRule(
  644. r'/\bstd::weak_ptr\b',
  645. (
  646. 'std::weak_ptr should not be used. Use base::WeakPtr instead.',
  647. ),
  648. True,
  649. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  650. ),
  651. BanRule(
  652. r'/\blong long\b',
  653. (
  654. 'long long is banned. Use stdint.h if you need a 64 bit number.',
  655. ),
  656. False, # Only a warning since it is already used.
  657. [_THIRD_PARTY_EXCEPT_BLINK], # Don't warn in third_party folders.
  658. ),
  659. BanRule(
  660. r'\b(absl|std)::any\b',
  661. (
  662. 'absl::any / std::any are not safe to use in a component build.',
  663. ),
  664. True,
  665. # Not an error in third party folders, though it probably should be :)
  666. [_THIRD_PARTY_EXCEPT_BLINK],
  667. ),
  668. BanRule(
  669. r'/\bstd::bind\b',
  670. (
  671. 'std::bind is banned because of lifetime risks.',
  672. 'Use base::BindOnce or base::BindRepeating instead.',
  673. ),
  674. True,
  675. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  676. ),
  677. BanRule(
  678. r'/\bstd::optional\b',
  679. (
  680. 'std::optional is banned. Use absl::optional instead.',
  681. ),
  682. True,
  683. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  684. ),
  685. BanRule(
  686. r'/\b#include <chrono>\b',
  687. (
  688. '<chrono> overlaps with Time APIs in base. Keep using',
  689. 'base classes.',
  690. ),
  691. True,
  692. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  693. ),
  694. BanRule(
  695. r'/\b#include <exception>\b',
  696. (
  697. 'Exceptions are banned and disabled in Chromium.',
  698. ),
  699. True,
  700. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  701. ),
  702. BanRule(
  703. r'/\bstd::function\b',
  704. (
  705. 'std::function is banned. Instead use base::OnceCallback or ',
  706. 'base::RepeatingCallback, which directly support Chromium\'s weak ',
  707. 'pointers, ref counting and more.',
  708. ),
  709. False, # Only a warning since it is already used.
  710. [_THIRD_PARTY_EXCEPT_BLINK], # Do not warn in third_party folders.
  711. ),
  712. BanRule(
  713. r'/\b#include <random>\b',
  714. (
  715. 'Do not use any random number engines from <random>. Instead',
  716. 'use base::RandomBitGenerator.',
  717. ),
  718. True,
  719. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  720. ),
  721. BanRule(
  722. r'/\b#include <X11/',
  723. (
  724. 'Do not use Xlib. Use xproto (from //ui/gfx/x:xproto) instead.',
  725. ),
  726. True,
  727. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  728. ),
  729. BanRule(
  730. r'/\bstd::ratio\b',
  731. (
  732. 'std::ratio is banned by the Google Style Guide.',
  733. ),
  734. True,
  735. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  736. ),
  737. BanRule(
  738. ('base::ThreadRestrictions::ScopedAllowIO'),
  739. (
  740. 'ScopedAllowIO is deprecated, use ScopedAllowBlocking instead.',
  741. ),
  742. False,
  743. (),
  744. ),
  745. BanRule(
  746. r'/\bRunMessageLoop\b',
  747. (
  748. 'RunMessageLoop is deprecated, use RunLoop instead.',
  749. ),
  750. False,
  751. (),
  752. ),
  753. BanRule(
  754. 'RunThisRunLoop',
  755. (
  756. 'RunThisRunLoop is deprecated, use RunLoop directly instead.',
  757. ),
  758. False,
  759. (),
  760. ),
  761. BanRule(
  762. 'RunAllPendingInMessageLoop()',
  763. (
  764. "Prefer RunLoop over RunAllPendingInMessageLoop, please contact gab@",
  765. "if you're convinced you need this.",
  766. ),
  767. False,
  768. (),
  769. ),
  770. BanRule(
  771. 'RunAllPendingInMessageLoop(BrowserThread',
  772. (
  773. 'RunAllPendingInMessageLoop is deprecated. Use RunLoop for',
  774. 'BrowserThread::UI, BrowserTaskEnvironment::RunIOThreadUntilIdle',
  775. 'for BrowserThread::IO, and prefer RunLoop::QuitClosure to observe',
  776. 'async events instead of flushing threads.',
  777. ),
  778. False,
  779. (),
  780. ),
  781. BanRule(
  782. r'MessageLoopRunner',
  783. (
  784. 'MessageLoopRunner is deprecated, use RunLoop instead.',
  785. ),
  786. False,
  787. (),
  788. ),
  789. BanRule(
  790. 'GetDeferredQuitTaskForRunLoop',
  791. (
  792. "GetDeferredQuitTaskForRunLoop shouldn't be needed, please contact",
  793. "gab@ if you found a use case where this is the only solution.",
  794. ),
  795. False,
  796. (),
  797. ),
  798. BanRule(
  799. 'sqlite3_initialize(',
  800. (
  801. 'Instead of calling sqlite3_initialize(), depend on //sql, ',
  802. '#include "sql/initialize.h" and use sql::EnsureSqliteInitialized().',
  803. ),
  804. True,
  805. (
  806. r'^sql/initialization\.(cc|h)$',
  807. r'^third_party/sqlite/.*\.(c|cc|h)$',
  808. ),
  809. ),
  810. BanRule(
  811. 'std::random_shuffle',
  812. (
  813. 'std::random_shuffle is deprecated in C++14, and removed in C++17. Use',
  814. 'base::RandomShuffle instead.'
  815. ),
  816. True,
  817. (),
  818. ),
  819. BanRule(
  820. 'ios/web/public/test/http_server',
  821. (
  822. 'web::HTTPserver is deprecated use net::EmbeddedTestServer instead.',
  823. ),
  824. False,
  825. (),
  826. ),
  827. BanRule(
  828. 'GetAddressOf',
  829. (
  830. 'Improper use of Microsoft::WRL::ComPtr<T>::GetAddressOf() has been ',
  831. 'implicated in a few leaks. ReleaseAndGetAddressOf() is safe but ',
  832. 'operator& is generally recommended. So always use operator& instead. ',
  833. 'See http://crbug.com/914910 for more conversion guidance.'
  834. ),
  835. True,
  836. (),
  837. ),
  838. BanRule(
  839. 'SHFileOperation',
  840. (
  841. 'SHFileOperation was deprecated in Windows Vista, and there are less ',
  842. 'complex functions to achieve the same goals. Use IFileOperation for ',
  843. 'any esoteric actions instead.'
  844. ),
  845. True,
  846. (),
  847. ),
  848. BanRule(
  849. 'StringFromGUID2',
  850. (
  851. 'StringFromGUID2 introduces an unnecessary dependency on ole32.dll.',
  852. 'Use base::win::WStringFromGUID instead.'
  853. ),
  854. True,
  855. (
  856. r'/base/win/win_util_unittest.cc',
  857. ),
  858. ),
  859. BanRule(
  860. 'StringFromCLSID',
  861. (
  862. 'StringFromCLSID introduces an unnecessary dependency on ole32.dll.',
  863. 'Use base::win::WStringFromGUID instead.'
  864. ),
  865. True,
  866. (
  867. r'/base/win/win_util_unittest.cc',
  868. ),
  869. ),
  870. BanRule(
  871. 'kCFAllocatorNull',
  872. (
  873. 'The use of kCFAllocatorNull with the NoCopy creation of ',
  874. 'CoreFoundation types is prohibited.',
  875. ),
  876. True,
  877. (),
  878. ),
  879. BanRule(
  880. 'mojo::ConvertTo',
  881. (
  882. 'mojo::ConvertTo and TypeConverter are deprecated. Please consider',
  883. 'StructTraits / UnionTraits / EnumTraits / ArrayTraits / MapTraits /',
  884. 'StringTraits if you would like to convert between custom types and',
  885. 'the wire format of mojom types.'
  886. ),
  887. False,
  888. (
  889. r'^fuchsia/engine/browser/url_request_rewrite_rules_manager\.cc$',
  890. r'^fuchsia/engine/url_request_rewrite_type_converters\.cc$',
  891. r'^third_party/blink/.*\.(cc|h)$',
  892. r'^content/renderer/.*\.(cc|h)$',
  893. ),
  894. ),
  895. BanRule(
  896. 'GetInterfaceProvider',
  897. (
  898. 'InterfaceProvider is deprecated.',
  899. 'Please use ExecutionContext::GetBrowserInterfaceBroker and overrides',
  900. 'or Platform::GetBrowserInterfaceBroker.'
  901. ),
  902. False,
  903. (),
  904. ),
  905. BanRule(
  906. 'CComPtr',
  907. (
  908. 'New code should use Microsoft::WRL::ComPtr from wrl/client.h as a ',
  909. 'replacement for CComPtr from ATL. See http://crbug.com/5027 for more ',
  910. 'details.'
  911. ),
  912. False,
  913. (),
  914. ),
  915. BanRule(
  916. r'/\b(IFACE|STD)METHOD_?\(',
  917. (
  918. 'IFACEMETHOD() and STDMETHOD() make code harder to format and read.',
  919. 'Instead, always use IFACEMETHODIMP in the declaration.'
  920. ),
  921. False,
  922. [_THIRD_PARTY_EXCEPT_BLINK], # Not an error in third_party folders.
  923. ),
  924. BanRule(
  925. 'set_owned_by_client',
  926. (
  927. 'set_owned_by_client is deprecated.',
  928. 'views::View already owns the child views by default. This introduces ',
  929. 'a competing ownership model which makes the code difficult to reason ',
  930. 'about. See http://crbug.com/1044687 for more details.'
  931. ),
  932. False,
  933. (),
  934. ),
  935. BanRule(
  936. 'RemoveAllChildViewsWithoutDeleting',
  937. (
  938. 'RemoveAllChildViewsWithoutDeleting is deprecated.',
  939. 'This method is deemed dangerous as, unless raw pointers are re-added,',
  940. 'calls to this method introduce memory leaks.'
  941. ),
  942. False,
  943. (),
  944. ),
  945. BanRule(
  946. r'/\bTRACE_EVENT_ASYNC_',
  947. (
  948. 'Please use TRACE_EVENT_NESTABLE_ASYNC_.. macros instead',
  949. 'of TRACE_EVENT_ASYNC_.. (crbug.com/1038710).',
  950. ),
  951. False,
  952. (
  953. r'^base/trace_event/.*',
  954. r'^base/tracing/.*',
  955. ),
  956. ),
  957. BanRule(
  958. r'/\bbase::debug::DumpWithoutCrashingUnthrottled[(][)]',
  959. (
  960. 'base::debug::DumpWithoutCrashingUnthrottled() does not throttle',
  961. 'dumps and may spam crash reports. Consider if the throttled',
  962. 'variants suffice instead.',
  963. ),
  964. False,
  965. (),
  966. ),
  967. BanRule(
  968. 'RoInitialize',
  969. (
  970. 'Improper use of [base::win]::RoInitialize() has been implicated in a ',
  971. 'few COM initialization leaks. Use base::win::ScopedWinrtInitializer ',
  972. 'instead. See http://crbug.com/1197722 for more information.'
  973. ),
  974. True,
  975. (
  976. r'^base[\\/]win[\\/]scoped_winrt_initializer\.cc$',
  977. ),
  978. ),
  979. )
  980. _BANNED_MOJOM_PATTERNS : Sequence[BanRule] = (
  981. BanRule(
  982. 'handle<shared_buffer>',
  983. (
  984. 'Please use one of the more specific shared memory types instead:',
  985. ' mojo_base.mojom.ReadOnlySharedMemoryRegion',
  986. ' mojo_base.mojom.WritableSharedMemoryRegion',
  987. ' mojo_base.mojom.UnsafeSharedMemoryRegion',
  988. ),
  989. True,
  990. ),
  991. )
  992. _IPC_ENUM_TRAITS_DEPRECATED = (
  993. 'You are using IPC_ENUM_TRAITS() in your code. It has been deprecated.\n'
  994. 'See http://www.chromium.org/Home/chromium-security/education/'
  995. 'security-tips-for-ipc')
  996. _LONG_PATH_ERROR = (
  997. 'Some files included in this CL have file names that are too long (> 200'
  998. ' characters). If committed, these files will cause issues on Windows. See'
  999. ' https://crbug.com/612667 for more details.'
  1000. )
  1001. _JAVA_MULTIPLE_DEFINITION_EXCLUDED_PATHS = [
  1002. r".*[\\/]AppHooksImpl\.java",
  1003. r".*[\\/]BuildHooksAndroidImpl\.java",
  1004. r".*[\\/]LicenseContentProvider\.java",
  1005. r".*[\\/]PlatformServiceBridgeImpl.java",
  1006. r".*chrome[\\\/]android[\\\/]feed[\\\/]dummy[\\\/].*\.java",
  1007. ]
  1008. # List of image extensions that are used as resources in chromium.
  1009. _IMAGE_EXTENSIONS = ['.svg', '.png', '.webp']
  1010. # These paths contain test data and other known invalid JSON files.
  1011. _KNOWN_TEST_DATA_AND_INVALID_JSON_FILE_PATTERNS = [
  1012. r'test[\\/]data[\\/]',
  1013. r'testing[\\/]buildbot[\\/]',
  1014. r'^components[\\/]policy[\\/]resources[\\/]policy_templates\.json$',
  1015. r'^third_party[\\/]protobuf[\\/]',
  1016. r'^third_party[\\/]blink[\\/]renderer[\\/]devtools[\\/]protocol\.json$',
  1017. r'^third_party[\\/]blink[\\/]web_tests[\\/]external[\\/]wpt[\\/]',
  1018. ]
  1019. # These are not checked on the public chromium-presubmit trybot.
  1020. # Add files here that rely on .py files that exists only for target_os="android"
  1021. # checkouts.
  1022. _ANDROID_SPECIFIC_PYDEPS_FILES = [
  1023. 'chrome/android/features/create_stripped_java_factory.pydeps',
  1024. ]
  1025. _GENERIC_PYDEPS_FILES = [
  1026. 'android_webview/tools/run_cts.pydeps',
  1027. 'base/android/jni_generator/jni_generator.pydeps',
  1028. 'base/android/jni_generator/jni_registration_generator.pydeps',
  1029. 'build/android/apk_operations.pydeps',
  1030. 'build/android/devil_chromium.pydeps',
  1031. 'build/android/gyp/aar.pydeps',
  1032. 'build/android/gyp/aidl.pydeps',
  1033. 'build/android/gyp/allot_native_libraries.pydeps',
  1034. 'build/android/gyp/apkbuilder.pydeps',
  1035. 'build/android/gyp/assert_static_initializers.pydeps',
  1036. 'build/android/gyp/bytecode_processor.pydeps',
  1037. 'build/android/gyp/bytecode_rewriter.pydeps',
  1038. 'build/android/gyp/check_flag_expectations.pydeps',
  1039. 'build/android/gyp/compile_java.pydeps',
  1040. 'build/android/gyp/compile_resources.pydeps',
  1041. 'build/android/gyp/copy_ex.pydeps',
  1042. 'build/android/gyp/create_apk_operations_script.pydeps',
  1043. 'build/android/gyp/create_app_bundle.pydeps',
  1044. 'build/android/gyp/create_app_bundle_apks.pydeps',
  1045. 'build/android/gyp/create_bundle_wrapper_script.pydeps',
  1046. 'build/android/gyp/create_java_binary_script.pydeps',
  1047. 'build/android/gyp/create_r_java.pydeps',
  1048. 'build/android/gyp/create_r_txt.pydeps',
  1049. 'build/android/gyp/create_size_info_files.pydeps',
  1050. 'build/android/gyp/create_ui_locale_resources.pydeps',
  1051. 'build/android/gyp/dex.pydeps',
  1052. 'build/android/gyp/dex_jdk_libs.pydeps',
  1053. 'build/android/gyp/dexsplitter.pydeps',
  1054. 'build/android/gyp/dist_aar.pydeps',
  1055. 'build/android/gyp/filter_zip.pydeps',
  1056. 'build/android/gyp/flatc_java.pydeps',
  1057. 'build/android/gyp/gcc_preprocess.pydeps',
  1058. 'build/android/gyp/generate_linker_version_script.pydeps',
  1059. 'build/android/gyp/ijar.pydeps',
  1060. 'build/android/gyp/jacoco_instr.pydeps',
  1061. 'build/android/gyp/java_cpp_enum.pydeps',
  1062. 'build/android/gyp/java_cpp_features.pydeps',
  1063. 'build/android/gyp/java_cpp_strings.pydeps',
  1064. 'build/android/gyp/java_google_api_keys.pydeps',
  1065. 'build/android/gyp/jetify_jar.pydeps',
  1066. 'build/android/gyp/jinja_template.pydeps',
  1067. 'build/android/gyp/lint.pydeps',
  1068. 'build/android/gyp/merge_manifest.pydeps',
  1069. 'build/android/gyp/prepare_resources.pydeps',
  1070. 'build/android/gyp/process_native_prebuilt.pydeps',
  1071. 'build/android/gyp/proguard.pydeps',
  1072. 'build/android/gyp/turbine.pydeps',
  1073. 'build/android/gyp/unused_resources.pydeps',
  1074. 'build/android/gyp/validate_static_library_dex_references.pydeps',
  1075. 'build/android/gyp/write_build_config.pydeps',
  1076. 'build/android/gyp/write_native_libraries_java.pydeps',
  1077. 'build/android/gyp/zip.pydeps',
  1078. 'build/android/incremental_install/generate_android_manifest.pydeps',
  1079. 'build/android/incremental_install/write_installer_json.pydeps',
  1080. 'build/android/resource_sizes.pydeps',
  1081. 'build/android/test_runner.pydeps',
  1082. 'build/android/test_wrapper/logdog_wrapper.pydeps',
  1083. 'build/lacros/lacros_resource_sizes.pydeps',
  1084. 'build/protoc_java.pydeps',
  1085. 'chrome/android/monochrome/scripts/monochrome_python_tests.pydeps',
  1086. 'chrome/test/chromedriver/log_replay/client_replay_unittest.pydeps',
  1087. 'chrome/test/chromedriver/test/run_py_tests.pydeps',
  1088. 'chromecast/resource_sizes/chromecast_resource_sizes.pydeps',
  1089. 'components/cronet/tools/generate_javadoc.pydeps',
  1090. 'components/cronet/tools/jar_src.pydeps',
  1091. 'components/module_installer/android/module_desc_java.pydeps',
  1092. 'content/public/android/generate_child_service.pydeps',
  1093. 'net/tools/testserver/testserver.pydeps',
  1094. 'testing/scripts/run_android_wpt.pydeps',
  1095. 'testing/scripts/run_isolated_script_test.pydeps',
  1096. 'testing/merge_scripts/standard_isolated_script_merge.pydeps',
  1097. 'testing/merge_scripts/standard_gtest_merge.pydeps',
  1098. 'testing/merge_scripts/code_coverage/merge_results.pydeps',
  1099. 'testing/merge_scripts/code_coverage/merge_steps.pydeps',
  1100. 'third_party/android_platform/development/scripts/stack.pydeps',
  1101. 'third_party/blink/renderer/bindings/scripts/build_web_idl_database.pydeps',
  1102. 'third_party/blink/renderer/bindings/scripts/collect_idl_files.pydeps',
  1103. 'third_party/blink/renderer/bindings/scripts/generate_bindings.pydeps',
  1104. 'third_party/blink/renderer/bindings/scripts/validate_web_idl.pydeps',
  1105. 'third_party/blink/tools/blinkpy/web_tests/merge_results.pydeps',
  1106. 'third_party/blink/tools/merge_web_test_results.pydeps',
  1107. 'tools/binary_size/sizes.pydeps',
  1108. 'tools/binary_size/supersize.pydeps',
  1109. ]
  1110. _ALL_PYDEPS_FILES = _ANDROID_SPECIFIC_PYDEPS_FILES + _GENERIC_PYDEPS_FILES
  1111. # Bypass the AUTHORS check for these accounts.
  1112. _KNOWN_ROBOTS = set(
  1113. ) | set('%s@appspot.gserviceaccount.com' % s for s in ('findit-for-me',)
  1114. ) | set('%s@developer.gserviceaccount.com' % s for s in ('3su6n15k.default',)
  1115. ) | set('%s@chops-service-accounts.iam.gserviceaccount.com' % s
  1116. for s in ('bling-autoroll-builder', 'v8-ci-autoroll-builder',
  1117. 'wpt-autoroller', 'chrome-weblayer-builder',
  1118. 'lacros-version-skew-roller', 'skylab-test-cros-roller',
  1119. 'infra-try-recipes-tester', 'lacros-tracking-roller')
  1120. ) | set('%s@skia-public.iam.gserviceaccount.com' % s
  1121. for s in ('chromium-autoroll', 'chromium-release-autoroll')
  1122. ) | set('%s@skia-corp.google.com.iam.gserviceaccount.com' % s
  1123. for s in ('chromium-internal-autoroll',)
  1124. ) | set('%s@owners-cleanup-prod.google.com.iam.gserviceaccount.com' % s
  1125. for s in ('swarming-tasks',))
  1126. _INVALID_GRD_FILE_LINE = [
  1127. (r'<file lang=.* path=.*', 'Path should come before lang in GRD files.')
  1128. ]
  1129. def _IsCPlusPlusFile(input_api, file_path):
  1130. """Returns True if this file contains C++-like code (and not Python,
  1131. Go, Java, MarkDown, ...)"""
  1132. ext = input_api.os_path.splitext(file_path)[1]
  1133. # This list is compatible with CppChecker.IsCppFile but we should
  1134. # consider adding ".c" to it. If we do that we can use this function
  1135. # at more places in the code.
  1136. return ext in (
  1137. '.h',
  1138. '.cc',
  1139. '.cpp',
  1140. '.m',
  1141. '.mm',
  1142. )
  1143. def _IsCPlusPlusHeaderFile(input_api, file_path):
  1144. return input_api.os_path.splitext(file_path)[1] == ".h"
  1145. def _IsJavaFile(input_api, file_path):
  1146. return input_api.os_path.splitext(file_path)[1] == ".java"
  1147. def _IsProtoFile(input_api, file_path):
  1148. return input_api.os_path.splitext(file_path)[1] == ".proto"
  1149. def _IsXmlOrGrdFile(input_api, file_path):
  1150. ext = input_api.os_path.splitext(file_path)[1]
  1151. return ext in ('.grd', '.xml')
  1152. def CheckNoUpstreamDepsOnClank(input_api, output_api):
  1153. """Prevent additions of dependencies from the upstream repo on //clank."""
  1154. # clank can depend on clank
  1155. if input_api.change.RepositoryRoot().endswith('clank'):
  1156. return []
  1157. build_file_patterns = [
  1158. r'(.+/)?BUILD\.gn',
  1159. r'.+\.gni',
  1160. ]
  1161. excluded_files = [r'build[/\\]config[/\\]android[/\\]config\.gni']
  1162. bad_pattern = input_api.re.compile(r'^[^#]*//clank')
  1163. error_message = 'Disallowed import on //clank in an upstream build file:'
  1164. def FilterFile(affected_file):
  1165. return input_api.FilterSourceFile(affected_file,
  1166. files_to_check=build_file_patterns,
  1167. files_to_skip=excluded_files)
  1168. problems = []
  1169. for f in input_api.AffectedSourceFiles(FilterFile):
  1170. local_path = f.LocalPath()
  1171. for line_number, line in f.ChangedContents():
  1172. if (bad_pattern.search(line)):
  1173. problems.append('%s:%d\n %s' %
  1174. (local_path, line_number, line.strip()))
  1175. if problems:
  1176. return [output_api.PresubmitPromptOrNotify(error_message, problems)]
  1177. else:
  1178. return []
  1179. def CheckNoProductionCodeUsingTestOnlyFunctions(input_api, output_api):
  1180. """Attempts to prevent use of functions intended only for testing in
  1181. non-testing code. For now this is just a best-effort implementation
  1182. that ignores header files and may have some false positives. A
  1183. better implementation would probably need a proper C++ parser.
  1184. """
  1185. # We only scan .cc files and the like, as the declaration of
  1186. # for-testing functions in header files are hard to distinguish from
  1187. # calls to such functions without a proper C++ parser.
  1188. file_inclusion_pattern = [r'.+%s' % _IMPLEMENTATION_EXTENSIONS]
  1189. base_function_pattern = r'[ :]test::[^\s]+|ForTest(s|ing)?|for_test(s|ing)?'
  1190. inclusion_pattern = input_api.re.compile(r'(%s)\s*\(' %
  1191. base_function_pattern)
  1192. comment_pattern = input_api.re.compile(r'//.*(%s)' % base_function_pattern)
  1193. allowlist_pattern = input_api.re.compile(r'// IN-TEST$')
  1194. exclusion_pattern = input_api.re.compile(
  1195. r'::[A-Za-z0-9_]+(%s)|(%s)[^;]+\{' %
  1196. (base_function_pattern, base_function_pattern))
  1197. # Avoid a false positive in this case, where the method name, the ::, and
  1198. # the closing { are all on different lines due to line wrapping.
  1199. # HelperClassForTesting::
  1200. # HelperClassForTesting(
  1201. # args)
  1202. # : member(0) {}
  1203. method_defn_pattern = input_api.re.compile(r'[A-Za-z0-9_]+::$')
  1204. def FilterFile(affected_file):
  1205. files_to_skip = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  1206. input_api.DEFAULT_FILES_TO_SKIP)
  1207. return input_api.FilterSourceFile(
  1208. affected_file,
  1209. files_to_check=file_inclusion_pattern,
  1210. files_to_skip=files_to_skip)
  1211. problems = []
  1212. for f in input_api.AffectedSourceFiles(FilterFile):
  1213. local_path = f.LocalPath()
  1214. in_method_defn = False
  1215. for line_number, line in f.ChangedContents():
  1216. if (inclusion_pattern.search(line)
  1217. and not comment_pattern.search(line)
  1218. and not exclusion_pattern.search(line)
  1219. and not allowlist_pattern.search(line)
  1220. and not in_method_defn):
  1221. problems.append('%s:%d\n %s' %
  1222. (local_path, line_number, line.strip()))
  1223. in_method_defn = method_defn_pattern.search(line)
  1224. if problems:
  1225. return [
  1226. output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)
  1227. ]
  1228. else:
  1229. return []
  1230. def CheckNoProductionCodeUsingTestOnlyFunctionsJava(input_api, output_api):
  1231. """This is a simplified version of
  1232. CheckNoProductionCodeUsingTestOnlyFunctions for Java files.
  1233. """
  1234. javadoc_start_re = input_api.re.compile(r'^\s*/\*\*')
  1235. javadoc_end_re = input_api.re.compile(r'^\s*\*/')
  1236. name_pattern = r'ForTest(s|ing)?'
  1237. # Describes an occurrence of "ForTest*" inside a // comment.
  1238. comment_re = input_api.re.compile(r'//.*%s' % name_pattern)
  1239. # Describes @VisibleForTesting(otherwise = VisibleForTesting.PROTECTED)
  1240. annotation_re = input_api.re.compile(r'@VisibleForTesting\(')
  1241. # Catch calls.
  1242. inclusion_re = input_api.re.compile(r'(%s)\s*\(' % name_pattern)
  1243. # Ignore definitions. (Comments are ignored separately.)
  1244. exclusion_re = input_api.re.compile(r'(%s)[^;]+\{' % name_pattern)
  1245. problems = []
  1246. sources = lambda x: input_api.FilterSourceFile(
  1247. x,
  1248. files_to_skip=(('(?i).*test', r'.*\/junit\/') + input_api.
  1249. DEFAULT_FILES_TO_SKIP),
  1250. files_to_check=[r'.*\.java$'])
  1251. for f in input_api.AffectedFiles(include_deletes=False,
  1252. file_filter=sources):
  1253. local_path = f.LocalPath()
  1254. is_inside_javadoc = False
  1255. for line_number, line in f.ChangedContents():
  1256. if is_inside_javadoc and javadoc_end_re.search(line):
  1257. is_inside_javadoc = False
  1258. if not is_inside_javadoc and javadoc_start_re.search(line):
  1259. is_inside_javadoc = True
  1260. if is_inside_javadoc:
  1261. continue
  1262. if (inclusion_re.search(line) and not comment_re.search(line)
  1263. and not annotation_re.search(line)
  1264. and not exclusion_re.search(line)):
  1265. problems.append('%s:%d\n %s' %
  1266. (local_path, line_number, line.strip()))
  1267. if problems:
  1268. return [
  1269. output_api.PresubmitPromptOrNotify(_TEST_ONLY_WARNING, problems)
  1270. ]
  1271. else:
  1272. return []
  1273. def CheckNoIOStreamInHeaders(input_api, output_api):
  1274. """Checks to make sure no .h files include <iostream>."""
  1275. files = []
  1276. pattern = input_api.re.compile(r'^#include\s*<iostream>',
  1277. input_api.re.MULTILINE)
  1278. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  1279. if not f.LocalPath().endswith('.h'):
  1280. continue
  1281. contents = input_api.ReadFile(f)
  1282. if pattern.search(contents):
  1283. files.append(f)
  1284. if len(files):
  1285. return [
  1286. output_api.PresubmitError(
  1287. 'Do not #include <iostream> in header files, since it inserts static '
  1288. 'initialization into every file including the header. Instead, '
  1289. '#include <ostream>. See http://crbug.com/94794', files)
  1290. ]
  1291. return []
  1292. def _CheckNoStrCatRedefines(input_api, output_api):
  1293. """Checks no windows headers with StrCat redefined are included directly."""
  1294. files = []
  1295. pattern_deny = input_api.re.compile(
  1296. r'^#include\s*[<"](shlwapi|atlbase|propvarutil|sphelper).h[">]',
  1297. input_api.re.MULTILINE)
  1298. pattern_allow = input_api.re.compile(
  1299. r'^#include\s"base/win/windows_defines.inc"', input_api.re.MULTILINE)
  1300. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  1301. contents = input_api.ReadFile(f)
  1302. if pattern_deny.search(
  1303. contents) and not pattern_allow.search(contents):
  1304. files.append(f.LocalPath())
  1305. if len(files):
  1306. return [
  1307. output_api.PresubmitError(
  1308. 'Do not #include shlwapi.h, atlbase.h, propvarutil.h or sphelper.h '
  1309. 'directly since they pollute code with StrCat macro. Instead, '
  1310. 'include matching header from base/win. See http://crbug.com/856536',
  1311. files)
  1312. ]
  1313. return []
  1314. def CheckNoUNIT_TESTInSourceFiles(input_api, output_api):
  1315. """Checks to make sure no source files use UNIT_TEST."""
  1316. problems = []
  1317. for f in input_api.AffectedFiles():
  1318. if (not f.LocalPath().endswith(('.cc', '.mm'))):
  1319. continue
  1320. for line_num, line in f.ChangedContents():
  1321. if 'UNIT_TEST ' in line or line.endswith('UNIT_TEST'):
  1322. problems.append(' %s:%d' % (f.LocalPath(), line_num))
  1323. if not problems:
  1324. return []
  1325. return [
  1326. output_api.PresubmitPromptWarning('UNIT_TEST is only for headers.\n' +
  1327. '\n'.join(problems))
  1328. ]
  1329. def CheckNoDISABLETypoInTests(input_api, output_api):
  1330. """Checks to prevent attempts to disable tests with DISABLE_ prefix.
  1331. This test warns if somebody tries to disable a test with the DISABLE_ prefix
  1332. instead of DISABLED_. To filter false positives, reports are only generated
  1333. if a corresponding MAYBE_ line exists.
  1334. """
  1335. problems = []
  1336. # The following two patterns are looked for in tandem - is a test labeled
  1337. # as MAYBE_ followed by a DISABLE_ (instead of the correct DISABLED)
  1338. maybe_pattern = input_api.re.compile(r'MAYBE_([a-zA-Z0-9_]+)')
  1339. disable_pattern = input_api.re.compile(r'DISABLE_([a-zA-Z0-9_]+)')
  1340. # This is for the case that a test is disabled on all platforms.
  1341. full_disable_pattern = input_api.re.compile(
  1342. r'^\s*TEST[^(]*\([a-zA-Z0-9_]+,\s*DISABLE_[a-zA-Z0-9_]+\)',
  1343. input_api.re.MULTILINE)
  1344. for f in input_api.AffectedFiles(False):
  1345. if not 'test' in f.LocalPath() or not f.LocalPath().endswith('.cc'):
  1346. continue
  1347. # Search for MABYE_, DISABLE_ pairs.
  1348. disable_lines = {} # Maps of test name to line number.
  1349. maybe_lines = {}
  1350. for line_num, line in f.ChangedContents():
  1351. disable_match = disable_pattern.search(line)
  1352. if disable_match:
  1353. disable_lines[disable_match.group(1)] = line_num
  1354. maybe_match = maybe_pattern.search(line)
  1355. if maybe_match:
  1356. maybe_lines[maybe_match.group(1)] = line_num
  1357. # Search for DISABLE_ occurrences within a TEST() macro.
  1358. disable_tests = set(disable_lines.keys())
  1359. maybe_tests = set(maybe_lines.keys())
  1360. for test in disable_tests.intersection(maybe_tests):
  1361. problems.append(' %s:%d' % (f.LocalPath(), disable_lines[test]))
  1362. contents = input_api.ReadFile(f)
  1363. full_disable_match = full_disable_pattern.search(contents)
  1364. if full_disable_match:
  1365. problems.append(' %s' % f.LocalPath())
  1366. if not problems:
  1367. return []
  1368. return [
  1369. output_api.PresubmitPromptWarning(
  1370. 'Attempt to disable a test with DISABLE_ instead of DISABLED_?\n' +
  1371. '\n'.join(problems))
  1372. ]
  1373. def CheckForgettingMAYBEInTests(input_api, output_api):
  1374. """Checks to make sure tests disabled conditionally are not missing a
  1375. corresponding MAYBE_ prefix.
  1376. """
  1377. # Expect at least a lowercase character in the test name. This helps rule out
  1378. # false positives with macros wrapping the actual tests name.
  1379. define_maybe_pattern = input_api.re.compile(
  1380. r'^\#define MAYBE_(?P<test_name>\w*[a-z]\w*)')
  1381. test_maybe_pattern = r'^\s*\w*TEST[^(]*\(\s*\w+,\s*MAYBE_{test_name}\)'
  1382. suite_maybe_pattern = r'^\s*\w*TEST[^(]*\(\s*MAYBE_{test_name}[\),]'
  1383. warnings = []
  1384. # Read the entire files. We can't just read the affected lines, forgetting to
  1385. # add MAYBE_ on a change would not show up otherwise.
  1386. for f in input_api.AffectedFiles(False):
  1387. if not 'test' in f.LocalPath() or not f.LocalPath().endswith('.cc'):
  1388. continue
  1389. contents = input_api.ReadFile(f)
  1390. lines = contents.splitlines(True)
  1391. current_position = 0
  1392. warning_test_names = set()
  1393. for line_num, line in enumerate(lines, start=1):
  1394. current_position += len(line)
  1395. maybe_match = define_maybe_pattern.search(line)
  1396. if maybe_match:
  1397. test_name = maybe_match.group('test_name')
  1398. # Do not warn twice for the same test.
  1399. if (test_name in warning_test_names):
  1400. continue
  1401. warning_test_names.add(test_name)
  1402. # Attempt to find the corresponding MAYBE_ test or suite, starting from
  1403. # the current position.
  1404. test_match = input_api.re.compile(
  1405. test_maybe_pattern.format(test_name=test_name),
  1406. input_api.re.MULTILINE).search(contents, current_position)
  1407. suite_match = input_api.re.compile(
  1408. suite_maybe_pattern.format(test_name=test_name),
  1409. input_api.re.MULTILINE).search(contents, current_position)
  1410. if not test_match and not suite_match:
  1411. warnings.append(
  1412. output_api.PresubmitPromptWarning(
  1413. '%s:%d found MAYBE_ defined without corresponding test %s'
  1414. % (f.LocalPath(), line_num, test_name)))
  1415. return warnings
  1416. def CheckDCHECK_IS_ONHasBraces(input_api, output_api):
  1417. """Checks to make sure DCHECK_IS_ON() does not skip the parentheses."""
  1418. errors = []
  1419. pattern = input_api.re.compile(r'DCHECK_IS_ON\b(?!\(\))',
  1420. input_api.re.MULTILINE)
  1421. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  1422. if (not f.LocalPath().endswith(('.cc', '.mm', '.h'))):
  1423. continue
  1424. for lnum, line in f.ChangedContents():
  1425. if input_api.re.search(pattern, line):
  1426. errors.append(
  1427. output_api.PresubmitError((
  1428. '%s:%d: Use of DCHECK_IS_ON() must be written as "#if '
  1429. + 'DCHECK_IS_ON()", not forgetting the parentheses.') %
  1430. (f.LocalPath(), lnum)))
  1431. return errors
  1432. # TODO(crbug/1138055): Reimplement CheckUmaHistogramChangesOnUpload check in a
  1433. # more reliable way. See
  1434. # https://chromium-review.googlesource.com/c/chromium/src/+/2500269
  1435. def CheckFlakyTestUsage(input_api, output_api):
  1436. """Check that FlakyTest annotation is our own instead of the android one"""
  1437. pattern = input_api.re.compile(r'import android.test.FlakyTest;')
  1438. files = []
  1439. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  1440. if f.LocalPath().endswith('Test.java'):
  1441. if pattern.search(input_api.ReadFile(f)):
  1442. files.append(f)
  1443. if len(files):
  1444. return [
  1445. output_api.PresubmitError(
  1446. 'Use org.chromium.base.test.util.FlakyTest instead of '
  1447. 'android.test.FlakyTest', files)
  1448. ]
  1449. return []
  1450. def CheckNoDEPSGIT(input_api, output_api):
  1451. """Make sure .DEPS.git is never modified manually."""
  1452. if any(f.LocalPath().endswith('.DEPS.git')
  1453. for f in input_api.AffectedFiles()):
  1454. return [
  1455. output_api.PresubmitError(
  1456. 'Never commit changes to .DEPS.git. This file is maintained by an\n'
  1457. 'automated system based on what\'s in DEPS and your changes will be\n'
  1458. 'overwritten.\n'
  1459. 'See https://sites.google.com/a/chromium.org/dev/developers/how-tos/'
  1460. 'get-the-code#Rolling_DEPS\n'
  1461. 'for more information')
  1462. ]
  1463. return []
  1464. def CheckValidHostsInDEPSOnUpload(input_api, output_api):
  1465. """Checks that DEPS file deps are from allowed_hosts."""
  1466. # Run only if DEPS file has been modified to annoy fewer bystanders.
  1467. if all(f.LocalPath() != 'DEPS' for f in input_api.AffectedFiles()):
  1468. return []
  1469. # Outsource work to gclient verify
  1470. try:
  1471. gclient_path = input_api.os_path.join(input_api.PresubmitLocalPath(),
  1472. 'third_party', 'depot_tools',
  1473. 'gclient.py')
  1474. input_api.subprocess.check_output(
  1475. [input_api.python_executable, gclient_path, 'verify'],
  1476. stderr=input_api.subprocess.STDOUT)
  1477. return []
  1478. except input_api.subprocess.CalledProcessError as error:
  1479. return [
  1480. output_api.PresubmitError(
  1481. 'DEPS file must have only git dependencies.',
  1482. long_text=error.output)
  1483. ]
  1484. def _GetMessageForMatchingType(input_api, affected_file, line_number, line,
  1485. ban_rule):
  1486. """Helper method for CheckNoBannedFunctions and CheckNoDeprecatedMojoTypes.
  1487. Returns an string composed of the name of the file, the line number where the
  1488. match has been found and the additional text passed as |message| in case the
  1489. target type name matches the text inside the line passed as parameter.
  1490. """
  1491. result = []
  1492. # Ignore comments about banned types.
  1493. if input_api.re.search(r"^ *//", line):
  1494. return result
  1495. # A // nocheck comment will bypass this error.
  1496. if line.endswith(" nocheck"):
  1497. return result
  1498. matched = False
  1499. if ban_rule.pattern[0:1] == '/':
  1500. regex = ban_rule.pattern[1:]
  1501. if input_api.re.search(regex, line):
  1502. matched = True
  1503. elif ban_rule.pattern in line:
  1504. matched = True
  1505. if matched:
  1506. result.append(' %s:%d:' % (affected_file.LocalPath(), line_number))
  1507. for line in ban_rule.explanation:
  1508. result.append(' %s' % line)
  1509. return result
  1510. def CheckNoBannedFunctions(input_api, output_api):
  1511. """Make sure that banned functions are not used."""
  1512. warnings = []
  1513. errors = []
  1514. def IsExcludedFile(affected_file, excluded_paths):
  1515. if not excluded_paths:
  1516. return False
  1517. local_path = affected_file.LocalPath()
  1518. for item in excluded_paths:
  1519. if input_api.re.match(item, local_path):
  1520. return True
  1521. return False
  1522. def IsIosObjcFile(affected_file):
  1523. local_path = affected_file.LocalPath()
  1524. if input_api.os_path.splitext(local_path)[-1] not in ('.mm', '.m',
  1525. '.h'):
  1526. return False
  1527. basename = input_api.os_path.basename(local_path)
  1528. if 'ios' in basename.split('_'):
  1529. return True
  1530. for sep in (input_api.os_path.sep, input_api.os_path.altsep):
  1531. if sep and 'ios' in local_path.split(sep):
  1532. return True
  1533. return False
  1534. def CheckForMatch(affected_file, line_num: int, line: str,
  1535. ban_rule: BanRule):
  1536. if IsExcludedFile(affected_file, ban_rule.excluded_paths):
  1537. return
  1538. problems = _GetMessageForMatchingType(input_api, f, line_num, line,
  1539. ban_rule)
  1540. if problems:
  1541. if ban_rule.treat_as_error is not None and ban_rule.treat_as_error:
  1542. errors.extend(problems)
  1543. else:
  1544. warnings.extend(problems)
  1545. file_filter = lambda f: f.LocalPath().endswith(('.java'))
  1546. for f in input_api.AffectedFiles(file_filter=file_filter):
  1547. for line_num, line in f.ChangedContents():
  1548. for ban_rule in _BANNED_JAVA_FUNCTIONS:
  1549. CheckForMatch(f, line_num, line, ban_rule)
  1550. file_filter = lambda f: f.LocalPath().endswith(('.mm', '.m', '.h'))
  1551. for f in input_api.AffectedFiles(file_filter=file_filter):
  1552. for line_num, line in f.ChangedContents():
  1553. for ban_rule in _BANNED_OBJC_FUNCTIONS:
  1554. CheckForMatch(f, line_num, line, ban_rule)
  1555. for f in input_api.AffectedFiles(file_filter=IsIosObjcFile):
  1556. for line_num, line in f.ChangedContents():
  1557. for ban_rule in _BANNED_IOS_OBJC_FUNCTIONS:
  1558. CheckForMatch(f, line_num, line, ban_rule)
  1559. egtest_filter = lambda f: f.LocalPath().endswith(('_egtest.mm'))
  1560. for f in input_api.AffectedFiles(file_filter=egtest_filter):
  1561. for line_num, line in f.ChangedContents():
  1562. for ban_rule in _BANNED_IOS_EGTEST_FUNCTIONS:
  1563. CheckForMatch(f, line_num, line, ban_rule)
  1564. file_filter = lambda f: f.LocalPath().endswith(('.cc', '.mm', '.h'))
  1565. for f in input_api.AffectedFiles(file_filter=file_filter):
  1566. for line_num, line in f.ChangedContents():
  1567. for ban_rule in _BANNED_CPP_FUNCTIONS:
  1568. CheckForMatch(f, line_num, line, ban_rule)
  1569. file_filter = lambda f: f.LocalPath().endswith(('.mojom'))
  1570. for f in input_api.AffectedFiles(file_filter=file_filter):
  1571. for line_num, line in f.ChangedContents():
  1572. for ban_rule in _BANNED_MOJOM_PATTERNS:
  1573. CheckForMatch(f, line_num, line, ban_rule)
  1574. result = []
  1575. if (warnings):
  1576. result.append(
  1577. output_api.PresubmitPromptWarning('Banned functions were used.\n' +
  1578. '\n'.join(warnings)))
  1579. if (errors):
  1580. result.append(
  1581. output_api.PresubmitError('Banned functions were used.\n' +
  1582. '\n'.join(errors)))
  1583. return result
  1584. def _CheckAndroidNoBannedImports(input_api, output_api):
  1585. """Make sure that banned java imports are not used."""
  1586. errors = []
  1587. file_filter = lambda f: f.LocalPath().endswith(('.java'))
  1588. for f in input_api.AffectedFiles(file_filter=file_filter):
  1589. for line_num, line in f.ChangedContents():
  1590. for ban_rule in _BANNED_JAVA_IMPORTS:
  1591. # Consider merging this into the above function. There is no
  1592. # real difference anymore other than helping with a little
  1593. # bit of boilerplate text. Doing so means things like
  1594. # `treat_as_error` will also be uniformly handled.
  1595. problems = _GetMessageForMatchingType(input_api, f, line_num,
  1596. line, ban_rule)
  1597. if problems:
  1598. errors.extend(problems)
  1599. result = []
  1600. if (errors):
  1601. result.append(
  1602. output_api.PresubmitError('Banned imports were used.\n' +
  1603. '\n'.join(errors)))
  1604. return result
  1605. def CheckNoPragmaOnce(input_api, output_api):
  1606. """Make sure that banned functions are not used."""
  1607. files = []
  1608. pattern = input_api.re.compile(r'^#pragma\s+once', input_api.re.MULTILINE)
  1609. for f in input_api.AffectedSourceFiles(input_api.FilterSourceFile):
  1610. if not f.LocalPath().endswith('.h'):
  1611. continue
  1612. contents = input_api.ReadFile(f)
  1613. if pattern.search(contents):
  1614. files.append(f)
  1615. if files:
  1616. return [
  1617. output_api.PresubmitError(
  1618. 'Do not use #pragma once in header files.\n'
  1619. 'See http://www.chromium.org/developers/coding-style#TOC-File-headers',
  1620. files)
  1621. ]
  1622. return []
  1623. def CheckNoTrinaryTrueFalse(input_api, output_api):
  1624. """Checks to make sure we don't introduce use of foo ? true : false."""
  1625. problems = []
  1626. pattern = input_api.re.compile(r'\?\s*(true|false)\s*:\s*(true|false)')
  1627. for f in input_api.AffectedFiles():
  1628. if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
  1629. continue
  1630. for line_num, line in f.ChangedContents():
  1631. if pattern.match(line):
  1632. problems.append(' %s:%d' % (f.LocalPath(), line_num))
  1633. if not problems:
  1634. return []
  1635. return [
  1636. output_api.PresubmitPromptWarning(
  1637. 'Please consider avoiding the "? true : false" pattern if possible.\n'
  1638. + '\n'.join(problems))
  1639. ]
  1640. def CheckUnwantedDependencies(input_api, output_api):
  1641. """Runs checkdeps on #include and import statements added in this
  1642. change. Breaking - rules is an error, breaking ! rules is a
  1643. warning.
  1644. """
  1645. # Return early if no relevant file types were modified.
  1646. for f in input_api.AffectedFiles():
  1647. path = f.LocalPath()
  1648. if (_IsCPlusPlusFile(input_api, path) or _IsProtoFile(input_api, path)
  1649. or _IsJavaFile(input_api, path)):
  1650. break
  1651. else:
  1652. return []
  1653. import sys
  1654. # We need to wait until we have an input_api object and use this
  1655. # roundabout construct to import checkdeps because this file is
  1656. # eval-ed and thus doesn't have __file__.
  1657. original_sys_path = sys.path
  1658. try:
  1659. sys.path = sys.path + [
  1660. input_api.os_path.join(input_api.PresubmitLocalPath(),
  1661. 'buildtools', 'checkdeps')
  1662. ]
  1663. import checkdeps
  1664. from rules import Rule
  1665. finally:
  1666. # Restore sys.path to what it was before.
  1667. sys.path = original_sys_path
  1668. added_includes = []
  1669. added_imports = []
  1670. added_java_imports = []
  1671. for f in input_api.AffectedFiles():
  1672. if _IsCPlusPlusFile(input_api, f.LocalPath()):
  1673. changed_lines = [line for _, line in f.ChangedContents()]
  1674. added_includes.append([f.AbsoluteLocalPath(), changed_lines])
  1675. elif _IsProtoFile(input_api, f.LocalPath()):
  1676. changed_lines = [line for _, line in f.ChangedContents()]
  1677. added_imports.append([f.AbsoluteLocalPath(), changed_lines])
  1678. elif _IsJavaFile(input_api, f.LocalPath()):
  1679. changed_lines = [line for _, line in f.ChangedContents()]
  1680. added_java_imports.append([f.AbsoluteLocalPath(), changed_lines])
  1681. deps_checker = checkdeps.DepsChecker(input_api.PresubmitLocalPath())
  1682. error_descriptions = []
  1683. warning_descriptions = []
  1684. error_subjects = set()
  1685. warning_subjects = set()
  1686. for path, rule_type, rule_description in deps_checker.CheckAddedCppIncludes(
  1687. added_includes):
  1688. path = input_api.os_path.relpath(path, input_api.PresubmitLocalPath())
  1689. description_with_path = '%s\n %s' % (path, rule_description)
  1690. if rule_type == Rule.DISALLOW:
  1691. error_descriptions.append(description_with_path)
  1692. error_subjects.add("#includes")
  1693. else:
  1694. warning_descriptions.append(description_with_path)
  1695. warning_subjects.add("#includes")
  1696. for path, rule_type, rule_description in deps_checker.CheckAddedProtoImports(
  1697. added_imports):
  1698. path = input_api.os_path.relpath(path, input_api.PresubmitLocalPath())
  1699. description_with_path = '%s\n %s' % (path, rule_description)
  1700. if rule_type == Rule.DISALLOW:
  1701. error_descriptions.append(description_with_path)
  1702. error_subjects.add("imports")
  1703. else:
  1704. warning_descriptions.append(description_with_path)
  1705. warning_subjects.add("imports")
  1706. for path, rule_type, rule_description in deps_checker.CheckAddedJavaImports(
  1707. added_java_imports, _JAVA_MULTIPLE_DEFINITION_EXCLUDED_PATHS):
  1708. path = input_api.os_path.relpath(path, input_api.PresubmitLocalPath())
  1709. description_with_path = '%s\n %s' % (path, rule_description)
  1710. if rule_type == Rule.DISALLOW:
  1711. error_descriptions.append(description_with_path)
  1712. error_subjects.add("imports")
  1713. else:
  1714. warning_descriptions.append(description_with_path)
  1715. warning_subjects.add("imports")
  1716. results = []
  1717. if error_descriptions:
  1718. results.append(
  1719. output_api.PresubmitError(
  1720. 'You added one or more %s that violate checkdeps rules.' %
  1721. " and ".join(error_subjects), error_descriptions))
  1722. if warning_descriptions:
  1723. results.append(
  1724. output_api.PresubmitPromptOrNotify(
  1725. 'You added one or more %s of files that are temporarily\n'
  1726. 'allowed but being removed. Can you avoid introducing the\n'
  1727. '%s? See relevant DEPS file(s) for details and contacts.' %
  1728. (" and ".join(warning_subjects), "/".join(warning_subjects)),
  1729. warning_descriptions))
  1730. return results
  1731. def CheckFilePermissions(input_api, output_api):
  1732. """Check that all files have their permissions properly set."""
  1733. if input_api.platform == 'win32':
  1734. return []
  1735. checkperms_tool = input_api.os_path.join(input_api.PresubmitLocalPath(),
  1736. 'tools', 'checkperms',
  1737. 'checkperms.py')
  1738. args = [
  1739. input_api.python_executable, checkperms_tool, '--root',
  1740. input_api.change.RepositoryRoot()
  1741. ]
  1742. with input_api.CreateTemporaryFile() as file_list:
  1743. for f in input_api.AffectedFiles():
  1744. # checkperms.py file/directory arguments must be relative to the
  1745. # repository.
  1746. file_list.write((f.LocalPath() + '\n').encode('utf8'))
  1747. file_list.close()
  1748. args += ['--file-list', file_list.name]
  1749. try:
  1750. input_api.subprocess.check_output(args)
  1751. return []
  1752. except input_api.subprocess.CalledProcessError as error:
  1753. return [
  1754. output_api.PresubmitError('checkperms.py failed:',
  1755. long_text=error.output.decode(
  1756. 'utf-8', 'ignore'))
  1757. ]
  1758. def CheckNoAuraWindowPropertyHInHeaders(input_api, output_api):
  1759. """Makes sure we don't include ui/aura/window_property.h
  1760. in header files.
  1761. """
  1762. pattern = input_api.re.compile(r'^#include\s*"ui/aura/window_property.h"')
  1763. errors = []
  1764. for f in input_api.AffectedFiles():
  1765. if not f.LocalPath().endswith('.h'):
  1766. continue
  1767. for line_num, line in f.ChangedContents():
  1768. if pattern.match(line):
  1769. errors.append(' %s:%d' % (f.LocalPath(), line_num))
  1770. results = []
  1771. if errors:
  1772. results.append(
  1773. output_api.PresubmitError(
  1774. 'Header files should not include ui/aura/window_property.h',
  1775. errors))
  1776. return results
  1777. def CheckNoInternalHeapIncludes(input_api, output_api):
  1778. """Makes sure we don't include any headers from
  1779. third_party/blink/renderer/platform/heap/impl or
  1780. third_party/blink/renderer/platform/heap/v8_wrapper from files outside of
  1781. third_party/blink/renderer/platform/heap
  1782. """
  1783. impl_pattern = input_api.re.compile(
  1784. r'^\s*#include\s*"third_party/blink/renderer/platform/heap/impl/.*"')
  1785. v8_wrapper_pattern = input_api.re.compile(
  1786. r'^\s*#include\s*"third_party/blink/renderer/platform/heap/v8_wrapper/.*"'
  1787. )
  1788. file_filter = lambda f: not input_api.re.match(
  1789. r"^third_party[\\/]blink[\\/]renderer[\\/]platform[\\/]heap[\\/].*",
  1790. f.LocalPath())
  1791. errors = []
  1792. for f in input_api.AffectedFiles(file_filter=file_filter):
  1793. for line_num, line in f.ChangedContents():
  1794. if impl_pattern.match(line) or v8_wrapper_pattern.match(line):
  1795. errors.append(' %s:%d' % (f.LocalPath(), line_num))
  1796. results = []
  1797. if errors:
  1798. results.append(
  1799. output_api.PresubmitError(
  1800. 'Do not include files from third_party/blink/renderer/platform/heap/impl'
  1801. ' or third_party/blink/renderer/platform/heap/v8_wrapper. Use the '
  1802. 'relevant counterparts from third_party/blink/renderer/platform/heap',
  1803. errors))
  1804. return results
  1805. def _CheckForVersionControlConflictsInFile(input_api, f):
  1806. pattern = input_api.re.compile('^(?:<<<<<<<|>>>>>>>) |^=======$')
  1807. errors = []
  1808. for line_num, line in f.ChangedContents():
  1809. if f.LocalPath().endswith(('.md', '.rst', '.txt')):
  1810. # First-level headers in markdown look a lot like version control
  1811. # conflict markers. http://daringfireball.net/projects/markdown/basics
  1812. continue
  1813. if pattern.match(line):
  1814. errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
  1815. return errors
  1816. def CheckForVersionControlConflicts(input_api, output_api):
  1817. """Usually this is not intentional and will cause a compile failure."""
  1818. errors = []
  1819. for f in input_api.AffectedFiles():
  1820. errors.extend(_CheckForVersionControlConflictsInFile(input_api, f))
  1821. results = []
  1822. if errors:
  1823. results.append(
  1824. output_api.PresubmitError(
  1825. 'Version control conflict markers found, please resolve.',
  1826. errors))
  1827. return results
  1828. def CheckGoogleSupportAnswerUrlOnUpload(input_api, output_api):
  1829. pattern = input_api.re.compile('support\.google\.com\/chrome.*/answer')
  1830. errors = []
  1831. for f in input_api.AffectedFiles():
  1832. for line_num, line in f.ChangedContents():
  1833. if pattern.search(line):
  1834. errors.append(' %s:%d %s' % (f.LocalPath(), line_num, line))
  1835. results = []
  1836. if errors:
  1837. results.append(
  1838. output_api.PresubmitPromptWarning(
  1839. 'Found Google support URL addressed by answer number. Please replace '
  1840. 'with a p= identifier instead. See crbug.com/679462\n',
  1841. errors))
  1842. return results
  1843. def CheckHardcodedGoogleHostsInLowerLayers(input_api, output_api):
  1844. def FilterFile(affected_file):
  1845. """Filter function for use with input_api.AffectedSourceFiles,
  1846. below. This filters out everything except non-test files from
  1847. top-level directories that generally speaking should not hard-code
  1848. service URLs (e.g. src/android_webview/, src/content/ and others).
  1849. """
  1850. return input_api.FilterSourceFile(
  1851. affected_file,
  1852. files_to_check=[r'^(android_webview|base|content|net)[\\/].*'],
  1853. files_to_skip=(_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  1854. input_api.DEFAULT_FILES_TO_SKIP))
  1855. base_pattern = ('"[^"]*(google|googleapis|googlezip|googledrive|appspot)'
  1856. '\.(com|net)[^"]*"')
  1857. comment_pattern = input_api.re.compile('//.*%s' % base_pattern)
  1858. pattern = input_api.re.compile(base_pattern)
  1859. problems = [] # items are (filename, line_number, line)
  1860. for f in input_api.AffectedSourceFiles(FilterFile):
  1861. for line_num, line in f.ChangedContents():
  1862. if not comment_pattern.search(line) and pattern.search(line):
  1863. problems.append((f.LocalPath(), line_num, line))
  1864. if problems:
  1865. return [
  1866. output_api.PresubmitPromptOrNotify(
  1867. 'Most layers below src/chrome/ should not hardcode service URLs.\n'
  1868. 'Are you sure this is correct?', [
  1869. ' %s:%d: %s' % (problem[0], problem[1], problem[2])
  1870. for problem in problems
  1871. ])
  1872. ]
  1873. else:
  1874. return []
  1875. def CheckChromeOsSyncedPrefRegistration(input_api, output_api):
  1876. """Warns if Chrome OS C++ files register syncable prefs as browser prefs."""
  1877. def FileFilter(affected_file):
  1878. """Includes directories known to be Chrome OS only."""
  1879. return input_api.FilterSourceFile(
  1880. affected_file,
  1881. files_to_check=(
  1882. '^ash/',
  1883. '^chromeos/', # Top-level src/chromeos.
  1884. '.*/chromeos/', # Any path component.
  1885. '^components/arc',
  1886. '^components/exo'),
  1887. files_to_skip=(input_api.DEFAULT_FILES_TO_SKIP))
  1888. prefs = []
  1889. priority_prefs = []
  1890. for f in input_api.AffectedFiles(file_filter=FileFilter):
  1891. for line_num, line in f.ChangedContents():
  1892. if input_api.re.search('PrefRegistrySyncable::SYNCABLE_PREF',
  1893. line):
  1894. prefs.append(' %s:%d:' % (f.LocalPath(), line_num))
  1895. prefs.append(' %s' % line)
  1896. if input_api.re.search(
  1897. 'PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF', line):
  1898. priority_prefs.append(' %s:%d' % (f.LocalPath(), line_num))
  1899. priority_prefs.append(' %s' % line)
  1900. results = []
  1901. if (prefs):
  1902. results.append(
  1903. output_api.PresubmitPromptWarning(
  1904. 'Preferences were registered as SYNCABLE_PREF and will be controlled '
  1905. 'by browser sync settings. If these prefs should be controlled by OS '
  1906. 'sync settings use SYNCABLE_OS_PREF instead.\n' +
  1907. '\n'.join(prefs)))
  1908. if (priority_prefs):
  1909. results.append(
  1910. output_api.PresubmitPromptWarning(
  1911. 'Preferences were registered as SYNCABLE_PRIORITY_PREF and will be '
  1912. 'controlled by browser sync settings. If these prefs should be '
  1913. 'controlled by OS sync settings use SYNCABLE_OS_PRIORITY_PREF '
  1914. 'instead.\n' + '\n'.join(prefs)))
  1915. return results
  1916. # TODO: add unit tests.
  1917. def CheckNoAbbreviationInPngFileName(input_api, output_api):
  1918. """Makes sure there are no abbreviations in the name of PNG files.
  1919. The native_client_sdk directory is excluded because it has auto-generated PNG
  1920. files for documentation.
  1921. """
  1922. errors = []
  1923. files_to_check = [r'.*_[a-z]_.*\.png$|.*_[a-z]\.png$']
  1924. files_to_skip = [r'^native_client_sdk[\\/]']
  1925. file_filter = lambda f: input_api.FilterSourceFile(
  1926. f, files_to_check=files_to_check, files_to_skip=files_to_skip)
  1927. for f in input_api.AffectedFiles(include_deletes=False,
  1928. file_filter=file_filter):
  1929. errors.append(' %s' % f.LocalPath())
  1930. results = []
  1931. if errors:
  1932. results.append(
  1933. output_api.PresubmitError(
  1934. 'The name of PNG files should not have abbreviations. \n'
  1935. 'Use _hover.png, _center.png, instead of _h.png, _c.png.\n'
  1936. 'Contact oshima@chromium.org if you have questions.', errors))
  1937. return results
  1938. def _ExtractAddRulesFromParsedDeps(parsed_deps):
  1939. """Extract the rules that add dependencies from a parsed DEPS file.
  1940. Args:
  1941. parsed_deps: the locals dictionary from evaluating the DEPS file."""
  1942. add_rules = set()
  1943. add_rules.update([
  1944. rule[1:] for rule in parsed_deps.get('include_rules', [])
  1945. if rule.startswith('+') or rule.startswith('!')
  1946. ])
  1947. for _, rules in parsed_deps.get('specific_include_rules', {}).items():
  1948. add_rules.update([
  1949. rule[1:] for rule in rules
  1950. if rule.startswith('+') or rule.startswith('!')
  1951. ])
  1952. return add_rules
  1953. def _ParseDeps(contents):
  1954. """Simple helper for parsing DEPS files."""
  1955. # Stubs for handling special syntax in the root DEPS file.
  1956. class _VarImpl:
  1957. def __init__(self, local_scope):
  1958. self._local_scope = local_scope
  1959. def Lookup(self, var_name):
  1960. """Implements the Var syntax."""
  1961. try:
  1962. return self._local_scope['vars'][var_name]
  1963. except KeyError:
  1964. raise Exception('Var is not defined: %s' % var_name)
  1965. local_scope = {}
  1966. global_scope = {
  1967. 'Var': _VarImpl(local_scope).Lookup,
  1968. 'Str': str,
  1969. }
  1970. exec(contents, global_scope, local_scope)
  1971. return local_scope
  1972. def _CalculateAddedDeps(os_path, old_contents, new_contents):
  1973. """Helper method for CheckAddedDepsHaveTargetApprovals. Returns
  1974. a set of DEPS entries that we should look up.
  1975. For a directory (rather than a specific filename) we fake a path to
  1976. a specific filename by adding /DEPS. This is chosen as a file that
  1977. will seldom or never be subject to per-file include_rules.
  1978. """
  1979. # We ignore deps entries on auto-generated directories.
  1980. AUTO_GENERATED_DIRS = ['grit', 'jni']
  1981. old_deps = _ExtractAddRulesFromParsedDeps(_ParseDeps(old_contents))
  1982. new_deps = _ExtractAddRulesFromParsedDeps(_ParseDeps(new_contents))
  1983. added_deps = new_deps.difference(old_deps)
  1984. results = set()
  1985. for added_dep in added_deps:
  1986. if added_dep.split('/')[0] in AUTO_GENERATED_DIRS:
  1987. continue
  1988. # Assume that a rule that ends in .h is a rule for a specific file.
  1989. if added_dep.endswith('.h'):
  1990. results.add(added_dep)
  1991. else:
  1992. results.add(os_path.join(added_dep, 'DEPS'))
  1993. return results
  1994. def CheckAddedDepsHaveTargetApprovals(input_api, output_api):
  1995. """When a dependency prefixed with + is added to a DEPS file, we
  1996. want to make sure that the change is reviewed by an OWNER of the
  1997. target file or directory, to avoid layering violations from being
  1998. introduced. This check verifies that this happens.
  1999. """
  2000. # We rely on Gerrit's code-owners to check approvals.
  2001. # input_api.gerrit is always set for Chromium, but other projects
  2002. # might not use Gerrit.
  2003. if not input_api.gerrit:
  2004. return []
  2005. if (input_api.change.issue and input_api.gerrit.IsOwnersOverrideApproved(
  2006. input_api.change.issue)):
  2007. # Skip OWNERS check when Owners-Override label is approved. This is intended
  2008. # for global owners, trusted bots, and on-call sheriffs. Review is still
  2009. # required for these changes.
  2010. return []
  2011. virtual_depended_on_files = set()
  2012. file_filter = lambda f: not input_api.re.match(
  2013. r"^third_party[\\/]blink[\\/].*", f.LocalPath())
  2014. for f in input_api.AffectedFiles(include_deletes=False,
  2015. file_filter=file_filter):
  2016. filename = input_api.os_path.basename(f.LocalPath())
  2017. if filename == 'DEPS':
  2018. virtual_depended_on_files.update(
  2019. _CalculateAddedDeps(input_api.os_path,
  2020. '\n'.join(f.OldContents()),
  2021. '\n'.join(f.NewContents())))
  2022. if not virtual_depended_on_files:
  2023. return []
  2024. if input_api.is_committing:
  2025. if input_api.tbr:
  2026. return [
  2027. output_api.PresubmitNotifyResult(
  2028. '--tbr was specified, skipping OWNERS check for DEPS additions'
  2029. )
  2030. ]
  2031. if input_api.dry_run:
  2032. return [
  2033. output_api.PresubmitNotifyResult(
  2034. 'This is a dry run, skipping OWNERS check for DEPS additions'
  2035. )
  2036. ]
  2037. if not input_api.change.issue:
  2038. return [
  2039. output_api.PresubmitError(
  2040. "DEPS approval by OWNERS check failed: this change has "
  2041. "no change number, so we can't check it for approvals.")
  2042. ]
  2043. output = output_api.PresubmitError
  2044. else:
  2045. output = output_api.PresubmitNotifyResult
  2046. owner_email, reviewers = (
  2047. input_api.canned_checks.GetCodereviewOwnerAndReviewers(
  2048. input_api, None, approval_needed=input_api.is_committing))
  2049. owner_email = owner_email or input_api.change.author_email
  2050. approval_status = input_api.owners_client.GetFilesApprovalStatus(
  2051. virtual_depended_on_files, reviewers.union([owner_email]), [])
  2052. missing_files = [
  2053. f for f in virtual_depended_on_files
  2054. if approval_status[f] != input_api.owners_client.APPROVED
  2055. ]
  2056. # We strip the /DEPS part that was added by
  2057. # _FilesToCheckForIncomingDeps to fake a path to a file in a
  2058. # directory.
  2059. def StripDeps(path):
  2060. start_deps = path.rfind('/DEPS')
  2061. if start_deps != -1:
  2062. return path[:start_deps]
  2063. else:
  2064. return path
  2065. unapproved_dependencies = [
  2066. "'+%s'," % StripDeps(path) for path in missing_files
  2067. ]
  2068. if unapproved_dependencies:
  2069. output_list = [
  2070. output(
  2071. 'You need LGTM from owners of depends-on paths in DEPS that were '
  2072. 'modified in this CL:\n %s' %
  2073. '\n '.join(sorted(unapproved_dependencies)))
  2074. ]
  2075. suggested_owners = input_api.owners_client.SuggestOwners(
  2076. missing_files, exclude=[owner_email])
  2077. output_list.append(
  2078. output('Suggested missing target path OWNERS:\n %s' %
  2079. '\n '.join(suggested_owners or [])))
  2080. return output_list
  2081. return []
  2082. # TODO: add unit tests.
  2083. def CheckSpamLogging(input_api, output_api):
  2084. file_inclusion_pattern = [r'.+%s' % _IMPLEMENTATION_EXTENSIONS]
  2085. files_to_skip = (
  2086. _EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  2087. input_api.DEFAULT_FILES_TO_SKIP + (
  2088. r"^base[\\/]logging\.h$",
  2089. r"^base[\\/]logging\.cc$",
  2090. r"^base[\\/]task[\\/]thread_pool[\\/]task_tracker\.cc$",
  2091. r"^chrome[\\/]app[\\/]chrome_main_delegate\.cc$",
  2092. r"^chrome[\\/]browser[\\/]chrome_browser_main\.cc$",
  2093. r"^chrome[\\/]browser[\\/]ui[\\/]startup[\\/]"
  2094. r"startup_browser_creator\.cc$",
  2095. r"^chrome[\\/]browser[\\/]browser_switcher[\\/]bho[\\/].*",
  2096. r"^chrome[\\/]browser[\\/]diagnostics[\\/]" +
  2097. r"diagnostics_writer\.cc$",
  2098. r"^chrome[\\/]chrome_cleaner[\\/].*",
  2099. r"^chrome[\\/]chrome_elf[\\/]dll_hash[\\/]" +
  2100. r"dll_hash_main\.cc$",
  2101. r"^chrome[\\/]installer[\\/]setup[\\/].*",
  2102. r"^chromecast[\\/]",
  2103. r"^components[\\/]browser_watcher[\\/]"
  2104. r"dump_stability_report_main_win.cc$",
  2105. r"^components[\\/]media_control[\\/]renderer[\\/]"
  2106. r"media_playback_options\.cc$",
  2107. r"^components[\\/]viz[\\/]service[\\/]display[\\/]"
  2108. r"overlay_strategy_underlay_cast\.cc$",
  2109. r"^components[\\/]zucchini[\\/].*",
  2110. # TODO(peter): Remove exception. https://crbug.com/534537
  2111. r"^content[\\/]browser[\\/]notifications[\\/]"
  2112. r"notification_event_dispatcher_impl\.cc$",
  2113. r"^content[\\/]common[\\/]gpu[\\/]client[\\/]"
  2114. r"gl_helper_benchmark\.cc$",
  2115. r"^courgette[\\/]courgette_minimal_tool\.cc$",
  2116. r"^courgette[\\/]courgette_tool\.cc$",
  2117. r"^extensions[\\/]renderer[\\/]logging_native_handler\.cc$",
  2118. r"^fuchsia[\\/]base[\\/]init_logging.cc$",
  2119. r"^fuchsia[\\/]engine[\\/]browser[\\/]frame_impl.cc$",
  2120. r"^fuchsia[\\/]runners[\\/]common[\\/]web_component.cc$",
  2121. r"^headless[\\/]app[\\/]headless_shell\.cc$",
  2122. r"^ipc[\\/]ipc_logging\.cc$",
  2123. r"^native_client_sdk[\\/]",
  2124. r"^remoting[\\/]base[\\/]logging\.h$",
  2125. r"^remoting[\\/]host[\\/].*",
  2126. r"^sandbox[\\/]linux[\\/].*",
  2127. r"^storage[\\/]browser[\\/]file_system[\\/]" +
  2128. r"dump_file_system.cc$",
  2129. r"^tools[\\/]",
  2130. r"^ui[\\/]base[\\/]resource[\\/]data_pack.cc$",
  2131. r"^ui[\\/]aura[\\/]bench[\\/]bench_main\.cc$",
  2132. r"^ui[\\/]ozone[\\/]platform[\\/]cast[\\/]",
  2133. r"^ui[\\/]base[\\/]x[\\/]xwmstartupcheck[\\/]"
  2134. r"xwmstartupcheck\.cc$"))
  2135. source_file_filter = lambda x: input_api.FilterSourceFile(
  2136. x, files_to_check=file_inclusion_pattern, files_to_skip=files_to_skip)
  2137. log_info = set([])
  2138. printf = set([])
  2139. for f in input_api.AffectedSourceFiles(source_file_filter):
  2140. for _, line in f.ChangedContents():
  2141. if input_api.re.search(r"\bD?LOG\s*\(\s*INFO\s*\)", line):
  2142. log_info.add(f.LocalPath())
  2143. elif input_api.re.search(r"\bD?LOG_IF\s*\(\s*INFO\s*,", line):
  2144. log_info.add(f.LocalPath())
  2145. if input_api.re.search(r"\bprintf\(", line):
  2146. printf.add(f.LocalPath())
  2147. elif input_api.re.search(r"\bfprintf\((stdout|stderr)", line):
  2148. printf.add(f.LocalPath())
  2149. if log_info:
  2150. return [
  2151. output_api.PresubmitError(
  2152. 'These files spam the console log with LOG(INFO):',
  2153. items=log_info)
  2154. ]
  2155. if printf:
  2156. return [
  2157. output_api.PresubmitError(
  2158. 'These files spam the console log with printf/fprintf:',
  2159. items=printf)
  2160. ]
  2161. return []
  2162. def CheckForAnonymousVariables(input_api, output_api):
  2163. """These types are all expected to hold locks while in scope and
  2164. so should never be anonymous (which causes them to be immediately
  2165. destroyed)."""
  2166. they_who_must_be_named = [
  2167. 'base::AutoLock',
  2168. 'base::AutoReset',
  2169. 'base::AutoUnlock',
  2170. 'SkAutoAlphaRestore',
  2171. 'SkAutoBitmapShaderInstall',
  2172. 'SkAutoBlitterChoose',
  2173. 'SkAutoBounderCommit',
  2174. 'SkAutoCallProc',
  2175. 'SkAutoCanvasRestore',
  2176. 'SkAutoCommentBlock',
  2177. 'SkAutoDescriptor',
  2178. 'SkAutoDisableDirectionCheck',
  2179. 'SkAutoDisableOvalCheck',
  2180. 'SkAutoFree',
  2181. 'SkAutoGlyphCache',
  2182. 'SkAutoHDC',
  2183. 'SkAutoLockColors',
  2184. 'SkAutoLockPixels',
  2185. 'SkAutoMalloc',
  2186. 'SkAutoMaskFreeImage',
  2187. 'SkAutoMutexAcquire',
  2188. 'SkAutoPathBoundsUpdate',
  2189. 'SkAutoPDFRelease',
  2190. 'SkAutoRasterClipValidate',
  2191. 'SkAutoRef',
  2192. 'SkAutoTime',
  2193. 'SkAutoTrace',
  2194. 'SkAutoUnref',
  2195. ]
  2196. anonymous = r'(%s)\s*[({]' % '|'.join(they_who_must_be_named)
  2197. # bad: base::AutoLock(lock.get());
  2198. # not bad: base::AutoLock lock(lock.get());
  2199. bad_pattern = input_api.re.compile(anonymous)
  2200. # good: new base::AutoLock(lock.get())
  2201. good_pattern = input_api.re.compile(r'\bnew\s*' + anonymous)
  2202. errors = []
  2203. for f in input_api.AffectedFiles():
  2204. if not f.LocalPath().endswith(('.cc', '.h', '.inl', '.m', '.mm')):
  2205. continue
  2206. for linenum, line in f.ChangedContents():
  2207. if bad_pattern.search(line) and not good_pattern.search(line):
  2208. errors.append('%s:%d' % (f.LocalPath(), linenum))
  2209. if errors:
  2210. return [
  2211. output_api.PresubmitError(
  2212. 'These lines create anonymous variables that need to be named:',
  2213. items=errors)
  2214. ]
  2215. return []
  2216. def CheckUniquePtrOnUpload(input_api, output_api):
  2217. # Returns whether |template_str| is of the form <T, U...> for some types T
  2218. # and U. Assumes that |template_str| is already in the form <...>.
  2219. def HasMoreThanOneArg(template_str):
  2220. # Level of <...> nesting.
  2221. nesting = 0
  2222. for c in template_str:
  2223. if c == '<':
  2224. nesting += 1
  2225. elif c == '>':
  2226. nesting -= 1
  2227. elif c == ',' and nesting == 1:
  2228. return True
  2229. return False
  2230. file_inclusion_pattern = [r'.+%s' % _IMPLEMENTATION_EXTENSIONS]
  2231. sources = lambda affected_file: input_api.FilterSourceFile(
  2232. affected_file,
  2233. files_to_skip=(_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS + input_api.
  2234. DEFAULT_FILES_TO_SKIP),
  2235. files_to_check=file_inclusion_pattern)
  2236. # Pattern to capture a single "<...>" block of template arguments. It can
  2237. # handle linearly nested blocks, such as "<std::vector<std::set<T>>>", but
  2238. # cannot handle branching structures, such as "<pair<set<T>,set<U>>". The
  2239. # latter would likely require counting that < and > match, which is not
  2240. # expressible in regular languages. Should the need arise, one can introduce
  2241. # limited counting (matching up to a total number of nesting depth), which
  2242. # should cover all practical cases for already a low nesting limit.
  2243. template_arg_pattern = (
  2244. r'<[^>]*' # Opening block of <.
  2245. r'>([^<]*>)?') # Closing block of >.
  2246. # Prefix expressing that whatever follows is not already inside a <...>
  2247. # block.
  2248. not_inside_template_arg_pattern = r'(^|[^<,\s]\s*)'
  2249. null_construct_pattern = input_api.re.compile(
  2250. not_inside_template_arg_pattern + r'\bstd::unique_ptr' +
  2251. template_arg_pattern + r'\(\)')
  2252. # Same as template_arg_pattern, but excluding type arrays, e.g., <T[]>.
  2253. template_arg_no_array_pattern = (
  2254. r'<[^>]*[^]]' # Opening block of <.
  2255. r'>([^(<]*[^]]>)?') # Closing block of >.
  2256. # Prefix saying that what follows is the start of an expression.
  2257. start_of_expr_pattern = r'(=|\breturn|^)\s*'
  2258. # Suffix saying that what follows are call parentheses with a non-empty list
  2259. # of arguments.
  2260. nonempty_arg_list_pattern = r'\(([^)]|$)'
  2261. # Put the template argument into a capture group for deeper examination later.
  2262. return_construct_pattern = input_api.re.compile(
  2263. start_of_expr_pattern + r'std::unique_ptr' + '(?P<template_arg>' +
  2264. template_arg_no_array_pattern + ')' + nonempty_arg_list_pattern)
  2265. problems_constructor = []
  2266. problems_nullptr = []
  2267. for f in input_api.AffectedSourceFiles(sources):
  2268. for line_number, line in f.ChangedContents():
  2269. # Disallow:
  2270. # return std::unique_ptr<T>(foo);
  2271. # bar = std::unique_ptr<T>(foo);
  2272. # But allow:
  2273. # return std::unique_ptr<T[]>(foo);
  2274. # bar = std::unique_ptr<T[]>(foo);
  2275. # And also allow cases when the second template argument is present. Those
  2276. # cases cannot be handled by std::make_unique:
  2277. # return std::unique_ptr<T, U>(foo);
  2278. # bar = std::unique_ptr<T, U>(foo);
  2279. local_path = f.LocalPath()
  2280. return_construct_result = return_construct_pattern.search(line)
  2281. if return_construct_result and not HasMoreThanOneArg(
  2282. return_construct_result.group('template_arg')):
  2283. problems_constructor.append(
  2284. '%s:%d\n %s' % (local_path, line_number, line.strip()))
  2285. # Disallow:
  2286. # std::unique_ptr<T>()
  2287. if null_construct_pattern.search(line):
  2288. problems_nullptr.append(
  2289. '%s:%d\n %s' % (local_path, line_number, line.strip()))
  2290. errors = []
  2291. if problems_nullptr:
  2292. errors.append(
  2293. output_api.PresubmitPromptWarning(
  2294. 'The following files use std::unique_ptr<T>(). Use nullptr instead.',
  2295. problems_nullptr))
  2296. if problems_constructor:
  2297. errors.append(
  2298. output_api.PresubmitError(
  2299. 'The following files use explicit std::unique_ptr constructor. '
  2300. 'Use std::make_unique<T>() instead, or use base::WrapUnique if '
  2301. 'std::make_unique is not an option.', problems_constructor))
  2302. return errors
  2303. def CheckUserActionUpdate(input_api, output_api):
  2304. """Checks if any new user action has been added."""
  2305. if any('actions.xml' == input_api.os_path.basename(f)
  2306. for f in input_api.LocalPaths()):
  2307. # If actions.xml is already included in the changelist, the PRESUBMIT
  2308. # for actions.xml will do a more complete presubmit check.
  2309. return []
  2310. file_inclusion_pattern = [r'.*\.(cc|mm)$']
  2311. files_to_skip = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  2312. input_api.DEFAULT_FILES_TO_SKIP)
  2313. file_filter = lambda f: input_api.FilterSourceFile(
  2314. f, files_to_check=file_inclusion_pattern, files_to_skip=files_to_skip)
  2315. action_re = r'[^a-zA-Z]UserMetricsAction\("([^"]*)'
  2316. current_actions = None
  2317. for f in input_api.AffectedFiles(file_filter=file_filter):
  2318. for line_num, line in f.ChangedContents():
  2319. match = input_api.re.search(action_re, line)
  2320. if match:
  2321. # Loads contents in tools/metrics/actions/actions.xml to memory. It's
  2322. # loaded only once.
  2323. if not current_actions:
  2324. with open(
  2325. 'tools/metrics/actions/actions.xml') as actions_f:
  2326. current_actions = actions_f.read()
  2327. # Search for the matched user action name in |current_actions|.
  2328. for action_name in match.groups():
  2329. action = 'name="{0}"'.format(action_name)
  2330. if action not in current_actions:
  2331. return [
  2332. output_api.PresubmitPromptWarning(
  2333. 'File %s line %d: %s is missing in '
  2334. 'tools/metrics/actions/actions.xml. Please run '
  2335. 'tools/metrics/actions/extract_actions.py to update.'
  2336. % (f.LocalPath(), line_num, action_name))
  2337. ]
  2338. return []
  2339. def _ImportJSONCommentEater(input_api):
  2340. import sys
  2341. sys.path = sys.path + [
  2342. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  2343. 'json_comment_eater')
  2344. ]
  2345. import json_comment_eater
  2346. return json_comment_eater
  2347. def _GetJSONParseError(input_api, filename, eat_comments=True):
  2348. try:
  2349. contents = input_api.ReadFile(filename)
  2350. if eat_comments:
  2351. json_comment_eater = _ImportJSONCommentEater(input_api)
  2352. contents = json_comment_eater.Nom(contents)
  2353. input_api.json.loads(contents)
  2354. except ValueError as e:
  2355. return e
  2356. return None
  2357. def _GetIDLParseError(input_api, filename):
  2358. try:
  2359. contents = input_api.ReadFile(filename)
  2360. idl_schema = input_api.os_path.join(input_api.PresubmitLocalPath(),
  2361. 'tools', 'json_schema_compiler',
  2362. 'idl_schema.py')
  2363. process = input_api.subprocess.Popen(
  2364. [input_api.python3_executable, idl_schema],
  2365. stdin=input_api.subprocess.PIPE,
  2366. stdout=input_api.subprocess.PIPE,
  2367. stderr=input_api.subprocess.PIPE,
  2368. universal_newlines=True)
  2369. (_, error) = process.communicate(input=contents)
  2370. return error or None
  2371. except ValueError as e:
  2372. return e
  2373. def CheckParseErrors(input_api, output_api):
  2374. """Check that IDL and JSON files do not contain syntax errors."""
  2375. actions = {
  2376. '.idl': _GetIDLParseError,
  2377. '.json': _GetJSONParseError,
  2378. }
  2379. # Most JSON files are preprocessed and support comments, but these do not.
  2380. json_no_comments_patterns = [
  2381. r'^testing[\\/]',
  2382. ]
  2383. # Only run IDL checker on files in these directories.
  2384. idl_included_patterns = [
  2385. r'^chrome[\\/]common[\\/]extensions[\\/]api[\\/]',
  2386. r'^extensions[\\/]common[\\/]api[\\/]',
  2387. ]
  2388. def get_action(affected_file):
  2389. filename = affected_file.LocalPath()
  2390. return actions.get(input_api.os_path.splitext(filename)[1])
  2391. def FilterFile(affected_file):
  2392. action = get_action(affected_file)
  2393. if not action:
  2394. return False
  2395. path = affected_file.LocalPath()
  2396. if _MatchesFile(input_api,
  2397. _KNOWN_TEST_DATA_AND_INVALID_JSON_FILE_PATTERNS, path):
  2398. return False
  2399. if (action == _GetIDLParseError
  2400. and not _MatchesFile(input_api, idl_included_patterns, path)):
  2401. return False
  2402. return True
  2403. results = []
  2404. for affected_file in input_api.AffectedFiles(file_filter=FilterFile,
  2405. include_deletes=False):
  2406. action = get_action(affected_file)
  2407. kwargs = {}
  2408. if (action == _GetJSONParseError
  2409. and _MatchesFile(input_api, json_no_comments_patterns,
  2410. affected_file.LocalPath())):
  2411. kwargs['eat_comments'] = False
  2412. parse_error = action(input_api, affected_file.AbsoluteLocalPath(),
  2413. **kwargs)
  2414. if parse_error:
  2415. results.append(
  2416. output_api.PresubmitError(
  2417. '%s could not be parsed: %s' %
  2418. (affected_file.LocalPath(), parse_error)))
  2419. return results
  2420. def CheckJavaStyle(input_api, output_api):
  2421. """Runs checkstyle on changed java files and returns errors if any exist."""
  2422. # Return early if no java files were modified.
  2423. if not any(
  2424. _IsJavaFile(input_api, f.LocalPath())
  2425. for f in input_api.AffectedFiles()):
  2426. return []
  2427. import sys
  2428. original_sys_path = sys.path
  2429. try:
  2430. sys.path = sys.path + [
  2431. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  2432. 'android', 'checkstyle')
  2433. ]
  2434. import checkstyle
  2435. finally:
  2436. # Restore sys.path to what it was before.
  2437. sys.path = original_sys_path
  2438. return checkstyle.RunCheckstyle(
  2439. input_api,
  2440. output_api,
  2441. 'tools/android/checkstyle/chromium-style-5.0.xml',
  2442. files_to_skip=_EXCLUDED_PATHS + input_api.DEFAULT_FILES_TO_SKIP)
  2443. def CheckPythonDevilInit(input_api, output_api):
  2444. """Checks to make sure devil is initialized correctly in python scripts."""
  2445. script_common_initialize_pattern = input_api.re.compile(
  2446. r'script_common\.InitializeEnvironment\(')
  2447. devil_env_config_initialize = input_api.re.compile(
  2448. r'devil_env\.config\.Initialize\(')
  2449. errors = []
  2450. sources = lambda affected_file: input_api.FilterSourceFile(
  2451. affected_file,
  2452. files_to_skip=(_EXCLUDED_PATHS + input_api.DEFAULT_FILES_TO_SKIP + (
  2453. r'^build[\\/]android[\\/]devil_chromium\.py',
  2454. r'^third_party[\\/].*',
  2455. )),
  2456. files_to_check=[r'.*\.py$'])
  2457. for f in input_api.AffectedSourceFiles(sources):
  2458. for line_num, line in f.ChangedContents():
  2459. if (script_common_initialize_pattern.search(line)
  2460. or devil_env_config_initialize.search(line)):
  2461. errors.append("%s:%d" % (f.LocalPath(), line_num))
  2462. results = []
  2463. if errors:
  2464. results.append(
  2465. output_api.PresubmitError(
  2466. 'Devil initialization should always be done using '
  2467. 'devil_chromium.Initialize() in the chromium project, to use better '
  2468. 'defaults for dependencies (ex. up-to-date version of adb).',
  2469. errors))
  2470. return results
  2471. def _MatchesFile(input_api, patterns, path):
  2472. for pattern in patterns:
  2473. if input_api.re.search(pattern, path):
  2474. return True
  2475. return False
  2476. def _GetOwnersFilesToCheckForIpcOwners(input_api):
  2477. """Gets a list of OWNERS files to check for correct security owners.
  2478. Returns:
  2479. A dictionary mapping an OWNER file to the list of OWNERS rules it must
  2480. contain to cover IPC-related files with noparent reviewer rules.
  2481. """
  2482. # Whether or not a file affects IPC is (mostly) determined by a simple list
  2483. # of filename patterns.
  2484. file_patterns = [
  2485. # Legacy IPC:
  2486. '*_messages.cc',
  2487. '*_messages*.h',
  2488. '*_param_traits*.*',
  2489. # Mojo IPC:
  2490. '*.mojom',
  2491. '*_mojom_traits*.*',
  2492. '*_struct_traits*.*',
  2493. '*_type_converter*.*',
  2494. '*.typemap',
  2495. # Android native IPC:
  2496. '*.aidl',
  2497. # Blink uses a different file naming convention:
  2498. '*EnumTraits*.*',
  2499. "*MojomTraits*.*",
  2500. '*StructTraits*.*',
  2501. '*TypeConverter*.*',
  2502. ]
  2503. # These third_party directories do not contain IPCs, but contain files
  2504. # matching the above patterns, which trigger false positives.
  2505. exclude_paths = [
  2506. 'third_party/crashpad/*',
  2507. 'third_party/blink/renderer/platform/bindings/*',
  2508. 'third_party/protobuf/benchmarks/python/*',
  2509. 'third_party/win_build_output/*',
  2510. # These files are just used to communicate between class loaders running
  2511. # in the same process.
  2512. 'weblayer/browser/java/org/chromium/weblayer_private/interfaces/*',
  2513. 'weblayer/browser/java/org/chromium/weblayer_private/test_interfaces/*',
  2514. ]
  2515. # Dictionary mapping an OWNERS file path to Patterns.
  2516. # Patterns is a dictionary mapping glob patterns (suitable for use in per-file
  2517. # rules ) to a PatternEntry.
  2518. # PatternEntry is a dictionary with two keys:
  2519. # - 'files': the files that are matched by this pattern
  2520. # - 'rules': the per-file rules needed for this pattern
  2521. # For example, if we expect OWNERS file to contain rules for *.mojom and
  2522. # *_struct_traits*.*, Patterns might look like this:
  2523. # {
  2524. # '*.mojom': {
  2525. # 'files': ...,
  2526. # 'rules': [
  2527. # 'per-file *.mojom=set noparent',
  2528. # 'per-file *.mojom=file://ipc/SECURITY_OWNERS',
  2529. # ],
  2530. # },
  2531. # '*_struct_traits*.*': {
  2532. # 'files': ...,
  2533. # 'rules': [
  2534. # 'per-file *_struct_traits*.*=set noparent',
  2535. # 'per-file *_struct_traits*.*=file://ipc/SECURITY_OWNERS',
  2536. # ],
  2537. # },
  2538. # }
  2539. to_check = {}
  2540. def AddPatternToCheck(input_file, pattern):
  2541. owners_file = input_api.os_path.join(
  2542. input_api.os_path.dirname(input_file.AbsoluteLocalPath()),
  2543. 'OWNERS')
  2544. if owners_file not in to_check:
  2545. to_check[owners_file] = {}
  2546. if pattern not in to_check[owners_file]:
  2547. to_check[owners_file][pattern] = {
  2548. 'files': [],
  2549. 'rules': [
  2550. 'per-file %s=set noparent' % pattern,
  2551. 'per-file %s=file://ipc/SECURITY_OWNERS' % pattern,
  2552. ]
  2553. }
  2554. to_check[owners_file][pattern]['files'].append(input_file)
  2555. # Iterate through the affected files to see what we actually need to check
  2556. # for. We should only nag patch authors about per-file rules if a file in that
  2557. # directory would match that pattern. If a directory only contains *.mojom
  2558. # files and no *_messages*.h files, we should only nag about rules for
  2559. # *.mojom files.
  2560. for f in input_api.AffectedFiles(include_deletes=False):
  2561. # Manifest files don't have a strong naming convention. Instead, try to find
  2562. # affected .cc and .h files which look like they contain a manifest
  2563. # definition.
  2564. manifest_pattern = input_api.re.compile('manifests?\.(cc|h)$')
  2565. test_manifest_pattern = input_api.re.compile('test_manifests?\.(cc|h)')
  2566. if (manifest_pattern.search(f.LocalPath())
  2567. and not test_manifest_pattern.search(f.LocalPath())):
  2568. # We expect all actual service manifest files to contain at least one
  2569. # qualified reference to service_manager::Manifest.
  2570. if 'service_manager::Manifest' in '\n'.join(f.NewContents()):
  2571. AddPatternToCheck(f, input_api.os_path.basename(f.LocalPath()))
  2572. for pattern in file_patterns:
  2573. if input_api.fnmatch.fnmatch(
  2574. input_api.os_path.basename(f.LocalPath()), pattern):
  2575. skip = False
  2576. for exclude in exclude_paths:
  2577. if input_api.fnmatch.fnmatch(f.LocalPath(), exclude):
  2578. skip = True
  2579. break
  2580. if skip:
  2581. continue
  2582. AddPatternToCheck(f, pattern)
  2583. break
  2584. return to_check
  2585. def _AddOwnersFilesToCheckForFuchsiaSecurityOwners(input_api, to_check):
  2586. """Adds OWNERS files to check for correct Fuchsia security owners."""
  2587. file_patterns = [
  2588. # Component specifications.
  2589. '*.cml', # Component Framework v2.
  2590. '*.cmx', # Component Framework v1.
  2591. # Fuchsia IDL protocol specifications.
  2592. '*.fidl',
  2593. ]
  2594. # Don't check for owners files for changes in these directories.
  2595. exclude_paths = [
  2596. 'third_party/crashpad/*',
  2597. ]
  2598. def AddPatternToCheck(input_file, pattern):
  2599. owners_file = input_api.os_path.join(
  2600. input_api.os_path.dirname(input_file.LocalPath()), 'OWNERS')
  2601. if owners_file not in to_check:
  2602. to_check[owners_file] = {}
  2603. if pattern not in to_check[owners_file]:
  2604. to_check[owners_file][pattern] = {
  2605. 'files': [],
  2606. 'rules': [
  2607. 'per-file %s=set noparent' % pattern,
  2608. 'per-file %s=file://fuchsia/SECURITY_OWNERS' % pattern,
  2609. ]
  2610. }
  2611. to_check[owners_file][pattern]['files'].append(input_file)
  2612. # Iterate through the affected files to see what we actually need to check
  2613. # for. We should only nag patch authors about per-file rules if a file in that
  2614. # directory would match that pattern.
  2615. for f in input_api.AffectedFiles(include_deletes=False):
  2616. skip = False
  2617. for exclude in exclude_paths:
  2618. if input_api.fnmatch.fnmatch(f.LocalPath(), exclude):
  2619. skip = True
  2620. if skip:
  2621. continue
  2622. for pattern in file_patterns:
  2623. if input_api.fnmatch.fnmatch(
  2624. input_api.os_path.basename(f.LocalPath()), pattern):
  2625. AddPatternToCheck(f, pattern)
  2626. break
  2627. return to_check
  2628. def CheckSecurityOwners(input_api, output_api):
  2629. """Checks that affected files involving IPC have an IPC OWNERS rule."""
  2630. to_check = _GetOwnersFilesToCheckForIpcOwners(input_api)
  2631. _AddOwnersFilesToCheckForFuchsiaSecurityOwners(input_api, to_check)
  2632. if to_check:
  2633. # If there are any OWNERS files to check, there are IPC-related changes in
  2634. # this CL. Auto-CC the review list.
  2635. output_api.AppendCC('ipc-security-reviews@chromium.org')
  2636. # Go through the OWNERS files to check, filtering out rules that are already
  2637. # present in that OWNERS file.
  2638. for owners_file, patterns in to_check.items():
  2639. try:
  2640. with open(owners_file) as f:
  2641. lines = set(f.read().splitlines())
  2642. for entry in patterns.values():
  2643. entry['rules'] = [
  2644. rule for rule in entry['rules'] if rule not in lines
  2645. ]
  2646. except IOError:
  2647. # No OWNERS file, so all the rules are definitely missing.
  2648. continue
  2649. # All the remaining lines weren't found in OWNERS files, so emit an error.
  2650. errors = []
  2651. for owners_file, patterns in to_check.items():
  2652. missing_lines = []
  2653. files = []
  2654. for _, entry in patterns.items():
  2655. missing_lines.extend(entry['rules'])
  2656. files.extend([' %s' % f.LocalPath() for f in entry['files']])
  2657. if missing_lines:
  2658. errors.append('Because of the presence of files:\n%s\n\n'
  2659. '%s needs the following %d lines added:\n\n%s' %
  2660. ('\n'.join(files), owners_file, len(missing_lines),
  2661. '\n'.join(missing_lines)))
  2662. results = []
  2663. if errors:
  2664. if input_api.is_committing:
  2665. output = output_api.PresubmitError
  2666. else:
  2667. output = output_api.PresubmitPromptWarning
  2668. results.append(
  2669. output(
  2670. 'Found OWNERS files that need to be updated for IPC security '
  2671. + 'review coverage.\nPlease update the OWNERS files below:',
  2672. long_text='\n\n'.join(errors)))
  2673. return results
  2674. def _GetFilesUsingSecurityCriticalFunctions(input_api):
  2675. """Checks affected files for changes to security-critical calls. This
  2676. function checks the full change diff, to catch both additions/changes
  2677. and removals.
  2678. Returns a dict keyed by file name, and the value is a set of detected
  2679. functions.
  2680. """
  2681. # Map of function pretty name (displayed in an error) to the pattern to
  2682. # match it with.
  2683. _PATTERNS_TO_CHECK = {
  2684. 'content::GetServiceSandboxType<>()': 'GetServiceSandboxType\\<'
  2685. }
  2686. _PATTERNS_TO_CHECK = {
  2687. k: input_api.re.compile(v)
  2688. for k, v in _PATTERNS_TO_CHECK.items()
  2689. }
  2690. import os
  2691. # We don't want to trigger on strings within this file.
  2692. def presubmit_file_filter(f):
  2693. return 'PRESUBMIT.py' != os.path.split(f.LocalPath())[1]
  2694. # Scan all affected files for changes touching _FUNCTIONS_TO_CHECK.
  2695. files_to_functions = {}
  2696. for f in input_api.AffectedFiles(file_filter=presubmit_file_filter):
  2697. diff = f.GenerateScmDiff()
  2698. for line in diff.split('\n'):
  2699. # Not using just RightHandSideLines() because removing a
  2700. # call to a security-critical function can be just as important
  2701. # as adding or changing the arguments.
  2702. if line.startswith('-') or (line.startswith('+')
  2703. and not line.startswith('++')):
  2704. for name, pattern in _PATTERNS_TO_CHECK.items():
  2705. if pattern.search(line):
  2706. path = f.LocalPath()
  2707. if not path in files_to_functions:
  2708. files_to_functions[path] = set()
  2709. files_to_functions[path].add(name)
  2710. return files_to_functions
  2711. def CheckSecurityChanges(input_api, output_api):
  2712. """Checks that changes involving security-critical functions are reviewed
  2713. by the security team.
  2714. """
  2715. files_to_functions = _GetFilesUsingSecurityCriticalFunctions(input_api)
  2716. if not len(files_to_functions):
  2717. return []
  2718. owner_email, reviewers = (
  2719. input_api.canned_checks.GetCodereviewOwnerAndReviewers(
  2720. input_api, None, approval_needed=input_api.is_committing))
  2721. # Load the OWNERS file for security changes.
  2722. owners_file = 'ipc/SECURITY_OWNERS'
  2723. security_owners = input_api.owners_client.ListOwners(owners_file)
  2724. has_security_owner = any([owner in reviewers for owner in security_owners])
  2725. if has_security_owner:
  2726. return []
  2727. msg = 'The following files change calls to security-sensive functions\n' \
  2728. 'that need to be reviewed by {}.\n'.format(owners_file)
  2729. for path, names in files_to_functions.items():
  2730. msg += ' {}\n'.format(path)
  2731. for name in names:
  2732. msg += ' {}\n'.format(name)
  2733. msg += '\n'
  2734. if input_api.is_committing:
  2735. output = output_api.PresubmitError
  2736. else:
  2737. output = output_api.PresubmitNotifyResult
  2738. return [output(msg)]
  2739. def CheckSetNoParent(input_api, output_api):
  2740. """Checks that set noparent is only used together with an OWNERS file in
  2741. //build/OWNERS.setnoparent (see also
  2742. //docs/code_reviews.md#owners-files-details)
  2743. """
  2744. # Return early if no OWNERS files were modified.
  2745. if not any(f.LocalPath().endswith('OWNERS')
  2746. for f in input_api.AffectedFiles(include_deletes=False)):
  2747. return []
  2748. errors = []
  2749. allowed_owners_files_file = 'build/OWNERS.setnoparent'
  2750. allowed_owners_files = set()
  2751. with open(allowed_owners_files_file, 'r') as f:
  2752. for line in f:
  2753. line = line.strip()
  2754. if not line or line.startswith('#'):
  2755. continue
  2756. allowed_owners_files.add(line)
  2757. per_file_pattern = input_api.re.compile('per-file (.+)=(.+)')
  2758. for f in input_api.AffectedFiles(include_deletes=False):
  2759. if not f.LocalPath().endswith('OWNERS'):
  2760. continue
  2761. found_owners_files = set()
  2762. found_set_noparent_lines = dict()
  2763. # Parse the OWNERS file.
  2764. for lineno, line in enumerate(f.NewContents(), 1):
  2765. line = line.strip()
  2766. if line.startswith('set noparent'):
  2767. found_set_noparent_lines[''] = lineno
  2768. if line.startswith('file://'):
  2769. if line in allowed_owners_files:
  2770. found_owners_files.add('')
  2771. if line.startswith('per-file'):
  2772. match = per_file_pattern.match(line)
  2773. if match:
  2774. glob = match.group(1).strip()
  2775. directive = match.group(2).strip()
  2776. if directive == 'set noparent':
  2777. found_set_noparent_lines[glob] = lineno
  2778. if directive.startswith('file://'):
  2779. if directive in allowed_owners_files:
  2780. found_owners_files.add(glob)
  2781. # Check that every set noparent line has a corresponding file:// line
  2782. # listed in build/OWNERS.setnoparent. An exception is made for top level
  2783. # directories since src/OWNERS shouldn't review them.
  2784. linux_path = f.LocalPath().replace(input_api.os_path.sep, '/')
  2785. if (linux_path.count('/') != 1
  2786. and (not linux_path in _EXCLUDED_SET_NO_PARENT_PATHS)):
  2787. for set_noparent_line in found_set_noparent_lines:
  2788. if set_noparent_line in found_owners_files:
  2789. continue
  2790. errors.append(' %s:%d' %
  2791. (linux_path,
  2792. found_set_noparent_lines[set_noparent_line]))
  2793. results = []
  2794. if errors:
  2795. if input_api.is_committing:
  2796. output = output_api.PresubmitError
  2797. else:
  2798. output = output_api.PresubmitPromptWarning
  2799. results.append(
  2800. output(
  2801. 'Found the following "set noparent" restrictions in OWNERS files that '
  2802. 'do not include owners from build/OWNERS.setnoparent:',
  2803. long_text='\n\n'.join(errors)))
  2804. return results
  2805. def CheckUselessForwardDeclarations(input_api, output_api):
  2806. """Checks that added or removed lines in non third party affected
  2807. header files do not lead to new useless class or struct forward
  2808. declaration.
  2809. """
  2810. results = []
  2811. class_pattern = input_api.re.compile(r'^class\s+(\w+);$',
  2812. input_api.re.MULTILINE)
  2813. struct_pattern = input_api.re.compile(r'^struct\s+(\w+);$',
  2814. input_api.re.MULTILINE)
  2815. for f in input_api.AffectedFiles(include_deletes=False):
  2816. if (f.LocalPath().startswith('third_party')
  2817. and not f.LocalPath().startswith('third_party/blink')
  2818. and not f.LocalPath().startswith('third_party\\blink')):
  2819. continue
  2820. if not f.LocalPath().endswith('.h'):
  2821. continue
  2822. contents = input_api.ReadFile(f)
  2823. fwd_decls = input_api.re.findall(class_pattern, contents)
  2824. fwd_decls.extend(input_api.re.findall(struct_pattern, contents))
  2825. useless_fwd_decls = []
  2826. for decl in fwd_decls:
  2827. count = sum(1 for _ in input_api.re.finditer(
  2828. r'\b%s\b' % input_api.re.escape(decl), contents))
  2829. if count == 1:
  2830. useless_fwd_decls.append(decl)
  2831. if not useless_fwd_decls:
  2832. continue
  2833. for line in f.GenerateScmDiff().splitlines():
  2834. if (line.startswith('-') and not line.startswith('--')
  2835. or line.startswith('+') and not line.startswith('++')):
  2836. for decl in useless_fwd_decls:
  2837. if input_api.re.search(r'\b%s\b' % decl, line[1:]):
  2838. results.append(
  2839. output_api.PresubmitPromptWarning(
  2840. '%s: %s forward declaration is no longer needed'
  2841. % (f.LocalPath(), decl)))
  2842. useless_fwd_decls.remove(decl)
  2843. return results
  2844. def _CheckAndroidDebuggableBuild(input_api, output_api):
  2845. """Checks that code uses BuildInfo.isDebugAndroid() instead of
  2846. Build.TYPE.equals('') or ''.equals(Build.TYPE) to check if
  2847. this is a debuggable build of Android.
  2848. """
  2849. build_type_check_pattern = input_api.re.compile(
  2850. r'\bBuild\.TYPE\.equals\(|\.equals\(\s*\bBuild\.TYPE\)')
  2851. errors = []
  2852. sources = lambda affected_file: input_api.FilterSourceFile(
  2853. affected_file,
  2854. files_to_skip=(
  2855. _EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS + input_api.
  2856. DEFAULT_FILES_TO_SKIP + (
  2857. r"^android_webview[\\/]support_library[\\/]"
  2858. "boundary_interfaces[\\/]",
  2859. r"^chrome[\\/]android[\\/]webapk[\\/].*",
  2860. r'^third_party[\\/].*',
  2861. r"tools[\\/]android[\\/]customtabs_benchmark[\\/].*",
  2862. r"webview[\\/]chromium[\\/]License.*",
  2863. )),
  2864. files_to_check=[r'.*\.java$'])
  2865. for f in input_api.AffectedSourceFiles(sources):
  2866. for line_num, line in f.ChangedContents():
  2867. if build_type_check_pattern.search(line):
  2868. errors.append("%s:%d" % (f.LocalPath(), line_num))
  2869. results = []
  2870. if errors:
  2871. results.append(
  2872. output_api.PresubmitPromptWarning(
  2873. 'Build.TYPE.equals or .equals(Build.TYPE) usage is detected.'
  2874. ' Please use BuildInfo.isDebugAndroid() instead.', errors))
  2875. return results
  2876. # TODO: add unit tests
  2877. def _CheckAndroidToastUsage(input_api, output_api):
  2878. """Checks that code uses org.chromium.ui.widget.Toast instead of
  2879. android.widget.Toast (Chromium Toast doesn't force hardware
  2880. acceleration on low-end devices, saving memory).
  2881. """
  2882. toast_import_pattern = input_api.re.compile(
  2883. r'^import android\.widget\.Toast;$')
  2884. errors = []
  2885. sources = lambda affected_file: input_api.FilterSourceFile(
  2886. affected_file,
  2887. files_to_skip=(_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS + input_api.
  2888. DEFAULT_FILES_TO_SKIP + (r'^chromecast[\\/].*',
  2889. r'^remoting[\\/].*')),
  2890. files_to_check=[r'.*\.java$'])
  2891. for f in input_api.AffectedSourceFiles(sources):
  2892. for line_num, line in f.ChangedContents():
  2893. if toast_import_pattern.search(line):
  2894. errors.append("%s:%d" % (f.LocalPath(), line_num))
  2895. results = []
  2896. if errors:
  2897. results.append(
  2898. output_api.PresubmitError(
  2899. 'android.widget.Toast usage is detected. Android toasts use hardware'
  2900. ' acceleration, and can be\ncostly on low-end devices. Please use'
  2901. ' org.chromium.ui.widget.Toast instead.\n'
  2902. 'Contact dskiba@chromium.org if you have any questions.',
  2903. errors))
  2904. return results
  2905. def _CheckAndroidCrLogUsage(input_api, output_api):
  2906. """Checks that new logs using org.chromium.base.Log:
  2907. - Are using 'TAG' as variable name for the tags (warn)
  2908. - Are using a tag that is shorter than 20 characters (error)
  2909. """
  2910. # Do not check format of logs in the given files
  2911. cr_log_check_excluded_paths = [
  2912. # //chrome/android/webapk cannot depend on //base
  2913. r"^chrome[\\/]android[\\/]webapk[\\/].*",
  2914. # WebView license viewer code cannot depend on //base; used in stub APK.
  2915. r"^android_webview[\\/]glue[\\/]java[\\/]src[\\/]com[\\/]android[\\/]"
  2916. r"webview[\\/]chromium[\\/]License.*",
  2917. # The customtabs_benchmark is a small app that does not depend on Chromium
  2918. # java pieces.
  2919. r"tools[\\/]android[\\/]customtabs_benchmark[\\/].*",
  2920. ]
  2921. cr_log_import_pattern = input_api.re.compile(
  2922. r'^import org\.chromium\.base\.Log;$', input_api.re.MULTILINE)
  2923. class_in_base_pattern = input_api.re.compile(
  2924. r'^package org\.chromium\.base;$', input_api.re.MULTILINE)
  2925. has_some_log_import_pattern = input_api.re.compile(r'^import .*\.Log;$',
  2926. input_api.re.MULTILINE)
  2927. # Extract the tag from lines like `Log.d(TAG, "*");` or `Log.d("TAG", "*");`
  2928. log_call_pattern = input_api.re.compile(r'\bLog\.\w\((?P<tag>\"?\w+)')
  2929. log_decl_pattern = input_api.re.compile(
  2930. r'static final String TAG = "(?P<name>(.*))"')
  2931. rough_log_decl_pattern = input_api.re.compile(r'\bString TAG\s*=')
  2932. REF_MSG = ('See docs/android_logging.md for more info.')
  2933. sources = lambda x: input_api.FilterSourceFile(
  2934. x,
  2935. files_to_check=[r'.*\.java$'],
  2936. files_to_skip=cr_log_check_excluded_paths)
  2937. tag_decl_errors = []
  2938. tag_length_errors = []
  2939. tag_errors = []
  2940. tag_with_dot_errors = []
  2941. util_log_errors = []
  2942. for f in input_api.AffectedSourceFiles(sources):
  2943. file_content = input_api.ReadFile(f)
  2944. has_modified_logs = False
  2945. # Per line checks
  2946. if (cr_log_import_pattern.search(file_content)
  2947. or (class_in_base_pattern.search(file_content)
  2948. and not has_some_log_import_pattern.search(file_content))):
  2949. # Checks to run for files using cr log
  2950. for line_num, line in f.ChangedContents():
  2951. if rough_log_decl_pattern.search(line):
  2952. has_modified_logs = True
  2953. # Check if the new line is doing some logging
  2954. match = log_call_pattern.search(line)
  2955. if match:
  2956. has_modified_logs = True
  2957. # Make sure it uses "TAG"
  2958. if not match.group('tag') == 'TAG':
  2959. tag_errors.append("%s:%d" % (f.LocalPath(), line_num))
  2960. else:
  2961. # Report non cr Log function calls in changed lines
  2962. for line_num, line in f.ChangedContents():
  2963. if log_call_pattern.search(line):
  2964. util_log_errors.append("%s:%d" % (f.LocalPath(), line_num))
  2965. # Per file checks
  2966. if has_modified_logs:
  2967. # Make sure the tag is using the "cr" prefix and is not too long
  2968. match = log_decl_pattern.search(file_content)
  2969. tag_name = match.group('name') if match else None
  2970. if not tag_name:
  2971. tag_decl_errors.append(f.LocalPath())
  2972. elif len(tag_name) > 20:
  2973. tag_length_errors.append(f.LocalPath())
  2974. elif '.' in tag_name:
  2975. tag_with_dot_errors.append(f.LocalPath())
  2976. results = []
  2977. if tag_decl_errors:
  2978. results.append(
  2979. output_api.PresubmitPromptWarning(
  2980. 'Please define your tags using the suggested format: .\n'
  2981. '"private static final String TAG = "<package tag>".\n'
  2982. 'They will be prepended with "cr_" automatically.\n' + REF_MSG,
  2983. tag_decl_errors))
  2984. if tag_length_errors:
  2985. results.append(
  2986. output_api.PresubmitError(
  2987. 'The tag length is restricted by the system to be at most '
  2988. '20 characters.\n' + REF_MSG, tag_length_errors))
  2989. if tag_errors:
  2990. results.append(
  2991. output_api.PresubmitPromptWarning(
  2992. 'Please use a variable named "TAG" for your log tags.\n' +
  2993. REF_MSG, tag_errors))
  2994. if util_log_errors:
  2995. results.append(
  2996. output_api.PresubmitPromptWarning(
  2997. 'Please use org.chromium.base.Log for new logs.\n' + REF_MSG,
  2998. util_log_errors))
  2999. if tag_with_dot_errors:
  3000. results.append(
  3001. output_api.PresubmitPromptWarning(
  3002. 'Dot in log tags cause them to be elided in crash reports.\n' +
  3003. REF_MSG, tag_with_dot_errors))
  3004. return results
  3005. def _CheckAndroidTestJUnitFrameworkImport(input_api, output_api):
  3006. """Checks that junit.framework.* is no longer used."""
  3007. deprecated_junit_framework_pattern = input_api.re.compile(
  3008. r'^import junit\.framework\..*;', input_api.re.MULTILINE)
  3009. sources = lambda x: input_api.FilterSourceFile(
  3010. x, files_to_check=[r'.*\.java$'], files_to_skip=None)
  3011. errors = []
  3012. for f in input_api.AffectedFiles(file_filter=sources):
  3013. for line_num, line in f.ChangedContents():
  3014. if deprecated_junit_framework_pattern.search(line):
  3015. errors.append("%s:%d" % (f.LocalPath(), line_num))
  3016. results = []
  3017. if errors:
  3018. results.append(
  3019. output_api.PresubmitError(
  3020. 'APIs from junit.framework.* are deprecated, please use JUnit4 framework'
  3021. '(org.junit.*) from //third_party/junit. Contact yolandyan@chromium.org'
  3022. ' if you have any question.', errors))
  3023. return results
  3024. def _CheckAndroidTestJUnitInheritance(input_api, output_api):
  3025. """Checks that if new Java test classes have inheritance.
  3026. Either the new test class is JUnit3 test or it is a JUnit4 test class
  3027. with a base class, either case is undesirable.
  3028. """
  3029. class_declaration_pattern = input_api.re.compile(r'^public class \w*Test ')
  3030. sources = lambda x: input_api.FilterSourceFile(
  3031. x, files_to_check=[r'.*Test\.java$'], files_to_skip=None)
  3032. errors = []
  3033. for f in input_api.AffectedFiles(file_filter=sources):
  3034. if not f.OldContents():
  3035. class_declaration_start_flag = False
  3036. for line_num, line in f.ChangedContents():
  3037. if class_declaration_pattern.search(line):
  3038. class_declaration_start_flag = True
  3039. if class_declaration_start_flag and ' extends ' in line:
  3040. errors.append('%s:%d' % (f.LocalPath(), line_num))
  3041. if '{' in line:
  3042. class_declaration_start_flag = False
  3043. results = []
  3044. if errors:
  3045. results.append(
  3046. output_api.PresubmitPromptWarning(
  3047. 'The newly created files include Test classes that inherits from base'
  3048. ' class. Please do not use inheritance in JUnit4 tests or add new'
  3049. ' JUnit3 tests. Contact yolandyan@chromium.org if you have any'
  3050. ' questions.', errors))
  3051. return results
  3052. def _CheckAndroidTestAnnotationUsage(input_api, output_api):
  3053. """Checks that android.test.suitebuilder.annotation.* is no longer used."""
  3054. deprecated_annotation_import_pattern = input_api.re.compile(
  3055. r'^import android\.test\.suitebuilder\.annotation\..*;',
  3056. input_api.re.MULTILINE)
  3057. sources = lambda x: input_api.FilterSourceFile(
  3058. x, files_to_check=[r'.*\.java$'], files_to_skip=None)
  3059. errors = []
  3060. for f in input_api.AffectedFiles(file_filter=sources):
  3061. for line_num, line in f.ChangedContents():
  3062. if deprecated_annotation_import_pattern.search(line):
  3063. errors.append("%s:%d" % (f.LocalPath(), line_num))
  3064. results = []
  3065. if errors:
  3066. results.append(
  3067. output_api.PresubmitError(
  3068. 'Annotations in android.test.suitebuilder.annotation have been'
  3069. ' deprecated since API level 24. Please use android.support.test.filters'
  3070. ' from //third_party/android_support_test_runner:runner_java instead.'
  3071. ' Contact yolandyan@chromium.org if you have any questions.',
  3072. errors))
  3073. return results
  3074. def _CheckAndroidNewMdpiAssetLocation(input_api, output_api):
  3075. """Checks if MDPI assets are placed in a correct directory."""
  3076. file_filter = lambda f: (f.LocalPath().endswith('.png') and
  3077. ('/res/drawable/' in f.LocalPath() or
  3078. '/res/drawable-ldrtl/' in f.LocalPath()))
  3079. errors = []
  3080. for f in input_api.AffectedFiles(include_deletes=False,
  3081. file_filter=file_filter):
  3082. errors.append(' %s' % f.LocalPath())
  3083. results = []
  3084. if errors:
  3085. results.append(
  3086. output_api.PresubmitError(
  3087. 'MDPI assets should be placed in /res/drawable-mdpi/ or '
  3088. '/res/drawable-ldrtl-mdpi/\ninstead of /res/drawable/ and'
  3089. '/res/drawable-ldrtl/.\n'
  3090. 'Contact newt@chromium.org if you have questions.', errors))
  3091. return results
  3092. def _CheckAndroidWebkitImports(input_api, output_api):
  3093. """Checks that code uses org.chromium.base.Callback instead of
  3094. android.webview.ValueCallback except in the WebView glue layer
  3095. and WebLayer.
  3096. """
  3097. valuecallback_import_pattern = input_api.re.compile(
  3098. r'^import android\.webkit\.ValueCallback;$')
  3099. errors = []
  3100. sources = lambda affected_file: input_api.FilterSourceFile(
  3101. affected_file,
  3102. files_to_skip=(_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS + input_api.
  3103. DEFAULT_FILES_TO_SKIP + (
  3104. r'^android_webview[\\/]glue[\\/].*',
  3105. r'^weblayer[\\/].*',
  3106. )),
  3107. files_to_check=[r'.*\.java$'])
  3108. for f in input_api.AffectedSourceFiles(sources):
  3109. for line_num, line in f.ChangedContents():
  3110. if valuecallback_import_pattern.search(line):
  3111. errors.append("%s:%d" % (f.LocalPath(), line_num))
  3112. results = []
  3113. if errors:
  3114. results.append(
  3115. output_api.PresubmitError(
  3116. 'android.webkit.ValueCallback usage is detected outside of the glue'
  3117. ' layer. To stay compatible with the support library, android.webkit.*'
  3118. ' classes should only be used inside the glue layer and'
  3119. ' org.chromium.base.Callback should be used instead.', errors))
  3120. return results
  3121. def _CheckAndroidXmlStyle(input_api, output_api, is_check_on_upload):
  3122. """Checks Android XML styles """
  3123. # Return early if no relevant files were modified.
  3124. if not any(
  3125. _IsXmlOrGrdFile(input_api, f.LocalPath())
  3126. for f in input_api.AffectedFiles(include_deletes=False)):
  3127. return []
  3128. import sys
  3129. original_sys_path = sys.path
  3130. try:
  3131. sys.path = sys.path + [
  3132. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  3133. 'android', 'checkxmlstyle')
  3134. ]
  3135. import checkxmlstyle
  3136. finally:
  3137. # Restore sys.path to what it was before.
  3138. sys.path = original_sys_path
  3139. if is_check_on_upload:
  3140. return checkxmlstyle.CheckStyleOnUpload(input_api, output_api)
  3141. else:
  3142. return checkxmlstyle.CheckStyleOnCommit(input_api, output_api)
  3143. def _CheckAndroidInfoBarDeprecation(input_api, output_api):
  3144. """Checks Android Infobar Deprecation """
  3145. import sys
  3146. original_sys_path = sys.path
  3147. try:
  3148. sys.path = sys.path + [
  3149. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  3150. 'android', 'infobar_deprecation')
  3151. ]
  3152. import infobar_deprecation
  3153. finally:
  3154. # Restore sys.path to what it was before.
  3155. sys.path = original_sys_path
  3156. return infobar_deprecation.CheckDeprecationOnUpload(input_api, output_api)
  3157. class _PydepsCheckerResult:
  3158. def __init__(self, cmd, pydeps_path, process, old_contents):
  3159. self._cmd = cmd
  3160. self._pydeps_path = pydeps_path
  3161. self._process = process
  3162. self._old_contents = old_contents
  3163. def GetError(self):
  3164. """Returns an error message, or None."""
  3165. import difflib
  3166. if self._process.wait() != 0:
  3167. # STDERR should already be printed.
  3168. return 'Command failed: ' + self._cmd
  3169. new_contents = self._process.stdout.read().splitlines()[2:]
  3170. if self._old_contents != new_contents:
  3171. diff = '\n'.join(
  3172. difflib.context_diff(self._old_contents, new_contents))
  3173. return ('File is stale: {}\n'
  3174. 'Diff (apply to fix):\n'
  3175. '{}\n'
  3176. 'To regenerate, run:\n\n'
  3177. ' {}').format(self._pydeps_path, diff, self._cmd)
  3178. return None
  3179. class PydepsChecker:
  3180. def __init__(self, input_api, pydeps_files):
  3181. self._file_cache = {}
  3182. self._input_api = input_api
  3183. self._pydeps_files = pydeps_files
  3184. def _LoadFile(self, path):
  3185. """Returns the list of paths within a .pydeps file relative to //."""
  3186. if path not in self._file_cache:
  3187. with open(path, encoding='utf-8') as f:
  3188. self._file_cache[path] = f.read()
  3189. return self._file_cache[path]
  3190. def _ComputeNormalizedPydepsEntries(self, pydeps_path):
  3191. """Returns an interable of paths within the .pydep, relativized to //."""
  3192. pydeps_data = self._LoadFile(pydeps_path)
  3193. uses_gn_paths = '--gn-paths' in pydeps_data
  3194. entries = (l for l in pydeps_data.splitlines()
  3195. if not l.startswith('#'))
  3196. if uses_gn_paths:
  3197. # Paths look like: //foo/bar/baz
  3198. return (e[2:] for e in entries)
  3199. else:
  3200. # Paths look like: path/relative/to/file.pydeps
  3201. os_path = self._input_api.os_path
  3202. pydeps_dir = os_path.dirname(pydeps_path)
  3203. return (os_path.normpath(os_path.join(pydeps_dir, e))
  3204. for e in entries)
  3205. def _CreateFilesToPydepsMap(self):
  3206. """Returns a map of local_path -> list_of_pydeps."""
  3207. ret = {}
  3208. for pydep_local_path in self._pydeps_files:
  3209. for path in self._ComputeNormalizedPydepsEntries(pydep_local_path):
  3210. ret.setdefault(path, []).append(pydep_local_path)
  3211. return ret
  3212. def ComputeAffectedPydeps(self):
  3213. """Returns an iterable of .pydeps files that might need regenerating."""
  3214. affected_pydeps = set()
  3215. file_to_pydeps_map = None
  3216. for f in self._input_api.AffectedFiles(include_deletes=True):
  3217. local_path = f.LocalPath()
  3218. # Changes to DEPS can lead to .pydeps changes if any .py files are in
  3219. # subrepositories. We can't figure out which files change, so re-check
  3220. # all files.
  3221. # Changes to print_python_deps.py affect all .pydeps.
  3222. if local_path in ('DEPS', 'PRESUBMIT.py'
  3223. ) or local_path.endswith('print_python_deps.py'):
  3224. return self._pydeps_files
  3225. elif local_path.endswith('.pydeps'):
  3226. if local_path in self._pydeps_files:
  3227. affected_pydeps.add(local_path)
  3228. elif local_path.endswith('.py'):
  3229. if file_to_pydeps_map is None:
  3230. file_to_pydeps_map = self._CreateFilesToPydepsMap()
  3231. affected_pydeps.update(file_to_pydeps_map.get(local_path, ()))
  3232. return affected_pydeps
  3233. def DetermineIfStaleAsync(self, pydeps_path):
  3234. """Runs print_python_deps.py to see if the files is stale."""
  3235. import os
  3236. old_pydeps_data = self._LoadFile(pydeps_path).splitlines()
  3237. if old_pydeps_data:
  3238. cmd = old_pydeps_data[1][1:].strip()
  3239. if '--output' not in cmd:
  3240. cmd += ' --output ' + pydeps_path
  3241. old_contents = old_pydeps_data[2:]
  3242. else:
  3243. # A default cmd that should work in most cases (as long as pydeps filename
  3244. # matches the script name) so that PRESUBMIT.py does not crash if pydeps
  3245. # file is empty/new.
  3246. cmd = 'build/print_python_deps.py {} --root={} --output={}'.format(
  3247. pydeps_path[:-4], os.path.dirname(pydeps_path), pydeps_path)
  3248. old_contents = []
  3249. env = dict(os.environ)
  3250. env['PYTHONDONTWRITEBYTECODE'] = '1'
  3251. process = self._input_api.subprocess.Popen(
  3252. cmd + ' --output ""',
  3253. shell=True,
  3254. env=env,
  3255. stdout=self._input_api.subprocess.PIPE,
  3256. encoding='utf-8')
  3257. return _PydepsCheckerResult(cmd, pydeps_path, process, old_contents)
  3258. def _ParseGclientArgs():
  3259. args = {}
  3260. with open('build/config/gclient_args.gni', 'r') as f:
  3261. for line in f:
  3262. line = line.strip()
  3263. if not line or line.startswith('#'):
  3264. continue
  3265. attribute, value = line.split('=')
  3266. args[attribute.strip()] = value.strip()
  3267. return args
  3268. def CheckPydepsNeedsUpdating(input_api, output_api, checker_for_tests=None):
  3269. """Checks if a .pydeps file needs to be regenerated."""
  3270. # This check is for Python dependency lists (.pydeps files), and involves
  3271. # paths not only in the PRESUBMIT.py, but also in the .pydeps files. It
  3272. # doesn't work on Windows and Mac, so skip it on other platforms.
  3273. if not input_api.platform.startswith('linux'):
  3274. return []
  3275. results = []
  3276. # First, check for new / deleted .pydeps.
  3277. for f in input_api.AffectedFiles(include_deletes=True):
  3278. # Check whether we are running the presubmit check for a file in src.
  3279. # f.LocalPath is relative to repo (src, or internal repo).
  3280. # os_path.exists is relative to src repo.
  3281. # Therefore if os_path.exists is true, it means f.LocalPath is relative
  3282. # to src and we can conclude that the pydeps is in src.
  3283. if f.LocalPath().endswith('.pydeps'):
  3284. if input_api.os_path.exists(f.LocalPath()):
  3285. if f.Action() == 'D' and f.LocalPath() in _ALL_PYDEPS_FILES:
  3286. results.append(
  3287. output_api.PresubmitError(
  3288. 'Please update _ALL_PYDEPS_FILES within //PRESUBMIT.py to '
  3289. 'remove %s' % f.LocalPath()))
  3290. elif f.Action() != 'D' and f.LocalPath(
  3291. ) not in _ALL_PYDEPS_FILES:
  3292. results.append(
  3293. output_api.PresubmitError(
  3294. 'Please update _ALL_PYDEPS_FILES within //PRESUBMIT.py to '
  3295. 'include %s' % f.LocalPath()))
  3296. if results:
  3297. return results
  3298. is_android = _ParseGclientArgs().get('checkout_android', 'false') == 'true'
  3299. checker = checker_for_tests or PydepsChecker(input_api, _ALL_PYDEPS_FILES)
  3300. affected_pydeps = set(checker.ComputeAffectedPydeps())
  3301. affected_android_pydeps = affected_pydeps.intersection(
  3302. set(_ANDROID_SPECIFIC_PYDEPS_FILES))
  3303. if affected_android_pydeps and not is_android:
  3304. results.append(
  3305. output_api.PresubmitPromptOrNotify(
  3306. 'You have changed python files that may affect pydeps for android\n'
  3307. 'specific scripts. However, the relevant presumbit check cannot be\n'
  3308. 'run because you are not using an Android checkout. To validate that\n'
  3309. 'the .pydeps are correct, re-run presubmit in an Android checkout, or\n'
  3310. 'use the android-internal-presubmit optional trybot.\n'
  3311. 'Possibly stale pydeps files:\n{}'.format(
  3312. '\n'.join(affected_android_pydeps))))
  3313. all_pydeps = _ALL_PYDEPS_FILES if is_android else _GENERIC_PYDEPS_FILES
  3314. pydeps_to_check = affected_pydeps.intersection(all_pydeps)
  3315. # Process these concurrently, as each one takes 1-2 seconds.
  3316. pydep_results = [checker.DetermineIfStaleAsync(p) for p in pydeps_to_check]
  3317. for result in pydep_results:
  3318. error_msg = result.GetError()
  3319. if error_msg:
  3320. results.append(output_api.PresubmitError(error_msg))
  3321. return results
  3322. def CheckSingletonInHeaders(input_api, output_api):
  3323. """Checks to make sure no header files have |Singleton<|."""
  3324. def FileFilter(affected_file):
  3325. # It's ok for base/memory/singleton.h to have |Singleton<|.
  3326. files_to_skip = (_EXCLUDED_PATHS + input_api.DEFAULT_FILES_TO_SKIP +
  3327. (r"^base[\\/]memory[\\/]singleton\.h$",
  3328. r"^net[\\/]quic[\\/]platform[\\/]impl[\\/]"
  3329. r"quic_singleton_impl\.h$"))
  3330. return input_api.FilterSourceFile(affected_file,
  3331. files_to_skip=files_to_skip)
  3332. pattern = input_api.re.compile(r'(?<!class\sbase::)Singleton\s*<')
  3333. files = []
  3334. for f in input_api.AffectedSourceFiles(FileFilter):
  3335. if (f.LocalPath().endswith('.h') or f.LocalPath().endswith('.hxx')
  3336. or f.LocalPath().endswith('.hpp')
  3337. or f.LocalPath().endswith('.inl')):
  3338. contents = input_api.ReadFile(f)
  3339. for line in contents.splitlines(False):
  3340. if (not line.lstrip().startswith('//')
  3341. and # Strip C++ comment.
  3342. pattern.search(line)):
  3343. files.append(f)
  3344. break
  3345. if files:
  3346. return [
  3347. output_api.PresubmitError(
  3348. 'Found base::Singleton<T> in the following header files.\n' +
  3349. 'Please move them to an appropriate source file so that the ' +
  3350. 'template gets instantiated in a single compilation unit.',
  3351. files)
  3352. ]
  3353. return []
  3354. _DEPRECATED_CSS = [
  3355. # Values
  3356. ( "-webkit-box", "flex" ),
  3357. ( "-webkit-inline-box", "inline-flex" ),
  3358. ( "-webkit-flex", "flex" ),
  3359. ( "-webkit-inline-flex", "inline-flex" ),
  3360. ( "-webkit-min-content", "min-content" ),
  3361. ( "-webkit-max-content", "max-content" ),
  3362. # Properties
  3363. ( "-webkit-background-clip", "background-clip" ),
  3364. ( "-webkit-background-origin", "background-origin" ),
  3365. ( "-webkit-background-size", "background-size" ),
  3366. ( "-webkit-box-shadow", "box-shadow" ),
  3367. ( "-webkit-user-select", "user-select" ),
  3368. # Functions
  3369. ( "-webkit-gradient", "gradient" ),
  3370. ( "-webkit-repeating-gradient", "repeating-gradient" ),
  3371. ( "-webkit-linear-gradient", "linear-gradient" ),
  3372. ( "-webkit-repeating-linear-gradient", "repeating-linear-gradient" ),
  3373. ( "-webkit-radial-gradient", "radial-gradient" ),
  3374. ( "-webkit-repeating-radial-gradient", "repeating-radial-gradient" ),
  3375. ]
  3376. # TODO: add unit tests
  3377. def CheckNoDeprecatedCss(input_api, output_api):
  3378. """ Make sure that we don't use deprecated CSS
  3379. properties, functions or values. Our external
  3380. documentation and iOS CSS for dom distiller
  3381. (reader mode) are ignored by the hooks as it
  3382. needs to be consumed by WebKit. """
  3383. results = []
  3384. file_inclusion_pattern = [r".+\.css$"]
  3385. files_to_skip = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  3386. input_api.DEFAULT_FILES_TO_SKIP +
  3387. (r"^chrome/common/extensions/docs", r"^chrome/docs",
  3388. r"^native_client_sdk"))
  3389. file_filter = lambda f: input_api.FilterSourceFile(
  3390. f, files_to_check=file_inclusion_pattern, files_to_skip=files_to_skip)
  3391. for fpath in input_api.AffectedFiles(file_filter=file_filter):
  3392. for line_num, line in fpath.ChangedContents():
  3393. for (deprecated_value, value) in _DEPRECATED_CSS:
  3394. if deprecated_value in line:
  3395. results.append(
  3396. output_api.PresubmitError(
  3397. "%s:%d: Use of deprecated CSS %s, use %s instead" %
  3398. (fpath.LocalPath(), line_num, deprecated_value,
  3399. value)))
  3400. return results
  3401. def CheckForRelativeIncludes(input_api, output_api):
  3402. bad_files = {}
  3403. for f in input_api.AffectedFiles(include_deletes=False):
  3404. if (f.LocalPath().startswith('third_party')
  3405. and not f.LocalPath().startswith('third_party/blink')
  3406. and not f.LocalPath().startswith('third_party\\blink')):
  3407. continue
  3408. if not _IsCPlusPlusFile(input_api, f.LocalPath()):
  3409. continue
  3410. relative_includes = [
  3411. line for _, line in f.ChangedContents()
  3412. if "#include" in line and "../" in line
  3413. ]
  3414. if not relative_includes:
  3415. continue
  3416. bad_files[f.LocalPath()] = relative_includes
  3417. if not bad_files:
  3418. return []
  3419. error_descriptions = []
  3420. for file_path, bad_lines in bad_files.items():
  3421. error_description = file_path
  3422. for line in bad_lines:
  3423. error_description += '\n ' + line
  3424. error_descriptions.append(error_description)
  3425. results = []
  3426. results.append(
  3427. output_api.PresubmitError(
  3428. 'You added one or more relative #include paths (including "../").\n'
  3429. 'These shouldn\'t be used because they can be used to include headers\n'
  3430. 'from code that\'s not correctly specified as a dependency in the\n'
  3431. 'relevant BUILD.gn file(s).', error_descriptions))
  3432. return results
  3433. def CheckForCcIncludes(input_api, output_api):
  3434. """Check that nobody tries to include a cc file. It's a relatively
  3435. common error which results in duplicate symbols in object
  3436. files. This may not always break the build until someone later gets
  3437. very confusing linking errors."""
  3438. results = []
  3439. for f in input_api.AffectedFiles(include_deletes=False):
  3440. # We let third_party code do whatever it wants
  3441. if (f.LocalPath().startswith('third_party')
  3442. and not f.LocalPath().startswith('third_party/blink')
  3443. and not f.LocalPath().startswith('third_party\\blink')):
  3444. continue
  3445. if not _IsCPlusPlusFile(input_api, f.LocalPath()):
  3446. continue
  3447. for _, line in f.ChangedContents():
  3448. if line.startswith('#include "'):
  3449. included_file = line.split('"')[1]
  3450. if _IsCPlusPlusFile(input_api, included_file):
  3451. # The most common naming for external files with C++ code,
  3452. # apart from standard headers, is to call them foo.inc, but
  3453. # Chromium sometimes uses foo-inc.cc so allow that as well.
  3454. if not included_file.endswith(('.h', '-inc.cc')):
  3455. results.append(
  3456. output_api.PresubmitError(
  3457. 'Only header files or .inc files should be included in other\n'
  3458. 'C++ files. Compiling the contents of a cc file more than once\n'
  3459. 'will cause duplicate information in the build which may later\n'
  3460. 'result in strange link_errors.\n' +
  3461. f.LocalPath() + ':\n ' + line))
  3462. return results
  3463. def _CheckWatchlistDefinitionsEntrySyntax(key, value, ast):
  3464. if not isinstance(key, ast.Str):
  3465. return 'Key at line %d must be a string literal' % key.lineno
  3466. if not isinstance(value, ast.Dict):
  3467. return 'Value at line %d must be a dict' % value.lineno
  3468. if len(value.keys) != 1:
  3469. return 'Dict at line %d must have single entry' % value.lineno
  3470. if not isinstance(value.keys[0], ast.Str) or value.keys[0].s != 'filepath':
  3471. return (
  3472. 'Entry at line %d must have a string literal \'filepath\' as key' %
  3473. value.lineno)
  3474. return None
  3475. def _CheckWatchlistsEntrySyntax(key, value, ast, email_regex):
  3476. if not isinstance(key, ast.Str):
  3477. return 'Key at line %d must be a string literal' % key.lineno
  3478. if not isinstance(value, ast.List):
  3479. return 'Value at line %d must be a list' % value.lineno
  3480. for element in value.elts:
  3481. if not isinstance(element, ast.Str):
  3482. return 'Watchlist elements on line %d is not a string' % key.lineno
  3483. if not email_regex.match(element.s):
  3484. return ('Watchlist element on line %d doesn\'t look like a valid '
  3485. + 'email: %s') % (key.lineno, element.s)
  3486. return None
  3487. def _CheckWATCHLISTSEntries(wd_dict, w_dict, input_api):
  3488. mismatch_template = (
  3489. 'Mismatch between WATCHLIST_DEFINITIONS entry (%s) and WATCHLISTS '
  3490. 'entry (%s)')
  3491. email_regex = input_api.re.compile(
  3492. r"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]+$")
  3493. ast = input_api.ast
  3494. i = 0
  3495. last_key = ''
  3496. while True:
  3497. if i >= len(wd_dict.keys):
  3498. if i >= len(w_dict.keys):
  3499. return None
  3500. return mismatch_template % ('missing',
  3501. 'line %d' % w_dict.keys[i].lineno)
  3502. elif i >= len(w_dict.keys):
  3503. return (mismatch_template %
  3504. ('line %d' % wd_dict.keys[i].lineno, 'missing'))
  3505. wd_key = wd_dict.keys[i]
  3506. w_key = w_dict.keys[i]
  3507. result = _CheckWatchlistDefinitionsEntrySyntax(wd_key,
  3508. wd_dict.values[i], ast)
  3509. if result is not None:
  3510. return 'Bad entry in WATCHLIST_DEFINITIONS dict: %s' % result
  3511. result = _CheckWatchlistsEntrySyntax(w_key, w_dict.values[i], ast,
  3512. email_regex)
  3513. if result is not None:
  3514. return 'Bad entry in WATCHLISTS dict: %s' % result
  3515. if wd_key.s != w_key.s:
  3516. return mismatch_template % ('%s at line %d' %
  3517. (wd_key.s, wd_key.lineno),
  3518. '%s at line %d' %
  3519. (w_key.s, w_key.lineno))
  3520. if wd_key.s < last_key:
  3521. return (
  3522. 'WATCHLISTS dict is not sorted lexicographically at line %d and %d'
  3523. % (wd_key.lineno, w_key.lineno))
  3524. last_key = wd_key.s
  3525. i = i + 1
  3526. def _CheckWATCHLISTSSyntax(expression, input_api):
  3527. ast = input_api.ast
  3528. if not isinstance(expression, ast.Expression):
  3529. return 'WATCHLISTS file must contain a valid expression'
  3530. dictionary = expression.body
  3531. if not isinstance(dictionary, ast.Dict) or len(dictionary.keys) != 2:
  3532. return 'WATCHLISTS file must have single dict with exactly two entries'
  3533. first_key = dictionary.keys[0]
  3534. first_value = dictionary.values[0]
  3535. second_key = dictionary.keys[1]
  3536. second_value = dictionary.values[1]
  3537. if (not isinstance(first_key, ast.Str)
  3538. or first_key.s != 'WATCHLIST_DEFINITIONS'
  3539. or not isinstance(first_value, ast.Dict)):
  3540. return ('The first entry of the dict in WATCHLISTS file must be '
  3541. 'WATCHLIST_DEFINITIONS dict')
  3542. if (not isinstance(second_key, ast.Str) or second_key.s != 'WATCHLISTS'
  3543. or not isinstance(second_value, ast.Dict)):
  3544. return ('The second entry of the dict in WATCHLISTS file must be '
  3545. 'WATCHLISTS dict')
  3546. return _CheckWATCHLISTSEntries(first_value, second_value, input_api)
  3547. def CheckWATCHLISTS(input_api, output_api):
  3548. for f in input_api.AffectedFiles(include_deletes=False):
  3549. if f.LocalPath() == 'WATCHLISTS':
  3550. contents = input_api.ReadFile(f, 'r')
  3551. try:
  3552. # First, make sure that it can be evaluated.
  3553. input_api.ast.literal_eval(contents)
  3554. # Get an AST tree for it and scan the tree for detailed style checking.
  3555. expression = input_api.ast.parse(contents,
  3556. filename='WATCHLISTS',
  3557. mode='eval')
  3558. except ValueError as e:
  3559. return [
  3560. output_api.PresubmitError('Cannot parse WATCHLISTS file',
  3561. long_text=repr(e))
  3562. ]
  3563. except SyntaxError as e:
  3564. return [
  3565. output_api.PresubmitError('Cannot parse WATCHLISTS file',
  3566. long_text=repr(e))
  3567. ]
  3568. except TypeError as e:
  3569. return [
  3570. output_api.PresubmitError('Cannot parse WATCHLISTS file',
  3571. long_text=repr(e))
  3572. ]
  3573. result = _CheckWATCHLISTSSyntax(expression, input_api)
  3574. if result is not None:
  3575. return [output_api.PresubmitError(result)]
  3576. break
  3577. return []
  3578. def CheckGnGlobForward(input_api, output_api):
  3579. """Checks that forward_variables_from(invoker, "*") follows best practices.
  3580. As documented at //build/docs/writing_gn_templates.md
  3581. """
  3582. def gn_files(f):
  3583. return input_api.FilterSourceFile(f, files_to_check=(r'.+\.gni', ))
  3584. problems = []
  3585. for f in input_api.AffectedSourceFiles(gn_files):
  3586. for line_num, line in f.ChangedContents():
  3587. if 'forward_variables_from(invoker, "*")' in line:
  3588. problems.append(
  3589. 'Bare forward_variables_from(invoker, "*") in %s:%d' %
  3590. (f.LocalPath(), line_num))
  3591. if problems:
  3592. return [
  3593. output_api.PresubmitPromptWarning(
  3594. 'forward_variables_from("*") without exclusions',
  3595. items=sorted(problems),
  3596. long_text=(
  3597. 'The variables "visibilty" and "test_only" should be '
  3598. 'explicitly listed in forward_variables_from(). For more '
  3599. 'details, see:\n'
  3600. 'https://chromium.googlesource.com/chromium/src/+/HEAD/'
  3601. 'build/docs/writing_gn_templates.md'
  3602. '#Using-forward_variables_from'))
  3603. ]
  3604. return []
  3605. def CheckNewHeaderWithoutGnChangeOnUpload(input_api, output_api):
  3606. """Checks that newly added header files have corresponding GN changes.
  3607. Note that this is only a heuristic. To be precise, run script:
  3608. build/check_gn_headers.py.
  3609. """
  3610. def headers(f):
  3611. return input_api.FilterSourceFile(
  3612. f, files_to_check=(r'.+%s' % _HEADER_EXTENSIONS, ))
  3613. new_headers = []
  3614. for f in input_api.AffectedSourceFiles(headers):
  3615. if f.Action() != 'A':
  3616. continue
  3617. new_headers.append(f.LocalPath())
  3618. def gn_files(f):
  3619. return input_api.FilterSourceFile(f, files_to_check=(r'.+\.gn', ))
  3620. all_gn_changed_contents = ''
  3621. for f in input_api.AffectedSourceFiles(gn_files):
  3622. for _, line in f.ChangedContents():
  3623. all_gn_changed_contents += line
  3624. problems = []
  3625. for header in new_headers:
  3626. basename = input_api.os_path.basename(header)
  3627. if basename not in all_gn_changed_contents:
  3628. problems.append(header)
  3629. if problems:
  3630. return [
  3631. output_api.PresubmitPromptWarning(
  3632. 'Missing GN changes for new header files',
  3633. items=sorted(problems),
  3634. long_text=
  3635. 'Please double check whether newly added header files need '
  3636. 'corresponding changes in gn or gni files.\nThis checking is only a '
  3637. 'heuristic. Run build/check_gn_headers.py to be precise.\n'
  3638. 'Read https://crbug.com/661774 for more info.')
  3639. ]
  3640. return []
  3641. def CheckCorrectProductNameInMessages(input_api, output_api):
  3642. """Check that Chromium-branded strings don't include "Chrome" or vice versa.
  3643. This assumes we won't intentionally reference one product from the other
  3644. product.
  3645. """
  3646. all_problems = []
  3647. test_cases = [{
  3648. "filename_postfix": "google_chrome_strings.grd",
  3649. "correct_name": "Chrome",
  3650. "incorrect_name": "Chromium",
  3651. }, {
  3652. "filename_postfix": "chromium_strings.grd",
  3653. "correct_name": "Chromium",
  3654. "incorrect_name": "Chrome",
  3655. }]
  3656. for test_case in test_cases:
  3657. problems = []
  3658. filename_filter = lambda x: x.LocalPath().endswith(test_case[
  3659. "filename_postfix"])
  3660. # Check each new line. Can yield false positives in multiline comments, but
  3661. # easier than trying to parse the XML because messages can have nested
  3662. # children, and associating message elements with affected lines is hard.
  3663. for f in input_api.AffectedSourceFiles(filename_filter):
  3664. for line_num, line in f.ChangedContents():
  3665. if "<message" in line or "<!--" in line or "-->" in line:
  3666. continue
  3667. if test_case["incorrect_name"] in line:
  3668. problems.append("Incorrect product name in %s:%d" %
  3669. (f.LocalPath(), line_num))
  3670. if problems:
  3671. message = (
  3672. "Strings in %s-branded string files should reference \"%s\", not \"%s\""
  3673. % (test_case["correct_name"], test_case["correct_name"],
  3674. test_case["incorrect_name"]))
  3675. all_problems.append(
  3676. output_api.PresubmitPromptWarning(message, items=problems))
  3677. return all_problems
  3678. def CheckForTooLargeFiles(input_api, output_api):
  3679. """Avoid large files, especially binary files, in the repository since
  3680. git doesn't scale well for those. They will be in everyone's repo
  3681. clones forever, forever making Chromium slower to clone and work
  3682. with."""
  3683. # Uploading files to cloud storage is not trivial so we don't want
  3684. # to set the limit too low, but the upper limit for "normal" large
  3685. # files seems to be 1-2 MB, with a handful around 5-8 MB, so
  3686. # anything over 20 MB is exceptional.
  3687. TOO_LARGE_FILE_SIZE_LIMIT = 20 * 1024 * 1024 # 10 MB
  3688. too_large_files = []
  3689. for f in input_api.AffectedFiles():
  3690. # Check both added and modified files (but not deleted files).
  3691. if f.Action() in ('A', 'M'):
  3692. size = input_api.os_path.getsize(f.AbsoluteLocalPath())
  3693. if size > TOO_LARGE_FILE_SIZE_LIMIT:
  3694. too_large_files.append("%s: %d bytes" % (f.LocalPath(), size))
  3695. if too_large_files:
  3696. message = (
  3697. 'Do not commit large files to git since git scales badly for those.\n'
  3698. +
  3699. 'Instead put the large files in cloud storage and use DEPS to\n' +
  3700. 'fetch them.\n' + '\n'.join(too_large_files))
  3701. return [
  3702. output_api.PresubmitError('Too large files found in commit',
  3703. long_text=message + '\n')
  3704. ]
  3705. else:
  3706. return []
  3707. def CheckFuzzTargetsOnUpload(input_api, output_api):
  3708. """Checks specific for fuzz target sources."""
  3709. EXPORTED_SYMBOLS = [
  3710. 'LLVMFuzzerInitialize',
  3711. 'LLVMFuzzerCustomMutator',
  3712. 'LLVMFuzzerCustomCrossOver',
  3713. 'LLVMFuzzerMutate',
  3714. ]
  3715. REQUIRED_HEADER = '#include "testing/libfuzzer/libfuzzer_exports.h"'
  3716. def FilterFile(affected_file):
  3717. """Ignore libFuzzer source code."""
  3718. files_to_check = r'.*fuzz.*\.(h|hpp|hcc|cc|cpp|cxx)$'
  3719. files_to_skip = r"^third_party[\\/]libFuzzer"
  3720. return input_api.FilterSourceFile(affected_file,
  3721. files_to_check=[files_to_check],
  3722. files_to_skip=[files_to_skip])
  3723. files_with_missing_header = []
  3724. for f in input_api.AffectedSourceFiles(FilterFile):
  3725. contents = input_api.ReadFile(f, 'r')
  3726. if REQUIRED_HEADER in contents:
  3727. continue
  3728. if any(symbol in contents for symbol in EXPORTED_SYMBOLS):
  3729. files_with_missing_header.append(f.LocalPath())
  3730. if not files_with_missing_header:
  3731. return []
  3732. long_text = (
  3733. 'If you define any of the libFuzzer optional functions (%s), it is '
  3734. 'recommended to add \'%s\' directive. Otherwise, the fuzz target may '
  3735. 'work incorrectly on Mac (crbug.com/687076).\nNote that '
  3736. 'LLVMFuzzerInitialize should not be used, unless your fuzz target needs '
  3737. 'to access command line arguments passed to the fuzzer. Instead, prefer '
  3738. 'static initialization and shared resources as documented in '
  3739. 'https://chromium.googlesource.com/chromium/src/+/main/testing/'
  3740. 'libfuzzer/efficient_fuzzing.md#simplifying-initialization_cleanup.\n'
  3741. % (', '.join(EXPORTED_SYMBOLS), REQUIRED_HEADER))
  3742. return [
  3743. output_api.PresubmitPromptWarning(message="Missing '%s' in:" %
  3744. REQUIRED_HEADER,
  3745. items=files_with_missing_header,
  3746. long_text=long_text)
  3747. ]
  3748. def _CheckNewImagesWarning(input_api, output_api):
  3749. """
  3750. Warns authors who add images into the repo to make sure their images are
  3751. optimized before committing.
  3752. """
  3753. images_added = False
  3754. image_paths = []
  3755. errors = []
  3756. filter_lambda = lambda x: input_api.FilterSourceFile(
  3757. x,
  3758. files_to_skip=(('(?i).*test', r'.*\/junit\/') + input_api.
  3759. DEFAULT_FILES_TO_SKIP),
  3760. files_to_check=[r'.*\/(drawable|mipmap)'])
  3761. for f in input_api.AffectedFiles(include_deletes=False,
  3762. file_filter=filter_lambda):
  3763. local_path = f.LocalPath().lower()
  3764. if any(
  3765. local_path.endswith(extension)
  3766. for extension in _IMAGE_EXTENSIONS):
  3767. images_added = True
  3768. image_paths.append(f)
  3769. if images_added:
  3770. errors.append(
  3771. output_api.PresubmitPromptWarning(
  3772. 'It looks like you are trying to commit some images. If these are '
  3773. 'non-test-only images, please make sure to read and apply the tips in '
  3774. 'https://chromium.googlesource.com/chromium/src/+/HEAD/docs/speed/'
  3775. 'binary_size/optimization_advice.md#optimizing-images\nThis check is '
  3776. 'FYI only and will not block your CL on the CQ.', image_paths))
  3777. return errors
  3778. def ChecksAndroidSpecificOnUpload(input_api, output_api):
  3779. """Groups upload checks that target android code."""
  3780. results = []
  3781. results.extend(_CheckAndroidCrLogUsage(input_api, output_api))
  3782. results.extend(_CheckAndroidDebuggableBuild(input_api, output_api))
  3783. results.extend(_CheckAndroidNewMdpiAssetLocation(input_api, output_api))
  3784. results.extend(_CheckAndroidToastUsage(input_api, output_api))
  3785. results.extend(_CheckAndroidTestJUnitInheritance(input_api, output_api))
  3786. results.extend(_CheckAndroidTestJUnitFrameworkImport(
  3787. input_api, output_api))
  3788. results.extend(_CheckAndroidTestAnnotationUsage(input_api, output_api))
  3789. results.extend(_CheckAndroidWebkitImports(input_api, output_api))
  3790. results.extend(_CheckAndroidXmlStyle(input_api, output_api, True))
  3791. results.extend(_CheckNewImagesWarning(input_api, output_api))
  3792. results.extend(_CheckAndroidNoBannedImports(input_api, output_api))
  3793. results.extend(_CheckAndroidInfoBarDeprecation(input_api, output_api))
  3794. return results
  3795. def ChecksAndroidSpecificOnCommit(input_api, output_api):
  3796. """Groups commit checks that target android code."""
  3797. results = []
  3798. results.extend(_CheckAndroidXmlStyle(input_api, output_api, False))
  3799. return results
  3800. # TODO(chrishall): could we additionally match on any path owned by
  3801. # ui/accessibility/OWNERS ?
  3802. _ACCESSIBILITY_PATHS = (
  3803. r"^chrome[\\/]browser.*[\\/]accessibility[\\/]",
  3804. r"^chrome[\\/]browser[\\/]extensions[\\/]api[\\/]automation.*[\\/]",
  3805. r"^chrome[\\/]renderer[\\/]extensions[\\/]accessibility_.*",
  3806. r"^chrome[\\/]tests[\\/]data[\\/]accessibility[\\/]",
  3807. r"^content[\\/]browser[\\/]accessibility[\\/]",
  3808. r"^content[\\/]renderer[\\/]accessibility[\\/]",
  3809. r"^content[\\/]tests[\\/]data[\\/]accessibility[\\/]",
  3810. r"^extensions[\\/]renderer[\\/]api[\\/]automation[\\/]",
  3811. r"^ui[\\/]accessibility[\\/]",
  3812. r"^ui[\\/]views[\\/]accessibility[\\/]",
  3813. )
  3814. def CheckAccessibilityRelnotesField(input_api, output_api):
  3815. """Checks that commits to accessibility code contain an AX-Relnotes field in
  3816. their commit message."""
  3817. def FileFilter(affected_file):
  3818. paths = _ACCESSIBILITY_PATHS
  3819. return input_api.FilterSourceFile(affected_file, files_to_check=paths)
  3820. # Only consider changes affecting accessibility paths.
  3821. if not any(input_api.AffectedFiles(file_filter=FileFilter)):
  3822. return []
  3823. # AX-Relnotes can appear in either the description or the footer.
  3824. # When searching the description, require 'AX-Relnotes:' to appear at the
  3825. # beginning of a line.
  3826. ax_regex = input_api.re.compile('ax-relnotes[:=]')
  3827. description_has_relnotes = any(
  3828. ax_regex.match(line)
  3829. for line in input_api.change.DescriptionText().lower().splitlines())
  3830. footer_relnotes = input_api.change.GitFootersFromDescription().get(
  3831. 'AX-Relnotes', [])
  3832. if description_has_relnotes or footer_relnotes:
  3833. return []
  3834. # TODO(chrishall): link to Relnotes documentation in message.
  3835. message = (
  3836. "Missing 'AX-Relnotes:' field required for accessibility changes"
  3837. "\n please add 'AX-Relnotes: [release notes].' to describe any "
  3838. "user-facing changes"
  3839. "\n otherwise add 'AX-Relnotes: n/a.' if this change has no "
  3840. "user-facing effects"
  3841. "\n if this is confusing or annoying then please contact members "
  3842. "of ui/accessibility/OWNERS.")
  3843. return [output_api.PresubmitNotifyResult(message)]
  3844. _ACCESSIBILITY_EVENTS_TEST_PATH = (
  3845. r"^content[\\/]test[\\/]data[\\/]accessibility[\\/]event[\\/].*\.html",
  3846. )
  3847. _ACCESSIBILITY_TREE_TEST_PATH = (
  3848. r"^content[\\/]test[\\/]data[\\/]accessibility[\\/]accname[\\/].*\.html",
  3849. r"^content[\\/]test[\\/]data[\\/]accessibility[\\/]aria[\\/].*\.html",
  3850. r"^content[\\/]test[\\/]data[\\/]accessibility[\\/]css[\\/].*\.html",
  3851. r"^content[\\/]test[\\/]data[\\/]accessibility[\\/]html[\\/].*\.html",
  3852. )
  3853. _ACCESSIBILITY_ANDROID_EVENTS_TEST_PATH = (
  3854. r"^.*[\\/]WebContentsAccessibilityEventsTest\.java",
  3855. )
  3856. _ACCESSIBILITY_ANDROID_TREE_TEST_PATH = (
  3857. r"^.*[\\/]WebContentsAccessibilityTreeTest\.java",
  3858. )
  3859. def CheckAccessibilityEventsTestsAreIncludedForAndroid(input_api, output_api):
  3860. """Checks that commits that include a newly added, renamed/moved, or deleted
  3861. test in the DumpAccessibilityEventsTest suite also includes a corresponding
  3862. change to the Android test."""
  3863. def FilePathFilter(affected_file):
  3864. paths = _ACCESSIBILITY_EVENTS_TEST_PATH
  3865. return input_api.FilterSourceFile(affected_file, files_to_check=paths)
  3866. def AndroidFilePathFilter(affected_file):
  3867. paths = _ACCESSIBILITY_ANDROID_EVENTS_TEST_PATH
  3868. return input_api.FilterSourceFile(affected_file, files_to_check=paths)
  3869. # Only consider changes in the events test data path with html type.
  3870. if not any(
  3871. input_api.AffectedFiles(include_deletes=True,
  3872. file_filter=FilePathFilter)):
  3873. return []
  3874. # If the commit contains any change to the Android test file, ignore.
  3875. if any(
  3876. input_api.AffectedFiles(include_deletes=True,
  3877. file_filter=AndroidFilePathFilter)):
  3878. return []
  3879. # Only consider changes that are adding/renaming or deleting a file
  3880. message = []
  3881. for f in input_api.AffectedFiles(include_deletes=True,
  3882. file_filter=FilePathFilter):
  3883. if f.Action() == 'A' or f.Action() == 'D':
  3884. message = (
  3885. "It appears that you are adding, renaming or deleting"
  3886. "\na dump_accessibility_events* test, but have not included"
  3887. "\na corresponding change for Android."
  3888. "\nPlease include (or remove) the test from:"
  3889. "\n content/public/android/javatests/src/org/chromium/"
  3890. "content/browser/accessibility/"
  3891. "WebContentsAccessibilityEventsTest.java"
  3892. "\nIf this message is confusing or annoying, please contact"
  3893. "\nmembers of ui/accessibility/OWNERS.")
  3894. # If no message was set, return empty.
  3895. if not len(message):
  3896. return []
  3897. return [output_api.PresubmitPromptWarning(message)]
  3898. def CheckAccessibilityTreeTestsAreIncludedForAndroid(input_api, output_api):
  3899. """Checks that commits that include a newly added, renamed/moved, or deleted
  3900. test in the DumpAccessibilityTreeTest suite also includes a corresponding
  3901. change to the Android test."""
  3902. def FilePathFilter(affected_file):
  3903. paths = _ACCESSIBILITY_TREE_TEST_PATH
  3904. return input_api.FilterSourceFile(affected_file, files_to_check=paths)
  3905. def AndroidFilePathFilter(affected_file):
  3906. paths = _ACCESSIBILITY_ANDROID_TREE_TEST_PATH
  3907. return input_api.FilterSourceFile(affected_file, files_to_check=paths)
  3908. # Only consider changes in the various tree test data paths with html type.
  3909. if not any(
  3910. input_api.AffectedFiles(include_deletes=True,
  3911. file_filter=FilePathFilter)):
  3912. return []
  3913. # If the commit contains any change to the Android test file, ignore.
  3914. if any(
  3915. input_api.AffectedFiles(include_deletes=True,
  3916. file_filter=AndroidFilePathFilter)):
  3917. return []
  3918. # Only consider changes that are adding/renaming or deleting a file
  3919. message = []
  3920. for f in input_api.AffectedFiles(include_deletes=True,
  3921. file_filter=FilePathFilter):
  3922. if f.Action() == 'A' or f.Action() == 'D':
  3923. message = (
  3924. "It appears that you are adding, renaming or deleting"
  3925. "\na dump_accessibility_tree* test, but have not included"
  3926. "\na corresponding change for Android."
  3927. "\nPlease include (or remove) the test from:"
  3928. "\n content/public/android/javatests/src/org/chromium/"
  3929. "content/browser/accessibility/"
  3930. "WebContentsAccessibilityTreeTest.java"
  3931. "\nIf this message is confusing or annoying, please contact"
  3932. "\nmembers of ui/accessibility/OWNERS.")
  3933. # If no message was set, return empty.
  3934. if not len(message):
  3935. return []
  3936. return [output_api.PresubmitPromptWarning(message)]
  3937. # string pattern, sequence of strings to show when pattern matches,
  3938. # error flag. True if match is a presubmit error, otherwise it's a warning.
  3939. _NON_INCLUSIVE_TERMS = (
  3940. (
  3941. # Note that \b pattern in python re is pretty particular. In this
  3942. # regexp, 'class WhiteList ...' will match, but 'class FooWhiteList
  3943. # ...' will not. This may require some tweaking to catch these cases
  3944. # without triggering a lot of false positives. Leaving it naive and
  3945. # less matchy for now.
  3946. r'/\b(?i)((black|white)list|master|slave)\b', # nocheck
  3947. (
  3948. 'Please don\'t use blacklist, whitelist, ' # nocheck
  3949. 'or slave in your', # nocheck
  3950. 'code and make every effort to use other terms. Using "// nocheck"',
  3951. '"# nocheck" or "<!-- nocheck -->"',
  3952. 'at the end of the offending line will bypass this PRESUBMIT error',
  3953. 'but avoid using this whenever possible. Reach out to',
  3954. 'community@chromium.org if you have questions'),
  3955. True),)
  3956. def ChecksCommon(input_api, output_api):
  3957. """Checks common to both upload and commit."""
  3958. results = []
  3959. results.extend(
  3960. input_api.canned_checks.PanProjectChecks(
  3961. input_api, output_api, excluded_paths=_EXCLUDED_PATHS))
  3962. author = input_api.change.author_email
  3963. if author and author not in _KNOWN_ROBOTS:
  3964. results.extend(
  3965. input_api.canned_checks.CheckAuthorizedAuthor(
  3966. input_api, output_api))
  3967. results.extend(
  3968. input_api.canned_checks.CheckChangeHasNoTabs(
  3969. input_api,
  3970. output_api,
  3971. source_file_filter=lambda x: x.LocalPath().endswith('.grd')))
  3972. results.extend(
  3973. input_api.RunTests(
  3974. input_api.canned_checks.CheckVPythonSpec(input_api, output_api)))
  3975. dirmd = 'dirmd.bat' if input_api.is_windows else 'dirmd'
  3976. dirmd_bin = input_api.os_path.join(input_api.PresubmitLocalPath(),
  3977. 'third_party', 'depot_tools', dirmd)
  3978. results.extend(
  3979. input_api.RunTests(
  3980. input_api.canned_checks.CheckDirMetadataFormat(
  3981. input_api, output_api, dirmd_bin)))
  3982. results.extend(
  3983. input_api.canned_checks.CheckOwnersDirMetadataExclusive(
  3984. input_api, output_api))
  3985. results.extend(
  3986. input_api.canned_checks.CheckNoNewMetadataInOwners(
  3987. input_api, output_api))
  3988. results.extend(
  3989. input_api.canned_checks.CheckInclusiveLanguage(
  3990. input_api,
  3991. output_api,
  3992. excluded_directories_relative_path=[
  3993. 'infra', 'inclusive_language_presubmit_exempt_dirs.txt'
  3994. ],
  3995. non_inclusive_terms=_NON_INCLUSIVE_TERMS))
  3996. for f in input_api.AffectedFiles():
  3997. path, name = input_api.os_path.split(f.LocalPath())
  3998. if name == 'PRESUBMIT.py':
  3999. full_path = input_api.os_path.join(input_api.PresubmitLocalPath(),
  4000. path)
  4001. test_file = input_api.os_path.join(path, 'PRESUBMIT_test.py')
  4002. if f.Action() != 'D' and input_api.os_path.exists(test_file):
  4003. # The PRESUBMIT.py file (and the directory containing it) might
  4004. # have been affected by being moved or removed, so only try to
  4005. # run the tests if they still exist.
  4006. use_python3 = False
  4007. with open(f.LocalPath()) as fp:
  4008. use_python3 = any(
  4009. line.startswith('USE_PYTHON3 = True')
  4010. for line in fp.readlines())
  4011. results.extend(
  4012. input_api.canned_checks.RunUnitTestsInDirectory(
  4013. input_api,
  4014. output_api,
  4015. full_path,
  4016. files_to_check=[r'^PRESUBMIT_test\.py$'],
  4017. run_on_python2=not use_python3,
  4018. run_on_python3=use_python3,
  4019. skip_shebang_check=True))
  4020. return results
  4021. def CheckPatchFiles(input_api, output_api):
  4022. problems = [
  4023. f.LocalPath() for f in input_api.AffectedFiles()
  4024. if f.LocalPath().endswith(('.orig', '.rej'))
  4025. ]
  4026. # Cargo.toml.orig files are part of third-party crates downloaded from
  4027. # crates.io and should be included.
  4028. problems = [f for f in problems if not f.endswith('Cargo.toml.orig')]
  4029. if problems:
  4030. return [
  4031. output_api.PresubmitError("Don't commit .rej and .orig files.",
  4032. problems)
  4033. ]
  4034. else:
  4035. return []
  4036. def CheckBuildConfigMacrosWithoutInclude(input_api, output_api):
  4037. # Excludes OS_CHROMEOS, which is not defined in build_config.h.
  4038. macro_re = input_api.re.compile(
  4039. r'^\s*#(el)?if.*\bdefined\(((COMPILER_|ARCH_CPU_|WCHAR_T_IS_)[^)]*)')
  4040. include_re = input_api.re.compile(r'^#include\s+"build/build_config.h"',
  4041. input_api.re.MULTILINE)
  4042. extension_re = input_api.re.compile(r'\.[a-z]+$')
  4043. errors = []
  4044. for f in input_api.AffectedFiles(include_deletes=False):
  4045. if not f.LocalPath().endswith(
  4046. ('.h', '.c', '.cc', '.cpp', '.m', '.mm')):
  4047. continue
  4048. found_line_number = None
  4049. found_macro = None
  4050. all_lines = input_api.ReadFile(f, 'r').splitlines()
  4051. for line_num, line in enumerate(all_lines):
  4052. match = macro_re.search(line)
  4053. if match:
  4054. found_line_number = line_num
  4055. found_macro = match.group(2)
  4056. break
  4057. if not found_line_number:
  4058. continue
  4059. found_include_line = -1
  4060. for line_num, line in enumerate(all_lines):
  4061. if include_re.search(line):
  4062. found_include_line = line_num
  4063. break
  4064. if found_include_line >= 0 and found_include_line < found_line_number:
  4065. continue
  4066. if not f.LocalPath().endswith('.h'):
  4067. primary_header_path = extension_re.sub('.h', f.AbsoluteLocalPath())
  4068. try:
  4069. content = input_api.ReadFile(primary_header_path, 'r')
  4070. if include_re.search(content):
  4071. continue
  4072. except IOError:
  4073. pass
  4074. errors.append('%s:%d %s macro is used without first including build/'
  4075. 'build_config.h.' %
  4076. (f.LocalPath(), found_line_number, found_macro))
  4077. if errors:
  4078. return [output_api.PresubmitPromptWarning('\n'.join(errors))]
  4079. return []
  4080. def CheckForSuperfluousStlIncludesInHeaders(input_api, output_api):
  4081. stl_include_re = input_api.re.compile(r'^#include\s+<('
  4082. r'algorithm|'
  4083. r'array|'
  4084. r'limits|'
  4085. r'list|'
  4086. r'map|'
  4087. r'memory|'
  4088. r'queue|'
  4089. r'set|'
  4090. r'string|'
  4091. r'unordered_map|'
  4092. r'unordered_set|'
  4093. r'utility|'
  4094. r'vector)>')
  4095. std_namespace_re = input_api.re.compile(r'std::')
  4096. errors = []
  4097. for f in input_api.AffectedFiles():
  4098. if not _IsCPlusPlusHeaderFile(input_api, f.LocalPath()):
  4099. continue
  4100. uses_std_namespace = False
  4101. has_stl_include = False
  4102. for line in f.NewContents():
  4103. if has_stl_include and uses_std_namespace:
  4104. break
  4105. if not has_stl_include and stl_include_re.search(line):
  4106. has_stl_include = True
  4107. continue
  4108. if not uses_std_namespace and (std_namespace_re.search(line)
  4109. or 'no-std-usage-because-pch-file' in line):
  4110. uses_std_namespace = True
  4111. continue
  4112. if has_stl_include and not uses_std_namespace:
  4113. errors.append(
  4114. '%s: Includes STL header(s) but does not reference std::' %
  4115. f.LocalPath())
  4116. if errors:
  4117. return [output_api.PresubmitPromptWarning('\n'.join(errors))]
  4118. return []
  4119. def _CheckForDeprecatedOSMacrosInFile(input_api, f):
  4120. """Check for sensible looking, totally invalid OS macros."""
  4121. preprocessor_statement = input_api.re.compile(r'^\s*#')
  4122. os_macro = input_api.re.compile(r'defined\(OS_([^)]+)\)')
  4123. results = []
  4124. for lnum, line in f.ChangedContents():
  4125. if preprocessor_statement.search(line):
  4126. for match in os_macro.finditer(line):
  4127. results.append(
  4128. ' %s:%d: %s' %
  4129. (f.LocalPath(), lnum, 'defined(OS_' + match.group(1) +
  4130. ') -> BUILDFLAG(IS_' + match.group(1) + ')'))
  4131. return results
  4132. def CheckForDeprecatedOSMacros(input_api, output_api):
  4133. """Check all affected files for invalid OS macros."""
  4134. bad_macros = []
  4135. for f in input_api.AffectedSourceFiles(None):
  4136. if not f.LocalPath().endswith(('.py', '.js', '.html', '.css', '.md')):
  4137. bad_macros.extend(_CheckForDeprecatedOSMacrosInFile(input_api, f))
  4138. if not bad_macros:
  4139. return []
  4140. return [
  4141. output_api.PresubmitError(
  4142. 'OS macros have been deprecated. Please use BUILDFLAGs instead (still '
  4143. 'defined in build_config.h):', bad_macros)
  4144. ]
  4145. def _CheckForInvalidIfDefinedMacrosInFile(input_api, f):
  4146. """Check all affected files for invalid "if defined" macros."""
  4147. ALWAYS_DEFINED_MACROS = (
  4148. "TARGET_CPU_PPC",
  4149. "TARGET_CPU_PPC64",
  4150. "TARGET_CPU_68K",
  4151. "TARGET_CPU_X86",
  4152. "TARGET_CPU_ARM",
  4153. "TARGET_CPU_MIPS",
  4154. "TARGET_CPU_SPARC",
  4155. "TARGET_CPU_ALPHA",
  4156. "TARGET_IPHONE_SIMULATOR",
  4157. "TARGET_OS_EMBEDDED",
  4158. "TARGET_OS_IPHONE",
  4159. "TARGET_OS_MAC",
  4160. "TARGET_OS_UNIX",
  4161. "TARGET_OS_WIN32",
  4162. )
  4163. ifdef_macro = input_api.re.compile(
  4164. r'^\s*#.*(?:ifdef\s|defined\()([^\s\)]+)')
  4165. results = []
  4166. for lnum, line in f.ChangedContents():
  4167. for match in ifdef_macro.finditer(line):
  4168. if match.group(1) in ALWAYS_DEFINED_MACROS:
  4169. always_defined = ' %s is always defined. ' % match.group(1)
  4170. did_you_mean = 'Did you mean \'#if %s\'?' % match.group(1)
  4171. results.append(
  4172. ' %s:%d %s\n\t%s' %
  4173. (f.LocalPath(), lnum, always_defined, did_you_mean))
  4174. return results
  4175. def CheckForInvalidIfDefinedMacros(input_api, output_api):
  4176. """Check all affected files for invalid "if defined" macros."""
  4177. bad_macros = []
  4178. skipped_paths = ['third_party/sqlite/', 'third_party/abseil-cpp/']
  4179. for f in input_api.AffectedFiles():
  4180. if any([f.LocalPath().startswith(path) for path in skipped_paths]):
  4181. continue
  4182. if f.LocalPath().endswith(('.h', '.c', '.cc', '.m', '.mm')):
  4183. bad_macros.extend(
  4184. _CheckForInvalidIfDefinedMacrosInFile(input_api, f))
  4185. if not bad_macros:
  4186. return []
  4187. return [
  4188. output_api.PresubmitError(
  4189. 'Found ifdef check on always-defined macro[s]. Please fix your code\n'
  4190. 'or check the list of ALWAYS_DEFINED_MACROS in src/PRESUBMIT.py.',
  4191. bad_macros)
  4192. ]
  4193. def CheckForIPCRules(input_api, output_api):
  4194. """Check for same IPC rules described in
  4195. http://www.chromium.org/Home/chromium-security/education/security-tips-for-ipc
  4196. """
  4197. base_pattern = r'IPC_ENUM_TRAITS\('
  4198. inclusion_pattern = input_api.re.compile(r'(%s)' % base_pattern)
  4199. comment_pattern = input_api.re.compile(r'//.*(%s)' % base_pattern)
  4200. problems = []
  4201. for f in input_api.AffectedSourceFiles(None):
  4202. local_path = f.LocalPath()
  4203. if not local_path.endswith('.h'):
  4204. continue
  4205. for line_number, line in f.ChangedContents():
  4206. if inclusion_pattern.search(
  4207. line) and not comment_pattern.search(line):
  4208. problems.append('%s:%d\n %s' %
  4209. (local_path, line_number, line.strip()))
  4210. if problems:
  4211. return [
  4212. output_api.PresubmitPromptWarning(_IPC_ENUM_TRAITS_DEPRECATED,
  4213. problems)
  4214. ]
  4215. else:
  4216. return []
  4217. def CheckForLongPathnames(input_api, output_api):
  4218. """Check to make sure no files being submitted have long paths.
  4219. This causes issues on Windows.
  4220. """
  4221. problems = []
  4222. for f in input_api.AffectedTestableFiles():
  4223. local_path = f.LocalPath()
  4224. # Windows has a path limit of 260 characters. Limit path length to 200 so
  4225. # that we have some extra for the prefix on dev machines and the bots.
  4226. if len(local_path) > 200:
  4227. problems.append(local_path)
  4228. if problems:
  4229. return [output_api.PresubmitError(_LONG_PATH_ERROR, problems)]
  4230. else:
  4231. return []
  4232. def CheckForIncludeGuards(input_api, output_api):
  4233. """Check that header files have proper guards against multiple inclusion.
  4234. If a file should not have such guards (and it probably should) then it
  4235. should include the string "no-include-guard-because-multiply-included" or
  4236. "no-include-guard-because-pch-file".
  4237. """
  4238. def is_chromium_header_file(f):
  4239. # We only check header files under the control of the Chromium
  4240. # project. That is, those outside third_party apart from
  4241. # third_party/blink.
  4242. # We also exclude *_message_generator.h headers as they use
  4243. # include guards in a special, non-typical way.
  4244. file_with_path = input_api.os_path.normpath(f.LocalPath())
  4245. return (file_with_path.endswith('.h')
  4246. and not file_with_path.endswith('_message_generator.h')
  4247. and (not file_with_path.startswith('third_party')
  4248. or file_with_path.startswith(
  4249. input_api.os_path.join('third_party', 'blink'))))
  4250. def replace_special_with_underscore(string):
  4251. return input_api.re.sub(r'[+\\/.-]', '_', string)
  4252. errors = []
  4253. for f in input_api.AffectedSourceFiles(is_chromium_header_file):
  4254. guard_name = None
  4255. guard_line_number = None
  4256. seen_guard_end = False
  4257. file_with_path = input_api.os_path.normpath(f.LocalPath())
  4258. base_file_name = input_api.os_path.splitext(
  4259. input_api.os_path.basename(file_with_path))[0]
  4260. upper_base_file_name = base_file_name.upper()
  4261. expected_guard = replace_special_with_underscore(
  4262. file_with_path.upper() + '_')
  4263. # For "path/elem/file_name.h" we should really only accept
  4264. # PATH_ELEM_FILE_NAME_H_ per coding style. Unfortunately there
  4265. # are too many (1000+) files with slight deviations from the
  4266. # coding style. The most important part is that the include guard
  4267. # is there, and that it's unique, not the name so this check is
  4268. # forgiving for existing files.
  4269. #
  4270. # As code becomes more uniform, this could be made stricter.
  4271. guard_name_pattern_list = [
  4272. # Anything with the right suffix (maybe with an extra _).
  4273. r'\w+_H__?',
  4274. # To cover include guards with old Blink style.
  4275. r'\w+_h',
  4276. # Anything including the uppercase name of the file.
  4277. r'\w*' + input_api.re.escape(
  4278. replace_special_with_underscore(upper_base_file_name)) +
  4279. r'\w*',
  4280. ]
  4281. guard_name_pattern = '|'.join(guard_name_pattern_list)
  4282. guard_pattern = input_api.re.compile(r'#ifndef\s+(' +
  4283. guard_name_pattern + ')')
  4284. for line_number, line in enumerate(f.NewContents()):
  4285. if ('no-include-guard-because-multiply-included' in line
  4286. or 'no-include-guard-because-pch-file' in line):
  4287. guard_name = 'DUMMY' # To not trigger check outside the loop.
  4288. break
  4289. if guard_name is None:
  4290. match = guard_pattern.match(line)
  4291. if match:
  4292. guard_name = match.group(1)
  4293. guard_line_number = line_number
  4294. # We allow existing files to use include guards whose names
  4295. # don't match the chromium style guide, but new files should
  4296. # get it right.
  4297. if guard_name != expected_guard:
  4298. if not f.OldContents():
  4299. errors.append(
  4300. output_api.PresubmitPromptWarning(
  4301. 'Header using the wrong include guard name %s'
  4302. % guard_name, [
  4303. '%s:%d' %
  4304. (f.LocalPath(), line_number + 1)
  4305. ], 'Expected: %r\nFound: %r' %
  4306. (expected_guard, guard_name)))
  4307. else:
  4308. # The line after #ifndef should have a #define of the same name.
  4309. if line_number == guard_line_number + 1:
  4310. expected_line = '#define %s' % guard_name
  4311. if line != expected_line:
  4312. errors.append(
  4313. output_api.PresubmitPromptWarning(
  4314. 'Missing "%s" for include guard' %
  4315. expected_line,
  4316. ['%s:%d' % (f.LocalPath(), line_number + 1)],
  4317. 'Expected: %r\nGot: %r' %
  4318. (expected_line, line)))
  4319. if not seen_guard_end and line == '#endif // %s' % guard_name:
  4320. seen_guard_end = True
  4321. elif seen_guard_end:
  4322. if line.strip() != '':
  4323. errors.append(
  4324. output_api.PresubmitPromptWarning(
  4325. 'Include guard %s not covering the whole file'
  4326. % (guard_name), [f.LocalPath()]))
  4327. break # Nothing else to check and enough to warn once.
  4328. if guard_name is None:
  4329. errors.append(
  4330. output_api.PresubmitPromptWarning(
  4331. 'Missing include guard in %s\n'
  4332. 'Recommended name: %s\n'
  4333. 'This check can be disabled by having the string\n'
  4334. '"no-include-guard-because-multiply-included" or\n'
  4335. '"no-include-guard-because-pch-file" in the header.'
  4336. % (f.LocalPath(), expected_guard)))
  4337. return errors
  4338. def CheckForWindowsLineEndings(input_api, output_api):
  4339. """Check source code and known ascii text files for Windows style line
  4340. endings.
  4341. """
  4342. known_text_files = r'.*\.(txt|html|htm|py|gyp|gypi|gn|isolate|icon)$'
  4343. file_inclusion_pattern = (known_text_files,
  4344. r'.+%s' % _IMPLEMENTATION_EXTENSIONS,
  4345. r'.+%s' % _HEADER_EXTENSIONS)
  4346. problems = []
  4347. source_file_filter = lambda f: input_api.FilterSourceFile(
  4348. f, files_to_check=file_inclusion_pattern, files_to_skip=None)
  4349. for f in input_api.AffectedSourceFiles(source_file_filter):
  4350. # Ignore test files that contain crlf intentionally.
  4351. if f.LocalPath().endswith('crlf.txt'):
  4352. continue
  4353. include_file = False
  4354. for line in input_api.ReadFile(f, 'r').splitlines(True):
  4355. if line.endswith('\r\n'):
  4356. include_file = True
  4357. if include_file:
  4358. problems.append(f.LocalPath())
  4359. if problems:
  4360. return [
  4361. output_api.PresubmitPromptWarning(
  4362. 'Are you sure that you want '
  4363. 'these files to contain Windows style line endings?\n' +
  4364. '\n'.join(problems))
  4365. ]
  4366. return []
  4367. def CheckIconFilesForLicenseHeaders(input_api, output_api):
  4368. """Check that .icon files (which are fragments of C++) have license headers.
  4369. """
  4370. icon_files = (r'.*\.icon$', )
  4371. icons = lambda x: input_api.FilterSourceFile(x, files_to_check=icon_files)
  4372. return input_api.canned_checks.CheckLicense(input_api,
  4373. output_api,
  4374. source_file_filter=icons)
  4375. def CheckForUseOfChromeAppsDeprecations(input_api, output_api):
  4376. """Check source code for use of Chrome App technologies being
  4377. deprecated.
  4378. """
  4379. def _CheckForDeprecatedTech(input_api,
  4380. output_api,
  4381. detection_list,
  4382. files_to_check=None,
  4383. files_to_skip=None):
  4384. if (files_to_check or files_to_skip):
  4385. source_file_filter = lambda f: input_api.FilterSourceFile(
  4386. f, files_to_check=files_to_check, files_to_skip=files_to_skip)
  4387. else:
  4388. source_file_filter = None
  4389. problems = []
  4390. for f in input_api.AffectedSourceFiles(source_file_filter):
  4391. if f.Action() == 'D':
  4392. continue
  4393. for _, line in f.ChangedContents():
  4394. if any(detect in line for detect in detection_list):
  4395. problems.append(f.LocalPath())
  4396. return problems
  4397. # to avoid this presubmit script triggering warnings
  4398. files_to_skip = ['PRESUBMIT.py', 'PRESUBMIT_test.py']
  4399. problems = []
  4400. # NMF: any files with extensions .nmf or NMF
  4401. _NMF_FILES = r'\.(nmf|NMF)$'
  4402. problems += _CheckForDeprecatedTech(
  4403. input_api,
  4404. output_api,
  4405. detection_list=[''], # any change to the file will trigger warning
  4406. files_to_check=[r'.+%s' % _NMF_FILES])
  4407. # MANIFEST: any manifest.json that in its diff includes "app":
  4408. _MANIFEST_FILES = r'(manifest\.json)$'
  4409. problems += _CheckForDeprecatedTech(
  4410. input_api,
  4411. output_api,
  4412. detection_list=['"app":'],
  4413. files_to_check=[r'.*%s' % _MANIFEST_FILES])
  4414. # NaCl / PNaCl: any file that in its diff contains the strings in the list
  4415. problems += _CheckForDeprecatedTech(
  4416. input_api,
  4417. output_api,
  4418. detection_list=['config=nacl', 'enable-nacl', 'cpu=pnacl', 'nacl_io'],
  4419. files_to_skip=files_to_skip + [r"^native_client_sdk[\\/]"])
  4420. # PPAPI: any C/C++ file that in its diff includes a ppappi library
  4421. problems += _CheckForDeprecatedTech(
  4422. input_api,
  4423. output_api,
  4424. detection_list=['#include "ppapi', '#include <ppapi'],
  4425. files_to_check=(r'.+%s' % _HEADER_EXTENSIONS,
  4426. r'.+%s' % _IMPLEMENTATION_EXTENSIONS),
  4427. files_to_skip=[r"^ppapi[\\/]"])
  4428. if problems:
  4429. return [
  4430. output_api.PresubmitPromptWarning(
  4431. 'You are adding/modifying code'
  4432. 'related to technologies which will soon be deprecated (Chrome Apps, NaCl,'
  4433. ' PNaCl, PPAPI). See this blog post for more details:\n'
  4434. 'https://blog.chromium.org/2020/08/changes-to-chrome-app-support-timeline.html\n'
  4435. 'and this documentation for options to replace these technologies:\n'
  4436. 'https://developer.chrome.com/docs/apps/migration/\n' +
  4437. '\n'.join(problems))
  4438. ]
  4439. return []
  4440. def CheckSyslogUseWarningOnUpload(input_api, output_api, src_file_filter=None):
  4441. """Checks that all source files use SYSLOG properly."""
  4442. syslog_files = []
  4443. for f in input_api.AffectedSourceFiles(src_file_filter):
  4444. for line_number, line in f.ChangedContents():
  4445. if 'SYSLOG' in line:
  4446. syslog_files.append(f.LocalPath() + ':' + str(line_number))
  4447. if syslog_files:
  4448. return [
  4449. output_api.PresubmitPromptWarning(
  4450. 'Please make sure there are no privacy sensitive bits of data in SYSLOG'
  4451. ' calls.\nFiles to check:\n',
  4452. items=syslog_files)
  4453. ]
  4454. return []
  4455. def CheckChangeOnUpload(input_api, output_api):
  4456. if input_api.version < [2, 0, 0]:
  4457. return [
  4458. output_api.PresubmitError(
  4459. "Your depot_tools is out of date. "
  4460. "This PRESUBMIT.py requires at least presubmit_support version 2.0.0, "
  4461. "but your version is %d.%d.%d" % tuple(input_api.version))
  4462. ]
  4463. results = []
  4464. results.extend(
  4465. input_api.canned_checks.CheckPatchFormatted(input_api, output_api))
  4466. return results
  4467. def CheckChangeOnCommit(input_api, output_api):
  4468. if input_api.version < [2, 0, 0]:
  4469. return [
  4470. output_api.PresubmitError(
  4471. "Your depot_tools is out of date. "
  4472. "This PRESUBMIT.py requires at least presubmit_support version 2.0.0, "
  4473. "but your version is %d.%d.%d" % tuple(input_api.version))
  4474. ]
  4475. results = []
  4476. # Make sure the tree is 'open'.
  4477. results.extend(
  4478. input_api.canned_checks.CheckTreeIsOpen(
  4479. input_api,
  4480. output_api,
  4481. json_url='http://chromium-status.appspot.com/current?format=json'))
  4482. results.extend(
  4483. input_api.canned_checks.CheckPatchFormatted(input_api, output_api))
  4484. results.extend(
  4485. input_api.canned_checks.CheckChangeHasBugField(input_api, output_api))
  4486. results.extend(
  4487. input_api.canned_checks.CheckChangeHasNoUnwantedTags(
  4488. input_api, output_api))
  4489. results.extend(
  4490. input_api.canned_checks.CheckChangeHasDescription(
  4491. input_api, output_api))
  4492. return results
  4493. def CheckStrings(input_api, output_api):
  4494. """Check string ICU syntax validity and if translation screenshots exist."""
  4495. # Skip translation screenshots check if a SkipTranslationScreenshotsCheck
  4496. # footer is set to true.
  4497. git_footers = input_api.change.GitFootersFromDescription()
  4498. skip_screenshot_check_footer = [
  4499. footer.lower() for footer in git_footers.get(
  4500. u'Skip-Translation-Screenshots-Check', [])
  4501. ]
  4502. run_screenshot_check = u'true' not in skip_screenshot_check_footer
  4503. import os
  4504. import re
  4505. import sys
  4506. from io import StringIO
  4507. new_or_added_paths = set(f.LocalPath() for f in input_api.AffectedFiles()
  4508. if (f.Action() == 'A' or f.Action() == 'M'))
  4509. removed_paths = set(f.LocalPath()
  4510. for f in input_api.AffectedFiles(include_deletes=True)
  4511. if f.Action() == 'D')
  4512. affected_grds = [
  4513. f for f in input_api.AffectedFiles()
  4514. if f.LocalPath().endswith(('.grd', '.grdp'))
  4515. ]
  4516. affected_grds = [
  4517. f for f in affected_grds if not 'testdata' in f.LocalPath()
  4518. ]
  4519. if not affected_grds:
  4520. return []
  4521. affected_png_paths = [
  4522. f.AbsoluteLocalPath() for f in input_api.AffectedFiles()
  4523. if (f.LocalPath().endswith('.png'))
  4524. ]
  4525. # Check for screenshots. Developers can upload screenshots using
  4526. # tools/translation/upload_screenshots.py which finds and uploads
  4527. # images associated with .grd files (e.g. test_grd/IDS_STRING.png for the
  4528. # message named IDS_STRING in test.grd) and produces a .sha1 file (e.g.
  4529. # test_grd/IDS_STRING.png.sha1) for each png when the upload is successful.
  4530. #
  4531. # The logic here is as follows:
  4532. #
  4533. # - If the CL has a .png file under the screenshots directory for a grd
  4534. # file, warn the developer. Actual images should never be checked into the
  4535. # Chrome repo.
  4536. #
  4537. # - If the CL contains modified or new messages in grd files and doesn't
  4538. # contain the corresponding .sha1 files, warn the developer to add images
  4539. # and upload them via tools/translation/upload_screenshots.py.
  4540. #
  4541. # - If the CL contains modified or new messages in grd files and the
  4542. # corresponding .sha1 files, everything looks good.
  4543. #
  4544. # - If the CL contains removed messages in grd files but the corresponding
  4545. # .sha1 files aren't removed, warn the developer to remove them.
  4546. unnecessary_screenshots = []
  4547. missing_sha1 = []
  4548. unnecessary_sha1_files = []
  4549. # This checks verifies that the ICU syntax of messages this CL touched is
  4550. # valid, and reports any found syntax errors.
  4551. # Without this presubmit check, ICU syntax errors in Chromium strings can land
  4552. # without developers being aware of them. Later on, such ICU syntax errors
  4553. # break message extraction for translation, hence would block Chromium
  4554. # translations until they are fixed.
  4555. icu_syntax_errors = []
  4556. def _CheckScreenshotAdded(screenshots_dir, message_id):
  4557. sha1_path = input_api.os_path.join(screenshots_dir,
  4558. message_id + '.png.sha1')
  4559. if sha1_path not in new_or_added_paths:
  4560. missing_sha1.append(sha1_path)
  4561. def _CheckScreenshotRemoved(screenshots_dir, message_id):
  4562. sha1_path = input_api.os_path.join(screenshots_dir,
  4563. message_id + '.png.sha1')
  4564. if input_api.os_path.exists(
  4565. sha1_path) and sha1_path not in removed_paths:
  4566. unnecessary_sha1_files.append(sha1_path)
  4567. def _ValidateIcuSyntax(text, level, signatures):
  4568. """Validates ICU syntax of a text string.
  4569. Check if text looks similar to ICU and checks for ICU syntax correctness
  4570. in this case. Reports various issues with ICU syntax and values of
  4571. variants. Supports checking of nested messages. Accumulate information of
  4572. each ICU messages found in the text for further checking.
  4573. Args:
  4574. text: a string to check.
  4575. level: a number of current nesting level.
  4576. signatures: an accumulator, a list of tuple of (level, variable,
  4577. kind, variants).
  4578. Returns:
  4579. None if a string is not ICU or no issue detected.
  4580. A tuple of (message, start index, end index) if an issue detected.
  4581. """
  4582. valid_types = {
  4583. 'plural': (frozenset(
  4584. ['=0', '=1', 'zero', 'one', 'two', 'few', 'many',
  4585. 'other']), frozenset(['=1', 'other'])),
  4586. 'selectordinal': (frozenset(
  4587. ['=0', '=1', 'zero', 'one', 'two', 'few', 'many',
  4588. 'other']), frozenset(['one', 'other'])),
  4589. 'select': (frozenset(), frozenset(['other'])),
  4590. }
  4591. # Check if the message looks like an attempt to use ICU
  4592. # plural. If yes - check if its syntax strictly matches ICU format.
  4593. like = re.match(r'^[^{]*\{[^{]*\b(plural|selectordinal|select)\b',
  4594. text)
  4595. if not like:
  4596. signatures.append((level, None, None, None))
  4597. return
  4598. # Check for valid prefix and suffix
  4599. m = re.match(
  4600. r'^([^{]*\{)([a-zA-Z0-9_]+),\s*'
  4601. r'(plural|selectordinal|select),\s*'
  4602. r'(?:offset:\d+)?\s*(.*)', text, re.DOTALL)
  4603. if not m:
  4604. return (('This message looks like an ICU plural, '
  4605. 'but does not follow ICU syntax.'), like.start(),
  4606. like.end())
  4607. starting, variable, kind, variant_pairs = m.groups()
  4608. variants, depth, last_pos = _ParseIcuVariants(variant_pairs,
  4609. m.start(4))
  4610. if depth:
  4611. return ('Invalid ICU format. Unbalanced opening bracket', last_pos,
  4612. len(text))
  4613. first = text[0]
  4614. ending = text[last_pos:]
  4615. if not starting:
  4616. return ('Invalid ICU format. No initial opening bracket',
  4617. last_pos - 1, last_pos)
  4618. if not ending or '}' not in ending:
  4619. return ('Invalid ICU format. No final closing bracket',
  4620. last_pos - 1, last_pos)
  4621. elif first != '{':
  4622. return ((
  4623. 'Invalid ICU format. Extra characters at the start of a complex '
  4624. 'message (go/icu-message-migration): "%s"') % starting, 0,
  4625. len(starting))
  4626. elif ending != '}':
  4627. return ((
  4628. 'Invalid ICU format. Extra characters at the end of a complex '
  4629. 'message (go/icu-message-migration): "%s"') % ending,
  4630. last_pos - 1, len(text) - 1)
  4631. if kind not in valid_types:
  4632. return (('Unknown ICU message type %s. '
  4633. 'Valid types are: plural, select, selectordinal') % kind,
  4634. 0, 0)
  4635. known, required = valid_types[kind]
  4636. defined_variants = set()
  4637. for variant, variant_range, value, value_range in variants:
  4638. start, end = variant_range
  4639. if variant in defined_variants:
  4640. return ('Variant "%s" is defined more than once' % variant,
  4641. start, end)
  4642. elif known and variant not in known:
  4643. return ('Variant "%s" is not valid for %s message' %
  4644. (variant, kind), start, end)
  4645. defined_variants.add(variant)
  4646. # Check for nested structure
  4647. res = _ValidateIcuSyntax(value[1:-1], level + 1, signatures)
  4648. if res:
  4649. return (res[0], res[1] + value_range[0] + 1,
  4650. res[2] + value_range[0] + 1)
  4651. missing = required - defined_variants
  4652. if missing:
  4653. return ('Required variants missing: %s' % ', '.join(missing), 0,
  4654. len(text))
  4655. signatures.append((level, variable, kind, defined_variants))
  4656. def _ParseIcuVariants(text, offset=0):
  4657. """Parse variants part of ICU complex message.
  4658. Builds a tuple of variant names and values, as well as
  4659. their offsets in the input string.
  4660. Args:
  4661. text: a string to parse
  4662. offset: additional offset to add to positions in the text to get correct
  4663. position in the complete ICU string.
  4664. Returns:
  4665. List of tuples, each tuple consist of four fields: variant name,
  4666. variant name span (tuple of two integers), variant value, value
  4667. span (tuple of two integers).
  4668. """
  4669. depth, start, end = 0, -1, -1
  4670. variants = []
  4671. key = None
  4672. for idx, char in enumerate(text):
  4673. if char == '{':
  4674. if not depth:
  4675. start = idx
  4676. chunk = text[end + 1:start]
  4677. key = chunk.strip()
  4678. pos = offset + end + 1 + chunk.find(key)
  4679. span = (pos, pos + len(key))
  4680. depth += 1
  4681. elif char == '}':
  4682. if not depth:
  4683. return variants, depth, offset + idx
  4684. depth -= 1
  4685. if not depth:
  4686. end = idx
  4687. variants.append((key, span, text[start:end + 1],
  4688. (offset + start, offset + end + 1)))
  4689. return variants, depth, offset + end + 1
  4690. try:
  4691. old_sys_path = sys.path
  4692. sys.path = sys.path + [
  4693. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  4694. 'translation')
  4695. ]
  4696. from helper import grd_helper
  4697. finally:
  4698. sys.path = old_sys_path
  4699. for f in affected_grds:
  4700. file_path = f.LocalPath()
  4701. old_id_to_msg_map = {}
  4702. new_id_to_msg_map = {}
  4703. # Note that this code doesn't check if the file has been deleted. This is
  4704. # OK because it only uses the old and new file contents and doesn't load
  4705. # the file via its path.
  4706. # It's also possible that a file's content refers to a renamed or deleted
  4707. # file via a <part> tag, such as <part file="now-deleted-file.grdp">. This
  4708. # is OK as well, because grd_helper ignores <part> tags when loading .grd or
  4709. # .grdp files.
  4710. if file_path.endswith('.grdp'):
  4711. if f.OldContents():
  4712. old_id_to_msg_map = grd_helper.GetGrdpMessagesFromString(
  4713. '\n'.join(f.OldContents()))
  4714. if f.NewContents():
  4715. new_id_to_msg_map = grd_helper.GetGrdpMessagesFromString(
  4716. '\n'.join(f.NewContents()))
  4717. else:
  4718. file_dir = input_api.os_path.dirname(file_path) or '.'
  4719. if f.OldContents():
  4720. old_id_to_msg_map = grd_helper.GetGrdMessages(
  4721. StringIO('\n'.join(f.OldContents())), file_dir)
  4722. if f.NewContents():
  4723. new_id_to_msg_map = grd_helper.GetGrdMessages(
  4724. StringIO('\n'.join(f.NewContents())), file_dir)
  4725. grd_name, ext = input_api.os_path.splitext(
  4726. input_api.os_path.basename(file_path))
  4727. screenshots_dir = input_api.os_path.join(
  4728. input_api.os_path.dirname(file_path),
  4729. grd_name + ext.replace('.', '_'))
  4730. # Compute added, removed and modified message IDs.
  4731. old_ids = set(old_id_to_msg_map)
  4732. new_ids = set(new_id_to_msg_map)
  4733. added_ids = new_ids - old_ids
  4734. removed_ids = old_ids - new_ids
  4735. modified_ids = set([])
  4736. for key in old_ids.intersection(new_ids):
  4737. if (old_id_to_msg_map[key].ContentsAsXml('', True) !=
  4738. new_id_to_msg_map[key].ContentsAsXml('', True)):
  4739. # The message content itself changed. Require an updated screenshot.
  4740. modified_ids.add(key)
  4741. elif old_id_to_msg_map[key].attrs['meaning'] != \
  4742. new_id_to_msg_map[key].attrs['meaning']:
  4743. # The message meaning changed. Ensure there is a screenshot for it.
  4744. sha1_path = input_api.os_path.join(screenshots_dir,
  4745. key + '.png.sha1')
  4746. if sha1_path not in new_or_added_paths and not \
  4747. input_api.os_path.exists(sha1_path):
  4748. # There is neither a previous screenshot nor is a new one added now.
  4749. # Require a screenshot.
  4750. modified_ids.add(key)
  4751. if run_screenshot_check:
  4752. # Check the screenshot directory for .png files. Warn if there is any.
  4753. for png_path in affected_png_paths:
  4754. if png_path.startswith(screenshots_dir):
  4755. unnecessary_screenshots.append(png_path)
  4756. for added_id in added_ids:
  4757. _CheckScreenshotAdded(screenshots_dir, added_id)
  4758. for modified_id in modified_ids:
  4759. _CheckScreenshotAdded(screenshots_dir, modified_id)
  4760. for removed_id in removed_ids:
  4761. _CheckScreenshotRemoved(screenshots_dir, removed_id)
  4762. # Check new and changed strings for ICU syntax errors.
  4763. for key in added_ids.union(modified_ids):
  4764. msg = new_id_to_msg_map[key].ContentsAsXml('', True)
  4765. err = _ValidateIcuSyntax(msg, 0, [])
  4766. if err is not None:
  4767. icu_syntax_errors.append(str(key) + ': ' + str(err[0]))
  4768. results = []
  4769. if run_screenshot_check:
  4770. if unnecessary_screenshots:
  4771. results.append(
  4772. output_api.PresubmitError(
  4773. 'Do not include actual screenshots in the changelist. Run '
  4774. 'tools/translate/upload_screenshots.py to upload them instead:',
  4775. sorted(unnecessary_screenshots)))
  4776. if missing_sha1:
  4777. results.append(
  4778. output_api.PresubmitError(
  4779. 'You are adding or modifying UI strings.\n'
  4780. 'To ensure the best translations, take screenshots of the relevant UI '
  4781. '(https://g.co/chrome/translation) and add these files to your '
  4782. 'changelist:', sorted(missing_sha1)))
  4783. if unnecessary_sha1_files:
  4784. results.append(
  4785. output_api.PresubmitError(
  4786. 'You removed strings associated with these files. Remove:',
  4787. sorted(unnecessary_sha1_files)))
  4788. else:
  4789. results.append(
  4790. output_api.PresubmitPromptOrNotify('Skipping translation '
  4791. 'screenshots check.'))
  4792. if icu_syntax_errors:
  4793. results.append(
  4794. output_api.PresubmitPromptWarning(
  4795. 'ICU syntax errors were found in the following strings (problems or '
  4796. 'feedback? Contact rainhard@chromium.org):',
  4797. items=icu_syntax_errors))
  4798. return results
  4799. def CheckTranslationExpectations(input_api, output_api,
  4800. repo_root=None,
  4801. translation_expectations_path=None,
  4802. grd_files=None):
  4803. import sys
  4804. affected_grds = [
  4805. f for f in input_api.AffectedFiles()
  4806. if (f.LocalPath().endswith('.grd') or f.LocalPath().endswith('.grdp'))
  4807. ]
  4808. if not affected_grds:
  4809. return []
  4810. try:
  4811. old_sys_path = sys.path
  4812. sys.path = sys.path + [
  4813. input_api.os_path.join(input_api.PresubmitLocalPath(), 'tools',
  4814. 'translation')
  4815. ]
  4816. from helper import git_helper
  4817. from helper import translation_helper
  4818. finally:
  4819. sys.path = old_sys_path
  4820. # Check that translation expectations can be parsed and we can get a list of
  4821. # translatable grd files. |repo_root| and |translation_expectations_path| are
  4822. # only passed by tests.
  4823. if not repo_root:
  4824. repo_root = input_api.PresubmitLocalPath()
  4825. if not translation_expectations_path:
  4826. translation_expectations_path = input_api.os_path.join(
  4827. repo_root, 'tools', 'gritsettings', 'translation_expectations.pyl')
  4828. if not grd_files:
  4829. grd_files = git_helper.list_grds_in_repository(repo_root)
  4830. # Ignore bogus grd files used only for testing
  4831. # ui/webui/resoucres/tools/generate_grd.py.
  4832. ignore_path = input_api.os_path.join('ui', 'webui', 'resources', 'tools',
  4833. 'tests')
  4834. grd_files = [p for p in grd_files if ignore_path not in p]
  4835. try:
  4836. translation_helper.get_translatable_grds(
  4837. repo_root, grd_files, translation_expectations_path)
  4838. except Exception as e:
  4839. return [
  4840. output_api.PresubmitNotifyResult(
  4841. 'Failed to get a list of translatable grd files. This happens when:\n'
  4842. ' - One of the modified grd or grdp files cannot be parsed or\n'
  4843. ' - %s is not updated.\n'
  4844. 'Stack:\n%s' % (translation_expectations_path, str(e)))
  4845. ]
  4846. return []
  4847. def CheckStableMojomChanges(input_api, output_api):
  4848. """Changes to [Stable] mojom types must preserve backward-compatibility."""
  4849. changed_mojoms = input_api.AffectedFiles(
  4850. include_deletes=True,
  4851. file_filter=lambda f: f.LocalPath().endswith(('.mojom')))
  4852. if not changed_mojoms:
  4853. return []
  4854. delta = []
  4855. for mojom in changed_mojoms:
  4856. delta.append({
  4857. 'filename': mojom.LocalPath(),
  4858. 'old': '\n'.join(mojom.OldContents()) or None,
  4859. 'new': '\n'.join(mojom.NewContents()) or None,
  4860. })
  4861. process = input_api.subprocess.Popen([
  4862. input_api.python3_executable,
  4863. input_api.os_path.join(
  4864. input_api.PresubmitLocalPath(), 'mojo', 'public', 'tools', 'mojom',
  4865. 'check_stable_mojom_compatibility.py'), '--src-root',
  4866. input_api.PresubmitLocalPath()
  4867. ],
  4868. stdin=input_api.subprocess.PIPE,
  4869. stdout=input_api.subprocess.PIPE,
  4870. stderr=input_api.subprocess.PIPE,
  4871. universal_newlines=True)
  4872. (x, error) = process.communicate(input=input_api.json.dumps(delta))
  4873. if process.returncode:
  4874. return [
  4875. output_api.PresubmitError(
  4876. 'One or more [Stable] mojom definitions appears to have been changed '
  4877. 'in a way that is not backward-compatible.',
  4878. long_text=error)
  4879. ]
  4880. return []
  4881. def CheckDeprecationOfPreferences(input_api, output_api):
  4882. """Removing a preference should come with a deprecation."""
  4883. def FilterFile(affected_file):
  4884. """Accept only .cc files and the like."""
  4885. file_inclusion_pattern = [r'.+%s' % _IMPLEMENTATION_EXTENSIONS]
  4886. files_to_skip = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  4887. input_api.DEFAULT_FILES_TO_SKIP)
  4888. return input_api.FilterSourceFile(
  4889. affected_file,
  4890. files_to_check=file_inclusion_pattern,
  4891. files_to_skip=files_to_skip)
  4892. def ModifiedLines(affected_file):
  4893. """Returns a list of tuples (line number, line text) of added and removed
  4894. lines.
  4895. Deleted lines share the same line number as the previous line.
  4896. This relies on the scm diff output describing each changed code section
  4897. with a line of the form
  4898. ^@@ <old line num>,<old size> <new line num>,<new size> @@$
  4899. """
  4900. line_num = 0
  4901. modified_lines = []
  4902. for line in affected_file.GenerateScmDiff().splitlines():
  4903. # Extract <new line num> of the patch fragment (see format above).
  4904. m = input_api.re.match(r'^@@ [0-9\,\+\-]+ \+([0-9]+)\,[0-9]+ @@',
  4905. line)
  4906. if m:
  4907. line_num = int(m.groups(1)[0])
  4908. continue
  4909. if ((line.startswith('+') and not line.startswith('++'))
  4910. or (line.startswith('-') and not line.startswith('--'))):
  4911. modified_lines.append((line_num, line))
  4912. if not line.startswith('-'):
  4913. line_num += 1
  4914. return modified_lines
  4915. def FindLineWith(lines, needle):
  4916. """Returns the line number (i.e. index + 1) in `lines` containing `needle`.
  4917. If 0 or >1 lines contain `needle`, -1 is returned.
  4918. """
  4919. matching_line_numbers = [
  4920. # + 1 for 1-based counting of line numbers.
  4921. i + 1 for i, line in enumerate(lines) if needle in line
  4922. ]
  4923. return matching_line_numbers[0] if len(
  4924. matching_line_numbers) == 1 else -1
  4925. def ModifiedPrefMigration(affected_file):
  4926. """Returns whether the MigrateObsolete.*Pref functions were modified."""
  4927. # Determine first and last lines of MigrateObsolete.*Pref functions.
  4928. new_contents = affected_file.NewContents()
  4929. range_1 = (FindLineWith(new_contents,
  4930. 'BEGIN_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS'),
  4931. FindLineWith(new_contents,
  4932. 'END_MIGRATE_OBSOLETE_LOCAL_STATE_PREFS'))
  4933. range_2 = (FindLineWith(new_contents,
  4934. 'BEGIN_MIGRATE_OBSOLETE_PROFILE_PREFS'),
  4935. FindLineWith(new_contents,
  4936. 'END_MIGRATE_OBSOLETE_PROFILE_PREFS'))
  4937. if (-1 in range_1 + range_2):
  4938. raise Exception(
  4939. 'Broken .*MIGRATE_OBSOLETE_.*_PREFS markers in browser_prefs.cc.'
  4940. )
  4941. # Check whether any of the modified lines are part of the
  4942. # MigrateObsolete.*Pref functions.
  4943. for line_nr, line in ModifiedLines(affected_file):
  4944. if (range_1[0] <= line_nr <= range_1[1]
  4945. or range_2[0] <= line_nr <= range_2[1]):
  4946. return True
  4947. return False
  4948. register_pref_pattern = input_api.re.compile(r'Register.+Pref')
  4949. browser_prefs_file_pattern = input_api.re.compile(
  4950. r'chrome/browser/prefs/browser_prefs.cc')
  4951. changes = input_api.AffectedFiles(include_deletes=True,
  4952. file_filter=FilterFile)
  4953. potential_problems = []
  4954. for f in changes:
  4955. for line in f.GenerateScmDiff().splitlines():
  4956. # Check deleted lines for pref registrations.
  4957. if (line.startswith('-') and not line.startswith('--')
  4958. and register_pref_pattern.search(line)):
  4959. potential_problems.append('%s: %s' % (f.LocalPath(), line))
  4960. if browser_prefs_file_pattern.search(f.LocalPath()):
  4961. # If the developer modified the MigrateObsolete.*Prefs() functions, we
  4962. # assume that they knew that they have to deprecate preferences and don't
  4963. # warn.
  4964. try:
  4965. if ModifiedPrefMigration(f):
  4966. return []
  4967. except Exception as e:
  4968. return [output_api.PresubmitError(str(e))]
  4969. if potential_problems:
  4970. return [
  4971. output_api.PresubmitPromptWarning(
  4972. 'Discovered possible removal of preference registrations.\n\n'
  4973. 'Please make sure to properly deprecate preferences by clearing their\n'
  4974. 'value for a couple of milestones before finally removing the code.\n'
  4975. 'Otherwise data may stay in the preferences files forever. See\n'
  4976. 'Migrate*Prefs() in chrome/browser/prefs/browser_prefs.cc and\n'
  4977. 'chrome/browser/prefs/README.md for examples.\n'
  4978. 'This may be a false positive warning (e.g. if you move preference\n'
  4979. 'registrations to a different place).\n', potential_problems)
  4980. ]
  4981. return []
  4982. def CheckConsistentGrdChanges(input_api, output_api):
  4983. """Changes to GRD files must be consistent for tools to read them."""
  4984. changed_grds = input_api.AffectedFiles(
  4985. include_deletes=False,
  4986. file_filter=lambda f: f.LocalPath().endswith(('.grd')))
  4987. errors = []
  4988. invalid_file_regexes = [(input_api.re.compile(matcher), msg)
  4989. for matcher, msg in _INVALID_GRD_FILE_LINE]
  4990. for grd in changed_grds:
  4991. for i, line in enumerate(grd.NewContents()):
  4992. for matcher, msg in invalid_file_regexes:
  4993. if matcher.search(line):
  4994. errors.append(
  4995. output_api.PresubmitError(
  4996. 'Problem on {grd}:{i} - {msg}'.format(
  4997. grd=grd.LocalPath(), i=i + 1, msg=msg)))
  4998. return errors
  4999. def CheckMPArchApiUsage(input_api, output_api):
  5000. """CC the MPArch watchlist if the CL uses an API that is ambiguous in the
  5001. presence of MPArch features such as bfcache, prerendering, and fenced frames.
  5002. """
  5003. # Only consider top-level directories that (1) can use content APIs, (2)
  5004. # apply to desktop or android chrome, and (3) are known to have a significant
  5005. # number of uses of the APIs of concern.
  5006. files_to_check = (
  5007. r'^(chrome|components|content|extensions)[\\/].+%s' %
  5008. _IMPLEMENTATION_EXTENSIONS,
  5009. r'^(chrome|components|content|extensions)[\\/].+%s' %
  5010. _HEADER_EXTENSIONS,
  5011. )
  5012. files_to_skip = (_EXCLUDED_PATHS + _TEST_CODE_EXCLUDED_PATHS +
  5013. input_api.DEFAULT_FILES_TO_SKIP)
  5014. source_file_filter = lambda f: input_api.FilterSourceFile(
  5015. f, files_to_check=files_to_check, files_to_skip=files_to_skip)
  5016. # Note that since these are are just regular expressions and we don't have
  5017. # the compiler's AST, we could have spurious matches (e.g. an unrelated class
  5018. # could have a method named IsInMainFrame).
  5019. concerning_class_pattern = input_api.re.compile(
  5020. r'WebContentsObserver|WebContentsUserData')
  5021. # A subset of WebContentsObserver overrides where there's particular risk for
  5022. # confusing tab and page level operations and data (e.g. incorrectly
  5023. # resetting page state in DidFinishNavigation).
  5024. concerning_wco_methods = [
  5025. 'DidStartNavigation',
  5026. 'ReadyToCommitNavigation',
  5027. 'DidFinishNavigation',
  5028. 'RenderViewReady',
  5029. 'RenderViewDeleted',
  5030. 'RenderViewHostChanged',
  5031. 'PrimaryMainDocumentElementAvailable',
  5032. 'DocumentOnLoadCompletedInPrimaryMainFrame',
  5033. 'DOMContentLoaded',
  5034. 'DidFinishLoad',
  5035. ]
  5036. concerning_nav_handle_methods = [
  5037. 'IsInMainFrame',
  5038. ]
  5039. concerning_web_contents_methods = [
  5040. 'ForEachFrame',
  5041. 'GetAllFrames',
  5042. 'FromRenderFrameHost',
  5043. 'FromRenderViewHost',
  5044. 'GetMainFrame',
  5045. 'GetRenderViewHost',
  5046. ]
  5047. concerning_rfh_methods = [
  5048. 'GetParent',
  5049. 'GetMainFrame',
  5050. 'GetFrameTreeNodeId',
  5051. ]
  5052. concerning_ftn_methods = [
  5053. 'IsMainFrame',
  5054. ]
  5055. concerning_method_pattern = input_api.re.compile(r'(' + r'|'.join(
  5056. item for sublist in [
  5057. concerning_wco_methods, concerning_nav_handle_methods,
  5058. concerning_web_contents_methods, concerning_rfh_methods,
  5059. concerning_ftn_methods,
  5060. ] for item in sublist) + r')\(')
  5061. used_apis = set()
  5062. for f in input_api.AffectedFiles(include_deletes=False,
  5063. file_filter=source_file_filter):
  5064. for line_num, line in f.ChangedContents():
  5065. class_match = concerning_class_pattern.search(line)
  5066. if class_match:
  5067. used_apis.add(class_match[0])
  5068. method_match = concerning_method_pattern.search(line)
  5069. if method_match:
  5070. used_apis.add(method_match[1])
  5071. if not used_apis:
  5072. return []
  5073. output_api.AppendCC('mparch-reviews+watch@chromium.org')
  5074. message = ('This change uses API(s) that are ambiguous in the presence of '
  5075. 'MPArch features such as bfcache, prerendering, and fenced '
  5076. 'frames.')
  5077. explaination = (
  5078. 'Please double check whether new code assumes that a WebContents only '
  5079. 'contains a single page at a time. For example, it is discouraged to '
  5080. 'reset per-document state in response to the observation of a '
  5081. 'navigation. See this doc [1] and the comments on the individual APIs '
  5082. 'for guidance and this doc [2] for context. The MPArch review '
  5083. 'watchlist has been CC\'d on this change to help identify any issues.\n'
  5084. '[1] https://docs.google.com/document/d/13l16rWTal3o5wce4i0RwdpMP5ESELLKr439Faj2BBRo/edit?usp=sharing\n'
  5085. '[2] https://docs.google.com/document/d/1NginQ8k0w3znuwTiJ5qjYmBKgZDekvEPC22q0I4swxQ/edit?usp=sharing'
  5086. )
  5087. return [
  5088. output_api.PresubmitNotifyResult(message,
  5089. items=list(used_apis),
  5090. long_text=explaination)
  5091. ]
  5092. def CheckAssertAshOnlyCode(input_api, output_api):
  5093. """Errors if a BUILD.gn file in an ash/ directory doesn't include
  5094. assert(is_chromeos_ash).
  5095. """
  5096. def FileFilter(affected_file):
  5097. """Includes directories known to be Ash only."""
  5098. return input_api.FilterSourceFile(
  5099. affected_file,
  5100. files_to_check=(
  5101. r'^ash/.*BUILD\.gn', # Top-level src/ash/.
  5102. r'.*/ash/.*BUILD\.gn'), # Any path component.
  5103. files_to_skip=(input_api.DEFAULT_FILES_TO_SKIP))
  5104. errors = []
  5105. pattern = input_api.re.compile(r'assert\(is_chromeos_ash')
  5106. for f in input_api.AffectedFiles(include_deletes=False,
  5107. file_filter=FileFilter):
  5108. if (not pattern.search(input_api.ReadFile(f))):
  5109. errors.append(
  5110. output_api.PresubmitError(
  5111. 'Please add assert(is_chromeos_ash) to %s. If that\'s not '
  5112. 'possible, please create and issue and add a comment such '
  5113. 'as:\n # TODO(https://crbug.com/XXX): add '
  5114. 'assert(is_chromeos_ash) when ...' % f.LocalPath()))
  5115. return errors
  5116. def _IsRendererOnlyCppFile(input_api, affected_file):
  5117. path = affected_file.LocalPath()
  5118. if not _IsCPlusPlusFile(input_api, path):
  5119. return False
  5120. # Any code under a "renderer" subdirectory is assumed to be Renderer-only.
  5121. if "/renderer/" in path:
  5122. return True
  5123. # Blink's public/web API is only used/included by Renderer-only code. Note
  5124. # that public/platform API may be used in non-Renderer processes (e.g. there
  5125. # are some includes in code used by Utility, PDF, or Plugin processes).
  5126. if "/blink/public/web/" in path:
  5127. return True
  5128. # We assume that everything else may be used outside of Renderer processes.
  5129. return False
  5130. # TODO(https://crbug.com/1273182): Remove these checks, once they are replaced
  5131. # by the Chromium Clang Plugin (which will be preferable because it will
  5132. # 1) report errors earlier - at compile-time and 2) cover more rules).
  5133. def CheckRawPtrUsage(input_api, output_api):
  5134. """Rough checks that raw_ptr<T> usage guidelines are followed."""
  5135. errors = []
  5136. # The regex below matches "raw_ptr<" following a word boundary, but not in a
  5137. # C++ comment.
  5138. raw_ptr_matcher = input_api.re.compile(r'^((?!//).)*\braw_ptr<')
  5139. file_filter = lambda f: _IsRendererOnlyCppFile(input_api, f)
  5140. for f, line_num, line in input_api.RightHandSideLines(file_filter):
  5141. if raw_ptr_matcher.search(line):
  5142. errors.append(
  5143. output_api.PresubmitError(
  5144. 'Problem on {path}:{line} - '\
  5145. 'raw_ptr<T> should not be used in Renderer-only code '\
  5146. '(as documented in the "Pointers to unprotected memory" '\
  5147. 'section in //base/memory/raw_ptr.md)'.format(
  5148. path=f.LocalPath(), line=line_num)))
  5149. return errors
  5150. def CheckPythonShebang(input_api, output_api):
  5151. """Checks that python scripts use #!/usr/bin/env instead of hardcoding a
  5152. system-wide python.
  5153. """
  5154. errors = []
  5155. sources = lambda affected_file: input_api.FilterSourceFile(
  5156. affected_file,
  5157. files_to_skip=((_THIRD_PARTY_EXCEPT_BLINK,
  5158. r'third_party/blink/web_tests/external/') + input_api.
  5159. DEFAULT_FILES_TO_SKIP),
  5160. files_to_check=[r'.*\.py$'])
  5161. for f in input_api.AffectedSourceFiles(sources):
  5162. for line_num, line in f.ChangedContents():
  5163. if line_num == 1 and line.startswith('#!/usr/bin/python'):
  5164. errors.append(f.LocalPath())
  5165. break
  5166. result = []
  5167. for file in errors:
  5168. result.append(
  5169. output_api.PresubmitError(
  5170. "Please use '#!/usr/bin/env python/2/3' as the shebang of %s" %
  5171. file))
  5172. return result