git_cl.py 178 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. # Copyright (C) 2008 Evan Martin <martine@danga.com>
  6. """A git-command for integrating reviews on Rietveld and Gerrit."""
  7. from distutils.version import LooseVersion
  8. from multiprocessing.pool import ThreadPool
  9. import base64
  10. import collections
  11. import glob
  12. import httplib
  13. import json
  14. import logging
  15. import multiprocessing
  16. import optparse
  17. import os
  18. import re
  19. import stat
  20. import sys
  21. import textwrap
  22. import time
  23. import traceback
  24. import urllib
  25. import urllib2
  26. import urlparse
  27. import uuid
  28. import webbrowser
  29. import zlib
  30. try:
  31. import readline # pylint: disable=F0401,W0611
  32. except ImportError:
  33. pass
  34. from third_party import colorama
  35. from third_party import httplib2
  36. from third_party import upload
  37. import auth
  38. from luci_hacks import trigger_luci_job as luci_trigger
  39. import clang_format
  40. import commit_queue
  41. import dart_format
  42. import setup_color
  43. import fix_encoding
  44. import gclient_utils
  45. import gerrit_util
  46. import git_cache
  47. import git_common
  48. import git_footers
  49. import owners
  50. import owners_finder
  51. import presubmit_support
  52. import rietveld
  53. import scm
  54. import subcommand
  55. import subprocess2
  56. import watchlists
  57. __version__ = '1.0'
  58. DEFAULT_SERVER = 'https://codereview.appspot.com'
  59. POSTUPSTREAM_HOOK_PATTERN = '.git/hooks/post-cl-%s'
  60. DESCRIPTION_BACKUP_FILE = '~/.git_cl_description_backup'
  61. GIT_INSTRUCTIONS_URL = 'http://code.google.com/p/chromium/wiki/UsingGit'
  62. REFS_THAT_ALIAS_TO_OTHER_REFS = {
  63. 'refs/remotes/origin/lkgr': 'refs/remotes/origin/master',
  64. 'refs/remotes/origin/lkcr': 'refs/remotes/origin/master',
  65. }
  66. # Valid extensions for files we want to lint.
  67. DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)"
  68. DEFAULT_LINT_IGNORE_REGEX = r"$^"
  69. # Shortcut since it quickly becomes redundant.
  70. Fore = colorama.Fore
  71. # Initialized in main()
  72. settings = None
  73. def DieWithError(message):
  74. print >> sys.stderr, message
  75. sys.exit(1)
  76. def GetNoGitPagerEnv():
  77. env = os.environ.copy()
  78. # 'cat' is a magical git string that disables pagers on all platforms.
  79. env['GIT_PAGER'] = 'cat'
  80. return env
  81. def RunCommand(args, error_ok=False, error_message=None, shell=False, **kwargs):
  82. try:
  83. return subprocess2.check_output(args, shell=shell, **kwargs)
  84. except subprocess2.CalledProcessError as e:
  85. logging.debug('Failed running %s', args)
  86. if not error_ok:
  87. DieWithError(
  88. 'Command "%s" failed.\n%s' % (
  89. ' '.join(args), error_message or e.stdout or ''))
  90. return e.stdout
  91. def RunGit(args, **kwargs):
  92. """Returns stdout."""
  93. return RunCommand(['git'] + args, **kwargs)
  94. def RunGitWithCode(args, suppress_stderr=False):
  95. """Returns return code and stdout."""
  96. try:
  97. if suppress_stderr:
  98. stderr = subprocess2.VOID
  99. else:
  100. stderr = sys.stderr
  101. out, code = subprocess2.communicate(['git'] + args,
  102. env=GetNoGitPagerEnv(),
  103. stdout=subprocess2.PIPE,
  104. stderr=stderr)
  105. return code, out[0]
  106. except ValueError:
  107. # When the subprocess fails, it returns None. That triggers a ValueError
  108. # when trying to unpack the return value into (out, code).
  109. return 1, ''
  110. def RunGitSilent(args):
  111. """Returns stdout, suppresses stderr and ignores the return code."""
  112. return RunGitWithCode(args, suppress_stderr=True)[1]
  113. def IsGitVersionAtLeast(min_version):
  114. prefix = 'git version '
  115. version = RunGit(['--version']).strip()
  116. return (version.startswith(prefix) and
  117. LooseVersion(version[len(prefix):]) >= LooseVersion(min_version))
  118. def BranchExists(branch):
  119. """Return True if specified branch exists."""
  120. code, _ = RunGitWithCode(['rev-parse', '--verify', branch],
  121. suppress_stderr=True)
  122. return not code
  123. def ask_for_data(prompt):
  124. try:
  125. return raw_input(prompt)
  126. except KeyboardInterrupt:
  127. # Hide the exception.
  128. sys.exit(1)
  129. def git_set_branch_value(key, value):
  130. branch = GetCurrentBranch()
  131. if not branch:
  132. return
  133. cmd = ['config']
  134. if isinstance(value, int):
  135. cmd.append('--int')
  136. git_key = 'branch.%s.%s' % (branch, key)
  137. RunGit(cmd + [git_key, str(value)])
  138. def git_get_branch_default(key, default):
  139. branch = GetCurrentBranch()
  140. if branch:
  141. git_key = 'branch.%s.%s' % (branch, key)
  142. (_, stdout) = RunGitWithCode(['config', '--int', '--get', git_key])
  143. try:
  144. return int(stdout.strip())
  145. except ValueError:
  146. pass
  147. return default
  148. def add_git_similarity(parser):
  149. parser.add_option(
  150. '--similarity', metavar='SIM', type='int', action='store',
  151. help='Sets the percentage that a pair of files need to match in order to'
  152. ' be considered copies (default 50)')
  153. parser.add_option(
  154. '--find-copies', action='store_true',
  155. help='Allows git to look for copies.')
  156. parser.add_option(
  157. '--no-find-copies', action='store_false', dest='find_copies',
  158. help='Disallows git from looking for copies.')
  159. old_parser_args = parser.parse_args
  160. def Parse(args):
  161. options, args = old_parser_args(args)
  162. if options.similarity is None:
  163. options.similarity = git_get_branch_default('git-cl-similarity', 50)
  164. else:
  165. print('Note: Saving similarity of %d%% in git config.'
  166. % options.similarity)
  167. git_set_branch_value('git-cl-similarity', options.similarity)
  168. options.similarity = max(0, min(options.similarity, 100))
  169. if options.find_copies is None:
  170. options.find_copies = bool(
  171. git_get_branch_default('git-find-copies', True))
  172. else:
  173. git_set_branch_value('git-find-copies', int(options.find_copies))
  174. print('Using %d%% similarity for rename/copy detection. '
  175. 'Override with --similarity.' % options.similarity)
  176. return options, args
  177. parser.parse_args = Parse
  178. def _get_properties_from_options(options):
  179. properties = dict(x.split('=', 1) for x in options.properties)
  180. for key, val in properties.iteritems():
  181. try:
  182. properties[key] = json.loads(val)
  183. except ValueError:
  184. pass # If a value couldn't be evaluated, treat it as a string.
  185. return properties
  186. def _prefix_master(master):
  187. """Convert user-specified master name to full master name.
  188. Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket
  189. name, while the developers always use shortened master name
  190. (tryserver.chromium.linux) by stripping off the prefix 'master.'. This
  191. function does the conversion for buildbucket migration.
  192. """
  193. prefix = 'master.'
  194. if master.startswith(prefix):
  195. return master
  196. return '%s%s' % (prefix, master)
  197. def _buildbucket_retry(operation_name, http, *args, **kwargs):
  198. """Retries requests to buildbucket service and returns parsed json content."""
  199. try_count = 0
  200. while True:
  201. response, content = http.request(*args, **kwargs)
  202. try:
  203. content_json = json.loads(content)
  204. except ValueError:
  205. content_json = None
  206. # Buildbucket could return an error even if status==200.
  207. if content_json and content_json.get('error'):
  208. error = content_json.get('error')
  209. if error.get('code') == 403:
  210. raise BuildbucketResponseException(
  211. 'Access denied: %s' % error.get('message', ''))
  212. msg = 'Error in response. Reason: %s. Message: %s.' % (
  213. error.get('reason', ''), error.get('message', ''))
  214. raise BuildbucketResponseException(msg)
  215. if response.status == 200:
  216. if not content_json:
  217. raise BuildbucketResponseException(
  218. 'Buildbucket returns invalid json content: %s.\n'
  219. 'Please file bugs at http://crbug.com, label "Infra-BuildBucket".' %
  220. content)
  221. return content_json
  222. if response.status < 500 or try_count >= 2:
  223. raise httplib2.HttpLib2Error(content)
  224. # status >= 500 means transient failures.
  225. logging.debug('Transient errors when %s. Will retry.', operation_name)
  226. time.sleep(0.5 + 1.5*try_count)
  227. try_count += 1
  228. assert False, 'unreachable'
  229. def trigger_luci_job(changelist, masters, options):
  230. """Send a job to run on LUCI."""
  231. issue_props = changelist.GetIssueProperties()
  232. issue = changelist.GetIssue()
  233. patchset = changelist.GetMostRecentPatchset()
  234. for builders_and_tests in sorted(masters.itervalues()):
  235. # TODO(hinoka et al): add support for other properties.
  236. # Currently, this completely ignores testfilter and other properties.
  237. for builder in sorted(builders_and_tests):
  238. luci_trigger.trigger(
  239. builder, 'HEAD', issue, patchset, issue_props['project'])
  240. def trigger_try_jobs(auth_config, changelist, options, masters, category):
  241. rietveld_url = settings.GetDefaultServerUrl()
  242. rietveld_host = urlparse.urlparse(rietveld_url).hostname
  243. authenticator = auth.get_authenticator_for_host(rietveld_host, auth_config)
  244. http = authenticator.authorize(httplib2.Http())
  245. http.force_exception_to_status_code = True
  246. issue_props = changelist.GetIssueProperties()
  247. issue = changelist.GetIssue()
  248. patchset = changelist.GetMostRecentPatchset()
  249. properties = _get_properties_from_options(options)
  250. buildbucket_put_url = (
  251. 'https://{hostname}/_ah/api/buildbucket/v1/builds/batch'.format(
  252. hostname=options.buildbucket_host))
  253. buildset = 'patch/rietveld/{hostname}/{issue}/{patch}'.format(
  254. hostname=rietveld_host,
  255. issue=issue,
  256. patch=patchset)
  257. batch_req_body = {'builds': []}
  258. print_text = []
  259. print_text.append('Tried jobs on:')
  260. for master, builders_and_tests in sorted(masters.iteritems()):
  261. print_text.append('Master: %s' % master)
  262. bucket = _prefix_master(master)
  263. for builder, tests in sorted(builders_and_tests.iteritems()):
  264. print_text.append(' %s: %s' % (builder, tests))
  265. parameters = {
  266. 'builder_name': builder,
  267. 'changes': [{
  268. 'author': {'email': issue_props['owner_email']},
  269. 'revision': options.revision,
  270. }],
  271. 'properties': {
  272. 'category': category,
  273. 'issue': issue,
  274. 'master': master,
  275. 'patch_project': issue_props['project'],
  276. 'patch_storage': 'rietveld',
  277. 'patchset': patchset,
  278. 'reason': options.name,
  279. 'rietveld': rietveld_url,
  280. },
  281. }
  282. if 'presubmit' in builder.lower():
  283. parameters['properties']['dry_run'] = 'true'
  284. if tests:
  285. parameters['properties']['testfilter'] = tests
  286. if properties:
  287. parameters['properties'].update(properties)
  288. if options.clobber:
  289. parameters['properties']['clobber'] = True
  290. batch_req_body['builds'].append(
  291. {
  292. 'bucket': bucket,
  293. 'parameters_json': json.dumps(parameters),
  294. 'client_operation_id': str(uuid.uuid4()),
  295. 'tags': ['builder:%s' % builder,
  296. 'buildset:%s' % buildset,
  297. 'master:%s' % master,
  298. 'user_agent:git_cl_try']
  299. }
  300. )
  301. _buildbucket_retry(
  302. 'triggering tryjobs',
  303. http,
  304. buildbucket_put_url,
  305. 'PUT',
  306. body=json.dumps(batch_req_body),
  307. headers={'Content-Type': 'application/json'}
  308. )
  309. print_text.append('To see results here, run: git cl try-results')
  310. print_text.append('To see results in browser, run: git cl web')
  311. print '\n'.join(print_text)
  312. def fetch_try_jobs(auth_config, changelist, options):
  313. """Fetches tryjobs from buildbucket.
  314. Returns a map from build id to build info as json dictionary.
  315. """
  316. rietveld_url = settings.GetDefaultServerUrl()
  317. rietveld_host = urlparse.urlparse(rietveld_url).hostname
  318. authenticator = auth.get_authenticator_for_host(rietveld_host, auth_config)
  319. if authenticator.has_cached_credentials():
  320. http = authenticator.authorize(httplib2.Http())
  321. else:
  322. print ('Warning: Some results might be missing because %s' %
  323. # Get the message on how to login.
  324. auth.LoginRequiredError(rietveld_host).message)
  325. http = httplib2.Http()
  326. http.force_exception_to_status_code = True
  327. buildset = 'patch/rietveld/{hostname}/{issue}/{patch}'.format(
  328. hostname=rietveld_host,
  329. issue=changelist.GetIssue(),
  330. patch=options.patchset)
  331. params = {'tag': 'buildset:%s' % buildset}
  332. builds = {}
  333. while True:
  334. url = 'https://{hostname}/_ah/api/buildbucket/v1/search?{params}'.format(
  335. hostname=options.buildbucket_host,
  336. params=urllib.urlencode(params))
  337. content = _buildbucket_retry('fetching tryjobs', http, url, 'GET')
  338. for build in content.get('builds', []):
  339. builds[build['id']] = build
  340. if 'next_cursor' in content:
  341. params['start_cursor'] = content['next_cursor']
  342. else:
  343. break
  344. return builds
  345. def print_tryjobs(options, builds):
  346. """Prints nicely result of fetch_try_jobs."""
  347. if not builds:
  348. print 'No tryjobs scheduled'
  349. return
  350. # Make a copy, because we'll be modifying builds dictionary.
  351. builds = builds.copy()
  352. builder_names_cache = {}
  353. def get_builder(b):
  354. try:
  355. return builder_names_cache[b['id']]
  356. except KeyError:
  357. try:
  358. parameters = json.loads(b['parameters_json'])
  359. name = parameters['builder_name']
  360. except (ValueError, KeyError) as error:
  361. print 'WARNING: failed to get builder name for build %s: %s' % (
  362. b['id'], error)
  363. name = None
  364. builder_names_cache[b['id']] = name
  365. return name
  366. def get_bucket(b):
  367. bucket = b['bucket']
  368. if bucket.startswith('master.'):
  369. return bucket[len('master.'):]
  370. return bucket
  371. if options.print_master:
  372. name_fmt = '%%-%ds %%-%ds' % (
  373. max(len(str(get_bucket(b))) for b in builds.itervalues()),
  374. max(len(str(get_builder(b))) for b in builds.itervalues()))
  375. def get_name(b):
  376. return name_fmt % (get_bucket(b), get_builder(b))
  377. else:
  378. name_fmt = '%%-%ds' % (
  379. max(len(str(get_builder(b))) for b in builds.itervalues()))
  380. def get_name(b):
  381. return name_fmt % get_builder(b)
  382. def sort_key(b):
  383. return b['status'], b.get('result'), get_name(b), b.get('url')
  384. def pop(title, f, color=None, **kwargs):
  385. """Pop matching builds from `builds` dict and print them."""
  386. if not options.color or color is None:
  387. colorize = str
  388. else:
  389. colorize = lambda x: '%s%s%s' % (color, x, Fore.RESET)
  390. result = []
  391. for b in builds.values():
  392. if all(b.get(k) == v for k, v in kwargs.iteritems()):
  393. builds.pop(b['id'])
  394. result.append(b)
  395. if result:
  396. print colorize(title)
  397. for b in sorted(result, key=sort_key):
  398. print ' ', colorize('\t'.join(map(str, f(b))))
  399. total = len(builds)
  400. pop(status='COMPLETED', result='SUCCESS',
  401. title='Successes:', color=Fore.GREEN,
  402. f=lambda b: (get_name(b), b.get('url')))
  403. pop(status='COMPLETED', result='FAILURE', failure_reason='INFRA_FAILURE',
  404. title='Infra Failures:', color=Fore.MAGENTA,
  405. f=lambda b: (get_name(b), b.get('url')))
  406. pop(status='COMPLETED', result='FAILURE', failure_reason='BUILD_FAILURE',
  407. title='Failures:', color=Fore.RED,
  408. f=lambda b: (get_name(b), b.get('url')))
  409. pop(status='COMPLETED', result='CANCELED',
  410. title='Canceled:', color=Fore.MAGENTA,
  411. f=lambda b: (get_name(b),))
  412. pop(status='COMPLETED', result='FAILURE',
  413. failure_reason='INVALID_BUILD_DEFINITION',
  414. title='Wrong master/builder name:', color=Fore.MAGENTA,
  415. f=lambda b: (get_name(b),))
  416. pop(status='COMPLETED', result='FAILURE',
  417. title='Other failures:',
  418. f=lambda b: (get_name(b), b.get('failure_reason'), b.get('url')))
  419. pop(status='COMPLETED',
  420. title='Other finished:',
  421. f=lambda b: (get_name(b), b.get('result'), b.get('url')))
  422. pop(status='STARTED',
  423. title='Started:', color=Fore.YELLOW,
  424. f=lambda b: (get_name(b), b.get('url')))
  425. pop(status='SCHEDULED',
  426. title='Scheduled:',
  427. f=lambda b: (get_name(b), 'id=%s' % b['id']))
  428. # The last section is just in case buildbucket API changes OR there is a bug.
  429. pop(title='Other:',
  430. f=lambda b: (get_name(b), 'id=%s' % b['id']))
  431. assert len(builds) == 0
  432. print 'Total: %d tryjobs' % total
  433. def MatchSvnGlob(url, base_url, glob_spec, allow_wildcards):
  434. """Return the corresponding git ref if |base_url| together with |glob_spec|
  435. matches the full |url|.
  436. If |allow_wildcards| is true, |glob_spec| can contain wildcards (see below).
  437. """
  438. fetch_suburl, as_ref = glob_spec.split(':')
  439. if allow_wildcards:
  440. glob_match = re.match('(.+/)?(\*|{[^/]*})(/.+)?', fetch_suburl)
  441. if glob_match:
  442. # Parse specs like "branches/*/src:refs/remotes/svn/*" or
  443. # "branches/{472,597,648}/src:refs/remotes/svn/*".
  444. branch_re = re.escape(base_url)
  445. if glob_match.group(1):
  446. branch_re += '/' + re.escape(glob_match.group(1))
  447. wildcard = glob_match.group(2)
  448. if wildcard == '*':
  449. branch_re += '([^/]*)'
  450. else:
  451. # Escape and replace surrounding braces with parentheses and commas
  452. # with pipe symbols.
  453. wildcard = re.escape(wildcard)
  454. wildcard = re.sub('^\\\\{', '(', wildcard)
  455. wildcard = re.sub('\\\\,', '|', wildcard)
  456. wildcard = re.sub('\\\\}$', ')', wildcard)
  457. branch_re += wildcard
  458. if glob_match.group(3):
  459. branch_re += re.escape(glob_match.group(3))
  460. match = re.match(branch_re, url)
  461. if match:
  462. return re.sub('\*$', match.group(1), as_ref)
  463. # Parse specs like "trunk/src:refs/remotes/origin/trunk".
  464. if fetch_suburl:
  465. full_url = base_url + '/' + fetch_suburl
  466. else:
  467. full_url = base_url
  468. if full_url == url:
  469. return as_ref
  470. return None
  471. def print_stats(similarity, find_copies, args):
  472. """Prints statistics about the change to the user."""
  473. # --no-ext-diff is broken in some versions of Git, so try to work around
  474. # this by overriding the environment (but there is still a problem if the
  475. # git config key "diff.external" is used).
  476. env = GetNoGitPagerEnv()
  477. if 'GIT_EXTERNAL_DIFF' in env:
  478. del env['GIT_EXTERNAL_DIFF']
  479. if find_copies:
  480. similarity_options = ['--find-copies-harder', '-l100000',
  481. '-C%s' % similarity]
  482. else:
  483. similarity_options = ['-M%s' % similarity]
  484. try:
  485. stdout = sys.stdout.fileno()
  486. except AttributeError:
  487. stdout = None
  488. return subprocess2.call(
  489. ['git',
  490. 'diff', '--no-ext-diff', '--stat'] + similarity_options + args,
  491. stdout=stdout, env=env)
  492. class BuildbucketResponseException(Exception):
  493. pass
  494. class Settings(object):
  495. def __init__(self):
  496. self.default_server = None
  497. self.cc = None
  498. self.root = None
  499. self.is_git_svn = None
  500. self.svn_branch = None
  501. self.tree_status_url = None
  502. self.viewvc_url = None
  503. self.updated = False
  504. self.is_gerrit = None
  505. self.squash_gerrit_uploads = None
  506. self.gerrit_skip_ensure_authenticated = None
  507. self.git_editor = None
  508. self.project = None
  509. self.force_https_commit_url = None
  510. self.pending_ref_prefix = None
  511. def LazyUpdateIfNeeded(self):
  512. """Updates the settings from a codereview.settings file, if available."""
  513. if not self.updated:
  514. # The only value that actually changes the behavior is
  515. # autoupdate = "false". Everything else means "true".
  516. autoupdate = RunGit(['config', 'rietveld.autoupdate'],
  517. error_ok=True
  518. ).strip().lower()
  519. cr_settings_file = FindCodereviewSettingsFile()
  520. if autoupdate != 'false' and cr_settings_file:
  521. LoadCodereviewSettingsFromFile(cr_settings_file)
  522. self.updated = True
  523. def GetDefaultServerUrl(self, error_ok=False):
  524. if not self.default_server:
  525. self.LazyUpdateIfNeeded()
  526. self.default_server = gclient_utils.UpgradeToHttps(
  527. self._GetRietveldConfig('server', error_ok=True))
  528. if error_ok:
  529. return self.default_server
  530. if not self.default_server:
  531. error_message = ('Could not find settings file. You must configure '
  532. 'your review setup by running "git cl config".')
  533. self.default_server = gclient_utils.UpgradeToHttps(
  534. self._GetRietveldConfig('server', error_message=error_message))
  535. return self.default_server
  536. @staticmethod
  537. def GetRelativeRoot():
  538. return RunGit(['rev-parse', '--show-cdup']).strip()
  539. def GetRoot(self):
  540. if self.root is None:
  541. self.root = os.path.abspath(self.GetRelativeRoot())
  542. return self.root
  543. def GetGitMirror(self, remote='origin'):
  544. """If this checkout is from a local git mirror, return a Mirror object."""
  545. local_url = RunGit(['config', '--get', 'remote.%s.url' % remote]).strip()
  546. if not os.path.isdir(local_url):
  547. return None
  548. git_cache.Mirror.SetCachePath(os.path.dirname(local_url))
  549. remote_url = git_cache.Mirror.CacheDirToUrl(local_url)
  550. # Use the /dev/null print_func to avoid terminal spew in WaitForRealCommit.
  551. mirror = git_cache.Mirror(remote_url, print_func = lambda *args: None)
  552. if mirror.exists():
  553. return mirror
  554. return None
  555. def GetIsGitSvn(self):
  556. """Return true if this repo looks like it's using git-svn."""
  557. if self.is_git_svn is None:
  558. if self.GetPendingRefPrefix():
  559. # If PENDING_REF_PREFIX is set then it's a pure git repo no matter what.
  560. self.is_git_svn = False
  561. else:
  562. # If you have any "svn-remote.*" config keys, we think you're using svn.
  563. self.is_git_svn = RunGitWithCode(
  564. ['config', '--local', '--get-regexp', r'^svn-remote\.'])[0] == 0
  565. return self.is_git_svn
  566. def GetSVNBranch(self):
  567. if self.svn_branch is None:
  568. if not self.GetIsGitSvn():
  569. DieWithError('Repo doesn\'t appear to be a git-svn repo.')
  570. # Try to figure out which remote branch we're based on.
  571. # Strategy:
  572. # 1) iterate through our branch history and find the svn URL.
  573. # 2) find the svn-remote that fetches from the URL.
  574. # regexp matching the git-svn line that contains the URL.
  575. git_svn_re = re.compile(r'^\s*git-svn-id: (\S+)@', re.MULTILINE)
  576. # We don't want to go through all of history, so read a line from the
  577. # pipe at a time.
  578. # The -100 is an arbitrary limit so we don't search forever.
  579. cmd = ['git', 'log', '-100', '--pretty=medium']
  580. proc = subprocess2.Popen(cmd, stdout=subprocess2.PIPE,
  581. env=GetNoGitPagerEnv())
  582. url = None
  583. for line in proc.stdout:
  584. match = git_svn_re.match(line)
  585. if match:
  586. url = match.group(1)
  587. proc.stdout.close() # Cut pipe.
  588. break
  589. if url:
  590. svn_remote_re = re.compile(r'^svn-remote\.([^.]+)\.url (.*)$')
  591. remotes = RunGit(['config', '--get-regexp',
  592. r'^svn-remote\..*\.url']).splitlines()
  593. for remote in remotes:
  594. match = svn_remote_re.match(remote)
  595. if match:
  596. remote = match.group(1)
  597. base_url = match.group(2)
  598. rewrite_root = RunGit(
  599. ['config', 'svn-remote.%s.rewriteRoot' % remote],
  600. error_ok=True).strip()
  601. if rewrite_root:
  602. base_url = rewrite_root
  603. fetch_spec = RunGit(
  604. ['config', 'svn-remote.%s.fetch' % remote],
  605. error_ok=True).strip()
  606. if fetch_spec:
  607. self.svn_branch = MatchSvnGlob(url, base_url, fetch_spec, False)
  608. if self.svn_branch:
  609. break
  610. branch_spec = RunGit(
  611. ['config', 'svn-remote.%s.branches' % remote],
  612. error_ok=True).strip()
  613. if branch_spec:
  614. self.svn_branch = MatchSvnGlob(url, base_url, branch_spec, True)
  615. if self.svn_branch:
  616. break
  617. tag_spec = RunGit(
  618. ['config', 'svn-remote.%s.tags' % remote],
  619. error_ok=True).strip()
  620. if tag_spec:
  621. self.svn_branch = MatchSvnGlob(url, base_url, tag_spec, True)
  622. if self.svn_branch:
  623. break
  624. if not self.svn_branch:
  625. DieWithError('Can\'t guess svn branch -- try specifying it on the '
  626. 'command line')
  627. return self.svn_branch
  628. def GetTreeStatusUrl(self, error_ok=False):
  629. if not self.tree_status_url:
  630. error_message = ('You must configure your tree status URL by running '
  631. '"git cl config".')
  632. self.tree_status_url = self._GetRietveldConfig(
  633. 'tree-status-url', error_ok=error_ok, error_message=error_message)
  634. return self.tree_status_url
  635. def GetViewVCUrl(self):
  636. if not self.viewvc_url:
  637. self.viewvc_url = self._GetRietveldConfig('viewvc-url', error_ok=True)
  638. return self.viewvc_url
  639. def GetBugPrefix(self):
  640. return self._GetRietveldConfig('bug-prefix', error_ok=True)
  641. def GetIsSkipDependencyUpload(self, branch_name):
  642. """Returns true if specified branch should skip dep uploads."""
  643. return self._GetBranchConfig(branch_name, 'skip-deps-uploads',
  644. error_ok=True)
  645. def GetRunPostUploadHook(self):
  646. run_post_upload_hook = self._GetRietveldConfig(
  647. 'run-post-upload-hook', error_ok=True)
  648. return run_post_upload_hook == "True"
  649. def GetDefaultCCList(self):
  650. return self._GetRietveldConfig('cc', error_ok=True)
  651. def GetDefaultPrivateFlag(self):
  652. return self._GetRietveldConfig('private', error_ok=True)
  653. def GetIsGerrit(self):
  654. """Return true if this repo is assosiated with gerrit code review system."""
  655. if self.is_gerrit is None:
  656. self.is_gerrit = self._GetConfig('gerrit.host', error_ok=True)
  657. return self.is_gerrit
  658. def GetSquashGerritUploads(self):
  659. """Return true if uploads to Gerrit should be squashed by default."""
  660. if self.squash_gerrit_uploads is None:
  661. self.squash_gerrit_uploads = (
  662. RunGit(['config', '--bool', 'gerrit.squash-uploads'],
  663. error_ok=True).strip() == 'true')
  664. return self.squash_gerrit_uploads
  665. def GetGerritSkipEnsureAuthenticated(self):
  666. """Return True if EnsureAuthenticated should not be done for Gerrit
  667. uploads."""
  668. if self.gerrit_skip_ensure_authenticated is None:
  669. self.gerrit_skip_ensure_authenticated = (
  670. RunGit(['config', '--bool', 'gerrit.skip-ensure-authenticated'],
  671. error_ok=True).strip() == 'true')
  672. return self.gerrit_skip_ensure_authenticated
  673. def GetGitEditor(self):
  674. """Return the editor specified in the git config, or None if none is."""
  675. if self.git_editor is None:
  676. self.git_editor = self._GetConfig('core.editor', error_ok=True)
  677. return self.git_editor or None
  678. def GetLintRegex(self):
  679. return (self._GetRietveldConfig('cpplint-regex', error_ok=True) or
  680. DEFAULT_LINT_REGEX)
  681. def GetLintIgnoreRegex(self):
  682. return (self._GetRietveldConfig('cpplint-ignore-regex', error_ok=True) or
  683. DEFAULT_LINT_IGNORE_REGEX)
  684. def GetProject(self):
  685. if not self.project:
  686. self.project = self._GetRietveldConfig('project', error_ok=True)
  687. return self.project
  688. def GetForceHttpsCommitUrl(self):
  689. if not self.force_https_commit_url:
  690. self.force_https_commit_url = self._GetRietveldConfig(
  691. 'force-https-commit-url', error_ok=True)
  692. return self.force_https_commit_url
  693. def GetPendingRefPrefix(self):
  694. if not self.pending_ref_prefix:
  695. self.pending_ref_prefix = self._GetRietveldConfig(
  696. 'pending-ref-prefix', error_ok=True)
  697. return self.pending_ref_prefix
  698. def _GetRietveldConfig(self, param, **kwargs):
  699. return self._GetConfig('rietveld.' + param, **kwargs)
  700. def _GetBranchConfig(self, branch_name, param, **kwargs):
  701. return self._GetConfig('branch.' + branch_name + '.' + param, **kwargs)
  702. def _GetConfig(self, param, **kwargs):
  703. self.LazyUpdateIfNeeded()
  704. return RunGit(['config', param], **kwargs).strip()
  705. def ShortBranchName(branch):
  706. """Convert a name like 'refs/heads/foo' to just 'foo'."""
  707. return branch.replace('refs/heads/', '', 1)
  708. def GetCurrentBranchRef():
  709. """Returns branch ref (e.g., refs/heads/master) or None."""
  710. return RunGit(['symbolic-ref', 'HEAD'],
  711. stderr=subprocess2.VOID, error_ok=True).strip() or None
  712. def GetCurrentBranch():
  713. """Returns current branch or None.
  714. For refs/heads/* branches, returns just last part. For others, full ref.
  715. """
  716. branchref = GetCurrentBranchRef()
  717. if branchref:
  718. return ShortBranchName(branchref)
  719. return None
  720. class _CQState(object):
  721. """Enum for states of CL with respect to Commit Queue."""
  722. NONE = 'none'
  723. DRY_RUN = 'dry_run'
  724. COMMIT = 'commit'
  725. ALL_STATES = [NONE, DRY_RUN, COMMIT]
  726. class _ParsedIssueNumberArgument(object):
  727. def __init__(self, issue=None, patchset=None, hostname=None):
  728. self.issue = issue
  729. self.patchset = patchset
  730. self.hostname = hostname
  731. @property
  732. def valid(self):
  733. return self.issue is not None
  734. class _RietveldParsedIssueNumberArgument(_ParsedIssueNumberArgument):
  735. def __init__(self, *args, **kwargs):
  736. self.patch_url = kwargs.pop('patch_url', None)
  737. super(_RietveldParsedIssueNumberArgument, self).__init__(*args, **kwargs)
  738. def ParseIssueNumberArgument(arg):
  739. """Parses the issue argument and returns _ParsedIssueNumberArgument."""
  740. fail_result = _ParsedIssueNumberArgument()
  741. if arg.isdigit():
  742. return _ParsedIssueNumberArgument(issue=int(arg))
  743. if not arg.startswith('http'):
  744. return fail_result
  745. url = gclient_utils.UpgradeToHttps(arg)
  746. try:
  747. parsed_url = urlparse.urlparse(url)
  748. except ValueError:
  749. return fail_result
  750. for cls in _CODEREVIEW_IMPLEMENTATIONS.itervalues():
  751. tmp = cls.ParseIssueURL(parsed_url)
  752. if tmp is not None:
  753. return tmp
  754. return fail_result
  755. class Changelist(object):
  756. """Changelist works with one changelist in local branch.
  757. Supports two codereview backends: Rietveld or Gerrit, selected at object
  758. creation.
  759. Notes:
  760. * Not safe for concurrent multi-{thread,process} use.
  761. * Caches values from current branch. Therefore, re-use after branch change
  762. with care.
  763. """
  764. def __init__(self, branchref=None, issue=None, codereview=None, **kwargs):
  765. """Create a new ChangeList instance.
  766. If issue is given, the codereview must be given too.
  767. If `codereview` is given, it must be 'rietveld' or 'gerrit'.
  768. Otherwise, it's decided based on current configuration of the local branch,
  769. with default being 'rietveld' for backwards compatibility.
  770. See _load_codereview_impl for more details.
  771. **kwargs will be passed directly to codereview implementation.
  772. """
  773. # Poke settings so we get the "configure your server" message if necessary.
  774. global settings
  775. if not settings:
  776. # Happens when git_cl.py is used as a utility library.
  777. settings = Settings()
  778. if issue:
  779. assert codereview, 'codereview must be known, if issue is known'
  780. self.branchref = branchref
  781. if self.branchref:
  782. assert branchref.startswith('refs/heads/')
  783. self.branch = ShortBranchName(self.branchref)
  784. else:
  785. self.branch = None
  786. self.upstream_branch = None
  787. self.lookedup_issue = False
  788. self.issue = issue or None
  789. self.has_description = False
  790. self.description = None
  791. self.lookedup_patchset = False
  792. self.patchset = None
  793. self.cc = None
  794. self.watchers = ()
  795. self._remote = None
  796. self._codereview_impl = None
  797. self._codereview = None
  798. self._load_codereview_impl(codereview, **kwargs)
  799. assert self._codereview_impl
  800. assert self._codereview in _CODEREVIEW_IMPLEMENTATIONS
  801. def _load_codereview_impl(self, codereview=None, **kwargs):
  802. if codereview:
  803. assert codereview in _CODEREVIEW_IMPLEMENTATIONS
  804. cls = _CODEREVIEW_IMPLEMENTATIONS[codereview]
  805. self._codereview = codereview
  806. self._codereview_impl = cls(self, **kwargs)
  807. return
  808. # Automatic selection based on issue number set for a current branch.
  809. # Rietveld takes precedence over Gerrit.
  810. assert not self.issue
  811. # Whether we find issue or not, we are doing the lookup.
  812. self.lookedup_issue = True
  813. for codereview, cls in _CODEREVIEW_IMPLEMENTATIONS.iteritems():
  814. setting = cls.IssueSetting(self.GetBranch())
  815. issue = RunGit(['config', setting], error_ok=True).strip()
  816. if issue:
  817. self._codereview = codereview
  818. self._codereview_impl = cls(self, **kwargs)
  819. self.issue = int(issue)
  820. return
  821. # No issue is set for this branch, so decide based on repo-wide settings.
  822. return self._load_codereview_impl(
  823. codereview='gerrit' if settings.GetIsGerrit() else 'rietveld',
  824. **kwargs)
  825. def IsGerrit(self):
  826. return self._codereview == 'gerrit'
  827. def GetCCList(self):
  828. """Return the users cc'd on this CL.
  829. Return is a string suitable for passing to gcl with the --cc flag.
  830. """
  831. if self.cc is None:
  832. base_cc = settings.GetDefaultCCList()
  833. more_cc = ','.join(self.watchers)
  834. self.cc = ','.join(filter(None, (base_cc, more_cc))) or ''
  835. return self.cc
  836. def GetCCListWithoutDefault(self):
  837. """Return the users cc'd on this CL excluding default ones."""
  838. if self.cc is None:
  839. self.cc = ','.join(self.watchers)
  840. return self.cc
  841. def SetWatchers(self, watchers):
  842. """Set the list of email addresses that should be cc'd based on the changed
  843. files in this CL.
  844. """
  845. self.watchers = watchers
  846. def GetBranch(self):
  847. """Returns the short branch name, e.g. 'master'."""
  848. if not self.branch:
  849. branchref = GetCurrentBranchRef()
  850. if not branchref:
  851. return None
  852. self.branchref = branchref
  853. self.branch = ShortBranchName(self.branchref)
  854. return self.branch
  855. def GetBranchRef(self):
  856. """Returns the full branch name, e.g. 'refs/heads/master'."""
  857. self.GetBranch() # Poke the lazy loader.
  858. return self.branchref
  859. def ClearBranch(self):
  860. """Clears cached branch data of this object."""
  861. self.branch = self.branchref = None
  862. @staticmethod
  863. def FetchUpstreamTuple(branch):
  864. """Returns a tuple containing remote and remote ref,
  865. e.g. 'origin', 'refs/heads/master'
  866. """
  867. remote = '.'
  868. upstream_branch = RunGit(['config', 'branch.%s.merge' % branch],
  869. error_ok=True).strip()
  870. if upstream_branch:
  871. remote = RunGit(['config', 'branch.%s.remote' % branch]).strip()
  872. else:
  873. upstream_branch = RunGit(['config', 'rietveld.upstream-branch'],
  874. error_ok=True).strip()
  875. if upstream_branch:
  876. remote = RunGit(['config', 'rietveld.upstream-remote']).strip()
  877. else:
  878. # Fall back on trying a git-svn upstream branch.
  879. if settings.GetIsGitSvn():
  880. upstream_branch = settings.GetSVNBranch()
  881. else:
  882. # Else, try to guess the origin remote.
  883. remote_branches = RunGit(['branch', '-r']).split()
  884. if 'origin/master' in remote_branches:
  885. # Fall back on origin/master if it exits.
  886. remote = 'origin'
  887. upstream_branch = 'refs/heads/master'
  888. elif 'origin/trunk' in remote_branches:
  889. # Fall back on origin/trunk if it exists. Generally a shared
  890. # git-svn clone
  891. remote = 'origin'
  892. upstream_branch = 'refs/heads/trunk'
  893. else:
  894. DieWithError(
  895. 'Unable to determine default branch to diff against.\n'
  896. 'Either pass complete "git diff"-style arguments, like\n'
  897. ' git cl upload origin/master\n'
  898. 'or verify this branch is set up to track another \n'
  899. '(via the --track argument to "git checkout -b ...").')
  900. return remote, upstream_branch
  901. def GetCommonAncestorWithUpstream(self):
  902. upstream_branch = self.GetUpstreamBranch()
  903. if not BranchExists(upstream_branch):
  904. DieWithError('The upstream for the current branch (%s) does not exist '
  905. 'anymore.\nPlease fix it and try again.' % self.GetBranch())
  906. return git_common.get_or_create_merge_base(self.GetBranch(),
  907. upstream_branch)
  908. def GetUpstreamBranch(self):
  909. if self.upstream_branch is None:
  910. remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
  911. if remote is not '.':
  912. upstream_branch = upstream_branch.replace('refs/heads/',
  913. 'refs/remotes/%s/' % remote)
  914. upstream_branch = upstream_branch.replace('refs/branch-heads/',
  915. 'refs/remotes/branch-heads/')
  916. self.upstream_branch = upstream_branch
  917. return self.upstream_branch
  918. def GetRemoteBranch(self):
  919. if not self._remote:
  920. remote, branch = None, self.GetBranch()
  921. seen_branches = set()
  922. while branch not in seen_branches:
  923. seen_branches.add(branch)
  924. remote, branch = self.FetchUpstreamTuple(branch)
  925. branch = ShortBranchName(branch)
  926. if remote != '.' or branch.startswith('refs/remotes'):
  927. break
  928. else:
  929. remotes = RunGit(['remote'], error_ok=True).split()
  930. if len(remotes) == 1:
  931. remote, = remotes
  932. elif 'origin' in remotes:
  933. remote = 'origin'
  934. logging.warning('Could not determine which remote this change is '
  935. 'associated with, so defaulting to "%s". This may '
  936. 'not be what you want. You may prevent this message '
  937. 'by running "git svn info" as documented here: %s',
  938. self._remote,
  939. GIT_INSTRUCTIONS_URL)
  940. else:
  941. logging.warn('Could not determine which remote this change is '
  942. 'associated with. You may prevent this message by '
  943. 'running "git svn info" as documented here: %s',
  944. GIT_INSTRUCTIONS_URL)
  945. branch = 'HEAD'
  946. if branch.startswith('refs/remotes'):
  947. self._remote = (remote, branch)
  948. elif branch.startswith('refs/branch-heads/'):
  949. self._remote = (remote, branch.replace('refs/', 'refs/remotes/'))
  950. else:
  951. self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch))
  952. return self._remote
  953. def GitSanityChecks(self, upstream_git_obj):
  954. """Checks git repo status and ensures diff is from local commits."""
  955. if upstream_git_obj is None:
  956. if self.GetBranch() is None:
  957. print >> sys.stderr, (
  958. 'ERROR: unable to determine current branch (detached HEAD?)')
  959. else:
  960. print >> sys.stderr, (
  961. 'ERROR: no upstream branch')
  962. return False
  963. # Verify the commit we're diffing against is in our current branch.
  964. upstream_sha = RunGit(['rev-parse', '--verify', upstream_git_obj]).strip()
  965. common_ancestor = RunGit(['merge-base', upstream_sha, 'HEAD']).strip()
  966. if upstream_sha != common_ancestor:
  967. print >> sys.stderr, (
  968. 'ERROR: %s is not in the current branch. You may need to rebase '
  969. 'your tracking branch' % upstream_sha)
  970. return False
  971. # List the commits inside the diff, and verify they are all local.
  972. commits_in_diff = RunGit(
  973. ['rev-list', '^%s' % upstream_sha, 'HEAD']).splitlines()
  974. code, remote_branch = RunGitWithCode(['config', 'gitcl.remotebranch'])
  975. remote_branch = remote_branch.strip()
  976. if code != 0:
  977. _, remote_branch = self.GetRemoteBranch()
  978. commits_in_remote = RunGit(
  979. ['rev-list', '^%s' % upstream_sha, remote_branch]).splitlines()
  980. common_commits = set(commits_in_diff) & set(commits_in_remote)
  981. if common_commits:
  982. print >> sys.stderr, (
  983. 'ERROR: Your diff contains %d commits already in %s.\n'
  984. 'Run "git log --oneline %s..HEAD" to get a list of commits in '
  985. 'the diff. If you are using a custom git flow, you can override'
  986. ' the reference used for this check with "git config '
  987. 'gitcl.remotebranch <git-ref>".' % (
  988. len(common_commits), remote_branch, upstream_git_obj))
  989. return False
  990. return True
  991. def GetGitBaseUrlFromConfig(self):
  992. """Return the configured base URL from branch.<branchname>.baseurl.
  993. Returns None if it is not set.
  994. """
  995. return RunGit(['config', 'branch.%s.base-url' % self.GetBranch()],
  996. error_ok=True).strip()
  997. def GetGitSvnRemoteUrl(self):
  998. """Return the configured git-svn remote URL parsed from git svn info.
  999. Returns None if it is not set.
  1000. """
  1001. # URL is dependent on the current directory.
  1002. data = RunGit(['svn', 'info'], cwd=settings.GetRoot())
  1003. if data:
  1004. keys = dict(line.split(': ', 1) for line in data.splitlines()
  1005. if ': ' in line)
  1006. return keys.get('URL', None)
  1007. return None
  1008. def GetRemoteUrl(self):
  1009. """Return the configured remote URL, e.g. 'git://example.org/foo.git/'.
  1010. Returns None if there is no remote.
  1011. """
  1012. remote, _ = self.GetRemoteBranch()
  1013. url = RunGit(['config', 'remote.%s.url' % remote], error_ok=True).strip()
  1014. # If URL is pointing to a local directory, it is probably a git cache.
  1015. if os.path.isdir(url):
  1016. url = RunGit(['config', 'remote.%s.url' % remote],
  1017. error_ok=True,
  1018. cwd=url).strip()
  1019. return url
  1020. def GetIssue(self):
  1021. """Returns the issue number as a int or None if not set."""
  1022. if self.issue is None and not self.lookedup_issue:
  1023. issue = RunGit(['config',
  1024. self._codereview_impl.IssueSetting(self.GetBranch())],
  1025. error_ok=True).strip()
  1026. self.issue = int(issue) or None if issue else None
  1027. self.lookedup_issue = True
  1028. return self.issue
  1029. def GetIssueURL(self):
  1030. """Get the URL for a particular issue."""
  1031. issue = self.GetIssue()
  1032. if not issue:
  1033. return None
  1034. return '%s/%s' % (self._codereview_impl.GetCodereviewServer(), issue)
  1035. def GetDescription(self, pretty=False):
  1036. if not self.has_description:
  1037. if self.GetIssue():
  1038. self.description = self._codereview_impl.FetchDescription()
  1039. self.has_description = True
  1040. if pretty:
  1041. wrapper = textwrap.TextWrapper()
  1042. wrapper.initial_indent = wrapper.subsequent_indent = ' '
  1043. return wrapper.fill(self.description)
  1044. return self.description
  1045. def GetPatchset(self):
  1046. """Returns the patchset number as a int or None if not set."""
  1047. if self.patchset is None and not self.lookedup_patchset:
  1048. patchset = RunGit(['config', self._codereview_impl.PatchsetSetting()],
  1049. error_ok=True).strip()
  1050. self.patchset = int(patchset) or None if patchset else None
  1051. self.lookedup_patchset = True
  1052. return self.patchset
  1053. def SetPatchset(self, patchset):
  1054. """Set this branch's patchset. If patchset=0, clears the patchset."""
  1055. patchset_setting = self._codereview_impl.PatchsetSetting()
  1056. if patchset:
  1057. RunGit(['config', patchset_setting, str(patchset)])
  1058. self.patchset = patchset
  1059. else:
  1060. RunGit(['config', '--unset', patchset_setting],
  1061. stderr=subprocess2.PIPE, error_ok=True)
  1062. self.patchset = None
  1063. def SetIssue(self, issue=None):
  1064. """Set this branch's issue. If issue isn't given, clears the issue."""
  1065. issue_setting = self._codereview_impl.IssueSetting(self.GetBranch())
  1066. codereview_setting = self._codereview_impl.GetCodereviewServerSetting()
  1067. if issue:
  1068. self.issue = issue
  1069. RunGit(['config', issue_setting, str(issue)])
  1070. codereview_server = self._codereview_impl.GetCodereviewServer()
  1071. if codereview_server:
  1072. RunGit(['config', codereview_setting, codereview_server])
  1073. else:
  1074. current_issue = self.GetIssue()
  1075. if current_issue:
  1076. RunGit(['config', '--unset', issue_setting])
  1077. self.issue = None
  1078. self.SetPatchset(None)
  1079. def GetChange(self, upstream_branch, author):
  1080. if not self.GitSanityChecks(upstream_branch):
  1081. DieWithError('\nGit sanity check failure')
  1082. root = settings.GetRelativeRoot()
  1083. if not root:
  1084. root = '.'
  1085. absroot = os.path.abspath(root)
  1086. # We use the sha1 of HEAD as a name of this change.
  1087. name = RunGitWithCode(['rev-parse', 'HEAD'])[1].strip()
  1088. # Need to pass a relative path for msysgit.
  1089. try:
  1090. files = scm.GIT.CaptureStatus([root], '.', upstream_branch)
  1091. except subprocess2.CalledProcessError:
  1092. DieWithError(
  1093. ('\nFailed to diff against upstream branch %s\n\n'
  1094. 'This branch probably doesn\'t exist anymore. To reset the\n'
  1095. 'tracking branch, please run\n'
  1096. ' git branch --set-upstream %s trunk\n'
  1097. 'replacing trunk with origin/master or the relevant branch') %
  1098. (upstream_branch, self.GetBranch()))
  1099. issue = self.GetIssue()
  1100. patchset = self.GetPatchset()
  1101. if issue:
  1102. description = self.GetDescription()
  1103. else:
  1104. # If the change was never uploaded, use the log messages of all commits
  1105. # up to the branch point, as git cl upload will prefill the description
  1106. # with these log messages.
  1107. args = ['log', '--pretty=format:%s%n%n%b', '%s...' % (upstream_branch)]
  1108. description = RunGitWithCode(args)[1].strip()
  1109. if not author:
  1110. author = RunGit(['config', 'user.email']).strip() or None
  1111. return presubmit_support.GitChange(
  1112. name,
  1113. description,
  1114. absroot,
  1115. files,
  1116. issue,
  1117. patchset,
  1118. author,
  1119. upstream=upstream_branch)
  1120. def UpdateDescription(self, description):
  1121. self.description = description
  1122. return self._codereview_impl.UpdateDescriptionRemote(description)
  1123. def RunHook(self, committing, may_prompt, verbose, change):
  1124. """Calls sys.exit() if the hook fails; returns a HookResults otherwise."""
  1125. try:
  1126. return presubmit_support.DoPresubmitChecks(change, committing,
  1127. verbose=verbose, output_stream=sys.stdout, input_stream=sys.stdin,
  1128. default_presubmit=None, may_prompt=may_prompt,
  1129. rietveld_obj=self._codereview_impl.GetRieveldObjForPresubmit(),
  1130. gerrit_obj=self._codereview_impl.GetGerritObjForPresubmit())
  1131. except presubmit_support.PresubmitFailure, e:
  1132. DieWithError(
  1133. ('%s\nMaybe your depot_tools is out of date?\n'
  1134. 'If all fails, contact maruel@') % e)
  1135. def CMDPatchIssue(self, issue_arg, reject, nocommit, directory):
  1136. """Fetches and applies the issue patch from codereview to local branch."""
  1137. if isinstance(issue_arg, (int, long)) or issue_arg.isdigit():
  1138. parsed_issue_arg = _ParsedIssueNumberArgument(int(issue_arg))
  1139. else:
  1140. # Assume url.
  1141. parsed_issue_arg = self._codereview_impl.ParseIssueURL(
  1142. urlparse.urlparse(issue_arg))
  1143. if not parsed_issue_arg or not parsed_issue_arg.valid:
  1144. DieWithError('Failed to parse issue argument "%s". '
  1145. 'Must be an issue number or a valid URL.' % issue_arg)
  1146. return self._codereview_impl.CMDPatchWithParsedIssue(
  1147. parsed_issue_arg, reject, nocommit, directory)
  1148. def CMDUpload(self, options, git_diff_args, orig_args):
  1149. """Uploads a change to codereview."""
  1150. if git_diff_args:
  1151. # TODO(ukai): is it ok for gerrit case?
  1152. base_branch = git_diff_args[0]
  1153. else:
  1154. if self.GetBranch() is None:
  1155. DieWithError('Can\'t upload from detached HEAD state. Get on a branch!')
  1156. # Default to diffing against common ancestor of upstream branch
  1157. base_branch = self.GetCommonAncestorWithUpstream()
  1158. git_diff_args = [base_branch, 'HEAD']
  1159. # Make sure authenticated to codereview before running potentially expensive
  1160. # hooks. It is a fast, best efforts check. Codereview still can reject the
  1161. # authentication during the actual upload.
  1162. self._codereview_impl.EnsureAuthenticated(force=options.force)
  1163. # Apply watchlists on upload.
  1164. change = self.GetChange(base_branch, None)
  1165. watchlist = watchlists.Watchlists(change.RepositoryRoot())
  1166. files = [f.LocalPath() for f in change.AffectedFiles()]
  1167. if not options.bypass_watchlists:
  1168. self.SetWatchers(watchlist.GetWatchersForPaths(files))
  1169. if not options.bypass_hooks:
  1170. if options.reviewers or options.tbr_owners:
  1171. # Set the reviewer list now so that presubmit checks can access it.
  1172. change_description = ChangeDescription(change.FullDescriptionText())
  1173. change_description.update_reviewers(options.reviewers,
  1174. options.tbr_owners,
  1175. change)
  1176. change.SetDescriptionText(change_description.description)
  1177. hook_results = self.RunHook(committing=False,
  1178. may_prompt=not options.force,
  1179. verbose=options.verbose,
  1180. change=change)
  1181. if not hook_results.should_continue():
  1182. return 1
  1183. if not options.reviewers and hook_results.reviewers:
  1184. options.reviewers = hook_results.reviewers.split(',')
  1185. if self.GetIssue():
  1186. latest_patchset = self.GetMostRecentPatchset()
  1187. local_patchset = self.GetPatchset()
  1188. if (latest_patchset and local_patchset and
  1189. local_patchset != latest_patchset):
  1190. print ('The last upload made from this repository was patchset #%d but '
  1191. 'the most recent patchset on the server is #%d.'
  1192. % (local_patchset, latest_patchset))
  1193. print ('Uploading will still work, but if you\'ve uploaded to this '
  1194. 'issue from another machine or branch the patch you\'re '
  1195. 'uploading now might not include those changes.')
  1196. ask_for_data('About to upload; enter to confirm.')
  1197. print_stats(options.similarity, options.find_copies, git_diff_args)
  1198. ret = self.CMDUploadChange(options, git_diff_args, change)
  1199. if not ret:
  1200. git_set_branch_value('last-upload-hash',
  1201. RunGit(['rev-parse', 'HEAD']).strip())
  1202. # Run post upload hooks, if specified.
  1203. if settings.GetRunPostUploadHook():
  1204. presubmit_support.DoPostUploadExecuter(
  1205. change,
  1206. self,
  1207. settings.GetRoot(),
  1208. options.verbose,
  1209. sys.stdout)
  1210. # Upload all dependencies if specified.
  1211. if options.dependencies:
  1212. print
  1213. print '--dependencies has been specified.'
  1214. print 'All dependent local branches will be re-uploaded.'
  1215. print
  1216. # Remove the dependencies flag from args so that we do not end up in a
  1217. # loop.
  1218. orig_args.remove('--dependencies')
  1219. ret = upload_branch_deps(self, orig_args)
  1220. return ret
  1221. def SetCQState(self, new_state):
  1222. """Update the CQ state for latest patchset.
  1223. Issue must have been already uploaded and known.
  1224. """
  1225. assert new_state in _CQState.ALL_STATES
  1226. assert self.GetIssue()
  1227. return self._codereview_impl.SetCQState(new_state)
  1228. # Forward methods to codereview specific implementation.
  1229. def CloseIssue(self):
  1230. return self._codereview_impl.CloseIssue()
  1231. def GetStatus(self):
  1232. return self._codereview_impl.GetStatus()
  1233. def GetCodereviewServer(self):
  1234. return self._codereview_impl.GetCodereviewServer()
  1235. def GetApprovingReviewers(self):
  1236. return self._codereview_impl.GetApprovingReviewers()
  1237. def GetMostRecentPatchset(self):
  1238. return self._codereview_impl.GetMostRecentPatchset()
  1239. def __getattr__(self, attr):
  1240. # This is because lots of untested code accesses Rietveld-specific stuff
  1241. # directly, and it's hard to fix for sure. So, just let it work, and fix
  1242. # on a case by case basis.
  1243. return getattr(self._codereview_impl, attr)
  1244. class _ChangelistCodereviewBase(object):
  1245. """Abstract base class encapsulating codereview specifics of a changelist."""
  1246. def __init__(self, changelist):
  1247. self._changelist = changelist # instance of Changelist
  1248. def __getattr__(self, attr):
  1249. # Forward methods to changelist.
  1250. # TODO(tandrii): maybe clean up _GerritChangelistImpl and
  1251. # _RietveldChangelistImpl to avoid this hack?
  1252. return getattr(self._changelist, attr)
  1253. def GetStatus(self):
  1254. """Apply a rough heuristic to give a simple summary of an issue's review
  1255. or CQ status, assuming adherence to a common workflow.
  1256. Returns None if no issue for this branch, or specific string keywords.
  1257. """
  1258. raise NotImplementedError()
  1259. def GetCodereviewServer(self):
  1260. """Returns server URL without end slash, like "https://codereview.com"."""
  1261. raise NotImplementedError()
  1262. def FetchDescription(self):
  1263. """Fetches and returns description from the codereview server."""
  1264. raise NotImplementedError()
  1265. def GetCodereviewServerSetting(self):
  1266. """Returns git config setting for the codereview server."""
  1267. raise NotImplementedError()
  1268. @classmethod
  1269. def IssueSetting(cls, branch):
  1270. return 'branch.%s.%s' % (branch, cls.IssueSettingSuffix())
  1271. @classmethod
  1272. def IssueSettingSuffix(cls):
  1273. """Returns name of git config setting which stores issue number for a given
  1274. branch."""
  1275. raise NotImplementedError()
  1276. def PatchsetSetting(self):
  1277. """Returns name of git config setting which stores issue number."""
  1278. raise NotImplementedError()
  1279. def GetRieveldObjForPresubmit(self):
  1280. # This is an unfortunate Rietveld-embeddedness in presubmit.
  1281. # For non-Rietveld codereviews, this probably should return a dummy object.
  1282. raise NotImplementedError()
  1283. def GetGerritObjForPresubmit(self):
  1284. # None is valid return value, otherwise presubmit_support.GerritAccessor.
  1285. return None
  1286. def UpdateDescriptionRemote(self, description):
  1287. """Update the description on codereview site."""
  1288. raise NotImplementedError()
  1289. def CloseIssue(self):
  1290. """Closes the issue."""
  1291. raise NotImplementedError()
  1292. def GetApprovingReviewers(self):
  1293. """Returns a list of reviewers approving the change.
  1294. Note: not necessarily committers.
  1295. """
  1296. raise NotImplementedError()
  1297. def GetMostRecentPatchset(self):
  1298. """Returns the most recent patchset number from the codereview site."""
  1299. raise NotImplementedError()
  1300. def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit,
  1301. directory):
  1302. """Fetches and applies the issue.
  1303. Arguments:
  1304. parsed_issue_arg: instance of _ParsedIssueNumberArgument.
  1305. reject: if True, reject the failed patch instead of switching to 3-way
  1306. merge. Rietveld only.
  1307. nocommit: do not commit the patch, thus leave the tree dirty. Rietveld
  1308. only.
  1309. directory: switch to directory before applying the patch. Rietveld only.
  1310. """
  1311. raise NotImplementedError()
  1312. @staticmethod
  1313. def ParseIssueURL(parsed_url):
  1314. """Parses url and returns instance of _ParsedIssueNumberArgument or None if
  1315. failed."""
  1316. raise NotImplementedError()
  1317. def EnsureAuthenticated(self, force):
  1318. """Best effort check that user is authenticated with codereview server.
  1319. Arguments:
  1320. force: whether to skip confirmation questions.
  1321. """
  1322. raise NotImplementedError()
  1323. def CMDUploadChange(self, options, args, change):
  1324. """Uploads a change to codereview."""
  1325. raise NotImplementedError()
  1326. def SetCQState(self, new_state):
  1327. """Update the CQ state for latest patchset.
  1328. Issue must have been already uploaded and known.
  1329. """
  1330. raise NotImplementedError()
  1331. class _RietveldChangelistImpl(_ChangelistCodereviewBase):
  1332. def __init__(self, changelist, auth_config=None, rietveld_server=None):
  1333. super(_RietveldChangelistImpl, self).__init__(changelist)
  1334. assert settings, 'must be initialized in _ChangelistCodereviewBase'
  1335. settings.GetDefaultServerUrl()
  1336. self._rietveld_server = rietveld_server
  1337. self._auth_config = auth_config
  1338. self._props = None
  1339. self._rpc_server = None
  1340. def GetCodereviewServer(self):
  1341. if not self._rietveld_server:
  1342. # If we're on a branch then get the server potentially associated
  1343. # with that branch.
  1344. if self.GetIssue():
  1345. rietveld_server_setting = self.GetCodereviewServerSetting()
  1346. if rietveld_server_setting:
  1347. self._rietveld_server = gclient_utils.UpgradeToHttps(RunGit(
  1348. ['config', rietveld_server_setting], error_ok=True).strip())
  1349. if not self._rietveld_server:
  1350. self._rietveld_server = settings.GetDefaultServerUrl()
  1351. return self._rietveld_server
  1352. def EnsureAuthenticated(self, force):
  1353. """Best effort check that user is authenticated with Rietveld server."""
  1354. if self._auth_config.use_oauth2:
  1355. authenticator = auth.get_authenticator_for_host(
  1356. self.GetCodereviewServer(), self._auth_config)
  1357. if not authenticator.has_cached_credentials():
  1358. raise auth.LoginRequiredError(self.GetCodereviewServer())
  1359. def FetchDescription(self):
  1360. issue = self.GetIssue()
  1361. assert issue
  1362. try:
  1363. return self.RpcServer().get_description(issue).strip()
  1364. except urllib2.HTTPError as e:
  1365. if e.code == 404:
  1366. DieWithError(
  1367. ('\nWhile fetching the description for issue %d, received a '
  1368. '404 (not found)\n'
  1369. 'error. It is likely that you deleted this '
  1370. 'issue on the server. If this is the\n'
  1371. 'case, please run\n\n'
  1372. ' git cl issue 0\n\n'
  1373. 'to clear the association with the deleted issue. Then run '
  1374. 'this command again.') % issue)
  1375. else:
  1376. DieWithError(
  1377. '\nFailed to fetch issue description. HTTP error %d' % e.code)
  1378. except urllib2.URLError as e:
  1379. print >> sys.stderr, (
  1380. 'Warning: Failed to retrieve CL description due to network '
  1381. 'failure.')
  1382. return ''
  1383. def GetMostRecentPatchset(self):
  1384. return self.GetIssueProperties()['patchsets'][-1]
  1385. def GetPatchSetDiff(self, issue, patchset):
  1386. return self.RpcServer().get(
  1387. '/download/issue%s_%s.diff' % (issue, patchset))
  1388. def GetIssueProperties(self):
  1389. if self._props is None:
  1390. issue = self.GetIssue()
  1391. if not issue:
  1392. self._props = {}
  1393. else:
  1394. self._props = self.RpcServer().get_issue_properties(issue, True)
  1395. return self._props
  1396. def GetApprovingReviewers(self):
  1397. return get_approving_reviewers(self.GetIssueProperties())
  1398. def AddComment(self, message):
  1399. return self.RpcServer().add_comment(self.GetIssue(), message)
  1400. def GetStatus(self):
  1401. """Apply a rough heuristic to give a simple summary of an issue's review
  1402. or CQ status, assuming adherence to a common workflow.
  1403. Returns None if no issue for this branch, or one of the following keywords:
  1404. * 'error' - error from review tool (including deleted issues)
  1405. * 'unsent' - not sent for review
  1406. * 'waiting' - waiting for review
  1407. * 'reply' - waiting for owner to reply to review
  1408. * 'lgtm' - LGTM from at least one approved reviewer
  1409. * 'commit' - in the commit queue
  1410. * 'closed' - closed
  1411. """
  1412. if not self.GetIssue():
  1413. return None
  1414. try:
  1415. props = self.GetIssueProperties()
  1416. except urllib2.HTTPError:
  1417. return 'error'
  1418. if props.get('closed'):
  1419. # Issue is closed.
  1420. return 'closed'
  1421. if props.get('commit') and not props.get('cq_dry_run', False):
  1422. # Issue is in the commit queue.
  1423. return 'commit'
  1424. try:
  1425. reviewers = self.GetApprovingReviewers()
  1426. except urllib2.HTTPError:
  1427. return 'error'
  1428. if reviewers:
  1429. # Was LGTM'ed.
  1430. return 'lgtm'
  1431. messages = props.get('messages') or []
  1432. if not messages:
  1433. # No message was sent.
  1434. return 'unsent'
  1435. if messages[-1]['sender'] != props.get('owner_email'):
  1436. # Non-LGTM reply from non-owner
  1437. return 'reply'
  1438. return 'waiting'
  1439. def UpdateDescriptionRemote(self, description):
  1440. return self.RpcServer().update_description(
  1441. self.GetIssue(), self.description)
  1442. def CloseIssue(self):
  1443. return self.RpcServer().close_issue(self.GetIssue())
  1444. def SetFlag(self, flag, value):
  1445. """Patchset must match."""
  1446. if not self.GetPatchset():
  1447. DieWithError('The patchset needs to match. Send another patchset.')
  1448. try:
  1449. return self.RpcServer().set_flag(
  1450. self.GetIssue(), self.GetPatchset(), flag, value)
  1451. except urllib2.HTTPError, e:
  1452. if e.code == 404:
  1453. DieWithError('The issue %s doesn\'t exist.' % self.GetIssue())
  1454. if e.code == 403:
  1455. DieWithError(
  1456. ('Access denied to issue %s. Maybe the patchset %s doesn\'t '
  1457. 'match?') % (self.GetIssue(), self.GetPatchset()))
  1458. raise
  1459. def RpcServer(self):
  1460. """Returns an upload.RpcServer() to access this review's rietveld instance.
  1461. """
  1462. if not self._rpc_server:
  1463. self._rpc_server = rietveld.CachingRietveld(
  1464. self.GetCodereviewServer(),
  1465. self._auth_config or auth.make_auth_config())
  1466. return self._rpc_server
  1467. @classmethod
  1468. def IssueSettingSuffix(cls):
  1469. return 'rietveldissue'
  1470. def PatchsetSetting(self):
  1471. """Return the git setting that stores this change's most recent patchset."""
  1472. return 'branch.%s.rietveldpatchset' % self.GetBranch()
  1473. def GetCodereviewServerSetting(self):
  1474. """Returns the git setting that stores this change's rietveld server."""
  1475. branch = self.GetBranch()
  1476. if branch:
  1477. return 'branch.%s.rietveldserver' % branch
  1478. return None
  1479. def GetRieveldObjForPresubmit(self):
  1480. return self.RpcServer()
  1481. def SetCQState(self, new_state):
  1482. props = self.GetIssueProperties()
  1483. if props.get('private'):
  1484. DieWithError('Cannot set-commit on private issue')
  1485. if new_state == _CQState.COMMIT:
  1486. self.SetFlag('commit', '1')
  1487. elif new_state == _CQState.NONE:
  1488. self.SetFlag('commit', '0')
  1489. else:
  1490. raise NotImplementedError()
  1491. def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit,
  1492. directory):
  1493. # TODO(maruel): Use apply_issue.py
  1494. # PatchIssue should never be called with a dirty tree. It is up to the
  1495. # caller to check this, but just in case we assert here since the
  1496. # consequences of the caller not checking this could be dire.
  1497. assert(not git_common.is_dirty_git_tree('apply'))
  1498. assert(parsed_issue_arg.valid)
  1499. self._changelist.issue = parsed_issue_arg.issue
  1500. if parsed_issue_arg.hostname:
  1501. self._rietveld_server = 'https://%s' % parsed_issue_arg.hostname
  1502. if (isinstance(parsed_issue_arg, _RietveldParsedIssueNumberArgument) and
  1503. parsed_issue_arg.patch_url):
  1504. assert parsed_issue_arg.patchset
  1505. patchset = parsed_issue_arg.patchset
  1506. patch_data = urllib2.urlopen(parsed_issue_arg.patch_url).read()
  1507. else:
  1508. patchset = parsed_issue_arg.patchset or self.GetMostRecentPatchset()
  1509. patch_data = self.GetPatchSetDiff(self.GetIssue(), patchset)
  1510. # Switch up to the top-level directory, if necessary, in preparation for
  1511. # applying the patch.
  1512. top = settings.GetRelativeRoot()
  1513. if top:
  1514. os.chdir(top)
  1515. # Git patches have a/ at the beginning of source paths. We strip that out
  1516. # with a sed script rather than the -p flag to patch so we can feed either
  1517. # Git or svn-style patches into the same apply command.
  1518. # re.sub() should be used but flags=re.MULTILINE is only in python 2.7.
  1519. try:
  1520. patch_data = subprocess2.check_output(
  1521. ['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'], stdin=patch_data)
  1522. except subprocess2.CalledProcessError:
  1523. DieWithError('Git patch mungling failed.')
  1524. logging.info(patch_data)
  1525. # We use "git apply" to apply the patch instead of "patch" so that we can
  1526. # pick up file adds.
  1527. # The --index flag means: also insert into the index (so we catch adds).
  1528. cmd = ['git', 'apply', '--index', '-p0']
  1529. if directory:
  1530. cmd.extend(('--directory', directory))
  1531. if reject:
  1532. cmd.append('--reject')
  1533. elif IsGitVersionAtLeast('1.7.12'):
  1534. cmd.append('--3way')
  1535. try:
  1536. subprocess2.check_call(cmd, env=GetNoGitPagerEnv(),
  1537. stdin=patch_data, stdout=subprocess2.VOID)
  1538. except subprocess2.CalledProcessError:
  1539. print 'Failed to apply the patch'
  1540. return 1
  1541. # If we had an issue, commit the current state and register the issue.
  1542. if not nocommit:
  1543. RunGit(['commit', '-m', (self.GetDescription() + '\n\n' +
  1544. 'patch from issue %(i)s at patchset '
  1545. '%(p)s (http://crrev.com/%(i)s#ps%(p)s)'
  1546. % {'i': self.GetIssue(), 'p': patchset})])
  1547. self.SetIssue(self.GetIssue())
  1548. self.SetPatchset(patchset)
  1549. print "Committed patch locally."
  1550. else:
  1551. print "Patch applied to index."
  1552. return 0
  1553. @staticmethod
  1554. def ParseIssueURL(parsed_url):
  1555. if not parsed_url.scheme or not parsed_url.scheme.startswith('http'):
  1556. return None
  1557. # Typical url: https://domain/<issue_number>[/[other]]
  1558. match = re.match('/(\d+)(/.*)?$', parsed_url.path)
  1559. if match:
  1560. return _RietveldParsedIssueNumberArgument(
  1561. issue=int(match.group(1)),
  1562. hostname=parsed_url.netloc)
  1563. # Rietveld patch: https://domain/download/issue<number>_<patchset>.diff
  1564. match = re.match(r'/download/issue(\d+)_(\d+).diff$', parsed_url.path)
  1565. if match:
  1566. return _RietveldParsedIssueNumberArgument(
  1567. issue=int(match.group(1)),
  1568. patchset=int(match.group(2)),
  1569. hostname=parsed_url.netloc,
  1570. patch_url=gclient_utils.UpgradeToHttps(parsed_url.geturl()))
  1571. return None
  1572. def CMDUploadChange(self, options, args, change):
  1573. """Upload the patch to Rietveld."""
  1574. upload_args = ['--assume_yes'] # Don't ask about untracked files.
  1575. upload_args.extend(['--server', self.GetCodereviewServer()])
  1576. upload_args.extend(auth.auth_config_to_command_options(self._auth_config))
  1577. if options.emulate_svn_auto_props:
  1578. upload_args.append('--emulate_svn_auto_props')
  1579. change_desc = None
  1580. if options.email is not None:
  1581. upload_args.extend(['--email', options.email])
  1582. if self.GetIssue():
  1583. if options.title:
  1584. upload_args.extend(['--title', options.title])
  1585. if options.message:
  1586. upload_args.extend(['--message', options.message])
  1587. upload_args.extend(['--issue', str(self.GetIssue())])
  1588. print ('This branch is associated with issue %s. '
  1589. 'Adding patch to that issue.' % self.GetIssue())
  1590. else:
  1591. if options.title:
  1592. upload_args.extend(['--title', options.title])
  1593. message = (options.title or options.message or
  1594. CreateDescriptionFromLog(args))
  1595. change_desc = ChangeDescription(message)
  1596. if options.reviewers or options.tbr_owners:
  1597. change_desc.update_reviewers(options.reviewers,
  1598. options.tbr_owners,
  1599. change)
  1600. if not options.force:
  1601. change_desc.prompt()
  1602. if not change_desc.description:
  1603. print "Description is empty; aborting."
  1604. return 1
  1605. upload_args.extend(['--message', change_desc.description])
  1606. if change_desc.get_reviewers():
  1607. upload_args.append('--reviewers=%s' % ','.join(
  1608. change_desc.get_reviewers()))
  1609. if options.send_mail:
  1610. if not change_desc.get_reviewers():
  1611. DieWithError("Must specify reviewers to send email.")
  1612. upload_args.append('--send_mail')
  1613. # We check this before applying rietveld.private assuming that in
  1614. # rietveld.cc only addresses which we can send private CLs to are listed
  1615. # if rietveld.private is set, and so we should ignore rietveld.cc only
  1616. # when --private is specified explicitly on the command line.
  1617. if options.private:
  1618. logging.warn('rietveld.cc is ignored since private flag is specified. '
  1619. 'You need to review and add them manually if necessary.')
  1620. cc = self.GetCCListWithoutDefault()
  1621. else:
  1622. cc = self.GetCCList()
  1623. cc = ','.join(filter(None, (cc, ','.join(options.cc))))
  1624. if cc:
  1625. upload_args.extend(['--cc', cc])
  1626. if options.private or settings.GetDefaultPrivateFlag() == "True":
  1627. upload_args.append('--private')
  1628. upload_args.extend(['--git_similarity', str(options.similarity)])
  1629. if not options.find_copies:
  1630. upload_args.extend(['--git_no_find_copies'])
  1631. # Include the upstream repo's URL in the change -- this is useful for
  1632. # projects that have their source spread across multiple repos.
  1633. remote_url = self.GetGitBaseUrlFromConfig()
  1634. if not remote_url:
  1635. if settings.GetIsGitSvn():
  1636. remote_url = self.GetGitSvnRemoteUrl()
  1637. else:
  1638. if self.GetRemoteUrl() and '/' in self.GetUpstreamBranch():
  1639. remote_url = '%s@%s' % (self.GetRemoteUrl(),
  1640. self.GetUpstreamBranch().split('/')[-1])
  1641. if remote_url:
  1642. upload_args.extend(['--base_url', remote_url])
  1643. remote, remote_branch = self.GetRemoteBranch()
  1644. target_ref = GetTargetRef(remote, remote_branch, options.target_branch,
  1645. settings.GetPendingRefPrefix())
  1646. if target_ref:
  1647. upload_args.extend(['--target_ref', target_ref])
  1648. # Look for dependent patchsets. See crbug.com/480453 for more details.
  1649. remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
  1650. upstream_branch = ShortBranchName(upstream_branch)
  1651. if remote is '.':
  1652. # A local branch is being tracked.
  1653. local_branch = upstream_branch
  1654. if settings.GetIsSkipDependencyUpload(local_branch):
  1655. print
  1656. print ('Skipping dependency patchset upload because git config '
  1657. 'branch.%s.skip-deps-uploads is set to True.' % local_branch)
  1658. print
  1659. else:
  1660. auth_config = auth.extract_auth_config_from_options(options)
  1661. branch_cl = Changelist(branchref='refs/heads/'+local_branch,
  1662. auth_config=auth_config)
  1663. branch_cl_issue_url = branch_cl.GetIssueURL()
  1664. branch_cl_issue = branch_cl.GetIssue()
  1665. branch_cl_patchset = branch_cl.GetPatchset()
  1666. if branch_cl_issue_url and branch_cl_issue and branch_cl_patchset:
  1667. upload_args.extend(
  1668. ['--depends_on_patchset', '%s:%s' % (
  1669. branch_cl_issue, branch_cl_patchset)])
  1670. print(
  1671. '\n'
  1672. 'The current branch (%s) is tracking a local branch (%s) with '
  1673. 'an associated CL.\n'
  1674. 'Adding %s/#ps%s as a dependency patchset.\n'
  1675. '\n' % (self.GetBranch(), local_branch, branch_cl_issue_url,
  1676. branch_cl_patchset))
  1677. project = settings.GetProject()
  1678. if project:
  1679. upload_args.extend(['--project', project])
  1680. if options.cq_dry_run:
  1681. upload_args.extend(['--cq_dry_run'])
  1682. try:
  1683. upload_args = ['upload'] + upload_args + args
  1684. logging.info('upload.RealMain(%s)', upload_args)
  1685. issue, patchset = upload.RealMain(upload_args)
  1686. issue = int(issue)
  1687. patchset = int(patchset)
  1688. except KeyboardInterrupt:
  1689. sys.exit(1)
  1690. except:
  1691. # If we got an exception after the user typed a description for their
  1692. # change, back up the description before re-raising.
  1693. if change_desc:
  1694. backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE)
  1695. print('\nGot exception while uploading -- saving description to %s\n' %
  1696. backup_path)
  1697. backup_file = open(backup_path, 'w')
  1698. backup_file.write(change_desc.description)
  1699. backup_file.close()
  1700. raise
  1701. if not self.GetIssue():
  1702. self.SetIssue(issue)
  1703. self.SetPatchset(patchset)
  1704. if options.use_commit_queue:
  1705. self.SetCQState(_CQState.COMMIT)
  1706. return 0
  1707. class _GerritChangelistImpl(_ChangelistCodereviewBase):
  1708. def __init__(self, changelist, auth_config=None):
  1709. # auth_config is Rietveld thing, kept here to preserve interface only.
  1710. super(_GerritChangelistImpl, self).__init__(changelist)
  1711. self._change_id = None
  1712. # Lazily cached values.
  1713. self._gerrit_server = None # e.g. https://chromium-review.googlesource.com
  1714. self._gerrit_host = None # e.g. chromium-review.googlesource.com
  1715. def _GetGerritHost(self):
  1716. # Lazy load of configs.
  1717. self.GetCodereviewServer()
  1718. return self._gerrit_host
  1719. def _GetGitHost(self):
  1720. """Returns git host to be used when uploading change to Gerrit."""
  1721. return urlparse.urlparse(self.GetRemoteUrl()).netloc
  1722. def GetCodereviewServer(self):
  1723. if not self._gerrit_server:
  1724. # If we're on a branch then get the server potentially associated
  1725. # with that branch.
  1726. if self.GetIssue():
  1727. gerrit_server_setting = self.GetCodereviewServerSetting()
  1728. if gerrit_server_setting:
  1729. self._gerrit_server = RunGit(['config', gerrit_server_setting],
  1730. error_ok=True).strip()
  1731. if self._gerrit_server:
  1732. self._gerrit_host = urlparse.urlparse(self._gerrit_server).netloc
  1733. if not self._gerrit_server:
  1734. # We assume repo to be hosted on Gerrit, and hence Gerrit server
  1735. # has "-review" suffix for lowest level subdomain.
  1736. parts = self._GetGitHost().split('.')
  1737. parts[0] = parts[0] + '-review'
  1738. self._gerrit_host = '.'.join(parts)
  1739. self._gerrit_server = 'https://%s' % self._gerrit_host
  1740. return self._gerrit_server
  1741. @classmethod
  1742. def IssueSettingSuffix(cls):
  1743. return 'gerritissue'
  1744. def EnsureAuthenticated(self, force):
  1745. """Best effort check that user is authenticated with Gerrit server."""
  1746. if settings.GetGerritSkipEnsureAuthenticated():
  1747. # For projects with unusual authentication schemes.
  1748. # See http://crbug.com/603378.
  1749. return
  1750. # Lazy-loader to identify Gerrit and Git hosts.
  1751. if gerrit_util.GceAuthenticator.is_gce():
  1752. return
  1753. self.GetCodereviewServer()
  1754. git_host = self._GetGitHost()
  1755. assert self._gerrit_server and self._gerrit_host
  1756. cookie_auth = gerrit_util.CookiesAuthenticator()
  1757. gerrit_auth = cookie_auth.get_auth_header(self._gerrit_host)
  1758. git_auth = cookie_auth.get_auth_header(git_host)
  1759. if gerrit_auth and git_auth:
  1760. if gerrit_auth == git_auth:
  1761. return
  1762. print((
  1763. 'WARNING: you have different credentials for Gerrit and git hosts.\n'
  1764. ' Check your %s or %s file for credentials of hosts:\n'
  1765. ' %s\n'
  1766. ' %s\n'
  1767. ' %s') %
  1768. (cookie_auth.get_gitcookies_path(), cookie_auth.get_netrc_path(),
  1769. git_host, self._gerrit_host,
  1770. cookie_auth.get_new_password_message(git_host)))
  1771. if not force:
  1772. ask_for_data('If you know what you are doing, press Enter to continue, '
  1773. 'Ctrl+C to abort.')
  1774. return
  1775. else:
  1776. missing = (
  1777. [] if gerrit_auth else [self._gerrit_host] +
  1778. [] if git_auth else [git_host])
  1779. DieWithError('Credentials for the following hosts are required:\n'
  1780. ' %s\n'
  1781. 'These are read from %s (or legacy %s)\n'
  1782. '%s' % (
  1783. '\n '.join(missing),
  1784. cookie_auth.get_gitcookies_path(),
  1785. cookie_auth.get_netrc_path(),
  1786. cookie_auth.get_new_password_message(git_host)))
  1787. def PatchsetSetting(self):
  1788. """Return the git setting that stores this change's most recent patchset."""
  1789. return 'branch.%s.gerritpatchset' % self.GetBranch()
  1790. def GetCodereviewServerSetting(self):
  1791. """Returns the git setting that stores this change's Gerrit server."""
  1792. branch = self.GetBranch()
  1793. if branch:
  1794. return 'branch.%s.gerritserver' % branch
  1795. return None
  1796. def GetRieveldObjForPresubmit(self):
  1797. class ThisIsNotRietveldIssue(object):
  1798. def __nonzero__(self):
  1799. # This is a hack to make presubmit_support think that rietveld is not
  1800. # defined, yet still ensure that calls directly result in a decent
  1801. # exception message below.
  1802. return False
  1803. def __getattr__(self, attr):
  1804. print(
  1805. 'You aren\'t using Rietveld at the moment, but Gerrit.\n'
  1806. 'Using Rietveld in your PRESUBMIT scripts won\'t work.\n'
  1807. 'Please, either change your PRESUBIT to not use rietveld_obj.%s,\n'
  1808. 'or use Rietveld for codereview.\n'
  1809. 'See also http://crbug.com/579160.' % attr)
  1810. raise NotImplementedError()
  1811. return ThisIsNotRietveldIssue()
  1812. def GetGerritObjForPresubmit(self):
  1813. return presubmit_support.GerritAccessor(self._GetGerritHost())
  1814. def GetStatus(self):
  1815. """Apply a rough heuristic to give a simple summary of an issue's review
  1816. or CQ status, assuming adherence to a common workflow.
  1817. Returns None if no issue for this branch, or one of the following keywords:
  1818. * 'error' - error from review tool (including deleted issues)
  1819. * 'unsent' - no reviewers added
  1820. * 'waiting' - waiting for review
  1821. * 'reply' - waiting for owner to reply to review
  1822. * 'not lgtm' - Code-Review -2 from at least one approved reviewer
  1823. * 'lgtm' - Code-Review +2 from at least one approved reviewer
  1824. * 'commit' - in the commit queue
  1825. * 'closed' - abandoned
  1826. """
  1827. if not self.GetIssue():
  1828. return None
  1829. try:
  1830. data = self._GetChangeDetail(['DETAILED_LABELS', 'CURRENT_REVISION'])
  1831. except httplib.HTTPException:
  1832. return 'error'
  1833. if data['status'] in ('ABANDONED', 'MERGED'):
  1834. return 'closed'
  1835. cq_label = data['labels'].get('Commit-Queue', {})
  1836. if cq_label:
  1837. # Vote value is a stringified integer, which we expect from 0 to 2.
  1838. vote_value = cq_label.get('value', '0')
  1839. vote_text = cq_label.get('values', {}).get(vote_value, '')
  1840. if vote_text.lower() == 'commit':
  1841. return 'commit'
  1842. lgtm_label = data['labels'].get('Code-Review', {})
  1843. if lgtm_label:
  1844. if 'rejected' in lgtm_label:
  1845. return 'not lgtm'
  1846. if 'approved' in lgtm_label:
  1847. return 'lgtm'
  1848. if not data.get('reviewers', {}).get('REVIEWER', []):
  1849. return 'unsent'
  1850. messages = data.get('messages', [])
  1851. if messages:
  1852. owner = data['owner'].get('_account_id')
  1853. last_message_author = messages[-1].get('author', {}).get('_account_id')
  1854. if owner != last_message_author:
  1855. # Some reply from non-owner.
  1856. return 'reply'
  1857. return 'waiting'
  1858. def GetMostRecentPatchset(self):
  1859. data = self._GetChangeDetail(['CURRENT_REVISION'])
  1860. return data['revisions'][data['current_revision']]['_number']
  1861. def FetchDescription(self):
  1862. data = self._GetChangeDetail(['CURRENT_REVISION'])
  1863. current_rev = data['current_revision']
  1864. url = data['revisions'][current_rev]['fetch']['http']['url']
  1865. return gerrit_util.GetChangeDescriptionFromGitiles(url, current_rev)
  1866. def UpdateDescriptionRemote(self, description):
  1867. gerrit_util.SetCommitMessage(self._GetGerritHost(), self.GetIssue(),
  1868. description)
  1869. def CloseIssue(self):
  1870. gerrit_util.AbandonChange(self._GetGerritHost(), self.GetIssue(), msg='')
  1871. def GetApprovingReviewers(self):
  1872. """Returns a list of reviewers approving the change.
  1873. Note: not necessarily committers.
  1874. """
  1875. raise NotImplementedError()
  1876. def SubmitIssue(self, wait_for_merge=True):
  1877. gerrit_util.SubmitChange(self._GetGerritHost(), self.GetIssue(),
  1878. wait_for_merge=wait_for_merge)
  1879. def _GetChangeDetail(self, options=None, issue=None):
  1880. options = options or []
  1881. issue = issue or self.GetIssue()
  1882. assert issue, 'issue required to query Gerrit'
  1883. return gerrit_util.GetChangeDetail(self._GetGerritHost(), str(issue),
  1884. options)
  1885. def CMDLand(self, force, bypass_hooks, verbose):
  1886. if git_common.is_dirty_git_tree('land'):
  1887. return 1
  1888. differs = True
  1889. last_upload = RunGit(['config',
  1890. 'branch.%s.gerritsquashhash' % self.GetBranch()],
  1891. error_ok=True).strip()
  1892. # Note: git diff outputs nothing if there is no diff.
  1893. if not last_upload or RunGit(['diff', last_upload]).strip():
  1894. print('WARNING: some changes from local branch haven\'t been uploaded')
  1895. else:
  1896. detail = self._GetChangeDetail(['CURRENT_REVISION'])
  1897. if detail['current_revision'] == last_upload:
  1898. differs = False
  1899. else:
  1900. print('WARNING: local branch contents differ from latest uploaded '
  1901. 'patchset')
  1902. if differs:
  1903. if not force:
  1904. ask_for_data(
  1905. 'Do you want to submit latest Gerrit patchset and bypass hooks?')
  1906. print('WARNING: bypassing hooks and submitting latest uploaded patchset')
  1907. elif not bypass_hooks:
  1908. hook_results = self.RunHook(
  1909. committing=True,
  1910. may_prompt=not force,
  1911. verbose=verbose,
  1912. change=self.GetChange(self.GetCommonAncestorWithUpstream(), None))
  1913. if not hook_results.should_continue():
  1914. return 1
  1915. self.SubmitIssue(wait_for_merge=True)
  1916. print('Issue %s has been submitted.' % self.GetIssueURL())
  1917. return 0
  1918. def CMDPatchWithParsedIssue(self, parsed_issue_arg, reject, nocommit,
  1919. directory):
  1920. assert not reject
  1921. assert not nocommit
  1922. assert not directory
  1923. assert parsed_issue_arg.valid
  1924. self._changelist.issue = parsed_issue_arg.issue
  1925. if parsed_issue_arg.hostname:
  1926. self._gerrit_host = parsed_issue_arg.hostname
  1927. self._gerrit_server = 'https://%s' % self._gerrit_host
  1928. detail = self._GetChangeDetail(['ALL_REVISIONS'])
  1929. if not parsed_issue_arg.patchset:
  1930. # Use current revision by default.
  1931. revision_info = detail['revisions'][detail['current_revision']]
  1932. patchset = int(revision_info['_number'])
  1933. else:
  1934. patchset = parsed_issue_arg.patchset
  1935. for revision_info in detail['revisions'].itervalues():
  1936. if int(revision_info['_number']) == parsed_issue_arg.patchset:
  1937. break
  1938. else:
  1939. DieWithError('Couldn\'t find patchset %i in issue %i' %
  1940. (parsed_issue_arg.patchset, self.GetIssue()))
  1941. fetch_info = revision_info['fetch']['http']
  1942. RunGit(['fetch', fetch_info['url'], fetch_info['ref']])
  1943. RunGit(['cherry-pick', 'FETCH_HEAD'])
  1944. self.SetIssue(self.GetIssue())
  1945. self.SetPatchset(patchset)
  1946. print('Committed patch for issue %i pathset %i locally' %
  1947. (self.GetIssue(), self.GetPatchset()))
  1948. return 0
  1949. @staticmethod
  1950. def ParseIssueURL(parsed_url):
  1951. if not parsed_url.scheme or not parsed_url.scheme.startswith('http'):
  1952. return None
  1953. # Gerrit's new UI is https://domain/c/<issue_number>[/[patchset]]
  1954. # But current GWT UI is https://domain/#/c/<issue_number>[/[patchset]]
  1955. # Short urls like https://domain/<issue_number> can be used, but don't allow
  1956. # specifying the patchset (you'd 404), but we allow that here.
  1957. if parsed_url.path == '/':
  1958. part = parsed_url.fragment
  1959. else:
  1960. part = parsed_url.path
  1961. match = re.match('(/c)?/(\d+)(/(\d+)?/?)?$', part)
  1962. if match:
  1963. return _ParsedIssueNumberArgument(
  1964. issue=int(match.group(2)),
  1965. patchset=int(match.group(4)) if match.group(4) else None,
  1966. hostname=parsed_url.netloc)
  1967. return None
  1968. def CMDUploadChange(self, options, args, change):
  1969. """Upload the current branch to Gerrit."""
  1970. if options.squash and options.no_squash:
  1971. DieWithError('Can only use one of --squash or --no-squash')
  1972. options.squash = ((settings.GetSquashGerritUploads() or options.squash) and
  1973. not options.no_squash)
  1974. # We assume the remote called "origin" is the one we want.
  1975. # It is probably not worthwhile to support different workflows.
  1976. gerrit_remote = 'origin'
  1977. remote, remote_branch = self.GetRemoteBranch()
  1978. branch = GetTargetRef(remote, remote_branch, options.target_branch,
  1979. pending_prefix='')
  1980. if options.squash:
  1981. if not self.GetIssue():
  1982. # TODO(tandrii): deperecate this after 2016Q2. Backwards compatibility
  1983. # with shadow branch, which used to contain change-id for a given
  1984. # branch, using which we can fetch actual issue number and set it as the
  1985. # property of the branch, which is the new way.
  1986. message = RunGitSilent([
  1987. 'show', '--format=%B', '-s',
  1988. 'refs/heads/git_cl_uploads/%s' % self.GetBranch()])
  1989. if message:
  1990. change_ids = git_footers.get_footer_change_id(message.strip())
  1991. if change_ids and len(change_ids) == 1:
  1992. details = self._GetChangeDetail(issue=change_ids[0])
  1993. if details:
  1994. print('WARNING: found old upload in branch git_cl_uploads/%s '
  1995. 'corresponding to issue %s' %
  1996. (self.GetBranch(), details['_number']))
  1997. self.SetIssue(details['_number'])
  1998. if not self.GetIssue():
  1999. DieWithError(
  2000. '\n' # For readability of the blob below.
  2001. 'Found old upload in branch git_cl_uploads/%s, '
  2002. 'but failed to find corresponding Gerrit issue.\n'
  2003. 'If you know the issue number, set it manually first:\n'
  2004. ' git cl issue 123456\n'
  2005. 'If you intended to upload this CL as new issue, '
  2006. 'just delete or rename the old upload branch:\n'
  2007. ' git rename-branch git_cl_uploads/%s old_upload-%s\n'
  2008. 'After that, please run git cl upload again.' %
  2009. tuple([self.GetBranch()] * 3))
  2010. # End of backwards compatability.
  2011. if self.GetIssue():
  2012. # Try to get the message from a previous upload.
  2013. message = self.GetDescription()
  2014. if not message:
  2015. DieWithError(
  2016. 'failed to fetch description from current Gerrit issue %d\n'
  2017. '%s' % (self.GetIssue(), self.GetIssueURL()))
  2018. change_id = self._GetChangeDetail()['change_id']
  2019. while True:
  2020. footer_change_ids = git_footers.get_footer_change_id(message)
  2021. if footer_change_ids == [change_id]:
  2022. break
  2023. if not footer_change_ids:
  2024. message = git_footers.add_footer_change_id(message, change_id)
  2025. print('WARNING: appended missing Change-Id to issue description')
  2026. continue
  2027. # There is already a valid footer but with different or several ids.
  2028. # Doing this automatically is non-trivial as we don't want to lose
  2029. # existing other footers, yet we want to append just 1 desired
  2030. # Change-Id. Thus, just create a new footer, but let user verify the
  2031. # new description.
  2032. message = '%s\n\nChange-Id: %s' % (message, change_id)
  2033. print(
  2034. 'WARNING: issue %s has Change-Id footer(s):\n'
  2035. ' %s\n'
  2036. 'but issue has Change-Id %s, according to Gerrit.\n'
  2037. 'Please, check the proposed correction to the description, '
  2038. 'and edit it if necessary but keep the "Change-Id: %s" footer\n'
  2039. % (self.GetIssue(), '\n '.join(footer_change_ids), change_id,
  2040. change_id))
  2041. ask_for_data('Press enter to edit now, Ctrl+C to abort')
  2042. if not options.force:
  2043. change_desc = ChangeDescription(message)
  2044. change_desc.prompt()
  2045. message = change_desc.description
  2046. if not message:
  2047. DieWithError("Description is empty. Aborting...")
  2048. # Continue the while loop.
  2049. # Sanity check of this code - we should end up with proper message
  2050. # footer.
  2051. assert [change_id] == git_footers.get_footer_change_id(message)
  2052. change_desc = ChangeDescription(message)
  2053. else:
  2054. change_desc = ChangeDescription(
  2055. options.message or CreateDescriptionFromLog(args))
  2056. if not options.force:
  2057. change_desc.prompt()
  2058. if not change_desc.description:
  2059. DieWithError("Description is empty. Aborting...")
  2060. message = change_desc.description
  2061. change_ids = git_footers.get_footer_change_id(message)
  2062. if len(change_ids) > 1:
  2063. DieWithError('too many Change-Id footers, at most 1 allowed.')
  2064. if not change_ids:
  2065. # Generate the Change-Id automatically.
  2066. message = git_footers.add_footer_change_id(
  2067. message, GenerateGerritChangeId(message))
  2068. change_desc.set_description(message)
  2069. change_ids = git_footers.get_footer_change_id(message)
  2070. assert len(change_ids) == 1
  2071. change_id = change_ids[0]
  2072. remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
  2073. if remote is '.':
  2074. # If our upstream branch is local, we base our squashed commit on its
  2075. # squashed version.
  2076. upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch)
  2077. # Check the squashed hash of the parent.
  2078. parent = RunGit(['config',
  2079. 'branch.%s.gerritsquashhash' % upstream_branch_name],
  2080. error_ok=True).strip()
  2081. # Verify that the upstream branch has been uploaded too, otherwise
  2082. # Gerrit will create additional CLs when uploading.
  2083. if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) !=
  2084. RunGitSilent(['rev-parse', parent + ':'])):
  2085. # TODO(tandrii): remove "old depot_tools" part on April 12, 2016.
  2086. DieWithError(
  2087. 'Upload upstream branch %s first.\n'
  2088. 'Note: maybe you\'ve uploaded it with --no-squash or with an old '
  2089. 'version of depot_tools. If so, then re-upload it with:\n'
  2090. ' git cl upload --squash\n' % upstream_branch_name)
  2091. else:
  2092. parent = self.GetCommonAncestorWithUpstream()
  2093. tree = RunGit(['rev-parse', 'HEAD:']).strip()
  2094. ref_to_push = RunGit(['commit-tree', tree, '-p', parent,
  2095. '-m', message]).strip()
  2096. else:
  2097. change_desc = ChangeDescription(
  2098. options.message or CreateDescriptionFromLog(args))
  2099. if not change_desc.description:
  2100. DieWithError("Description is empty. Aborting...")
  2101. if not git_footers.get_footer_change_id(change_desc.description):
  2102. DownloadGerritHook(False)
  2103. change_desc.set_description(self._AddChangeIdToCommitMessage(options,
  2104. args))
  2105. ref_to_push = 'HEAD'
  2106. parent = '%s/%s' % (gerrit_remote, branch)
  2107. change_id = git_footers.get_footer_change_id(change_desc.description)[0]
  2108. assert change_desc
  2109. commits = RunGitSilent(['rev-list', '%s..%s' % (parent,
  2110. ref_to_push)]).splitlines()
  2111. if len(commits) > 1:
  2112. print('WARNING: This will upload %d commits. Run the following command '
  2113. 'to see which commits will be uploaded: ' % len(commits))
  2114. print('git log %s..%s' % (parent, ref_to_push))
  2115. print('You can also use `git squash-branch` to squash these into a '
  2116. 'single commit.')
  2117. ask_for_data('About to upload; enter to confirm.')
  2118. if options.reviewers or options.tbr_owners:
  2119. change_desc.update_reviewers(options.reviewers, options.tbr_owners,
  2120. change)
  2121. # Extra options that can be specified at push time. Doc:
  2122. # https://gerrit-review.googlesource.com/Documentation/user-upload.html
  2123. refspec_opts = []
  2124. if options.title:
  2125. # Per doc, spaces must be converted to underscores, and Gerrit will do the
  2126. # reverse on its side.
  2127. if '_' in options.title:
  2128. print('WARNING: underscores in title will be converted to spaces.')
  2129. refspec_opts.append('m=' + options.title.replace(' ', '_'))
  2130. if options.send_mail:
  2131. if not change_desc.get_reviewers():
  2132. DieWithError('Must specify reviewers to send email.')
  2133. refspec_opts.append('notify=ALL')
  2134. else:
  2135. refspec_opts.append('notify=NONE')
  2136. cc = self.GetCCList().split(',')
  2137. if options.cc:
  2138. cc.extend(options.cc)
  2139. cc = filter(None, cc)
  2140. if cc:
  2141. # refspec_opts.extend('cc=' + email.strip() for email in cc)
  2142. # TODO(tandrii): enable this back. http://crbug.com/604377
  2143. print('WARNING: Gerrit doesn\'t yet support cc-ing arbitrary emails.\n'
  2144. ' Ignoring cc-ed emails. See http://crbug.com/604377.')
  2145. if change_desc.get_reviewers():
  2146. refspec_opts.extend('r=' + email.strip()
  2147. for email in change_desc.get_reviewers())
  2148. refspec_suffix = ''
  2149. if refspec_opts:
  2150. refspec_suffix = '%' + ','.join(refspec_opts)
  2151. assert ' ' not in refspec_suffix, (
  2152. 'spaces not allowed in refspec: "%s"' % refspec_suffix)
  2153. refspec = '%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix)
  2154. push_stdout = gclient_utils.CheckCallAndFilter(
  2155. ['git', 'push', gerrit_remote, refspec],
  2156. print_stdout=True,
  2157. # Flush after every line: useful for seeing progress when running as
  2158. # recipe.
  2159. filter_fn=lambda _: sys.stdout.flush())
  2160. if options.squash:
  2161. regex = re.compile(r'remote:\s+https?://[\w\-\.\/]*/(\d+)\s.*')
  2162. change_numbers = [m.group(1)
  2163. for m in map(regex.match, push_stdout.splitlines())
  2164. if m]
  2165. if len(change_numbers) != 1:
  2166. DieWithError(
  2167. ('Created|Updated %d issues on Gerrit, but only 1 expected.\n'
  2168. 'Change-Id: %s') % (len(change_numbers), change_id))
  2169. self.SetIssue(change_numbers[0])
  2170. RunGit(['config', 'branch.%s.gerritsquashhash' % self.GetBranch(),
  2171. ref_to_push])
  2172. return 0
  2173. def _AddChangeIdToCommitMessage(self, options, args):
  2174. """Re-commits using the current message, assumes the commit hook is in
  2175. place.
  2176. """
  2177. log_desc = options.message or CreateDescriptionFromLog(args)
  2178. git_command = ['commit', '--amend', '-m', log_desc]
  2179. RunGit(git_command)
  2180. new_log_desc = CreateDescriptionFromLog(args)
  2181. if git_footers.get_footer_change_id(new_log_desc):
  2182. print 'git-cl: Added Change-Id to commit message.'
  2183. return new_log_desc
  2184. else:
  2185. print >> sys.stderr, 'ERROR: Gerrit commit-msg hook not available.'
  2186. def SetCQState(self, new_state):
  2187. """Sets the Commit-Queue label assuming canonical CQ config for Gerrit."""
  2188. # TODO(tandrii): maybe allow configurability in codereview.settings or by
  2189. # self-discovery of label config for this CL using REST API.
  2190. vote_map = {
  2191. _CQState.NONE: 0,
  2192. _CQState.DRY_RUN: 1,
  2193. _CQState.COMMIT : 2,
  2194. }
  2195. gerrit_util.SetReview(self._GetGerritHost(), self.GetIssue(),
  2196. labels={'Commit-Queue': vote_map[new_state]})
  2197. _CODEREVIEW_IMPLEMENTATIONS = {
  2198. 'rietveld': _RietveldChangelistImpl,
  2199. 'gerrit': _GerritChangelistImpl,
  2200. }
  2201. def _add_codereview_select_options(parser):
  2202. """Appends --gerrit and --rietveld options to force specific codereview."""
  2203. parser.codereview_group = optparse.OptionGroup(
  2204. parser, 'EXPERIMENTAL! Codereview override options')
  2205. parser.add_option_group(parser.codereview_group)
  2206. parser.codereview_group.add_option(
  2207. '--gerrit', action='store_true',
  2208. help='Force the use of Gerrit for codereview')
  2209. parser.codereview_group.add_option(
  2210. '--rietveld', action='store_true',
  2211. help='Force the use of Rietveld for codereview')
  2212. def _process_codereview_select_options(parser, options):
  2213. if options.gerrit and options.rietveld:
  2214. parser.error('Options --gerrit and --rietveld are mutually exclusive')
  2215. options.forced_codereview = None
  2216. if options.gerrit:
  2217. options.forced_codereview = 'gerrit'
  2218. elif options.rietveld:
  2219. options.forced_codereview = 'rietveld'
  2220. class ChangeDescription(object):
  2221. """Contains a parsed form of the change description."""
  2222. R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$'
  2223. BUG_LINE = r'^[ \t]*(BUG)[ \t]*=[ \t]*(.*?)[ \t]*$'
  2224. def __init__(self, description):
  2225. self._description_lines = (description or '').strip().splitlines()
  2226. @property # www.logilab.org/ticket/89786
  2227. def description(self): # pylint: disable=E0202
  2228. return '\n'.join(self._description_lines)
  2229. def set_description(self, desc):
  2230. if isinstance(desc, basestring):
  2231. lines = desc.splitlines()
  2232. else:
  2233. lines = [line.rstrip() for line in desc]
  2234. while lines and not lines[0]:
  2235. lines.pop(0)
  2236. while lines and not lines[-1]:
  2237. lines.pop(-1)
  2238. self._description_lines = lines
  2239. def update_reviewers(self, reviewers, add_owners_tbr=False, change=None):
  2240. """Rewrites the R=/TBR= line(s) as a single line each."""
  2241. assert isinstance(reviewers, list), reviewers
  2242. if not reviewers and not add_owners_tbr:
  2243. return
  2244. reviewers = reviewers[:]
  2245. # Get the set of R= and TBR= lines and remove them from the desciption.
  2246. regexp = re.compile(self.R_LINE)
  2247. matches = [regexp.match(line) for line in self._description_lines]
  2248. new_desc = [l for i, l in enumerate(self._description_lines)
  2249. if not matches[i]]
  2250. self.set_description(new_desc)
  2251. # Construct new unified R= and TBR= lines.
  2252. r_names = []
  2253. tbr_names = []
  2254. for match in matches:
  2255. if not match:
  2256. continue
  2257. people = cleanup_list([match.group(2).strip()])
  2258. if match.group(1) == 'TBR':
  2259. tbr_names.extend(people)
  2260. else:
  2261. r_names.extend(people)
  2262. for name in r_names:
  2263. if name not in reviewers:
  2264. reviewers.append(name)
  2265. if add_owners_tbr:
  2266. owners_db = owners.Database(change.RepositoryRoot(),
  2267. fopen=file, os_path=os.path, glob=glob.glob)
  2268. all_reviewers = set(tbr_names + reviewers)
  2269. missing_files = owners_db.files_not_covered_by(change.LocalPaths(),
  2270. all_reviewers)
  2271. tbr_names.extend(owners_db.reviewers_for(missing_files,
  2272. change.author_email))
  2273. new_r_line = 'R=' + ', '.join(reviewers) if reviewers else None
  2274. new_tbr_line = 'TBR=' + ', '.join(tbr_names) if tbr_names else None
  2275. # Put the new lines in the description where the old first R= line was.
  2276. line_loc = next((i for i, match in enumerate(matches) if match), -1)
  2277. if 0 <= line_loc < len(self._description_lines):
  2278. if new_tbr_line:
  2279. self._description_lines.insert(line_loc, new_tbr_line)
  2280. if new_r_line:
  2281. self._description_lines.insert(line_loc, new_r_line)
  2282. else:
  2283. if new_r_line:
  2284. self.append_footer(new_r_line)
  2285. if new_tbr_line:
  2286. self.append_footer(new_tbr_line)
  2287. def prompt(self):
  2288. """Asks the user to update the description."""
  2289. self.set_description([
  2290. '# Enter a description of the change.',
  2291. '# This will be displayed on the codereview site.',
  2292. '# The first line will also be used as the subject of the review.',
  2293. '#--------------------This line is 72 characters long'
  2294. '--------------------',
  2295. ] + self._description_lines)
  2296. regexp = re.compile(self.BUG_LINE)
  2297. if not any((regexp.match(line) for line in self._description_lines)):
  2298. self.append_footer('BUG=%s' % settings.GetBugPrefix())
  2299. content = gclient_utils.RunEditor(self.description, True,
  2300. git_editor=settings.GetGitEditor())
  2301. if not content:
  2302. DieWithError('Running editor failed')
  2303. lines = content.splitlines()
  2304. # Strip off comments.
  2305. clean_lines = [line.rstrip() for line in lines if not line.startswith('#')]
  2306. if not clean_lines:
  2307. DieWithError('No CL description, aborting')
  2308. self.set_description(clean_lines)
  2309. def append_footer(self, line):
  2310. if self._description_lines:
  2311. # Add an empty line if either the last line or the new line isn't a tag.
  2312. last_line = self._description_lines[-1]
  2313. if (not presubmit_support.Change.TAG_LINE_RE.match(last_line) or
  2314. not presubmit_support.Change.TAG_LINE_RE.match(line)):
  2315. self._description_lines.append('')
  2316. self._description_lines.append(line)
  2317. def get_reviewers(self):
  2318. """Retrieves the list of reviewers."""
  2319. matches = [re.match(self.R_LINE, line) for line in self._description_lines]
  2320. reviewers = [match.group(2).strip() for match in matches if match]
  2321. return cleanup_list(reviewers)
  2322. def get_approving_reviewers(props):
  2323. """Retrieves the reviewers that approved a CL from the issue properties with
  2324. messages.
  2325. Note that the list may contain reviewers that are not committer, thus are not
  2326. considered by the CQ.
  2327. """
  2328. return sorted(
  2329. set(
  2330. message['sender']
  2331. for message in props['messages']
  2332. if message['approval'] and message['sender'] in props['reviewers']
  2333. )
  2334. )
  2335. def FindCodereviewSettingsFile(filename='codereview.settings'):
  2336. """Finds the given file starting in the cwd and going up.
  2337. Only looks up to the top of the repository unless an
  2338. 'inherit-review-settings-ok' file exists in the root of the repository.
  2339. """
  2340. inherit_ok_file = 'inherit-review-settings-ok'
  2341. cwd = os.getcwd()
  2342. root = settings.GetRoot()
  2343. if os.path.isfile(os.path.join(root, inherit_ok_file)):
  2344. root = '/'
  2345. while True:
  2346. if filename in os.listdir(cwd):
  2347. if os.path.isfile(os.path.join(cwd, filename)):
  2348. return open(os.path.join(cwd, filename))
  2349. if cwd == root:
  2350. break
  2351. cwd = os.path.dirname(cwd)
  2352. def LoadCodereviewSettingsFromFile(fileobj):
  2353. """Parse a codereview.settings file and updates hooks."""
  2354. keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read())
  2355. def SetProperty(name, setting, unset_error_ok=False):
  2356. fullname = 'rietveld.' + name
  2357. if setting in keyvals:
  2358. RunGit(['config', fullname, keyvals[setting]])
  2359. else:
  2360. RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok)
  2361. SetProperty('server', 'CODE_REVIEW_SERVER')
  2362. # Only server setting is required. Other settings can be absent.
  2363. # In that case, we ignore errors raised during option deletion attempt.
  2364. SetProperty('cc', 'CC_LIST', unset_error_ok=True)
  2365. SetProperty('private', 'PRIVATE', unset_error_ok=True)
  2366. SetProperty('tree-status-url', 'STATUS', unset_error_ok=True)
  2367. SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True)
  2368. SetProperty('bug-prefix', 'BUG_PREFIX', unset_error_ok=True)
  2369. SetProperty('cpplint-regex', 'LINT_REGEX', unset_error_ok=True)
  2370. SetProperty('force-https-commit-url', 'FORCE_HTTPS_COMMIT_URL',
  2371. unset_error_ok=True)
  2372. SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX', unset_error_ok=True)
  2373. SetProperty('project', 'PROJECT', unset_error_ok=True)
  2374. SetProperty('pending-ref-prefix', 'PENDING_REF_PREFIX', unset_error_ok=True)
  2375. SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK',
  2376. unset_error_ok=True)
  2377. if 'GERRIT_HOST' in keyvals:
  2378. RunGit(['config', 'gerrit.host', keyvals['GERRIT_HOST']])
  2379. if 'GERRIT_SQUASH_UPLOADS' in keyvals:
  2380. RunGit(['config', 'gerrit.squash-uploads',
  2381. keyvals['GERRIT_SQUASH_UPLOADS']])
  2382. if 'GERRIT_SKIP_ENSURE_AUTHENTICATED' in keyvals:
  2383. RunGit(['config', 'gerrit.skip-ensure-authenticated',
  2384. keyvals['GERRIT_SKIP_ENSURE_AUTHENTICATED']])
  2385. if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals:
  2386. #should be of the form
  2387. #PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof
  2388. #ORIGIN_URL_CONFIG: http://src.chromium.org/git
  2389. RunGit(['config', keyvals['PUSH_URL_CONFIG'],
  2390. keyvals['ORIGIN_URL_CONFIG']])
  2391. def urlretrieve(source, destination):
  2392. """urllib is broken for SSL connections via a proxy therefore we
  2393. can't use urllib.urlretrieve()."""
  2394. with open(destination, 'w') as f:
  2395. f.write(urllib2.urlopen(source).read())
  2396. def hasSheBang(fname):
  2397. """Checks fname is a #! script."""
  2398. with open(fname) as f:
  2399. return f.read(2).startswith('#!')
  2400. # TODO(bpastene) Remove once a cleaner fix to crbug.com/600473 presents itself.
  2401. def DownloadHooks(*args, **kwargs):
  2402. pass
  2403. def DownloadGerritHook(force):
  2404. """Download and install Gerrit commit-msg hook.
  2405. Args:
  2406. force: True to update hooks. False to install hooks if not present.
  2407. """
  2408. if not settings.GetIsGerrit():
  2409. return
  2410. src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg'
  2411. dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
  2412. if not os.access(dst, os.X_OK):
  2413. if os.path.exists(dst):
  2414. if not force:
  2415. return
  2416. try:
  2417. print(
  2418. 'WARNING: installing Gerrit commit-msg hook.\n'
  2419. ' This behavior of git cl will soon be disabled.\n'
  2420. ' See bug http://crbug.com/579176.')
  2421. urlretrieve(src, dst)
  2422. if not hasSheBang(dst):
  2423. DieWithError('Not a script: %s\n'
  2424. 'You need to download from\n%s\n'
  2425. 'into .git/hooks/commit-msg and '
  2426. 'chmod +x .git/hooks/commit-msg' % (dst, src))
  2427. os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
  2428. except Exception:
  2429. if os.path.exists(dst):
  2430. os.remove(dst)
  2431. DieWithError('\nFailed to download hooks.\n'
  2432. 'You need to download from\n%s\n'
  2433. 'into .git/hooks/commit-msg and '
  2434. 'chmod +x .git/hooks/commit-msg' % src)
  2435. def GetRietveldCodereviewSettingsInteractively():
  2436. """Prompt the user for settings."""
  2437. server = settings.GetDefaultServerUrl(error_ok=True)
  2438. prompt = 'Rietveld server (host[:port])'
  2439. prompt += ' [%s]' % (server or DEFAULT_SERVER)
  2440. newserver = ask_for_data(prompt + ':')
  2441. if not server and not newserver:
  2442. newserver = DEFAULT_SERVER
  2443. if newserver:
  2444. newserver = gclient_utils.UpgradeToHttps(newserver)
  2445. if newserver != server:
  2446. RunGit(['config', 'rietveld.server', newserver])
  2447. def SetProperty(initial, caption, name, is_url):
  2448. prompt = caption
  2449. if initial:
  2450. prompt += ' ("x" to clear) [%s]' % initial
  2451. new_val = ask_for_data(prompt + ':')
  2452. if new_val == 'x':
  2453. RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True)
  2454. elif new_val:
  2455. if is_url:
  2456. new_val = gclient_utils.UpgradeToHttps(new_val)
  2457. if new_val != initial:
  2458. RunGit(['config', 'rietveld.' + name, new_val])
  2459. SetProperty(settings.GetDefaultCCList(), 'CC list', 'cc', False)
  2460. SetProperty(settings.GetDefaultPrivateFlag(),
  2461. 'Private flag (rietveld only)', 'private', False)
  2462. SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL',
  2463. 'tree-status-url', False)
  2464. SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url', True)
  2465. SetProperty(settings.GetBugPrefix(), 'Bug Prefix', 'bug-prefix', False)
  2466. SetProperty(settings.GetRunPostUploadHook(), 'Run Post Upload Hook',
  2467. 'run-post-upload-hook', False)
  2468. @subcommand.usage('[repo root containing codereview.settings]')
  2469. def CMDconfig(parser, args):
  2470. """Edits configuration for this tree."""
  2471. print('WARNING: git cl config works for Rietveld only.\n'
  2472. 'For Gerrit, see http://crbug.com/603116.')
  2473. # TODO(tandrii): add Gerrit support as part of http://crbug.com/603116.
  2474. parser.add_option('--activate-update', action='store_true',
  2475. help='activate auto-updating [rietveld] section in '
  2476. '.git/config')
  2477. parser.add_option('--deactivate-update', action='store_true',
  2478. help='deactivate auto-updating [rietveld] section in '
  2479. '.git/config')
  2480. options, args = parser.parse_args(args)
  2481. if options.deactivate_update:
  2482. RunGit(['config', 'rietveld.autoupdate', 'false'])
  2483. return
  2484. if options.activate_update:
  2485. RunGit(['config', '--unset', 'rietveld.autoupdate'])
  2486. return
  2487. if len(args) == 0:
  2488. GetRietveldCodereviewSettingsInteractively()
  2489. return 0
  2490. url = args[0]
  2491. if not url.endswith('codereview.settings'):
  2492. url = os.path.join(url, 'codereview.settings')
  2493. # Load code review settings and download hooks (if available).
  2494. LoadCodereviewSettingsFromFile(urllib2.urlopen(url))
  2495. return 0
  2496. def CMDbaseurl(parser, args):
  2497. """Gets or sets base-url for this branch."""
  2498. branchref = RunGit(['symbolic-ref', 'HEAD']).strip()
  2499. branch = ShortBranchName(branchref)
  2500. _, args = parser.parse_args(args)
  2501. if not args:
  2502. print("Current base-url:")
  2503. return RunGit(['config', 'branch.%s.base-url' % branch],
  2504. error_ok=False).strip()
  2505. else:
  2506. print("Setting base-url to %s" % args[0])
  2507. return RunGit(['config', 'branch.%s.base-url' % branch, args[0]],
  2508. error_ok=False).strip()
  2509. def color_for_status(status):
  2510. """Maps a Changelist status to color, for CMDstatus and other tools."""
  2511. return {
  2512. 'unsent': Fore.RED,
  2513. 'waiting': Fore.BLUE,
  2514. 'reply': Fore.YELLOW,
  2515. 'lgtm': Fore.GREEN,
  2516. 'commit': Fore.MAGENTA,
  2517. 'closed': Fore.CYAN,
  2518. 'error': Fore.WHITE,
  2519. }.get(status, Fore.WHITE)
  2520. def get_cl_statuses(changes, fine_grained, max_processes=None):
  2521. """Returns a blocking iterable of (cl, status) for given branches.
  2522. If fine_grained is true, this will fetch CL statuses from the server.
  2523. Otherwise, simply indicate if there's a matching url for the given branches.
  2524. If max_processes is specified, it is used as the maximum number of processes
  2525. to spawn to fetch CL status from the server. Otherwise 1 process per branch is
  2526. spawned.
  2527. See GetStatus() for a list of possible statuses.
  2528. """
  2529. # Silence upload.py otherwise it becomes unwieldly.
  2530. upload.verbosity = 0
  2531. if fine_grained:
  2532. # Process one branch synchronously to work through authentication, then
  2533. # spawn processes to process all the other branches in parallel.
  2534. if changes:
  2535. fetch = lambda cl: (cl, cl.GetStatus())
  2536. yield fetch(changes[0])
  2537. changes_to_fetch = changes[1:]
  2538. pool = ThreadPool(
  2539. min(max_processes, len(changes_to_fetch))
  2540. if max_processes is not None
  2541. else len(changes_to_fetch))
  2542. fetched_cls = set()
  2543. it = pool.imap_unordered(fetch, changes_to_fetch).__iter__()
  2544. while True:
  2545. try:
  2546. row = it.next(timeout=5)
  2547. except multiprocessing.TimeoutError:
  2548. break
  2549. fetched_cls.add(row[0])
  2550. yield row
  2551. # Add any branches that failed to fetch.
  2552. for cl in set(changes_to_fetch) - fetched_cls:
  2553. yield (cl, 'error')
  2554. else:
  2555. # Do not use GetApprovingReviewers(), since it requires an HTTP request.
  2556. for cl in changes:
  2557. yield (cl, 'waiting' if cl.GetIssueURL() else 'error')
  2558. def upload_branch_deps(cl, args):
  2559. """Uploads CLs of local branches that are dependents of the current branch.
  2560. If the local branch dependency tree looks like:
  2561. test1 -> test2.1 -> test3.1
  2562. -> test3.2
  2563. -> test2.2 -> test3.3
  2564. and you run "git cl upload --dependencies" from test1 then "git cl upload" is
  2565. run on the dependent branches in this order:
  2566. test2.1, test3.1, test3.2, test2.2, test3.3
  2567. Note: This function does not rebase your local dependent branches. Use it when
  2568. you make a change to the parent branch that will not conflict with its
  2569. dependent branches, and you would like their dependencies updated in
  2570. Rietveld.
  2571. """
  2572. if git_common.is_dirty_git_tree('upload-branch-deps'):
  2573. return 1
  2574. root_branch = cl.GetBranch()
  2575. if root_branch is None:
  2576. DieWithError('Can\'t find dependent branches from detached HEAD state. '
  2577. 'Get on a branch!')
  2578. if not cl.GetIssue() or not cl.GetPatchset():
  2579. DieWithError('Current branch does not have an uploaded CL. We cannot set '
  2580. 'patchset dependencies without an uploaded CL.')
  2581. branches = RunGit(['for-each-ref',
  2582. '--format=%(refname:short) %(upstream:short)',
  2583. 'refs/heads'])
  2584. if not branches:
  2585. print('No local branches found.')
  2586. return 0
  2587. # Create a dictionary of all local branches to the branches that are dependent
  2588. # on it.
  2589. tracked_to_dependents = collections.defaultdict(list)
  2590. for b in branches.splitlines():
  2591. tokens = b.split()
  2592. if len(tokens) == 2:
  2593. branch_name, tracked = tokens
  2594. tracked_to_dependents[tracked].append(branch_name)
  2595. print
  2596. print 'The dependent local branches of %s are:' % root_branch
  2597. dependents = []
  2598. def traverse_dependents_preorder(branch, padding=''):
  2599. dependents_to_process = tracked_to_dependents.get(branch, [])
  2600. padding += ' '
  2601. for dependent in dependents_to_process:
  2602. print '%s%s' % (padding, dependent)
  2603. dependents.append(dependent)
  2604. traverse_dependents_preorder(dependent, padding)
  2605. traverse_dependents_preorder(root_branch)
  2606. print
  2607. if not dependents:
  2608. print 'There are no dependent local branches for %s' % root_branch
  2609. return 0
  2610. print ('This command will checkout all dependent branches and run '
  2611. '"git cl upload".')
  2612. ask_for_data('[Press enter to continue or ctrl-C to quit]')
  2613. # Add a default patchset title to all upload calls in Rietveld.
  2614. if not cl.IsGerrit():
  2615. args.extend(['-t', 'Updated patchset dependency'])
  2616. # Record all dependents that failed to upload.
  2617. failures = {}
  2618. # Go through all dependents, checkout the branch and upload.
  2619. try:
  2620. for dependent_branch in dependents:
  2621. print
  2622. print '--------------------------------------'
  2623. print 'Running "git cl upload" from %s:' % dependent_branch
  2624. RunGit(['checkout', '-q', dependent_branch])
  2625. print
  2626. try:
  2627. if CMDupload(OptionParser(), args) != 0:
  2628. print 'Upload failed for %s!' % dependent_branch
  2629. failures[dependent_branch] = 1
  2630. except: # pylint: disable=W0702
  2631. failures[dependent_branch] = 1
  2632. print
  2633. finally:
  2634. # Swap back to the original root branch.
  2635. RunGit(['checkout', '-q', root_branch])
  2636. print
  2637. print 'Upload complete for dependent branches!'
  2638. for dependent_branch in dependents:
  2639. upload_status = 'failed' if failures.get(dependent_branch) else 'succeeded'
  2640. print ' %s : %s' % (dependent_branch, upload_status)
  2641. print
  2642. return 0
  2643. def CMDstatus(parser, args):
  2644. """Show status of changelists.
  2645. Colors are used to tell the state of the CL unless --fast is used:
  2646. - Red not sent for review or broken
  2647. - Blue waiting for review
  2648. - Yellow waiting for you to reply to review
  2649. - Green LGTM'ed
  2650. - Magenta in the commit queue
  2651. - Cyan was committed, branch can be deleted
  2652. Also see 'git cl comments'.
  2653. """
  2654. parser.add_option('--field',
  2655. help='print only specific field (desc|id|patch|url)')
  2656. parser.add_option('-f', '--fast', action='store_true',
  2657. help='Do not retrieve review status')
  2658. parser.add_option(
  2659. '-j', '--maxjobs', action='store', type=int,
  2660. help='The maximum number of jobs to use when retrieving review status')
  2661. auth.add_auth_options(parser)
  2662. options, args = parser.parse_args(args)
  2663. if args:
  2664. parser.error('Unsupported args: %s' % args)
  2665. auth_config = auth.extract_auth_config_from_options(options)
  2666. if options.field:
  2667. cl = Changelist(auth_config=auth_config)
  2668. if options.field.startswith('desc'):
  2669. print cl.GetDescription()
  2670. elif options.field == 'id':
  2671. issueid = cl.GetIssue()
  2672. if issueid:
  2673. print issueid
  2674. elif options.field == 'patch':
  2675. patchset = cl.GetPatchset()
  2676. if patchset:
  2677. print patchset
  2678. elif options.field == 'url':
  2679. url = cl.GetIssueURL()
  2680. if url:
  2681. print url
  2682. return 0
  2683. branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
  2684. if not branches:
  2685. print('No local branch found.')
  2686. return 0
  2687. changes = [
  2688. Changelist(branchref=b, auth_config=auth_config)
  2689. for b in branches.splitlines()]
  2690. print 'Branches associated with reviews:'
  2691. output = get_cl_statuses(changes,
  2692. fine_grained=not options.fast,
  2693. max_processes=options.maxjobs)
  2694. branch_statuses = {}
  2695. alignment = max(5, max(len(ShortBranchName(c.GetBranch())) for c in changes))
  2696. for cl in sorted(changes, key=lambda c: c.GetBranch()):
  2697. branch = cl.GetBranch()
  2698. while branch not in branch_statuses:
  2699. c, status = output.next()
  2700. branch_statuses[c.GetBranch()] = status
  2701. status = branch_statuses.pop(branch)
  2702. url = cl.GetIssueURL()
  2703. if url and (not status or status == 'error'):
  2704. # The issue probably doesn't exist anymore.
  2705. url += ' (broken)'
  2706. color = color_for_status(status)
  2707. reset = Fore.RESET
  2708. if not setup_color.IS_TTY:
  2709. color = ''
  2710. reset = ''
  2711. status_str = '(%s)' % status if status else ''
  2712. print ' %*s : %s%s %s%s' % (
  2713. alignment, ShortBranchName(branch), color, url,
  2714. status_str, reset)
  2715. cl = Changelist(auth_config=auth_config)
  2716. print
  2717. print 'Current branch:',
  2718. print cl.GetBranch()
  2719. if not cl.GetIssue():
  2720. print 'No issue assigned.'
  2721. return 0
  2722. print 'Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())
  2723. if not options.fast:
  2724. print 'Issue description:'
  2725. print cl.GetDescription(pretty=True)
  2726. return 0
  2727. def colorize_CMDstatus_doc():
  2728. """To be called once in main() to add colors to git cl status help."""
  2729. colors = [i for i in dir(Fore) if i[0].isupper()]
  2730. def colorize_line(line):
  2731. for color in colors:
  2732. if color in line.upper():
  2733. # Extract whitespaces first and the leading '-'.
  2734. indent = len(line) - len(line.lstrip(' ')) + 1
  2735. return line[:indent] + getattr(Fore, color) + line[indent:] + Fore.RESET
  2736. return line
  2737. lines = CMDstatus.__doc__.splitlines()
  2738. CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines)
  2739. @subcommand.usage('[issue_number]')
  2740. def CMDissue(parser, args):
  2741. """Sets or displays the current code review issue number.
  2742. Pass issue number 0 to clear the current issue.
  2743. """
  2744. parser.add_option('-r', '--reverse', action='store_true',
  2745. help='Lookup the branch(es) for the specified issues. If '
  2746. 'no issues are specified, all branches with mapped '
  2747. 'issues will be listed.')
  2748. _add_codereview_select_options(parser)
  2749. options, args = parser.parse_args(args)
  2750. _process_codereview_select_options(parser, options)
  2751. if options.reverse:
  2752. branches = RunGit(['for-each-ref', 'refs/heads',
  2753. '--format=%(refname:short)']).splitlines()
  2754. # Reverse issue lookup.
  2755. issue_branch_map = {}
  2756. for branch in branches:
  2757. cl = Changelist(branchref=branch)
  2758. issue_branch_map.setdefault(cl.GetIssue(), []).append(branch)
  2759. if not args:
  2760. args = sorted(issue_branch_map.iterkeys())
  2761. for issue in args:
  2762. if not issue:
  2763. continue
  2764. print 'Branch for issue number %s: %s' % (
  2765. issue, ', '.join(issue_branch_map.get(int(issue)) or ('None',)))
  2766. else:
  2767. cl = Changelist(codereview=options.forced_codereview)
  2768. if len(args) > 0:
  2769. try:
  2770. issue = int(args[0])
  2771. except ValueError:
  2772. DieWithError('Pass a number to set the issue or none to list it.\n'
  2773. 'Maybe you want to run git cl status?')
  2774. cl.SetIssue(issue)
  2775. print 'Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())
  2776. return 0
  2777. def CMDcomments(parser, args):
  2778. """Shows or posts review comments for any changelist."""
  2779. parser.add_option('-a', '--add-comment', dest='comment',
  2780. help='comment to add to an issue')
  2781. parser.add_option('-i', dest='issue',
  2782. help="review issue id (defaults to current issue)")
  2783. parser.add_option('-j', '--json-file',
  2784. help='File to write JSON summary to')
  2785. auth.add_auth_options(parser)
  2786. options, args = parser.parse_args(args)
  2787. auth_config = auth.extract_auth_config_from_options(options)
  2788. issue = None
  2789. if options.issue:
  2790. try:
  2791. issue = int(options.issue)
  2792. except ValueError:
  2793. DieWithError('A review issue id is expected to be a number')
  2794. cl = Changelist(issue=issue, codereview='rietveld', auth_config=auth_config)
  2795. if options.comment:
  2796. cl.AddComment(options.comment)
  2797. return 0
  2798. data = cl.GetIssueProperties()
  2799. summary = []
  2800. for message in sorted(data.get('messages', []), key=lambda x: x['date']):
  2801. summary.append({
  2802. 'date': message['date'],
  2803. 'lgtm': False,
  2804. 'message': message['text'],
  2805. 'not_lgtm': False,
  2806. 'sender': message['sender'],
  2807. })
  2808. if message['disapproval']:
  2809. color = Fore.RED
  2810. summary[-1]['not lgtm'] = True
  2811. elif message['approval']:
  2812. color = Fore.GREEN
  2813. summary[-1]['lgtm'] = True
  2814. elif message['sender'] == data['owner_email']:
  2815. color = Fore.MAGENTA
  2816. else:
  2817. color = Fore.BLUE
  2818. print '\n%s%s %s%s' % (
  2819. color, message['date'].split('.', 1)[0], message['sender'],
  2820. Fore.RESET)
  2821. if message['text'].strip():
  2822. print '\n'.join(' ' + l for l in message['text'].splitlines())
  2823. if options.json_file:
  2824. with open(options.json_file, 'wb') as f:
  2825. json.dump(summary, f)
  2826. return 0
  2827. @subcommand.usage('[codereview url or issue id]')
  2828. def CMDdescription(parser, args):
  2829. """Brings up the editor for the current CL's description."""
  2830. parser.add_option('-d', '--display', action='store_true',
  2831. help='Display the description instead of opening an editor')
  2832. parser.add_option('-n', '--new-description',
  2833. help='New description to set for this issue (- for stdin)')
  2834. _add_codereview_select_options(parser)
  2835. auth.add_auth_options(parser)
  2836. options, args = parser.parse_args(args)
  2837. _process_codereview_select_options(parser, options)
  2838. target_issue = None
  2839. if len(args) > 0:
  2840. issue_arg = ParseIssueNumberArgument(args[0])
  2841. if not issue_arg.valid:
  2842. parser.print_help()
  2843. return 1
  2844. target_issue = issue_arg.issue
  2845. auth_config = auth.extract_auth_config_from_options(options)
  2846. cl = Changelist(
  2847. auth_config=auth_config, issue=target_issue,
  2848. codereview=options.forced_codereview)
  2849. if not cl.GetIssue():
  2850. DieWithError('This branch has no associated changelist.')
  2851. description = ChangeDescription(cl.GetDescription())
  2852. if options.display:
  2853. print description.description
  2854. return 0
  2855. if options.new_description:
  2856. text = options.new_description
  2857. if text == '-':
  2858. text = '\n'.join(l.rstrip() for l in sys.stdin)
  2859. description.set_description(text)
  2860. else:
  2861. description.prompt()
  2862. if cl.GetDescription() != description.description:
  2863. cl.UpdateDescription(description.description)
  2864. return 0
  2865. def CreateDescriptionFromLog(args):
  2866. """Pulls out the commit log to use as a base for the CL description."""
  2867. log_args = []
  2868. if len(args) == 1 and not args[0].endswith('.'):
  2869. log_args = [args[0] + '..']
  2870. elif len(args) == 1 and args[0].endswith('...'):
  2871. log_args = [args[0][:-1]]
  2872. elif len(args) == 2:
  2873. log_args = [args[0] + '..' + args[1]]
  2874. else:
  2875. log_args = args[:] # Hope for the best!
  2876. return RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args)
  2877. def CMDlint(parser, args):
  2878. """Runs cpplint on the current changelist."""
  2879. parser.add_option('--filter', action='append', metavar='-x,+y',
  2880. help='Comma-separated list of cpplint\'s category-filters')
  2881. auth.add_auth_options(parser)
  2882. options, args = parser.parse_args(args)
  2883. auth_config = auth.extract_auth_config_from_options(options)
  2884. # Access to a protected member _XX of a client class
  2885. # pylint: disable=W0212
  2886. try:
  2887. import cpplint
  2888. import cpplint_chromium
  2889. except ImportError:
  2890. print "Your depot_tools is missing cpplint.py and/or cpplint_chromium.py."
  2891. return 1
  2892. # Change the current working directory before calling lint so that it
  2893. # shows the correct base.
  2894. previous_cwd = os.getcwd()
  2895. os.chdir(settings.GetRoot())
  2896. try:
  2897. cl = Changelist(auth_config=auth_config)
  2898. change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
  2899. files = [f.LocalPath() for f in change.AffectedFiles()]
  2900. if not files:
  2901. print "Cannot lint an empty CL"
  2902. return 1
  2903. # Process cpplints arguments if any.
  2904. command = args + files
  2905. if options.filter:
  2906. command = ['--filter=' + ','.join(options.filter)] + command
  2907. filenames = cpplint.ParseArguments(command)
  2908. white_regex = re.compile(settings.GetLintRegex())
  2909. black_regex = re.compile(settings.GetLintIgnoreRegex())
  2910. extra_check_functions = [cpplint_chromium.CheckPointerDeclarationWhitespace]
  2911. for filename in filenames:
  2912. if white_regex.match(filename):
  2913. if black_regex.match(filename):
  2914. print "Ignoring file %s" % filename
  2915. else:
  2916. cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level,
  2917. extra_check_functions)
  2918. else:
  2919. print "Skipping file %s" % filename
  2920. finally:
  2921. os.chdir(previous_cwd)
  2922. print "Total errors found: %d\n" % cpplint._cpplint_state.error_count
  2923. if cpplint._cpplint_state.error_count != 0:
  2924. return 1
  2925. return 0
  2926. def CMDpresubmit(parser, args):
  2927. """Runs presubmit tests on the current changelist."""
  2928. parser.add_option('-u', '--upload', action='store_true',
  2929. help='Run upload hook instead of the push/dcommit hook')
  2930. parser.add_option('-f', '--force', action='store_true',
  2931. help='Run checks even if tree is dirty')
  2932. auth.add_auth_options(parser)
  2933. options, args = parser.parse_args(args)
  2934. auth_config = auth.extract_auth_config_from_options(options)
  2935. if not options.force and git_common.is_dirty_git_tree('presubmit'):
  2936. print 'use --force to check even if tree is dirty.'
  2937. return 1
  2938. cl = Changelist(auth_config=auth_config)
  2939. if args:
  2940. base_branch = args[0]
  2941. else:
  2942. # Default to diffing against the common ancestor of the upstream branch.
  2943. base_branch = cl.GetCommonAncestorWithUpstream()
  2944. cl.RunHook(
  2945. committing=not options.upload,
  2946. may_prompt=False,
  2947. verbose=options.verbose,
  2948. change=cl.GetChange(base_branch, None))
  2949. return 0
  2950. def GenerateGerritChangeId(message):
  2951. """Returns Ixxxxxx...xxx change id.
  2952. Works the same way as
  2953. https://gerrit-review.googlesource.com/tools/hooks/commit-msg
  2954. but can be called on demand on all platforms.
  2955. The basic idea is to generate git hash of a state of the tree, original commit
  2956. message, author/committer info and timestamps.
  2957. """
  2958. lines = []
  2959. tree_hash = RunGitSilent(['write-tree'])
  2960. lines.append('tree %s' % tree_hash.strip())
  2961. code, parent = RunGitWithCode(['rev-parse', 'HEAD~0'], suppress_stderr=False)
  2962. if code == 0:
  2963. lines.append('parent %s' % parent.strip())
  2964. author = RunGitSilent(['var', 'GIT_AUTHOR_IDENT'])
  2965. lines.append('author %s' % author.strip())
  2966. committer = RunGitSilent(['var', 'GIT_COMMITTER_IDENT'])
  2967. lines.append('committer %s' % committer.strip())
  2968. lines.append('')
  2969. # Note: Gerrit's commit-hook actually cleans message of some lines and
  2970. # whitespace. This code is not doing this, but it clearly won't decrease
  2971. # entropy.
  2972. lines.append(message)
  2973. change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'],
  2974. stdin='\n'.join(lines))
  2975. return 'I%s' % change_hash.strip()
  2976. def GetTargetRef(remote, remote_branch, target_branch, pending_prefix):
  2977. """Computes the remote branch ref to use for the CL.
  2978. Args:
  2979. remote (str): The git remote for the CL.
  2980. remote_branch (str): The git remote branch for the CL.
  2981. target_branch (str): The target branch specified by the user.
  2982. pending_prefix (str): The pending prefix from the settings.
  2983. """
  2984. if not (remote and remote_branch):
  2985. return None
  2986. if target_branch:
  2987. # Cannonicalize branch references to the equivalent local full symbolic
  2988. # refs, which are then translated into the remote full symbolic refs
  2989. # below.
  2990. if '/' not in target_branch:
  2991. remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch)
  2992. else:
  2993. prefix_replacements = (
  2994. ('^((refs/)?remotes/)?branch-heads/', 'refs/remotes/branch-heads/'),
  2995. ('^((refs/)?remotes/)?%s/' % remote, 'refs/remotes/%s/' % remote),
  2996. ('^(refs/)?heads/', 'refs/remotes/%s/' % remote),
  2997. )
  2998. match = None
  2999. for regex, replacement in prefix_replacements:
  3000. match = re.search(regex, target_branch)
  3001. if match:
  3002. remote_branch = target_branch.replace(match.group(0), replacement)
  3003. break
  3004. if not match:
  3005. # This is a branch path but not one we recognize; use as-is.
  3006. remote_branch = target_branch
  3007. elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS:
  3008. # Handle the refs that need to land in different refs.
  3009. remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch]
  3010. # Create the true path to the remote branch.
  3011. # Does the following translation:
  3012. # * refs/remotes/origin/refs/diff/test -> refs/diff/test
  3013. # * refs/remotes/origin/master -> refs/heads/master
  3014. # * refs/remotes/branch-heads/test -> refs/branch-heads/test
  3015. if remote_branch.startswith('refs/remotes/%s/refs/' % remote):
  3016. remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '')
  3017. elif remote_branch.startswith('refs/remotes/%s/' % remote):
  3018. remote_branch = remote_branch.replace('refs/remotes/%s/' % remote,
  3019. 'refs/heads/')
  3020. elif remote_branch.startswith('refs/remotes/branch-heads'):
  3021. remote_branch = remote_branch.replace('refs/remotes/', 'refs/')
  3022. # If a pending prefix exists then replace refs/ with it.
  3023. if pending_prefix:
  3024. remote_branch = remote_branch.replace('refs/', pending_prefix)
  3025. return remote_branch
  3026. def cleanup_list(l):
  3027. """Fixes a list so that comma separated items are put as individual items.
  3028. So that "--reviewers joe@c,john@c --reviewers joa@c" results in
  3029. options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']).
  3030. """
  3031. items = sum((i.split(',') for i in l), [])
  3032. stripped_items = (i.strip() for i in items)
  3033. return sorted(filter(None, stripped_items))
  3034. @subcommand.usage('[args to "git diff"]')
  3035. def CMDupload(parser, args):
  3036. """Uploads the current changelist to codereview.
  3037. Can skip dependency patchset uploads for a branch by running:
  3038. git config branch.branch_name.skip-deps-uploads True
  3039. To unset run:
  3040. git config --unset branch.branch_name.skip-deps-uploads
  3041. Can also set the above globally by using the --global flag.
  3042. """
  3043. parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
  3044. help='bypass upload presubmit hook')
  3045. parser.add_option('--bypass-watchlists', action='store_true',
  3046. dest='bypass_watchlists',
  3047. help='bypass watchlists auto CC-ing reviewers')
  3048. parser.add_option('-f', action='store_true', dest='force',
  3049. help="force yes to questions (don't prompt)")
  3050. parser.add_option('-m', dest='message', help='message for patchset')
  3051. parser.add_option('-t', dest='title',
  3052. help='title for patchset (Rietveld only)')
  3053. parser.add_option('-r', '--reviewers',
  3054. action='append', default=[],
  3055. help='reviewer email addresses')
  3056. parser.add_option('--cc',
  3057. action='append', default=[],
  3058. help='cc email addresses')
  3059. parser.add_option('-s', '--send-mail', action='store_true',
  3060. help='send email to reviewer immediately')
  3061. parser.add_option('--emulate_svn_auto_props',
  3062. '--emulate-svn-auto-props',
  3063. action="store_true",
  3064. dest="emulate_svn_auto_props",
  3065. help="Emulate Subversion's auto properties feature.")
  3066. parser.add_option('-c', '--use-commit-queue', action='store_true',
  3067. help='tell the commit queue to commit this patchset')
  3068. parser.add_option('--private', action='store_true',
  3069. help='set the review private (rietveld only)')
  3070. parser.add_option('--target_branch',
  3071. '--target-branch',
  3072. metavar='TARGET',
  3073. help='Apply CL to remote ref TARGET. ' +
  3074. 'Default: remote branch head, or master')
  3075. parser.add_option('--squash', action='store_true',
  3076. help='Squash multiple commits into one (Gerrit only)')
  3077. parser.add_option('--no-squash', action='store_true',
  3078. help='Don\'t squash multiple commits into one ' +
  3079. '(Gerrit only)')
  3080. parser.add_option('--email', default=None,
  3081. help='email address to use to connect to Rietveld')
  3082. parser.add_option('--tbr-owners', dest='tbr_owners', action='store_true',
  3083. help='add a set of OWNERS to TBR')
  3084. parser.add_option('-d', '--cq-dry-run', dest='cq_dry_run',
  3085. action='store_true',
  3086. help='Send the patchset to do a CQ dry run right after '
  3087. 'upload.')
  3088. parser.add_option('--dependencies', action='store_true',
  3089. help='Uploads CLs of all the local branches that depend on '
  3090. 'the current branch')
  3091. orig_args = args
  3092. add_git_similarity(parser)
  3093. auth.add_auth_options(parser)
  3094. _add_codereview_select_options(parser)
  3095. (options, args) = parser.parse_args(args)
  3096. _process_codereview_select_options(parser, options)
  3097. auth_config = auth.extract_auth_config_from_options(options)
  3098. if git_common.is_dirty_git_tree('upload'):
  3099. return 1
  3100. options.reviewers = cleanup_list(options.reviewers)
  3101. options.cc = cleanup_list(options.cc)
  3102. # For sanity of test expectations, do this otherwise lazy-loading *now*.
  3103. settings.GetIsGerrit()
  3104. cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview)
  3105. return cl.CMDUpload(options, args, orig_args)
  3106. def IsSubmoduleMergeCommit(ref):
  3107. # When submodules are added to the repo, we expect there to be a single
  3108. # non-git-svn merge commit at remote HEAD with a signature comment.
  3109. pattern = '^SVN changes up to revision [0-9]*$'
  3110. cmd = ['rev-list', '--merges', '--grep=%s' % pattern, '%s^!' % ref]
  3111. return RunGit(cmd) != ''
  3112. def SendUpstream(parser, args, cmd):
  3113. """Common code for CMDland and CmdDCommit
  3114. In case of Gerrit, uses Gerrit REST api to "submit" the issue, which pushes
  3115. upstream and closes the issue automatically and atomically.
  3116. Otherwise (in case of Rietveld):
  3117. Squashes branch into a single commit.
  3118. Updates changelog with metadata (e.g. pointer to review).
  3119. Pushes/dcommits the code upstream.
  3120. Updates review and closes.
  3121. """
  3122. parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
  3123. help='bypass upload presubmit hook')
  3124. parser.add_option('-m', dest='message',
  3125. help="override review description")
  3126. parser.add_option('-f', action='store_true', dest='force',
  3127. help="force yes to questions (don't prompt)")
  3128. parser.add_option('-c', dest='contributor',
  3129. help="external contributor for patch (appended to " +
  3130. "description and used as author for git). Should be " +
  3131. "formatted as 'First Last <email@example.com>'")
  3132. add_git_similarity(parser)
  3133. auth.add_auth_options(parser)
  3134. (options, args) = parser.parse_args(args)
  3135. auth_config = auth.extract_auth_config_from_options(options)
  3136. cl = Changelist(auth_config=auth_config)
  3137. # TODO(tandrii): refactor this into _RietveldChangelistImpl method.
  3138. if cl.IsGerrit():
  3139. if options.message:
  3140. # This could be implemented, but it requires sending a new patch to
  3141. # Gerrit, as Gerrit unlike Rietveld versions messages with patchsets.
  3142. # Besides, Gerrit has the ability to change the commit message on submit
  3143. # automatically, thus there is no need to support this option (so far?).
  3144. parser.error('-m MESSAGE option is not supported for Gerrit.')
  3145. if options.contributor:
  3146. parser.error(
  3147. '-c CONTRIBUTOR option is not supported for Gerrit.\n'
  3148. 'Before uploading a commit to Gerrit, ensure it\'s author field is '
  3149. 'the contributor\'s "name <email>". If you can\'t upload such a '
  3150. 'commit for review, contact your repository admin and request'
  3151. '"Forge-Author" permission.')
  3152. return cl._codereview_impl.CMDLand(options.force, options.bypass_hooks,
  3153. options.verbose)
  3154. current = cl.GetBranch()
  3155. remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch())
  3156. if not settings.GetIsGitSvn() and remote == '.':
  3157. print
  3158. print 'Attempting to push branch %r into another local branch!' % current
  3159. print
  3160. print 'Either reparent this branch on top of origin/master:'
  3161. print ' git reparent-branch --root'
  3162. print
  3163. print 'OR run `git rebase-update` if you think the parent branch is already'
  3164. print 'committed.'
  3165. print
  3166. print ' Current parent: %r' % upstream_branch
  3167. return 1
  3168. if not args or cmd == 'land':
  3169. # Default to merging against our best guess of the upstream branch.
  3170. args = [cl.GetUpstreamBranch()]
  3171. if options.contributor:
  3172. if not re.match('^.*\s<\S+@\S+>$', options.contributor):
  3173. print "Please provide contibutor as 'First Last <email@example.com>'"
  3174. return 1
  3175. base_branch = args[0]
  3176. base_has_submodules = IsSubmoduleMergeCommit(base_branch)
  3177. if git_common.is_dirty_git_tree(cmd):
  3178. return 1
  3179. # This rev-list syntax means "show all commits not in my branch that
  3180. # are in base_branch".
  3181. upstream_commits = RunGit(['rev-list', '^' + cl.GetBranchRef(),
  3182. base_branch]).splitlines()
  3183. if upstream_commits:
  3184. print ('Base branch "%s" has %d commits '
  3185. 'not in this branch.' % (base_branch, len(upstream_commits)))
  3186. print 'Run "git merge %s" before attempting to %s.' % (base_branch, cmd)
  3187. return 1
  3188. # This is the revision `svn dcommit` will commit on top of.
  3189. svn_head = None
  3190. if cmd == 'dcommit' or base_has_submodules:
  3191. svn_head = RunGit(['log', '--grep=^git-svn-id:', '-1',
  3192. '--pretty=format:%H'])
  3193. if cmd == 'dcommit':
  3194. # If the base_head is a submodule merge commit, the first parent of the
  3195. # base_head should be a git-svn commit, which is what we're interested in.
  3196. base_svn_head = base_branch
  3197. if base_has_submodules:
  3198. base_svn_head += '^1'
  3199. extra_commits = RunGit(['rev-list', '^' + svn_head, base_svn_head])
  3200. if extra_commits:
  3201. print ('This branch has %d additional commits not upstreamed yet.'
  3202. % len(extra_commits.splitlines()))
  3203. print ('Upstream "%s" or rebase this branch on top of the upstream trunk '
  3204. 'before attempting to %s.' % (base_branch, cmd))
  3205. return 1
  3206. merge_base = RunGit(['merge-base', base_branch, 'HEAD']).strip()
  3207. if not options.bypass_hooks:
  3208. author = None
  3209. if options.contributor:
  3210. author = re.search(r'\<(.*)\>', options.contributor).group(1)
  3211. hook_results = cl.RunHook(
  3212. committing=True,
  3213. may_prompt=not options.force,
  3214. verbose=options.verbose,
  3215. change=cl.GetChange(merge_base, author))
  3216. if not hook_results.should_continue():
  3217. return 1
  3218. # Check the tree status if the tree status URL is set.
  3219. status = GetTreeStatus()
  3220. if 'closed' == status:
  3221. print('The tree is closed. Please wait for it to reopen. Use '
  3222. '"git cl %s --bypass-hooks" to commit on a closed tree.' % cmd)
  3223. return 1
  3224. elif 'unknown' == status:
  3225. print('Unable to determine tree status. Please verify manually and '
  3226. 'use "git cl %s --bypass-hooks" to commit on a closed tree.' % cmd)
  3227. return 1
  3228. change_desc = ChangeDescription(options.message)
  3229. if not change_desc.description and cl.GetIssue():
  3230. change_desc = ChangeDescription(cl.GetDescription())
  3231. if not change_desc.description:
  3232. if not cl.GetIssue() and options.bypass_hooks:
  3233. change_desc = ChangeDescription(CreateDescriptionFromLog([merge_base]))
  3234. else:
  3235. print 'No description set.'
  3236. print 'Visit %s/edit to set it.' % (cl.GetIssueURL())
  3237. return 1
  3238. # Keep a separate copy for the commit message, because the commit message
  3239. # contains the link to the Rietveld issue, while the Rietveld message contains
  3240. # the commit viewvc url.
  3241. # Keep a separate copy for the commit message.
  3242. if cl.GetIssue():
  3243. change_desc.update_reviewers(cl.GetApprovingReviewers())
  3244. commit_desc = ChangeDescription(change_desc.description)
  3245. if cl.GetIssue():
  3246. # Xcode won't linkify this URL unless there is a non-whitespace character
  3247. # after it. Add a period on a new line to circumvent this. Also add a space
  3248. # before the period to make sure that Gitiles continues to correctly resolve
  3249. # the URL.
  3250. commit_desc.append_footer('Review URL: %s .' % cl.GetIssueURL())
  3251. if options.contributor:
  3252. commit_desc.append_footer('Patch from %s.' % options.contributor)
  3253. print('Description:')
  3254. print(commit_desc.description)
  3255. branches = [merge_base, cl.GetBranchRef()]
  3256. if not options.force:
  3257. print_stats(options.similarity, options.find_copies, branches)
  3258. # We want to squash all this branch's commits into one commit with the proper
  3259. # description. We do this by doing a "reset --soft" to the base branch (which
  3260. # keeps the working copy the same), then dcommitting that. If origin/master
  3261. # has a submodule merge commit, we'll also need to cherry-pick the squashed
  3262. # commit onto a branch based on the git-svn head.
  3263. MERGE_BRANCH = 'git-cl-commit'
  3264. CHERRY_PICK_BRANCH = 'git-cl-cherry-pick'
  3265. # Delete the branches if they exist.
  3266. for branch in [MERGE_BRANCH, CHERRY_PICK_BRANCH]:
  3267. showref_cmd = ['show-ref', '--quiet', '--verify', 'refs/heads/%s' % branch]
  3268. result = RunGitWithCode(showref_cmd)
  3269. if result[0] == 0:
  3270. RunGit(['branch', '-D', branch])
  3271. # We might be in a directory that's present in this branch but not in the
  3272. # trunk. Move up to the top of the tree so that git commands that expect a
  3273. # valid CWD won't fail after we check out the merge branch.
  3274. rel_base_path = settings.GetRelativeRoot()
  3275. if rel_base_path:
  3276. os.chdir(rel_base_path)
  3277. # Stuff our change into the merge branch.
  3278. # We wrap in a try...finally block so if anything goes wrong,
  3279. # we clean up the branches.
  3280. retcode = -1
  3281. pushed_to_pending = False
  3282. pending_ref = None
  3283. revision = None
  3284. try:
  3285. RunGit(['checkout', '-q', '-b', MERGE_BRANCH])
  3286. RunGit(['reset', '--soft', merge_base])
  3287. if options.contributor:
  3288. RunGit(
  3289. [
  3290. 'commit', '--author', options.contributor,
  3291. '-m', commit_desc.description,
  3292. ])
  3293. else:
  3294. RunGit(['commit', '-m', commit_desc.description])
  3295. if base_has_submodules:
  3296. cherry_pick_commit = RunGit(['rev-list', 'HEAD^!']).rstrip()
  3297. RunGit(['branch', CHERRY_PICK_BRANCH, svn_head])
  3298. RunGit(['checkout', CHERRY_PICK_BRANCH])
  3299. RunGit(['cherry-pick', cherry_pick_commit])
  3300. if cmd == 'land':
  3301. remote, branch = cl.FetchUpstreamTuple(cl.GetBranch())
  3302. mirror = settings.GetGitMirror(remote)
  3303. pushurl = mirror.url if mirror else remote
  3304. pending_prefix = settings.GetPendingRefPrefix()
  3305. if not pending_prefix or branch.startswith(pending_prefix):
  3306. # If not using refs/pending/heads/* at all, or target ref is already set
  3307. # to pending, then push to the target ref directly.
  3308. retcode, output = RunGitWithCode(
  3309. ['push', '--porcelain', pushurl, 'HEAD:%s' % branch])
  3310. pushed_to_pending = pending_prefix and branch.startswith(pending_prefix)
  3311. else:
  3312. # Cherry-pick the change on top of pending ref and then push it.
  3313. assert branch.startswith('refs/'), branch
  3314. assert pending_prefix[-1] == '/', pending_prefix
  3315. pending_ref = pending_prefix + branch[len('refs/'):]
  3316. retcode, output = PushToGitPending(pushurl, pending_ref, branch)
  3317. pushed_to_pending = (retcode == 0)
  3318. if retcode == 0:
  3319. revision = RunGit(['rev-parse', 'HEAD']).strip()
  3320. else:
  3321. # dcommit the merge branch.
  3322. cmd_args = [
  3323. 'svn', 'dcommit',
  3324. '-C%s' % options.similarity,
  3325. '--no-rebase', '--rmdir',
  3326. ]
  3327. if settings.GetForceHttpsCommitUrl():
  3328. # Allow forcing https commit URLs for some projects that don't allow
  3329. # committing to http URLs (like Google Code).
  3330. remote_url = cl.GetGitSvnRemoteUrl()
  3331. if urlparse.urlparse(remote_url).scheme == 'http':
  3332. remote_url = remote_url.replace('http://', 'https://')
  3333. cmd_args.append('--commit-url=%s' % remote_url)
  3334. _, output = RunGitWithCode(cmd_args)
  3335. if 'Committed r' in output:
  3336. revision = re.match(
  3337. '.*?\nCommitted r(\\d+)', output, re.DOTALL).group(1)
  3338. logging.debug(output)
  3339. finally:
  3340. # And then swap back to the original branch and clean up.
  3341. RunGit(['checkout', '-q', cl.GetBranch()])
  3342. RunGit(['branch', '-D', MERGE_BRANCH])
  3343. if base_has_submodules:
  3344. RunGit(['branch', '-D', CHERRY_PICK_BRANCH])
  3345. if not revision:
  3346. print 'Failed to push. If this persists, please file a bug.'
  3347. return 1
  3348. killed = False
  3349. if pushed_to_pending:
  3350. try:
  3351. revision = WaitForRealCommit(remote, revision, base_branch, branch)
  3352. # We set pushed_to_pending to False, since it made it all the way to the
  3353. # real ref.
  3354. pushed_to_pending = False
  3355. except KeyboardInterrupt:
  3356. killed = True
  3357. if cl.GetIssue():
  3358. to_pending = ' to pending queue' if pushed_to_pending else ''
  3359. viewvc_url = settings.GetViewVCUrl()
  3360. if not to_pending:
  3361. if viewvc_url and revision:
  3362. change_desc.append_footer(
  3363. 'Committed: %s%s' % (viewvc_url, revision))
  3364. elif revision:
  3365. change_desc.append_footer('Committed: %s' % (revision,))
  3366. print ('Closing issue '
  3367. '(you may be prompted for your codereview password)...')
  3368. cl.UpdateDescription(change_desc.description)
  3369. cl.CloseIssue()
  3370. props = cl.GetIssueProperties()
  3371. patch_num = len(props['patchsets'])
  3372. comment = "Committed patchset #%d (id:%d)%s manually as %s" % (
  3373. patch_num, props['patchsets'][-1], to_pending, revision)
  3374. if options.bypass_hooks:
  3375. comment += ' (tree was closed).' if GetTreeStatus() == 'closed' else '.'
  3376. else:
  3377. comment += ' (presubmit successful).'
  3378. cl.RpcServer().add_comment(cl.GetIssue(), comment)
  3379. cl.SetIssue(None)
  3380. if pushed_to_pending:
  3381. _, branch = cl.FetchUpstreamTuple(cl.GetBranch())
  3382. print 'The commit is in the pending queue (%s).' % pending_ref
  3383. print (
  3384. 'It will show up on %s in ~1 min, once it gets a Cr-Commit-Position '
  3385. 'footer.' % branch)
  3386. hook = POSTUPSTREAM_HOOK_PATTERN % cmd
  3387. if os.path.isfile(hook):
  3388. RunCommand([hook, merge_base], error_ok=True)
  3389. return 1 if killed else 0
  3390. def WaitForRealCommit(remote, pushed_commit, local_base_ref, real_ref):
  3391. print
  3392. print 'Waiting for commit to be landed on %s...' % real_ref
  3393. print '(If you are impatient, you may Ctrl-C once without harm)'
  3394. target_tree = RunGit(['rev-parse', '%s:' % pushed_commit]).strip()
  3395. current_rev = RunGit(['rev-parse', local_base_ref]).strip()
  3396. mirror = settings.GetGitMirror(remote)
  3397. loop = 0
  3398. while True:
  3399. sys.stdout.write('fetching (%d)... \r' % loop)
  3400. sys.stdout.flush()
  3401. loop += 1
  3402. if mirror:
  3403. mirror.populate()
  3404. RunGit(['retry', 'fetch', remote, real_ref], stderr=subprocess2.VOID)
  3405. to_rev = RunGit(['rev-parse', 'FETCH_HEAD']).strip()
  3406. commits = RunGit(['rev-list', '%s..%s' % (current_rev, to_rev)])
  3407. for commit in commits.splitlines():
  3408. if RunGit(['rev-parse', '%s:' % commit]).strip() == target_tree:
  3409. print 'Found commit on %s' % real_ref
  3410. return commit
  3411. current_rev = to_rev
  3412. def PushToGitPending(remote, pending_ref, upstream_ref):
  3413. """Fetches pending_ref, cherry-picks current HEAD on top of it, pushes.
  3414. Returns:
  3415. (retcode of last operation, output log of last operation).
  3416. """
  3417. assert pending_ref.startswith('refs/'), pending_ref
  3418. local_pending_ref = 'refs/git-cl/' + pending_ref[len('refs/'):]
  3419. cherry = RunGit(['rev-parse', 'HEAD']).strip()
  3420. code = 0
  3421. out = ''
  3422. max_attempts = 3
  3423. attempts_left = max_attempts
  3424. while attempts_left:
  3425. if attempts_left != max_attempts:
  3426. print 'Retrying, %d attempts left...' % (attempts_left - 1,)
  3427. attempts_left -= 1
  3428. # Fetch. Retry fetch errors.
  3429. print 'Fetching pending ref %s...' % pending_ref
  3430. code, out = RunGitWithCode(
  3431. ['retry', 'fetch', remote, '+%s:%s' % (pending_ref, local_pending_ref)])
  3432. if code:
  3433. print 'Fetch failed with exit code %d.' % code
  3434. if out.strip():
  3435. print out.strip()
  3436. continue
  3437. # Try to cherry pick. Abort on merge conflicts.
  3438. print 'Cherry-picking commit on top of pending ref...'
  3439. RunGitWithCode(['checkout', local_pending_ref], suppress_stderr=True)
  3440. code, out = RunGitWithCode(['cherry-pick', cherry])
  3441. if code:
  3442. print (
  3443. 'Your patch doesn\'t apply cleanly to ref \'%s\', '
  3444. 'the following files have merge conflicts:' % pending_ref)
  3445. print RunGit(['diff', '--name-status', '--diff-filter=U']).strip()
  3446. print 'Please rebase your patch and try again.'
  3447. RunGitWithCode(['cherry-pick', '--abort'])
  3448. return code, out
  3449. # Applied cleanly, try to push now. Retry on error (flake or non-ff push).
  3450. print 'Pushing commit to %s... It can take a while.' % pending_ref
  3451. code, out = RunGitWithCode(
  3452. ['retry', 'push', '--porcelain', remote, 'HEAD:%s' % pending_ref])
  3453. if code == 0:
  3454. # Success.
  3455. print 'Commit pushed to pending ref successfully!'
  3456. return code, out
  3457. print 'Push failed with exit code %d.' % code
  3458. if out.strip():
  3459. print out.strip()
  3460. if IsFatalPushFailure(out):
  3461. print (
  3462. 'Fatal push error. Make sure your .netrc credentials and git '
  3463. 'user.email are correct and you have push access to the repo.')
  3464. return code, out
  3465. print 'All attempts to push to pending ref failed.'
  3466. return code, out
  3467. def IsFatalPushFailure(push_stdout):
  3468. """True if retrying push won't help."""
  3469. return '(prohibited by Gerrit)' in push_stdout
  3470. @subcommand.usage('[upstream branch to apply against]')
  3471. def CMDdcommit(parser, args):
  3472. """Commits the current changelist via git-svn."""
  3473. if not settings.GetIsGitSvn():
  3474. if git_footers.get_footer_svn_id():
  3475. # If it looks like previous commits were mirrored with git-svn.
  3476. message = """This repository appears to be a git-svn mirror, but no
  3477. upstream SVN master is set. You probably need to run 'git auto-svn' once."""
  3478. else:
  3479. message = """This doesn't appear to be an SVN repository.
  3480. If your project has a true, writeable git repository, you probably want to run
  3481. 'git cl land' instead.
  3482. If your project has a git mirror of an upstream SVN master, you probably need
  3483. to run 'git svn init'.
  3484. Using the wrong command might cause your commit to appear to succeed, and the
  3485. review to be closed, without actually landing upstream. If you choose to
  3486. proceed, please verify that the commit lands upstream as expected."""
  3487. print(message)
  3488. ask_for_data('[Press enter to dcommit or ctrl-C to quit]')
  3489. return SendUpstream(parser, args, 'dcommit')
  3490. @subcommand.usage('[upstream branch to apply against]')
  3491. def CMDland(parser, args):
  3492. """Commits the current changelist via git."""
  3493. if settings.GetIsGitSvn() or git_footers.get_footer_svn_id():
  3494. print('This appears to be an SVN repository.')
  3495. print('Are you sure you didn\'t mean \'git cl dcommit\'?')
  3496. print('(Ignore if this is the first commit after migrating from svn->git)')
  3497. ask_for_data('[Press enter to push or ctrl-C to quit]')
  3498. return SendUpstream(parser, args, 'land')
  3499. @subcommand.usage('<patch url or issue id or issue url>')
  3500. def CMDpatch(parser, args):
  3501. """Patches in a code review."""
  3502. parser.add_option('-b', dest='newbranch',
  3503. help='create a new branch off trunk for the patch')
  3504. parser.add_option('-f', '--force', action='store_true',
  3505. help='with -b, clobber any existing branch')
  3506. parser.add_option('-d', '--directory', action='store', metavar='DIR',
  3507. help='Change to the directory DIR immediately, '
  3508. 'before doing anything else. Rietveld only.')
  3509. parser.add_option('--reject', action='store_true',
  3510. help='failed patches spew .rej files rather than '
  3511. 'attempting a 3-way merge. Rietveld only.')
  3512. parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit',
  3513. help='don\'t commit after patch applies. Rietveld only.')
  3514. group = optparse.OptionGroup(
  3515. parser,
  3516. 'Options for continuing work on the current issue uploaded from a '
  3517. 'different clone (e.g. different machine). Must be used independently '
  3518. 'from the other options. No issue number should be specified, and the '
  3519. 'branch must have an issue number associated with it')
  3520. group.add_option('--reapply', action='store_true', dest='reapply',
  3521. help='Reset the branch and reapply the issue.\n'
  3522. 'CAUTION: This will undo any local changes in this '
  3523. 'branch')
  3524. group.add_option('--pull', action='store_true', dest='pull',
  3525. help='Performs a pull before reapplying.')
  3526. parser.add_option_group(group)
  3527. auth.add_auth_options(parser)
  3528. _add_codereview_select_options(parser)
  3529. (options, args) = parser.parse_args(args)
  3530. _process_codereview_select_options(parser, options)
  3531. auth_config = auth.extract_auth_config_from_options(options)
  3532. cl = Changelist(auth_config=auth_config, codereview=options.forced_codereview)
  3533. issue_arg = None
  3534. if options.reapply :
  3535. if len(args) > 0:
  3536. parser.error('--reapply implies no additional arguments.')
  3537. issue_arg = cl.GetIssue()
  3538. upstream = cl.GetUpstreamBranch()
  3539. if upstream == None:
  3540. parser.error('No upstream branch specified. Cannot reset branch')
  3541. RunGit(['reset', '--hard', upstream])
  3542. if options.pull:
  3543. RunGit(['pull'])
  3544. else:
  3545. if len(args) != 1:
  3546. parser.error('Must specify issue number or url')
  3547. issue_arg = args[0]
  3548. if not issue_arg:
  3549. parser.print_help()
  3550. return 1
  3551. if cl.IsGerrit():
  3552. if options.reject:
  3553. parser.error('--reject is not supported with Gerrit codereview.')
  3554. if options.nocommit:
  3555. parser.error('--nocommit is not supported with Gerrit codereview.')
  3556. if options.directory:
  3557. parser.error('--directory is not supported with Gerrit codereview.')
  3558. # We don't want uncommitted changes mixed up with the patch.
  3559. if git_common.is_dirty_git_tree('patch'):
  3560. return 1
  3561. if options.newbranch:
  3562. if options.reapply:
  3563. parser.error("--reapply excludes any option other than --pull")
  3564. if options.force:
  3565. RunGit(['branch', '-D', options.newbranch],
  3566. stderr=subprocess2.PIPE, error_ok=True)
  3567. RunGit(['checkout', '-b', options.newbranch,
  3568. Changelist().GetUpstreamBranch()])
  3569. return cl.CMDPatchIssue(issue_arg, options.reject, options.nocommit,
  3570. options.directory)
  3571. def CMDrebase(parser, args):
  3572. """Rebases current branch on top of svn repo."""
  3573. # Provide a wrapper for git svn rebase to help avoid accidental
  3574. # git svn dcommit.
  3575. # It's the only command that doesn't use parser at all since we just defer
  3576. # execution to git-svn.
  3577. return RunGitWithCode(['svn', 'rebase'] + args)[1]
  3578. def GetTreeStatus(url=None):
  3579. """Fetches the tree status and returns either 'open', 'closed',
  3580. 'unknown' or 'unset'."""
  3581. url = url or settings.GetTreeStatusUrl(error_ok=True)
  3582. if url:
  3583. status = urllib2.urlopen(url).read().lower()
  3584. if status.find('closed') != -1 or status == '0':
  3585. return 'closed'
  3586. elif status.find('open') != -1 or status == '1':
  3587. return 'open'
  3588. return 'unknown'
  3589. return 'unset'
  3590. def GetTreeStatusReason():
  3591. """Fetches the tree status from a json url and returns the message
  3592. with the reason for the tree to be opened or closed."""
  3593. url = settings.GetTreeStatusUrl()
  3594. json_url = urlparse.urljoin(url, '/current?format=json')
  3595. connection = urllib2.urlopen(json_url)
  3596. status = json.loads(connection.read())
  3597. connection.close()
  3598. return status['message']
  3599. def GetBuilderMaster(bot_list):
  3600. """For a given builder, fetch the master from AE if available."""
  3601. map_url = 'https://builders-map.appspot.com/'
  3602. try:
  3603. master_map = json.load(urllib2.urlopen(map_url))
  3604. except urllib2.URLError as e:
  3605. return None, ('Failed to fetch builder-to-master map from %s. Error: %s.' %
  3606. (map_url, e))
  3607. except ValueError as e:
  3608. return None, ('Invalid json string from %s. Error: %s.' % (map_url, e))
  3609. if not master_map:
  3610. return None, 'Failed to build master map.'
  3611. result_master = ''
  3612. for bot in bot_list:
  3613. builder = bot.split(':', 1)[0]
  3614. master_list = master_map.get(builder, [])
  3615. if not master_list:
  3616. return None, ('No matching master for builder %s.' % builder)
  3617. elif len(master_list) > 1:
  3618. return None, ('The builder name %s exists in multiple masters %s.' %
  3619. (builder, master_list))
  3620. else:
  3621. cur_master = master_list[0]
  3622. if not result_master:
  3623. result_master = cur_master
  3624. elif result_master != cur_master:
  3625. return None, 'The builders do not belong to the same master.'
  3626. return result_master, None
  3627. def CMDtree(parser, args):
  3628. """Shows the status of the tree."""
  3629. _, args = parser.parse_args(args)
  3630. status = GetTreeStatus()
  3631. if 'unset' == status:
  3632. print 'You must configure your tree status URL by running "git cl config".'
  3633. return 2
  3634. print "The tree is %s" % status
  3635. print
  3636. print GetTreeStatusReason()
  3637. if status != 'open':
  3638. return 1
  3639. return 0
  3640. def CMDtry(parser, args):
  3641. """Triggers try jobs through BuildBucket."""
  3642. group = optparse.OptionGroup(parser, "Try job options")
  3643. group.add_option(
  3644. "-b", "--bot", action="append",
  3645. help=("IMPORTANT: specify ONE builder per --bot flag. Use it multiple "
  3646. "times to specify multiple builders. ex: "
  3647. "'-b win_rel -b win_layout'. See "
  3648. "the try server waterfall for the builders name and the tests "
  3649. "available."))
  3650. group.add_option(
  3651. "-m", "--master", default='',
  3652. help=("Specify a try master where to run the tries."))
  3653. group.add_option( "--luci", action='store_true')
  3654. group.add_option(
  3655. "-r", "--revision",
  3656. help="Revision to use for the try job; default: the "
  3657. "revision will be determined by the try server; see "
  3658. "its waterfall for more info")
  3659. group.add_option(
  3660. "-c", "--clobber", action="store_true", default=False,
  3661. help="Force a clobber before building; e.g. don't do an "
  3662. "incremental build")
  3663. group.add_option(
  3664. "--project",
  3665. help="Override which project to use. Projects are defined "
  3666. "server-side to define what default bot set to use")
  3667. group.add_option(
  3668. "-p", "--property", dest="properties", action="append", default=[],
  3669. help="Specify generic properties in the form -p key1=value1 -p "
  3670. "key2=value2 etc (buildbucket only). The value will be treated as "
  3671. "json if decodable, or as string otherwise.")
  3672. group.add_option(
  3673. "-n", "--name", help="Try job name; default to current branch name")
  3674. group.add_option(
  3675. "--use-rietveld", action="store_true", default=False,
  3676. help="Use Rietveld to trigger try jobs.")
  3677. group.add_option(
  3678. "--buildbucket-host", default='cr-buildbucket.appspot.com',
  3679. help="Host of buildbucket. The default host is %default.")
  3680. parser.add_option_group(group)
  3681. auth.add_auth_options(parser)
  3682. options, args = parser.parse_args(args)
  3683. auth_config = auth.extract_auth_config_from_options(options)
  3684. if options.use_rietveld and options.properties:
  3685. parser.error('Properties can only be specified with buildbucket')
  3686. # Make sure that all properties are prop=value pairs.
  3687. bad_params = [x for x in options.properties if '=' not in x]
  3688. if bad_params:
  3689. parser.error('Got properties with missing "=": %s' % bad_params)
  3690. if args:
  3691. parser.error('Unknown arguments: %s' % args)
  3692. cl = Changelist(auth_config=auth_config)
  3693. if not cl.GetIssue():
  3694. parser.error('Need to upload first')
  3695. if cl.IsGerrit():
  3696. parser.error(
  3697. 'Not yet supported for Gerrit (http://crbug.com/599931).\n'
  3698. 'If your project has Commit Queue, dry run is a workaround:\n'
  3699. ' git cl set-commit --dry-run')
  3700. # Code below assumes Rietveld issue.
  3701. # TODO(tandrii): actually implement for Gerrit http://crbug.com/599931.
  3702. props = cl.GetIssueProperties()
  3703. if props.get('closed'):
  3704. parser.error('Cannot send tryjobs for a closed CL')
  3705. if props.get('private'):
  3706. parser.error('Cannot use trybots with private issue')
  3707. if not options.name:
  3708. options.name = cl.GetBranch()
  3709. if options.bot and not options.master:
  3710. options.master, err_msg = GetBuilderMaster(options.bot)
  3711. if err_msg:
  3712. parser.error('Tryserver master cannot be found because: %s\n'
  3713. 'Please manually specify the tryserver master'
  3714. ', e.g. "-m tryserver.chromium.linux".' % err_msg)
  3715. def GetMasterMap():
  3716. # Process --bot.
  3717. if not options.bot:
  3718. change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
  3719. # Get try masters from PRESUBMIT.py files.
  3720. masters = presubmit_support.DoGetTryMasters(
  3721. change,
  3722. change.LocalPaths(),
  3723. settings.GetRoot(),
  3724. None,
  3725. None,
  3726. options.verbose,
  3727. sys.stdout)
  3728. if masters:
  3729. return masters
  3730. # Fall back to deprecated method: get try slaves from PRESUBMIT.py files.
  3731. options.bot = presubmit_support.DoGetTrySlaves(
  3732. change,
  3733. change.LocalPaths(),
  3734. settings.GetRoot(),
  3735. None,
  3736. None,
  3737. options.verbose,
  3738. sys.stdout)
  3739. if not options.bot:
  3740. # Get try masters from cq.cfg if any.
  3741. # TODO(tandrii): some (but very few) projects store cq.cfg in different
  3742. # location.
  3743. cq_cfg = os.path.join(change.RepositoryRoot(),
  3744. 'infra', 'config', 'cq.cfg')
  3745. if os.path.exists(cq_cfg):
  3746. masters = {}
  3747. cq_masters = commit_queue.get_master_builder_map(
  3748. cq_cfg, include_experimental=False, include_triggered=False)
  3749. for master, builders in cq_masters.iteritems():
  3750. for builder in builders:
  3751. # Skip presubmit builders, because these will fail without LGTM.
  3752. masters.setdefault(master, {})[builder] = ['defaulttests']
  3753. if masters:
  3754. return masters
  3755. if not options.bot:
  3756. parser.error('No default try builder to try, use --bot')
  3757. builders_and_tests = {}
  3758. # TODO(machenbach): The old style command-line options don't support
  3759. # multiple try masters yet.
  3760. old_style = filter(lambda x: isinstance(x, basestring), options.bot)
  3761. new_style = filter(lambda x: isinstance(x, tuple), options.bot)
  3762. for bot in old_style:
  3763. if ':' in bot:
  3764. parser.error('Specifying testfilter is no longer supported')
  3765. elif ',' in bot:
  3766. parser.error('Specify one bot per --bot flag')
  3767. else:
  3768. builders_and_tests.setdefault(bot, [])
  3769. for bot, tests in new_style:
  3770. builders_and_tests.setdefault(bot, []).extend(tests)
  3771. # Return a master map with one master to be backwards compatible. The
  3772. # master name defaults to an empty string, which will cause the master
  3773. # not to be set on rietveld (deprecated).
  3774. return {options.master: builders_and_tests}
  3775. masters = GetMasterMap()
  3776. for builders in masters.itervalues():
  3777. if any('triggered' in b for b in builders):
  3778. print >> sys.stderr, (
  3779. 'ERROR You are trying to send a job to a triggered bot. This type of'
  3780. ' bot requires an\ninitial job from a parent (usually a builder). '
  3781. 'Instead send your job to the parent.\n'
  3782. 'Bot list: %s' % builders)
  3783. return 1
  3784. patchset = cl.GetMostRecentPatchset()
  3785. if patchset and patchset != cl.GetPatchset():
  3786. print(
  3787. '\nWARNING Mismatch between local config and server. Did a previous '
  3788. 'upload fail?\ngit-cl try always uses latest patchset from rietveld. '
  3789. 'Continuing using\npatchset %s.\n' % patchset)
  3790. if options.luci:
  3791. trigger_luci_job(cl, masters, options)
  3792. elif not options.use_rietveld:
  3793. try:
  3794. trigger_try_jobs(auth_config, cl, options, masters, 'git_cl_try')
  3795. except BuildbucketResponseException as ex:
  3796. print 'ERROR: %s' % ex
  3797. return 1
  3798. except Exception as e:
  3799. stacktrace = (''.join(traceback.format_stack()) + traceback.format_exc())
  3800. print 'ERROR: Exception when trying to trigger tryjobs: %s\n%s' % (
  3801. e, stacktrace)
  3802. return 1
  3803. else:
  3804. try:
  3805. cl.RpcServer().trigger_distributed_try_jobs(
  3806. cl.GetIssue(), patchset, options.name, options.clobber,
  3807. options.revision, masters)
  3808. except urllib2.HTTPError as e:
  3809. if e.code == 404:
  3810. print('404 from rietveld; '
  3811. 'did you mean to use "git try" instead of "git cl try"?')
  3812. return 1
  3813. print('Tried jobs on:')
  3814. for (master, builders) in sorted(masters.iteritems()):
  3815. if master:
  3816. print 'Master: %s' % master
  3817. length = max(len(builder) for builder in builders)
  3818. for builder in sorted(builders):
  3819. print ' %*s: %s' % (length, builder, ','.join(builders[builder]))
  3820. return 0
  3821. def CMDtry_results(parser, args):
  3822. group = optparse.OptionGroup(parser, "Try job results options")
  3823. group.add_option(
  3824. "-p", "--patchset", type=int, help="patchset number if not current.")
  3825. group.add_option(
  3826. "--print-master", action='store_true', help="print master name as well.")
  3827. group.add_option(
  3828. "--color", action='store_true', default=setup_color.IS_TTY,
  3829. help="force color output, useful when piping output.")
  3830. group.add_option(
  3831. "--buildbucket-host", default='cr-buildbucket.appspot.com',
  3832. help="Host of buildbucket. The default host is %default.")
  3833. parser.add_option_group(group)
  3834. auth.add_auth_options(parser)
  3835. options, args = parser.parse_args(args)
  3836. if args:
  3837. parser.error('Unrecognized args: %s' % ' '.join(args))
  3838. auth_config = auth.extract_auth_config_from_options(options)
  3839. cl = Changelist(auth_config=auth_config)
  3840. if not cl.GetIssue():
  3841. parser.error('Need to upload first')
  3842. if not options.patchset:
  3843. options.patchset = cl.GetMostRecentPatchset()
  3844. if options.patchset and options.patchset != cl.GetPatchset():
  3845. print(
  3846. '\nWARNING Mismatch between local config and server. Did a previous '
  3847. 'upload fail?\ngit-cl try always uses latest patchset from rietveld. '
  3848. 'Continuing using\npatchset %s.\n' % options.patchset)
  3849. try:
  3850. jobs = fetch_try_jobs(auth_config, cl, options)
  3851. except BuildbucketResponseException as ex:
  3852. print 'Buildbucket error: %s' % ex
  3853. return 1
  3854. except Exception as e:
  3855. stacktrace = (''.join(traceback.format_stack()) + traceback.format_exc())
  3856. print 'ERROR: Exception when trying to fetch tryjobs: %s\n%s' % (
  3857. e, stacktrace)
  3858. return 1
  3859. print_tryjobs(options, jobs)
  3860. return 0
  3861. @subcommand.usage('[new upstream branch]')
  3862. def CMDupstream(parser, args):
  3863. """Prints or sets the name of the upstream branch, if any."""
  3864. _, args = parser.parse_args(args)
  3865. if len(args) > 1:
  3866. parser.error('Unrecognized args: %s' % ' '.join(args))
  3867. cl = Changelist()
  3868. if args:
  3869. # One arg means set upstream branch.
  3870. branch = cl.GetBranch()
  3871. RunGit(['branch', '--set-upstream', branch, args[0]])
  3872. cl = Changelist()
  3873. print "Upstream branch set to " + cl.GetUpstreamBranch()
  3874. # Clear configured merge-base, if there is one.
  3875. git_common.remove_merge_base(branch)
  3876. else:
  3877. print cl.GetUpstreamBranch()
  3878. return 0
  3879. def CMDweb(parser, args):
  3880. """Opens the current CL in the web browser."""
  3881. _, args = parser.parse_args(args)
  3882. if args:
  3883. parser.error('Unrecognized args: %s' % ' '.join(args))
  3884. issue_url = Changelist().GetIssueURL()
  3885. if not issue_url:
  3886. print >> sys.stderr, 'ERROR No issue to open'
  3887. return 1
  3888. webbrowser.open(issue_url)
  3889. return 0
  3890. def CMDset_commit(parser, args):
  3891. """Sets the commit bit to trigger the Commit Queue."""
  3892. parser.add_option('-d', '--dry-run', action='store_true',
  3893. help='trigger in dry run mode')
  3894. parser.add_option('-c', '--clear', action='store_true',
  3895. help='stop CQ run, if any')
  3896. auth.add_auth_options(parser)
  3897. options, args = parser.parse_args(args)
  3898. auth_config = auth.extract_auth_config_from_options(options)
  3899. if args:
  3900. parser.error('Unrecognized args: %s' % ' '.join(args))
  3901. if options.dry_run and options.clear:
  3902. parser.error('Make up your mind: both --dry-run and --clear not allowed')
  3903. cl = Changelist(auth_config=auth_config)
  3904. if options.clear:
  3905. state = _CQState.CLEAR
  3906. elif options.dry_run:
  3907. state = _CQState.DRY_RUN
  3908. else:
  3909. state = _CQState.COMMIT
  3910. if not cl.GetIssue():
  3911. parser.error('Must upload the issue first')
  3912. cl.SetCQState(state)
  3913. return 0
  3914. def CMDset_close(parser, args):
  3915. """Closes the issue."""
  3916. auth.add_auth_options(parser)
  3917. options, args = parser.parse_args(args)
  3918. auth_config = auth.extract_auth_config_from_options(options)
  3919. if args:
  3920. parser.error('Unrecognized args: %s' % ' '.join(args))
  3921. cl = Changelist(auth_config=auth_config)
  3922. # Ensure there actually is an issue to close.
  3923. cl.GetDescription()
  3924. cl.CloseIssue()
  3925. return 0
  3926. def CMDdiff(parser, args):
  3927. """Shows differences between local tree and last upload."""
  3928. auth.add_auth_options(parser)
  3929. options, args = parser.parse_args(args)
  3930. auth_config = auth.extract_auth_config_from_options(options)
  3931. if args:
  3932. parser.error('Unrecognized args: %s' % ' '.join(args))
  3933. # Uncommitted (staged and unstaged) changes will be destroyed by
  3934. # "git reset --hard" if there are merging conflicts in CMDPatchIssue().
  3935. # Staged changes would be committed along with the patch from last
  3936. # upload, hence counted toward the "last upload" side in the final
  3937. # diff output, and this is not what we want.
  3938. if git_common.is_dirty_git_tree('diff'):
  3939. return 1
  3940. cl = Changelist(auth_config=auth_config)
  3941. issue = cl.GetIssue()
  3942. branch = cl.GetBranch()
  3943. if not issue:
  3944. DieWithError('No issue found for current branch (%s)' % branch)
  3945. TMP_BRANCH = 'git-cl-diff'
  3946. base_branch = cl.GetCommonAncestorWithUpstream()
  3947. # Create a new branch based on the merge-base
  3948. RunGit(['checkout', '-q', '-b', TMP_BRANCH, base_branch])
  3949. # Clear cached branch in cl object, to avoid overwriting original CL branch
  3950. # properties.
  3951. cl.ClearBranch()
  3952. try:
  3953. rtn = cl.CMDPatchIssue(issue, reject=False, nocommit=False, directory=None)
  3954. if rtn != 0:
  3955. RunGit(['reset', '--hard'])
  3956. return rtn
  3957. # Switch back to starting branch and diff against the temporary
  3958. # branch containing the latest rietveld patch.
  3959. subprocess2.check_call(['git', 'diff', TMP_BRANCH, branch, '--'])
  3960. finally:
  3961. RunGit(['checkout', '-q', branch])
  3962. RunGit(['branch', '-D', TMP_BRANCH])
  3963. return 0
  3964. def CMDowners(parser, args):
  3965. """Interactively find the owners for reviewing."""
  3966. parser.add_option(
  3967. '--no-color',
  3968. action='store_true',
  3969. help='Use this option to disable color output')
  3970. auth.add_auth_options(parser)
  3971. options, args = parser.parse_args(args)
  3972. auth_config = auth.extract_auth_config_from_options(options)
  3973. author = RunGit(['config', 'user.email']).strip() or None
  3974. cl = Changelist(auth_config=auth_config)
  3975. if args:
  3976. if len(args) > 1:
  3977. parser.error('Unknown args')
  3978. base_branch = args[0]
  3979. else:
  3980. # Default to diffing against the common ancestor of the upstream branch.
  3981. base_branch = cl.GetCommonAncestorWithUpstream()
  3982. change = cl.GetChange(base_branch, None)
  3983. return owners_finder.OwnersFinder(
  3984. [f.LocalPath() for f in
  3985. cl.GetChange(base_branch, None).AffectedFiles()],
  3986. change.RepositoryRoot(), author,
  3987. fopen=file, os_path=os.path, glob=glob.glob,
  3988. disable_color=options.no_color).run()
  3989. def BuildGitDiffCmd(diff_type, upstream_commit, args):
  3990. """Generates a diff command."""
  3991. # Generate diff for the current branch's changes.
  3992. diff_cmd = ['diff', '--no-ext-diff', '--no-prefix', diff_type,
  3993. upstream_commit, '--' ]
  3994. if args:
  3995. for arg in args:
  3996. if os.path.isdir(arg) or os.path.isfile(arg):
  3997. diff_cmd.append(arg)
  3998. else:
  3999. DieWithError('Argument "%s" is not a file or a directory' % arg)
  4000. return diff_cmd
  4001. def MatchingFileType(file_name, extensions):
  4002. """Returns true if the file name ends with one of the given extensions."""
  4003. return bool([ext for ext in extensions if file_name.lower().endswith(ext)])
  4004. @subcommand.usage('[files or directories to diff]')
  4005. def CMDformat(parser, args):
  4006. """Runs auto-formatting tools (clang-format etc.) on the diff."""
  4007. CLANG_EXTS = ['.cc', '.cpp', '.h', '.mm', '.proto', '.java']
  4008. GN_EXTS = ['.gn', '.gni']
  4009. parser.add_option('--full', action='store_true',
  4010. help='Reformat the full content of all touched files')
  4011. parser.add_option('--dry-run', action='store_true',
  4012. help='Don\'t modify any file on disk.')
  4013. parser.add_option('--python', action='store_true',
  4014. help='Format python code with yapf (experimental).')
  4015. parser.add_option('--diff', action='store_true',
  4016. help='Print diff to stdout rather than modifying files.')
  4017. opts, args = parser.parse_args(args)
  4018. # git diff generates paths against the root of the repository. Change
  4019. # to that directory so clang-format can find files even within subdirs.
  4020. rel_base_path = settings.GetRelativeRoot()
  4021. if rel_base_path:
  4022. os.chdir(rel_base_path)
  4023. # Grab the merge-base commit, i.e. the upstream commit of the current
  4024. # branch when it was created or the last time it was rebased. This is
  4025. # to cover the case where the user may have called "git fetch origin",
  4026. # moving the origin branch to a newer commit, but hasn't rebased yet.
  4027. upstream_commit = None
  4028. cl = Changelist()
  4029. upstream_branch = cl.GetUpstreamBranch()
  4030. if upstream_branch:
  4031. upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch])
  4032. upstream_commit = upstream_commit.strip()
  4033. if not upstream_commit:
  4034. DieWithError('Could not find base commit for this branch. '
  4035. 'Are you in detached state?')
  4036. changed_files_cmd = BuildGitDiffCmd('--name-only', upstream_commit, args)
  4037. diff_output = RunGit(changed_files_cmd)
  4038. diff_files = diff_output.splitlines()
  4039. # Filter out files deleted by this CL
  4040. diff_files = [x for x in diff_files if os.path.isfile(x)]
  4041. clang_diff_files = [x for x in diff_files if MatchingFileType(x, CLANG_EXTS)]
  4042. python_diff_files = [x for x in diff_files if MatchingFileType(x, ['.py'])]
  4043. dart_diff_files = [x for x in diff_files if MatchingFileType(x, ['.dart'])]
  4044. gn_diff_files = [x for x in diff_files if MatchingFileType(x, GN_EXTS)]
  4045. top_dir = os.path.normpath(
  4046. RunGit(["rev-parse", "--show-toplevel"]).rstrip('\n'))
  4047. # Set to 2 to signal to CheckPatchFormatted() that this patch isn't
  4048. # formatted. This is used to block during the presubmit.
  4049. return_value = 0
  4050. if clang_diff_files:
  4051. # Locate the clang-format binary in the checkout
  4052. try:
  4053. clang_format_tool = clang_format.FindClangFormatToolInChromiumTree()
  4054. except clang_format.NotFoundError, e:
  4055. DieWithError(e)
  4056. if opts.full:
  4057. cmd = [clang_format_tool]
  4058. if not opts.dry_run and not opts.diff:
  4059. cmd.append('-i')
  4060. stdout = RunCommand(cmd + clang_diff_files, cwd=top_dir)
  4061. if opts.diff:
  4062. sys.stdout.write(stdout)
  4063. else:
  4064. env = os.environ.copy()
  4065. env['PATH'] = str(os.path.dirname(clang_format_tool))
  4066. try:
  4067. script = clang_format.FindClangFormatScriptInChromiumTree(
  4068. 'clang-format-diff.py')
  4069. except clang_format.NotFoundError, e:
  4070. DieWithError(e)
  4071. cmd = [sys.executable, script, '-p0']
  4072. if not opts.dry_run and not opts.diff:
  4073. cmd.append('-i')
  4074. diff_cmd = BuildGitDiffCmd('-U0', upstream_commit, clang_diff_files)
  4075. diff_output = RunGit(diff_cmd)
  4076. stdout = RunCommand(cmd, stdin=diff_output, cwd=top_dir, env=env)
  4077. if opts.diff:
  4078. sys.stdout.write(stdout)
  4079. if opts.dry_run and len(stdout) > 0:
  4080. return_value = 2
  4081. # Similar code to above, but using yapf on .py files rather than clang-format
  4082. # on C/C++ files
  4083. if opts.python:
  4084. yapf_tool = gclient_utils.FindExecutable('yapf')
  4085. if yapf_tool is None:
  4086. DieWithError('yapf not found in PATH')
  4087. if opts.full:
  4088. if python_diff_files:
  4089. cmd = [yapf_tool]
  4090. if not opts.dry_run and not opts.diff:
  4091. cmd.append('-i')
  4092. stdout = RunCommand(cmd + python_diff_files, cwd=top_dir)
  4093. if opts.diff:
  4094. sys.stdout.write(stdout)
  4095. else:
  4096. # TODO(sbc): yapf --lines mode still has some issues.
  4097. # https://github.com/google/yapf/issues/154
  4098. DieWithError('--python currently only works with --full')
  4099. # Dart's formatter does not have the nice property of only operating on
  4100. # modified chunks, so hard code full.
  4101. if dart_diff_files:
  4102. try:
  4103. command = [dart_format.FindDartFmtToolInChromiumTree()]
  4104. if not opts.dry_run and not opts.diff:
  4105. command.append('-w')
  4106. command.extend(dart_diff_files)
  4107. stdout = RunCommand(command, cwd=top_dir)
  4108. if opts.dry_run and stdout:
  4109. return_value = 2
  4110. except dart_format.NotFoundError as e:
  4111. print ('Warning: Unable to check Dart code formatting. Dart SDK not ' +
  4112. 'found in this checkout. Files in other languages are still ' +
  4113. 'formatted.')
  4114. # Format GN build files. Always run on full build files for canonical form.
  4115. if gn_diff_files:
  4116. cmd = ['gn', 'format']
  4117. if not opts.dry_run and not opts.diff:
  4118. cmd.append('--in-place')
  4119. for gn_diff_file in gn_diff_files:
  4120. stdout = RunCommand(cmd + [gn_diff_file],
  4121. shell=sys.platform == 'win32',
  4122. cwd=top_dir)
  4123. if opts.diff:
  4124. sys.stdout.write(stdout)
  4125. return return_value
  4126. @subcommand.usage('<codereview url or issue id>')
  4127. def CMDcheckout(parser, args):
  4128. """Checks out a branch associated with a given Rietveld or Gerrit issue."""
  4129. _, args = parser.parse_args(args)
  4130. if len(args) != 1:
  4131. parser.print_help()
  4132. return 1
  4133. issue_arg = ParseIssueNumberArgument(args[0])
  4134. if not issue_arg.valid:
  4135. parser.print_help()
  4136. return 1
  4137. target_issue = str(issue_arg.issue)
  4138. def find_issues(issueprefix):
  4139. output = RunGit(['config', '--local', '--get-regexp',
  4140. r'branch\..*\.%s' % issueprefix],
  4141. error_ok=True)
  4142. for key, issue in [x.split() for x in output.splitlines()]:
  4143. if issue == target_issue:
  4144. yield re.sub(r'branch\.(.*)\.%s' % issueprefix, r'\1', key)
  4145. branches = []
  4146. for cls in _CODEREVIEW_IMPLEMENTATIONS.values():
  4147. branches.extend(find_issues(cls.IssueSettingSuffix()))
  4148. if len(branches) == 0:
  4149. print 'No branch found for issue %s.' % target_issue
  4150. return 1
  4151. if len(branches) == 1:
  4152. RunGit(['checkout', branches[0]])
  4153. else:
  4154. print 'Multiple branches match issue %s:' % target_issue
  4155. for i in range(len(branches)):
  4156. print '%d: %s' % (i, branches[i])
  4157. which = raw_input('Choose by index: ')
  4158. try:
  4159. RunGit(['checkout', branches[int(which)]])
  4160. except (IndexError, ValueError):
  4161. print 'Invalid selection, not checking out any branch.'
  4162. return 1
  4163. return 0
  4164. def CMDlol(parser, args):
  4165. # This command is intentionally undocumented.
  4166. print zlib.decompress(base64.b64decode(
  4167. 'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE'
  4168. 'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9'
  4169. 'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W'
  4170. 'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY'))
  4171. return 0
  4172. class OptionParser(optparse.OptionParser):
  4173. """Creates the option parse and add --verbose support."""
  4174. def __init__(self, *args, **kwargs):
  4175. optparse.OptionParser.__init__(
  4176. self, *args, prog='git cl', version=__version__, **kwargs)
  4177. self.add_option(
  4178. '-v', '--verbose', action='count', default=0,
  4179. help='Use 2 times for more debugging info')
  4180. def parse_args(self, args=None, values=None):
  4181. options, args = optparse.OptionParser.parse_args(self, args, values)
  4182. levels = [logging.WARNING, logging.INFO, logging.DEBUG]
  4183. logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
  4184. return options, args
  4185. def main(argv):
  4186. if sys.hexversion < 0x02060000:
  4187. print >> sys.stderr, (
  4188. '\nYour python version %s is unsupported, please upgrade.\n' %
  4189. sys.version.split(' ', 1)[0])
  4190. return 2
  4191. # Reload settings.
  4192. global settings
  4193. settings = Settings()
  4194. colorize_CMDstatus_doc()
  4195. dispatcher = subcommand.CommandDispatcher(__name__)
  4196. try:
  4197. return dispatcher.execute(OptionParser(), argv)
  4198. except auth.AuthenticationError as e:
  4199. DieWithError(str(e))
  4200. except urllib2.HTTPError, e:
  4201. if e.code != 500:
  4202. raise
  4203. DieWithError(
  4204. ('AppEngine is misbehaving and returned HTTP %d, again. Keep faith '
  4205. 'and retry or visit go/isgaeup.\n%s') % (e.code, str(e)))
  4206. return 0
  4207. if __name__ == '__main__':
  4208. # These affect sys.stdout so do it outside of main() to simplify mocks in
  4209. # unit testing.
  4210. fix_encoding.fix_encoding()
  4211. setup_color.init()
  4212. try:
  4213. sys.exit(main(sys.argv[1:]))
  4214. except KeyboardInterrupt:
  4215. sys.stderr.write('interrupted\n')
  4216. sys.exit(1)