git_cl.py 194 KB

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