git_cl.py 203 KB

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