git_cl.py 196 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355
  1. #!/usr/bin/env vpython
  2. # Copyright (c) 2013 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. # Copyright (C) 2008 Evan Martin <martine@danga.com>
  6. """A git-command for integrating reviews on Gerrit."""
  7. from __future__ import print_function
  8. import base64
  9. import collections
  10. import datetime
  11. import fnmatch
  12. import httplib2
  13. import itertools
  14. import json
  15. import logging
  16. import multiprocessing
  17. import optparse
  18. import os
  19. import re
  20. import shutil
  21. import stat
  22. import sys
  23. import tempfile
  24. import textwrap
  25. import time
  26. import uuid
  27. import webbrowser
  28. import zlib
  29. from third_party import colorama
  30. import auth
  31. import clang_format
  32. import fix_encoding
  33. import gclient_utils
  34. import gerrit_util
  35. import git_common
  36. import git_footers
  37. import git_new_branch
  38. import metrics
  39. import metrics_utils
  40. import owners_client
  41. import owners_finder
  42. import presubmit_canned_checks
  43. import presubmit_support
  44. import scm
  45. import setup_color
  46. import split_cl
  47. import subcommand
  48. import subprocess2
  49. import watchlists
  50. from third_party import six
  51. from six.moves import urllib
  52. if sys.version_info.major == 3:
  53. basestring = (str,) # pylint: disable=redefined-builtin
  54. __version__ = '2.0'
  55. # Traces for git push will be stored in a traces directory inside the
  56. # depot_tools checkout.
  57. DEPOT_TOOLS = os.path.dirname(os.path.abspath(__file__))
  58. TRACES_DIR = os.path.join(DEPOT_TOOLS, 'traces')
  59. PRESUBMIT_SUPPORT = os.path.join(DEPOT_TOOLS, 'presubmit_support.py')
  60. # When collecting traces, Git hashes will be reduced to 6 characters to reduce
  61. # the size after compression.
  62. GIT_HASH_RE = re.compile(r'\b([a-f0-9]{6})[a-f0-9]{34}\b', flags=re.I)
  63. # Used to redact the cookies from the gitcookies file.
  64. GITCOOKIES_REDACT_RE = re.compile(r'1/.*')
  65. MAX_ATTEMPTS = 3
  66. # The maximum number of traces we will keep. Multiplied by 3 since we store
  67. # 3 files per trace.
  68. MAX_TRACES = 3 * 10
  69. # Message to be displayed to the user to inform where to find the traces for a
  70. # git-cl upload execution.
  71. TRACES_MESSAGE = (
  72. '\n'
  73. 'The traces of this git-cl execution have been recorded at:\n'
  74. ' %(trace_name)s-traces.zip\n'
  75. 'Copies of your gitcookies file and git config have been recorded at:\n'
  76. ' %(trace_name)s-git-info.zip\n')
  77. # Format of the message to be stored as part of the traces to give developers a
  78. # better context when they go through traces.
  79. TRACES_README_FORMAT = (
  80. 'Date: %(now)s\n'
  81. '\n'
  82. 'Change: https://%(gerrit_host)s/q/%(change_id)s\n'
  83. 'Title: %(title)s\n'
  84. '\n'
  85. '%(description)s\n'
  86. '\n'
  87. 'Execution time: %(execution_time)s\n'
  88. 'Exit code: %(exit_code)s\n') + TRACES_MESSAGE
  89. POSTUPSTREAM_HOOK = '.git/hooks/post-cl-land'
  90. DESCRIPTION_BACKUP_FILE = '.git_cl_description_backup'
  91. REFS_THAT_ALIAS_TO_OTHER_REFS = {
  92. 'refs/remotes/origin/lkgr': 'refs/remotes/origin/master',
  93. 'refs/remotes/origin/lkcr': 'refs/remotes/origin/master',
  94. }
  95. DEFAULT_OLD_BRANCH = 'refs/remotes/origin/master'
  96. DEFAULT_NEW_BRANCH = 'refs/remotes/origin/main'
  97. # Valid extensions for files we want to lint.
  98. DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)"
  99. DEFAULT_LINT_IGNORE_REGEX = r"$^"
  100. # File name for yapf style config files.
  101. YAPF_CONFIG_FILENAME = '.style.yapf'
  102. # The issue, patchset and codereview server are stored on git config for each
  103. # branch under branch.<branch-name>.<config-key>.
  104. ISSUE_CONFIG_KEY = 'gerritissue'
  105. PATCHSET_CONFIG_KEY = 'gerritpatchset'
  106. CODEREVIEW_SERVER_CONFIG_KEY = 'gerritserver'
  107. # Shortcut since it quickly becomes repetitive.
  108. Fore = colorama.Fore
  109. # Initialized in main()
  110. settings = None
  111. # Used by tests/git_cl_test.py to add extra logging.
  112. # Inside the weirdly failing test, add this:
  113. # >>> self.mock(git_cl, '_IS_BEING_TESTED', True)
  114. # And scroll up to see the stack trace printed.
  115. _IS_BEING_TESTED = False
  116. _KNOWN_GERRIT_TO_SHORT_URLS = {
  117. 'https://chrome-internal-review.googlesource.com': 'https://crrev.com/i',
  118. 'https://chromium-review.googlesource.com': 'https://crrev.com/c',
  119. }
  120. assert len(_KNOWN_GERRIT_TO_SHORT_URLS) == len(
  121. set(_KNOWN_GERRIT_TO_SHORT_URLS.values())), 'must have unique values'
  122. class GitPushError(Exception):
  123. pass
  124. def DieWithError(message, change_desc=None):
  125. if change_desc:
  126. SaveDescriptionBackup(change_desc)
  127. print('\n ** Content of CL description **\n' +
  128. '='*72 + '\n' +
  129. change_desc.description + '\n' +
  130. '='*72 + '\n')
  131. print(message, file=sys.stderr)
  132. sys.exit(1)
  133. def SaveDescriptionBackup(change_desc):
  134. backup_path = os.path.join(DEPOT_TOOLS, DESCRIPTION_BACKUP_FILE)
  135. print('\nsaving CL description to %s\n' % backup_path)
  136. with open(backup_path, 'w') as backup_file:
  137. backup_file.write(change_desc.description)
  138. def GetNoGitPagerEnv():
  139. env = os.environ.copy()
  140. # 'cat' is a magical git string that disables pagers on all platforms.
  141. env['GIT_PAGER'] = 'cat'
  142. return env
  143. def RunCommand(args, error_ok=False, error_message=None, shell=False, **kwargs):
  144. try:
  145. stdout = subprocess2.check_output(args, shell=shell, **kwargs)
  146. return stdout.decode('utf-8', 'replace')
  147. except subprocess2.CalledProcessError as e:
  148. logging.debug('Failed running %s', args)
  149. if not error_ok:
  150. message = error_message or e.stdout.decode('utf-8', 'replace') or ''
  151. DieWithError('Command "%s" failed.\n%s' % (' '.join(args), message))
  152. return e.stdout.decode('utf-8', 'replace')
  153. def RunGit(args, **kwargs):
  154. """Returns stdout."""
  155. return RunCommand(['git'] + args, **kwargs)
  156. def RunGitWithCode(args, suppress_stderr=False):
  157. """Returns return code and stdout."""
  158. if suppress_stderr:
  159. stderr = subprocess2.DEVNULL
  160. else:
  161. stderr = sys.stderr
  162. try:
  163. (out, _), code = subprocess2.communicate(['git'] + args,
  164. env=GetNoGitPagerEnv(),
  165. stdout=subprocess2.PIPE,
  166. stderr=stderr)
  167. return code, out.decode('utf-8', 'replace')
  168. except subprocess2.CalledProcessError as e:
  169. logging.debug('Failed running %s', ['git'] + args)
  170. return e.returncode, e.stdout.decode('utf-8', 'replace')
  171. def RunGitSilent(args):
  172. """Returns stdout, suppresses stderr and ignores the return code."""
  173. return RunGitWithCode(args, suppress_stderr=True)[1]
  174. def time_sleep(seconds):
  175. # Use this so that it can be mocked in tests without interfering with python
  176. # system machinery.
  177. return time.sleep(seconds)
  178. def time_time():
  179. # Use this so that it can be mocked in tests without interfering with python
  180. # system machinery.
  181. return time.time()
  182. def datetime_now():
  183. # Use this so that it can be mocked in tests without interfering with python
  184. # system machinery.
  185. return datetime.datetime.now()
  186. def confirm_or_exit(prefix='', action='confirm'):
  187. """Asks user to press enter to continue or press Ctrl+C to abort."""
  188. if not prefix or prefix.endswith('\n'):
  189. mid = 'Press'
  190. elif prefix.endswith('.') or prefix.endswith('?'):
  191. mid = ' Press'
  192. elif prefix.endswith(' '):
  193. mid = 'press'
  194. else:
  195. mid = ' press'
  196. gclient_utils.AskForData(
  197. '%s%s Enter to %s, or Ctrl+C to abort' % (prefix, mid, action))
  198. def ask_for_explicit_yes(prompt):
  199. """Returns whether user typed 'y' or 'yes' to confirm the given prompt."""
  200. result = gclient_utils.AskForData(prompt + ' [Yes/No]: ').lower()
  201. while True:
  202. if 'yes'.startswith(result):
  203. return True
  204. if 'no'.startswith(result):
  205. return False
  206. result = gclient_utils.AskForData('Please, type yes or no: ').lower()
  207. def _get_properties_from_options(options):
  208. prop_list = getattr(options, 'properties', [])
  209. properties = dict(x.split('=', 1) for x in prop_list)
  210. for key, val in properties.items():
  211. try:
  212. properties[key] = json.loads(val)
  213. except ValueError:
  214. pass # If a value couldn't be evaluated, treat it as a string.
  215. return properties
  216. def _call_buildbucket(http, buildbucket_host, method, request):
  217. """Calls a buildbucket v2 method and returns the parsed json response."""
  218. headers = {
  219. 'Accept': 'application/json',
  220. 'Content-Type': 'application/json',
  221. }
  222. request = json.dumps(request)
  223. url = 'https://%s/prpc/buildbucket.v2.Builds/%s' % (buildbucket_host, method)
  224. logging.info('POST %s with %s' % (url, request))
  225. attempts = 1
  226. time_to_sleep = 1
  227. while True:
  228. response, content = http.request(url, 'POST', body=request, headers=headers)
  229. if response.status == 200:
  230. return json.loads(content[4:])
  231. if attempts >= MAX_ATTEMPTS or 400 <= response.status < 500:
  232. msg = '%s error when calling POST %s with %s: %s' % (
  233. response.status, url, request, content)
  234. raise BuildbucketResponseException(msg)
  235. logging.debug(
  236. '%s error when calling POST %s with %s. '
  237. 'Sleeping for %d seconds and retrying...' % (
  238. response.status, url, request, time_to_sleep))
  239. time.sleep(time_to_sleep)
  240. time_to_sleep *= 2
  241. attempts += 1
  242. assert False, 'unreachable'
  243. def _parse_bucket(raw_bucket):
  244. legacy = True
  245. project = bucket = None
  246. if '/' in raw_bucket:
  247. legacy = False
  248. project, bucket = raw_bucket.split('/', 1)
  249. # Assume luci.<project>.<bucket>.
  250. elif raw_bucket.startswith('luci.'):
  251. project, bucket = raw_bucket[len('luci.'):].split('.', 1)
  252. # Otherwise, assume prefix is also the project name.
  253. elif '.' in raw_bucket:
  254. project = raw_bucket.split('.')[0]
  255. bucket = raw_bucket
  256. # Legacy buckets.
  257. if legacy and project and bucket:
  258. print('WARNING Please use %s/%s to specify the bucket.' % (project, bucket))
  259. return project, bucket
  260. def _trigger_tryjobs(changelist, jobs, options, patchset):
  261. """Sends a request to Buildbucket to trigger tryjobs for a changelist.
  262. Args:
  263. changelist: Changelist that the tryjobs are associated with.
  264. jobs: A list of (project, bucket, builder).
  265. options: Command-line options.
  266. """
  267. print('Scheduling jobs on:')
  268. for project, bucket, builder in jobs:
  269. print(' %s/%s: %s' % (project, bucket, builder))
  270. print('To see results here, run: git cl try-results')
  271. print('To see results in browser, run: git cl web')
  272. requests = _make_tryjob_schedule_requests(changelist, jobs, options, patchset)
  273. if not requests:
  274. return
  275. http = auth.Authenticator().authorize(httplib2.Http())
  276. http.force_exception_to_status_code = True
  277. batch_request = {'requests': requests}
  278. batch_response = _call_buildbucket(
  279. http, options.buildbucket_host, 'Batch', batch_request)
  280. errors = [
  281. ' ' + response['error']['message']
  282. for response in batch_response.get('responses', [])
  283. if 'error' in response
  284. ]
  285. if errors:
  286. raise BuildbucketResponseException(
  287. 'Failed to schedule builds for some bots:\n%s' % '\n'.join(errors))
  288. def _make_tryjob_schedule_requests(changelist, jobs, options, patchset):
  289. """Constructs requests for Buildbucket to trigger tryjobs."""
  290. gerrit_changes = [changelist.GetGerritChange(patchset)]
  291. shared_properties = {
  292. 'category': options.ensure_value('category', 'git_cl_try')
  293. }
  294. if options.ensure_value('clobber', False):
  295. shared_properties['clobber'] = True
  296. shared_properties.update(_get_properties_from_options(options) or {})
  297. shared_tags = [{'key': 'user_agent', 'value': 'git_cl_try'}]
  298. if options.ensure_value('retry_failed', False):
  299. shared_tags.append({'key': 'retry_failed',
  300. 'value': '1'})
  301. requests = []
  302. for (project, bucket, builder) in jobs:
  303. properties = shared_properties.copy()
  304. if 'presubmit' in builder.lower():
  305. properties['dry_run'] = 'true'
  306. requests.append({
  307. 'scheduleBuild': {
  308. 'requestId': str(uuid.uuid4()),
  309. 'builder': {
  310. 'project': getattr(options, 'project', None) or project,
  311. 'bucket': bucket,
  312. 'builder': builder,
  313. },
  314. 'gerritChanges': gerrit_changes,
  315. 'properties': properties,
  316. 'tags': [
  317. {'key': 'builder', 'value': builder},
  318. ] + shared_tags,
  319. }
  320. })
  321. if options.ensure_value('revision', None):
  322. remote, remote_branch = changelist.GetRemoteBranch()
  323. requests[-1]['scheduleBuild']['gitilesCommit'] = {
  324. 'host': gerrit_changes[0]['host'],
  325. 'project': gerrit_changes[0]['project'],
  326. 'id': options.revision,
  327. 'ref': GetTargetRef(remote, remote_branch, None)
  328. }
  329. return requests
  330. def _fetch_tryjobs(changelist, buildbucket_host, patchset=None):
  331. """Fetches tryjobs from buildbucket.
  332. Returns list of buildbucket.v2.Build with the try jobs for the changelist.
  333. """
  334. fields = ['id', 'builder', 'status', 'createTime', 'tags']
  335. request = {
  336. 'predicate': {
  337. 'gerritChanges': [changelist.GetGerritChange(patchset)],
  338. },
  339. 'fields': ','.join('builds.*.' + field for field in fields),
  340. }
  341. authenticator = auth.Authenticator()
  342. if authenticator.has_cached_credentials():
  343. http = authenticator.authorize(httplib2.Http())
  344. else:
  345. print('Warning: Some results might be missing because %s' %
  346. # Get the message on how to login.
  347. (str(auth.LoginRequiredError()),))
  348. http = httplib2.Http()
  349. http.force_exception_to_status_code = True
  350. response = _call_buildbucket(http, buildbucket_host, 'SearchBuilds', request)
  351. return response.get('builds', [])
  352. def _fetch_latest_builds(changelist, buildbucket_host, latest_patchset=None):
  353. """Fetches builds from the latest patchset that has builds (within
  354. the last few patchsets).
  355. Args:
  356. changelist (Changelist): The CL to fetch builds for
  357. buildbucket_host (str): Buildbucket host, e.g. "cr-buildbucket.appspot.com"
  358. lastest_patchset(int|NoneType): the patchset to start fetching builds from.
  359. If None (default), starts with the latest available patchset.
  360. Returns:
  361. A tuple (builds, patchset) where builds is a list of buildbucket.v2.Build,
  362. and patchset is the patchset number where those builds came from.
  363. """
  364. assert buildbucket_host
  365. assert changelist.GetIssue(), 'CL must be uploaded first'
  366. assert changelist.GetCodereviewServer(), 'CL must be uploaded first'
  367. if latest_patchset is None:
  368. assert changelist.GetMostRecentPatchset()
  369. ps = changelist.GetMostRecentPatchset()
  370. else:
  371. assert latest_patchset > 0, latest_patchset
  372. ps = latest_patchset
  373. min_ps = max(1, ps - 5)
  374. while ps >= min_ps:
  375. builds = _fetch_tryjobs(changelist, buildbucket_host, patchset=ps)
  376. if len(builds):
  377. return builds, ps
  378. ps -= 1
  379. return [], 0
  380. def _filter_failed_for_retry(all_builds):
  381. """Returns a list of buckets/builders that are worth retrying.
  382. Args:
  383. all_builds (list): Builds, in the format returned by _fetch_tryjobs,
  384. i.e. a list of buildbucket.v2.Builds which includes status and builder
  385. info.
  386. Returns:
  387. A dict {(proj, bucket): [builders]}. This is the same format accepted by
  388. _trigger_tryjobs.
  389. """
  390. grouped = {}
  391. for build in all_builds:
  392. builder = build['builder']
  393. key = (builder['project'], builder['bucket'], builder['builder'])
  394. grouped.setdefault(key, []).append(build)
  395. jobs = []
  396. for (project, bucket, builder), builds in grouped.items():
  397. if 'triggered' in builder:
  398. print('WARNING: Not scheduling %s. Triggered bots require an initial job '
  399. 'from a parent. Please schedule a manual job for the parent '
  400. 'instead.')
  401. continue
  402. if any(b['status'] in ('STARTED', 'SCHEDULED') for b in builds):
  403. # Don't retry if any are running.
  404. continue
  405. # If builder had several builds, retry only if the last one failed.
  406. # This is a bit different from CQ, which would re-use *any* SUCCESS-full
  407. # build, but in case of retrying failed jobs retrying a flaky one makes
  408. # sense.
  409. builds = sorted(builds, key=lambda b: b['createTime'])
  410. if builds[-1]['status'] not in ('FAILURE', 'INFRA_FAILURE'):
  411. continue
  412. # Don't retry experimental build previously triggered by CQ.
  413. if any(t['key'] == 'cq_experimental' and t['value'] == 'true'
  414. for t in builds[-1]['tags']):
  415. continue
  416. jobs.append((project, bucket, builder))
  417. # Sort the jobs to make testing easier.
  418. return sorted(jobs)
  419. def _print_tryjobs(options, builds):
  420. """Prints nicely result of _fetch_tryjobs."""
  421. if not builds:
  422. print('No tryjobs scheduled.')
  423. return
  424. longest_builder = max(len(b['builder']['builder']) for b in builds)
  425. name_fmt = '{builder:<%d}' % longest_builder
  426. if options.print_master:
  427. longest_bucket = max(len(b['builder']['bucket']) for b in builds)
  428. name_fmt = ('{bucket:>%d} ' % longest_bucket) + name_fmt
  429. builds_by_status = {}
  430. for b in builds:
  431. builds_by_status.setdefault(b['status'], []).append({
  432. 'id': b['id'],
  433. 'name': name_fmt.format(
  434. builder=b['builder']['builder'], bucket=b['builder']['bucket']),
  435. })
  436. sort_key = lambda b: (b['name'], b['id'])
  437. def print_builds(title, builds, fmt=None, color=None):
  438. """Pop matching builds from `builds` dict and print them."""
  439. if not builds:
  440. return
  441. fmt = fmt or '{name} https://ci.chromium.org/b/{id}'
  442. if not options.color or color is None:
  443. colorize = lambda x: x
  444. else:
  445. colorize = lambda x: '%s%s%s' % (color, x, Fore.RESET)
  446. print(colorize(title))
  447. for b in sorted(builds, key=sort_key):
  448. print(' ', colorize(fmt.format(**b)))
  449. total = len(builds)
  450. print_builds(
  451. 'Successes:', builds_by_status.pop('SUCCESS', []), color=Fore.GREEN)
  452. print_builds(
  453. 'Infra Failures:', builds_by_status.pop('INFRA_FAILURE', []),
  454. color=Fore.MAGENTA)
  455. print_builds('Failures:', builds_by_status.pop('FAILURE', []), color=Fore.RED)
  456. print_builds('Canceled:', builds_by_status.pop('CANCELED', []), fmt='{name}',
  457. color=Fore.MAGENTA)
  458. print_builds('Started:', builds_by_status.pop('STARTED', []),
  459. color=Fore.YELLOW)
  460. print_builds(
  461. 'Scheduled:', builds_by_status.pop('SCHEDULED', []), fmt='{name} id={id}')
  462. # The last section is just in case buildbucket API changes OR there is a bug.
  463. print_builds(
  464. 'Other:', sum(builds_by_status.values(), []), fmt='{name} id={id}')
  465. print('Total: %d tryjobs' % total)
  466. def _ComputeDiffLineRanges(files, upstream_commit):
  467. """Gets the changed line ranges for each file since upstream_commit.
  468. Parses a git diff on provided files and returns a dict that maps a file name
  469. to an ordered list of range tuples in the form (start_line, count).
  470. Ranges are in the same format as a git diff.
  471. """
  472. # If files is empty then diff_output will be a full diff.
  473. if len(files) == 0:
  474. return {}
  475. # Take the git diff and find the line ranges where there are changes.
  476. diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, files, allow_prefix=True)
  477. diff_output = RunGit(diff_cmd)
  478. pattern = r'(?:^diff --git a/(?:.*) b/(.*))|(?:^@@.*\+(.*) @@)'
  479. # 2 capture groups
  480. # 0 == fname of diff file
  481. # 1 == 'diff_start,diff_count' or 'diff_start'
  482. # will match each of
  483. # diff --git a/foo.foo b/foo.py
  484. # @@ -12,2 +14,3 @@
  485. # @@ -12,2 +17 @@
  486. # running re.findall on the above string with pattern will give
  487. # [('foo.py', ''), ('', '14,3'), ('', '17')]
  488. curr_file = None
  489. line_diffs = {}
  490. for match in re.findall(pattern, diff_output, flags=re.MULTILINE):
  491. if match[0] != '':
  492. # Will match the second filename in diff --git a/a.py b/b.py.
  493. curr_file = match[0]
  494. line_diffs[curr_file] = []
  495. else:
  496. # Matches +14,3
  497. if ',' in match[1]:
  498. diff_start, diff_count = match[1].split(',')
  499. else:
  500. # Single line changes are of the form +12 instead of +12,1.
  501. diff_start = match[1]
  502. diff_count = 1
  503. diff_start = int(diff_start)
  504. diff_count = int(diff_count)
  505. # If diff_count == 0 this is a removal we can ignore.
  506. line_diffs[curr_file].append((diff_start, diff_count))
  507. return line_diffs
  508. def _FindYapfConfigFile(fpath, yapf_config_cache, top_dir=None):
  509. """Checks if a yapf file is in any parent directory of fpath until top_dir.
  510. Recursively checks parent directories to find yapf file and if no yapf file
  511. is found returns None. Uses yapf_config_cache as a cache for previously found
  512. configs.
  513. """
  514. fpath = os.path.abspath(fpath)
  515. # Return result if we've already computed it.
  516. if fpath in yapf_config_cache:
  517. return yapf_config_cache[fpath]
  518. parent_dir = os.path.dirname(fpath)
  519. if os.path.isfile(fpath):
  520. ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir)
  521. else:
  522. # Otherwise fpath is a directory
  523. yapf_file = os.path.join(fpath, YAPF_CONFIG_FILENAME)
  524. if os.path.isfile(yapf_file):
  525. ret = yapf_file
  526. elif fpath == top_dir or parent_dir == fpath:
  527. # If we're at the top level directory, or if we're at root
  528. # there is no provided style.
  529. ret = None
  530. else:
  531. # Otherwise recurse on the current directory.
  532. ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir)
  533. yapf_config_cache[fpath] = ret
  534. return ret
  535. def _GetYapfIgnorePatterns(top_dir):
  536. """Returns all patterns in the .yapfignore file.
  537. yapf is supposed to handle the ignoring of files listed in .yapfignore itself,
  538. but this functionality appears to break when explicitly passing files to
  539. yapf for formatting. According to
  540. https://github.com/google/yapf/blob/HEAD/README.rst#excluding-files-from-formatting-yapfignore,
  541. the .yapfignore file should be in the directory that yapf is invoked from,
  542. which we assume to be the top level directory in this case.
  543. Args:
  544. top_dir: The top level directory for the repository being formatted.
  545. Returns:
  546. A set of all fnmatch patterns to be ignored.
  547. """
  548. yapfignore_file = os.path.join(top_dir, '.yapfignore')
  549. ignore_patterns = set()
  550. if not os.path.exists(yapfignore_file):
  551. return ignore_patterns
  552. with open(yapfignore_file) as f:
  553. for line in f.readlines():
  554. stripped_line = line.strip()
  555. # Comments and blank lines should be ignored.
  556. if stripped_line.startswith('#') or stripped_line == '':
  557. continue
  558. ignore_patterns.add(stripped_line)
  559. return ignore_patterns
  560. def _FilterYapfIgnoredFiles(filepaths, patterns):
  561. """Filters out any filepaths that match any of the given patterns.
  562. Args:
  563. filepaths: An iterable of strings containing filepaths to filter.
  564. patterns: An iterable of strings containing fnmatch patterns to filter on.
  565. Returns:
  566. A list of strings containing all the elements of |filepaths| that did not
  567. match any of the patterns in |patterns|.
  568. """
  569. # Not inlined so that tests can use the same implementation.
  570. return [f for f in filepaths
  571. if not any(fnmatch.fnmatch(f, p) for p in patterns)]
  572. def print_stats(args):
  573. """Prints statistics about the change to the user."""
  574. # --no-ext-diff is broken in some versions of Git, so try to work around
  575. # this by overriding the environment (but there is still a problem if the
  576. # git config key "diff.external" is used).
  577. env = GetNoGitPagerEnv()
  578. if 'GIT_EXTERNAL_DIFF' in env:
  579. del env['GIT_EXTERNAL_DIFF']
  580. return subprocess2.call(
  581. ['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] + args,
  582. env=env)
  583. class BuildbucketResponseException(Exception):
  584. pass
  585. class Settings(object):
  586. def __init__(self):
  587. self.cc = None
  588. self.root = None
  589. self.tree_status_url = None
  590. self.viewvc_url = None
  591. self.updated = False
  592. self.is_gerrit = None
  593. self.squash_gerrit_uploads = None
  594. self.gerrit_skip_ensure_authenticated = None
  595. self.git_editor = None
  596. self.format_full_by_default = None
  597. def _LazyUpdateIfNeeded(self):
  598. """Updates the settings from a codereview.settings file, if available."""
  599. if self.updated:
  600. return
  601. # The only value that actually changes the behavior is
  602. # autoupdate = "false". Everything else means "true".
  603. autoupdate = (
  604. scm.GIT.GetConfig(self.GetRoot(), 'rietveld.autoupdate', '').lower())
  605. cr_settings_file = FindCodereviewSettingsFile()
  606. if autoupdate != 'false' and cr_settings_file:
  607. LoadCodereviewSettingsFromFile(cr_settings_file)
  608. cr_settings_file.close()
  609. self.updated = True
  610. @staticmethod
  611. def GetRelativeRoot():
  612. return scm.GIT.GetCheckoutRoot('.')
  613. def GetRoot(self):
  614. if self.root is None:
  615. self.root = os.path.abspath(self.GetRelativeRoot())
  616. return self.root
  617. def GetTreeStatusUrl(self, error_ok=False):
  618. if not self.tree_status_url:
  619. self.tree_status_url = self._GetConfig('rietveld.tree-status-url')
  620. if self.tree_status_url is None and not error_ok:
  621. DieWithError(
  622. 'You must configure your tree status URL by running '
  623. '"git cl config".')
  624. return self.tree_status_url
  625. def GetViewVCUrl(self):
  626. if not self.viewvc_url:
  627. self.viewvc_url = self._GetConfig('rietveld.viewvc-url')
  628. return self.viewvc_url
  629. def GetBugPrefix(self):
  630. return self._GetConfig('rietveld.bug-prefix')
  631. def GetRunPostUploadHook(self):
  632. run_post_upload_hook = self._GetConfig(
  633. 'rietveld.run-post-upload-hook')
  634. return run_post_upload_hook == "True"
  635. def GetDefaultCCList(self):
  636. return self._GetConfig('rietveld.cc')
  637. def GetSquashGerritUploads(self):
  638. """Returns True if uploads to Gerrit should be squashed by default."""
  639. if self.squash_gerrit_uploads is None:
  640. self.squash_gerrit_uploads = self.GetSquashGerritUploadsOverride()
  641. if self.squash_gerrit_uploads is None:
  642. # Default is squash now (http://crbug.com/611892#c23).
  643. self.squash_gerrit_uploads = self._GetConfig(
  644. 'gerrit.squash-uploads').lower() != 'false'
  645. return self.squash_gerrit_uploads
  646. def GetSquashGerritUploadsOverride(self):
  647. """Return True or False if codereview.settings should be overridden.
  648. Returns None if no override has been defined.
  649. """
  650. # See also http://crbug.com/611892#c23
  651. result = self._GetConfig('gerrit.override-squash-uploads').lower()
  652. if result == 'true':
  653. return True
  654. if result == 'false':
  655. return False
  656. return None
  657. def GetGerritSkipEnsureAuthenticated(self):
  658. """Return True if EnsureAuthenticated should not be done for Gerrit
  659. uploads."""
  660. if self.gerrit_skip_ensure_authenticated is None:
  661. self.gerrit_skip_ensure_authenticated = self._GetConfig(
  662. 'gerrit.skip-ensure-authenticated').lower() == 'true'
  663. return self.gerrit_skip_ensure_authenticated
  664. def GetGitEditor(self):
  665. """Returns the editor specified in the git config, or None if none is."""
  666. if self.git_editor is None:
  667. # Git requires single quotes for paths with spaces. We need to replace
  668. # them with double quotes for Windows to treat such paths as a single
  669. # path.
  670. self.git_editor = self._GetConfig('core.editor').replace('\'', '"')
  671. return self.git_editor or None
  672. def GetLintRegex(self):
  673. return self._GetConfig('rietveld.cpplint-regex', DEFAULT_LINT_REGEX)
  674. def GetLintIgnoreRegex(self):
  675. return self._GetConfig(
  676. 'rietveld.cpplint-ignore-regex', DEFAULT_LINT_IGNORE_REGEX)
  677. def GetFormatFullByDefault(self):
  678. if self.format_full_by_default is None:
  679. result = (
  680. RunGit(['config', '--bool', 'rietveld.format-full-by-default'],
  681. error_ok=True).strip())
  682. self.format_full_by_default = (result == 'true')
  683. return self.format_full_by_default
  684. def _GetConfig(self, key, default=''):
  685. self._LazyUpdateIfNeeded()
  686. return scm.GIT.GetConfig(self.GetRoot(), key, default)
  687. class _CQState(object):
  688. """Enum for states of CL with respect to CQ."""
  689. NONE = 'none'
  690. DRY_RUN = 'dry_run'
  691. COMMIT = 'commit'
  692. ALL_STATES = [NONE, DRY_RUN, COMMIT]
  693. class _ParsedIssueNumberArgument(object):
  694. def __init__(self, issue=None, patchset=None, hostname=None):
  695. self.issue = issue
  696. self.patchset = patchset
  697. self.hostname = hostname
  698. @property
  699. def valid(self):
  700. return self.issue is not None
  701. def ParseIssueNumberArgument(arg):
  702. """Parses the issue argument and returns _ParsedIssueNumberArgument."""
  703. fail_result = _ParsedIssueNumberArgument()
  704. if isinstance(arg, int):
  705. return _ParsedIssueNumberArgument(issue=arg)
  706. if not isinstance(arg, basestring):
  707. return fail_result
  708. if arg.isdigit():
  709. return _ParsedIssueNumberArgument(issue=int(arg))
  710. if not arg.startswith('http'):
  711. return fail_result
  712. url = gclient_utils.UpgradeToHttps(arg)
  713. for gerrit_url, short_url in _KNOWN_GERRIT_TO_SHORT_URLS.items():
  714. if url.startswith(short_url):
  715. url = gerrit_url + url[len(short_url):]
  716. break
  717. try:
  718. parsed_url = urllib.parse.urlparse(url)
  719. except ValueError:
  720. return fail_result
  721. # Gerrit's new UI is https://domain/c/project/+/<issue_number>[/[patchset]]
  722. # But old GWT UI is https://domain/#/c/project/+/<issue_number>[/[patchset]]
  723. # Short urls like https://domain/<issue_number> can be used, but don't allow
  724. # specifying the patchset (you'd 404), but we allow that here.
  725. if parsed_url.path == '/':
  726. part = parsed_url.fragment
  727. else:
  728. part = parsed_url.path
  729. match = re.match(
  730. r'(/c(/.*/\+)?)?/(?P<issue>\d+)(/(?P<patchset>\d+)?/?)?$', part)
  731. if not match:
  732. return fail_result
  733. issue = int(match.group('issue'))
  734. patchset = match.group('patchset')
  735. return _ParsedIssueNumberArgument(
  736. issue=issue,
  737. patchset=int(patchset) if patchset else None,
  738. hostname=parsed_url.netloc)
  739. def _create_description_from_log(args):
  740. """Pulls out the commit log to use as a base for the CL description."""
  741. log_args = []
  742. if len(args) == 1 and not args[0].endswith('.'):
  743. log_args = [args[0] + '..']
  744. elif len(args) == 1 and args[0].endswith('...'):
  745. log_args = [args[0][:-1]]
  746. elif len(args) == 2:
  747. log_args = [args[0] + '..' + args[1]]
  748. else:
  749. log_args = args[:] # Hope for the best!
  750. return RunGit(['log', '--pretty=format:%B%n'] + log_args)
  751. class GerritChangeNotExists(Exception):
  752. def __init__(self, issue, url):
  753. self.issue = issue
  754. self.url = url
  755. super(GerritChangeNotExists, self).__init__()
  756. def __str__(self):
  757. return 'change %s at %s does not exist or you have no access to it' % (
  758. self.issue, self.url)
  759. _CommentSummary = collections.namedtuple(
  760. '_CommentSummary', ['date', 'message', 'sender', 'autogenerated',
  761. # TODO(tandrii): these two aren't known in Gerrit.
  762. 'approval', 'disapproval'])
  763. class Changelist(object):
  764. """Changelist works with one changelist in local branch.
  765. Notes:
  766. * Not safe for concurrent multi-{thread,process} use.
  767. * Caches values from current branch. Therefore, re-use after branch change
  768. with great care.
  769. """
  770. def __init__(self,
  771. branchref=None,
  772. issue=None,
  773. codereview_host=None,
  774. commit_date=None):
  775. """Create a new ChangeList instance.
  776. **kwargs will be passed directly to Gerrit implementation.
  777. """
  778. # Poke settings so we get the "configure your server" message if necessary.
  779. global settings
  780. if not settings:
  781. # Happens when git_cl.py is used as a utility library.
  782. settings = Settings()
  783. self.branchref = branchref
  784. if self.branchref:
  785. assert branchref.startswith('refs/heads/')
  786. self.branch = scm.GIT.ShortBranchName(self.branchref)
  787. else:
  788. self.branch = None
  789. self.commit_date = commit_date
  790. self.upstream_branch = None
  791. self.lookedup_issue = False
  792. self.issue = issue or None
  793. self.description = None
  794. self.lookedup_patchset = False
  795. self.patchset = None
  796. self.cc = None
  797. self.more_cc = []
  798. self._remote = None
  799. self._cached_remote_url = (False, None) # (is_cached, value)
  800. # Lazily cached values.
  801. self._gerrit_host = None # e.g. chromium-review.googlesource.com
  802. self._gerrit_server = None # e.g. https://chromium-review.googlesource.com
  803. self._owners_client = None
  804. # Map from change number (issue) to its detail cache.
  805. self._detail_cache = {}
  806. if codereview_host is not None:
  807. assert not codereview_host.startswith('https://'), codereview_host
  808. self._gerrit_host = codereview_host
  809. self._gerrit_server = 'https://%s' % codereview_host
  810. @property
  811. def owners_client(self):
  812. if self._owners_client is None:
  813. remote, remote_branch = self.GetRemoteBranch()
  814. branch = GetTargetRef(remote, remote_branch, None)
  815. self._owners_client = owners_client.GetCodeOwnersClient(
  816. root=settings.GetRoot(),
  817. upstream=self.GetCommonAncestorWithUpstream(),
  818. host=self.GetGerritHost(),
  819. project=self.GetGerritProject(),
  820. branch=branch)
  821. return self._owners_client
  822. def GetCCList(self):
  823. """Returns the users cc'd on this CL.
  824. The return value is a string suitable for passing to git cl with the --cc
  825. flag.
  826. """
  827. if self.cc is None:
  828. base_cc = settings.GetDefaultCCList()
  829. more_cc = ','.join(self.more_cc)
  830. self.cc = ','.join(filter(None, (base_cc, more_cc))) or ''
  831. return self.cc
  832. def ExtendCC(self, more_cc):
  833. """Extends the list of users to cc on this CL based on the changed files."""
  834. self.more_cc.extend(more_cc)
  835. def GetCommitDate(self):
  836. """Returns the commit date as provided in the constructor"""
  837. return self.commit_date
  838. def GetBranch(self):
  839. """Returns the short branch name, e.g. 'main'."""
  840. if not self.branch:
  841. branchref = scm.GIT.GetBranchRef(settings.GetRoot())
  842. if not branchref:
  843. return None
  844. self.branchref = branchref
  845. self.branch = scm.GIT.ShortBranchName(self.branchref)
  846. return self.branch
  847. def GetBranchRef(self):
  848. """Returns the full branch name, e.g. 'refs/heads/main'."""
  849. self.GetBranch() # Poke the lazy loader.
  850. return self.branchref
  851. def _GitGetBranchConfigValue(self, key, default=None):
  852. return scm.GIT.GetBranchConfig(
  853. settings.GetRoot(), self.GetBranch(), key, default)
  854. def _GitSetBranchConfigValue(self, key, value):
  855. action = 'set %s to %r' % (key, value)
  856. if not value:
  857. action = 'unset %s' % key
  858. assert self.GetBranch(), 'a branch is needed to ' + action
  859. return scm.GIT.SetBranchConfig(
  860. settings.GetRoot(), self.GetBranch(), key, value)
  861. @staticmethod
  862. def FetchUpstreamTuple(branch):
  863. """Returns a tuple containing remote and remote ref,
  864. e.g. 'origin', 'refs/heads/main'
  865. """
  866. remote, upstream_branch = scm.GIT.FetchUpstreamTuple(
  867. settings.GetRoot(), branch)
  868. if not remote or not upstream_branch:
  869. DieWithError(
  870. 'Unable to determine default branch to diff against.\n'
  871. 'Verify this branch is set up to track another \n'
  872. '(via the --track argument to "git checkout -b ..."). \n'
  873. 'or pass complete "git diff"-style arguments if supported, like\n'
  874. ' git cl upload origin/main\n')
  875. return remote, upstream_branch
  876. def GetCommonAncestorWithUpstream(self):
  877. upstream_branch = self.GetUpstreamBranch()
  878. if not scm.GIT.IsValidRevision(settings.GetRoot(), upstream_branch):
  879. DieWithError('The upstream for the current branch (%s) does not exist '
  880. 'anymore.\nPlease fix it and try again.' % self.GetBranch())
  881. return git_common.get_or_create_merge_base(self.GetBranch(),
  882. upstream_branch)
  883. def GetUpstreamBranch(self):
  884. if self.upstream_branch is None:
  885. remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
  886. if remote != '.':
  887. upstream_branch = upstream_branch.replace('refs/heads/',
  888. 'refs/remotes/%s/' % remote)
  889. upstream_branch = upstream_branch.replace('refs/branch-heads/',
  890. 'refs/remotes/branch-heads/')
  891. self.upstream_branch = upstream_branch
  892. return self.upstream_branch
  893. def GetRemoteBranch(self):
  894. if not self._remote:
  895. remote, branch = None, self.GetBranch()
  896. seen_branches = set()
  897. while branch not in seen_branches:
  898. seen_branches.add(branch)
  899. remote, branch = self.FetchUpstreamTuple(branch)
  900. branch = scm.GIT.ShortBranchName(branch)
  901. if remote != '.' or branch.startswith('refs/remotes'):
  902. break
  903. else:
  904. remotes = RunGit(['remote'], error_ok=True).split()
  905. if len(remotes) == 1:
  906. remote, = remotes
  907. elif 'origin' in remotes:
  908. remote = 'origin'
  909. logging.warning('Could not determine which remote this change is '
  910. 'associated with, so defaulting to "%s".' %
  911. self._remote)
  912. else:
  913. logging.warning('Could not determine which remote this change is '
  914. 'associated with.')
  915. branch = 'HEAD'
  916. if branch.startswith('refs/remotes'):
  917. self._remote = (remote, branch)
  918. elif branch.startswith('refs/branch-heads/'):
  919. self._remote = (remote, branch.replace('refs/', 'refs/remotes/'))
  920. else:
  921. self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch))
  922. return self._remote
  923. def GetRemoteUrl(self):
  924. """Return the configured remote URL, e.g. 'git://example.org/foo.git/'.
  925. Returns None if there is no remote.
  926. """
  927. is_cached, value = self._cached_remote_url
  928. if is_cached:
  929. return value
  930. remote, _ = self.GetRemoteBranch()
  931. url = scm.GIT.GetConfig(settings.GetRoot(), 'remote.%s.url' % remote, '')
  932. # Check if the remote url can be parsed as an URL.
  933. host = urllib.parse.urlparse(url).netloc
  934. if host:
  935. self._cached_remote_url = (True, url)
  936. return url
  937. # If it cannot be parsed as an url, assume it is a local directory,
  938. # probably a git cache.
  939. logging.warning('"%s" doesn\'t appear to point to a git host. '
  940. 'Interpreting it as a local directory.', url)
  941. if not os.path.isdir(url):
  942. logging.error(
  943. 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
  944. 'but it doesn\'t exist.',
  945. {'remote': remote, 'branch': self.GetBranch(), 'url': url})
  946. return None
  947. cache_path = url
  948. url = scm.GIT.GetConfig(url, 'remote.%s.url' % remote, '')
  949. host = urllib.parse.urlparse(url).netloc
  950. if not host:
  951. logging.error(
  952. 'Remote "%(remote)s" for branch "%(branch)s" points to '
  953. '"%(cache_path)s", but it is misconfigured.\n'
  954. '"%(cache_path)s" must be a git repo and must have a remote named '
  955. '"%(remote)s" pointing to the git host.', {
  956. 'remote': remote,
  957. 'cache_path': cache_path,
  958. 'branch': self.GetBranch()})
  959. return None
  960. self._cached_remote_url = (True, url)
  961. return url
  962. def GetIssue(self):
  963. """Returns the issue number as a int or None if not set."""
  964. if self.issue is None and not self.lookedup_issue:
  965. self.issue = self._GitGetBranchConfigValue(ISSUE_CONFIG_KEY)
  966. if self.issue is not None:
  967. self.issue = int(self.issue)
  968. self.lookedup_issue = True
  969. return self.issue
  970. def GetIssueURL(self, short=False):
  971. """Get the URL for a particular issue."""
  972. issue = self.GetIssue()
  973. if not issue:
  974. return None
  975. server = self.GetCodereviewServer()
  976. if short:
  977. server = _KNOWN_GERRIT_TO_SHORT_URLS.get(server, server)
  978. return '%s/%s' % (server, issue)
  979. def FetchDescription(self, pretty=False):
  980. assert self.GetIssue(), 'issue is required to query Gerrit'
  981. if self.description is None:
  982. data = self._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'])
  983. current_rev = data['current_revision']
  984. self.description = data['revisions'][current_rev]['commit']['message']
  985. if not pretty:
  986. return self.description
  987. # Set width to 72 columns + 2 space indent.
  988. wrapper = textwrap.TextWrapper(width=74, replace_whitespace=True)
  989. wrapper.initial_indent = wrapper.subsequent_indent = ' '
  990. lines = self.description.splitlines()
  991. return '\n'.join([wrapper.fill(line) for line in lines])
  992. def GetPatchset(self):
  993. """Returns the patchset number as a int or None if not set."""
  994. if self.patchset is None and not self.lookedup_patchset:
  995. self.patchset = self._GitGetBranchConfigValue(PATCHSET_CONFIG_KEY)
  996. if self.patchset is not None:
  997. self.patchset = int(self.patchset)
  998. self.lookedup_patchset = True
  999. return self.patchset
  1000. def GetAuthor(self):
  1001. return scm.GIT.GetConfig(settings.GetRoot(), 'user.email')
  1002. def SetPatchset(self, patchset):
  1003. """Set this branch's patchset. If patchset=0, clears the patchset."""
  1004. assert self.GetBranch()
  1005. if not patchset:
  1006. self.patchset = None
  1007. else:
  1008. self.patchset = int(patchset)
  1009. self._GitSetBranchConfigValue(PATCHSET_CONFIG_KEY, str(self.patchset))
  1010. def SetIssue(self, issue=None):
  1011. """Set this branch's issue. If issue isn't given, clears the issue."""
  1012. assert self.GetBranch()
  1013. if issue:
  1014. issue = int(issue)
  1015. self._GitSetBranchConfigValue(ISSUE_CONFIG_KEY, str(issue))
  1016. self.issue = issue
  1017. codereview_server = self.GetCodereviewServer()
  1018. if codereview_server:
  1019. self._GitSetBranchConfigValue(
  1020. CODEREVIEW_SERVER_CONFIG_KEY, codereview_server)
  1021. else:
  1022. # Reset all of these just to be clean.
  1023. reset_suffixes = [
  1024. 'last-upload-hash',
  1025. ISSUE_CONFIG_KEY,
  1026. PATCHSET_CONFIG_KEY,
  1027. CODEREVIEW_SERVER_CONFIG_KEY,
  1028. 'gerritsquashhash',
  1029. ]
  1030. for prop in reset_suffixes:
  1031. try:
  1032. self._GitSetBranchConfigValue(prop, None)
  1033. except subprocess2.CalledProcessError:
  1034. pass
  1035. msg = RunGit(['log', '-1', '--format=%B']).strip()
  1036. if msg and git_footers.get_footer_change_id(msg):
  1037. print('WARNING: The change patched into this branch has a Change-Id. '
  1038. 'Removing it.')
  1039. RunGit(['commit', '--amend', '-m',
  1040. git_footers.remove_footer(msg, 'Change-Id')])
  1041. self.lookedup_issue = True
  1042. self.issue = None
  1043. self.patchset = None
  1044. def GetAffectedFiles(self, upstream):
  1045. try:
  1046. return [f for _, f in scm.GIT.CaptureStatus(settings.GetRoot(), upstream)]
  1047. except subprocess2.CalledProcessError:
  1048. DieWithError(
  1049. ('\nFailed to diff against upstream branch %s\n\n'
  1050. 'This branch probably doesn\'t exist anymore. To reset the\n'
  1051. 'tracking branch, please run\n'
  1052. ' git branch --set-upstream-to origin/main %s\n'
  1053. 'or replace origin/main with the relevant branch') %
  1054. (upstream, self.GetBranch()))
  1055. def UpdateDescription(self, description, force=False):
  1056. assert self.GetIssue(), 'issue is required to update description'
  1057. if gerrit_util.HasPendingChangeEdit(
  1058. self.GetGerritHost(), self._GerritChangeIdentifier()):
  1059. if not force:
  1060. confirm_or_exit(
  1061. 'The description cannot be modified while the issue has a pending '
  1062. 'unpublished edit. Either publish the edit in the Gerrit web UI '
  1063. 'or delete it.\n\n', action='delete the unpublished edit')
  1064. gerrit_util.DeletePendingChangeEdit(
  1065. self.GetGerritHost(), self._GerritChangeIdentifier())
  1066. gerrit_util.SetCommitMessage(
  1067. self.GetGerritHost(), self._GerritChangeIdentifier(),
  1068. description, notify='NONE')
  1069. self.description = description
  1070. def _GetCommonPresubmitArgs(self, verbose, upstream):
  1071. args = [
  1072. '--root', settings.GetRoot(),
  1073. '--upstream', upstream,
  1074. ]
  1075. args.extend(['--verbose'] * verbose)
  1076. remote, remote_branch = self.GetRemoteBranch()
  1077. target_ref = GetTargetRef(remote, remote_branch, None)
  1078. args.extend(['--gerrit_url', self.GetCodereviewServer()])
  1079. args.extend(['--gerrit_project', self.GetGerritProject()])
  1080. args.extend(['--gerrit_branch', target_ref])
  1081. author = self.GetAuthor()
  1082. issue = self.GetIssue()
  1083. patchset = self.GetPatchset()
  1084. if author:
  1085. args.extend(['--author', author])
  1086. if issue:
  1087. args.extend(['--issue', str(issue)])
  1088. if patchset:
  1089. args.extend(['--patchset', str(patchset)])
  1090. return args
  1091. def RunHook(self, committing, may_prompt, verbose, parallel, upstream,
  1092. description, all_files, resultdb=False, realm=None):
  1093. """Calls sys.exit() if the hook fails; returns a HookResults otherwise."""
  1094. args = self._GetCommonPresubmitArgs(verbose, upstream)
  1095. args.append('--commit' if committing else '--upload')
  1096. if may_prompt:
  1097. args.append('--may_prompt')
  1098. if parallel:
  1099. args.append('--parallel')
  1100. if all_files:
  1101. args.append('--all_files')
  1102. with gclient_utils.temporary_file() as description_file:
  1103. with gclient_utils.temporary_file() as json_output:
  1104. gclient_utils.FileWrite(description_file, description)
  1105. args.extend(['--json_output', json_output])
  1106. args.extend(['--description_file', description_file])
  1107. start = time_time()
  1108. cmd = ['vpython', PRESUBMIT_SUPPORT] + args
  1109. if resultdb and realm:
  1110. cmd = ['rdb', 'stream', '-new', '-realm', realm, '--'] + cmd
  1111. elif resultdb:
  1112. # TODO (crbug.com/1113463): store realm somewhere and look it up so
  1113. # it is not required to pass the realm flag
  1114. print('Note: ResultDB reporting will NOT be performed because --realm'
  1115. ' was not specified. To enable ResultDB, please run the command'
  1116. ' again with the --realm argument to specify the LUCI realm.')
  1117. p = subprocess2.Popen(cmd)
  1118. exit_code = p.wait()
  1119. metrics.collector.add_repeated('sub_commands', {
  1120. 'command': 'presubmit',
  1121. 'execution_time': time_time() - start,
  1122. 'exit_code': exit_code,
  1123. })
  1124. if exit_code:
  1125. sys.exit(exit_code)
  1126. json_results = gclient_utils.FileRead(json_output)
  1127. return json.loads(json_results)
  1128. def RunPostUploadHook(self, verbose, upstream, description):
  1129. args = self._GetCommonPresubmitArgs(verbose, upstream)
  1130. args.append('--post_upload')
  1131. with gclient_utils.temporary_file() as description_file:
  1132. gclient_utils.FileWrite(description_file, description)
  1133. args.extend(['--description_file', description_file])
  1134. p = subprocess2.Popen(['vpython', PRESUBMIT_SUPPORT] + args)
  1135. p.wait()
  1136. def _GetDescriptionForUpload(self, options, git_diff_args, files):
  1137. # Get description message for upload.
  1138. if self.GetIssue():
  1139. description = self.FetchDescription()
  1140. elif options.message:
  1141. description = options.message
  1142. else:
  1143. description = _create_description_from_log(git_diff_args)
  1144. if options.title and options.squash:
  1145. description = options.title + '\n\n' + description
  1146. # Extract bug number from branch name.
  1147. bug = options.bug
  1148. fixed = options.fixed
  1149. match = re.match(r'(?P<type>bug|fix(?:e[sd])?)[_-]?(?P<bugnum>\d+)',
  1150. self.GetBranch())
  1151. if not bug and not fixed and match:
  1152. if match.group('type') == 'bug':
  1153. bug = match.group('bugnum')
  1154. else:
  1155. fixed = match.group('bugnum')
  1156. change_description = ChangeDescription(description, bug, fixed)
  1157. # Fill gaps in OWNERS coverage to tbrs/reviewers if requested.
  1158. if options.add_owners_to:
  1159. assert options.add_owners_to in ('TBR', 'R'), options.add_owners_to
  1160. status = self.owners_client.GetFilesApprovalStatus(
  1161. files, [], options.tbrs + options.reviewers)
  1162. missing_files = [
  1163. f for f in files
  1164. if status[f] == self._owners_client.INSUFFICIENT_REVIEWERS
  1165. ]
  1166. owners = self.owners_client.SuggestOwners(
  1167. missing_files, exclude=[self.GetAuthor()])
  1168. if options.add_owners_to == 'TBR':
  1169. assert isinstance(options.tbrs, list), options.tbrs
  1170. options.tbrs.extend(owners)
  1171. else:
  1172. assert isinstance(options.reviewers, list), options.reviewers
  1173. options.reviewers.extend(owners)
  1174. # Set the reviewer list now so that presubmit checks can access it.
  1175. if options.reviewers or options.tbrs:
  1176. change_description.update_reviewers(options.reviewers, options.tbrs)
  1177. return change_description
  1178. def _GetTitleForUpload(self, options):
  1179. # When not squashing, just return options.title.
  1180. if not options.squash:
  1181. return options.title
  1182. # On first upload, patchset title is always this string, while options.title
  1183. # gets converted to first line of message.
  1184. if not self.GetIssue():
  1185. return 'Initial upload'
  1186. # When uploading subsequent patchsets, options.message is taken as the title
  1187. # if options.title is not provided.
  1188. if options.title:
  1189. return options.title
  1190. if options.message:
  1191. return options.message.strip()
  1192. # Use the subject of the last commit as title by default.
  1193. title = RunGit(['show', '-s', '--format=%s', 'HEAD']).strip()
  1194. if options.force or options.skip_title:
  1195. return title
  1196. user_title = gclient_utils.AskForData('Title for patchset [%s]: ' % title)
  1197. return user_title or title
  1198. def CMDUpload(self, options, git_diff_args, orig_args):
  1199. """Uploads a change to codereview."""
  1200. custom_cl_base = None
  1201. if git_diff_args:
  1202. custom_cl_base = base_branch = git_diff_args[0]
  1203. else:
  1204. if self.GetBranch() is None:
  1205. DieWithError('Can\'t upload from detached HEAD state. Get on a branch!')
  1206. # Default to diffing against common ancestor of upstream branch
  1207. base_branch = self.GetCommonAncestorWithUpstream()
  1208. git_diff_args = [base_branch, 'HEAD']
  1209. # Fast best-effort checks to abort before running potentially expensive
  1210. # hooks if uploading is likely to fail anyway. Passing these checks does
  1211. # not guarantee that uploading will not fail.
  1212. self.EnsureAuthenticated(force=options.force)
  1213. self.EnsureCanUploadPatchset(force=options.force)
  1214. # Apply watchlists on upload.
  1215. watchlist = watchlists.Watchlists(settings.GetRoot())
  1216. files = self.GetAffectedFiles(base_branch)
  1217. if not options.bypass_watchlists:
  1218. self.ExtendCC(watchlist.GetWatchersForPaths(files))
  1219. change_desc = self._GetDescriptionForUpload(options, git_diff_args, files)
  1220. if not options.bypass_hooks:
  1221. hook_results = self.RunHook(
  1222. committing=False,
  1223. may_prompt=not options.force,
  1224. verbose=options.verbose,
  1225. parallel=options.parallel,
  1226. upstream=base_branch,
  1227. description=change_desc.description,
  1228. all_files=False,
  1229. resultdb=options.resultdb,
  1230. realm=options.realm)
  1231. self.ExtendCC(hook_results['more_cc'])
  1232. print_stats(git_diff_args)
  1233. ret = self.CMDUploadChange(
  1234. options, git_diff_args, custom_cl_base, change_desc)
  1235. if not ret:
  1236. self._GitSetBranchConfigValue(
  1237. 'last-upload-hash', scm.GIT.ResolveCommit(settings.GetRoot(), 'HEAD'))
  1238. # Run post upload hooks, if specified.
  1239. if settings.GetRunPostUploadHook():
  1240. self.RunPostUploadHook(
  1241. options.verbose, base_branch, change_desc.description)
  1242. # Upload all dependencies if specified.
  1243. if options.dependencies:
  1244. print()
  1245. print('--dependencies has been specified.')
  1246. print('All dependent local branches will be re-uploaded.')
  1247. print()
  1248. # Remove the dependencies flag from args so that we do not end up in a
  1249. # loop.
  1250. orig_args.remove('--dependencies')
  1251. ret = upload_branch_deps(self, orig_args, options.force)
  1252. return ret
  1253. def SetCQState(self, new_state):
  1254. """Updates the CQ state for the latest patchset.
  1255. Issue must have been already uploaded and known.
  1256. """
  1257. assert new_state in _CQState.ALL_STATES
  1258. assert self.GetIssue()
  1259. try:
  1260. vote_map = {
  1261. _CQState.NONE: 0,
  1262. _CQState.DRY_RUN: 1,
  1263. _CQState.COMMIT: 2,
  1264. }
  1265. labels = {'Commit-Queue': vote_map[new_state]}
  1266. notify = False if new_state == _CQState.DRY_RUN else None
  1267. gerrit_util.SetReview(
  1268. self.GetGerritHost(), self._GerritChangeIdentifier(),
  1269. labels=labels, notify=notify)
  1270. return 0
  1271. except KeyboardInterrupt:
  1272. raise
  1273. except:
  1274. print('WARNING: Failed to %s.\n'
  1275. 'Either:\n'
  1276. ' * Your project has no CQ,\n'
  1277. ' * You don\'t have permission to change the CQ state,\n'
  1278. ' * There\'s a bug in this code (see stack trace below).\n'
  1279. 'Consider specifying which bots to trigger manually or asking your '
  1280. 'project owners for permissions or contacting Chrome Infra at:\n'
  1281. 'https://www.chromium.org/infra\n\n' %
  1282. ('cancel CQ' if new_state == _CQState.NONE else 'trigger CQ'))
  1283. # Still raise exception so that stack trace is printed.
  1284. raise
  1285. def GetGerritHost(self):
  1286. # Lazy load of configs.
  1287. self.GetCodereviewServer()
  1288. if self._gerrit_host and '.' not in self._gerrit_host:
  1289. # Abbreviated domain like "chromium" instead of chromium.googlesource.com.
  1290. # This happens for internal stuff http://crbug.com/614312.
  1291. parsed = urllib.parse.urlparse(self.GetRemoteUrl())
  1292. if parsed.scheme == 'sso':
  1293. print('WARNING: using non-https URLs for remote is likely broken\n'
  1294. ' Your current remote is: %s' % self.GetRemoteUrl())
  1295. self._gerrit_host = '%s.googlesource.com' % self._gerrit_host
  1296. self._gerrit_server = 'https://%s' % self._gerrit_host
  1297. return self._gerrit_host
  1298. def _GetGitHost(self):
  1299. """Returns git host to be used when uploading change to Gerrit."""
  1300. remote_url = self.GetRemoteUrl()
  1301. if not remote_url:
  1302. return None
  1303. return urllib.parse.urlparse(remote_url).netloc
  1304. def GetCodereviewServer(self):
  1305. if not self._gerrit_server:
  1306. # If we're on a branch then get the server potentially associated
  1307. # with that branch.
  1308. if self.GetIssue() and self.GetBranch():
  1309. self._gerrit_server = self._GitGetBranchConfigValue(
  1310. CODEREVIEW_SERVER_CONFIG_KEY)
  1311. if self._gerrit_server:
  1312. self._gerrit_host = urllib.parse.urlparse(self._gerrit_server).netloc
  1313. if not self._gerrit_server:
  1314. # We assume repo to be hosted on Gerrit, and hence Gerrit server
  1315. # has "-review" suffix for lowest level subdomain.
  1316. parts = self._GetGitHost().split('.')
  1317. parts[0] = parts[0] + '-review'
  1318. self._gerrit_host = '.'.join(parts)
  1319. self._gerrit_server = 'https://%s' % self._gerrit_host
  1320. return self._gerrit_server
  1321. def GetGerritProject(self):
  1322. """Returns Gerrit project name based on remote git URL."""
  1323. remote_url = self.GetRemoteUrl()
  1324. if remote_url is None:
  1325. logging.warning('can\'t detect Gerrit project.')
  1326. return None
  1327. project = urllib.parse.urlparse(remote_url).path.strip('/')
  1328. if project.endswith('.git'):
  1329. project = project[:-len('.git')]
  1330. # *.googlesource.com hosts ensure that Git/Gerrit projects don't start with
  1331. # 'a/' prefix, because 'a/' prefix is used to force authentication in
  1332. # gitiles/git-over-https protocol. E.g.,
  1333. # https://chromium.googlesource.com/a/v8/v8 refers to the same repo/project
  1334. # as
  1335. # https://chromium.googlesource.com/v8/v8
  1336. if project.startswith('a/'):
  1337. project = project[len('a/'):]
  1338. return project
  1339. def _GerritChangeIdentifier(self):
  1340. """Handy method for gerrit_util.ChangeIdentifier for a given CL.
  1341. Not to be confused by value of "Change-Id:" footer.
  1342. If Gerrit project can be determined, this will speed up Gerrit HTTP API RPC.
  1343. """
  1344. project = self.GetGerritProject()
  1345. if project:
  1346. return gerrit_util.ChangeIdentifier(project, self.GetIssue())
  1347. # Fall back on still unique, but less efficient change number.
  1348. return str(self.GetIssue())
  1349. def EnsureAuthenticated(self, force, refresh=None):
  1350. """Best effort check that user is authenticated with Gerrit server."""
  1351. if settings.GetGerritSkipEnsureAuthenticated():
  1352. # For projects with unusual authentication schemes.
  1353. # See http://crbug.com/603378.
  1354. return
  1355. # Check presence of cookies only if using cookies-based auth method.
  1356. cookie_auth = gerrit_util.Authenticator.get()
  1357. if not isinstance(cookie_auth, gerrit_util.CookiesAuthenticator):
  1358. return
  1359. remote_url = self.GetRemoteUrl()
  1360. if remote_url is None:
  1361. logging.warning('invalid remote')
  1362. return
  1363. if urllib.parse.urlparse(remote_url).scheme != 'https':
  1364. logging.warning('Ignoring branch %(branch)s with non-https remote '
  1365. '%(remote)s', {
  1366. 'branch': self.branch,
  1367. 'remote': self.GetRemoteUrl()
  1368. })
  1369. return
  1370. # Lazy-loader to identify Gerrit and Git hosts.
  1371. self.GetCodereviewServer()
  1372. git_host = self._GetGitHost()
  1373. assert self._gerrit_server and self._gerrit_host and git_host
  1374. gerrit_auth = cookie_auth.get_auth_header(self._gerrit_host)
  1375. git_auth = cookie_auth.get_auth_header(git_host)
  1376. if gerrit_auth and git_auth:
  1377. if gerrit_auth == git_auth:
  1378. return
  1379. all_gsrc = cookie_auth.get_auth_header('d0esN0tEx1st.googlesource.com')
  1380. print(
  1381. 'WARNING: You have different credentials for Gerrit and git hosts:\n'
  1382. ' %s\n'
  1383. ' %s\n'
  1384. ' Consider running the following command:\n'
  1385. ' git cl creds-check\n'
  1386. ' %s\n'
  1387. ' %s' %
  1388. (git_host, self._gerrit_host,
  1389. ('Hint: delete creds for .googlesource.com' if all_gsrc else ''),
  1390. cookie_auth.get_new_password_message(git_host)))
  1391. if not force:
  1392. confirm_or_exit('If you know what you are doing', action='continue')
  1393. return
  1394. else:
  1395. missing = (
  1396. ([] if gerrit_auth else [self._gerrit_host]) +
  1397. ([] if git_auth else [git_host]))
  1398. DieWithError('Credentials for the following hosts are required:\n'
  1399. ' %s\n'
  1400. 'These are read from %s (or legacy %s)\n'
  1401. '%s' % (
  1402. '\n '.join(missing),
  1403. cookie_auth.get_gitcookies_path(),
  1404. cookie_auth.get_netrc_path(),
  1405. cookie_auth.get_new_password_message(git_host)))
  1406. def EnsureCanUploadPatchset(self, force):
  1407. if not self.GetIssue():
  1408. return
  1409. status = self._GetChangeDetail()['status']
  1410. if status in ('MERGED', 'ABANDONED'):
  1411. DieWithError('Change %s has been %s, new uploads are not allowed' %
  1412. (self.GetIssueURL(),
  1413. 'submitted' if status == 'MERGED' else 'abandoned'))
  1414. # TODO(vadimsh): For some reason the chunk of code below was skipped if
  1415. # 'is_gce' is True. I'm just refactoring it to be 'skip if not cookies'.
  1416. # Apparently this check is not very important? Otherwise get_auth_email
  1417. # could have been added to other implementations of Authenticator.
  1418. cookies_auth = gerrit_util.Authenticator.get()
  1419. if not isinstance(cookies_auth, gerrit_util.CookiesAuthenticator):
  1420. return
  1421. cookies_user = cookies_auth.get_auth_email(self.GetGerritHost())
  1422. if self.GetIssueOwner() == cookies_user:
  1423. return
  1424. logging.debug('change %s owner is %s, cookies user is %s',
  1425. self.GetIssue(), self.GetIssueOwner(), cookies_user)
  1426. # Maybe user has linked accounts or something like that,
  1427. # so ask what Gerrit thinks of this user.
  1428. details = gerrit_util.GetAccountDetails(self.GetGerritHost(), 'self')
  1429. if details['email'] == self.GetIssueOwner():
  1430. return
  1431. if not force:
  1432. print('WARNING: Change %s is owned by %s, but you authenticate to Gerrit '
  1433. 'as %s.\n'
  1434. 'Uploading may fail due to lack of permissions.' %
  1435. (self.GetIssue(), self.GetIssueOwner(), details['email']))
  1436. confirm_or_exit(action='upload')
  1437. def GetStatus(self):
  1438. """Applies a rough heuristic to give a simple summary of an issue's review
  1439. or CQ status, assuming adherence to a common workflow.
  1440. Returns None if no issue for this branch, or one of the following keywords:
  1441. * 'error' - error from review tool (including deleted issues)
  1442. * 'unsent' - no reviewers added
  1443. * 'waiting' - waiting for review
  1444. * 'reply' - waiting for uploader to reply to review
  1445. * 'lgtm' - Code-Review label has been set
  1446. * 'dry-run' - dry-running in the CQ
  1447. * 'commit' - in the CQ
  1448. * 'closed' - successfully submitted or abandoned
  1449. """
  1450. if not self.GetIssue():
  1451. return None
  1452. try:
  1453. data = self._GetChangeDetail([
  1454. 'DETAILED_LABELS', 'CURRENT_REVISION', 'SUBMITTABLE'])
  1455. except GerritChangeNotExists:
  1456. return 'error'
  1457. if data['status'] in ('ABANDONED', 'MERGED'):
  1458. return 'closed'
  1459. cq_label = data['labels'].get('Commit-Queue', {})
  1460. max_cq_vote = 0
  1461. for vote in cq_label.get('all', []):
  1462. max_cq_vote = max(max_cq_vote, vote.get('value', 0))
  1463. if max_cq_vote == 2:
  1464. return 'commit'
  1465. if max_cq_vote == 1:
  1466. return 'dry-run'
  1467. if data['labels'].get('Code-Review', {}).get('approved'):
  1468. return 'lgtm'
  1469. if not data.get('reviewers', {}).get('REVIEWER', []):
  1470. return 'unsent'
  1471. owner = data['owner'].get('_account_id')
  1472. messages = sorted(data.get('messages', []), key=lambda m: m.get('date'))
  1473. while messages:
  1474. m = messages.pop()
  1475. if m.get('tag', '').startswith('autogenerated:cq:'):
  1476. # Ignore replies from CQ.
  1477. continue
  1478. if m.get('author', {}).get('_account_id') == owner:
  1479. # Most recent message was by owner.
  1480. return 'waiting'
  1481. else:
  1482. # Some reply from non-owner.
  1483. return 'reply'
  1484. # Somehow there are no messages even though there are reviewers.
  1485. return 'unsent'
  1486. def GetMostRecentPatchset(self):
  1487. if not self.GetIssue():
  1488. return None
  1489. data = self._GetChangeDetail(['CURRENT_REVISION'])
  1490. patchset = data['revisions'][data['current_revision']]['_number']
  1491. self.SetPatchset(patchset)
  1492. return patchset
  1493. def GetMostRecentDryRunPatchset(self):
  1494. """Get patchsets equivalent to the most recent patchset and return
  1495. the patchset with the latest dry run. If none have been dry run, return
  1496. the latest patchset."""
  1497. if not self.GetIssue():
  1498. return None
  1499. data = self._GetChangeDetail(['ALL_REVISIONS'])
  1500. patchset = data['revisions'][data['current_revision']]['_number']
  1501. dry_run = set([int(m['_revision_number'])
  1502. for m in data.get('messages', [])
  1503. if m.get('tag', '').endswith('dry-run')])
  1504. for revision_info in sorted(data.get('revisions', {}).values(),
  1505. key=lambda c: c['_number'], reverse=True):
  1506. if revision_info['_number'] in dry_run:
  1507. patchset = revision_info['_number']
  1508. break
  1509. if revision_info.get('kind', '') not in \
  1510. ('NO_CHANGE', 'NO_CODE_CHANGE', 'TRIVIAL_REBASE'):
  1511. break
  1512. self.SetPatchset(patchset)
  1513. return patchset
  1514. def AddComment(self, message, publish=None):
  1515. gerrit_util.SetReview(
  1516. self.GetGerritHost(), self._GerritChangeIdentifier(),
  1517. msg=message, ready=publish)
  1518. def GetCommentsSummary(self, readable=True):
  1519. # DETAILED_ACCOUNTS is to get emails in accounts.
  1520. # CURRENT_REVISION is included to get the latest patchset so that
  1521. # only the robot comments from the latest patchset can be shown.
  1522. messages = self._GetChangeDetail(
  1523. options=['MESSAGES', 'DETAILED_ACCOUNTS',
  1524. 'CURRENT_REVISION']).get('messages', [])
  1525. file_comments = gerrit_util.GetChangeComments(
  1526. self.GetGerritHost(), self._GerritChangeIdentifier())
  1527. robot_file_comments = gerrit_util.GetChangeRobotComments(
  1528. self.GetGerritHost(), self._GerritChangeIdentifier())
  1529. # Add the robot comments onto the list of comments, but only
  1530. # keep those that are from the latest patchset.
  1531. latest_patch_set = self.GetMostRecentPatchset()
  1532. for path, robot_comments in robot_file_comments.items():
  1533. line_comments = file_comments.setdefault(path, [])
  1534. line_comments.extend(
  1535. [c for c in robot_comments if c['patch_set'] == latest_patch_set])
  1536. # Build dictionary of file comments for easy access and sorting later.
  1537. # {author+date: {path: {patchset: {line: url+message}}}}
  1538. comments = collections.defaultdict(
  1539. lambda: collections.defaultdict(lambda: collections.defaultdict(dict)))
  1540. server = self.GetCodereviewServer()
  1541. if server in _KNOWN_GERRIT_TO_SHORT_URLS:
  1542. # /c/ is automatically added by short URL server.
  1543. url_prefix = '%s/%s' % (_KNOWN_GERRIT_TO_SHORT_URLS[server],
  1544. self.GetIssue())
  1545. else:
  1546. url_prefix = '%s/c/%s' % (server, self.GetIssue())
  1547. for path, line_comments in file_comments.items():
  1548. for comment in line_comments:
  1549. tag = comment.get('tag', '')
  1550. if tag.startswith('autogenerated') and 'robot_id' not in comment:
  1551. continue
  1552. key = (comment['author']['email'], comment['updated'])
  1553. if comment.get('side', 'REVISION') == 'PARENT':
  1554. patchset = 'Base'
  1555. else:
  1556. patchset = 'PS%d' % comment['patch_set']
  1557. line = comment.get('line', 0)
  1558. url = ('%s/%s/%s#%s%s' %
  1559. (url_prefix, comment['patch_set'], path,
  1560. 'b' if comment.get('side') == 'PARENT' else '',
  1561. str(line) if line else ''))
  1562. comments[key][path][patchset][line] = (url, comment['message'])
  1563. summaries = []
  1564. for msg in messages:
  1565. summary = self._BuildCommentSummary(msg, comments, readable)
  1566. if summary:
  1567. summaries.append(summary)
  1568. return summaries
  1569. @staticmethod
  1570. def _BuildCommentSummary(msg, comments, readable):
  1571. key = (msg['author']['email'], msg['date'])
  1572. # Don't bother showing autogenerated messages that don't have associated
  1573. # file or line comments. this will filter out most autogenerated
  1574. # messages, but will keep robot comments like those from Tricium.
  1575. is_autogenerated = msg.get('tag', '').startswith('autogenerated')
  1576. if is_autogenerated and not comments.get(key):
  1577. return None
  1578. message = msg['message']
  1579. # Gerrit spits out nanoseconds.
  1580. assert len(msg['date'].split('.')[-1]) == 9
  1581. date = datetime.datetime.strptime(msg['date'][:-3],
  1582. '%Y-%m-%d %H:%M:%S.%f')
  1583. if key in comments:
  1584. message += '\n'
  1585. for path, patchsets in sorted(comments.get(key, {}).items()):
  1586. if readable:
  1587. message += '\n%s' % path
  1588. for patchset, lines in sorted(patchsets.items()):
  1589. for line, (url, content) in sorted(lines.items()):
  1590. if line:
  1591. line_str = 'Line %d' % line
  1592. path_str = '%s:%d:' % (path, line)
  1593. else:
  1594. line_str = 'File comment'
  1595. path_str = '%s:0:' % path
  1596. if readable:
  1597. message += '\n %s, %s: %s' % (patchset, line_str, url)
  1598. message += '\n %s\n' % content
  1599. else:
  1600. message += '\n%s ' % path_str
  1601. message += '\n%s\n' % content
  1602. return _CommentSummary(
  1603. date=date,
  1604. message=message,
  1605. sender=msg['author']['email'],
  1606. autogenerated=is_autogenerated,
  1607. # These could be inferred from the text messages and correlated with
  1608. # Code-Review label maximum, however this is not reliable.
  1609. # Leaving as is until the need arises.
  1610. approval=False,
  1611. disapproval=False,
  1612. )
  1613. def CloseIssue(self):
  1614. gerrit_util.AbandonChange(
  1615. self.GetGerritHost(), self._GerritChangeIdentifier(), msg='')
  1616. def SubmitIssue(self, wait_for_merge=True):
  1617. gerrit_util.SubmitChange(
  1618. self.GetGerritHost(), self._GerritChangeIdentifier(),
  1619. wait_for_merge=wait_for_merge)
  1620. def _GetChangeDetail(self, options=None):
  1621. """Returns details of associated Gerrit change and caching results."""
  1622. options = options or []
  1623. assert self.GetIssue(), 'issue is required to query Gerrit'
  1624. # Optimization to avoid multiple RPCs:
  1625. if 'CURRENT_REVISION' in options or 'ALL_REVISIONS' in options:
  1626. options.append('CURRENT_COMMIT')
  1627. # Normalize issue and options for consistent keys in cache.
  1628. cache_key = str(self.GetIssue())
  1629. options_set = frozenset(o.upper() for o in options)
  1630. for cached_options_set, data in self._detail_cache.get(cache_key, []):
  1631. # Assumption: data fetched before with extra options is suitable
  1632. # for return for a smaller set of options.
  1633. # For example, if we cached data for
  1634. # options=[CURRENT_REVISION, DETAILED_FOOTERS]
  1635. # and request is for options=[CURRENT_REVISION],
  1636. # THEN we can return prior cached data.
  1637. if options_set.issubset(cached_options_set):
  1638. return data
  1639. try:
  1640. data = gerrit_util.GetChangeDetail(
  1641. self.GetGerritHost(), self._GerritChangeIdentifier(), options_set)
  1642. except gerrit_util.GerritError as e:
  1643. if e.http_status == 404:
  1644. raise GerritChangeNotExists(self.GetIssue(), self.GetCodereviewServer())
  1645. raise
  1646. self._detail_cache.setdefault(cache_key, []).append((options_set, data))
  1647. return data
  1648. def _GetChangeCommit(self):
  1649. assert self.GetIssue(), 'issue must be set to query Gerrit'
  1650. try:
  1651. data = gerrit_util.GetChangeCommit(
  1652. self.GetGerritHost(), self._GerritChangeIdentifier())
  1653. except gerrit_util.GerritError as e:
  1654. if e.http_status == 404:
  1655. raise GerritChangeNotExists(self.GetIssue(), self.GetCodereviewServer())
  1656. raise
  1657. return data
  1658. def _IsCqConfigured(self):
  1659. detail = self._GetChangeDetail(['LABELS'])
  1660. return u'Commit-Queue' in detail.get('labels', {})
  1661. def CMDLand(self, force, bypass_hooks, verbose, parallel, resultdb, realm):
  1662. if git_common.is_dirty_git_tree('land'):
  1663. return 1
  1664. detail = self._GetChangeDetail(['CURRENT_REVISION', 'LABELS'])
  1665. if not force and self._IsCqConfigured():
  1666. confirm_or_exit('\nIt seems this repository has a CQ, '
  1667. 'which can test and land changes for you. '
  1668. 'Are you sure you wish to bypass it?\n',
  1669. action='bypass CQ')
  1670. differs = True
  1671. last_upload = self._GitGetBranchConfigValue('gerritsquashhash')
  1672. # Note: git diff outputs nothing if there is no diff.
  1673. if not last_upload or RunGit(['diff', last_upload]).strip():
  1674. print('WARNING: Some changes from local branch haven\'t been uploaded.')
  1675. else:
  1676. if detail['current_revision'] == last_upload:
  1677. differs = False
  1678. else:
  1679. print('WARNING: Local branch contents differ from latest uploaded '
  1680. 'patchset.')
  1681. if differs:
  1682. if not force:
  1683. confirm_or_exit(
  1684. 'Do you want to submit latest Gerrit patchset and bypass hooks?\n',
  1685. action='submit')
  1686. print('WARNING: Bypassing hooks and submitting latest uploaded patchset.')
  1687. elif not bypass_hooks:
  1688. upstream = self.GetCommonAncestorWithUpstream()
  1689. if self.GetIssue():
  1690. description = self.FetchDescription()
  1691. else:
  1692. description = _create_description_from_log([upstream])
  1693. self.RunHook(
  1694. committing=True,
  1695. may_prompt=not force,
  1696. verbose=verbose,
  1697. parallel=parallel,
  1698. upstream=upstream,
  1699. description=description,
  1700. all_files=False,
  1701. resultdb=resultdb,
  1702. realm=realm)
  1703. self.SubmitIssue(wait_for_merge=True)
  1704. print('Issue %s has been submitted.' % self.GetIssueURL())
  1705. links = self._GetChangeCommit().get('web_links', [])
  1706. for link in links:
  1707. if link.get('name') == 'gitiles' and link.get('url'):
  1708. print('Landed as: %s' % link.get('url'))
  1709. break
  1710. return 0
  1711. def CMDPatchWithParsedIssue(self, parsed_issue_arg, nocommit, force,
  1712. newbranch):
  1713. assert parsed_issue_arg.valid
  1714. self.issue = parsed_issue_arg.issue
  1715. if parsed_issue_arg.hostname:
  1716. self._gerrit_host = parsed_issue_arg.hostname
  1717. self._gerrit_server = 'https://%s' % self._gerrit_host
  1718. try:
  1719. detail = self._GetChangeDetail(['ALL_REVISIONS'])
  1720. except GerritChangeNotExists as e:
  1721. DieWithError(str(e))
  1722. if not parsed_issue_arg.patchset:
  1723. # Use current revision by default.
  1724. revision_info = detail['revisions'][detail['current_revision']]
  1725. patchset = int(revision_info['_number'])
  1726. else:
  1727. patchset = parsed_issue_arg.patchset
  1728. for revision_info in detail['revisions'].values():
  1729. if int(revision_info['_number']) == parsed_issue_arg.patchset:
  1730. break
  1731. else:
  1732. DieWithError('Couldn\'t find patchset %i in change %i' %
  1733. (parsed_issue_arg.patchset, self.GetIssue()))
  1734. remote_url = self.GetRemoteUrl()
  1735. if remote_url.endswith('.git'):
  1736. remote_url = remote_url[:-len('.git')]
  1737. remote_url = remote_url.rstrip('/')
  1738. fetch_info = revision_info['fetch']['http']
  1739. fetch_info['url'] = fetch_info['url'].rstrip('/')
  1740. if remote_url != fetch_info['url']:
  1741. DieWithError('Trying to patch a change from %s but this repo appears '
  1742. 'to be %s.' % (fetch_info['url'], remote_url))
  1743. RunGit(['fetch', fetch_info['url'], fetch_info['ref']])
  1744. # If we have created a new branch then do the "set issue" immediately in
  1745. # case the cherry-pick fails, which happens when resolving conflicts.
  1746. if newbranch:
  1747. self.SetIssue(parsed_issue_arg.issue)
  1748. if force:
  1749. RunGit(['reset', '--hard', 'FETCH_HEAD'])
  1750. print('Checked out commit for change %i patchset %i locally' %
  1751. (parsed_issue_arg.issue, patchset))
  1752. elif nocommit:
  1753. RunGit(['cherry-pick', '--no-commit', 'FETCH_HEAD'])
  1754. print('Patch applied to index.')
  1755. else:
  1756. RunGit(['cherry-pick', 'FETCH_HEAD'])
  1757. print('Committed patch for change %i patchset %i locally.' %
  1758. (parsed_issue_arg.issue, patchset))
  1759. print('Note: this created a local commit which does not have '
  1760. 'the same hash as the one uploaded for review. This will make '
  1761. 'uploading changes based on top of this branch difficult.\n'
  1762. 'If you want to do that, use "git cl patch --force" instead.')
  1763. if self.GetBranch():
  1764. self.SetIssue(parsed_issue_arg.issue)
  1765. self.SetPatchset(patchset)
  1766. fetched_hash = scm.GIT.ResolveCommit(settings.GetRoot(), 'FETCH_HEAD')
  1767. self._GitSetBranchConfigValue('last-upload-hash', fetched_hash)
  1768. self._GitSetBranchConfigValue('gerritsquashhash', fetched_hash)
  1769. else:
  1770. print('WARNING: You are in detached HEAD state.\n'
  1771. 'The patch has been applied to your checkout, but you will not be '
  1772. 'able to upload a new patch set to the gerrit issue.\n'
  1773. 'Try using the \'-b\' option if you would like to work on a '
  1774. 'branch and/or upload a new patch set.')
  1775. return 0
  1776. def _GerritCommitMsgHookCheck(self, offer_removal):
  1777. hook = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
  1778. if not os.path.exists(hook):
  1779. return
  1780. # Crude attempt to distinguish Gerrit Codereview hook from a potentially
  1781. # custom developer-made one.
  1782. data = gclient_utils.FileRead(hook)
  1783. if not('From Gerrit Code Review' in data and 'add_ChangeId()' in data):
  1784. return
  1785. print('WARNING: You have Gerrit commit-msg hook installed.\n'
  1786. 'It is not necessary for uploading with git cl in squash mode, '
  1787. 'and may interfere with it in subtle ways.\n'
  1788. 'We recommend you remove the commit-msg hook.')
  1789. if offer_removal:
  1790. if ask_for_explicit_yes('Do you want to remove it now?'):
  1791. gclient_utils.rm_file_or_tree(hook)
  1792. print('Gerrit commit-msg hook removed.')
  1793. else:
  1794. print('OK, will keep Gerrit commit-msg hook in place.')
  1795. def _CleanUpOldTraces(self):
  1796. """Keep only the last |MAX_TRACES| traces."""
  1797. try:
  1798. traces = sorted([
  1799. os.path.join(TRACES_DIR, f)
  1800. for f in os.listdir(TRACES_DIR)
  1801. if (os.path.isfile(os.path.join(TRACES_DIR, f))
  1802. and not f.startswith('tmp'))
  1803. ])
  1804. traces_to_delete = traces[:-MAX_TRACES]
  1805. for trace in traces_to_delete:
  1806. os.remove(trace)
  1807. except OSError:
  1808. print('WARNING: Failed to remove old git traces from\n'
  1809. ' %s'
  1810. 'Consider removing them manually.' % TRACES_DIR)
  1811. def _WriteGitPushTraces(self, trace_name, traces_dir, git_push_metadata):
  1812. """Zip and write the git push traces stored in traces_dir."""
  1813. gclient_utils.safe_makedirs(TRACES_DIR)
  1814. traces_zip = trace_name + '-traces'
  1815. traces_readme = trace_name + '-README'
  1816. # Create a temporary dir to store git config and gitcookies in. It will be
  1817. # compressed and stored next to the traces.
  1818. git_info_dir = tempfile.mkdtemp()
  1819. git_info_zip = trace_name + '-git-info'
  1820. git_push_metadata['now'] = datetime_now().strftime('%Y-%m-%dT%H:%M:%S.%f')
  1821. git_push_metadata['trace_name'] = trace_name
  1822. gclient_utils.FileWrite(
  1823. traces_readme, TRACES_README_FORMAT % git_push_metadata)
  1824. # Keep only the first 6 characters of the git hashes on the packet
  1825. # trace. This greatly decreases size after compression.
  1826. packet_traces = os.path.join(traces_dir, 'trace-packet')
  1827. if os.path.isfile(packet_traces):
  1828. contents = gclient_utils.FileRead(packet_traces)
  1829. gclient_utils.FileWrite(
  1830. packet_traces, GIT_HASH_RE.sub(r'\1', contents))
  1831. shutil.make_archive(traces_zip, 'zip', traces_dir)
  1832. # Collect and compress the git config and gitcookies.
  1833. git_config = RunGit(['config', '-l'])
  1834. gclient_utils.FileWrite(
  1835. os.path.join(git_info_dir, 'git-config'),
  1836. git_config)
  1837. cookie_auth = gerrit_util.Authenticator.get()
  1838. if isinstance(cookie_auth, gerrit_util.CookiesAuthenticator):
  1839. gitcookies_path = cookie_auth.get_gitcookies_path()
  1840. if os.path.isfile(gitcookies_path):
  1841. gitcookies = gclient_utils.FileRead(gitcookies_path)
  1842. gclient_utils.FileWrite(
  1843. os.path.join(git_info_dir, 'gitcookies'),
  1844. GITCOOKIES_REDACT_RE.sub('REDACTED', gitcookies))
  1845. shutil.make_archive(git_info_zip, 'zip', git_info_dir)
  1846. gclient_utils.rmtree(git_info_dir)
  1847. def _RunGitPushWithTraces(self,
  1848. refspec,
  1849. refspec_opts,
  1850. git_push_metadata,
  1851. git_push_options=None):
  1852. """Run git push and collect the traces resulting from the execution."""
  1853. # Create a temporary directory to store traces in. Traces will be compressed
  1854. # and stored in a 'traces' dir inside depot_tools.
  1855. traces_dir = tempfile.mkdtemp()
  1856. trace_name = os.path.join(
  1857. TRACES_DIR, datetime_now().strftime('%Y%m%dT%H%M%S.%f'))
  1858. env = os.environ.copy()
  1859. env['GIT_REDACT_COOKIES'] = 'o,SSO,GSSO_Uberproxy'
  1860. env['GIT_TR2_EVENT'] = os.path.join(traces_dir, 'tr2-event')
  1861. env['GIT_TRACE2_EVENT'] = os.path.join(traces_dir, 'tr2-event')
  1862. env['GIT_TRACE_CURL'] = os.path.join(traces_dir, 'trace-curl')
  1863. env['GIT_TRACE_CURL_NO_DATA'] = '1'
  1864. env['GIT_TRACE_PACKET'] = os.path.join(traces_dir, 'trace-packet')
  1865. try:
  1866. push_returncode = 0
  1867. remote_url = self.GetRemoteUrl()
  1868. before_push = time_time()
  1869. push_cmd = ['git', 'push', remote_url, refspec]
  1870. if git_push_options:
  1871. for opt in git_push_options:
  1872. push_cmd.extend(['-o', opt])
  1873. push_stdout = gclient_utils.CheckCallAndFilter(
  1874. push_cmd,
  1875. env=env,
  1876. print_stdout=True,
  1877. # Flush after every line: useful for seeing progress when running as
  1878. # recipe.
  1879. filter_fn=lambda _: sys.stdout.flush())
  1880. push_stdout = push_stdout.decode('utf-8', 'replace')
  1881. except subprocess2.CalledProcessError as e:
  1882. push_returncode = e.returncode
  1883. raise GitPushError(
  1884. 'Failed to create a change. Please examine output above for the '
  1885. 'reason of the failure.\n'
  1886. 'For emergencies, Googlers can escalate to '
  1887. 'go/gob-support or go/notify#gob\n'
  1888. 'Hint: run command below to diagnose common Git/Gerrit '
  1889. 'credential problems:\n'
  1890. ' git cl creds-check\n'
  1891. '\n'
  1892. 'If git-cl is not working correctly, file a bug under the Infra>SDK '
  1893. 'component including the files below.\n'
  1894. 'Review the files before upload, since they might contain sensitive '
  1895. 'information.\n'
  1896. 'Set the Restrict-View-Google label so that they are not publicly '
  1897. 'accessible.\n' + TRACES_MESSAGE % {'trace_name': trace_name})
  1898. finally:
  1899. execution_time = time_time() - before_push
  1900. metrics.collector.add_repeated('sub_commands', {
  1901. 'command': 'git push',
  1902. 'execution_time': execution_time,
  1903. 'exit_code': push_returncode,
  1904. 'arguments': metrics_utils.extract_known_subcommand_args(refspec_opts),
  1905. })
  1906. git_push_metadata['execution_time'] = execution_time
  1907. git_push_metadata['exit_code'] = push_returncode
  1908. self._WriteGitPushTraces(trace_name, traces_dir, git_push_metadata)
  1909. self._CleanUpOldTraces()
  1910. gclient_utils.rmtree(traces_dir)
  1911. return push_stdout
  1912. def CMDUploadChange(self, options, git_diff_args, custom_cl_base,
  1913. change_desc):
  1914. """Upload the current branch to Gerrit, retry if new remote HEAD is
  1915. found. options and change_desc may be mutated."""
  1916. remote, remote_branch = self.GetRemoteBranch()
  1917. branch = GetTargetRef(remote, remote_branch, options.target_branch)
  1918. try:
  1919. return self._CMDUploadChange(options, git_diff_args, custom_cl_base,
  1920. change_desc, branch)
  1921. except GitPushError as e:
  1922. # Repository might be in the middle of transition to main branch as
  1923. # default, and uploads to old default might be blocked.
  1924. if remote_branch not in [DEFAULT_OLD_BRANCH, DEFAULT_NEW_BRANCH]:
  1925. DieWithError(str(e), change_desc)
  1926. project_head = gerrit_util.GetProjectHead(self._gerrit_host,
  1927. self.GetGerritProject())
  1928. if project_head == branch:
  1929. DieWithError(str(e), change_desc)
  1930. branch = project_head
  1931. print("WARNING: Fetching remote state and retrying upload to default "
  1932. "branch...")
  1933. RunGit(['fetch', '--prune', remote])
  1934. options.edit_description = False
  1935. options.force = True
  1936. try:
  1937. self._CMDUploadChange(options, git_diff_args, custom_cl_base,
  1938. change_desc, branch)
  1939. except GitPushError as e:
  1940. DieWithError(str(e), change_desc)
  1941. def _CMDUploadChange(self, options, git_diff_args, custom_cl_base,
  1942. change_desc, branch):
  1943. """Upload the current branch to Gerrit."""
  1944. if options.squash:
  1945. self._GerritCommitMsgHookCheck(offer_removal=not options.force)
  1946. if self.GetIssue():
  1947. # User requested to change description
  1948. if options.edit_description:
  1949. change_desc.prompt()
  1950. change_id = self._GetChangeDetail()['change_id']
  1951. change_desc.ensure_change_id(change_id)
  1952. else: # if not self.GetIssue()
  1953. if not options.force and not options.message_file:
  1954. change_desc.prompt()
  1955. change_ids = git_footers.get_footer_change_id(change_desc.description)
  1956. if len(change_ids) == 1:
  1957. change_id = change_ids[0]
  1958. else:
  1959. change_id = GenerateGerritChangeId(change_desc.description)
  1960. change_desc.ensure_change_id(change_id)
  1961. if options.preserve_tryjobs:
  1962. change_desc.set_preserve_tryjobs()
  1963. remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
  1964. parent = self._ComputeParent(
  1965. remote, upstream_branch, custom_cl_base, options.force, change_desc)
  1966. tree = RunGit(['rev-parse', 'HEAD:']).strip()
  1967. with gclient_utils.temporary_file() as desc_tempfile:
  1968. gclient_utils.FileWrite(desc_tempfile, change_desc.description)
  1969. ref_to_push = RunGit(
  1970. ['commit-tree', tree, '-p', parent, '-F', desc_tempfile]).strip()
  1971. else: # if not options.squash
  1972. if not git_footers.get_footer_change_id(change_desc.description):
  1973. DownloadGerritHook(False)
  1974. change_desc.set_description(
  1975. self._AddChangeIdToCommitMessage(
  1976. change_desc.description, git_diff_args))
  1977. ref_to_push = 'HEAD'
  1978. # For no-squash mode, we assume the remote called "origin" is the one we
  1979. # want. It is not worthwhile to support different workflows for
  1980. # no-squash mode.
  1981. parent = 'origin/%s' % branch
  1982. change_id = git_footers.get_footer_change_id(change_desc.description)[0]
  1983. SaveDescriptionBackup(change_desc)
  1984. commits = RunGitSilent(['rev-list', '%s..%s' % (parent,
  1985. ref_to_push)]).splitlines()
  1986. if len(commits) > 1:
  1987. print('WARNING: This will upload %d commits. Run the following command '
  1988. 'to see which commits will be uploaded: ' % len(commits))
  1989. print('git log %s..%s' % (parent, ref_to_push))
  1990. print('You can also use `git squash-branch` to squash these into a '
  1991. 'single commit.')
  1992. confirm_or_exit(action='upload')
  1993. reviewers = sorted(change_desc.get_reviewers())
  1994. cc = []
  1995. # Add CCs from WATCHLISTS and rietveld.cc git config unless this is
  1996. # the initial upload, the CL is private, or auto-CCing has ben disabled.
  1997. if not (self.GetIssue() or options.private or options.no_autocc):
  1998. cc = self.GetCCList().split(',')
  1999. if len(cc) > 100:
  2000. lsc = ('https://chromium.googlesource.com/chromium/src/+/HEAD/docs/'
  2001. 'process/lsc/lsc_workflow.md')
  2002. print('WARNING: This will auto-CC %s users.' % len(cc))
  2003. print('LSC may be more appropriate: %s' % lsc)
  2004. print('You can also use the --no-autocc flag to disable auto-CC.')
  2005. confirm_or_exit(action='continue')
  2006. # Add cc's from the --cc flag.
  2007. if options.cc:
  2008. cc.extend(options.cc)
  2009. cc = [email.strip() for email in cc if email.strip()]
  2010. if change_desc.get_cced():
  2011. cc.extend(change_desc.get_cced())
  2012. if self.GetGerritHost() == 'chromium-review.googlesource.com':
  2013. valid_accounts = set(reviewers + cc)
  2014. # TODO(crbug/877717): relax this for all hosts.
  2015. else:
  2016. valid_accounts = gerrit_util.ValidAccounts(
  2017. self.GetGerritHost(), reviewers + cc)
  2018. logging.info('accounts %s are recognized, %s invalid',
  2019. sorted(valid_accounts),
  2020. set(reviewers + cc).difference(set(valid_accounts)))
  2021. # Extra options that can be specified at push time. Doc:
  2022. # https://gerrit-review.googlesource.com/Documentation/user-upload.html
  2023. refspec_opts = []
  2024. # By default, new changes are started in WIP mode, and subsequent patchsets
  2025. # don't send email. At any time, passing --send-mail will mark the change
  2026. # ready and send email for that particular patch.
  2027. if options.send_mail:
  2028. refspec_opts.append('ready')
  2029. refspec_opts.append('notify=ALL')
  2030. elif not self.GetIssue() and options.squash:
  2031. refspec_opts.append('wip')
  2032. else:
  2033. refspec_opts.append('notify=NONE')
  2034. # TODO(tandrii): options.message should be posted as a comment
  2035. # if --send-mail is set on non-initial upload as Rietveld used to do it.
  2036. # Set options.title in case user was prompted in _GetTitleForUpload and
  2037. # _CMDUploadChange needs to be called again.
  2038. options.title = self._GetTitleForUpload(options)
  2039. if options.title:
  2040. # Punctuation and whitespace in |title| must be percent-encoded.
  2041. refspec_opts.append(
  2042. 'm=' + gerrit_util.PercentEncodeForGitRef(options.title))
  2043. if options.private:
  2044. refspec_opts.append('private')
  2045. for r in sorted(reviewers):
  2046. if r in valid_accounts:
  2047. refspec_opts.append('r=%s' % r)
  2048. reviewers.remove(r)
  2049. else:
  2050. # TODO(tandrii): this should probably be a hard failure.
  2051. print('WARNING: reviewer %s doesn\'t have a Gerrit account, skipping'
  2052. % r)
  2053. for c in sorted(cc):
  2054. # refspec option will be rejected if cc doesn't correspond to an
  2055. # account, even though REST call to add such arbitrary cc may succeed.
  2056. if c in valid_accounts:
  2057. refspec_opts.append('cc=%s' % c)
  2058. cc.remove(c)
  2059. if options.topic:
  2060. # Documentation on Gerrit topics is here:
  2061. # https://gerrit-review.googlesource.com/Documentation/user-upload.html#topic
  2062. refspec_opts.append('topic=%s' % options.topic)
  2063. if options.enable_auto_submit:
  2064. refspec_opts.append('l=Auto-Submit+1')
  2065. if options.set_bot_commit:
  2066. refspec_opts.append('l=Bot-Commit+1')
  2067. if options.use_commit_queue:
  2068. refspec_opts.append('l=Commit-Queue+2')
  2069. elif options.cq_dry_run:
  2070. refspec_opts.append('l=Commit-Queue+1')
  2071. if change_desc.get_reviewers(tbr_only=True):
  2072. score = gerrit_util.GetCodeReviewTbrScore(
  2073. self.GetGerritHost(),
  2074. self.GetGerritProject())
  2075. refspec_opts.append('l=Code-Review+%s' % score)
  2076. # Gerrit sorts hashtags, so order is not important.
  2077. hashtags = {change_desc.sanitize_hash_tag(t) for t in options.hashtags}
  2078. if not self.GetIssue():
  2079. hashtags.update(change_desc.get_hash_tags())
  2080. refspec_opts += ['hashtag=%s' % t for t in sorted(hashtags)]
  2081. refspec_suffix = ''
  2082. if refspec_opts:
  2083. refspec_suffix = '%' + ','.join(refspec_opts)
  2084. assert ' ' not in refspec_suffix, (
  2085. 'spaces not allowed in refspec: "%s"' % refspec_suffix)
  2086. refspec = '%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix)
  2087. git_push_metadata = {
  2088. 'gerrit_host': self.GetGerritHost(),
  2089. 'title': options.title or '<untitled>',
  2090. 'change_id': change_id,
  2091. 'description': change_desc.description,
  2092. }
  2093. push_stdout = self._RunGitPushWithTraces(refspec, refspec_opts,
  2094. git_push_metadata,
  2095. options.push_options)
  2096. if options.squash:
  2097. regex = re.compile(r'remote:\s+https?://[\w\-\.\+\/#]*/(\d+)\s.*')
  2098. change_numbers = [m.group(1)
  2099. for m in map(regex.match, push_stdout.splitlines())
  2100. if m]
  2101. if len(change_numbers) != 1:
  2102. DieWithError(
  2103. ('Created|Updated %d issues on Gerrit, but only 1 expected.\n'
  2104. 'Change-Id: %s') % (len(change_numbers), change_id), change_desc)
  2105. self.SetIssue(change_numbers[0])
  2106. self._GitSetBranchConfigValue('gerritsquashhash', ref_to_push)
  2107. if self.GetIssue() and (reviewers or cc):
  2108. # GetIssue() is not set in case of non-squash uploads according to tests.
  2109. # TODO(crbug.com/751901): non-squash uploads in git cl should be removed.
  2110. gerrit_util.AddReviewers(
  2111. self.GetGerritHost(),
  2112. self._GerritChangeIdentifier(),
  2113. reviewers, cc,
  2114. notify=bool(options.send_mail))
  2115. return 0
  2116. def _ComputeParent(self, remote, upstream_branch, custom_cl_base, force,
  2117. change_desc):
  2118. """Computes parent of the generated commit to be uploaded to Gerrit.
  2119. Returns revision or a ref name.
  2120. """
  2121. if custom_cl_base:
  2122. # Try to avoid creating additional unintended CLs when uploading, unless
  2123. # user wants to take this risk.
  2124. local_ref_of_target_remote = self.GetRemoteBranch()[1]
  2125. code, _ = RunGitWithCode(['merge-base', '--is-ancestor', custom_cl_base,
  2126. local_ref_of_target_remote])
  2127. if code == 1:
  2128. print('\nWARNING: Manually specified base of this CL `%s` '
  2129. 'doesn\'t seem to belong to target remote branch `%s`.\n\n'
  2130. 'If you proceed with upload, more than 1 CL may be created by '
  2131. 'Gerrit as a result, in turn confusing or crashing git cl.\n\n'
  2132. 'If you are certain that specified base `%s` has already been '
  2133. 'uploaded to Gerrit as another CL, you may proceed.\n' %
  2134. (custom_cl_base, local_ref_of_target_remote, custom_cl_base))
  2135. if not force:
  2136. confirm_or_exit(
  2137. 'Do you take responsibility for cleaning up potential mess '
  2138. 'resulting from proceeding with upload?',
  2139. action='upload')
  2140. return custom_cl_base
  2141. if remote != '.':
  2142. return self.GetCommonAncestorWithUpstream()
  2143. # If our upstream branch is local, we base our squashed commit on its
  2144. # squashed version.
  2145. upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch)
  2146. if upstream_branch_name == 'master':
  2147. return self.GetCommonAncestorWithUpstream()
  2148. if upstream_branch_name == 'main':
  2149. return self.GetCommonAncestorWithUpstream()
  2150. # Check the squashed hash of the parent.
  2151. # TODO(tandrii): consider checking parent change in Gerrit and using its
  2152. # hash if tree hash of latest parent revision (patchset) in Gerrit matches
  2153. # the tree hash of the parent branch. The upside is less likely bogus
  2154. # requests to reupload parent change just because it's uploadhash is
  2155. # missing, yet the downside likely exists, too (albeit unknown to me yet).
  2156. parent = scm.GIT.GetBranchConfig(
  2157. settings.GetRoot(), upstream_branch_name, 'gerritsquashhash')
  2158. # Verify that the upstream branch has been uploaded too, otherwise
  2159. # Gerrit will create additional CLs when uploading.
  2160. if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) !=
  2161. RunGitSilent(['rev-parse', parent + ':'])):
  2162. DieWithError(
  2163. '\nUpload upstream branch %s first.\n'
  2164. 'It is likely that this branch has been rebased since its last '
  2165. 'upload, so you just need to upload it again.\n'
  2166. '(If you uploaded it with --no-squash, then branch dependencies '
  2167. 'are not supported, and you should reupload with --squash.)'
  2168. % upstream_branch_name,
  2169. change_desc)
  2170. return parent
  2171. def _AddChangeIdToCommitMessage(self, log_desc, args):
  2172. """Re-commits using the current message, assumes the commit hook is in
  2173. place.
  2174. """
  2175. RunGit(['commit', '--amend', '-m', log_desc])
  2176. new_log_desc = _create_description_from_log(args)
  2177. if git_footers.get_footer_change_id(new_log_desc):
  2178. print('git-cl: Added Change-Id to commit message.')
  2179. return new_log_desc
  2180. else:
  2181. DieWithError('ERROR: Gerrit commit-msg hook not installed.')
  2182. def CannotTriggerTryJobReason(self):
  2183. try:
  2184. data = self._GetChangeDetail()
  2185. except GerritChangeNotExists:
  2186. return 'Gerrit doesn\'t know about your change %s' % self.GetIssue()
  2187. if data['status'] in ('ABANDONED', 'MERGED'):
  2188. return 'CL %s is closed' % self.GetIssue()
  2189. def GetGerritChange(self, patchset=None):
  2190. """Returns a buildbucket.v2.GerritChange message for the current issue."""
  2191. host = urllib.parse.urlparse(self.GetCodereviewServer()).hostname
  2192. issue = self.GetIssue()
  2193. patchset = int(patchset or self.GetPatchset())
  2194. data = self._GetChangeDetail(['ALL_REVISIONS'])
  2195. assert host and issue and patchset, 'CL must be uploaded first'
  2196. has_patchset = any(
  2197. int(revision_data['_number']) == patchset
  2198. for revision_data in data['revisions'].values())
  2199. if not has_patchset:
  2200. raise Exception('Patchset %d is not known in Gerrit change %d' %
  2201. (patchset, self.GetIssue()))
  2202. return {
  2203. 'host': host,
  2204. 'change': issue,
  2205. 'project': data['project'],
  2206. 'patchset': patchset,
  2207. }
  2208. def GetIssueOwner(self):
  2209. return self._GetChangeDetail(['DETAILED_ACCOUNTS'])['owner']['email']
  2210. def GetReviewers(self):
  2211. details = self._GetChangeDetail(['DETAILED_ACCOUNTS'])
  2212. return [r['email'] for r in details['reviewers'].get('REVIEWER', [])]
  2213. def _get_bug_line_values(default_project_prefix, bugs):
  2214. """Given default_project_prefix and comma separated list of bugs, yields bug
  2215. line values.
  2216. Each bug can be either:
  2217. * a number, which is combined with default_project_prefix
  2218. * string, which is left as is.
  2219. This function may produce more than one line, because bugdroid expects one
  2220. project per line.
  2221. >>> list(_get_bug_line_values('v8:', '123,chromium:789'))
  2222. ['v8:123', 'chromium:789']
  2223. """
  2224. default_bugs = []
  2225. others = []
  2226. for bug in bugs.split(','):
  2227. bug = bug.strip()
  2228. if bug:
  2229. try:
  2230. default_bugs.append(int(bug))
  2231. except ValueError:
  2232. others.append(bug)
  2233. if default_bugs:
  2234. default_bugs = ','.join(map(str, default_bugs))
  2235. if default_project_prefix:
  2236. if not default_project_prefix.endswith(':'):
  2237. default_project_prefix += ':'
  2238. yield '%s%s' % (default_project_prefix, default_bugs)
  2239. else:
  2240. yield default_bugs
  2241. for other in sorted(others):
  2242. # Don't bother finding common prefixes, CLs with >2 bugs are very very rare.
  2243. yield other
  2244. class ChangeDescription(object):
  2245. """Contains a parsed form of the change description."""
  2246. R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$'
  2247. CC_LINE = r'^[ \t]*(CC)[ \t]*=[ \t]*(.*?)[ \t]*$'
  2248. BUG_LINE = r'^[ \t]*(?:(BUG)[ \t]*=|Bug:)[ \t]*(.*?)[ \t]*$'
  2249. FIXED_LINE = r'^[ \t]*Fixed[ \t]*:[ \t]*(.*?)[ \t]*$'
  2250. CHERRY_PICK_LINE = r'^\(cherry picked from commit [a-fA-F0-9]{40}\)$'
  2251. STRIP_HASH_TAG_PREFIX = r'^(\s*(revert|reland)( "|:)?\s*)*'
  2252. BRACKET_HASH_TAG = r'\s*\[([^\[\]]+)\]'
  2253. COLON_SEPARATED_HASH_TAG = r'^([a-zA-Z0-9_\- ]+):($|[^:])'
  2254. BAD_HASH_TAG_CHUNK = r'[^a-zA-Z0-9]+'
  2255. def __init__(self, description, bug=None, fixed=None):
  2256. self._description_lines = (description or '').strip().splitlines()
  2257. if bug:
  2258. regexp = re.compile(self.BUG_LINE)
  2259. prefix = settings.GetBugPrefix()
  2260. if not any((regexp.match(line) for line in self._description_lines)):
  2261. values = list(_get_bug_line_values(prefix, bug))
  2262. self.append_footer('Bug: %s' % ', '.join(values))
  2263. if fixed:
  2264. regexp = re.compile(self.FIXED_LINE)
  2265. prefix = settings.GetBugPrefix()
  2266. if not any((regexp.match(line) for line in self._description_lines)):
  2267. values = list(_get_bug_line_values(prefix, fixed))
  2268. self.append_footer('Fixed: %s' % ', '.join(values))
  2269. @property # www.logilab.org/ticket/89786
  2270. def description(self): # pylint: disable=method-hidden
  2271. return '\n'.join(self._description_lines)
  2272. def set_description(self, desc):
  2273. if isinstance(desc, basestring):
  2274. lines = desc.splitlines()
  2275. else:
  2276. lines = [line.rstrip() for line in desc]
  2277. while lines and not lines[0]:
  2278. lines.pop(0)
  2279. while lines and not lines[-1]:
  2280. lines.pop(-1)
  2281. self._description_lines = lines
  2282. def ensure_change_id(self, change_id):
  2283. description = self.description
  2284. footer_change_ids = git_footers.get_footer_change_id(description)
  2285. # Make sure that the Change-Id in the description matches the given one.
  2286. if footer_change_ids != [change_id]:
  2287. if footer_change_ids:
  2288. # Remove any existing Change-Id footers since they don't match the
  2289. # expected change_id footer.
  2290. description = git_footers.remove_footer(description, 'Change-Id')
  2291. print('WARNING: Change-Id has been set to %s. Use `git cl issue 0` '
  2292. 'if you want to set a new one.')
  2293. # Add the expected Change-Id footer.
  2294. description = git_footers.add_footer_change_id(description, change_id)
  2295. self.set_description(description)
  2296. def update_reviewers(self, reviewers, tbrs):
  2297. """Rewrites the R=/TBR= line(s) as a single line each.
  2298. Args:
  2299. reviewers (list(str)) - list of additional emails to use for reviewers.
  2300. tbrs (list(str)) - list of additional emails to use for TBRs.
  2301. """
  2302. if not reviewers and not tbrs:
  2303. return
  2304. reviewers = set(reviewers)
  2305. tbrs = set(tbrs)
  2306. LOOKUP = {
  2307. 'TBR': tbrs,
  2308. 'R': reviewers,
  2309. }
  2310. # Get the set of R= and TBR= lines and remove them from the description.
  2311. regexp = re.compile(self.R_LINE)
  2312. matches = [regexp.match(line) for line in self._description_lines]
  2313. new_desc = [l for i, l in enumerate(self._description_lines)
  2314. if not matches[i]]
  2315. self.set_description(new_desc)
  2316. # Construct new unified R= and TBR= lines.
  2317. # First, update tbrs/reviewers with names from the R=/TBR= lines (if any).
  2318. for match in matches:
  2319. if not match:
  2320. continue
  2321. LOOKUP[match.group(1)].update(cleanup_list([match.group(2).strip()]))
  2322. # If any folks ended up in both groups, remove them from tbrs.
  2323. tbrs -= reviewers
  2324. new_r_line = 'R=' + ', '.join(sorted(reviewers)) if reviewers else None
  2325. new_tbr_line = 'TBR=' + ', '.join(sorted(tbrs)) if tbrs else None
  2326. # Put the new lines in the description where the old first R= line was.
  2327. line_loc = next((i for i, match in enumerate(matches) if match), -1)
  2328. if 0 <= line_loc < len(self._description_lines):
  2329. if new_tbr_line:
  2330. self._description_lines.insert(line_loc, new_tbr_line)
  2331. if new_r_line:
  2332. self._description_lines.insert(line_loc, new_r_line)
  2333. else:
  2334. if new_r_line:
  2335. self.append_footer(new_r_line)
  2336. if new_tbr_line:
  2337. self.append_footer(new_tbr_line)
  2338. def set_preserve_tryjobs(self):
  2339. """Ensures description footer contains 'Cq-Do-Not-Cancel-Tryjobs: true'."""
  2340. footers = git_footers.parse_footers(self.description)
  2341. for v in footers.get('Cq-Do-Not-Cancel-Tryjobs', []):
  2342. if v.lower() == 'true':
  2343. return
  2344. self.append_footer('Cq-Do-Not-Cancel-Tryjobs: true')
  2345. def prompt(self):
  2346. """Asks the user to update the description."""
  2347. self.set_description([
  2348. '# Enter a description of the change.',
  2349. '# This will be displayed on the codereview site.',
  2350. '# The first line will also be used as the subject of the review.',
  2351. '#--------------------This line is 72 characters long'
  2352. '--------------------',
  2353. ] + self._description_lines)
  2354. bug_regexp = re.compile(self.BUG_LINE)
  2355. fixed_regexp = re.compile(self.FIXED_LINE)
  2356. prefix = settings.GetBugPrefix()
  2357. has_issue = lambda l: bug_regexp.match(l) or fixed_regexp.match(l)
  2358. if not any((has_issue(line) for line in self._description_lines)):
  2359. self.append_footer('Bug: %s' % prefix)
  2360. print('Waiting for editor...')
  2361. content = gclient_utils.RunEditor(self.description, True,
  2362. git_editor=settings.GetGitEditor())
  2363. if not content:
  2364. DieWithError('Running editor failed')
  2365. lines = content.splitlines()
  2366. # Strip off comments and default inserted "Bug:" line.
  2367. clean_lines = [line.rstrip() for line in lines if not
  2368. (line.startswith('#') or
  2369. line.rstrip() == "Bug:" or
  2370. line.rstrip() == "Bug: " + prefix)]
  2371. if not clean_lines:
  2372. DieWithError('No CL description, aborting')
  2373. self.set_description(clean_lines)
  2374. def append_footer(self, line):
  2375. """Adds a footer line to the description.
  2376. Differentiates legacy "KEY=xxx" footers (used to be called tags) and
  2377. Gerrit's footers in the form of "Footer-Key: footer any value" and ensures
  2378. that Gerrit footers are always at the end.
  2379. """
  2380. parsed_footer_line = git_footers.parse_footer(line)
  2381. if parsed_footer_line:
  2382. # Line is a gerrit footer in the form: Footer-Key: any value.
  2383. # Thus, must be appended observing Gerrit footer rules.
  2384. self.set_description(
  2385. git_footers.add_footer(self.description,
  2386. key=parsed_footer_line[0],
  2387. value=parsed_footer_line[1]))
  2388. return
  2389. if not self._description_lines:
  2390. self._description_lines.append(line)
  2391. return
  2392. top_lines, gerrit_footers, _ = git_footers.split_footers(self.description)
  2393. if gerrit_footers:
  2394. # git_footers.split_footers ensures that there is an empty line before
  2395. # actual (gerrit) footers, if any. We have to keep it that way.
  2396. assert top_lines and top_lines[-1] == ''
  2397. top_lines, separator = top_lines[:-1], top_lines[-1:]
  2398. else:
  2399. separator = [] # No need for separator if there are no gerrit_footers.
  2400. prev_line = top_lines[-1] if top_lines else ''
  2401. if (not presubmit_support.Change.TAG_LINE_RE.match(prev_line) or
  2402. not presubmit_support.Change.TAG_LINE_RE.match(line)):
  2403. top_lines.append('')
  2404. top_lines.append(line)
  2405. self._description_lines = top_lines + separator + gerrit_footers
  2406. def get_reviewers(self, tbr_only=False):
  2407. """Retrieves the list of reviewers."""
  2408. matches = [re.match(self.R_LINE, line) for line in self._description_lines]
  2409. reviewers = [match.group(2).strip()
  2410. for match in matches
  2411. if match and (not tbr_only or match.group(1).upper() == 'TBR')]
  2412. return cleanup_list(reviewers)
  2413. def get_cced(self):
  2414. """Retrieves the list of reviewers."""
  2415. matches = [re.match(self.CC_LINE, line) for line in self._description_lines]
  2416. cced = [match.group(2).strip() for match in matches if match]
  2417. return cleanup_list(cced)
  2418. def get_hash_tags(self):
  2419. """Extracts and sanitizes a list of Gerrit hashtags."""
  2420. subject = (self._description_lines or ('',))[0]
  2421. subject = re.sub(
  2422. self.STRIP_HASH_TAG_PREFIX, '', subject, flags=re.IGNORECASE)
  2423. tags = []
  2424. start = 0
  2425. bracket_exp = re.compile(self.BRACKET_HASH_TAG)
  2426. while True:
  2427. m = bracket_exp.match(subject, start)
  2428. if not m:
  2429. break
  2430. tags.append(self.sanitize_hash_tag(m.group(1)))
  2431. start = m.end()
  2432. if not tags:
  2433. # Try "Tag: " prefix.
  2434. m = re.match(self.COLON_SEPARATED_HASH_TAG, subject)
  2435. if m:
  2436. tags.append(self.sanitize_hash_tag(m.group(1)))
  2437. return tags
  2438. @classmethod
  2439. def sanitize_hash_tag(cls, tag):
  2440. """Returns a sanitized Gerrit hash tag.
  2441. A sanitized hashtag can be used as a git push refspec parameter value.
  2442. """
  2443. return re.sub(cls.BAD_HASH_TAG_CHUNK, '-', tag).strip('-').lower()
  2444. def FindCodereviewSettingsFile(filename='codereview.settings'):
  2445. """Finds the given file starting in the cwd and going up.
  2446. Only looks up to the top of the repository unless an
  2447. 'inherit-review-settings-ok' file exists in the root of the repository.
  2448. """
  2449. inherit_ok_file = 'inherit-review-settings-ok'
  2450. cwd = os.getcwd()
  2451. root = settings.GetRoot()
  2452. if os.path.isfile(os.path.join(root, inherit_ok_file)):
  2453. root = '/'
  2454. while True:
  2455. if filename in os.listdir(cwd):
  2456. if os.path.isfile(os.path.join(cwd, filename)):
  2457. return open(os.path.join(cwd, filename))
  2458. if cwd == root:
  2459. break
  2460. cwd = os.path.dirname(cwd)
  2461. def LoadCodereviewSettingsFromFile(fileobj):
  2462. """Parses a codereview.settings file and updates hooks."""
  2463. keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read())
  2464. def SetProperty(name, setting, unset_error_ok=False):
  2465. fullname = 'rietveld.' + name
  2466. if setting in keyvals:
  2467. RunGit(['config', fullname, keyvals[setting]])
  2468. else:
  2469. RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok)
  2470. if not keyvals.get('GERRIT_HOST', False):
  2471. SetProperty('server', 'CODE_REVIEW_SERVER')
  2472. # Only server setting is required. Other settings can be absent.
  2473. # In that case, we ignore errors raised during option deletion attempt.
  2474. SetProperty('cc', 'CC_LIST', unset_error_ok=True)
  2475. SetProperty('tree-status-url', 'STATUS', unset_error_ok=True)
  2476. SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True)
  2477. SetProperty('bug-prefix', 'BUG_PREFIX', unset_error_ok=True)
  2478. SetProperty('cpplint-regex', 'LINT_REGEX', unset_error_ok=True)
  2479. SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX', unset_error_ok=True)
  2480. SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK',
  2481. unset_error_ok=True)
  2482. SetProperty(
  2483. 'format-full-by-default', 'FORMAT_FULL_BY_DEFAULT', unset_error_ok=True)
  2484. if 'GERRIT_HOST' in keyvals:
  2485. RunGit(['config', 'gerrit.host', keyvals['GERRIT_HOST']])
  2486. if 'GERRIT_SQUASH_UPLOADS' in keyvals:
  2487. RunGit(['config', 'gerrit.squash-uploads',
  2488. keyvals['GERRIT_SQUASH_UPLOADS']])
  2489. if 'GERRIT_SKIP_ENSURE_AUTHENTICATED' in keyvals:
  2490. RunGit(['config', 'gerrit.skip-ensure-authenticated',
  2491. keyvals['GERRIT_SKIP_ENSURE_AUTHENTICATED']])
  2492. if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals:
  2493. # should be of the form
  2494. # PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof
  2495. # ORIGIN_URL_CONFIG: http://src.chromium.org/git
  2496. RunGit(['config', keyvals['PUSH_URL_CONFIG'],
  2497. keyvals['ORIGIN_URL_CONFIG']])
  2498. def urlretrieve(source, destination):
  2499. """Downloads a network object to a local file, like urllib.urlretrieve.
  2500. This is necessary because urllib is broken for SSL connections via a proxy.
  2501. """
  2502. with open(destination, 'w') as f:
  2503. f.write(urllib.request.urlopen(source).read())
  2504. def hasSheBang(fname):
  2505. """Checks fname is a #! script."""
  2506. with open(fname) as f:
  2507. return f.read(2).startswith('#!')
  2508. def DownloadGerritHook(force):
  2509. """Downloads and installs a Gerrit commit-msg hook.
  2510. Args:
  2511. force: True to update hooks. False to install hooks if not present.
  2512. """
  2513. src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg'
  2514. dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
  2515. if not os.access(dst, os.X_OK):
  2516. if os.path.exists(dst):
  2517. if not force:
  2518. return
  2519. try:
  2520. urlretrieve(src, dst)
  2521. if not hasSheBang(dst):
  2522. DieWithError('Not a script: %s\n'
  2523. 'You need to download from\n%s\n'
  2524. 'into .git/hooks/commit-msg and '
  2525. 'chmod +x .git/hooks/commit-msg' % (dst, src))
  2526. os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
  2527. except Exception:
  2528. if os.path.exists(dst):
  2529. os.remove(dst)
  2530. DieWithError('\nFailed to download hooks.\n'
  2531. 'You need to download from\n%s\n'
  2532. 'into .git/hooks/commit-msg and '
  2533. 'chmod +x .git/hooks/commit-msg' % src)
  2534. class _GitCookiesChecker(object):
  2535. """Provides facilities for validating and suggesting fixes to .gitcookies."""
  2536. _GOOGLESOURCE = 'googlesource.com'
  2537. def __init__(self):
  2538. # Cached list of [host, identity, source], where source is either
  2539. # .gitcookies or .netrc.
  2540. self._all_hosts = None
  2541. def ensure_configured_gitcookies(self):
  2542. """Runs checks and suggests fixes to make git use .gitcookies from default
  2543. path."""
  2544. default = gerrit_util.CookiesAuthenticator.get_gitcookies_path()
  2545. configured_path = RunGitSilent(
  2546. ['config', '--global', 'http.cookiefile']).strip()
  2547. configured_path = os.path.expanduser(configured_path)
  2548. if configured_path:
  2549. self._ensure_default_gitcookies_path(configured_path, default)
  2550. else:
  2551. self._configure_gitcookies_path(default)
  2552. @staticmethod
  2553. def _ensure_default_gitcookies_path(configured_path, default_path):
  2554. assert configured_path
  2555. if configured_path == default_path:
  2556. print('git is already configured to use your .gitcookies from %s' %
  2557. configured_path)
  2558. return
  2559. print('WARNING: You have configured custom path to .gitcookies: %s\n'
  2560. 'Gerrit and other depot_tools expect .gitcookies at %s\n' %
  2561. (configured_path, default_path))
  2562. if not os.path.exists(configured_path):
  2563. print('However, your configured .gitcookies file is missing.')
  2564. confirm_or_exit('Reconfigure git to use default .gitcookies?',
  2565. action='reconfigure')
  2566. RunGit(['config', '--global', 'http.cookiefile', default_path])
  2567. return
  2568. if os.path.exists(default_path):
  2569. print('WARNING: default .gitcookies file already exists %s' %
  2570. default_path)
  2571. DieWithError('Please delete %s manually and re-run git cl creds-check' %
  2572. default_path)
  2573. confirm_or_exit('Move existing .gitcookies to default location?',
  2574. action='move')
  2575. shutil.move(configured_path, default_path)
  2576. RunGit(['config', '--global', 'http.cookiefile', default_path])
  2577. print('Moved and reconfigured git to use .gitcookies from %s' %
  2578. default_path)
  2579. @staticmethod
  2580. def _configure_gitcookies_path(default_path):
  2581. netrc_path = gerrit_util.CookiesAuthenticator.get_netrc_path()
  2582. if os.path.exists(netrc_path):
  2583. print('You seem to be using outdated .netrc for git credentials: %s' %
  2584. netrc_path)
  2585. print('This tool will guide you through setting up recommended '
  2586. '.gitcookies store for git credentials.\n'
  2587. '\n'
  2588. 'IMPORTANT: If something goes wrong and you decide to go back, do:\n'
  2589. ' git config --global --unset http.cookiefile\n'
  2590. ' mv %s %s.backup\n\n' % (default_path, default_path))
  2591. confirm_or_exit(action='setup .gitcookies')
  2592. RunGit(['config', '--global', 'http.cookiefile', default_path])
  2593. print('Configured git to use .gitcookies from %s' % default_path)
  2594. def get_hosts_with_creds(self, include_netrc=False):
  2595. if self._all_hosts is None:
  2596. a = gerrit_util.CookiesAuthenticator()
  2597. self._all_hosts = [
  2598. (h, u, s)
  2599. for h, u, s in itertools.chain(
  2600. ((h, u, '.netrc') for h, (u, _, _) in a.netrc.hosts.items()),
  2601. ((h, u, '.gitcookies') for h, (u, _) in a.gitcookies.items())
  2602. )
  2603. if h.endswith(self._GOOGLESOURCE)
  2604. ]
  2605. if include_netrc:
  2606. return self._all_hosts
  2607. return [(h, u, s) for h, u, s in self._all_hosts if s != '.netrc']
  2608. def print_current_creds(self, include_netrc=False):
  2609. hosts = sorted(self.get_hosts_with_creds(include_netrc=include_netrc))
  2610. if not hosts:
  2611. print('No Git/Gerrit credentials found')
  2612. return
  2613. lengths = [max(map(len, (row[i] for row in hosts))) for i in range(3)]
  2614. header = [('Host', 'User', 'Which file'),
  2615. ['=' * l for l in lengths]]
  2616. for row in (header + hosts):
  2617. print('\t'.join((('%%+%ds' % l) % s)
  2618. for l, s in zip(lengths, row)))
  2619. @staticmethod
  2620. def _parse_identity(identity):
  2621. """Parses identity "git-<username>.domain" into <username> and domain."""
  2622. # Special case: usernames that contain ".", which are generally not
  2623. # distinguishable from sub-domains. But we do know typical domains:
  2624. if identity.endswith('.chromium.org'):
  2625. domain = 'chromium.org'
  2626. username = identity[:-len('.chromium.org')]
  2627. else:
  2628. username, domain = identity.split('.', 1)
  2629. if username.startswith('git-'):
  2630. username = username[len('git-'):]
  2631. return username, domain
  2632. def _canonical_git_googlesource_host(self, host):
  2633. """Normalizes Gerrit hosts (with '-review') to Git host."""
  2634. assert host.endswith(self._GOOGLESOURCE)
  2635. # Prefix doesn't include '.' at the end.
  2636. prefix = host[:-(1 + len(self._GOOGLESOURCE))]
  2637. if prefix.endswith('-review'):
  2638. prefix = prefix[:-len('-review')]
  2639. return prefix + '.' + self._GOOGLESOURCE
  2640. def _canonical_gerrit_googlesource_host(self, host):
  2641. git_host = self._canonical_git_googlesource_host(host)
  2642. prefix = git_host.split('.', 1)[0]
  2643. return prefix + '-review.' + self._GOOGLESOURCE
  2644. def _get_counterpart_host(self, host):
  2645. assert host.endswith(self._GOOGLESOURCE)
  2646. git = self._canonical_git_googlesource_host(host)
  2647. gerrit = self._canonical_gerrit_googlesource_host(git)
  2648. return git if gerrit == host else gerrit
  2649. def has_generic_host(self):
  2650. """Returns whether generic .googlesource.com has been configured.
  2651. Chrome Infra recommends to use explicit ${host}.googlesource.com instead.
  2652. """
  2653. for host, _, _ in self.get_hosts_with_creds(include_netrc=False):
  2654. if host == '.' + self._GOOGLESOURCE:
  2655. return True
  2656. return False
  2657. def _get_git_gerrit_identity_pairs(self):
  2658. """Returns map from canonic host to pair of identities (Git, Gerrit).
  2659. One of identities might be None, meaning not configured.
  2660. """
  2661. host_to_identity_pairs = {}
  2662. for host, identity, _ in self.get_hosts_with_creds():
  2663. canonical = self._canonical_git_googlesource_host(host)
  2664. pair = host_to_identity_pairs.setdefault(canonical, [None, None])
  2665. idx = 0 if canonical == host else 1
  2666. pair[idx] = identity
  2667. return host_to_identity_pairs
  2668. def get_partially_configured_hosts(self):
  2669. return set(
  2670. (host if i1 else self._canonical_gerrit_googlesource_host(host))
  2671. for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items()
  2672. if None in (i1, i2) and host != '.' + self._GOOGLESOURCE)
  2673. def get_conflicting_hosts(self):
  2674. return set(
  2675. host
  2676. for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items()
  2677. if None not in (i1, i2) and i1 != i2)
  2678. def get_duplicated_hosts(self):
  2679. counters = collections.Counter(h for h, _, _ in self.get_hosts_with_creds())
  2680. return set(host for host, count in counters.items() if count > 1)
  2681. @staticmethod
  2682. def _format_hosts(hosts, extra_column_func=None):
  2683. hosts = sorted(hosts)
  2684. assert hosts
  2685. if extra_column_func is None:
  2686. extras = [''] * len(hosts)
  2687. else:
  2688. extras = [extra_column_func(host) for host in hosts]
  2689. tmpl = '%%-%ds %%-%ds' % (max(map(len, hosts)), max(map(len, extras)))
  2690. lines = []
  2691. for he in zip(hosts, extras):
  2692. lines.append(tmpl % he)
  2693. return lines
  2694. def _find_problems(self):
  2695. if self.has_generic_host():
  2696. yield ('.googlesource.com wildcard record detected',
  2697. ['Chrome Infrastructure team recommends to list full host names '
  2698. 'explicitly.'],
  2699. None)
  2700. dups = self.get_duplicated_hosts()
  2701. if dups:
  2702. yield ('The following hosts were defined twice',
  2703. self._format_hosts(dups),
  2704. None)
  2705. partial = self.get_partially_configured_hosts()
  2706. if partial:
  2707. yield ('Credentials should come in pairs for Git and Gerrit hosts. '
  2708. 'These hosts are missing',
  2709. self._format_hosts(partial, lambda host: 'but %s defined' %
  2710. self._get_counterpart_host(host)),
  2711. partial)
  2712. conflicting = self.get_conflicting_hosts()
  2713. if conflicting:
  2714. yield ('The following Git hosts have differing credentials from their '
  2715. 'Gerrit counterparts',
  2716. self._format_hosts(conflicting, lambda host: '%s vs %s' %
  2717. tuple(self._get_git_gerrit_identity_pairs()[host])),
  2718. conflicting)
  2719. def find_and_report_problems(self):
  2720. """Returns True if there was at least one problem, else False."""
  2721. found = False
  2722. bad_hosts = set()
  2723. for title, sublines, hosts in self._find_problems():
  2724. if not found:
  2725. found = True
  2726. print('\n\n.gitcookies problem report:\n')
  2727. bad_hosts.update(hosts or [])
  2728. print(' %s%s' % (title, (':' if sublines else '')))
  2729. if sublines:
  2730. print()
  2731. print(' %s' % '\n '.join(sublines))
  2732. print()
  2733. if bad_hosts:
  2734. assert found
  2735. print(' You can manually remove corresponding lines in your %s file and '
  2736. 'visit the following URLs with correct account to generate '
  2737. 'correct credential lines:\n' %
  2738. gerrit_util.CookiesAuthenticator.get_gitcookies_path())
  2739. print(' %s' % '\n '.join(sorted(set(
  2740. gerrit_util.CookiesAuthenticator().get_new_password_url(
  2741. self._canonical_git_googlesource_host(host))
  2742. for host in bad_hosts
  2743. ))))
  2744. return found
  2745. @metrics.collector.collect_metrics('git cl creds-check')
  2746. def CMDcreds_check(parser, args):
  2747. """Checks credentials and suggests changes."""
  2748. _, _ = parser.parse_args(args)
  2749. # Code below checks .gitcookies. Abort if using something else.
  2750. authn = gerrit_util.Authenticator.get()
  2751. if not isinstance(authn, gerrit_util.CookiesAuthenticator):
  2752. message = (
  2753. 'This command is not designed for bot environment. It checks '
  2754. '~/.gitcookies file not generally used on bots.')
  2755. # TODO(crbug.com/1059384): Automatically detect when running on cloudtop.
  2756. if isinstance(authn, gerrit_util.GceAuthenticator):
  2757. message += (
  2758. '\n'
  2759. 'If you need to run this on GCE or a cloudtop instance, '
  2760. 'export SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
  2761. DieWithError(message)
  2762. checker = _GitCookiesChecker()
  2763. checker.ensure_configured_gitcookies()
  2764. print('Your .netrc and .gitcookies have credentials for these hosts:')
  2765. checker.print_current_creds(include_netrc=True)
  2766. if not checker.find_and_report_problems():
  2767. print('\nNo problems detected in your .gitcookies file.')
  2768. return 0
  2769. return 1
  2770. @metrics.collector.collect_metrics('git cl baseurl')
  2771. def CMDbaseurl(parser, args):
  2772. """Gets or sets base-url for this branch."""
  2773. branchref = scm.GIT.GetBranchRef(settings.GetRoot())
  2774. branch = scm.GIT.ShortBranchName(branchref)
  2775. _, args = parser.parse_args(args)
  2776. if not args:
  2777. print('Current base-url:')
  2778. return RunGit(['config', 'branch.%s.base-url' % branch],
  2779. error_ok=False).strip()
  2780. else:
  2781. print('Setting base-url to %s' % args[0])
  2782. return RunGit(['config', 'branch.%s.base-url' % branch, args[0]],
  2783. error_ok=False).strip()
  2784. def color_for_status(status):
  2785. """Maps a Changelist status to color, for CMDstatus and other tools."""
  2786. BOLD = '\033[1m'
  2787. return {
  2788. 'unsent': BOLD + Fore.YELLOW,
  2789. 'waiting': BOLD + Fore.RED,
  2790. 'reply': BOLD + Fore.YELLOW,
  2791. 'not lgtm': BOLD + Fore.RED,
  2792. 'lgtm': BOLD + Fore.GREEN,
  2793. 'commit': BOLD + Fore.MAGENTA,
  2794. 'closed': BOLD + Fore.CYAN,
  2795. 'error': BOLD + Fore.WHITE,
  2796. }.get(status, Fore.WHITE)
  2797. def get_cl_statuses(changes, fine_grained, max_processes=None):
  2798. """Returns a blocking iterable of (cl, status) for given branches.
  2799. If fine_grained is true, this will fetch CL statuses from the server.
  2800. Otherwise, simply indicate if there's a matching url for the given branches.
  2801. If max_processes is specified, it is used as the maximum number of processes
  2802. to spawn to fetch CL status from the server. Otherwise 1 process per branch is
  2803. spawned.
  2804. See GetStatus() for a list of possible statuses.
  2805. """
  2806. if not changes:
  2807. return
  2808. if not fine_grained:
  2809. # Fast path which doesn't involve querying codereview servers.
  2810. # Do not use get_approving_reviewers(), since it requires an HTTP request.
  2811. for cl in changes:
  2812. yield (cl, 'waiting' if cl.GetIssueURL() else 'error')
  2813. return
  2814. # First, sort out authentication issues.
  2815. logging.debug('ensuring credentials exist')
  2816. for cl in changes:
  2817. cl.EnsureAuthenticated(force=False, refresh=True)
  2818. def fetch(cl):
  2819. try:
  2820. return (cl, cl.GetStatus())
  2821. except:
  2822. # See http://crbug.com/629863.
  2823. logging.exception('failed to fetch status for cl %s:', cl.GetIssue())
  2824. raise
  2825. threads_count = len(changes)
  2826. if max_processes:
  2827. threads_count = max(1, min(threads_count, max_processes))
  2828. logging.debug('querying %d CLs using %d threads', len(changes), threads_count)
  2829. pool = multiprocessing.pool.ThreadPool(threads_count)
  2830. fetched_cls = set()
  2831. try:
  2832. it = pool.imap_unordered(fetch, changes).__iter__()
  2833. while True:
  2834. try:
  2835. cl, status = it.next(timeout=5)
  2836. except (multiprocessing.TimeoutError, StopIteration):
  2837. break
  2838. fetched_cls.add(cl)
  2839. yield cl, status
  2840. finally:
  2841. pool.close()
  2842. # Add any branches that failed to fetch.
  2843. for cl in set(changes) - fetched_cls:
  2844. yield (cl, 'error')
  2845. def upload_branch_deps(cl, args, force=False):
  2846. """Uploads CLs of local branches that are dependents of the current branch.
  2847. If the local branch dependency tree looks like:
  2848. test1 -> test2.1 -> test3.1
  2849. -> test3.2
  2850. -> test2.2 -> test3.3
  2851. and you run "git cl upload --dependencies" from test1 then "git cl upload" is
  2852. run on the dependent branches in this order:
  2853. test2.1, test3.1, test3.2, test2.2, test3.3
  2854. Note: This function does not rebase your local dependent branches. Use it
  2855. when you make a change to the parent branch that will not conflict
  2856. with its dependent branches, and you would like their dependencies
  2857. updated in Rietveld.
  2858. """
  2859. if git_common.is_dirty_git_tree('upload-branch-deps'):
  2860. return 1
  2861. root_branch = cl.GetBranch()
  2862. if root_branch is None:
  2863. DieWithError('Can\'t find dependent branches from detached HEAD state. '
  2864. 'Get on a branch!')
  2865. if not cl.GetIssue():
  2866. DieWithError('Current branch does not have an uploaded CL. We cannot set '
  2867. 'patchset dependencies without an uploaded CL.')
  2868. branches = RunGit(['for-each-ref',
  2869. '--format=%(refname:short) %(upstream:short)',
  2870. 'refs/heads'])
  2871. if not branches:
  2872. print('No local branches found.')
  2873. return 0
  2874. # Create a dictionary of all local branches to the branches that are
  2875. # dependent on it.
  2876. tracked_to_dependents = collections.defaultdict(list)
  2877. for b in branches.splitlines():
  2878. tokens = b.split()
  2879. if len(tokens) == 2:
  2880. branch_name, tracked = tokens
  2881. tracked_to_dependents[tracked].append(branch_name)
  2882. print()
  2883. print('The dependent local branches of %s are:' % root_branch)
  2884. dependents = []
  2885. def traverse_dependents_preorder(branch, padding=''):
  2886. dependents_to_process = tracked_to_dependents.get(branch, [])
  2887. padding += ' '
  2888. for dependent in dependents_to_process:
  2889. print('%s%s' % (padding, dependent))
  2890. dependents.append(dependent)
  2891. traverse_dependents_preorder(dependent, padding)
  2892. traverse_dependents_preorder(root_branch)
  2893. print()
  2894. if not dependents:
  2895. print('There are no dependent local branches for %s' % root_branch)
  2896. return 0
  2897. if not force:
  2898. confirm_or_exit('This command will checkout all dependent branches and run '
  2899. '"git cl upload".', action='continue')
  2900. # Record all dependents that failed to upload.
  2901. failures = {}
  2902. # Go through all dependents, checkout the branch and upload.
  2903. try:
  2904. for dependent_branch in dependents:
  2905. print()
  2906. print('--------------------------------------')
  2907. print('Running "git cl upload" from %s:' % dependent_branch)
  2908. RunGit(['checkout', '-q', dependent_branch])
  2909. print()
  2910. try:
  2911. if CMDupload(OptionParser(), args) != 0:
  2912. print('Upload failed for %s!' % dependent_branch)
  2913. failures[dependent_branch] = 1
  2914. except: # pylint: disable=bare-except
  2915. failures[dependent_branch] = 1
  2916. print()
  2917. finally:
  2918. # Swap back to the original root branch.
  2919. RunGit(['checkout', '-q', root_branch])
  2920. print()
  2921. print('Upload complete for dependent branches!')
  2922. for dependent_branch in dependents:
  2923. upload_status = 'failed' if failures.get(dependent_branch) else 'succeeded'
  2924. print(' %s : %s' % (dependent_branch, upload_status))
  2925. print()
  2926. return 0
  2927. def GetArchiveTagForBranch(issue_num, branch_name, existing_tags, pattern):
  2928. """Given a proposed tag name, returns a tag name that is guaranteed to be
  2929. unique. If 'foo' is proposed but already exists, then 'foo-2' is used,
  2930. or 'foo-3', and so on."""
  2931. proposed_tag = pattern.format(**{'issue': issue_num, 'branch': branch_name})
  2932. for suffix_num in itertools.count(1):
  2933. if suffix_num == 1:
  2934. to_check = proposed_tag
  2935. else:
  2936. to_check = '%s-%d' % (proposed_tag, suffix_num)
  2937. if to_check not in existing_tags:
  2938. return to_check
  2939. @metrics.collector.collect_metrics('git cl archive')
  2940. def CMDarchive(parser, args):
  2941. """Archives and deletes branches associated with closed changelists."""
  2942. parser.add_option(
  2943. '-j', '--maxjobs', action='store', type=int,
  2944. help='The maximum number of jobs to use when retrieving review status.')
  2945. parser.add_option(
  2946. '-f', '--force', action='store_true',
  2947. help='Bypasses the confirmation prompt.')
  2948. parser.add_option(
  2949. '-d', '--dry-run', action='store_true',
  2950. help='Skip the branch tagging and removal steps.')
  2951. parser.add_option(
  2952. '-t', '--notags', action='store_true',
  2953. help='Do not tag archived branches. '
  2954. 'Note: local commit history may be lost.')
  2955. parser.add_option(
  2956. '-p',
  2957. '--pattern',
  2958. default='git-cl-archived-{issue}-{branch}',
  2959. help='Format string for archive tags. '
  2960. 'E.g. \'archived-{issue}-{branch}\'.')
  2961. options, args = parser.parse_args(args)
  2962. if args:
  2963. parser.error('Unsupported args: %s' % ' '.join(args))
  2964. branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
  2965. if not branches:
  2966. return 0
  2967. tags = RunGit(['for-each-ref', '--format=%(refname)',
  2968. 'refs/tags']).splitlines() or []
  2969. tags = [t.split('/')[-1] for t in tags]
  2970. print('Finding all branches associated with closed issues...')
  2971. changes = [Changelist(branchref=b)
  2972. for b in branches.splitlines()]
  2973. alignment = max(5, max(len(c.GetBranch()) for c in changes))
  2974. statuses = get_cl_statuses(changes,
  2975. fine_grained=True,
  2976. max_processes=options.maxjobs)
  2977. proposal = [(cl.GetBranch(),
  2978. GetArchiveTagForBranch(cl.GetIssue(), cl.GetBranch(), tags,
  2979. options.pattern))
  2980. for cl, status in statuses
  2981. if status in ('closed', 'rietveld-not-supported')]
  2982. proposal.sort()
  2983. if not proposal:
  2984. print('No branches with closed codereview issues found.')
  2985. return 0
  2986. current_branch = scm.GIT.GetBranch(settings.GetRoot())
  2987. print('\nBranches with closed issues that will be archived:\n')
  2988. if options.notags:
  2989. for next_item in proposal:
  2990. print(' ' + next_item[0])
  2991. else:
  2992. print('%*s | %s' % (alignment, 'Branch name', 'Archival tag name'))
  2993. for next_item in proposal:
  2994. print('%*s %s' % (alignment, next_item[0], next_item[1]))
  2995. # Quit now on precondition failure or if instructed by the user, either
  2996. # via an interactive prompt or by command line flags.
  2997. if options.dry_run:
  2998. print('\nNo changes were made (dry run).\n')
  2999. return 0
  3000. elif any(branch == current_branch for branch, _ in proposal):
  3001. print('You are currently on a branch \'%s\' which is associated with a '
  3002. 'closed codereview issue, so archive cannot proceed. Please '
  3003. 'checkout another branch and run this command again.' %
  3004. current_branch)
  3005. return 1
  3006. elif not options.force:
  3007. answer = gclient_utils.AskForData('\nProceed with deletion (Y/n)? ').lower()
  3008. if answer not in ('y', ''):
  3009. print('Aborted.')
  3010. return 1
  3011. for branch, tagname in proposal:
  3012. if not options.notags:
  3013. RunGit(['tag', tagname, branch])
  3014. if RunGitWithCode(['branch', '-D', branch])[0] != 0:
  3015. # Clean up the tag if we failed to delete the branch.
  3016. RunGit(['tag', '-d', tagname])
  3017. print('\nJob\'s done!')
  3018. return 0
  3019. @metrics.collector.collect_metrics('git cl status')
  3020. def CMDstatus(parser, args):
  3021. """Show status of changelists.
  3022. Colors are used to tell the state of the CL unless --fast is used:
  3023. - Blue waiting for review
  3024. - Yellow waiting for you to reply to review, or not yet sent
  3025. - Green LGTM'ed
  3026. - Red 'not LGTM'ed
  3027. - Magenta in the CQ
  3028. - Cyan was committed, branch can be deleted
  3029. - White error, or unknown status
  3030. Also see 'git cl comments'.
  3031. """
  3032. parser.add_option(
  3033. '--no-branch-color',
  3034. action='store_true',
  3035. help='Disable colorized branch names')
  3036. parser.add_option('--field',
  3037. help='print only specific field (desc|id|patch|status|url)')
  3038. parser.add_option('-f', '--fast', action='store_true',
  3039. help='Do not retrieve review status')
  3040. parser.add_option(
  3041. '-j', '--maxjobs', action='store', type=int,
  3042. help='The maximum number of jobs to use when retrieving review status')
  3043. parser.add_option(
  3044. '-i', '--issue', type=int,
  3045. help='Operate on this issue instead of the current branch\'s implicit '
  3046. 'issue. Requires --field to be set.')
  3047. parser.add_option('-d',
  3048. '--date-order',
  3049. action='store_true',
  3050. help='Order branches by committer date.')
  3051. options, args = parser.parse_args(args)
  3052. if args:
  3053. parser.error('Unsupported args: %s' % args)
  3054. if options.issue is not None and not options.field:
  3055. parser.error('--field must be given when --issue is set.')
  3056. if options.field:
  3057. cl = Changelist(issue=options.issue)
  3058. if options.field.startswith('desc'):
  3059. if cl.GetIssue():
  3060. print(cl.FetchDescription())
  3061. elif options.field == 'id':
  3062. issueid = cl.GetIssue()
  3063. if issueid:
  3064. print(issueid)
  3065. elif options.field == 'patch':
  3066. patchset = cl.GetMostRecentPatchset()
  3067. if patchset:
  3068. print(patchset)
  3069. elif options.field == 'status':
  3070. print(cl.GetStatus())
  3071. elif options.field == 'url':
  3072. url = cl.GetIssueURL()
  3073. if url:
  3074. print(url)
  3075. return 0
  3076. branches = RunGit([
  3077. 'for-each-ref', '--format=%(refname) %(committerdate:unix)', 'refs/heads'
  3078. ])
  3079. if not branches:
  3080. print('No local branch found.')
  3081. return 0
  3082. changes = [
  3083. Changelist(branchref=b, commit_date=ct)
  3084. for b, ct in map(lambda line: line.split(' '), branches.splitlines())
  3085. ]
  3086. print('Branches associated with reviews:')
  3087. output = get_cl_statuses(changes,
  3088. fine_grained=not options.fast,
  3089. max_processes=options.maxjobs)
  3090. current_branch = scm.GIT.GetBranch(settings.GetRoot())
  3091. def FormatBranchName(branch, colorize=False):
  3092. """Simulates 'git branch' behavior. Colorizes and prefixes branch name with
  3093. an asterisk when it is the current branch."""
  3094. asterisk = ""
  3095. color = Fore.RESET
  3096. if branch == current_branch:
  3097. asterisk = "* "
  3098. color = Fore.GREEN
  3099. branch_name = scm.GIT.ShortBranchName(branch)
  3100. if colorize:
  3101. return asterisk + color + branch_name + Fore.RESET
  3102. return asterisk + branch_name
  3103. branch_statuses = {}
  3104. alignment = max(5, max(len(FormatBranchName(c.GetBranch())) for c in changes))
  3105. if options.date_order:
  3106. sorted_changes = sorted(changes,
  3107. key=lambda c: c.GetCommitDate(),
  3108. reverse=True)
  3109. else:
  3110. sorted_changes = sorted(changes, key=lambda c: c.GetBranch())
  3111. for cl in sorted_changes:
  3112. branch = cl.GetBranch()
  3113. while branch not in branch_statuses:
  3114. c, status = next(output)
  3115. branch_statuses[c.GetBranch()] = status
  3116. status = branch_statuses.pop(branch)
  3117. url = cl.GetIssueURL(short=True)
  3118. if url and (not status or status == 'error'):
  3119. # The issue probably doesn't exist anymore.
  3120. url += ' (broken)'
  3121. color = color_for_status(status)
  3122. # Turn off bold as well as colors.
  3123. END = '\033[0m'
  3124. reset = Fore.RESET + END
  3125. if not setup_color.IS_TTY:
  3126. color = ''
  3127. reset = ''
  3128. status_str = '(%s)' % status if status else ''
  3129. branch_display = FormatBranchName(branch)
  3130. padding = ' ' * (alignment - len(branch_display))
  3131. if not options.no_branch_color:
  3132. branch_display = FormatBranchName(branch, colorize=True)
  3133. print(' %s : %s%s %s%s' % (padding + branch_display, color, url,
  3134. status_str, reset))
  3135. print()
  3136. print('Current branch: %s' % current_branch)
  3137. for cl in changes:
  3138. if cl.GetBranch() == current_branch:
  3139. break
  3140. if not cl.GetIssue():
  3141. print('No issue assigned.')
  3142. return 0
  3143. print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()))
  3144. if not options.fast:
  3145. print('Issue description:')
  3146. print(cl.FetchDescription(pretty=True))
  3147. return 0
  3148. def colorize_CMDstatus_doc():
  3149. """To be called once in main() to add colors to git cl status help."""
  3150. colors = [i for i in dir(Fore) if i[0].isupper()]
  3151. def colorize_line(line):
  3152. for color in colors:
  3153. if color in line.upper():
  3154. # Extract whitespace first and the leading '-'.
  3155. indent = len(line) - len(line.lstrip(' ')) + 1
  3156. return line[:indent] + getattr(Fore, color) + line[indent:] + Fore.RESET
  3157. return line
  3158. lines = CMDstatus.__doc__.splitlines()
  3159. CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines)
  3160. def write_json(path, contents):
  3161. if path == '-':
  3162. json.dump(contents, sys.stdout)
  3163. else:
  3164. with open(path, 'w') as f:
  3165. json.dump(contents, f)
  3166. @subcommand.usage('[issue_number]')
  3167. @metrics.collector.collect_metrics('git cl issue')
  3168. def CMDissue(parser, args):
  3169. """Sets or displays the current code review issue number.
  3170. Pass issue number 0 to clear the current issue.
  3171. """
  3172. parser.add_option('-r', '--reverse', action='store_true',
  3173. help='Lookup the branch(es) for the specified issues. If '
  3174. 'no issues are specified, all branches with mapped '
  3175. 'issues will be listed.')
  3176. parser.add_option('--json',
  3177. help='Path to JSON output file, or "-" for stdout.')
  3178. options, args = parser.parse_args(args)
  3179. if options.reverse:
  3180. branches = RunGit(['for-each-ref', 'refs/heads',
  3181. '--format=%(refname)']).splitlines()
  3182. # Reverse issue lookup.
  3183. issue_branch_map = {}
  3184. git_config = {}
  3185. for config in RunGit(['config', '--get-regexp',
  3186. r'branch\..*issue']).splitlines():
  3187. name, _space, val = config.partition(' ')
  3188. git_config[name] = val
  3189. for branch in branches:
  3190. issue = git_config.get(
  3191. 'branch.%s.%s' % (scm.GIT.ShortBranchName(branch), ISSUE_CONFIG_KEY))
  3192. if issue:
  3193. issue_branch_map.setdefault(int(issue), []).append(branch)
  3194. if not args:
  3195. args = sorted(issue_branch_map.keys())
  3196. result = {}
  3197. for issue in args:
  3198. try:
  3199. issue_num = int(issue)
  3200. except ValueError:
  3201. print('ERROR cannot parse issue number: %s' % issue, file=sys.stderr)
  3202. continue
  3203. result[issue_num] = issue_branch_map.get(issue_num)
  3204. print('Branch for issue number %s: %s' % (
  3205. issue, ', '.join(issue_branch_map.get(issue_num) or ('None',))))
  3206. if options.json:
  3207. write_json(options.json, result)
  3208. return 0
  3209. if len(args) > 0:
  3210. issue = ParseIssueNumberArgument(args[0])
  3211. if not issue.valid:
  3212. DieWithError('Pass a url or number to set the issue, 0 to unset it, '
  3213. 'or no argument to list it.\n'
  3214. 'Maybe you want to run git cl status?')
  3215. cl = Changelist()
  3216. cl.SetIssue(issue.issue)
  3217. else:
  3218. cl = Changelist()
  3219. print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()))
  3220. if options.json:
  3221. write_json(options.json, {
  3222. 'gerrit_host': cl.GetGerritHost(),
  3223. 'gerrit_project': cl.GetGerritProject(),
  3224. 'issue_url': cl.GetIssueURL(),
  3225. 'issue': cl.GetIssue(),
  3226. })
  3227. return 0
  3228. @metrics.collector.collect_metrics('git cl comments')
  3229. def CMDcomments(parser, args):
  3230. """Shows or posts review comments for any changelist."""
  3231. parser.add_option('-a', '--add-comment', dest='comment',
  3232. help='comment to add to an issue')
  3233. parser.add_option('-p', '--publish', action='store_true',
  3234. help='marks CL as ready and sends comment to reviewers')
  3235. parser.add_option('-i', '--issue', dest='issue',
  3236. help='review issue id (defaults to current issue).')
  3237. parser.add_option('-m', '--machine-readable', dest='readable',
  3238. action='store_false', default=True,
  3239. help='output comments in a format compatible with '
  3240. 'editor parsing')
  3241. parser.add_option('-j', '--json-file',
  3242. help='File to write JSON summary to, or "-" for stdout')
  3243. options, args = parser.parse_args(args)
  3244. issue = None
  3245. if options.issue:
  3246. try:
  3247. issue = int(options.issue)
  3248. except ValueError:
  3249. DieWithError('A review issue ID is expected to be a number.')
  3250. cl = Changelist(issue=issue)
  3251. if options.comment:
  3252. cl.AddComment(options.comment, options.publish)
  3253. return 0
  3254. summary = sorted(cl.GetCommentsSummary(readable=options.readable),
  3255. key=lambda c: c.date)
  3256. for comment in summary:
  3257. if comment.disapproval:
  3258. color = Fore.RED
  3259. elif comment.approval:
  3260. color = Fore.GREEN
  3261. elif comment.sender == cl.GetIssueOwner():
  3262. color = Fore.MAGENTA
  3263. elif comment.autogenerated:
  3264. color = Fore.CYAN
  3265. else:
  3266. color = Fore.BLUE
  3267. print('\n%s%s %s%s\n%s' % (
  3268. color,
  3269. comment.date.strftime('%Y-%m-%d %H:%M:%S UTC'),
  3270. comment.sender,
  3271. Fore.RESET,
  3272. '\n'.join(' ' + l for l in comment.message.strip().splitlines())))
  3273. if options.json_file:
  3274. def pre_serialize(c):
  3275. dct = c._asdict().copy()
  3276. dct['date'] = dct['date'].strftime('%Y-%m-%d %H:%M:%S.%f')
  3277. return dct
  3278. write_json(options.json_file, [pre_serialize(x) for x in summary])
  3279. return 0
  3280. @subcommand.usage('[codereview url or issue id]')
  3281. @metrics.collector.collect_metrics('git cl description')
  3282. def CMDdescription(parser, args):
  3283. """Brings up the editor for the current CL's description."""
  3284. parser.add_option('-d', '--display', action='store_true',
  3285. help='Display the description instead of opening an editor')
  3286. parser.add_option('-n', '--new-description',
  3287. help='New description to set for this issue (- for stdin, '
  3288. '+ to load from local commit HEAD)')
  3289. parser.add_option('-f', '--force', action='store_true',
  3290. help='Delete any unpublished Gerrit edits for this issue '
  3291. 'without prompting')
  3292. options, args = parser.parse_args(args)
  3293. target_issue_arg = None
  3294. if len(args) > 0:
  3295. target_issue_arg = ParseIssueNumberArgument(args[0])
  3296. if not target_issue_arg.valid:
  3297. parser.error('Invalid issue ID or URL.')
  3298. kwargs = {}
  3299. if target_issue_arg:
  3300. kwargs['issue'] = target_issue_arg.issue
  3301. kwargs['codereview_host'] = target_issue_arg.hostname
  3302. cl = Changelist(**kwargs)
  3303. if not cl.GetIssue():
  3304. DieWithError('This branch has no associated changelist.')
  3305. if args and not args[0].isdigit():
  3306. logging.info('canonical issue/change URL: %s\n', cl.GetIssueURL())
  3307. description = ChangeDescription(cl.FetchDescription())
  3308. if options.display:
  3309. print(description.description)
  3310. return 0
  3311. if options.new_description:
  3312. text = options.new_description
  3313. if text == '-':
  3314. text = '\n'.join(l.rstrip() for l in sys.stdin)
  3315. elif text == '+':
  3316. base_branch = cl.GetCommonAncestorWithUpstream()
  3317. text = _create_description_from_log([base_branch])
  3318. description.set_description(text)
  3319. else:
  3320. description.prompt()
  3321. if cl.FetchDescription().strip() != description.description:
  3322. cl.UpdateDescription(description.description, force=options.force)
  3323. return 0
  3324. @metrics.collector.collect_metrics('git cl lint')
  3325. def CMDlint(parser, args):
  3326. """Runs cpplint on the current changelist."""
  3327. parser.add_option('--filter', action='append', metavar='-x,+y',
  3328. help='Comma-separated list of cpplint\'s category-filters')
  3329. options, args = parser.parse_args(args)
  3330. # Access to a protected member _XX of a client class
  3331. # pylint: disable=protected-access
  3332. try:
  3333. import cpplint
  3334. import cpplint_chromium
  3335. except ImportError:
  3336. print('Your depot_tools is missing cpplint.py and/or cpplint_chromium.py.')
  3337. return 1
  3338. # Change the current working directory before calling lint so that it
  3339. # shows the correct base.
  3340. previous_cwd = os.getcwd()
  3341. os.chdir(settings.GetRoot())
  3342. try:
  3343. cl = Changelist()
  3344. files = cl.GetAffectedFiles(cl.GetCommonAncestorWithUpstream())
  3345. if not files:
  3346. print('Cannot lint an empty CL')
  3347. return 1
  3348. # Process cpplint arguments, if any.
  3349. filters = presubmit_canned_checks.GetCppLintFilters(options.filter)
  3350. command = ['--filter=' + ','.join(filters)] + args + files
  3351. filenames = cpplint.ParseArguments(command)
  3352. include_regex = re.compile(settings.GetLintRegex())
  3353. ignore_regex = re.compile(settings.GetLintIgnoreRegex())
  3354. extra_check_functions = [cpplint_chromium.CheckPointerDeclarationWhitespace]
  3355. for filename in filenames:
  3356. if not include_regex.match(filename):
  3357. print('Skipping file %s' % filename)
  3358. continue
  3359. if ignore_regex.match(filename):
  3360. print('Ignoring file %s' % filename)
  3361. continue
  3362. cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level,
  3363. extra_check_functions)
  3364. finally:
  3365. os.chdir(previous_cwd)
  3366. print('Total errors found: %d\n' % cpplint._cpplint_state.error_count)
  3367. if cpplint._cpplint_state.error_count != 0:
  3368. return 1
  3369. return 0
  3370. @metrics.collector.collect_metrics('git cl presubmit')
  3371. def CMDpresubmit(parser, args):
  3372. """Runs presubmit tests on the current changelist."""
  3373. parser.add_option('-u', '--upload', action='store_true',
  3374. help='Run upload hook instead of the push hook')
  3375. parser.add_option('-f', '--force', action='store_true',
  3376. help='Run checks even if tree is dirty')
  3377. parser.add_option('--all', action='store_true',
  3378. help='Run checks against all files, not just modified ones')
  3379. parser.add_option('--parallel', action='store_true',
  3380. help='Run all tests specified by input_api.RunTests in all '
  3381. 'PRESUBMIT files in parallel.')
  3382. parser.add_option('--resultdb', action='store_true',
  3383. help='Run presubmit checks in the ResultSink environment '
  3384. 'and send results to the ResultDB database.')
  3385. parser.add_option('--realm', help='LUCI realm if reporting to ResultDB')
  3386. options, args = parser.parse_args(args)
  3387. if not options.force and git_common.is_dirty_git_tree('presubmit'):
  3388. print('use --force to check even if tree is dirty.')
  3389. return 1
  3390. cl = Changelist()
  3391. if args:
  3392. base_branch = args[0]
  3393. else:
  3394. # Default to diffing against the common ancestor of the upstream branch.
  3395. base_branch = cl.GetCommonAncestorWithUpstream()
  3396. if cl.GetIssue():
  3397. description = cl.FetchDescription()
  3398. else:
  3399. description = _create_description_from_log([base_branch])
  3400. cl.RunHook(
  3401. committing=not options.upload,
  3402. may_prompt=False,
  3403. verbose=options.verbose,
  3404. parallel=options.parallel,
  3405. upstream=base_branch,
  3406. description=description,
  3407. all_files=options.all,
  3408. resultdb=options.resultdb,
  3409. realm=options.realm)
  3410. return 0
  3411. def GenerateGerritChangeId(message):
  3412. """Returns the Change ID footer value (Ixxxxxx...xxx).
  3413. Works the same way as
  3414. https://gerrit-review.googlesource.com/tools/hooks/commit-msg
  3415. but can be called on demand on all platforms.
  3416. The basic idea is to generate git hash of a state of the tree, original
  3417. commit message, author/committer info and timestamps.
  3418. """
  3419. lines = []
  3420. tree_hash = RunGitSilent(['write-tree'])
  3421. lines.append('tree %s' % tree_hash.strip())
  3422. code, parent = RunGitWithCode(['rev-parse', 'HEAD~0'], suppress_stderr=False)
  3423. if code == 0:
  3424. lines.append('parent %s' % parent.strip())
  3425. author = RunGitSilent(['var', 'GIT_AUTHOR_IDENT'])
  3426. lines.append('author %s' % author.strip())
  3427. committer = RunGitSilent(['var', 'GIT_COMMITTER_IDENT'])
  3428. lines.append('committer %s' % committer.strip())
  3429. lines.append('')
  3430. # Note: Gerrit's commit-hook actually cleans message of some lines and
  3431. # whitespace. This code is not doing this, but it clearly won't decrease
  3432. # entropy.
  3433. lines.append(message)
  3434. change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'],
  3435. stdin=('\n'.join(lines)).encode())
  3436. return 'I%s' % change_hash.strip()
  3437. def GetTargetRef(remote, remote_branch, target_branch):
  3438. """Computes the remote branch ref to use for the CL.
  3439. Args:
  3440. remote (str): The git remote for the CL.
  3441. remote_branch (str): The git remote branch for the CL.
  3442. target_branch (str): The target branch specified by the user.
  3443. """
  3444. if not (remote and remote_branch):
  3445. return None
  3446. if target_branch:
  3447. # Canonicalize branch references to the equivalent local full symbolic
  3448. # refs, which are then translated into the remote full symbolic refs
  3449. # below.
  3450. if '/' not in target_branch:
  3451. remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch)
  3452. else:
  3453. prefix_replacements = (
  3454. ('^((refs/)?remotes/)?branch-heads/', 'refs/remotes/branch-heads/'),
  3455. ('^((refs/)?remotes/)?%s/' % remote, 'refs/remotes/%s/' % remote),
  3456. ('^(refs/)?heads/', 'refs/remotes/%s/' % remote),
  3457. )
  3458. match = None
  3459. for regex, replacement in prefix_replacements:
  3460. match = re.search(regex, target_branch)
  3461. if match:
  3462. remote_branch = target_branch.replace(match.group(0), replacement)
  3463. break
  3464. if not match:
  3465. # This is a branch path but not one we recognize; use as-is.
  3466. remote_branch = target_branch
  3467. elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS:
  3468. # Handle the refs that need to land in different refs.
  3469. remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch]
  3470. # Migration to new default branch, only if available on remote.
  3471. allow_push_on_master = bool(os.environ.get("ALLOW_PUSH_TO_MASTER", None))
  3472. if remote_branch == DEFAULT_OLD_BRANCH and not allow_push_on_master:
  3473. if RunGit(['show-branch', DEFAULT_NEW_BRANCH], error_ok=True,
  3474. stderr=subprocess2.PIPE):
  3475. # TODO(crbug.com/ID): Print location to local git migration script.
  3476. print("WARNING: Using new branch name %s instead of %s" % (
  3477. DEFAULT_NEW_BRANCH, DEFAULT_OLD_BRANCH))
  3478. remote_branch = DEFAULT_NEW_BRANCH
  3479. # Create the true path to the remote branch.
  3480. # Does the following translation:
  3481. # * refs/remotes/origin/refs/diff/test -> refs/diff/test
  3482. # * refs/remotes/origin/main -> refs/heads/main
  3483. # * refs/remotes/branch-heads/test -> refs/branch-heads/test
  3484. if remote_branch.startswith('refs/remotes/%s/refs/' % remote):
  3485. remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '')
  3486. elif remote_branch.startswith('refs/remotes/%s/' % remote):
  3487. remote_branch = remote_branch.replace('refs/remotes/%s/' % remote,
  3488. 'refs/heads/')
  3489. elif remote_branch.startswith('refs/remotes/branch-heads'):
  3490. remote_branch = remote_branch.replace('refs/remotes/', 'refs/')
  3491. return remote_branch
  3492. def cleanup_list(l):
  3493. """Fixes a list so that comma separated items are put as individual items.
  3494. So that "--reviewers joe@c,john@c --reviewers joa@c" results in
  3495. options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']).
  3496. """
  3497. items = sum((i.split(',') for i in l), [])
  3498. stripped_items = (i.strip() for i in items)
  3499. return sorted(filter(None, stripped_items))
  3500. @subcommand.usage('[flags]')
  3501. @metrics.collector.collect_metrics('git cl upload')
  3502. def CMDupload(parser, args):
  3503. """Uploads the current changelist to codereview.
  3504. Can skip dependency patchset uploads for a branch by running:
  3505. git config branch.branch_name.skip-deps-uploads True
  3506. To unset, run:
  3507. git config --unset branch.branch_name.skip-deps-uploads
  3508. Can also set the above globally by using the --global flag.
  3509. If the name of the checked out branch starts with "bug-" or "fix-" followed
  3510. by a bug number, this bug number is automatically populated in the CL
  3511. description.
  3512. If subject contains text in square brackets or has "<text>: " prefix, such
  3513. text(s) is treated as Gerrit hashtags. For example, CLs with subjects:
  3514. [git-cl] add support for hashtags
  3515. Foo bar: implement foo
  3516. will be hashtagged with "git-cl" and "foo-bar" respectively.
  3517. """
  3518. parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
  3519. help='bypass upload presubmit hook')
  3520. parser.add_option('--bypass-watchlists', action='store_true',
  3521. dest='bypass_watchlists',
  3522. help='bypass watchlists auto CC-ing reviewers')
  3523. parser.add_option('-f', '--force', action='store_true', dest='force',
  3524. help="force yes to questions (don't prompt)")
  3525. parser.add_option('--message', '-m', dest='message',
  3526. help='message for patchset')
  3527. parser.add_option('-b', '--bug',
  3528. help='pre-populate the bug number(s) for this issue. '
  3529. 'If several, separate with commas')
  3530. parser.add_option('--message-file', dest='message_file',
  3531. help='file which contains message for patchset')
  3532. parser.add_option('--title', '-t', dest='title',
  3533. help='title for patchset')
  3534. parser.add_option('-T', '--skip-title', action='store_true',
  3535. dest='skip_title',
  3536. help='Use the most recent commit message as the title of '
  3537. 'the patchset')
  3538. parser.add_option('-r', '--reviewers',
  3539. action='append', default=[],
  3540. help='reviewer email addresses')
  3541. parser.add_option('--tbrs',
  3542. action='append', default=[],
  3543. help='TBR email addresses')
  3544. parser.add_option('--cc',
  3545. action='append', default=[],
  3546. help='cc email addresses')
  3547. parser.add_option('--hashtag', dest='hashtags',
  3548. action='append', default=[],
  3549. help=('Gerrit hashtag for new CL; '
  3550. 'can be applied multiple times'))
  3551. parser.add_option('-s', '--send-mail', action='store_true',
  3552. help='send email to reviewer(s) and cc(s) immediately')
  3553. parser.add_option('--target_branch',
  3554. '--target-branch',
  3555. metavar='TARGET',
  3556. help='Apply CL to remote ref TARGET. ' +
  3557. 'Default: remote branch head, or main')
  3558. parser.add_option('--squash', action='store_true',
  3559. help='Squash multiple commits into one')
  3560. parser.add_option('--no-squash', action='store_false', dest='squash',
  3561. help='Don\'t squash multiple commits into one')
  3562. parser.add_option('--topic', default=None,
  3563. help='Topic to specify when uploading')
  3564. parser.add_option('--tbr-owners', dest='add_owners_to', action='store_const',
  3565. const='TBR', help='add a set of OWNERS to TBR')
  3566. parser.add_option('--r-owners', dest='add_owners_to', action='store_const',
  3567. const='R', help='add a set of OWNERS to R')
  3568. parser.add_option('-c', '--use-commit-queue', action='store_true',
  3569. default=False,
  3570. help='tell the CQ to commit this patchset; '
  3571. 'implies --send-mail')
  3572. parser.add_option('-d', '--cq-dry-run',
  3573. action='store_true', default=False,
  3574. help='Send the patchset to do a CQ dry run right after '
  3575. 'upload.')
  3576. parser.add_option('--set-bot-commit', action='store_true',
  3577. help=optparse.SUPPRESS_HELP)
  3578. parser.add_option('--preserve-tryjobs', action='store_true',
  3579. help='instruct the CQ to let tryjobs running even after '
  3580. 'new patchsets are uploaded instead of canceling '
  3581. 'prior patchset\' tryjobs')
  3582. parser.add_option('--dependencies', action='store_true',
  3583. help='Uploads CLs of all the local branches that depend on '
  3584. 'the current branch')
  3585. parser.add_option('-a', '--enable-auto-submit', action='store_true',
  3586. help='Sends your change to the CQ after an approval. Only '
  3587. 'works on repos that have the Auto-Submit label '
  3588. 'enabled')
  3589. parser.add_option('--parallel', action='store_true',
  3590. help='Run all tests specified by input_api.RunTests in all '
  3591. 'PRESUBMIT files in parallel.')
  3592. parser.add_option('--no-autocc', action='store_true',
  3593. help='Disables automatic addition of CC emails')
  3594. parser.add_option('--private', action='store_true',
  3595. help='Set the review private. This implies --no-autocc.')
  3596. parser.add_option('-R', '--retry-failed', action='store_true',
  3597. help='Retry failed tryjobs from old patchset immediately '
  3598. 'after uploading new patchset. Cannot be used with '
  3599. '--use-commit-queue or --cq-dry-run.')
  3600. parser.add_option('--buildbucket-host', default='cr-buildbucket.appspot.com',
  3601. help='Host of buildbucket. The default host is %default.')
  3602. parser.add_option('--fixed', '-x',
  3603. help='List of bugs that will be commented on and marked '
  3604. 'fixed (pre-populates "Fixed:" tag). Same format as '
  3605. '-b option / "Bug:" tag. If fixing several issues, '
  3606. 'separate with commas.')
  3607. parser.add_option('--edit-description', action='store_true', default=False,
  3608. help='Modify description before upload. Cannot be used '
  3609. 'with --force. It is a noop when --no-squash is set '
  3610. 'or a new commit is created.')
  3611. parser.add_option('--git-completion-helper', action="store_true",
  3612. help=optparse.SUPPRESS_HELP)
  3613. parser.add_option('--resultdb', action='store_true',
  3614. help='Run presubmit checks in the ResultSink environment '
  3615. 'and send results to the ResultDB database.')
  3616. parser.add_option('--realm', help='LUCI realm if reporting to ResultDB')
  3617. parser.add_option('-o',
  3618. '--push-options',
  3619. action='append',
  3620. default=[],
  3621. help='Transmit the given string to the server when '
  3622. 'performing git push (pass-through). See git-push '
  3623. 'documentation for more details.')
  3624. orig_args = args
  3625. (options, args) = parser.parse_args(args)
  3626. if options.git_completion_helper:
  3627. print(' '.join(opt.get_opt_string() for opt in parser.option_list
  3628. if opt.help != optparse.SUPPRESS_HELP))
  3629. return
  3630. if git_common.is_dirty_git_tree('upload'):
  3631. return 1
  3632. options.reviewers = cleanup_list(options.reviewers)
  3633. options.tbrs = cleanup_list(options.tbrs)
  3634. options.cc = cleanup_list(options.cc)
  3635. if options.edit_description and options.force:
  3636. parser.error('Only one of --force and --edit-description allowed')
  3637. if options.message_file:
  3638. if options.message:
  3639. parser.error('Only one of --message and --message-file allowed.')
  3640. options.message = gclient_utils.FileRead(options.message_file)
  3641. if ([options.cq_dry_run,
  3642. options.use_commit_queue,
  3643. options.retry_failed].count(True) > 1):
  3644. parser.error('Only one of --use-commit-queue, --cq-dry-run, or '
  3645. '--retry-failed is allowed.')
  3646. if options.skip_title and options.title:
  3647. parser.error('Only one of --title and --skip-title allowed.')
  3648. if options.use_commit_queue:
  3649. options.send_mail = True
  3650. if options.squash is None:
  3651. # Load default for user, repo, squash=true, in this order.
  3652. options.squash = settings.GetSquashGerritUploads()
  3653. cl = Changelist(branchref=options.target_branch)
  3654. # Warm change details cache now to avoid RPCs later, reducing latency for
  3655. # developers.
  3656. if cl.GetIssue():
  3657. cl._GetChangeDetail(
  3658. ['DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS'])
  3659. if options.retry_failed and not cl.GetIssue():
  3660. print('No previous patchsets, so --retry-failed has no effect.')
  3661. options.retry_failed = False
  3662. # cl.GetMostRecentPatchset uses cached information, and can return the last
  3663. # patchset before upload. Calling it here makes it clear that it's the
  3664. # last patchset before upload. Note that GetMostRecentPatchset will fail
  3665. # if no CL has been uploaded yet.
  3666. if options.retry_failed:
  3667. patchset = cl.GetMostRecentPatchset()
  3668. ret = cl.CMDUpload(options, args, orig_args)
  3669. if options.retry_failed:
  3670. if ret != 0:
  3671. print('Upload failed, so --retry-failed has no effect.')
  3672. return ret
  3673. builds, _ = _fetch_latest_builds(
  3674. cl, options.buildbucket_host, latest_patchset=patchset)
  3675. jobs = _filter_failed_for_retry(builds)
  3676. if len(jobs) == 0:
  3677. print('No failed tryjobs, so --retry-failed has no effect.')
  3678. return ret
  3679. _trigger_tryjobs(cl, jobs, options, patchset + 1)
  3680. return ret
  3681. @subcommand.usage('--description=<description file>')
  3682. @metrics.collector.collect_metrics('git cl split')
  3683. def CMDsplit(parser, args):
  3684. """Splits a branch into smaller branches and uploads CLs.
  3685. Creates a branch and uploads a CL for each group of files modified in the
  3686. current branch that share a common OWNERS file. In the CL description and
  3687. comment, the string '$directory', is replaced with the directory containing
  3688. the shared OWNERS file.
  3689. """
  3690. parser.add_option('-d', '--description', dest='description_file',
  3691. help='A text file containing a CL description in which '
  3692. '$directory will be replaced by each CL\'s directory.')
  3693. parser.add_option('-c', '--comment', dest='comment_file',
  3694. help='A text file containing a CL comment.')
  3695. parser.add_option('-n', '--dry-run', dest='dry_run', action='store_true',
  3696. default=False,
  3697. help='List the files and reviewers for each CL that would '
  3698. 'be created, but don\'t create branches or CLs.')
  3699. parser.add_option('--cq-dry-run', action='store_true',
  3700. help='If set, will do a cq dry run for each uploaded CL. '
  3701. 'Please be careful when doing this; more than ~10 CLs '
  3702. 'has the potential to overload our build '
  3703. 'infrastructure. Try to upload these not during high '
  3704. 'load times (usually 11-3 Mountain View time). Email '
  3705. 'infra-dev@chromium.org with any questions.')
  3706. parser.add_option('-a', '--enable-auto-submit', action='store_true',
  3707. default=True,
  3708. help='Sends your change to the CQ after an approval. Only '
  3709. 'works on repos that have the Auto-Submit label '
  3710. 'enabled')
  3711. options, _ = parser.parse_args(args)
  3712. if not options.description_file:
  3713. parser.error('No --description flag specified.')
  3714. def WrappedCMDupload(args):
  3715. return CMDupload(OptionParser(), args)
  3716. return split_cl.SplitCl(
  3717. options.description_file, options.comment_file, Changelist,
  3718. WrappedCMDupload, options.dry_run, options.cq_dry_run,
  3719. options.enable_auto_submit, settings.GetRoot())
  3720. @subcommand.usage('DEPRECATED')
  3721. @metrics.collector.collect_metrics('git cl commit')
  3722. def CMDdcommit(parser, args):
  3723. """DEPRECATED: Used to commit the current changelist via git-svn."""
  3724. message = ('git-cl no longer supports committing to SVN repositories via '
  3725. 'git-svn. You probably want to use `git cl land` instead.')
  3726. print(message)
  3727. return 1
  3728. @subcommand.usage('[upstream branch to apply against]')
  3729. @metrics.collector.collect_metrics('git cl land')
  3730. def CMDland(parser, args):
  3731. """Commits the current changelist via git.
  3732. In case of Gerrit, uses Gerrit REST api to "submit" the issue, which pushes
  3733. upstream and closes the issue automatically and atomically.
  3734. """
  3735. parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
  3736. help='bypass upload presubmit hook')
  3737. parser.add_option('-f', '--force', action='store_true', dest='force',
  3738. help="force yes to questions (don't prompt)")
  3739. parser.add_option('--parallel', action='store_true',
  3740. help='Run all tests specified by input_api.RunTests in all '
  3741. 'PRESUBMIT files in parallel.')
  3742. parser.add_option('--resultdb', action='store_true',
  3743. help='Run presubmit checks in the ResultSink environment '
  3744. 'and send results to the ResultDB database.')
  3745. parser.add_option('--realm', help='LUCI realm if reporting to ResultDB')
  3746. (options, args) = parser.parse_args(args)
  3747. cl = Changelist()
  3748. if not cl.GetIssue():
  3749. DieWithError('You must upload the change first to Gerrit.\n'
  3750. ' If you would rather have `git cl land` upload '
  3751. 'automatically for you, see http://crbug.com/642759')
  3752. return cl.CMDLand(options.force, options.bypass_hooks, options.verbose,
  3753. options.parallel, options.resultdb, options.realm)
  3754. @subcommand.usage('<patch url or issue id or issue url>')
  3755. @metrics.collector.collect_metrics('git cl patch')
  3756. def CMDpatch(parser, args):
  3757. """Patches in a code review."""
  3758. parser.add_option('-b', dest='newbranch',
  3759. help='create a new branch off trunk for the patch')
  3760. parser.add_option('-f', '--force', action='store_true',
  3761. help='overwrite state on the current or chosen branch')
  3762. parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit',
  3763. help='don\'t commit after patch applies.')
  3764. group = optparse.OptionGroup(
  3765. parser,
  3766. 'Options for continuing work on the current issue uploaded from a '
  3767. 'different clone (e.g. different machine). Must be used independently '
  3768. 'from the other options. No issue number should be specified, and the '
  3769. 'branch must have an issue number associated with it')
  3770. group.add_option('--reapply', action='store_true', dest='reapply',
  3771. help='Reset the branch and reapply the issue.\n'
  3772. 'CAUTION: This will undo any local changes in this '
  3773. 'branch')
  3774. group.add_option('--pull', action='store_true', dest='pull',
  3775. help='Performs a pull before reapplying.')
  3776. parser.add_option_group(group)
  3777. (options, args) = parser.parse_args(args)
  3778. if options.reapply:
  3779. if options.newbranch:
  3780. parser.error('--reapply works on the current branch only.')
  3781. if len(args) > 0:
  3782. parser.error('--reapply implies no additional arguments.')
  3783. cl = Changelist()
  3784. if not cl.GetIssue():
  3785. parser.error('Current branch must have an associated issue.')
  3786. upstream = cl.GetUpstreamBranch()
  3787. if upstream is None:
  3788. parser.error('No upstream branch specified. Cannot reset branch.')
  3789. RunGit(['reset', '--hard', upstream])
  3790. if options.pull:
  3791. RunGit(['pull'])
  3792. target_issue_arg = ParseIssueNumberArgument(cl.GetIssue())
  3793. return cl.CMDPatchWithParsedIssue(target_issue_arg, options.nocommit, False,
  3794. False)
  3795. if len(args) != 1 or not args[0]:
  3796. parser.error('Must specify issue number or URL.')
  3797. target_issue_arg = ParseIssueNumberArgument(args[0])
  3798. if not target_issue_arg.valid:
  3799. parser.error('Invalid issue ID or URL.')
  3800. # We don't want uncommitted changes mixed up with the patch.
  3801. if git_common.is_dirty_git_tree('patch'):
  3802. return 1
  3803. if options.newbranch:
  3804. if options.force:
  3805. RunGit(['branch', '-D', options.newbranch],
  3806. stderr=subprocess2.PIPE, error_ok=True)
  3807. git_new_branch.create_new_branch(options.newbranch)
  3808. cl = Changelist(
  3809. codereview_host=target_issue_arg.hostname, issue=target_issue_arg.issue)
  3810. if not args[0].isdigit():
  3811. print('canonical issue/change URL: %s\n' % cl.GetIssueURL())
  3812. return cl.CMDPatchWithParsedIssue(target_issue_arg, options.nocommit,
  3813. options.force, options.newbranch)
  3814. def GetTreeStatus(url=None):
  3815. """Fetches the tree status and returns either 'open', 'closed',
  3816. 'unknown' or 'unset'."""
  3817. url = url or settings.GetTreeStatusUrl(error_ok=True)
  3818. if url:
  3819. status = str(urllib.request.urlopen(url).read().lower())
  3820. if status.find('closed') != -1 or status == '0':
  3821. return 'closed'
  3822. elif status.find('open') != -1 or status == '1':
  3823. return 'open'
  3824. return 'unknown'
  3825. return 'unset'
  3826. def GetTreeStatusReason():
  3827. """Fetches the tree status from a json url and returns the message
  3828. with the reason for the tree to be opened or closed."""
  3829. url = settings.GetTreeStatusUrl()
  3830. json_url = urllib.parse.urljoin(url, '/current?format=json')
  3831. connection = urllib.request.urlopen(json_url)
  3832. status = json.loads(connection.read())
  3833. connection.close()
  3834. return status['message']
  3835. @metrics.collector.collect_metrics('git cl tree')
  3836. def CMDtree(parser, args):
  3837. """Shows the status of the tree."""
  3838. _, args = parser.parse_args(args)
  3839. status = GetTreeStatus()
  3840. if 'unset' == status:
  3841. print('You must configure your tree status URL by running "git cl config".')
  3842. return 2
  3843. print('The tree is %s' % status)
  3844. print()
  3845. print(GetTreeStatusReason())
  3846. if status != 'open':
  3847. return 1
  3848. return 0
  3849. @metrics.collector.collect_metrics('git cl try')
  3850. def CMDtry(parser, args):
  3851. """Triggers tryjobs using either Buildbucket or CQ dry run."""
  3852. group = optparse.OptionGroup(parser, 'Tryjob options')
  3853. group.add_option(
  3854. '-b', '--bot', action='append',
  3855. help=('IMPORTANT: specify ONE builder per --bot flag. Use it multiple '
  3856. 'times to specify multiple builders. ex: '
  3857. '"-b win_rel -b win_layout". See '
  3858. 'the try server waterfall for the builders name and the tests '
  3859. 'available.'))
  3860. group.add_option(
  3861. '-B', '--bucket', default='',
  3862. help=('Buildbucket bucket to send the try requests.'))
  3863. group.add_option(
  3864. '-r', '--revision',
  3865. help='Revision to use for the tryjob; default: the revision will '
  3866. 'be determined by the try recipe that builder runs, which usually '
  3867. 'defaults to HEAD of origin/master or origin/main')
  3868. group.add_option(
  3869. '-c', '--clobber', action='store_true', default=False,
  3870. help='Force a clobber before building; that is don\'t do an '
  3871. 'incremental build')
  3872. group.add_option(
  3873. '--category', default='git_cl_try', help='Specify custom build category.')
  3874. group.add_option(
  3875. '--project',
  3876. help='Override which project to use. Projects are defined '
  3877. 'in recipe to determine to which repository or directory to '
  3878. 'apply the patch')
  3879. group.add_option(
  3880. '-p', '--property', dest='properties', action='append', default=[],
  3881. help='Specify generic properties in the form -p key1=value1 -p '
  3882. 'key2=value2 etc. The value will be treated as '
  3883. 'json if decodable, or as string otherwise. '
  3884. 'NOTE: using this may make your tryjob not usable for CQ, '
  3885. 'which will then schedule another tryjob with default properties')
  3886. group.add_option(
  3887. '--buildbucket-host', default='cr-buildbucket.appspot.com',
  3888. help='Host of buildbucket. The default host is %default.')
  3889. parser.add_option_group(group)
  3890. parser.add_option(
  3891. '-R', '--retry-failed', action='store_true', default=False,
  3892. help='Retry failed jobs from the latest set of tryjobs. '
  3893. 'Not allowed with --bucket and --bot options.')
  3894. parser.add_option(
  3895. '-i', '--issue', type=int,
  3896. help='Operate on this issue instead of the current branch\'s implicit '
  3897. 'issue.')
  3898. options, args = parser.parse_args(args)
  3899. # Make sure that all properties are prop=value pairs.
  3900. bad_params = [x for x in options.properties if '=' not in x]
  3901. if bad_params:
  3902. parser.error('Got properties with missing "=": %s' % bad_params)
  3903. if args:
  3904. parser.error('Unknown arguments: %s' % args)
  3905. cl = Changelist(issue=options.issue)
  3906. if not cl.GetIssue():
  3907. parser.error('Need to upload first.')
  3908. # HACK: warm up Gerrit change detail cache to save on RPCs.
  3909. cl._GetChangeDetail(['DETAILED_ACCOUNTS', 'ALL_REVISIONS'])
  3910. error_message = cl.CannotTriggerTryJobReason()
  3911. if error_message:
  3912. parser.error('Can\'t trigger tryjobs: %s' % error_message)
  3913. if options.bot:
  3914. if options.retry_failed:
  3915. parser.error('--bot is not compatible with --retry-failed.')
  3916. if not options.bucket:
  3917. parser.error('A bucket (e.g. "chromium/try") is required.')
  3918. triggered = [b for b in options.bot if 'triggered' in b]
  3919. if triggered:
  3920. parser.error(
  3921. 'Cannot schedule builds on triggered bots: %s.\n'
  3922. 'This type of bot requires an initial job from a parent (usually a '
  3923. 'builder). Schedule a job on the parent instead.\n' % triggered)
  3924. if options.bucket.startswith('.master'):
  3925. parser.error('Buildbot masters are not supported.')
  3926. project, bucket = _parse_bucket(options.bucket)
  3927. if project is None or bucket is None:
  3928. parser.error('Invalid bucket: %s.' % options.bucket)
  3929. jobs = sorted((project, bucket, bot) for bot in options.bot)
  3930. elif options.retry_failed:
  3931. print('Searching for failed tryjobs...')
  3932. builds, patchset = _fetch_latest_builds(cl, options.buildbucket_host)
  3933. if options.verbose:
  3934. print('Got %d builds in patchset #%d' % (len(builds), patchset))
  3935. jobs = _filter_failed_for_retry(builds)
  3936. if not jobs:
  3937. print('There are no failed jobs in the latest set of jobs '
  3938. '(patchset #%d), doing nothing.' % patchset)
  3939. return 0
  3940. num_builders = len(jobs)
  3941. if num_builders > 10:
  3942. confirm_or_exit('There are %d builders with failed builds.'
  3943. % num_builders, action='continue')
  3944. else:
  3945. if options.verbose:
  3946. print('git cl try with no bots now defaults to CQ dry run.')
  3947. print('Scheduling CQ dry run on: %s' % cl.GetIssueURL())
  3948. return cl.SetCQState(_CQState.DRY_RUN)
  3949. patchset = cl.GetMostRecentPatchset()
  3950. try:
  3951. _trigger_tryjobs(cl, jobs, options, patchset)
  3952. except BuildbucketResponseException as ex:
  3953. print('ERROR: %s' % ex)
  3954. return 1
  3955. return 0
  3956. @metrics.collector.collect_metrics('git cl try-results')
  3957. def CMDtry_results(parser, args):
  3958. """Prints info about results for tryjobs associated with the current CL."""
  3959. group = optparse.OptionGroup(parser, 'Tryjob results options')
  3960. group.add_option(
  3961. '-p', '--patchset', type=int, help='patchset number if not current.')
  3962. group.add_option(
  3963. '--print-master', action='store_true', help='print master name as well.')
  3964. group.add_option(
  3965. '--color', action='store_true', default=setup_color.IS_TTY,
  3966. help='force color output, useful when piping output.')
  3967. group.add_option(
  3968. '--buildbucket-host', default='cr-buildbucket.appspot.com',
  3969. help='Host of buildbucket. The default host is %default.')
  3970. group.add_option(
  3971. '--json', help=('Path of JSON output file to write tryjob results to,'
  3972. 'or "-" for stdout.'))
  3973. parser.add_option_group(group)
  3974. parser.add_option(
  3975. '-i', '--issue', type=int,
  3976. help='Operate on this issue instead of the current branch\'s implicit '
  3977. 'issue.')
  3978. options, args = parser.parse_args(args)
  3979. if args:
  3980. parser.error('Unrecognized args: %s' % ' '.join(args))
  3981. cl = Changelist(issue=options.issue)
  3982. if not cl.GetIssue():
  3983. parser.error('Need to upload first.')
  3984. patchset = options.patchset
  3985. if not patchset:
  3986. patchset = cl.GetMostRecentDryRunPatchset()
  3987. if not patchset:
  3988. parser.error('Code review host doesn\'t know about issue %s. '
  3989. 'No access to issue or wrong issue number?\n'
  3990. 'Either upload first, or pass --patchset explicitly.' %
  3991. cl.GetIssue())
  3992. try:
  3993. jobs = _fetch_tryjobs(cl, options.buildbucket_host, patchset)
  3994. except BuildbucketResponseException as ex:
  3995. print('Buildbucket error: %s' % ex)
  3996. return 1
  3997. if options.json:
  3998. write_json(options.json, jobs)
  3999. else:
  4000. _print_tryjobs(options, jobs)
  4001. return 0
  4002. @subcommand.usage('[new upstream branch]')
  4003. @metrics.collector.collect_metrics('git cl upstream')
  4004. def CMDupstream(parser, args):
  4005. """Prints or sets the name of the upstream branch, if any."""
  4006. _, args = parser.parse_args(args)
  4007. if len(args) > 1:
  4008. parser.error('Unrecognized args: %s' % ' '.join(args))
  4009. cl = Changelist()
  4010. if args:
  4011. # One arg means set upstream branch.
  4012. branch = cl.GetBranch()
  4013. RunGit(['branch', '--set-upstream-to', args[0], branch])
  4014. cl = Changelist()
  4015. print('Upstream branch set to %s' % (cl.GetUpstreamBranch(),))
  4016. # Clear configured merge-base, if there is one.
  4017. git_common.remove_merge_base(branch)
  4018. else:
  4019. print(cl.GetUpstreamBranch())
  4020. return 0
  4021. @metrics.collector.collect_metrics('git cl web')
  4022. def CMDweb(parser, args):
  4023. """Opens the current CL in the web browser."""
  4024. _, args = parser.parse_args(args)
  4025. if args:
  4026. parser.error('Unrecognized args: %s' % ' '.join(args))
  4027. issue_url = Changelist().GetIssueURL()
  4028. if not issue_url:
  4029. print('ERROR No issue to open', file=sys.stderr)
  4030. return 1
  4031. # Redirect I/O before invoking browser to hide its output. For example, this
  4032. # allows us to hide the "Created new window in existing browser session."
  4033. # message from Chrome. Based on https://stackoverflow.com/a/2323563.
  4034. saved_stdout = os.dup(1)
  4035. saved_stderr = os.dup(2)
  4036. os.close(1)
  4037. os.close(2)
  4038. os.open(os.devnull, os.O_RDWR)
  4039. try:
  4040. webbrowser.open(issue_url)
  4041. finally:
  4042. os.dup2(saved_stdout, 1)
  4043. os.dup2(saved_stderr, 2)
  4044. return 0
  4045. @metrics.collector.collect_metrics('git cl set-commit')
  4046. def CMDset_commit(parser, args):
  4047. """Sets the commit bit to trigger the CQ."""
  4048. parser.add_option('-d', '--dry-run', action='store_true',
  4049. help='trigger in dry run mode')
  4050. parser.add_option('-c', '--clear', action='store_true',
  4051. help='stop CQ run, if any')
  4052. parser.add_option(
  4053. '-i', '--issue', type=int,
  4054. help='Operate on this issue instead of the current branch\'s implicit '
  4055. 'issue.')
  4056. options, args = parser.parse_args(args)
  4057. if args:
  4058. parser.error('Unrecognized args: %s' % ' '.join(args))
  4059. if options.dry_run and options.clear:
  4060. parser.error('Only one of --dry-run and --clear are allowed.')
  4061. cl = Changelist(issue=options.issue)
  4062. if options.clear:
  4063. state = _CQState.NONE
  4064. elif options.dry_run:
  4065. state = _CQState.DRY_RUN
  4066. else:
  4067. state = _CQState.COMMIT
  4068. if not cl.GetIssue():
  4069. parser.error('Must upload the issue first.')
  4070. cl.SetCQState(state)
  4071. return 0
  4072. @metrics.collector.collect_metrics('git cl set-close')
  4073. def CMDset_close(parser, args):
  4074. """Closes the issue."""
  4075. parser.add_option(
  4076. '-i', '--issue', type=int,
  4077. help='Operate on this issue instead of the current branch\'s implicit '
  4078. 'issue.')
  4079. options, args = parser.parse_args(args)
  4080. if args:
  4081. parser.error('Unrecognized args: %s' % ' '.join(args))
  4082. cl = Changelist(issue=options.issue)
  4083. # Ensure there actually is an issue to close.
  4084. if not cl.GetIssue():
  4085. DieWithError('ERROR: No issue to close.')
  4086. cl.CloseIssue()
  4087. return 0
  4088. @metrics.collector.collect_metrics('git cl diff')
  4089. def CMDdiff(parser, args):
  4090. """Shows differences between local tree and last upload."""
  4091. parser.add_option(
  4092. '--stat',
  4093. action='store_true',
  4094. dest='stat',
  4095. help='Generate a diffstat')
  4096. options, args = parser.parse_args(args)
  4097. if args:
  4098. parser.error('Unrecognized args: %s' % ' '.join(args))
  4099. cl = Changelist()
  4100. issue = cl.GetIssue()
  4101. branch = cl.GetBranch()
  4102. if not issue:
  4103. DieWithError('No issue found for current branch (%s)' % branch)
  4104. base = cl._GitGetBranchConfigValue('last-upload-hash')
  4105. if not base:
  4106. base = cl._GitGetBranchConfigValue('gerritsquashhash')
  4107. if not base:
  4108. detail = cl._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'])
  4109. revision_info = detail['revisions'][detail['current_revision']]
  4110. fetch_info = revision_info['fetch']['http']
  4111. RunGit(['fetch', fetch_info['url'], fetch_info['ref']])
  4112. base = 'FETCH_HEAD'
  4113. cmd = ['git', 'diff']
  4114. if options.stat:
  4115. cmd.append('--stat')
  4116. cmd.append(base)
  4117. subprocess2.check_call(cmd)
  4118. return 0
  4119. @metrics.collector.collect_metrics('git cl owners')
  4120. def CMDowners(parser, args):
  4121. """Finds potential owners for reviewing."""
  4122. parser.add_option(
  4123. '--ignore-current',
  4124. action='store_true',
  4125. help='Ignore the CL\'s current reviewers and start from scratch.')
  4126. parser.add_option(
  4127. '--ignore-self',
  4128. action='store_true',
  4129. help='Do not consider CL\'s author as an owners.')
  4130. parser.add_option(
  4131. '--no-color',
  4132. action='store_true',
  4133. help='Use this option to disable color output')
  4134. parser.add_option(
  4135. '--batch',
  4136. action='store_true',
  4137. help='Do not run interactively, just suggest some')
  4138. # TODO: Consider moving this to another command, since other
  4139. # git-cl owners commands deal with owners for a given CL.
  4140. parser.add_option(
  4141. '--show-all',
  4142. action='store_true',
  4143. help='Show all owners for a particular file')
  4144. options, args = parser.parse_args(args)
  4145. cl = Changelist()
  4146. author = cl.GetAuthor()
  4147. if options.show_all:
  4148. if len(args) == 0:
  4149. print('No files specified for --show-all. Nothing to do.')
  4150. return 0
  4151. owners_by_path = cl.owners_client.BatchListOwners(args)
  4152. for path in args:
  4153. print('Owners for %s:' % path)
  4154. print('\n'.join(
  4155. ' - %s' % owner
  4156. for owner in owners_by_path.get(path, ['No owners found'])))
  4157. return 0
  4158. if args:
  4159. if len(args) > 1:
  4160. parser.error('Unknown args.')
  4161. base_branch = args[0]
  4162. else:
  4163. # Default to diffing against the common ancestor of the upstream branch.
  4164. base_branch = cl.GetCommonAncestorWithUpstream()
  4165. affected_files = cl.GetAffectedFiles(base_branch)
  4166. if options.batch:
  4167. owners = cl.owners_client.SuggestOwners(affected_files, exclude=[author])
  4168. print('\n'.join(owners))
  4169. return 0
  4170. return owners_finder.OwnersFinder(
  4171. affected_files,
  4172. author,
  4173. [] if options.ignore_current else cl.GetReviewers(),
  4174. cl.owners_client,
  4175. disable_color=options.no_color,
  4176. ignore_author=options.ignore_self).run()
  4177. def BuildGitDiffCmd(diff_type, upstream_commit, args, allow_prefix=False):
  4178. """Generates a diff command."""
  4179. # Generate diff for the current branch's changes.
  4180. diff_cmd = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff']
  4181. if allow_prefix:
  4182. # explicitly setting --src-prefix and --dst-prefix is necessary in the
  4183. # case that diff.noprefix is set in the user's git config.
  4184. diff_cmd += ['--src-prefix=a/', '--dst-prefix=b/']
  4185. else:
  4186. diff_cmd += ['--no-prefix']
  4187. diff_cmd += [diff_type, upstream_commit, '--']
  4188. if args:
  4189. for arg in args:
  4190. if os.path.isdir(arg) or os.path.isfile(arg):
  4191. diff_cmd.append(arg)
  4192. else:
  4193. DieWithError('Argument "%s" is not a file or a directory' % arg)
  4194. return diff_cmd
  4195. def _RunClangFormatDiff(opts, clang_diff_files, top_dir, upstream_commit):
  4196. """Runs clang-format-diff and sets a return value if necessary."""
  4197. if not clang_diff_files:
  4198. return 0
  4199. # Set to 2 to signal to CheckPatchFormatted() that this patch isn't
  4200. # formatted. This is used to block during the presubmit.
  4201. return_value = 0
  4202. # Locate the clang-format binary in the checkout
  4203. try:
  4204. clang_format_tool = clang_format.FindClangFormatToolInChromiumTree()
  4205. except clang_format.NotFoundError as e:
  4206. DieWithError(e)
  4207. if opts.full or settings.GetFormatFullByDefault():
  4208. cmd = [clang_format_tool]
  4209. if not opts.dry_run and not opts.diff:
  4210. cmd.append('-i')
  4211. if opts.dry_run:
  4212. for diff_file in clang_diff_files:
  4213. with open(diff_file, 'r') as myfile:
  4214. code = myfile.read().replace('\r\n', '\n')
  4215. stdout = RunCommand(cmd + [diff_file], cwd=top_dir)
  4216. stdout = stdout.replace('\r\n', '\n')
  4217. if opts.diff:
  4218. sys.stdout.write(stdout)
  4219. if code != stdout:
  4220. return_value = 2
  4221. else:
  4222. stdout = RunCommand(cmd + clang_diff_files, cwd=top_dir)
  4223. if opts.diff:
  4224. sys.stdout.write(stdout)
  4225. else:
  4226. try:
  4227. script = clang_format.FindClangFormatScriptInChromiumTree(
  4228. 'clang-format-diff.py')
  4229. except clang_format.NotFoundError as e:
  4230. DieWithError(e)
  4231. cmd = ['vpython', script, '-p0']
  4232. if not opts.dry_run and not opts.diff:
  4233. cmd.append('-i')
  4234. diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, clang_diff_files)
  4235. diff_output = RunGit(diff_cmd).encode('utf-8')
  4236. env = os.environ.copy()
  4237. env['PATH'] = (
  4238. str(os.path.dirname(clang_format_tool)) + os.pathsep + env['PATH'])
  4239. stdout = RunCommand(
  4240. cmd, stdin=diff_output, cwd=top_dir, env=env,
  4241. shell=sys.platform.startswith('win32'))
  4242. if opts.diff:
  4243. sys.stdout.write(stdout)
  4244. if opts.dry_run and len(stdout) > 0:
  4245. return_value = 2
  4246. return return_value
  4247. def MatchingFileType(file_name, extensions):
  4248. """Returns True if the file name ends with one of the given extensions."""
  4249. return bool([ext for ext in extensions if file_name.lower().endswith(ext)])
  4250. @subcommand.usage('[files or directories to diff]')
  4251. @metrics.collector.collect_metrics('git cl format')
  4252. def CMDformat(parser, args):
  4253. """Runs auto-formatting tools (clang-format etc.) on the diff."""
  4254. CLANG_EXTS = ['.cc', '.cpp', '.h', '.m', '.mm', '.proto', '.java']
  4255. GN_EXTS = ['.gn', '.gni', '.typemap']
  4256. parser.add_option('--full', action='store_true',
  4257. help='Reformat the full content of all touched files')
  4258. parser.add_option('--dry-run', action='store_true',
  4259. help='Don\'t modify any file on disk.')
  4260. parser.add_option(
  4261. '--no-clang-format',
  4262. dest='clang_format',
  4263. action='store_false',
  4264. default=True,
  4265. help='Disables formatting of various file types using clang-format.')
  4266. parser.add_option(
  4267. '--python',
  4268. action='store_true',
  4269. default=None,
  4270. help='Enables python formatting on all python files.')
  4271. parser.add_option(
  4272. '--no-python',
  4273. action='store_true',
  4274. default=False,
  4275. help='Disables python formatting on all python files. '
  4276. 'If neither --python or --no-python are set, python files that have a '
  4277. '.style.yapf file in an ancestor directory will be formatted. '
  4278. 'It is an error to set both.')
  4279. parser.add_option(
  4280. '--js',
  4281. action='store_true',
  4282. help='Format javascript code with clang-format. '
  4283. 'Has no effect if --no-clang-format is set.')
  4284. parser.add_option('--diff', action='store_true',
  4285. help='Print diff to stdout rather than modifying files.')
  4286. parser.add_option('--presubmit', action='store_true',
  4287. help='Used when running the script from a presubmit.')
  4288. opts, args = parser.parse_args(args)
  4289. if opts.python is not None and opts.no_python:
  4290. raise parser.error('Cannot set both --python and --no-python')
  4291. if opts.no_python:
  4292. opts.python = False
  4293. # Normalize any remaining args against the current path, so paths relative to
  4294. # the current directory are still resolved as expected.
  4295. args = [os.path.join(os.getcwd(), arg) for arg in args]
  4296. # git diff generates paths against the root of the repository. Change
  4297. # to that directory so clang-format can find files even within subdirs.
  4298. rel_base_path = settings.GetRelativeRoot()
  4299. if rel_base_path:
  4300. os.chdir(rel_base_path)
  4301. # Grab the merge-base commit, i.e. the upstream commit of the current
  4302. # branch when it was created or the last time it was rebased. This is
  4303. # to cover the case where the user may have called "git fetch origin",
  4304. # moving the origin branch to a newer commit, but hasn't rebased yet.
  4305. upstream_commit = None
  4306. cl = Changelist()
  4307. upstream_branch = cl.GetUpstreamBranch()
  4308. if upstream_branch:
  4309. upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch])
  4310. upstream_commit = upstream_commit.strip()
  4311. if not upstream_commit:
  4312. DieWithError('Could not find base commit for this branch. '
  4313. 'Are you in detached state?')
  4314. changed_files_cmd = BuildGitDiffCmd('--name-only', upstream_commit, args)
  4315. diff_output = RunGit(changed_files_cmd)
  4316. diff_files = diff_output.splitlines()
  4317. # Filter out files deleted by this CL
  4318. diff_files = [x for x in diff_files if os.path.isfile(x)]
  4319. if opts.js:
  4320. CLANG_EXTS.extend(['.js', '.ts'])
  4321. clang_diff_files = []
  4322. if opts.clang_format:
  4323. clang_diff_files = [
  4324. x for x in diff_files if MatchingFileType(x, CLANG_EXTS)
  4325. ]
  4326. python_diff_files = [x for x in diff_files if MatchingFileType(x, ['.py'])]
  4327. gn_diff_files = [x for x in diff_files if MatchingFileType(x, GN_EXTS)]
  4328. top_dir = settings.GetRoot()
  4329. return_value = _RunClangFormatDiff(opts, clang_diff_files, top_dir,
  4330. upstream_commit)
  4331. # Similar code to above, but using yapf on .py files rather than clang-format
  4332. # on C/C++ files
  4333. py_explicitly_disabled = opts.python is not None and not opts.python
  4334. if python_diff_files and not py_explicitly_disabled:
  4335. depot_tools_path = os.path.dirname(os.path.abspath(__file__))
  4336. yapf_tool = os.path.join(depot_tools_path, 'yapf')
  4337. # Used for caching.
  4338. yapf_configs = {}
  4339. for f in python_diff_files:
  4340. # Find the yapf style config for the current file, defaults to depot
  4341. # tools default.
  4342. _FindYapfConfigFile(f, yapf_configs, top_dir)
  4343. # Turn on python formatting by default if a yapf config is specified.
  4344. # This breaks in the case of this repo though since the specified
  4345. # style file is also the global default.
  4346. if opts.python is None:
  4347. filtered_py_files = []
  4348. for f in python_diff_files:
  4349. if _FindYapfConfigFile(f, yapf_configs, top_dir) is not None:
  4350. filtered_py_files.append(f)
  4351. else:
  4352. filtered_py_files = python_diff_files
  4353. # Note: yapf still seems to fix indentation of the entire file
  4354. # even if line ranges are specified.
  4355. # See https://github.com/google/yapf/issues/499
  4356. if not opts.full and filtered_py_files:
  4357. py_line_diffs = _ComputeDiffLineRanges(filtered_py_files, upstream_commit)
  4358. yapfignore_patterns = _GetYapfIgnorePatterns(top_dir)
  4359. filtered_py_files = _FilterYapfIgnoredFiles(filtered_py_files,
  4360. yapfignore_patterns)
  4361. for f in filtered_py_files:
  4362. yapf_style = _FindYapfConfigFile(f, yapf_configs, top_dir)
  4363. # Default to pep8 if not .style.yapf is found.
  4364. if not yapf_style:
  4365. yapf_style = 'pep8'
  4366. with open(f, 'r') as py_f:
  4367. if 'python3' in py_f.readline():
  4368. vpython_script = 'vpython3'
  4369. else:
  4370. vpython_script = 'vpython'
  4371. cmd = [vpython_script, yapf_tool, '--style', yapf_style, f]
  4372. has_formattable_lines = False
  4373. if not opts.full:
  4374. # Only run yapf over changed line ranges.
  4375. for diff_start, diff_len in py_line_diffs[f]:
  4376. diff_end = diff_start + diff_len - 1
  4377. # Yapf errors out if diff_end < diff_start but this
  4378. # is a valid line range diff for a removal.
  4379. if diff_end >= diff_start:
  4380. has_formattable_lines = True
  4381. cmd += ['-l', '{}-{}'.format(diff_start, diff_end)]
  4382. # If all line diffs were removals we have nothing to format.
  4383. if not has_formattable_lines:
  4384. continue
  4385. if opts.diff or opts.dry_run:
  4386. cmd += ['--diff']
  4387. # Will return non-zero exit code if non-empty diff.
  4388. stdout = RunCommand(cmd,
  4389. error_ok=True,
  4390. cwd=top_dir,
  4391. shell=sys.platform.startswith('win32'))
  4392. if opts.diff:
  4393. sys.stdout.write(stdout)
  4394. elif len(stdout) > 0:
  4395. return_value = 2
  4396. else:
  4397. cmd += ['-i']
  4398. RunCommand(cmd, cwd=top_dir, shell=sys.platform.startswith('win32'))
  4399. # Format GN build files. Always run on full build files for canonical form.
  4400. if gn_diff_files:
  4401. cmd = ['gn', 'format']
  4402. if opts.dry_run or opts.diff:
  4403. cmd.append('--dry-run')
  4404. for gn_diff_file in gn_diff_files:
  4405. gn_ret = subprocess2.call(cmd + [gn_diff_file],
  4406. shell=sys.platform.startswith('win'),
  4407. cwd=top_dir)
  4408. if opts.dry_run and gn_ret == 2:
  4409. return_value = 2 # Not formatted.
  4410. elif opts.diff and gn_ret == 2:
  4411. # TODO this should compute and print the actual diff.
  4412. print('This change has GN build file diff for ' + gn_diff_file)
  4413. elif gn_ret != 0:
  4414. # For non-dry run cases (and non-2 return values for dry-run), a
  4415. # nonzero error code indicates a failure, probably because the file
  4416. # doesn't parse.
  4417. DieWithError('gn format failed on ' + gn_diff_file +
  4418. '\nTry running `gn format` on this file manually.')
  4419. # Skip the metrics formatting from the global presubmit hook. These files have
  4420. # a separate presubmit hook that issues an error if the files need formatting,
  4421. # whereas the top-level presubmit script merely issues a warning. Formatting
  4422. # these files is somewhat slow, so it's important not to duplicate the work.
  4423. if not opts.presubmit:
  4424. for diff_xml in GetDiffXMLs(diff_files):
  4425. xml_dir = GetMetricsDir(diff_xml)
  4426. if not xml_dir:
  4427. continue
  4428. tool_dir = os.path.join(top_dir, xml_dir)
  4429. pretty_print_tool = os.path.join(tool_dir, 'pretty_print.py')
  4430. cmd = ['vpython', pretty_print_tool, '--non-interactive']
  4431. # If the XML file is histograms.xml or enums.xml, add the xml path to the
  4432. # command as histograms/pretty_print.py now needs a relative path argument
  4433. # after splitting the histograms into multiple directories.
  4434. # For example, in tools/metrics/ukm, pretty-print could be run using:
  4435. # $ python pretty_print.py
  4436. # But in tools/metrics/histogrmas, pretty-print should be run with an
  4437. # additional relative path argument, like:
  4438. # $ python pretty_print.py histograms_xml/UMA/histograms.xml
  4439. # $ python pretty_print.py enums.xml
  4440. # TODO (crbug/1116488): Remove this check after ensuring that the updated
  4441. # version of histograms/pretty_print.py is released.
  4442. filepath_required = os.path.exists(
  4443. os.path.join(tool_dir, 'validate_prefix.py'))
  4444. if (diff_xml.endswith('histograms.xml') or diff_xml.endswith('enums.xml')
  4445. or diff_xml.endswith('histogram_suffixes_list.xml')
  4446. ) and filepath_required:
  4447. cmd.append(diff_xml)
  4448. if opts.dry_run or opts.diff:
  4449. cmd.append('--diff')
  4450. # TODO(isherman): Once this file runs only on Python 3.3+, drop the
  4451. # `shell` param and instead replace `'vpython'` with
  4452. # `shutil.which('frob')` above: https://stackoverflow.com/a/32799942
  4453. stdout = RunCommand(cmd,
  4454. cwd=top_dir,
  4455. shell=sys.platform.startswith('win32'))
  4456. if opts.diff:
  4457. sys.stdout.write(stdout)
  4458. if opts.dry_run and stdout:
  4459. return_value = 2 # Not formatted.
  4460. return return_value
  4461. def GetDiffXMLs(diff_files):
  4462. return [
  4463. os.path.normpath(x) for x in diff_files if MatchingFileType(x, ['.xml'])
  4464. ]
  4465. def GetMetricsDir(diff_xml):
  4466. metrics_xml_dirs = [
  4467. os.path.join('tools', 'metrics', 'actions'),
  4468. os.path.join('tools', 'metrics', 'histograms'),
  4469. os.path.join('tools', 'metrics', 'rappor'),
  4470. os.path.join('tools', 'metrics', 'structured'),
  4471. os.path.join('tools', 'metrics', 'ukm'),
  4472. ]
  4473. for xml_dir in metrics_xml_dirs:
  4474. if diff_xml.startswith(xml_dir):
  4475. return xml_dir
  4476. return None
  4477. @subcommand.usage('<codereview url or issue id>')
  4478. @metrics.collector.collect_metrics('git cl checkout')
  4479. def CMDcheckout(parser, args):
  4480. """Checks out a branch associated with a given Gerrit issue."""
  4481. _, args = parser.parse_args(args)
  4482. if len(args) != 1:
  4483. parser.print_help()
  4484. return 1
  4485. issue_arg = ParseIssueNumberArgument(args[0])
  4486. if not issue_arg.valid:
  4487. parser.error('Invalid issue ID or URL.')
  4488. target_issue = str(issue_arg.issue)
  4489. output = RunGit(['config', '--local', '--get-regexp',
  4490. r'branch\..*\.' + ISSUE_CONFIG_KEY],
  4491. error_ok=True)
  4492. branches = []
  4493. for key, issue in [x.split() for x in output.splitlines()]:
  4494. if issue == target_issue:
  4495. branches.append(re.sub(r'branch\.(.*)\.' + ISSUE_CONFIG_KEY, r'\1', key))
  4496. if len(branches) == 0:
  4497. print('No branch found for issue %s.' % target_issue)
  4498. return 1
  4499. if len(branches) == 1:
  4500. RunGit(['checkout', branches[0]])
  4501. else:
  4502. print('Multiple branches match issue %s:' % target_issue)
  4503. for i in range(len(branches)):
  4504. print('%d: %s' % (i, branches[i]))
  4505. which = gclient_utils.AskForData('Choose by index: ')
  4506. try:
  4507. RunGit(['checkout', branches[int(which)]])
  4508. except (IndexError, ValueError):
  4509. print('Invalid selection, not checking out any branch.')
  4510. return 1
  4511. return 0
  4512. def CMDlol(parser, args):
  4513. # This command is intentionally undocumented.
  4514. print(zlib.decompress(base64.b64decode(
  4515. 'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE'
  4516. 'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9'
  4517. 'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W'
  4518. 'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY')).decode('utf-8'))
  4519. return 0
  4520. class OptionParser(optparse.OptionParser):
  4521. """Creates the option parse and add --verbose support."""
  4522. def __init__(self, *args, **kwargs):
  4523. optparse.OptionParser.__init__(
  4524. self, *args, prog='git cl', version=__version__, **kwargs)
  4525. self.add_option(
  4526. '-v', '--verbose', action='count', default=0,
  4527. help='Use 2 times for more debugging info')
  4528. def parse_args(self, args=None, _values=None):
  4529. try:
  4530. return self._parse_args(args)
  4531. finally:
  4532. # Regardless of success or failure of args parsing, we want to report
  4533. # metrics, but only after logging has been initialized (if parsing
  4534. # succeeded).
  4535. global settings
  4536. settings = Settings()
  4537. if not metrics.DISABLE_METRICS_COLLECTION:
  4538. # GetViewVCUrl ultimately calls logging method.
  4539. project_url = settings.GetViewVCUrl().strip('/+')
  4540. if project_url in metrics_utils.KNOWN_PROJECT_URLS:
  4541. metrics.collector.add('project_urls', [project_url])
  4542. def _parse_args(self, args=None):
  4543. # Create an optparse.Values object that will store only the actual passed
  4544. # options, without the defaults.
  4545. actual_options = optparse.Values()
  4546. _, args = optparse.OptionParser.parse_args(self, args, actual_options)
  4547. # Create an optparse.Values object with the default options.
  4548. options = optparse.Values(self.get_default_values().__dict__)
  4549. # Update it with the options passed by the user.
  4550. options._update_careful(actual_options.__dict__)
  4551. # Store the options passed by the user in an _actual_options attribute.
  4552. # We store only the keys, and not the values, since the values can contain
  4553. # arbitrary information, which might be PII.
  4554. metrics.collector.add('arguments', list(actual_options.__dict__.keys()))
  4555. levels = [logging.WARNING, logging.INFO, logging.DEBUG]
  4556. logging.basicConfig(
  4557. level=levels[min(options.verbose, len(levels) - 1)],
  4558. format='[%(levelname).1s%(asctime)s %(process)d %(thread)d '
  4559. '%(filename)s] %(message)s')
  4560. return options, args
  4561. def main(argv):
  4562. if sys.hexversion < 0x02060000:
  4563. print('\nYour Python version %s is unsupported, please upgrade.\n' %
  4564. (sys.version.split(' ', 1)[0],), file=sys.stderr)
  4565. return 2
  4566. colorize_CMDstatus_doc()
  4567. dispatcher = subcommand.CommandDispatcher(__name__)
  4568. try:
  4569. return dispatcher.execute(OptionParser(), argv)
  4570. except auth.LoginRequiredError as e:
  4571. DieWithError(str(e))
  4572. except urllib.error.HTTPError as e:
  4573. if e.code != 500:
  4574. raise
  4575. DieWithError(
  4576. ('App Engine is misbehaving and returned HTTP %d, again. Keep faith '
  4577. 'and retry or visit go/isgaeup.\n%s') % (e.code, str(e)))
  4578. return 0
  4579. if __name__ == '__main__':
  4580. # These affect sys.stdout, so do it outside of main() to simplify mocks in
  4581. # the unit tests.
  4582. fix_encoding.fix_encoding()
  4583. setup_color.init()
  4584. with metrics.collector.print_notice_and_exit():
  4585. sys.exit(main(sys.argv[1:]))