git_cl.py 271 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011
  1. #!/usr/bin/env vpython3
  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 annotations
  8. import base64
  9. import collections
  10. import datetime
  11. import enum
  12. import fnmatch
  13. import functools
  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 urllib.parse
  29. import urllib.request
  30. import uuid
  31. import webbrowser
  32. import zlib
  33. from typing import Any
  34. from typing import Callable
  35. from typing import List
  36. from typing import Mapping
  37. from typing import NoReturn
  38. from typing import Optional
  39. from typing import Sequence
  40. from typing import Tuple
  41. import auth
  42. import clang_format
  43. import gclient_paths
  44. import gclient_utils
  45. import gerrit_util
  46. import git_auth
  47. import git_common
  48. import git_footers
  49. import git_new_branch
  50. import google_java_format
  51. import metrics
  52. import metrics_utils
  53. import newauth
  54. import owners_client
  55. import owners_finder
  56. import presubmit_canned_checks
  57. import presubmit_support
  58. import rustfmt
  59. import scm
  60. import setup_color
  61. import split_cl
  62. import subcommand
  63. import subprocess2
  64. import swift_format
  65. import watchlists
  66. from third_party import colorama
  67. __version__ = '2.0'
  68. # TODO: Should fix these warnings.
  69. # pylint: disable=line-too-long
  70. # Traces for git push will be stored in a traces directory inside the
  71. # depot_tools checkout.
  72. DEPOT_TOOLS = os.path.dirname(os.path.abspath(__file__))
  73. TRACES_DIR = os.path.join(DEPOT_TOOLS, 'traces')
  74. PRESUBMIT_SUPPORT = os.path.join(DEPOT_TOOLS, 'presubmit_support.py')
  75. # When collecting traces, Git hashes will be reduced to 6 characters to reduce
  76. # the size after compression.
  77. GIT_HASH_RE = re.compile(r'\b([a-f0-9]{6})[a-f0-9]{34}\b', flags=re.I)
  78. # Used to redact the cookies from the gitcookies file.
  79. GITCOOKIES_REDACT_RE = re.compile(r'1/.*')
  80. MAX_ATTEMPTS = 3
  81. # The maximum number of traces we will keep. Multiplied by 3 since we store
  82. # 3 files per trace.
  83. MAX_TRACES = 3 * 10
  84. # Message to be displayed to the user to inform where to find the traces for a
  85. # git-cl upload execution.
  86. TRACES_MESSAGE = (
  87. '\n'
  88. 'The traces of this git-cl execution have been recorded at:\n'
  89. ' %(trace_name)s-traces.zip\n'
  90. 'Copies of your gitcookies file and git config have been recorded at:\n'
  91. ' %(trace_name)s-git-info.zip\n')
  92. # Format of the message to be stored as part of the traces to give developers a
  93. # better context when they go through traces.
  94. TRACES_README_FORMAT = ('Date: %(now)s\n'
  95. '\n'
  96. 'Change: https://%(gerrit_host)s/q/%(change_id)s\n'
  97. 'Title: %(title)s\n'
  98. '\n'
  99. '%(description)s\n'
  100. '\n'
  101. 'Execution time: %(execution_time)s\n'
  102. 'Exit code: %(exit_code)s\n') + TRACES_MESSAGE
  103. POSTUPSTREAM_HOOK = '.git/hooks/post-cl-land'
  104. DESCRIPTION_BACKUP_FILE = '.git_cl_description_backup'
  105. REFS_THAT_ALIAS_TO_OTHER_REFS = {
  106. 'refs/remotes/origin/lkgr': 'refs/remotes/origin/main',
  107. 'refs/remotes/origin/lkcr': 'refs/remotes/origin/main',
  108. }
  109. DEFAULT_OLD_BRANCH = 'refs/remotes/origin/master'
  110. DEFAULT_NEW_BRANCH = 'refs/remotes/origin/main'
  111. DEFAULT_BUILDBUCKET_HOST = 'cr-buildbucket.appspot.com'
  112. # Valid extensions for files we want to lint.
  113. DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)"
  114. DEFAULT_LINT_IGNORE_REGEX = r"$^"
  115. # File name for yapf style config files.
  116. YAPF_CONFIG_FILENAME = '.style.yapf'
  117. # The issue, patchset and codereview server are stored on git config for each
  118. # branch under branch.<branch-name>.<config-key>.
  119. ISSUE_CONFIG_KEY = 'gerritissue'
  120. PATCHSET_CONFIG_KEY = 'gerritpatchset'
  121. CODEREVIEW_SERVER_CONFIG_KEY = 'gerritserver'
  122. # When using squash workflow, _CMDUploadChange doesn't simply push the commit(s)
  123. # you make to Gerrit. Instead, it creates a new commit object that contains all
  124. # changes you've made, diffed against a parent/merge base.
  125. # This is the hash of the new squashed commit and you can find this on Gerrit.
  126. GERRIT_SQUASH_HASH_CONFIG_KEY = 'gerritsquashhash'
  127. # This is the latest uploaded local commit hash.
  128. LAST_UPLOAD_HASH_CONFIG_KEY = 'last-upload-hash'
  129. # Shortcut since it quickly becomes repetitive.
  130. Fore = colorama.Fore
  131. # Used by tests/git_cl_test.py to add extra logging.
  132. # Inside the weirdly failing test, add this:
  133. # >>> self.mock(git_cl, '_IS_BEING_TESTED', True)
  134. # And scroll up to see the stack trace printed.
  135. _IS_BEING_TESTED = False
  136. _GOOGLESOURCE = 'googlesource.com'
  137. _KNOWN_GERRIT_TO_SHORT_URLS = {
  138. 'https://chrome-internal-review.googlesource.com': 'https://crrev.com/i',
  139. 'https://chromium-review.googlesource.com': 'https://crrev.com/c',
  140. }
  141. assert len(_KNOWN_GERRIT_TO_SHORT_URLS) == len(
  142. set(_KNOWN_GERRIT_TO_SHORT_URLS.values())), 'must have unique values'
  143. # Maximum number of branches in a stack that can be traversed and uploaded
  144. # at once. Picked arbitrarily.
  145. _MAX_STACKED_BRANCHES_UPLOAD = 20
  146. class GitPushError(Exception):
  147. pass
  148. def DieWithError(message, change_desc=None) -> NoReturn:
  149. if change_desc:
  150. SaveDescriptionBackup(change_desc)
  151. print('\n ** Content of CL description **\n' + '=' * 72 + '\n' +
  152. change_desc.description + '\n' + '=' * 72 + '\n')
  153. print(message, file=sys.stderr)
  154. sys.exit(1)
  155. def SaveDescriptionBackup(change_desc):
  156. backup_path = os.path.join(DEPOT_TOOLS, DESCRIPTION_BACKUP_FILE)
  157. print('\nsaving CL description to %s\n' % backup_path)
  158. with open(backup_path, 'wb') as backup_file:
  159. backup_file.write(change_desc.description.encode('utf-8'))
  160. def GetNoGitPagerEnv():
  161. env = os.environ.copy()
  162. # 'cat' is a magical git string that disables pagers on all platforms.
  163. env['GIT_PAGER'] = 'cat'
  164. return env
  165. def RunCommand(args, error_ok=False, error_message=None, shell=False, **kwargs):
  166. try:
  167. stdout = subprocess2.check_output(args, shell=shell, **kwargs)
  168. return stdout.decode('utf-8', 'replace')
  169. except subprocess2.CalledProcessError as e:
  170. logging.debug('Failed running %s', args)
  171. if not error_ok:
  172. message = error_message or e.stdout.decode('utf-8', 'replace') or ''
  173. DieWithError('Command "%s" failed.\n%s' % (' '.join(args), message))
  174. out = e.stdout.decode('utf-8', 'replace')
  175. if e.stderr:
  176. out += e.stderr.decode('utf-8', 'replace')
  177. return out
  178. def RunGit(args, **kwargs):
  179. """Returns stdout."""
  180. return RunCommand(['git'] + args, **kwargs)
  181. def RunGitWithCode(args, suppress_stderr=False):
  182. """Returns return code and stdout."""
  183. if suppress_stderr:
  184. stderr = subprocess2.DEVNULL
  185. else:
  186. stderr = sys.stderr
  187. try:
  188. (out, _), code = subprocess2.communicate(['git'] + args,
  189. env=GetNoGitPagerEnv(),
  190. stdout=subprocess2.PIPE,
  191. stderr=stderr)
  192. return code, out.decode('utf-8', 'replace')
  193. except subprocess2.CalledProcessError as e:
  194. logging.debug('Failed running %s', ['git'] + args)
  195. return e.returncode, e.stdout.decode('utf-8', 'replace')
  196. def RunGitSilent(args):
  197. """Returns stdout, suppresses stderr and ignores the return code."""
  198. return RunGitWithCode(args, suppress_stderr=True)[1]
  199. def time_sleep(seconds):
  200. # Use this so that it can be mocked in tests without interfering with python
  201. # system machinery.
  202. return time.sleep(seconds)
  203. def time_time():
  204. # Use this so that it can be mocked in tests without interfering with python
  205. # system machinery.
  206. return time.time()
  207. def datetime_now():
  208. # Use this so that it can be mocked in tests without interfering with python
  209. # system machinery.
  210. return datetime.datetime.now()
  211. def confirm_or_exit(prefix='', action='confirm'):
  212. """Asks user to press enter to continue or press Ctrl+C to abort."""
  213. if not prefix or prefix.endswith('\n'):
  214. mid = 'Press'
  215. elif prefix.endswith('.') or prefix.endswith('?'):
  216. mid = ' Press'
  217. elif prefix.endswith(' '):
  218. mid = 'press'
  219. else:
  220. mid = ' press'
  221. gclient_utils.AskForData('%s%s Enter to %s, or Ctrl+C to abort' %
  222. (prefix, mid, action))
  223. def ask_for_explicit_yes(prompt):
  224. """Returns whether user typed 'y' or 'yes' to confirm the given prompt."""
  225. result = gclient_utils.AskForData(prompt + ' [Yes/No]: ').lower()
  226. while True:
  227. if 'yes'.startswith(result):
  228. return True
  229. if 'no'.startswith(result):
  230. return False
  231. result = gclient_utils.AskForData('Please, type yes or no: ').lower()
  232. def _get_properties_from_options(options):
  233. prop_list = getattr(options, 'properties', [])
  234. properties = dict(x.split('=', 1) for x in prop_list)
  235. for key, val in properties.items():
  236. try:
  237. properties[key] = json.loads(val)
  238. except ValueError:
  239. pass # If a value couldn't be evaluated, treat it as a string.
  240. return properties
  241. def _call_buildbucket(http, buildbucket_host, method, request):
  242. """Calls a buildbucket v2 method and returns the parsed json response."""
  243. headers = {
  244. 'Accept': 'application/json',
  245. 'Content-Type': 'application/json',
  246. }
  247. request = json.dumps(request)
  248. url = 'https://%s/prpc/buildbucket.v2.Builds/%s' % (buildbucket_host,
  249. method)
  250. logging.info('POST %s with %s' % (url, request))
  251. attempts = 1
  252. time_to_sleep = 1
  253. while True:
  254. response, content = http.request(url,
  255. 'POST',
  256. body=request,
  257. headers=headers)
  258. if response.status == 200:
  259. return json.loads(content[4:])
  260. if attempts >= MAX_ATTEMPTS or 400 <= response.status < 500:
  261. msg = '%s error when calling POST %s with %s: %s' % (
  262. response.status, url, request, content)
  263. raise BuildbucketResponseException(msg)
  264. logging.debug('%s error when calling POST %s with %s. '
  265. 'Sleeping for %d seconds and retrying...' %
  266. (response.status, url, request, time_to_sleep))
  267. time.sleep(time_to_sleep)
  268. time_to_sleep *= 2
  269. attempts += 1
  270. assert False, 'unreachable'
  271. def _parse_bucket(raw_bucket):
  272. legacy = True
  273. project = bucket = None
  274. if '/' in raw_bucket:
  275. legacy = False
  276. project, bucket = raw_bucket.split('/', 1)
  277. # Assume luci.<project>.<bucket>.
  278. elif raw_bucket.startswith('luci.'):
  279. project, bucket = raw_bucket[len('luci.'):].split('.', 1)
  280. # Otherwise, assume prefix is also the project name.
  281. elif '.' in raw_bucket:
  282. project = raw_bucket.split('.')[0]
  283. bucket = raw_bucket
  284. # Legacy buckets.
  285. if legacy and project and bucket:
  286. print('WARNING Please use %s/%s to specify the bucket.' %
  287. (project, bucket))
  288. return project, bucket
  289. def _canonical_git_googlesource_host(host):
  290. """Normalizes Gerrit hosts (with '-review') to Git host."""
  291. assert host.endswith(_GOOGLESOURCE)
  292. # Prefix doesn't include '.' at the end.
  293. prefix = host[:-(1 + len(_GOOGLESOURCE))]
  294. if prefix.endswith('-review'):
  295. prefix = prefix[:-len('-review')]
  296. return prefix + '.' + _GOOGLESOURCE
  297. def _canonical_gerrit_googlesource_host(host):
  298. git_host = _canonical_git_googlesource_host(host)
  299. prefix = git_host.split('.', 1)[0]
  300. return prefix + '-review.' + _GOOGLESOURCE
  301. def _get_counterpart_host(host):
  302. assert host.endswith(_GOOGLESOURCE)
  303. git = _canonical_git_googlesource_host(host)
  304. gerrit = _canonical_gerrit_googlesource_host(git)
  305. return git if gerrit == host else gerrit
  306. def _trigger_tryjobs(changelist, jobs, options, patchset):
  307. """Sends a request to Buildbucket to trigger tryjobs for a changelist.
  308. Args:
  309. changelist: Changelist that the tryjobs are associated with.
  310. jobs: A list of (project, bucket, builder).
  311. options: Command-line options.
  312. """
  313. print('Scheduling jobs on:')
  314. for project, bucket, builder in jobs:
  315. print(' %s/%s: %s' % (project, bucket, builder))
  316. print('To see results here, run: git cl try-results')
  317. print('To see results in browser, run: git cl web')
  318. requests = _make_tryjob_schedule_requests(changelist, jobs, options,
  319. patchset)
  320. if not requests:
  321. return
  322. http = auth.Authenticator().authorize(httplib2.Http())
  323. http.force_exception_to_status_code = True
  324. batch_request = {'requests': requests}
  325. batch_response = _call_buildbucket(http, DEFAULT_BUILDBUCKET_HOST, 'Batch',
  326. batch_request)
  327. errors = [
  328. ' ' + response['error']['message']
  329. for response in batch_response.get('responses', [])
  330. if 'error' in response
  331. ]
  332. if errors:
  333. raise BuildbucketResponseException(
  334. 'Failed to schedule builds for some bots:\n%s' % '\n'.join(errors))
  335. def _make_tryjob_schedule_requests(changelist, jobs, options, patchset):
  336. """Constructs requests for Buildbucket to trigger tryjobs."""
  337. gerrit_changes = [changelist.GetGerritChange(patchset)]
  338. shared_properties = {
  339. 'category': options.ensure_value('category', 'git_cl_try')
  340. }
  341. shared_properties.update(_get_properties_from_options(options) or {})
  342. shared_tags = [{'key': 'user_agent', 'value': 'git_cl_try'}]
  343. if options.ensure_value('retry_failed', False):
  344. shared_tags.append({'key': 'retry_failed', 'value': '1'})
  345. requests = []
  346. for (project, bucket, builder) in jobs:
  347. properties = shared_properties.copy()
  348. if 'presubmit' in builder.lower():
  349. properties['dry_run'] = 'true'
  350. requests.append({
  351. 'scheduleBuild': {
  352. 'requestId': str(uuid.uuid4()),
  353. 'builder': {
  354. 'project': getattr(options, 'project', None) or project,
  355. 'bucket': bucket,
  356. 'builder': builder,
  357. },
  358. 'gerritChanges': gerrit_changes,
  359. 'properties': properties,
  360. 'tags': [
  361. {
  362. 'key': 'builder',
  363. 'value': builder
  364. },
  365. ] + shared_tags,
  366. }
  367. })
  368. if options.ensure_value('revision', None):
  369. remote, remote_branch = changelist.GetRemoteBranch()
  370. requests[-1]['scheduleBuild']['gitilesCommit'] = {
  371. 'host':
  372. _canonical_git_googlesource_host(gerrit_changes[0]['host']),
  373. 'project': gerrit_changes[0]['project'],
  374. 'id': options.revision,
  375. 'ref': GetTargetRef(remote, remote_branch, None)
  376. }
  377. return requests
  378. def _fetch_tryjobs(changelist, buildbucket_host, patchset=None):
  379. """Fetches tryjobs from buildbucket.
  380. Returns list of buildbucket.v2.Build with the try jobs for the changelist.
  381. """
  382. fields = ['id', 'builder', 'status', 'createTime', 'tags']
  383. request = {
  384. 'predicate': {
  385. 'gerritChanges': [changelist.GetGerritChange(patchset)],
  386. },
  387. 'fields': ','.join('builds.*.' + field for field in fields),
  388. }
  389. authenticator = auth.Authenticator()
  390. if authenticator.has_cached_credentials():
  391. http = authenticator.authorize(httplib2.Http())
  392. else:
  393. print('Warning: Some results might be missing because %s' %
  394. # Get the message on how to login.
  395. (
  396. str(auth.LoginRequiredError()), ))
  397. http = httplib2.Http()
  398. http.force_exception_to_status_code = True
  399. response = _call_buildbucket(http, buildbucket_host, 'SearchBuilds',
  400. request)
  401. return response.get('builds', [])
  402. def _fetch_latest_builds(changelist, buildbucket_host, latest_patchset=None):
  403. """Fetches builds from the latest patchset that has builds (within
  404. the last few patchsets).
  405. Args:
  406. changelist (Changelist): The CL to fetch builds for
  407. buildbucket_host (str): Buildbucket host, e.g. "cr-buildbucket.appspot.com"
  408. lastest_patchset(int|NoneType): the patchset to start fetching builds from.
  409. If None (default), starts with the latest available patchset.
  410. Returns:
  411. A tuple (builds, patchset) where builds is a list of buildbucket.v2.Build,
  412. and patchset is the patchset number where those builds came from.
  413. """
  414. assert buildbucket_host
  415. assert changelist.GetIssue(), 'CL must be uploaded first'
  416. assert changelist.GetCodereviewServer(), 'CL must be uploaded first'
  417. if latest_patchset is None:
  418. assert changelist.GetMostRecentPatchset()
  419. ps = changelist.GetMostRecentPatchset()
  420. else:
  421. assert latest_patchset > 0, latest_patchset
  422. ps = latest_patchset
  423. min_ps = max(1, ps - 5)
  424. while ps >= min_ps:
  425. builds = _fetch_tryjobs(changelist, buildbucket_host, patchset=ps)
  426. if len(builds):
  427. return builds, ps
  428. ps -= 1
  429. return [], 0
  430. def _filter_failed_for_retry(all_builds):
  431. """Returns a list of buckets/builders that are worth retrying.
  432. Args:
  433. all_builds (list): Builds, in the format returned by _fetch_tryjobs,
  434. i.e. a list of buildbucket.v2.Builds which includes status and builder
  435. info.
  436. Returns:
  437. A dict {(proj, bucket): [builders]}. This is the same format accepted by
  438. _trigger_tryjobs.
  439. """
  440. grouped = {}
  441. for build in all_builds:
  442. builder = build['builder']
  443. key = (builder['project'], builder['bucket'], builder['builder'])
  444. grouped.setdefault(key, []).append(build)
  445. jobs = []
  446. for (project, bucket, builder), builds in grouped.items():
  447. if 'triggered' in builder:
  448. print(
  449. 'WARNING: Not scheduling %s. Triggered bots require an initial job '
  450. 'from a parent. Please schedule a manual job for the parent '
  451. 'instead.')
  452. continue
  453. if any(b['status'] in ('STARTED', 'SCHEDULED') for b in builds):
  454. # Don't retry if any are running.
  455. continue
  456. # If builder had several builds, retry only if the last one failed.
  457. # This is a bit different from CQ, which would re-use *any* SUCCESS-full
  458. # build, but in case of retrying failed jobs retrying a flaky one makes
  459. # sense.
  460. builds = sorted(builds, key=lambda b: b['createTime'])
  461. if builds[-1]['status'] not in ('FAILURE', 'INFRA_FAILURE'):
  462. continue
  463. # Don't retry experimental build previously triggered by CQ.
  464. if any(t['key'] == 'cq_experimental' and t['value'] == 'true'
  465. for t in builds[-1]['tags']):
  466. continue
  467. jobs.append((project, bucket, builder))
  468. # Sort the jobs to make testing easier.
  469. return sorted(jobs)
  470. def _print_tryjobs(options, builds):
  471. """Prints nicely result of _fetch_tryjobs."""
  472. if not builds:
  473. print('No tryjobs scheduled.')
  474. return
  475. longest_builder = max(len(b['builder']['builder']) for b in builds)
  476. name_fmt = '{builder:<%d}' % longest_builder
  477. if options.print_master:
  478. longest_bucket = max(len(b['builder']['bucket']) for b in builds)
  479. name_fmt = ('{bucket:>%d} ' % longest_bucket) + name_fmt
  480. builds_by_status = {}
  481. for b in builds:
  482. builds_by_status.setdefault(b['status'], []).append({
  483. 'id':
  484. b['id'],
  485. 'name':
  486. name_fmt.format(builder=b['builder']['builder'],
  487. bucket=b['builder']['bucket']),
  488. })
  489. sort_key = lambda b: (b['name'], b['id'])
  490. def print_builds(title, builds, fmt=None, color=None):
  491. """Pop matching builds from `builds` dict and print them."""
  492. if not builds:
  493. return
  494. fmt = fmt or '{name} https://ci.chromium.org/b/{id}'
  495. if not options.color or color is None:
  496. colorize = lambda x: x
  497. else:
  498. colorize = lambda x: '%s%s%s' % (color, x, Fore.RESET)
  499. print(colorize(title))
  500. for b in sorted(builds, key=sort_key):
  501. print(' ', colorize(fmt.format(**b)))
  502. total = len(builds)
  503. print_builds('Successes:',
  504. builds_by_status.pop('SUCCESS', []),
  505. color=Fore.GREEN)
  506. print_builds('Infra Failures:',
  507. builds_by_status.pop('INFRA_FAILURE', []),
  508. color=Fore.MAGENTA)
  509. print_builds('Failures:',
  510. builds_by_status.pop('FAILURE', []),
  511. color=Fore.RED)
  512. print_builds('Canceled:',
  513. builds_by_status.pop('CANCELED', []),
  514. fmt='{name}',
  515. color=Fore.MAGENTA)
  516. print_builds('Started:',
  517. builds_by_status.pop('STARTED', []),
  518. color=Fore.YELLOW)
  519. print_builds('Scheduled:',
  520. builds_by_status.pop('SCHEDULED', []),
  521. fmt='{name} id={id}')
  522. # The last section is just in case buildbucket API changes OR there is a
  523. # bug.
  524. print_builds('Other:',
  525. sum(builds_by_status.values(), []),
  526. fmt='{name} id={id}')
  527. print('Total: %d tryjobs' % total)
  528. def _ComputeFormatDiffLineRanges(files, upstream_commit, expand=0):
  529. """Gets the changed line ranges for each file since upstream_commit.
  530. Parses a git diff on provided files and returns a dict that maps a file name
  531. to an ordered list of range tuples in the form (start_line, count).
  532. Ranges are in the same format as a git diff.
  533. Args:
  534. files: List of paths to diff.
  535. upstream_commit: Commit to diff against to find changed lines.
  536. expand: Expand diff ranges by this many lines before & after.
  537. Returns:
  538. A dict of path->[(start_line, end_line), ...]
  539. """
  540. # If files is empty then diff_output will be a full diff.
  541. if len(files) == 0:
  542. return {}
  543. # Take the git diff and find the line ranges where there are changes.
  544. diff_output = RunGitDiffCmd(['-U0'],
  545. upstream_commit,
  546. files,
  547. allow_prefix=True)
  548. pattern = r'(?:^diff --git a/(?:.*) b/(.*))|(?:^@@.*\+(.*) @@)'
  549. # 2 capture groups
  550. # 0 == fname of diff file
  551. # 1 == 'diff_start,diff_count' or 'diff_start'
  552. # will match each of
  553. # diff --git a/foo.foo b/foo.py
  554. # @@ -12,2 +14,3 @@
  555. # @@ -12,2 +17 @@
  556. # running re.findall on the above string with pattern will give
  557. # [('foo.py', ''), ('', '14,3'), ('', '17')]
  558. curr_file = None
  559. line_diffs = {}
  560. for match in re.findall(pattern, diff_output, flags=re.MULTILINE):
  561. if match[0] != '':
  562. # Will match the second filename in diff --git a/a.py b/b.py.
  563. curr_file = match[0]
  564. line_diffs[curr_file] = []
  565. prev_end = 1
  566. else:
  567. # Matches +14,3
  568. if ',' in match[1]:
  569. diff_start, diff_count = match[1].split(',')
  570. else:
  571. # Single line changes are of the form +12 instead of +12,1.
  572. diff_start = match[1]
  573. diff_count = 1
  574. diff_start = int(diff_start)
  575. diff_count = int(diff_count)
  576. diff_end = diff_start + diff_count + expand
  577. diff_start = max(prev_end + 1, diff_start - expand)
  578. if diff_start <= diff_end:
  579. prev_end = diff_end
  580. line_diffs[curr_file].append((diff_start, diff_end))
  581. return line_diffs
  582. def _FindYapfConfigFile(fpath, yapf_config_cache, top_dir=None):
  583. """Checks if a yapf file is in any parent directory of fpath until top_dir.
  584. Recursively checks parent directories to find yapf file and if no yapf file
  585. is found returns None. Uses yapf_config_cache as a cache for previously found
  586. configs.
  587. """
  588. fpath = os.path.abspath(fpath)
  589. # Return result if we've already computed it.
  590. if fpath in yapf_config_cache:
  591. return yapf_config_cache[fpath]
  592. parent_dir = os.path.dirname(fpath)
  593. if os.path.isfile(fpath):
  594. ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir)
  595. else:
  596. # Otherwise fpath is a directory
  597. yapf_file = os.path.join(fpath, YAPF_CONFIG_FILENAME)
  598. if os.path.isfile(yapf_file):
  599. ret = yapf_file
  600. elif fpath in (top_dir, parent_dir):
  601. # If we're at the top level directory, or if we're at root
  602. # there is no provided style.
  603. ret = None
  604. else:
  605. # Otherwise recurse on the current directory.
  606. ret = _FindYapfConfigFile(parent_dir, yapf_config_cache, top_dir)
  607. yapf_config_cache[fpath] = ret
  608. return ret
  609. def _GetYapfIgnorePatterns(top_dir):
  610. """Returns all patterns in the .yapfignore file.
  611. yapf is supposed to handle the ignoring of files listed in .yapfignore itself,
  612. but this functionality appears to break when explicitly passing files to
  613. yapf for formatting. According to
  614. https://github.com/google/yapf/blob/HEAD/README.rst#excluding-files-from-formatting-yapfignore,
  615. the .yapfignore file should be in the directory that yapf is invoked from,
  616. which we assume to be the top level directory in this case.
  617. Args:
  618. top_dir: The top level directory for the repository being formatted.
  619. Returns:
  620. A set of all fnmatch patterns to be ignored.
  621. """
  622. yapfignore_file = os.path.join(top_dir, '.yapfignore')
  623. ignore_patterns = set()
  624. if not os.path.exists(yapfignore_file):
  625. return ignore_patterns
  626. for line in gclient_utils.FileRead(yapfignore_file).split('\n'):
  627. stripped_line = line.strip()
  628. # Comments and blank lines should be ignored.
  629. if stripped_line.startswith('#') or stripped_line == '':
  630. continue
  631. ignore_patterns.add(stripped_line)
  632. return ignore_patterns
  633. def _FilterYapfIgnoredFiles(filepaths, patterns):
  634. """Filters out any filepaths that match any of the given patterns.
  635. Args:
  636. filepaths: An iterable of strings containing filepaths to filter.
  637. patterns: An iterable of strings containing fnmatch patterns to filter on.
  638. Returns:
  639. A list of strings containing all the elements of |filepaths| that did not
  640. match any of the patterns in |patterns|.
  641. """
  642. # Not inlined so that tests can use the same implementation.
  643. return [
  644. f for f in filepaths
  645. if not any(fnmatch.fnmatch(f, p) for p in patterns)
  646. ]
  647. def _GetCommitCountSummary(begin_commit: str,
  648. end_commit: str = "HEAD") -> Optional[str]:
  649. """Generate a summary of the number of commits in (begin_commit, end_commit).
  650. Returns a string containing the summary, or None if the range is empty.
  651. """
  652. count = int(
  653. RunGitSilent(['rev-list', '--count', f'{begin_commit}..{end_commit}']))
  654. if not count:
  655. return None
  656. return f'{count} commit{"s"[:count!=1]}'
  657. def print_stats(args):
  658. """Prints statistics about the change to the user."""
  659. # --no-ext-diff is broken in some versions of Git, so try to work around
  660. # this by overriding the environment (but there is still a problem if the
  661. # git config key "diff.external" is used).
  662. env = GetNoGitPagerEnv()
  663. if 'GIT_EXTERNAL_DIFF' in env:
  664. del env['GIT_EXTERNAL_DIFF']
  665. return subprocess2.call(
  666. ['git', 'diff', '--no-ext-diff', '--stat', '-l100000', '-C50'] + args,
  667. env=env)
  668. class BuildbucketResponseException(Exception):
  669. pass
  670. class Settings(object):
  671. def __init__(self):
  672. self.cc = None
  673. self.root = None
  674. self.tree_status_url = None
  675. self.viewvc_url = None
  676. self.updated = False
  677. self.is_gerrit = None
  678. self.squash_gerrit_uploads = None
  679. self.gerrit_skip_ensure_authenticated = None
  680. self.git_editor = None
  681. self.format_full_by_default = None
  682. self.is_status_commit_order_by_date = None
  683. def _LazyUpdateIfNeeded(self):
  684. """Updates the settings from a codereview.settings file, if available."""
  685. if self.updated:
  686. return
  687. # The only value that actually changes the behavior is
  688. # autoupdate = "false". Everything else means "true".
  689. autoupdate = (scm.GIT.GetConfig(self.GetRoot(), 'rietveld.autoupdate',
  690. '').lower())
  691. cr_settings_file = FindCodereviewSettingsFile()
  692. if autoupdate != 'false' and cr_settings_file:
  693. LoadCodereviewSettingsFromFile(cr_settings_file)
  694. cr_settings_file.close()
  695. self.updated = True
  696. @staticmethod
  697. def GetRelativeRoot():
  698. return scm.GIT.GetCheckoutRoot('.')
  699. def GetRoot(self):
  700. if self.root is None:
  701. self.root = os.path.abspath(self.GetRelativeRoot())
  702. return self.root
  703. def GetTreeStatusUrl(self, error_ok=False):
  704. if not self.tree_status_url:
  705. self.tree_status_url = self._GetConfig('rietveld.tree-status-url')
  706. if self.tree_status_url is None and not error_ok:
  707. DieWithError(
  708. 'You must configure your tree status URL by running '
  709. '"git cl config".')
  710. return self.tree_status_url
  711. def GetViewVCUrl(self):
  712. if not self.viewvc_url:
  713. self.viewvc_url = self._GetConfig('rietveld.viewvc-url')
  714. return self.viewvc_url
  715. def GetBugPrefix(self):
  716. return self._GetConfig('rietveld.bug-prefix')
  717. def GetRunPostUploadHook(self):
  718. run_post_upload_hook = self._GetConfig('rietveld.run-post-upload-hook')
  719. return run_post_upload_hook == "True"
  720. def GetDefaultCCList(self):
  721. return self._GetConfig('rietveld.cc')
  722. def GetSquashGerritUploads(self):
  723. """Returns True if uploads to Gerrit should be squashed by default."""
  724. if self.squash_gerrit_uploads is None:
  725. self.squash_gerrit_uploads = self.GetSquashGerritUploadsOverride()
  726. if self.squash_gerrit_uploads is None:
  727. # Default is squash now (http://crbug.com/611892#c23).
  728. self.squash_gerrit_uploads = self._GetConfig(
  729. 'gerrit.squash-uploads').lower() != 'false'
  730. return self.squash_gerrit_uploads
  731. def GetSquashGerritUploadsOverride(self):
  732. """Return True or False if codereview.settings should be overridden.
  733. Returns None if no override has been defined.
  734. """
  735. # See also http://crbug.com/611892#c23
  736. result = self._GetConfig('gerrit.override-squash-uploads').lower()
  737. if result == 'true':
  738. return True
  739. if result == 'false':
  740. return False
  741. return None
  742. def GetIsGerrit(self):
  743. """Return True if gerrit.host is set."""
  744. if self.is_gerrit is None:
  745. self.is_gerrit = bool(self._GetConfig('gerrit.host', False))
  746. return self.is_gerrit
  747. def GetGerritSkipEnsureAuthenticated(self):
  748. """Return True if EnsureAuthenticated should not be done for Gerrit
  749. uploads."""
  750. if self.gerrit_skip_ensure_authenticated is None:
  751. self.gerrit_skip_ensure_authenticated = self._GetConfig(
  752. 'gerrit.skip-ensure-authenticated').lower() == 'true'
  753. return self.gerrit_skip_ensure_authenticated
  754. def GetGitEditor(self):
  755. """Returns the editor specified in the git config, or None if none is."""
  756. if self.git_editor is None:
  757. # Git requires single quotes for paths with spaces. We need to
  758. # replace them with double quotes for Windows to treat such paths as
  759. # a single path.
  760. self.git_editor = self._GetConfig('core.editor').replace('\'', '"')
  761. return self.git_editor or None
  762. def GetLintRegex(self):
  763. return self._GetConfig('rietveld.cpplint-regex', DEFAULT_LINT_REGEX)
  764. def GetLintIgnoreRegex(self):
  765. return self._GetConfig('rietveld.cpplint-ignore-regex',
  766. DEFAULT_LINT_IGNORE_REGEX)
  767. def GetFormatFullByDefault(self):
  768. if self.format_full_by_default is None:
  769. self.format_full_by_default = self._GetConfigBool(
  770. 'rietveld.format-full-by-default')
  771. return self.format_full_by_default
  772. def IsStatusCommitOrderByDate(self):
  773. if self.is_status_commit_order_by_date is None:
  774. self.is_status_commit_order_by_date = self._GetConfigBool(
  775. 'cl.date-order')
  776. return self.is_status_commit_order_by_date
  777. def _GetConfig(self, key, default=''):
  778. self._LazyUpdateIfNeeded()
  779. return scm.GIT.GetConfig(self.GetRoot(), key, default)
  780. def _GetConfigBool(self, key) -> bool:
  781. self._LazyUpdateIfNeeded()
  782. return scm.GIT.GetConfigBool(self.GetRoot(), key)
  783. settings = Settings()
  784. class _CQState(object):
  785. """Enum for states of CL with respect to CQ."""
  786. NONE = 'none'
  787. DRY_RUN = 'dry_run'
  788. COMMIT = 'commit'
  789. ALL_STATES = [NONE, DRY_RUN, COMMIT]
  790. class _ParsedIssueNumberArgument(object):
  791. def __init__(self, issue=None, patchset=None, hostname=None):
  792. self.issue = issue
  793. self.patchset = patchset
  794. self.hostname = hostname
  795. @property
  796. def valid(self):
  797. return self.issue is not None
  798. def ParseIssueNumberArgument(arg):
  799. """Parses the issue argument and returns _ParsedIssueNumberArgument."""
  800. fail_result = _ParsedIssueNumberArgument()
  801. if isinstance(arg, int):
  802. return _ParsedIssueNumberArgument(issue=arg)
  803. if not isinstance(arg, str):
  804. return fail_result
  805. if arg.isdigit():
  806. return _ParsedIssueNumberArgument(issue=int(arg))
  807. url = gclient_utils.UpgradeToHttps(arg)
  808. if not url.startswith('http'):
  809. return fail_result
  810. for gerrit_url, short_url in _KNOWN_GERRIT_TO_SHORT_URLS.items():
  811. if url.startswith(short_url):
  812. url = gerrit_url + url[len(short_url):]
  813. break
  814. try:
  815. parsed_url = urllib.parse.urlparse(url)
  816. except ValueError:
  817. return fail_result
  818. # If "https://" was automatically added, fail if `arg` looks unlikely to be
  819. # a URL.
  820. if not arg.startswith('http') and '.' not in parsed_url.netloc:
  821. return fail_result
  822. # Gerrit's new UI is https://domain/c/project/+/<issue_number>[/[patchset]]
  823. # But old GWT UI is https://domain/#/c/project/+/<issue_number>[/[patchset]]
  824. # Short urls like https://domain/<issue_number> can be used, but don't allow
  825. # specifying the patchset (you'd 404), but we allow that here.
  826. if parsed_url.path == '/':
  827. part = parsed_url.fragment
  828. else:
  829. part = parsed_url.path
  830. match = re.match(r'(/c(/.*/\+)?)?/(?P<issue>\d+)(/(?P<patchset>\d+)?/?)?$',
  831. part)
  832. if not match:
  833. return fail_result
  834. issue = int(match.group('issue'))
  835. patchset = match.group('patchset')
  836. return _ParsedIssueNumberArgument(
  837. issue=issue,
  838. patchset=int(patchset) if patchset else None,
  839. hostname=parsed_url.netloc)
  840. def _create_description_from_log(args):
  841. """Pulls out the commit log to use as a base for the CL description."""
  842. log_args = []
  843. if len(args) == 1 and args[0] == None:
  844. # Handle the case where None is passed as the branch.
  845. return ''
  846. if len(args) == 1 and not args[0].endswith('.'):
  847. log_args = [args[0] + '..']
  848. elif len(args) == 1 and args[0].endswith('...'):
  849. log_args = [args[0][:-1]]
  850. elif len(args) == 2:
  851. log_args = [args[0] + '..' + args[1]]
  852. else:
  853. log_args = args[:] # Hope for the best!
  854. return RunGit(['log', '--pretty=format:%B%n'] + log_args)
  855. class GerritChangeNotExists(Exception):
  856. def __init__(self, issue, url):
  857. self.issue = issue
  858. self.url = url
  859. super(GerritChangeNotExists, self).__init__()
  860. def __str__(self):
  861. return 'change %s at %s does not exist or you have no access to it' % (
  862. self.issue, self.url)
  863. _CommentSummary = collections.namedtuple(
  864. '_CommentSummary',
  865. [
  866. 'date',
  867. 'message',
  868. 'sender',
  869. 'autogenerated',
  870. # TODO(tandrii): these two aren't known in Gerrit.
  871. 'approval',
  872. 'disapproval'
  873. ])
  874. # TODO(b/265929888): Change `parent` to `pushed_commit_base`.
  875. _NewUpload = collections.namedtuple('NewUpload', [
  876. 'reviewers', 'ccs', 'commit_to_push', 'new_last_uploaded_commit', 'parent',
  877. 'change_desc', 'prev_patchset'
  878. ])
  879. class ChangeDescription(object):
  880. """Contains a parsed form of the change description."""
  881. R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$'
  882. CC_LINE = r'^[ \t]*(CC)[ \t]*=[ \t]*(.*?)[ \t]*$'
  883. BUG_LINE = r'^[ \t]*(?:(BUG)[ \t]*=|Bug:)[ \t]*(.*?)[ \t]*$'
  884. FIXED_LINE = r'^[ \t]*Fixed[ \t]*:[ \t]*(.*?)[ \t]*$'
  885. CHERRY_PICK_LINE = r'^\(cherry picked from commit [a-fA-F0-9]{40}\)$'
  886. STRIP_HASH_TAG_PREFIX = r'^(\s*(revert|reland)( "|:)?\s*)*'
  887. BRACKET_HASH_TAG = r'\s*\[([^\[\]]+)\]'
  888. COLON_SEPARATED_HASH_TAG = r'^([a-zA-Z0-9_\- ]+):($|[^:])'
  889. BAD_HASH_TAG_CHUNK = r'[^a-zA-Z0-9]+'
  890. def __init__(self, description, bug=None, fixed=None):
  891. self._description_lines = (description or '').strip().splitlines()
  892. if bug:
  893. regexp = re.compile(self.BUG_LINE)
  894. prefix = settings.GetBugPrefix()
  895. if not any(
  896. (regexp.match(line) for line in self._description_lines)):
  897. values = list(_get_bug_line_values(prefix, bug))
  898. self.append_footer('Bug: %s' % ', '.join(values))
  899. if fixed:
  900. regexp = re.compile(self.FIXED_LINE)
  901. prefix = settings.GetBugPrefix()
  902. if not any(
  903. (regexp.match(line) for line in self._description_lines)):
  904. values = list(_get_bug_line_values(prefix, fixed))
  905. self.append_footer('Fixed: %s' % ', '.join(values))
  906. @property # www.logilab.org/ticket/89786
  907. def description(self): # pylint: disable=method-hidden
  908. return '\n'.join(self._description_lines)
  909. def set_description(self, desc):
  910. if isinstance(desc, str):
  911. lines = desc.splitlines()
  912. else:
  913. lines = [line.rstrip() for line in desc]
  914. while lines and not lines[0]:
  915. lines.pop(0)
  916. while lines and not lines[-1]:
  917. lines.pop(-1)
  918. self._description_lines = lines
  919. def ensure_change_id(self, change_id):
  920. description = self.description
  921. footer_change_ids = git_footers.get_footer_change_id(description)
  922. # Make sure that the Change-Id in the description matches the given one.
  923. if footer_change_ids != [change_id]:
  924. if footer_change_ids:
  925. # Remove any existing Change-Id footers since they don't match
  926. # the expected change_id footer.
  927. description = git_footers.remove_footer(description,
  928. 'Change-Id')
  929. print(
  930. 'WARNING: Change-Id has been set to %s. Use `git cl issue 0` '
  931. 'if you want to set a new one.')
  932. # Add the expected Change-Id footer.
  933. description = git_footers.add_footer_change_id(
  934. description, change_id)
  935. self.set_description(description)
  936. def update_reviewers(self, reviewers):
  937. """Rewrites the R= line(s) as a single line each.
  938. Args:
  939. reviewers (list(str)) - list of additional emails to use for reviewers.
  940. """
  941. if not reviewers:
  942. return
  943. reviewers = set(reviewers)
  944. # Get the set of R= lines and remove them from the description.
  945. regexp = re.compile(self.R_LINE)
  946. matches = [regexp.match(line) for line in self._description_lines]
  947. new_desc = [
  948. l for i, l in enumerate(self._description_lines) if not matches[i]
  949. ]
  950. self.set_description(new_desc)
  951. # Construct new unified R= lines.
  952. # First, update reviewers with names from the R= lines (if any).
  953. for match in matches:
  954. if not match:
  955. continue
  956. reviewers.update(cleanup_list([match.group(2).strip()]))
  957. new_r_line = 'R=' + ', '.join(sorted(reviewers))
  958. # Put the new lines in the description where the old first R= line was.
  959. line_loc = next((i for i, match in enumerate(matches) if match), -1)
  960. if 0 <= line_loc < len(self._description_lines):
  961. self._description_lines.insert(line_loc, new_r_line)
  962. else:
  963. self.append_footer(new_r_line)
  964. def set_preserve_tryjobs(self):
  965. """Ensures description footer contains 'Cq-Do-Not-Cancel-Tryjobs: true'."""
  966. footers = git_footers.parse_footers(self.description)
  967. for v in footers.get('Cq-Do-Not-Cancel-Tryjobs', []):
  968. if v.lower() == 'true':
  969. return
  970. self.append_footer('Cq-Do-Not-Cancel-Tryjobs: true')
  971. def prompt(self):
  972. """Asks the user to update the description."""
  973. self.set_description([
  974. '# Enter a description of the change.',
  975. '# This will be displayed on the codereview site.',
  976. '# The first line will also be used as the subject of the review.',
  977. '#--------------------This line is 72 characters long'
  978. '--------------------',
  979. ] + self._description_lines)
  980. bug_regexp = re.compile(self.BUG_LINE)
  981. fixed_regexp = re.compile(self.FIXED_LINE)
  982. prefix = settings.GetBugPrefix()
  983. has_issue = lambda l: bug_regexp.match(l) or fixed_regexp.match(l)
  984. if not any((has_issue(line) for line in self._description_lines)):
  985. self.append_footer('Bug: %s' % prefix)
  986. print('Waiting for editor...')
  987. content = gclient_utils.RunEditor(self.description,
  988. True,
  989. git_editor=settings.GetGitEditor())
  990. if not content:
  991. DieWithError('Running editor failed')
  992. lines = content.splitlines()
  993. # Strip off comments and default inserted "Bug:" line.
  994. clean_lines = [
  995. line.rstrip() for line in lines
  996. if not (line.startswith('#') or line.rstrip() == "Bug:"
  997. or line.rstrip() == "Bug: " + prefix)
  998. ]
  999. if not clean_lines:
  1000. DieWithError('No CL description, aborting')
  1001. self.set_description(clean_lines)
  1002. def append_footer(self, line):
  1003. """Adds a footer line to the description.
  1004. Differentiates legacy "KEY=xxx" footers (used to be called tags) and
  1005. Gerrit's footers in the form of "Footer-Key: footer any value" and ensures
  1006. that Gerrit footers are always at the end.
  1007. """
  1008. parsed_footer_line = git_footers.parse_footer(line)
  1009. if parsed_footer_line:
  1010. # Line is a gerrit footer in the form: Footer-Key: any value.
  1011. # Thus, must be appended observing Gerrit footer rules.
  1012. self.set_description(
  1013. git_footers.add_footer(self.description,
  1014. key=parsed_footer_line[0],
  1015. value=parsed_footer_line[1]))
  1016. return
  1017. if not self._description_lines:
  1018. self._description_lines.append(line)
  1019. return
  1020. top_lines, gerrit_footers, _ = git_footers.split_footers(
  1021. self.description)
  1022. if gerrit_footers:
  1023. # git_footers.split_footers ensures that there is an empty line
  1024. # before actual (gerrit) footers, if any. We have to keep it that
  1025. # way.
  1026. assert top_lines and top_lines[-1] == ''
  1027. top_lines, separator = top_lines[:-1], top_lines[-1:]
  1028. else:
  1029. separator = [
  1030. ] # No need for separator if there are no gerrit_footers.
  1031. prev_line = top_lines[-1] if top_lines else ''
  1032. if (not presubmit_support.Change.TAG_LINE_RE.match(prev_line)
  1033. or not presubmit_support.Change.TAG_LINE_RE.match(line)):
  1034. top_lines.append('')
  1035. top_lines.append(line)
  1036. self._description_lines = top_lines + separator + gerrit_footers
  1037. def get_reviewers(self, tbr_only=False):
  1038. """Retrieves the list of reviewers."""
  1039. matches = [
  1040. re.match(self.R_LINE, line) for line in self._description_lines
  1041. ]
  1042. reviewers = [
  1043. match.group(2).strip() for match in matches
  1044. if match and (not tbr_only or match.group(1).upper() == 'TBR')
  1045. ]
  1046. return cleanup_list(reviewers)
  1047. def get_cced(self):
  1048. """Retrieves the list of reviewers."""
  1049. matches = [
  1050. re.match(self.CC_LINE, line) for line in self._description_lines
  1051. ]
  1052. cced = [match.group(2).strip() for match in matches if match]
  1053. return cleanup_list(cced)
  1054. def get_hash_tags(self):
  1055. """Extracts and sanitizes a list of Gerrit hashtags."""
  1056. subject = (self._description_lines or ('', ))[0]
  1057. subject = re.sub(self.STRIP_HASH_TAG_PREFIX,
  1058. '',
  1059. subject,
  1060. flags=re.IGNORECASE)
  1061. tags = []
  1062. start = 0
  1063. bracket_exp = re.compile(self.BRACKET_HASH_TAG)
  1064. while True:
  1065. m = bracket_exp.match(subject, start)
  1066. if not m:
  1067. break
  1068. tags.append(self.sanitize_hash_tag(m.group(1)))
  1069. start = m.end()
  1070. if not tags:
  1071. # Try "Tag: " prefix.
  1072. m = re.match(self.COLON_SEPARATED_HASH_TAG, subject)
  1073. if m:
  1074. tags.append(self.sanitize_hash_tag(m.group(1)))
  1075. return tags
  1076. @classmethod
  1077. def sanitize_hash_tag(cls, tag):
  1078. """Returns a sanitized Gerrit hash tag.
  1079. A sanitized hashtag can be used as a git push refspec parameter value.
  1080. """
  1081. return re.sub(cls.BAD_HASH_TAG_CHUNK, '-', tag).strip('-').lower()
  1082. class Changelist(object):
  1083. """Changelist works with one changelist in local branch.
  1084. Notes:
  1085. * Not safe for concurrent multi-{thread,process} use.
  1086. * Caches values from current branch. Therefore, re-use after branch change
  1087. with great care.
  1088. """
  1089. def __init__(self,
  1090. branchref=None,
  1091. issue=None,
  1092. codereview_host=None,
  1093. commit_date=None):
  1094. """Create a new ChangeList instance.
  1095. **kwargs will be passed directly to Gerrit implementation.
  1096. """
  1097. self.branchref = branchref
  1098. if self.branchref:
  1099. assert (branchref.startswith(('refs/heads/', 'refs/branch-heads/'))
  1100. or branchref == 'refs/meta/config')
  1101. self.branch = scm.GIT.ShortBranchName(self.branchref)
  1102. else:
  1103. self.branch = None
  1104. self.commit_date = commit_date
  1105. self.upstream_branch = None
  1106. self.lookedup_issue = False
  1107. self.issue = issue or None
  1108. self.description = None
  1109. self.lookedup_patchset = False
  1110. self.patchset = None
  1111. self.cc = None
  1112. self.more_cc = []
  1113. self._remote = None
  1114. self._cached_remote_url = (False, None) # (is_cached, value)
  1115. # Lazily cached values.
  1116. self._gerrit_host = None # e.g. chromium-review.googlesource.com
  1117. self._gerrit_server = None # e.g. https://chromium-review.googlesource.com
  1118. self._owners_client = None
  1119. # Map from change number (issue) to its detail cache.
  1120. self._detail_cache = {}
  1121. if codereview_host is not None:
  1122. assert not codereview_host.startswith('https://'), codereview_host
  1123. self._gerrit_host = codereview_host
  1124. self._gerrit_server = 'https://%s' % codereview_host
  1125. @property
  1126. def owners_client(self):
  1127. if self._owners_client is None:
  1128. remote, remote_branch = self.GetRemoteBranch()
  1129. branch = GetTargetRef(remote, remote_branch, None)
  1130. self._owners_client = owners_client.GetCodeOwnersClient(
  1131. host=self.GetGerritHost(),
  1132. project=self.GetGerritProject(),
  1133. branch=branch)
  1134. return self._owners_client
  1135. def GetCCList(self):
  1136. """Returns the users cc'd on this CL.
  1137. The return value is a string suitable for passing to git cl with the --cc
  1138. flag.
  1139. """
  1140. if self.cc is None:
  1141. base_cc = settings.GetDefaultCCList()
  1142. more_cc = ','.join(self.more_cc)
  1143. self.cc = ','.join(filter(None, (base_cc, more_cc))) or ''
  1144. return self.cc
  1145. def ExtendCC(self, more_cc):
  1146. """Extends the list of users to cc on this CL based on the changed files."""
  1147. self.more_cc.extend(more_cc)
  1148. def GetCommitDate(self):
  1149. """Returns the commit date as provided in the constructor"""
  1150. return self.commit_date
  1151. def GetBranch(self):
  1152. """Returns the short branch name, e.g. 'main'."""
  1153. if not self.branch:
  1154. branchref = scm.GIT.GetBranchRef(settings.GetRoot())
  1155. if not branchref:
  1156. return None
  1157. self.branchref = branchref
  1158. self.branch = scm.GIT.ShortBranchName(self.branchref)
  1159. return self.branch
  1160. def GetBranchRef(self):
  1161. """Returns the full branch name, e.g. 'refs/heads/main'."""
  1162. self.GetBranch() # Poke the lazy loader.
  1163. return self.branchref
  1164. def _GitGetBranchConfigValue(self, key, default=None):
  1165. return scm.GIT.GetBranchConfig(settings.GetRoot(), self.GetBranch(),
  1166. key, default)
  1167. def _GitSetBranchConfigValue(self, key, value):
  1168. action = 'set %s to %r' % (key, value)
  1169. if not value:
  1170. action = 'unset %s' % key
  1171. assert self.GetBranch(), 'a branch is needed to ' + action
  1172. return scm.GIT.SetBranchConfig(settings.GetRoot(), self.GetBranch(),
  1173. key, value)
  1174. @staticmethod
  1175. def FetchUpstreamTuple(branch):
  1176. """Returns a tuple containing remote and remote ref,
  1177. e.g. 'origin', 'refs/heads/main'
  1178. """
  1179. remote, upstream_branch = scm.GIT.FetchUpstreamTuple(
  1180. settings.GetRoot(), branch)
  1181. if not remote or not upstream_branch:
  1182. DieWithError(
  1183. 'Unable to determine default branch to diff against.\n'
  1184. 'Verify this branch is set up to track another \n'
  1185. '(via the --track argument to "git checkout -b ..."). \n'
  1186. 'or pass complete "git diff"-style arguments if supported, like\n'
  1187. ' git cl upload origin/main\n')
  1188. return remote, upstream_branch
  1189. def GetCommonAncestorWithUpstream(self):
  1190. upstream_branch = self.GetUpstreamBranch()
  1191. if not scm.GIT.IsValidRevision(settings.GetRoot(), upstream_branch):
  1192. DieWithError(
  1193. 'The current branch (%s) has an upstream (%s) that does not exist '
  1194. 'anymore.\nPlease fix it and try again.' %
  1195. (self.GetBranch(), upstream_branch))
  1196. return git_common.get_or_create_merge_base(self.GetBranch(),
  1197. upstream_branch)
  1198. def GetUpstreamBranch(self):
  1199. if self.upstream_branch is None:
  1200. remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
  1201. if remote != '.':
  1202. upstream_branch = upstream_branch.replace(
  1203. 'refs/heads/', 'refs/remotes/%s/' % remote)
  1204. upstream_branch = upstream_branch.replace(
  1205. 'refs/branch-heads/', 'refs/remotes/branch-heads/')
  1206. self.upstream_branch = upstream_branch
  1207. return self.upstream_branch
  1208. def GetRemoteBranch(self):
  1209. if not self._remote:
  1210. remote, branch = None, self.GetBranch()
  1211. seen_branches = set()
  1212. while branch not in seen_branches:
  1213. seen_branches.add(branch)
  1214. remote, branch = self.FetchUpstreamTuple(branch)
  1215. branch = scm.GIT.ShortBranchName(branch)
  1216. if remote != '.' or branch.startswith('refs/remotes'):
  1217. break
  1218. else:
  1219. remotes = RunGit(['remote'], error_ok=True).split()
  1220. if len(remotes) == 1:
  1221. remote, = remotes
  1222. elif 'origin' in remotes:
  1223. remote = 'origin'
  1224. logging.warning(
  1225. 'Could not determine which remote this change is '
  1226. 'associated with, so defaulting to "%s".' %
  1227. self._remote)
  1228. else:
  1229. logging.warning(
  1230. 'Could not determine which remote this change is '
  1231. 'associated with.')
  1232. branch = 'HEAD'
  1233. if branch.startswith('refs/remotes'):
  1234. self._remote = (remote, branch)
  1235. elif branch.startswith('refs/branch-heads/'):
  1236. self._remote = (remote, branch.replace('refs/',
  1237. 'refs/remotes/'))
  1238. else:
  1239. self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch))
  1240. return self._remote
  1241. def GetRemoteUrl(self) -> Optional[str]:
  1242. """Return the configured remote URL, e.g. 'git://example.org/foo.git/'.
  1243. Returns None if there is no remote.
  1244. """
  1245. is_cached, value = self._cached_remote_url
  1246. if is_cached:
  1247. return value
  1248. remote, _ = self.GetRemoteBranch()
  1249. url = scm.GIT.GetConfig(settings.GetRoot(), 'remote.%s.url' % remote,
  1250. '')
  1251. # Check if the remote url can be parsed as an URL.
  1252. host = urllib.parse.urlparse(url).netloc
  1253. if host:
  1254. self._cached_remote_url = (True, url)
  1255. return url
  1256. # If it cannot be parsed as an url, assume it is a local directory,
  1257. # probably a git cache.
  1258. logging.warning(
  1259. '"%s" doesn\'t appear to point to a git host. '
  1260. 'Interpreting it as a local directory.', url)
  1261. if not os.path.isdir(url):
  1262. logging.error(
  1263. 'Remote "%(remote)s" for branch "%(branch)s" points to "%(url)s", '
  1264. 'but it doesn\'t exist.', {
  1265. 'remote': remote,
  1266. 'branch': self.GetBranch(),
  1267. 'url': url
  1268. })
  1269. return None
  1270. cache_path = url
  1271. url = scm.GIT.GetConfig(url, 'remote.%s.url' % remote, '')
  1272. host = urllib.parse.urlparse(url).netloc
  1273. if not host:
  1274. logging.error(
  1275. 'Remote "%(remote)s" for branch "%(branch)s" points to '
  1276. '"%(cache_path)s", but it is misconfigured.\n'
  1277. '"%(cache_path)s" must be a git repo and must have a remote named '
  1278. '"%(remote)s" pointing to the git host.', {
  1279. 'remote': remote,
  1280. 'cache_path': cache_path,
  1281. 'branch': self.GetBranch()
  1282. })
  1283. return None
  1284. self._cached_remote_url = (True, url)
  1285. return url
  1286. def _GetIssueFromTripletId(self):
  1287. project = self.GetGerritProject()
  1288. remote, branch = self.GetRemoteBranch()
  1289. remote_ref = GetTargetRef(remote, branch,
  1290. None).replace("refs/heads/", "")
  1291. # _create_description_from_log calls into `git log
  1292. # HEAD^..`. This will exclude everything reachable from `HEAD^`,
  1293. # leaving just `HEAD`.
  1294. change_ids = git_footers.get_footer_change_id(
  1295. _create_description_from_log(["HEAD^"]))
  1296. if len(change_ids) != 1:
  1297. return None
  1298. change_id = change_ids[0]
  1299. triplet_id = urllib.parse.quote("%s~%s~%s" %
  1300. (project, remote_ref, change_id),
  1301. safe='')
  1302. # GetGerritHost() would attempt to lookup the host from the
  1303. # issue first, leading to infinite recursion. Instead, use the
  1304. # fallback of getting the host from the remote URL.
  1305. gerrit_host = self._GetGerritHostFromRemoteUrl()
  1306. change = gerrit_util.GetChange(gerrit_host,
  1307. triplet_id,
  1308. accept_statuses=[200, 404])
  1309. return change.get('_number')
  1310. def GetIssue(self):
  1311. """Returns the issue number as a int or None if not set."""
  1312. if self.issue is None and not self.lookedup_issue:
  1313. if self.GetBranch():
  1314. self.issue = self._GitGetBranchConfigValue(ISSUE_CONFIG_KEY)
  1315. if not settings.GetSquashGerritUploads() and self.issue is None:
  1316. self.issue = self._GetIssueFromTripletId()
  1317. if self.issue is not None:
  1318. self.issue = int(self.issue)
  1319. self.lookedup_issue = True
  1320. return self.issue
  1321. def GetIssueURL(self, short=False):
  1322. """Get the URL for a particular issue."""
  1323. issue = self.GetIssue()
  1324. if not issue:
  1325. return None
  1326. server = self.GetCodereviewServer()
  1327. if short:
  1328. server = _KNOWN_GERRIT_TO_SHORT_URLS.get(server, server)
  1329. return '%s/%s' % (server, issue)
  1330. def FetchDescription(self, pretty=False):
  1331. assert self.GetIssue(), 'issue is required to query Gerrit'
  1332. if self.description is None:
  1333. data = self._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'])
  1334. current_rev = data['current_revision']
  1335. self.description = data['revisions'][current_rev]['commit'][
  1336. 'message']
  1337. if not pretty:
  1338. return self.description
  1339. # Set width to 72 columns + 2 space indent.
  1340. wrapper = textwrap.TextWrapper(width=74, replace_whitespace=True)
  1341. wrapper.initial_indent = wrapper.subsequent_indent = ' '
  1342. lines = self.description.splitlines()
  1343. return '\n'.join([wrapper.fill(line) for line in lines])
  1344. def GetPatchset(self):
  1345. """Returns the patchset number as a int or None if not set."""
  1346. if self.patchset is None and not self.lookedup_patchset:
  1347. if self.GetBranch():
  1348. self.patchset = self._GitGetBranchConfigValue(
  1349. PATCHSET_CONFIG_KEY)
  1350. if self.patchset is not None:
  1351. self.patchset = int(self.patchset)
  1352. self.lookedup_patchset = True
  1353. return self.patchset
  1354. def GetAuthor(self):
  1355. return scm.GIT.GetConfig(settings.GetRoot(), 'user.email')
  1356. def SetPatchset(self, patchset):
  1357. """Set this branch's patchset. If patchset=0, clears the patchset."""
  1358. assert self.GetBranch()
  1359. if not patchset:
  1360. self.patchset = None
  1361. else:
  1362. self.patchset = int(patchset)
  1363. self._GitSetBranchConfigValue(PATCHSET_CONFIG_KEY, str(self.patchset))
  1364. def SetIssue(self, issue=None):
  1365. """Set this branch's issue. If issue isn't given, clears the issue."""
  1366. assert self.GetBranch()
  1367. if issue:
  1368. issue = int(issue)
  1369. self._GitSetBranchConfigValue(ISSUE_CONFIG_KEY, str(issue))
  1370. self.issue = issue
  1371. codereview_server = self.GetCodereviewServer()
  1372. if codereview_server:
  1373. self._GitSetBranchConfigValue(CODEREVIEW_SERVER_CONFIG_KEY,
  1374. codereview_server)
  1375. else:
  1376. # Reset all of these just to be clean.
  1377. reset_suffixes = [
  1378. LAST_UPLOAD_HASH_CONFIG_KEY,
  1379. ISSUE_CONFIG_KEY,
  1380. PATCHSET_CONFIG_KEY,
  1381. CODEREVIEW_SERVER_CONFIG_KEY,
  1382. GERRIT_SQUASH_HASH_CONFIG_KEY,
  1383. ]
  1384. for prop in reset_suffixes:
  1385. try:
  1386. self._GitSetBranchConfigValue(prop, None)
  1387. except subprocess2.CalledProcessError:
  1388. pass
  1389. msg = RunGit(['log', '-1', '--format=%B']).strip()
  1390. if msg and git_footers.get_footer_change_id(msg):
  1391. print(
  1392. 'WARNING: The change patched into this branch has a Change-Id. '
  1393. 'Removing it.')
  1394. RunGit([
  1395. 'commit', '--amend', '-m',
  1396. git_footers.remove_footer(msg, 'Change-Id')
  1397. ])
  1398. self.lookedup_issue = True
  1399. self.issue = None
  1400. self.patchset = None
  1401. def GetAffectedFiles(self,
  1402. upstream: str,
  1403. end_commit: Optional[str] = None) -> Sequence[str]:
  1404. """Returns the list of affected files for the given commit range."""
  1405. try:
  1406. return [
  1407. f for _, f in scm.GIT.CaptureStatus(
  1408. settings.GetRoot(), upstream, end_commit=end_commit)
  1409. ]
  1410. except subprocess2.CalledProcessError:
  1411. DieWithError(
  1412. ('\nFailed to diff against upstream branch %s\n\n'
  1413. 'This branch probably doesn\'t exist anymore. To reset the\n'
  1414. 'tracking branch, please run\n'
  1415. ' git branch --set-upstream-to origin/main %s\n'
  1416. 'or replace origin/main with the relevant branch') %
  1417. (upstream, self.GetBranch()))
  1418. def UpdateDescription(self, description, force=False):
  1419. assert self.GetIssue(), 'issue is required to update description'
  1420. if gerrit_util.HasPendingChangeEdit(self.GetGerritHost(),
  1421. self._GerritChangeIdentifier()):
  1422. if not force:
  1423. confirm_or_exit(
  1424. 'The description cannot be modified while the issue has a pending '
  1425. 'unpublished edit. Either publish the edit in the Gerrit web UI '
  1426. 'or delete it.\n\n',
  1427. action='delete the unpublished edit')
  1428. gerrit_util.DeletePendingChangeEdit(self.GetGerritHost(),
  1429. self._GerritChangeIdentifier())
  1430. gerrit_util.SetCommitMessage(self.GetGerritHost(),
  1431. self._GerritChangeIdentifier(),
  1432. description,
  1433. notify='NONE')
  1434. self.description = description
  1435. def _GetCommonPresubmitArgs(self, verbose, upstream):
  1436. args = [
  1437. '--root',
  1438. settings.GetRoot(),
  1439. '--upstream',
  1440. upstream,
  1441. ]
  1442. args.extend(['--verbose'] * verbose)
  1443. remote, remote_branch = self.GetRemoteBranch()
  1444. target_ref = GetTargetRef(remote, remote_branch, None)
  1445. if settings.GetIsGerrit():
  1446. args.extend(['--gerrit_url', self.GetCodereviewServer()])
  1447. args.extend(['--gerrit_project', self.GetGerritProject()])
  1448. args.extend(['--gerrit_branch', target_ref])
  1449. author = self.GetAuthor()
  1450. issue = self.GetIssue()
  1451. patchset = self.GetPatchset()
  1452. if author:
  1453. args.extend(['--author', author])
  1454. if issue:
  1455. args.extend(['--issue', str(issue)])
  1456. if patchset:
  1457. args.extend(['--patchset', str(patchset)])
  1458. return args
  1459. def RunHook(self,
  1460. committing,
  1461. may_prompt,
  1462. verbose,
  1463. parallel,
  1464. upstream,
  1465. description,
  1466. all_files,
  1467. files=None,
  1468. resultdb=False,
  1469. realm=None):
  1470. """Calls sys.exit() if the hook fails; returns a HookResults otherwise."""
  1471. args = self._GetCommonPresubmitArgs(verbose, upstream)
  1472. args.append('--commit' if committing else '--upload')
  1473. if may_prompt:
  1474. args.append('--may_prompt')
  1475. if parallel:
  1476. args.append('--parallel')
  1477. if all_files:
  1478. args.append('--all_files')
  1479. if files:
  1480. args.extend(files.split(';'))
  1481. args.append('--source_controlled_only')
  1482. if files or all_files:
  1483. args.append('--no_diffs')
  1484. if resultdb and not realm:
  1485. # TODO (crbug.com/1113463): store realm somewhere and look it up so
  1486. # it is not required to pass the realm flag
  1487. print(
  1488. 'Note: ResultDB reporting will NOT be performed because --realm'
  1489. ' was not specified. To enable ResultDB, please run the command'
  1490. ' again with the --realm argument to specify the LUCI realm.')
  1491. return self._RunPresubmit(args,
  1492. description,
  1493. resultdb=resultdb,
  1494. realm=realm)
  1495. def _RunPresubmit(self,
  1496. args: Sequence[str],
  1497. description: str,
  1498. resultdb: bool = False,
  1499. realm: Optional[str] = None) -> Mapping[str, Any]:
  1500. args = list(args)
  1501. with gclient_utils.temporary_file() as description_file:
  1502. with gclient_utils.temporary_file() as json_output:
  1503. gclient_utils.FileWrite(description_file, description)
  1504. args.extend(['--json_output', json_output])
  1505. args.extend(['--description_file', description_file])
  1506. start = time_time()
  1507. cmd = ['vpython3', PRESUBMIT_SUPPORT] + args
  1508. if resultdb and realm:
  1509. cmd = ['rdb', 'stream', '-new', '-realm', realm, '--'] + cmd
  1510. p = subprocess2.Popen(cmd)
  1511. exit_code = p.wait()
  1512. metrics.collector.add_repeated(
  1513. 'sub_commands', {
  1514. 'command': 'presubmit',
  1515. 'execution_time': time_time() - start,
  1516. 'exit_code': exit_code,
  1517. })
  1518. if exit_code:
  1519. sys.exit(exit_code)
  1520. json_results = gclient_utils.FileRead(json_output)
  1521. return json.loads(json_results)
  1522. def RunPostUploadHook(self, verbose, upstream, description):
  1523. args = self._GetCommonPresubmitArgs(verbose, upstream)
  1524. args.append('--post_upload')
  1525. with gclient_utils.temporary_file() as description_file:
  1526. gclient_utils.FileWrite(description_file, description)
  1527. args.extend(['--description_file', description_file])
  1528. subprocess2.Popen(['vpython3', PRESUBMIT_SUPPORT] + args).wait()
  1529. def _GetDescriptionForUpload(self, options: optparse.Values,
  1530. git_diff_args: Sequence[str],
  1531. files: Sequence[str]) -> ChangeDescription:
  1532. """Get description message for upload."""
  1533. if options.commit_description:
  1534. description = options.commit_description
  1535. if description == '-':
  1536. description = '\n'.join(l.rstrip() for l in sys.stdin)
  1537. elif description == '+':
  1538. description = _create_description_from_log(git_diff_args)
  1539. elif self.GetIssue():
  1540. description = self.FetchDescription()
  1541. elif options.message:
  1542. description = options.message
  1543. else:
  1544. description = _create_description_from_log(git_diff_args)
  1545. if options.title and options.squash:
  1546. description = options.title + '\n\n' + description
  1547. bug = options.bug
  1548. fixed = options.fixed
  1549. if not self.GetIssue():
  1550. # Extract bug number from branch name, but only if issue is being
  1551. # created. It must start with bug or fix, followed by _ or - and
  1552. # number. Optionally, it may contain _ or - after number with
  1553. # arbitrary text. Examples: bug-123 bug_123 fix-123
  1554. # fix-123-some-description
  1555. branch = self.GetBranch()
  1556. if branch is not None:
  1557. match = re.match(
  1558. r'^(?P<type>bug|fix(?:e[sd])?)[_-]?(?P<bugnum>\d+)([-_]|$)',
  1559. branch)
  1560. if not bug and not fixed and match:
  1561. if match.group('type') == 'bug':
  1562. bug = match.group('bugnum')
  1563. else:
  1564. fixed = match.group('bugnum')
  1565. change_description = ChangeDescription(description, bug, fixed)
  1566. # Fill gaps in OWNERS coverage to reviewers if requested.
  1567. if options.add_owners_to:
  1568. assert options.add_owners_to in ('R'), options.add_owners_to
  1569. status = self.owners_client.GetFilesApprovalStatus(
  1570. files, [], options.reviewers)
  1571. missing_files = [
  1572. f for f in files
  1573. if status[f] == self._owners_client.INSUFFICIENT_REVIEWERS
  1574. ]
  1575. owners = self.owners_client.SuggestOwners(
  1576. missing_files, exclude=[self.GetAuthor()])
  1577. assert isinstance(options.reviewers, list), options.reviewers
  1578. options.reviewers.extend(owners)
  1579. # Set the reviewer list now so that presubmit checks can access it.
  1580. if options.reviewers:
  1581. change_description.update_reviewers(options.reviewers)
  1582. return change_description
  1583. def _GetTitleForUpload(self, options, multi_change_upload=False):
  1584. # type: (optparse.Values, Optional[bool]) -> str
  1585. # Getting titles for multipl commits is not supported so we return the
  1586. # default.
  1587. if not options.squash or multi_change_upload or options.title:
  1588. return options.title
  1589. # On first upload, patchset title is always this string, while
  1590. # options.title gets converted to first line of message.
  1591. if not self.GetIssue():
  1592. return 'Initial upload'
  1593. # When uploading subsequent patchsets, options.message is taken as the
  1594. # title if options.title is not provided.
  1595. if options.message:
  1596. return options.message.strip()
  1597. # Use the subject of the last commit as title by default.
  1598. title = RunGit(['show', '-s', '--format=%s', 'HEAD', '--']).strip()
  1599. if options.force or options.skip_title:
  1600. return title
  1601. user_title = gclient_utils.AskForData(
  1602. 'Title for patchset (\'y\' for default) [%s]: ' % title)
  1603. # Use the default title if the user confirms the default with a 'y'.
  1604. if user_title.lower() == 'y':
  1605. return title
  1606. return user_title or title
  1607. def _GetRefSpecOptions(self,
  1608. options: optparse.Values,
  1609. change_desc: ChangeDescription,
  1610. multi_change_upload: bool = False,
  1611. dogfood_path: bool = False) -> List[str]:
  1612. # Extra options that can be specified at push time. Doc:
  1613. # https://gerrit-review.googlesource.com/Documentation/user-upload.html
  1614. refspec_opts = []
  1615. # By default, new changes are started in WIP mode, and subsequent
  1616. # patchsets don't send email. At any time, passing --send-mail or
  1617. # --send-email will mark the change ready and send email for that
  1618. # particular patch.
  1619. if options.send_mail:
  1620. refspec_opts.append('ready')
  1621. refspec_opts.append('notify=ALL')
  1622. elif (not self.GetIssue() and options.squash and not dogfood_path):
  1623. refspec_opts.append('wip')
  1624. # TODO(tandrii): options.message should be posted as a comment if
  1625. # --send-mail or --send-email is set on non-initial upload as Rietveld
  1626. # used to do it.
  1627. # Set options.title in case user was prompted in _GetTitleForUpload and
  1628. # _CMDUploadChange needs to be called again.
  1629. options.title = self._GetTitleForUpload(
  1630. options, multi_change_upload=multi_change_upload)
  1631. if options.title:
  1632. # Punctuation and whitespace in |title| must be percent-encoded.
  1633. refspec_opts.append(
  1634. 'm=' + gerrit_util.PercentEncodeForGitRef(options.title))
  1635. if options.private:
  1636. refspec_opts.append('private')
  1637. if options.topic:
  1638. # Documentation on Gerrit topics is here:
  1639. # https://gerrit-review.googlesource.com/Documentation/user-upload.html#topic
  1640. refspec_opts.append('topic=%s' % options.topic)
  1641. if options.enable_auto_submit:
  1642. refspec_opts.append('l=Auto-Submit+1')
  1643. if options.set_bot_commit:
  1644. refspec_opts.append('l=Bot-Commit+1')
  1645. if options.use_commit_queue:
  1646. refspec_opts.append('l=Commit-Queue+2')
  1647. elif options.cq_dry_run:
  1648. refspec_opts.append('l=Commit-Queue+1')
  1649. if change_desc.get_reviewers(tbr_only=True):
  1650. score = gerrit_util.GetCodeReviewTbrScore(self.GetGerritHost(),
  1651. self.GetGerritProject())
  1652. refspec_opts.append('l=Code-Review+%s' % score)
  1653. # Gerrit sorts hashtags, so order is not important.
  1654. hashtags = {change_desc.sanitize_hash_tag(t) for t in options.hashtags}
  1655. # We check GetIssue because we only add hashtags from the
  1656. # description on the first upload.
  1657. # TODO(b/265929888): When we fully launch the new path:
  1658. # 1) remove fetching hashtags from description alltogether
  1659. # 2) Or use descrtiption hashtags for:
  1660. # `not (self.GetIssue() and multi_change_upload)`
  1661. # 3) Or enabled change description tags for multi and single changes
  1662. # by adding them post `git push`.
  1663. if not (self.GetIssue() and dogfood_path):
  1664. hashtags.update(change_desc.get_hash_tags())
  1665. refspec_opts.extend(['hashtag=%s' % t for t in hashtags])
  1666. # Note: Reviewers, and ccs are handled individually for each
  1667. # branch/change.
  1668. return refspec_opts
  1669. def PrepareSquashedCommit(self,
  1670. options: optparse.Values,
  1671. parent: str,
  1672. orig_parent: str,
  1673. end_commit: Optional[str] = None) -> _NewUpload:
  1674. """Create a squashed commit to upload.
  1675. Args:
  1676. parent: The commit to use as the parent for the new squashed.
  1677. orig_parent: The commit that is an actual ancestor of `end_commit`. It
  1678. is part of the same original tree as end_commit, which does not
  1679. contain squashed commits. This is used to create the change
  1680. description for the new squashed commit with:
  1681. `git log orig_parent..end_commit`.
  1682. end_commit: The commit to use as the end of the new squashed commit.
  1683. """
  1684. if end_commit is None:
  1685. end_commit = RunGit(['rev-parse', self.branchref]).strip()
  1686. reviewers, ccs, change_desc = self._PrepareChange(
  1687. options, orig_parent, end_commit)
  1688. latest_tree = RunGit(['rev-parse', end_commit + ':']).strip()
  1689. with gclient_utils.temporary_file() as desc_tempfile:
  1690. gclient_utils.FileWrite(desc_tempfile, change_desc.description)
  1691. commit_to_push = RunGit(
  1692. ['commit-tree', latest_tree, '-p', parent, '-F',
  1693. desc_tempfile]).strip()
  1694. # Gerrit may or may not update fast enough to return the correct
  1695. # patchset number after we push. Get the pre-upload patchset and
  1696. # increment later.
  1697. prev_patchset = self.GetMostRecentPatchset(update=False) or 0
  1698. return _NewUpload(reviewers, ccs, commit_to_push, end_commit, parent,
  1699. change_desc, prev_patchset)
  1700. def PrepareCherryPickSquashedCommit(self, options: optparse.Values,
  1701. parent: str) -> _NewUpload:
  1702. """Create a commit cherry-picked on parent to push."""
  1703. # The `parent` is what we will cherry-pick on top of.
  1704. # The `cherry_pick_base` is the beginning range of what
  1705. # we are cherry-picking.
  1706. cherry_pick_base = self.GetCommonAncestorWithUpstream()
  1707. reviewers, ccs, change_desc = self._PrepareChange(
  1708. options, cherry_pick_base, self.branchref)
  1709. new_upload_hash = RunGit(['rev-parse', self.branchref]).strip()
  1710. latest_tree = RunGit(['rev-parse', self.branchref + ':']).strip()
  1711. with gclient_utils.temporary_file() as desc_tempfile:
  1712. gclient_utils.FileWrite(desc_tempfile, change_desc.description)
  1713. commit_to_cp = RunGit([
  1714. 'commit-tree', latest_tree, '-p', cherry_pick_base, '-F',
  1715. desc_tempfile
  1716. ]).strip()
  1717. RunGit(['checkout', '-q', parent])
  1718. ret, _out = RunGitWithCode(['cherry-pick', commit_to_cp])
  1719. if ret:
  1720. RunGit(['cherry-pick', '--abort'])
  1721. RunGit(['checkout', '-q', self.branch])
  1722. DieWithError('Could not cleanly cherry-pick')
  1723. commit_to_push = RunGit(['rev-parse', 'HEAD']).strip()
  1724. RunGit(['checkout', '-q', self.branch])
  1725. # Gerrit may or may not update fast enough to return the correct
  1726. # patchset number after we push. Get the pre-upload patchset and
  1727. # increment later.
  1728. prev_patchset = self.GetMostRecentPatchset(update=False) or 0
  1729. return _NewUpload(reviewers, ccs, commit_to_push, new_upload_hash,
  1730. cherry_pick_base, change_desc, prev_patchset)
  1731. def _PrepareChange(
  1732. self, options: optparse.Values, parent: str, end_commit: str
  1733. ) -> Tuple[Sequence[str], Sequence[str], ChangeDescription]:
  1734. """Prepares the change to be uploaded."""
  1735. self.EnsureCanUploadPatchset(options.force)
  1736. files = self.GetAffectedFiles(parent, end_commit=end_commit)
  1737. change_desc = self._GetDescriptionForUpload(options,
  1738. [parent, end_commit], files)
  1739. watchlist = watchlists.Watchlists(settings.GetRoot())
  1740. self.ExtendCC(watchlist.GetWatchersForPaths(files))
  1741. if not options.bypass_hooks:
  1742. hook_results = self.RunHook(committing=False,
  1743. may_prompt=not options.force,
  1744. verbose=options.verbose,
  1745. parallel=options.parallel,
  1746. upstream=parent,
  1747. description=change_desc.description,
  1748. all_files=False)
  1749. self.ExtendCC(hook_results['more_cc'])
  1750. # Update the change description and ensure we have a Change Id.
  1751. if self.GetIssue():
  1752. if options.edit_description:
  1753. change_desc.prompt()
  1754. change_detail = self._GetChangeDetail(['CURRENT_REVISION'])
  1755. change_id = change_detail['change_id']
  1756. change_desc.ensure_change_id(change_id)
  1757. else: # No change issue. First time uploading
  1758. if not options.force and not (options.message_file
  1759. or options.commit_description):
  1760. change_desc.prompt()
  1761. # Check if user added a change_id in the descripiton.
  1762. change_ids = git_footers.get_footer_change_id(
  1763. change_desc.description)
  1764. if len(change_ids) == 1:
  1765. change_id = change_ids[0]
  1766. else:
  1767. change_id = GenerateGerritChangeId(change_desc.description)
  1768. change_desc.ensure_change_id(change_id)
  1769. if options.preserve_tryjobs:
  1770. change_desc.set_preserve_tryjobs()
  1771. SaveDescriptionBackup(change_desc)
  1772. # Add ccs
  1773. ccs = []
  1774. # Add default, watchlist, presubmit ccs if this is the initial upload
  1775. # and CL is not private and auto-ccing has not been disabled.
  1776. if not options.private and not options.no_autocc and not self.GetIssue(
  1777. ):
  1778. ccs = self.GetCCList().split(',')
  1779. # Add ccs from the --cc flag.
  1780. if options.cc:
  1781. ccs.extend(options.cc)
  1782. ccs = [email.strip() for email in ccs if email.strip()]
  1783. if change_desc.get_cced():
  1784. ccs.extend(change_desc.get_cced())
  1785. return change_desc.get_reviewers(), ccs, change_desc
  1786. def PostUploadUpdates(self, options: optparse.Values,
  1787. new_upload: _NewUpload, change_number: str) -> None:
  1788. """Makes necessary post upload changes to the local and remote cl."""
  1789. if not self.GetIssue():
  1790. self.SetIssue(change_number)
  1791. self.SetPatchset(new_upload.prev_patchset + 1)
  1792. self._GitSetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY,
  1793. new_upload.commit_to_push)
  1794. self._GitSetBranchConfigValue(LAST_UPLOAD_HASH_CONFIG_KEY,
  1795. new_upload.new_last_uploaded_commit)
  1796. if settings.GetRunPostUploadHook():
  1797. self.RunPostUploadHook(options.verbose, new_upload.parent,
  1798. new_upload.change_desc.description)
  1799. if new_upload.reviewers or new_upload.ccs:
  1800. gerrit_util.AddReviewers(self.GetGerritHost(),
  1801. self._GerritChangeIdentifier(),
  1802. reviewers=new_upload.reviewers,
  1803. ccs=new_upload.ccs,
  1804. notify=bool(options.send_mail))
  1805. def CMDUpload(self, options, git_diff_args, orig_args):
  1806. """Uploads a change to codereview."""
  1807. custom_cl_base = None
  1808. if git_diff_args:
  1809. custom_cl_base = base_branch = git_diff_args[0]
  1810. else:
  1811. if self.GetBranch() is None:
  1812. DieWithError(
  1813. 'Can\'t upload from detached HEAD state. Get on a branch!')
  1814. # Default to diffing against common ancestor of upstream branch
  1815. base_branch = self.GetCommonAncestorWithUpstream()
  1816. git_diff_args = [base_branch, 'HEAD']
  1817. # Fast best-effort checks to abort before running potentially expensive
  1818. # hooks if uploading is likely to fail anyway. Passing these checks does
  1819. # not guarantee that uploading will not fail.
  1820. self.EnsureAuthenticated(force=options.force)
  1821. self.EnsureCanUploadPatchset(force=options.force)
  1822. print(f'Processing {_GetCommitCountSummary(*git_diff_args)}...')
  1823. # Apply watchlists on upload.
  1824. watchlist = watchlists.Watchlists(settings.GetRoot())
  1825. files = self.GetAffectedFiles(base_branch)
  1826. if not options.bypass_watchlists:
  1827. self.ExtendCC(watchlist.GetWatchersForPaths(files))
  1828. change_desc = self._GetDescriptionForUpload(options, git_diff_args,
  1829. files)
  1830. if not options.bypass_hooks:
  1831. hook_results = self.RunHook(committing=False,
  1832. may_prompt=not options.force,
  1833. verbose=options.verbose,
  1834. parallel=options.parallel,
  1835. upstream=base_branch,
  1836. description=change_desc.description,
  1837. all_files=False)
  1838. self.ExtendCC(hook_results['more_cc'])
  1839. print_stats(git_diff_args)
  1840. ret = self.CMDUploadChange(options, git_diff_args, custom_cl_base,
  1841. change_desc)
  1842. if not ret:
  1843. if self.GetBranch() is not None:
  1844. self._GitSetBranchConfigValue(
  1845. LAST_UPLOAD_HASH_CONFIG_KEY,
  1846. scm.GIT.ResolveCommit(settings.GetRoot(), 'HEAD'))
  1847. # Run post upload hooks, if specified.
  1848. if settings.GetRunPostUploadHook():
  1849. self.RunPostUploadHook(options.verbose, base_branch,
  1850. change_desc.description)
  1851. # Upload all dependencies if specified.
  1852. if options.dependencies:
  1853. print()
  1854. print('--dependencies has been specified.')
  1855. print('All dependent local branches will be re-uploaded.')
  1856. print()
  1857. # Remove the dependencies flag from args so that we do not end
  1858. # up in a loop.
  1859. orig_args.remove('--dependencies')
  1860. ret = upload_branch_deps(self, orig_args, options.force)
  1861. return ret
  1862. def SetCQState(self, new_state):
  1863. """Updates the CQ state for the latest patchset.
  1864. Issue must have been already uploaded and known.
  1865. """
  1866. assert new_state in _CQState.ALL_STATES
  1867. assert self.GetIssue()
  1868. try:
  1869. vote_map = {
  1870. _CQState.NONE: 0,
  1871. _CQState.DRY_RUN: 1,
  1872. _CQState.COMMIT: 2,
  1873. }
  1874. labels = {'Commit-Queue': vote_map[new_state]}
  1875. notify = False if new_state == _CQState.DRY_RUN else None
  1876. gerrit_util.SetReview(self.GetGerritHost(),
  1877. self._GerritChangeIdentifier(),
  1878. labels=labels,
  1879. notify=notify)
  1880. return 0
  1881. except KeyboardInterrupt:
  1882. raise
  1883. except:
  1884. print(
  1885. 'WARNING: Failed to %s.\n'
  1886. 'Either:\n'
  1887. ' * Your project has no CQ,\n'
  1888. ' * You don\'t have permission to change the CQ state,\n'
  1889. ' * There\'s a bug in this code (see stack trace below).\n'
  1890. 'Consider specifying which bots to trigger manually or asking your '
  1891. 'project owners for permissions or contacting Chrome Infra at:\n'
  1892. 'https://www.chromium.org/infra\n\n' %
  1893. ('cancel CQ' if new_state == _CQState.NONE else 'trigger CQ'))
  1894. # Still raise exception so that stack trace is printed.
  1895. raise
  1896. def GetGerritHost(self):
  1897. # Populate self._gerrit_host
  1898. self.GetCodereviewServer()
  1899. if self._gerrit_host and '.' not in self._gerrit_host:
  1900. # Abbreviated domain like "chromium" instead of
  1901. # chromium.googlesource.com.
  1902. parsed = urllib.parse.urlparse(self.GetRemoteUrl())
  1903. if parsed.scheme == 'sso':
  1904. self._gerrit_host = '%s.googlesource.com' % self._gerrit_host
  1905. self._gerrit_server = 'https://%s' % self._gerrit_host
  1906. return self._gerrit_host
  1907. def _GetGitHost(self):
  1908. """Returns git host to be used when uploading change to Gerrit."""
  1909. remote_url = self.GetRemoteUrl()
  1910. if not remote_url:
  1911. return None
  1912. return urllib.parse.urlparse(remote_url).netloc
  1913. def _GetGerritHostFromRemoteUrl(self):
  1914. url = urllib.parse.urlparse(self.GetRemoteUrl())
  1915. parts = url.netloc.split('.')
  1916. # We assume repo to be hosted on Gerrit, and hence Gerrit server
  1917. # has "-review" suffix for lowest level subdomain.
  1918. parts[0] = parts[0] + '-review'
  1919. if url.scheme == 'sso' and len(parts) == 1:
  1920. # sso:// uses abbreivated hosts, eg. sso://chromium instead
  1921. # of chromium.googlesource.com. Hence, for code review
  1922. # server, they need to be expanded.
  1923. parts[0] += '.googlesource.com'
  1924. return '.'.join(parts)
  1925. def GetCodereviewServer(self):
  1926. if not self._gerrit_server:
  1927. # If we're on a branch then get the server potentially associated
  1928. # with that branch.
  1929. if self.GetIssue() and self.GetBranch():
  1930. self._gerrit_server = self._GitGetBranchConfigValue(
  1931. CODEREVIEW_SERVER_CONFIG_KEY)
  1932. if self._gerrit_server:
  1933. self._gerrit_host = urllib.parse.urlparse(
  1934. self._gerrit_server).netloc
  1935. if not self._gerrit_server:
  1936. self._gerrit_host = self._GetGerritHostFromRemoteUrl()
  1937. self._gerrit_server = 'https://%s' % self._gerrit_host
  1938. return self._gerrit_server
  1939. def GetGerritProject(self):
  1940. """Returns Gerrit project name based on remote git URL."""
  1941. remote_url = self.GetRemoteUrl()
  1942. if remote_url is None:
  1943. logging.warning('can\'t detect Gerrit project.')
  1944. return None
  1945. project = urllib.parse.urlparse(remote_url).path.strip('/')
  1946. if project.endswith('.git'):
  1947. project = project[:-len('.git')]
  1948. # *.googlesource.com hosts ensure that Git/Gerrit projects don't start
  1949. # with 'a/' prefix, because 'a/' prefix is used to force authentication
  1950. # in gitiles/git-over-https protocol. E.g.,
  1951. # https://chromium.googlesource.com/a/v8/v8 refers to the same
  1952. # repo/project as https://chromium.googlesource.com/v8/v8
  1953. if project.startswith('a/'):
  1954. project = project[len('a/'):]
  1955. return project
  1956. def _GerritChangeIdentifier(self):
  1957. """Handy method for gerrit_util.ChangeIdentifier for a given CL.
  1958. Not to be confused by value of "Change-Id:" footer.
  1959. If Gerrit project can be determined, this will speed up Gerrit HTTP API RPC.
  1960. """
  1961. project = self.GetGerritProject()
  1962. if project:
  1963. return gerrit_util.ChangeIdentifier(project, self.GetIssue())
  1964. # Fall back on still unique, but less efficient change number.
  1965. return str(self.GetIssue())
  1966. def EnsureAuthenticated(self, force: bool) -> None:
  1967. """Best effort check that user is authenticated with Gerrit server."""
  1968. if settings.GetGerritSkipEnsureAuthenticated():
  1969. # For projects with unusual authentication schemes.
  1970. # See http://crbug.com/603378.
  1971. return
  1972. remote_url = self.GetRemoteUrl()
  1973. if remote_url is None:
  1974. logging.warning('invalid remote')
  1975. return
  1976. parsed_url = urllib.parse.urlparse(remote_url)
  1977. if parsed_url.scheme == 'sso':
  1978. # Skip checking authentication for projects with sso:// scheme.
  1979. return
  1980. if parsed_url.scheme != 'https':
  1981. logging.warning(
  1982. 'Ignoring branch %(branch)s with non-https remote '
  1983. '%(remote)s', {
  1984. 'branch': self.branch,
  1985. 'remote': self.GetRemoteUrl()
  1986. })
  1987. return
  1988. if newauth.Enabled():
  1989. latestVer: int = git_auth.ConfigChanger.VERSION
  1990. v: int = 0
  1991. try:
  1992. v = int(
  1993. scm.GIT.GetConfig(settings.GetRoot(),
  1994. 'depot-tools.gitauthautoconfigured',
  1995. default='0'))
  1996. except ValueError:
  1997. v = 0
  1998. if v < latestVer:
  1999. logging.debug(
  2000. 'Automatically configuring Git repo authentication (current version: %r, latest: %r)',
  2001. v, latestVer)
  2002. ConfigureGitRepoAuth()
  2003. scm.GIT.SetConfig(settings.GetRoot(),
  2004. 'depot-tools.gitAuthAutoConfigured',
  2005. str(latestVer))
  2006. return
  2007. # Lazy-loader to identify Gerrit and Git hosts.
  2008. self.GetCodereviewServer()
  2009. git_host = self._GetGitHost()
  2010. assert self._gerrit_server and self._gerrit_host and git_host
  2011. bypassable, msg = gerrit_util.ensure_authenticated(
  2012. git_host, self._gerrit_host)
  2013. if not msg:
  2014. return # OK
  2015. if bypassable:
  2016. if not force:
  2017. confirm_or_exit(msg, action='continue')
  2018. else:
  2019. DieWithError(msg)
  2020. def EnsureCanUploadPatchset(self, force):
  2021. issue = self.GetIssue()
  2022. if not issue:
  2023. return
  2024. status = self._GetChangeDetail()['status']
  2025. if status == 'ABANDONED':
  2026. DieWithError(
  2027. 'Change %s has been abandoned, new uploads are not allowed' %
  2028. (self.GetIssueURL()))
  2029. if status == 'MERGED':
  2030. answer = gclient_utils.AskForData(
  2031. 'Change %s has been submitted, new uploads are not allowed. '
  2032. 'Would you like to start a new change (Y/n)?' %
  2033. self.GetIssueURL()).lower()
  2034. if answer not in ('y', ''):
  2035. DieWithError('New uploads are not allowed.')
  2036. self.SetIssue()
  2037. return
  2038. # Check to see if the currently authenticated account is the issue
  2039. # owner.
  2040. # first, grab the issue owner email
  2041. owner = self.GetIssueOwner()
  2042. # do a quick check to see if this matches the local git config's
  2043. # configured email.
  2044. git_config_email = scm.GIT.GetConfig(settings.GetRoot(), 'user.email')
  2045. if git_config_email == owner:
  2046. # Good enough - Gerrit will reject this if the user is doing funny things
  2047. # with user.email.
  2048. return
  2049. # However, the user may have linked accounts in Gerrit, so pull up the
  2050. # list of all known emails for the currently authenticated account.
  2051. emails = gerrit_util.GetAccountEmails(self.GetGerritHost(), 'self')
  2052. if not emails:
  2053. print('WARNING: Gerrit does not have a record for your account.')
  2054. print('Please browse to https://{self.GetGerritHost()} and log in.')
  2055. return
  2056. # If the issue owner is one of the emails for the currently
  2057. # authenticated account, Gerrit will accept the upload.
  2058. if any(owner == e['email'] for e in emails):
  2059. return
  2060. if not force:
  2061. print(
  2062. f'WARNING: Change {issue} is owned by {owner}, but Gerrit knows you as:'
  2063. )
  2064. for email in emails:
  2065. tag = ' (preferred)' if email.get('preferred') else ''
  2066. print(f' * {email["email"]}{tag}')
  2067. print('Uploading may fail due to lack of permissions.')
  2068. confirm_or_exit(action='upload')
  2069. def GetStatus(self):
  2070. """Applies a rough heuristic to give a simple summary of an issue's review
  2071. or CQ status, assuming adherence to a common workflow.
  2072. Returns None if no issue for this branch, or one of the following keywords:
  2073. * 'error' - error from review tool (including deleted issues)
  2074. * 'unsent' - no reviewers added
  2075. * 'waiting' - waiting for review
  2076. * 'reply' - waiting for uploader to reply to review
  2077. * 'lgtm' - Code-Review label has been set
  2078. * 'dry-run' - dry-running in the CQ
  2079. * 'commit' - in the CQ
  2080. * 'closed' - successfully submitted or abandoned
  2081. """
  2082. if not self.GetIssue():
  2083. return None
  2084. try:
  2085. data = self._GetChangeDetail(
  2086. ['DETAILED_LABELS', 'CURRENT_REVISION', 'SUBMITTABLE'])
  2087. except GerritChangeNotExists:
  2088. return 'error'
  2089. if data['status'] in ('ABANDONED', 'MERGED'):
  2090. return 'closed'
  2091. cq_label = data['labels'].get('Commit-Queue', {})
  2092. max_cq_vote = 0
  2093. for vote in cq_label.get('all', []):
  2094. max_cq_vote = max(max_cq_vote, vote.get('value', 0))
  2095. if max_cq_vote == 2:
  2096. return 'commit'
  2097. if max_cq_vote == 1:
  2098. return 'dry-run'
  2099. if data['labels'].get('Code-Review', {}).get('approved'):
  2100. return 'lgtm'
  2101. if not data.get('reviewers', {}).get('REVIEWER', []):
  2102. return 'unsent'
  2103. owner = data['owner'].get('_account_id')
  2104. messages = sorted(data.get('messages', []), key=lambda m: m.get('date'))
  2105. while messages:
  2106. m = messages.pop()
  2107. if (m.get('tag', '').startswith('autogenerated:cq')
  2108. or m.get('tag', '').startswith('autogenerated:cv')):
  2109. # Ignore replies from LUCI CV/CQ.
  2110. continue
  2111. if m.get('author', {}).get('_account_id') == owner:
  2112. # Most recent message was by owner.
  2113. return 'waiting'
  2114. # Some reply from non-owner.
  2115. return 'reply'
  2116. # Somehow there are no messages even though there are reviewers.
  2117. return 'unsent'
  2118. def GetMostRecentPatchset(self, update=True):
  2119. if not self.GetIssue():
  2120. return None
  2121. data = self._GetChangeDetail(['CURRENT_REVISION'])
  2122. patchset = data['revisions'][data['current_revision']]['_number']
  2123. if update:
  2124. self.SetPatchset(patchset)
  2125. return patchset
  2126. def _IsPatchsetRangeSignificant(self, lower, upper):
  2127. """Returns True if the inclusive range of patchsets contains any reworks or
  2128. rebases."""
  2129. if not self.GetIssue():
  2130. return False
  2131. data = self._GetChangeDetail(['ALL_REVISIONS'])
  2132. ps_kind = {}
  2133. for rev_info in data.get('revisions', {}).values():
  2134. ps_kind[rev_info['_number']] = rev_info.get('kind', '')
  2135. for ps in range(lower, upper + 1):
  2136. assert ps in ps_kind, 'expected patchset %d in change detail' % ps
  2137. if ps_kind[ps] not in ('NO_CHANGE', 'NO_CODE_CHANGE'):
  2138. return True
  2139. return False
  2140. def GetMostRecentDryRunPatchset(self):
  2141. """Get patchsets equivalent to the most recent patchset and return
  2142. the patchset with the latest dry run. If none have been dry run, return
  2143. the latest patchset."""
  2144. if not self.GetIssue():
  2145. return None
  2146. data = self._GetChangeDetail(['ALL_REVISIONS'])
  2147. patchset = data['revisions'][data['current_revision']]['_number']
  2148. dry_run = {
  2149. int(m['_revision_number'])
  2150. for m in data.get('messages', [])
  2151. if m.get('tag', '').endswith('dry-run')
  2152. }
  2153. for revision_info in sorted(data.get('revisions', {}).values(),
  2154. key=lambda c: c['_number'],
  2155. reverse=True):
  2156. if revision_info['_number'] in dry_run:
  2157. patchset = revision_info['_number']
  2158. break
  2159. if revision_info.get('kind', '') not in \
  2160. ('NO_CHANGE', 'NO_CODE_CHANGE', 'TRIVIAL_REBASE'):
  2161. break
  2162. self.SetPatchset(patchset)
  2163. return patchset
  2164. def AddComment(self, message, publish=None):
  2165. gerrit_util.SetReview(self.GetGerritHost(),
  2166. self._GerritChangeIdentifier(),
  2167. msg=message,
  2168. ready=publish)
  2169. def GetCommentsSummary(self, readable=True):
  2170. # DETAILED_ACCOUNTS is to get emails in accounts.
  2171. # CURRENT_REVISION is included to get the latest patchset so that
  2172. # only the robot comments from the latest patchset can be shown.
  2173. messages = self._GetChangeDetail(
  2174. options=['MESSAGES', 'DETAILED_ACCOUNTS', 'CURRENT_REVISION']).get(
  2175. 'messages', [])
  2176. file_comments = gerrit_util.GetChangeComments(
  2177. self.GetGerritHost(), self._GerritChangeIdentifier())
  2178. robot_file_comments = gerrit_util.GetChangeRobotComments(
  2179. self.GetGerritHost(), self._GerritChangeIdentifier())
  2180. # Add the robot comments onto the list of comments, but only
  2181. # keep those that are from the latest patchset.
  2182. latest_patch_set = self.GetMostRecentPatchset()
  2183. for path, robot_comments in robot_file_comments.items():
  2184. line_comments = file_comments.setdefault(path, [])
  2185. line_comments.extend([
  2186. c for c in robot_comments if c['patch_set'] == latest_patch_set
  2187. ])
  2188. # Build dictionary of file comments for easy access and sorting later.
  2189. # {author+date: {path: {patchset: {line: url+message}}}}
  2190. comments = collections.defaultdict(lambda: collections.defaultdict(
  2191. lambda: collections.defaultdict(dict)))
  2192. server = self.GetCodereviewServer()
  2193. if server in _KNOWN_GERRIT_TO_SHORT_URLS:
  2194. # /c/ is automatically added by short URL server.
  2195. url_prefix = '%s/%s' % (_KNOWN_GERRIT_TO_SHORT_URLS[server],
  2196. self.GetIssue())
  2197. else:
  2198. url_prefix = '%s/c/%s' % (server, self.GetIssue())
  2199. for path, line_comments in file_comments.items():
  2200. for comment in line_comments:
  2201. tag = comment.get('tag', '')
  2202. if tag.startswith(
  2203. 'autogenerated') and 'robot_id' not in comment:
  2204. continue
  2205. key = (comment['author']['email'], comment['updated'])
  2206. if comment.get('side', 'REVISION') == 'PARENT':
  2207. patchset = 'Base'
  2208. else:
  2209. patchset = 'PS%d' % comment['patch_set']
  2210. line = comment.get('line', 0)
  2211. url = ('%s/%s/%s#%s%s' %
  2212. (url_prefix, comment['patch_set'],
  2213. path, 'b' if comment.get('side') == 'PARENT' else '',
  2214. str(line) if line else ''))
  2215. comments[key][path][patchset][line] = (url, comment['message'])
  2216. summaries = []
  2217. for msg in messages:
  2218. summary = self._BuildCommentSummary(msg, comments, readable)
  2219. if summary:
  2220. summaries.append(summary)
  2221. return summaries
  2222. @staticmethod
  2223. def _BuildCommentSummary(msg, comments, readable):
  2224. if 'email' not in msg['author']:
  2225. # Some bot accounts may not have an email associated.
  2226. return None
  2227. key = (msg['author']['email'], msg['date'])
  2228. # Don't bother showing autogenerated messages that don't have associated
  2229. # file or line comments. this will filter out most autogenerated
  2230. # messages, but will keep robot comments like those from Tricium.
  2231. is_autogenerated = msg.get('tag', '').startswith('autogenerated')
  2232. if is_autogenerated and not comments.get(key):
  2233. return None
  2234. message = msg['message']
  2235. # Gerrit spits out nanoseconds.
  2236. assert len(msg['date'].split('.')[-1]) == 9
  2237. date = datetime.datetime.strptime(msg['date'][:-3],
  2238. '%Y-%m-%d %H:%M:%S.%f')
  2239. if key in comments:
  2240. message += '\n'
  2241. for path, patchsets in sorted(comments.get(key, {}).items()):
  2242. if readable:
  2243. message += '\n%s' % path
  2244. for patchset, lines in sorted(patchsets.items()):
  2245. for line, (url, content) in sorted(lines.items()):
  2246. if line:
  2247. line_str = 'Line %d' % line
  2248. path_str = '%s:%d:' % (path, line)
  2249. else:
  2250. line_str = 'File comment'
  2251. path_str = '%s:0:' % path
  2252. if readable:
  2253. message += '\n %s, %s: %s' % (patchset, line_str, url)
  2254. message += '\n %s\n' % content
  2255. else:
  2256. message += '\n%s ' % path_str
  2257. message += '\n%s\n' % content
  2258. return _CommentSummary(
  2259. date=date,
  2260. message=message,
  2261. sender=msg['author']['email'],
  2262. autogenerated=is_autogenerated,
  2263. # These could be inferred from the text messages and correlated with
  2264. # Code-Review label maximum, however this is not reliable.
  2265. # Leaving as is until the need arises.
  2266. approval=False,
  2267. disapproval=False,
  2268. )
  2269. def CloseIssue(self):
  2270. gerrit_util.AbandonChange(self.GetGerritHost(),
  2271. self._GerritChangeIdentifier(),
  2272. msg='')
  2273. def SubmitIssue(self):
  2274. gerrit_util.SubmitChange(self.GetGerritHost(),
  2275. self._GerritChangeIdentifier())
  2276. def _GetChangeDetail(self, options=None):
  2277. """Returns details of associated Gerrit change and caching results."""
  2278. options = options or []
  2279. assert self.GetIssue(), 'issue is required to query Gerrit'
  2280. # Optimization to avoid multiple RPCs:
  2281. if 'CURRENT_REVISION' in options or 'ALL_REVISIONS' in options:
  2282. options.append('CURRENT_COMMIT')
  2283. # Normalize issue and options for consistent keys in cache.
  2284. cache_key = str(self.GetIssue())
  2285. options_set = frozenset(o.upper() for o in options)
  2286. for cached_options_set, data in self._detail_cache.get(cache_key, []):
  2287. # Assumption: data fetched before with extra options is suitable
  2288. # for return for a smaller set of options.
  2289. # For example, if we cached data for
  2290. # options=[CURRENT_REVISION, DETAILED_FOOTERS]
  2291. # and request is for options=[CURRENT_REVISION],
  2292. # THEN we can return prior cached data.
  2293. if options_set.issubset(cached_options_set):
  2294. return data
  2295. try:
  2296. data = gerrit_util.GetChangeDetail(self.GetGerritHost(),
  2297. self._GerritChangeIdentifier(),
  2298. options_set)
  2299. except gerrit_util.GerritError as e:
  2300. if e.http_status == 404:
  2301. raise GerritChangeNotExists(self.GetIssue(),
  2302. self.GetCodereviewServer())
  2303. raise
  2304. self._detail_cache.setdefault(cache_key, []).append((options_set, data))
  2305. return data
  2306. def _GetChangeCommit(self, revision='current'):
  2307. assert self.GetIssue(), 'issue must be set to query Gerrit'
  2308. try:
  2309. data = gerrit_util.GetChangeCommit(self.GetGerritHost(),
  2310. self._GerritChangeIdentifier(),
  2311. revision)
  2312. except gerrit_util.GerritError as e:
  2313. if e.http_status == 404:
  2314. raise GerritChangeNotExists(self.GetIssue(),
  2315. self.GetCodereviewServer())
  2316. raise
  2317. return data
  2318. def _IsCqConfigured(self):
  2319. detail = self._GetChangeDetail(['LABELS'])
  2320. return u'Commit-Queue' in detail.get('labels', {})
  2321. def CMDLand(self, force, bypass_hooks, verbose, parallel, resultdb, realm):
  2322. if git_common.is_dirty_git_tree('land'):
  2323. return 1
  2324. detail = self._GetChangeDetail(['CURRENT_REVISION', 'LABELS'])
  2325. if not force and self._IsCqConfigured():
  2326. confirm_or_exit(
  2327. '\nIt seems this repository has a CQ, '
  2328. 'which can test and land changes for you. '
  2329. 'Are you sure you wish to bypass it?\n',
  2330. action='bypass CQ')
  2331. differs = True
  2332. last_upload = self._GitGetBranchConfigValue(
  2333. GERRIT_SQUASH_HASH_CONFIG_KEY)
  2334. # Note: git diff outputs nothing if there is no diff.
  2335. if not last_upload or RunGit(['diff', last_upload]).strip():
  2336. print(
  2337. 'WARNING: Some changes from local branch haven\'t been uploaded.'
  2338. )
  2339. else:
  2340. if detail['current_revision'] == last_upload:
  2341. differs = False
  2342. else:
  2343. print(
  2344. 'WARNING: Local branch contents differ from latest uploaded '
  2345. 'patchset.')
  2346. if differs:
  2347. if not force:
  2348. confirm_or_exit(
  2349. 'Do you want to submit latest Gerrit patchset and bypass hooks?\n',
  2350. action='submit')
  2351. print(
  2352. 'WARNING: Bypassing hooks and submitting latest uploaded patchset.'
  2353. )
  2354. elif not bypass_hooks:
  2355. upstream = self.GetCommonAncestorWithUpstream()
  2356. if self.GetIssue():
  2357. description = self.FetchDescription()
  2358. else:
  2359. description = _create_description_from_log([upstream])
  2360. self.RunHook(committing=True,
  2361. may_prompt=not force,
  2362. verbose=verbose,
  2363. parallel=parallel,
  2364. upstream=upstream,
  2365. description=description,
  2366. all_files=False,
  2367. resultdb=resultdb,
  2368. realm=realm)
  2369. self.SubmitIssue()
  2370. print('Issue %s has been submitted.' % self.GetIssueURL())
  2371. links = self._GetChangeCommit().get('web_links', [])
  2372. for link in links:
  2373. if link.get('name') in ['gitiles', 'browse'] and link.get('url'):
  2374. print('Landed as: %s' % link.get('url'))
  2375. break
  2376. return 0
  2377. def CMDPatchWithParsedIssue(self, parsed_issue_arg, nocommit, force):
  2378. assert parsed_issue_arg.valid
  2379. self.issue = parsed_issue_arg.issue
  2380. if parsed_issue_arg.hostname:
  2381. self._gerrit_host = parsed_issue_arg.hostname
  2382. self._gerrit_server = 'https://%s' % self._gerrit_host
  2383. try:
  2384. detail = self._GetChangeDetail(['ALL_REVISIONS'])
  2385. except GerritChangeNotExists as e:
  2386. DieWithError(str(e))
  2387. if not parsed_issue_arg.patchset:
  2388. # Use current revision by default.
  2389. revision_info = detail['revisions'][detail['current_revision']]
  2390. patchset = int(revision_info['_number'])
  2391. else:
  2392. patchset = parsed_issue_arg.patchset
  2393. for revision_info in detail['revisions'].values():
  2394. if int(revision_info['_number']) == parsed_issue_arg.patchset:
  2395. break
  2396. else:
  2397. DieWithError('Couldn\'t find patchset %i in change %i' %
  2398. (parsed_issue_arg.patchset, self.GetIssue()))
  2399. remote_url = self.GetRemoteUrl()
  2400. if remote_url.endswith('.git'):
  2401. remote_url = remote_url[:-len('.git')]
  2402. remote_url = remote_url.rstrip('/')
  2403. fetch_info = revision_info['fetch']['http']
  2404. fetch_info['url'] = fetch_info['url'].rstrip('/')
  2405. if remote_url != fetch_info['url']:
  2406. DieWithError(
  2407. 'Trying to patch a change from %s but this repo appears '
  2408. 'to be %s.' % (fetch_info['url'], remote_url))
  2409. RunGit(['fetch', fetch_info['url'], fetch_info['ref']])
  2410. # Set issue immediately in case the cherry-pick fails, which happens
  2411. # when resolving conflicts.
  2412. if self.GetBranch():
  2413. self.SetIssue(parsed_issue_arg.issue)
  2414. if force:
  2415. RunGit(['reset', '--hard', 'FETCH_HEAD'])
  2416. print('Checked out commit for change %i patchset %i locally' %
  2417. (parsed_issue_arg.issue, patchset))
  2418. elif nocommit:
  2419. RunGit(['cherry-pick', '--no-commit', 'FETCH_HEAD'])
  2420. print('Patch applied to index.')
  2421. else:
  2422. RunGit(['cherry-pick', 'FETCH_HEAD'])
  2423. print('Committed patch for change %i patchset %i locally.' %
  2424. (parsed_issue_arg.issue, patchset))
  2425. print(
  2426. 'Note: this created a local commit which does not have '
  2427. 'the same hash as the one uploaded for review. This will make '
  2428. 'uploading changes based on top of this branch difficult.\n'
  2429. 'If you want to do that, use "git cl patch --force" instead.')
  2430. if self.GetBranch():
  2431. self.SetPatchset(patchset)
  2432. fetched_hash = scm.GIT.ResolveCommit(settings.GetRoot(),
  2433. 'FETCH_HEAD')
  2434. self._GitSetBranchConfigValue(LAST_UPLOAD_HASH_CONFIG_KEY,
  2435. fetched_hash)
  2436. self._GitSetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY,
  2437. fetched_hash)
  2438. else:
  2439. print(
  2440. 'WARNING: You are in detached HEAD state.\n'
  2441. 'The patch has been applied to your checkout, but you will not be '
  2442. 'able to upload a new patch set to the gerrit issue.\n'
  2443. 'Try using the \'-b\' option if you would like to work on a '
  2444. 'branch and/or upload a new patch set.')
  2445. return 0
  2446. @staticmethod
  2447. def _GerritCommitMsgHookCheck(offer_removal):
  2448. # type: (bool) -> None
  2449. """Checks for the gerrit's commit-msg hook and removes it if necessary."""
  2450. hook = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
  2451. if not os.path.exists(hook):
  2452. return
  2453. # Crude attempt to distinguish Gerrit Codereview hook from a potentially
  2454. # custom developer-made one.
  2455. data = gclient_utils.FileRead(hook)
  2456. if not ('From Gerrit Code Review' in data and 'add_ChangeId()' in data):
  2457. return
  2458. print('WARNING: You have Gerrit commit-msg hook installed.\n'
  2459. 'It is not necessary for uploading with git cl in squash mode, '
  2460. 'and may interfere with it in subtle ways.\n'
  2461. 'We recommend you remove the commit-msg hook.')
  2462. if offer_removal:
  2463. if ask_for_explicit_yes('Do you want to remove it now?'):
  2464. gclient_utils.rm_file_or_tree(hook)
  2465. print('Gerrit commit-msg hook removed.')
  2466. else:
  2467. print('OK, will keep Gerrit commit-msg hook in place.')
  2468. def _CleanUpOldTraces(self):
  2469. """Keep only the last |MAX_TRACES| traces."""
  2470. try:
  2471. traces = sorted([
  2472. os.path.join(TRACES_DIR, f) for f in os.listdir(TRACES_DIR)
  2473. if (os.path.isfile(os.path.join(TRACES_DIR, f))
  2474. and not f.startswith('tmp'))
  2475. ])
  2476. traces_to_delete = traces[:-MAX_TRACES]
  2477. for trace in traces_to_delete:
  2478. os.remove(trace)
  2479. except OSError:
  2480. print('WARNING: Failed to remove old git traces from\n'
  2481. ' %s'
  2482. 'Consider removing them manually.' % TRACES_DIR)
  2483. def _WriteGitPushTraces(self, trace_name, traces_dir, git_push_metadata):
  2484. """Zip and write the git push traces stored in traces_dir."""
  2485. gclient_utils.safe_makedirs(TRACES_DIR)
  2486. traces_zip = trace_name + '-traces'
  2487. traces_readme = trace_name + '-README'
  2488. # Create a temporary dir to store git config and gitcookies in. It will
  2489. # be compressed and stored next to the traces.
  2490. git_info_dir = tempfile.mkdtemp()
  2491. git_info_zip = trace_name + '-git-info'
  2492. git_push_metadata['now'] = datetime_now().strftime(
  2493. '%Y-%m-%dT%H:%M:%S.%f')
  2494. git_push_metadata['trace_name'] = trace_name
  2495. gclient_utils.FileWrite(traces_readme,
  2496. TRACES_README_FORMAT % git_push_metadata)
  2497. # Keep only the first 6 characters of the git hashes on the packet
  2498. # trace. This greatly decreases size after compression.
  2499. packet_traces = os.path.join(traces_dir, 'trace-packet')
  2500. if os.path.isfile(packet_traces):
  2501. contents = gclient_utils.FileRead(packet_traces)
  2502. gclient_utils.FileWrite(packet_traces,
  2503. GIT_HASH_RE.sub(r'\1', contents))
  2504. shutil.make_archive(traces_zip, 'zip', traces_dir)
  2505. # Collect and compress the git config and gitcookies.
  2506. git_config = '\n'.join(
  2507. f'{k}={v}' for k, v in scm.GIT.YieldConfigRegexp(settings.GetRoot()))
  2508. gclient_utils.FileWrite(os.path.join(git_info_dir, 'git-config'),
  2509. git_config)
  2510. auth_name, debug_state = gerrit_util.debug_auth()
  2511. # Writes a file like CookiesAuthenticator.debug_summary_state
  2512. gclient_utils.FileWrite(
  2513. os.path.join(git_info_dir, f'{auth_name}.debug_summary_state'),
  2514. debug_state)
  2515. shutil.make_archive(git_info_zip, 'zip', git_info_dir)
  2516. gclient_utils.rmtree(git_info_dir)
  2517. def _RunGitPushWithTraces(self,
  2518. refspec,
  2519. refspec_opts,
  2520. git_push_metadata,
  2521. git_push_options=None):
  2522. """Run git push and collect the traces resulting from the execution."""
  2523. # Create a temporary directory to store traces in. Traces will be
  2524. # compressed and stored in a 'traces' dir inside depot_tools.
  2525. traces_dir = tempfile.mkdtemp()
  2526. trace_name = os.path.join(TRACES_DIR,
  2527. datetime_now().strftime('%Y%m%dT%H%M%S.%f'))
  2528. env = os.environ.copy()
  2529. env['GIT_REDACT_COOKIES'] = 'o,SSO,GSSO_Uberproxy'
  2530. env['GIT_TR2_EVENT'] = os.path.join(traces_dir, 'tr2-event')
  2531. env['GIT_TRACE2_EVENT'] = os.path.join(traces_dir, 'tr2-event')
  2532. env['GIT_TRACE_CURL'] = os.path.join(traces_dir, 'trace-curl')
  2533. env['GIT_TRACE_CURL_NO_DATA'] = '1'
  2534. env['GIT_TRACE_PACKET'] = os.path.join(traces_dir, 'trace-packet')
  2535. push_returncode = 0
  2536. before_push = time_time()
  2537. try:
  2538. remote_url = self.GetRemoteUrl()
  2539. push_cmd = ['git', 'push', remote_url, refspec]
  2540. if git_push_options:
  2541. for opt in git_push_options:
  2542. push_cmd.extend(['-o', opt])
  2543. push_stdout = gclient_utils.CheckCallAndFilter(
  2544. push_cmd,
  2545. env=env,
  2546. print_stdout=True,
  2547. # Flush after every line: useful for seeing progress when
  2548. # running as recipe.
  2549. filter_fn=lambda _: sys.stdout.flush())
  2550. push_stdout = push_stdout.decode('utf-8', 'replace')
  2551. except subprocess2.CalledProcessError as e:
  2552. push_returncode = e.returncode
  2553. if 'blocked keyword' in str(e.stdout) or 'banned word' in str(
  2554. e.stdout):
  2555. raise GitPushError(
  2556. 'Failed to create a change, very likely due to blocked keyword. '
  2557. 'Please examine output above for the reason of the failure.\n'
  2558. 'If this is a false positive, you can try to bypass blocked '
  2559. 'keyword by using push option '
  2560. '-o banned-words~skip, e.g.:\n'
  2561. 'git cl upload -o banned-words~skip\n\n'
  2562. 'If git-cl is not working correctly, file a bug under the '
  2563. 'Infra>SDK component.')
  2564. if 'git push -o nokeycheck' in str(e.stdout):
  2565. raise GitPushError(
  2566. 'Failed to create a change, very likely due to a private key being '
  2567. 'detected. Please examine output above for the reason of the '
  2568. 'failure.\n'
  2569. 'If this is a false positive, you can try to bypass private key '
  2570. 'detection by using push option '
  2571. '-o nokeycheck, e.g.:\n'
  2572. 'git cl upload -o nokeycheck\n\n'
  2573. 'If git-cl is not working correctly, file a bug under the '
  2574. 'Infra>SDK component.')
  2575. raise GitPushError(
  2576. 'Failed to create a change. Please examine output above for the '
  2577. 'reason of the failure.\n'
  2578. 'For emergencies, Googlers can escalate to '
  2579. 'go/gob-support or go/notify#gob\n'
  2580. 'Hint: run command below to diagnose common Git/Gerrit '
  2581. 'credential problems:\n'
  2582. ' git cl creds-check\n'
  2583. '\n'
  2584. 'If git-cl is not working correctly, file a bug under the Infra>SDK '
  2585. 'component including the files below.\n'
  2586. 'Review the files before upload, since they might contain sensitive '
  2587. 'information.\n'
  2588. 'Set the Restrict-View-Google label so that they are not publicly '
  2589. 'accessible.\n' + TRACES_MESSAGE % {'trace_name': trace_name})
  2590. finally:
  2591. execution_time = time_time() - before_push
  2592. metrics.collector.add_repeated(
  2593. 'sub_commands', {
  2594. 'command':
  2595. 'git push',
  2596. 'execution_time':
  2597. execution_time,
  2598. 'exit_code':
  2599. push_returncode,
  2600. 'arguments':
  2601. metrics_utils.extract_known_subcommand_args(refspec_opts),
  2602. })
  2603. git_push_metadata['execution_time'] = execution_time
  2604. git_push_metadata['exit_code'] = push_returncode
  2605. self._WriteGitPushTraces(trace_name, traces_dir, git_push_metadata)
  2606. self._CleanUpOldTraces()
  2607. gclient_utils.rmtree(traces_dir)
  2608. return push_stdout
  2609. def CMDUploadChange(self, options, git_diff_args, custom_cl_base,
  2610. change_desc):
  2611. """Upload the current branch to Gerrit, retry if new remote HEAD is
  2612. found. options and change_desc may be mutated."""
  2613. remote, remote_branch = self.GetRemoteBranch()
  2614. branch = GetTargetRef(remote, remote_branch, options.target_branch)
  2615. try:
  2616. return self._CMDUploadChange(options, git_diff_args, custom_cl_base,
  2617. change_desc, branch)
  2618. except GitPushError as e:
  2619. # Repository might be in the middle of transition to main branch as
  2620. # default, and uploads to old default might be blocked.
  2621. if remote_branch not in [DEFAULT_OLD_BRANCH, DEFAULT_NEW_BRANCH]:
  2622. DieWithError(str(e), change_desc)
  2623. project_head = gerrit_util.GetProjectHead(self._gerrit_host,
  2624. self.GetGerritProject())
  2625. if project_head == branch:
  2626. DieWithError(str(e), change_desc)
  2627. branch = project_head
  2628. print("WARNING: Fetching remote state and retrying upload to default "
  2629. "branch...")
  2630. RunGit(['fetch', '--prune', remote])
  2631. options.edit_description = False
  2632. options.force = True
  2633. try:
  2634. self._CMDUploadChange(options, git_diff_args, custom_cl_base,
  2635. change_desc, branch)
  2636. except GitPushError as e:
  2637. DieWithError(str(e), change_desc)
  2638. def _CMDUploadChange(self, options, git_diff_args, custom_cl_base,
  2639. change_desc, branch):
  2640. """Upload the current branch to Gerrit."""
  2641. if options.squash:
  2642. Changelist._GerritCommitMsgHookCheck(
  2643. offer_removal=not options.force)
  2644. external_parent = None
  2645. if self.GetIssue():
  2646. # User requested to change description
  2647. if options.edit_description:
  2648. change_desc.prompt()
  2649. change_detail = self._GetChangeDetail(['CURRENT_REVISION'])
  2650. change_id = change_detail['change_id']
  2651. change_desc.ensure_change_id(change_id)
  2652. # Check if changes outside of this workspace have been uploaded.
  2653. current_rev = change_detail['current_revision']
  2654. last_uploaded_rev = self._GitGetBranchConfigValue(
  2655. GERRIT_SQUASH_HASH_CONFIG_KEY)
  2656. if last_uploaded_rev and current_rev != last_uploaded_rev:
  2657. external_parent = self._UpdateWithExternalChanges()
  2658. else: # if not self.GetIssue()
  2659. if not options.force and not (options.message_file
  2660. or options.commit_description):
  2661. change_desc.prompt()
  2662. change_ids = git_footers.get_footer_change_id(
  2663. change_desc.description)
  2664. if len(change_ids) == 1:
  2665. change_id = change_ids[0]
  2666. else:
  2667. change_id = GenerateGerritChangeId(change_desc.description)
  2668. change_desc.ensure_change_id(change_id)
  2669. if options.preserve_tryjobs:
  2670. change_desc.set_preserve_tryjobs()
  2671. remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
  2672. parent = external_parent or self._ComputeParent(
  2673. remote, upstream_branch, custom_cl_base, options.force,
  2674. change_desc)
  2675. tree = RunGit(['rev-parse', 'HEAD:']).strip()
  2676. with gclient_utils.temporary_file() as desc_tempfile:
  2677. gclient_utils.FileWrite(desc_tempfile, change_desc.description)
  2678. ref_to_push = RunGit(
  2679. ['commit-tree', tree, '-p', parent, '-F',
  2680. desc_tempfile]).strip()
  2681. else: # if not options.squash
  2682. if options.no_add_changeid:
  2683. pass
  2684. else: # adding Change-Ids is okay.
  2685. if not git_footers.get_footer_change_id(
  2686. change_desc.description):
  2687. DownloadGerritHook(False)
  2688. change_desc.set_description(
  2689. self._AddChangeIdToCommitMessage(
  2690. change_desc.description, git_diff_args))
  2691. ref_to_push = 'HEAD'
  2692. # For no-squash mode, we assume the remote called "origin" is the
  2693. # one we want. It is not worthwhile to support different workflows
  2694. # for no-squash mode.
  2695. parent = 'origin/%s' % branch
  2696. # attempt to extract the changeid from the current description
  2697. # fail informatively if not possible.
  2698. change_id_candidates = git_footers.get_footer_change_id(
  2699. change_desc.description)
  2700. if not change_id_candidates:
  2701. DieWithError("Unable to extract change-id from message.")
  2702. change_id = change_id_candidates[0]
  2703. SaveDescriptionBackup(change_desc)
  2704. commits = RunGitSilent(['rev-list',
  2705. '%s..%s' % (parent, ref_to_push)]).splitlines()
  2706. if len(commits) > 1:
  2707. print(
  2708. 'WARNING: This will upload %d commits. Run the following command '
  2709. 'to see which commits will be uploaded: ' % len(commits))
  2710. print('git log %s..%s' % (parent, ref_to_push))
  2711. print('You can also use `git squash-branch` to squash these into a '
  2712. 'single commit.')
  2713. confirm_or_exit(action='upload')
  2714. reviewers = sorted(change_desc.get_reviewers())
  2715. cc = []
  2716. # Add default, watchlist, presubmit ccs if this is the initial upload
  2717. # and CL is not private and auto-ccing has not been disabled.
  2718. if not options.private and not options.no_autocc and not self.GetIssue(
  2719. ):
  2720. cc = self.GetCCList().split(',')
  2721. # Add cc's from the --cc flag.
  2722. if options.cc:
  2723. cc.extend(options.cc)
  2724. cc = [email.strip() for email in cc if email.strip()]
  2725. if change_desc.get_cced():
  2726. cc.extend(change_desc.get_cced())
  2727. if self.GetGerritHost() == 'chromium-review.googlesource.com':
  2728. valid_accounts = set(reviewers + cc)
  2729. # TODO(crbug/877717): relax this for all hosts.
  2730. else:
  2731. valid_accounts = gerrit_util.ValidAccounts(self.GetGerritHost(),
  2732. reviewers + cc)
  2733. logging.info('accounts %s are recognized, %s invalid',
  2734. sorted(valid_accounts),
  2735. set(reviewers + cc).difference(set(valid_accounts)))
  2736. # Extra options that can be specified at push time. Doc:
  2737. # https://gerrit-review.googlesource.com/Documentation/user-upload.html
  2738. refspec_opts = self._GetRefSpecOptions(options, change_desc)
  2739. for r in sorted(reviewers):
  2740. if r in valid_accounts:
  2741. refspec_opts.append('r=%s' % r)
  2742. reviewers.remove(r)
  2743. else:
  2744. # TODO(tandrii): this should probably be a hard failure.
  2745. print(
  2746. 'WARNING: reviewer %s doesn\'t have a Gerrit account, skipping'
  2747. % r)
  2748. for c in sorted(cc):
  2749. # refspec option will be rejected if cc doesn't correspond to an
  2750. # account, even though REST call to add such arbitrary cc may
  2751. # succeed.
  2752. if c in valid_accounts:
  2753. refspec_opts.append('cc=%s' % c)
  2754. cc.remove(c)
  2755. refspec_suffix = ''
  2756. if refspec_opts:
  2757. refspec_suffix = '%' + ','.join(refspec_opts)
  2758. assert ' ' not in refspec_suffix, (
  2759. 'spaces not allowed in refspec: "%s"' % refspec_suffix)
  2760. refspec = '%s:refs/for/%s%s' % (ref_to_push, branch, refspec_suffix)
  2761. git_push_metadata = {
  2762. 'gerrit_host': self.GetGerritHost(),
  2763. 'title': options.title or '<untitled>',
  2764. 'change_id': change_id,
  2765. 'description': change_desc.description,
  2766. }
  2767. # Gerrit may or may not update fast enough to return the correct
  2768. # patchset number after we push. Get the pre-upload patchset and
  2769. # increment later.
  2770. latest_ps = self.GetMostRecentPatchset(update=False) or 0
  2771. push_stdout = self._RunGitPushWithTraces(refspec, refspec_opts,
  2772. git_push_metadata,
  2773. options.push_options)
  2774. if options.squash:
  2775. regex = re.compile(r'remote:\s+https?://[\w\-\.\+\/#]*/(\d+)\s.*')
  2776. change_numbers = [
  2777. m.group(1) for m in map(regex.match, push_stdout.splitlines())
  2778. if m
  2779. ]
  2780. if len(change_numbers) != 1:
  2781. DieWithError((
  2782. 'Created|Updated %d issues on Gerrit, but only 1 expected.\n'
  2783. 'Change-Id: %s') % (len(change_numbers), change_id),
  2784. change_desc)
  2785. self.SetIssue(change_numbers[0])
  2786. self.SetPatchset(latest_ps + 1)
  2787. self._GitSetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY,
  2788. ref_to_push)
  2789. if self.GetIssue() and (reviewers or cc):
  2790. # GetIssue() is not set in case of non-squash uploads according to
  2791. # tests. TODO(crbug.com/751901): non-squash uploads in git cl should
  2792. # be removed.
  2793. gerrit_util.AddReviewers(self.GetGerritHost(),
  2794. self._GerritChangeIdentifier(),
  2795. reviewers,
  2796. cc,
  2797. notify=bool(options.send_mail))
  2798. return 0
  2799. def _ComputeParent(self, remote, upstream_branch, custom_cl_base, force,
  2800. change_desc):
  2801. """Computes parent of the generated commit to be uploaded to Gerrit.
  2802. Returns revision or a ref name.
  2803. """
  2804. if custom_cl_base:
  2805. # Try to avoid creating additional unintended CLs when uploading,
  2806. # unless user wants to take this risk.
  2807. local_ref_of_target_remote = self.GetRemoteBranch()[1]
  2808. code, _ = RunGitWithCode([
  2809. 'merge-base', '--is-ancestor', custom_cl_base,
  2810. local_ref_of_target_remote
  2811. ])
  2812. if code == 1:
  2813. print(
  2814. '\nWARNING: Manually specified base of this CL `%s` '
  2815. 'doesn\'t seem to belong to target remote branch `%s`.\n\n'
  2816. 'If you proceed with upload, more than 1 CL may be created by '
  2817. 'Gerrit as a result, in turn confusing or crashing git cl.\n\n'
  2818. 'If you are certain that specified base `%s` has already been '
  2819. 'uploaded to Gerrit as another CL, you may proceed.\n' %
  2820. (custom_cl_base, local_ref_of_target_remote,
  2821. custom_cl_base))
  2822. if not force:
  2823. confirm_or_exit(
  2824. 'Do you take responsibility for cleaning up potential mess '
  2825. 'resulting from proceeding with upload?',
  2826. action='upload')
  2827. return custom_cl_base
  2828. if remote != '.':
  2829. return self.GetCommonAncestorWithUpstream()
  2830. # If our upstream branch is local, we base our squashed commit on its
  2831. # squashed version.
  2832. upstream_branch_name = scm.GIT.ShortBranchName(upstream_branch)
  2833. if upstream_branch_name == 'master':
  2834. return self.GetCommonAncestorWithUpstream()
  2835. if upstream_branch_name == 'main':
  2836. return self.GetCommonAncestorWithUpstream()
  2837. # Check the squashed hash of the parent.
  2838. # TODO(tandrii): consider checking parent change in Gerrit and using its
  2839. # hash if tree hash of latest parent revision (patchset) in Gerrit
  2840. # matches the tree hash of the parent branch. The upside is less likely
  2841. # bogus requests to reupload parent change just because it's uploadhash
  2842. # is missing, yet the downside likely exists, too (albeit unknown to me
  2843. # yet).
  2844. parent = scm.GIT.GetBranchConfig(settings.GetRoot(),
  2845. upstream_branch_name,
  2846. GERRIT_SQUASH_HASH_CONFIG_KEY)
  2847. # Verify that the upstream branch has been uploaded too, otherwise
  2848. # Gerrit will create additional CLs when uploading.
  2849. if not parent or (RunGitSilent(['rev-parse', upstream_branch + ':']) !=
  2850. RunGitSilent(['rev-parse', parent + ':'])):
  2851. DieWithError(
  2852. '\nUpload upstream branch %s first.\n'
  2853. 'It is likely that this branch has been rebased since its last '
  2854. 'upload, so you just need to upload it again.\n'
  2855. '(If you uploaded it with --no-squash, then branch dependencies '
  2856. 'are not supported, and you should reupload with --squash.)' %
  2857. upstream_branch_name, change_desc)
  2858. return parent
  2859. def _UpdateWithExternalChanges(self):
  2860. """Updates workspace with external changes.
  2861. Returns the commit hash that should be used as the merge base on upload.
  2862. """
  2863. local_ps = self.GetPatchset()
  2864. if local_ps is None:
  2865. return
  2866. external_ps = self.GetMostRecentPatchset(update=False)
  2867. if external_ps is None or local_ps == external_ps or \
  2868. not self._IsPatchsetRangeSignificant(local_ps + 1, external_ps):
  2869. return
  2870. num_changes = external_ps - local_ps
  2871. if num_changes > 1:
  2872. change_words = 'changes were'
  2873. else:
  2874. change_words = 'change was'
  2875. print('\n%d external %s published to %s:\n' %
  2876. (num_changes, change_words, self.GetIssueURL(short=True)))
  2877. # Print an overview of external changes.
  2878. ps_to_commit = {}
  2879. ps_to_info = {}
  2880. revisions = self._GetChangeDetail(['ALL_REVISIONS'])
  2881. for commit_id, revision_info in revisions.get('revisions', {}).items():
  2882. ps_num = revision_info['_number']
  2883. ps_to_commit[ps_num] = commit_id
  2884. ps_to_info[ps_num] = revision_info
  2885. for ps in range(external_ps, local_ps, -1):
  2886. commit = ps_to_commit[ps][:8]
  2887. desc = ps_to_info[ps].get('description', '')
  2888. print('Patchset %d [%s] %s' % (ps, commit, desc))
  2889. print('\nSee diff at: %s/%d..%d' %
  2890. (self.GetIssueURL(short=True), local_ps, external_ps))
  2891. print('\nUploading without applying patches will override them.')
  2892. if not ask_for_explicit_yes('Get the latest changes and apply on top?'):
  2893. return
  2894. # Get latest Gerrit merge base. Use the first parent even if multiple
  2895. # exist.
  2896. external_parent = self._GetChangeCommit(
  2897. revision=external_ps)['parents'][0]
  2898. external_base = external_parent['commit']
  2899. branch = git_common.current_branch()
  2900. local_base = self.GetCommonAncestorWithUpstream()
  2901. if local_base != external_base:
  2902. print('\nLocal merge base %s is different from Gerrit %s.\n' %
  2903. (local_base, external_base))
  2904. if git_common.upstream(branch):
  2905. confirm_or_exit(
  2906. 'Can\'t apply the latest changes from Gerrit.\n'
  2907. 'Continue with upload and override the latest changes?')
  2908. return
  2909. print(
  2910. 'No upstream branch set. Continuing upload with Gerrit merge base.'
  2911. )
  2912. external_parent_last_uploaded = self._GetChangeCommit(
  2913. revision=local_ps)['parents'][0]
  2914. external_base_last_uploaded = external_parent_last_uploaded['commit']
  2915. if external_base != external_base_last_uploaded:
  2916. print('\nPatch set merge bases are different (%s, %s).\n' %
  2917. (external_base_last_uploaded, external_base))
  2918. confirm_or_exit(
  2919. 'Can\'t apply the latest changes from Gerrit.\n'
  2920. 'Continue with upload and override the latest changes?')
  2921. return
  2922. # Fetch Gerrit's CL base if it doesn't exist locally.
  2923. remote, _ = self.GetRemoteBranch()
  2924. if not scm.GIT.IsValidRevision(settings.GetRoot(), external_base):
  2925. RunGitSilent(['fetch', remote, external_base])
  2926. # Get the diff between local_ps and external_ps.
  2927. print('Fetching changes...')
  2928. issue = self.GetIssue()
  2929. changes_ref = 'refs/changes/%02d/%d/' % (issue % 100, issue)
  2930. RunGitSilent(['fetch', remote, changes_ref + str(local_ps)])
  2931. last_uploaded = RunGitSilent(['rev-parse', 'FETCH_HEAD']).strip()
  2932. RunGitSilent(['fetch', remote, changes_ref + str(external_ps)])
  2933. latest_external = RunGitSilent(['rev-parse', 'FETCH_HEAD']).strip()
  2934. # If the commit parents are different, don't apply the diff as it very
  2935. # likely contains many more changes not relevant to this CL.
  2936. parents = RunGitSilent(
  2937. ['rev-parse',
  2938. '%s~1' % (last_uploaded),
  2939. '%s~1' % (latest_external)]).strip().split()
  2940. assert len(parents) == 2, 'Expected two parents.'
  2941. if parents[0] != parents[1]:
  2942. confirm_or_exit(
  2943. 'Can\'t apply the latest changes from Gerrit (parent mismatch '
  2944. 'between PS).\n'
  2945. 'Continue with upload and override the latest changes?')
  2946. return
  2947. diff = RunGitSilent([
  2948. 'diff', '--no-ext-diff',
  2949. '%s..%s' % (last_uploaded, latest_external)
  2950. ])
  2951. # Diff can be empty in the case of trivial rebases.
  2952. if not diff:
  2953. return external_base
  2954. # Apply the diff.
  2955. with gclient_utils.temporary_file() as diff_tempfile:
  2956. gclient_utils.FileWrite(diff_tempfile, diff)
  2957. clean_patch = RunGitWithCode(['apply', '--check',
  2958. diff_tempfile])[0] == 0
  2959. RunGitSilent(['apply', '-3', '--intent-to-add', diff_tempfile])
  2960. if not clean_patch:
  2961. # Normally patchset is set after upload. But because we exit,
  2962. # that never happens. Updating here makes sure that subsequent
  2963. # uploads don't need to fetch/apply the same diff again.
  2964. self.SetPatchset(external_ps)
  2965. DieWithError(
  2966. '\nPatch did not apply cleanly. Please resolve any '
  2967. 'conflicts and reupload.')
  2968. message = 'Incorporate external changes from '
  2969. if num_changes == 1:
  2970. message += 'patchset %d' % external_ps
  2971. else:
  2972. message += 'patchsets %d to %d' % (local_ps + 1, external_ps)
  2973. RunGitSilent(['commit', '-am', message])
  2974. # TODO(crbug.com/1382528): Use the previous commit's message as a
  2975. # default patchset title instead of this 'Incorporate' message.
  2976. return external_base
  2977. def _AddChangeIdToCommitMessage(self, log_desc, args):
  2978. """Re-commits using the current message, assumes the commit hook is in
  2979. place.
  2980. """
  2981. RunGit(['commit', '--amend', '-m', log_desc])
  2982. new_log_desc = _create_description_from_log(args)
  2983. if git_footers.get_footer_change_id(new_log_desc):
  2984. print('git-cl: Added Change-Id to commit message.')
  2985. return new_log_desc
  2986. DieWithError('ERROR: Gerrit commit-msg hook not installed.')
  2987. def CannotTriggerTryJobReason(self):
  2988. try:
  2989. data = self._GetChangeDetail()
  2990. except GerritChangeNotExists:
  2991. return 'Gerrit doesn\'t know about your change %s' % self.GetIssue()
  2992. if data['status'] in ('ABANDONED', 'MERGED'):
  2993. return 'CL %s is closed' % self.GetIssue()
  2994. def GetGerritChange(self, patchset=None):
  2995. """Returns a buildbucket.v2.GerritChange message for the current issue."""
  2996. host = urllib.parse.urlparse(self.GetCodereviewServer()).hostname
  2997. issue = self.GetIssue()
  2998. patchset = int(patchset or self.GetPatchset())
  2999. data = self._GetChangeDetail(['ALL_REVISIONS'])
  3000. assert host and issue and patchset, 'CL must be uploaded first'
  3001. has_patchset = any(
  3002. int(revision_data['_number']) == patchset
  3003. for revision_data in data['revisions'].values())
  3004. if not has_patchset:
  3005. raise Exception('Patchset %d is not known in Gerrit change %d' %
  3006. (patchset, self.GetIssue()))
  3007. return {
  3008. 'host': host,
  3009. 'change': issue,
  3010. 'project': data['project'],
  3011. 'patchset': patchset,
  3012. }
  3013. def GetIssueOwner(self):
  3014. return self._GetChangeDetail(['DETAILED_ACCOUNTS'])['owner']['email']
  3015. def GetReviewers(self):
  3016. details = self._GetChangeDetail(['DETAILED_ACCOUNTS'])
  3017. return [r['email'] for r in details['reviewers'].get('REVIEWER', [])]
  3018. def _get_bug_line_values(default_project_prefix, bugs):
  3019. """Given default_project_prefix and comma separated list of bugs, yields bug
  3020. line values.
  3021. Each bug can be either:
  3022. * a number, which is combined with default_project_prefix
  3023. * string, which is left as is.
  3024. This function may produce more than one line, because bugdroid expects one
  3025. project per line.
  3026. >>> list(_get_bug_line_values('v8:', '123,chromium:789'))
  3027. ['v8:123', 'chromium:789']
  3028. """
  3029. default_bugs = []
  3030. others = []
  3031. for bug in bugs.split(','):
  3032. bug = bug.strip()
  3033. if bug:
  3034. try:
  3035. default_bugs.append(int(bug))
  3036. except ValueError:
  3037. others.append(bug)
  3038. if default_bugs:
  3039. default_bugs = ','.join(map(str, default_bugs))
  3040. if default_project_prefix:
  3041. if not default_project_prefix.endswith(':'):
  3042. default_project_prefix += ':'
  3043. yield '%s%s' % (default_project_prefix, default_bugs)
  3044. else:
  3045. yield default_bugs
  3046. for other in sorted(others):
  3047. # Don't bother finding common prefixes, CLs with >2 bugs are very very
  3048. # rare.
  3049. yield other
  3050. def FindCodereviewSettingsFile(filename='codereview.settings'):
  3051. """Finds the given file starting in the cwd and going up.
  3052. Only looks up to the top of the repository unless an
  3053. 'inherit-review-settings-ok' file exists in the root of the repository.
  3054. """
  3055. inherit_ok_file = 'inherit-review-settings-ok'
  3056. cwd = os.getcwd()
  3057. root = settings.GetRoot()
  3058. if os.path.isfile(os.path.join(root, inherit_ok_file)):
  3059. root = None
  3060. while True:
  3061. if os.path.isfile(os.path.join(cwd, filename)):
  3062. return open(os.path.join(cwd, filename))
  3063. if cwd == root:
  3064. break
  3065. parent_dir = os.path.dirname(cwd)
  3066. if parent_dir == cwd:
  3067. # We hit the system root directory.
  3068. break
  3069. cwd = parent_dir
  3070. return None
  3071. def LoadCodereviewSettingsFromFile(fileobj):
  3072. """Parses a codereview.settings file and updates hooks."""
  3073. keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read())
  3074. root = settings.GetRoot()
  3075. def SetProperty(name, setting):
  3076. fullname = 'rietveld.' + name
  3077. if setting in keyvals:
  3078. scm.GIT.SetConfig(root, fullname, keyvals[setting])
  3079. else:
  3080. scm.GIT.SetConfig(root, fullname, None, modify_all=True)
  3081. if not keyvals.get('GERRIT_HOST', False):
  3082. SetProperty('server', 'CODE_REVIEW_SERVER')
  3083. # Only server setting is required. Other settings can be absent.
  3084. # In that case, we ignore errors raised during option deletion attempt.
  3085. SetProperty('cc', 'CC_LIST')
  3086. SetProperty('tree-status-url', 'STATUS')
  3087. SetProperty('viewvc-url', 'VIEW_VC')
  3088. SetProperty('bug-prefix', 'BUG_PREFIX')
  3089. SetProperty('cpplint-regex', 'LINT_REGEX')
  3090. SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX')
  3091. SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK')
  3092. SetProperty('format-full-by-default', 'FORMAT_FULL_BY_DEFAULT')
  3093. if 'GERRIT_HOST' in keyvals:
  3094. scm.GIT.SetConfig(root, 'gerrit.host', keyvals['GERRIT_HOST'])
  3095. if 'GERRIT_SQUASH_UPLOADS' in keyvals:
  3096. scm.GIT.SetConfig(root, 'gerrit.squash-uploads',
  3097. keyvals['GERRIT_SQUASH_UPLOADS'])
  3098. if 'GERRIT_SKIP_ENSURE_AUTHENTICATED' in keyvals:
  3099. scm.GIT.SetConfig('gerrit.skip-ensure-authenticated',
  3100. keyvals['GERRIT_SKIP_ENSURE_AUTHENTICATED'])
  3101. if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals:
  3102. # should be of the form
  3103. # PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof
  3104. # ORIGIN_URL_CONFIG: http://src.chromium.org/git
  3105. scm.GIT.SetConfig(keyvals['PUSH_URL_CONFIG'],
  3106. keyvals['ORIGIN_URL_CONFIG'])
  3107. def urlretrieve(source, destination):
  3108. """Downloads a network object to a local file, like urllib.urlretrieve.
  3109. This is necessary because urllib is broken for SSL connections via a proxy.
  3110. """
  3111. with open(destination, 'wb') as f:
  3112. f.write(urllib.request.urlopen(source).read())
  3113. def hasSheBang(fname):
  3114. """Checks fname is a #! script."""
  3115. with open(fname) as f:
  3116. return f.read(2).startswith('#!')
  3117. def DownloadGerritHook(force):
  3118. """Downloads and installs a Gerrit commit-msg hook.
  3119. Args:
  3120. force: True to update hooks. False to install hooks if not present.
  3121. """
  3122. src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg'
  3123. dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
  3124. if not os.access(dst, os.X_OK):
  3125. if os.path.exists(dst):
  3126. if not force:
  3127. return
  3128. try:
  3129. urlretrieve(src, dst)
  3130. if not hasSheBang(dst):
  3131. DieWithError('Not a script: %s\n'
  3132. 'You need to download from\n%s\n'
  3133. 'into .git/hooks/commit-msg and '
  3134. 'chmod +x .git/hooks/commit-msg' % (dst, src))
  3135. os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
  3136. except Exception:
  3137. if os.path.exists(dst):
  3138. os.remove(dst)
  3139. DieWithError('\nFailed to download hooks.\n'
  3140. 'You need to download from\n%s\n'
  3141. 'into .git/hooks/commit-msg and '
  3142. 'chmod +x .git/hooks/commit-msg' % src)
  3143. def ConfigureGitAuth() -> None:
  3144. """Configure Git authentication.
  3145. This may modify the global Git config and the local repo config as
  3146. needed.
  3147. """
  3148. logging.debug('Configuring Git authentication...')
  3149. logging.debug('Configuring global Git authentication...')
  3150. # We want the user's global config.
  3151. # We can probably assume the root directory doesn't have any local
  3152. # Git configuration.
  3153. c = git_auth.ConfigChanger.new_from_env('/')
  3154. c.apply_global(os.path.expanduser('~'))
  3155. cwd = os.getcwd()
  3156. c2 = git_auth.ConfigChanger.new_from_env(cwd)
  3157. if c2.mode == c.mode:
  3158. logging.debug(
  3159. 'Local user wants same mode %s as global; clearing local repo auth config',
  3160. c2.mode)
  3161. c2.mode = git_auth.ConfigMode.NO_AUTH
  3162. c2.apply(cwd)
  3163. return
  3164. logging.debug('Local user wants mode %s while global user wants mode %s',
  3165. c2.mode, c.mode)
  3166. logging.debug('Configuring current Git repo authentication...')
  3167. c2.apply(cwd)
  3168. def ConfigureGitRepoAuth() -> None:
  3169. """Configure the current Git repo authentication."""
  3170. logging.debug('Configuring current Git repo authentication...')
  3171. cwd = os.getcwd()
  3172. c = git_auth.ConfigChanger.new_from_env(cwd)
  3173. c.apply(cwd)
  3174. def ClearGitRepoAuth() -> None:
  3175. """Clear the current Git repo authentication."""
  3176. logging.debug('Clearing current Git repo authentication...')
  3177. c = git_auth.ConfigChanger.new_from_env(cwd)
  3178. c.mode = git_auth.ConfigMode.NO_AUTH
  3179. c.apply(cwd)
  3180. class _GitCookiesChecker(object):
  3181. """Provides facilities for validating and suggesting fixes to .gitcookies."""
  3182. def __init__(self):
  3183. # Cached list of [host, identity, source], where source is
  3184. # .gitcookies
  3185. self._all_hosts = None
  3186. def ensure_configured_gitcookies(self):
  3187. """Runs checks and suggests fixes to make git use .gitcookies from default
  3188. path."""
  3189. default = gerrit_util.CookiesAuthenticator.get_gitcookies_path()
  3190. configured_path = scm.GIT.GetConfig(settings.GetRoot(),
  3191. 'http.cookiefile', '')
  3192. configured_path = os.path.expanduser(configured_path)
  3193. if configured_path:
  3194. self._ensure_default_gitcookies_path(configured_path, default)
  3195. else:
  3196. self._configure_gitcookies_path(default)
  3197. @staticmethod
  3198. def _ensure_default_gitcookies_path(configured_path, default_path):
  3199. assert configured_path
  3200. if configured_path == default_path:
  3201. print('git is already configured to use your .gitcookies from %s' %
  3202. configured_path)
  3203. return
  3204. print('WARNING: You have configured custom path to .gitcookies: %s\n'
  3205. 'Gerrit and other depot_tools expect .gitcookies at %s\n' %
  3206. (configured_path, default_path))
  3207. if not os.path.exists(configured_path):
  3208. print('However, your configured .gitcookies file is missing.')
  3209. confirm_or_exit('Reconfigure git to use default .gitcookies?',
  3210. action='reconfigure')
  3211. scm.GIT.SetConfig(settings.GetRoot(),
  3212. 'http.cookiefile',
  3213. default_path,
  3214. scope='global')
  3215. return
  3216. if os.path.exists(default_path):
  3217. print('WARNING: default .gitcookies file already exists %s' %
  3218. default_path)
  3219. DieWithError(
  3220. 'Please delete %s manually and re-run git cl creds-check' %
  3221. default_path)
  3222. confirm_or_exit('Move existing .gitcookies to default location?',
  3223. action='move')
  3224. shutil.move(configured_path, default_path)
  3225. scm.GIT.SetConfig(settings.GetRoot(),
  3226. 'http.cookiefile',
  3227. default_path,
  3228. scope='global')
  3229. print('Moved and reconfigured git to use .gitcookies from %s' %
  3230. default_path)
  3231. @staticmethod
  3232. def _configure_gitcookies_path(default_path):
  3233. print(
  3234. 'This tool will guide you through setting up recommended '
  3235. '.gitcookies store for git credentials.\n'
  3236. '\n'
  3237. 'IMPORTANT: If something goes wrong and you decide to go back, do:\n'
  3238. ' git config --global --unset http.cookiefile\n'
  3239. ' mv %s %s.backup\n\n' % (default_path, default_path))
  3240. confirm_or_exit(action='setup .gitcookies')
  3241. scm.GIT.SetConfig(settings.GetRoot(),
  3242. 'http.cookiefile',
  3243. default_path,
  3244. scope='global')
  3245. print('Configured git to use .gitcookies from %s' % default_path)
  3246. def get_hosts_with_creds(self):
  3247. if self._all_hosts is None:
  3248. a = gerrit_util.CookiesAuthenticator()
  3249. self._all_hosts = [(h, u, '.gitcookies')
  3250. for h, (u, _) in a.gitcookies.items()
  3251. if h.endswith(_GOOGLESOURCE)]
  3252. return self._all_hosts
  3253. def print_current_creds(self):
  3254. hosts = sorted(self.get_hosts_with_creds())
  3255. if not hosts:
  3256. print('No Git/Gerrit credentials found.')
  3257. return
  3258. lengths = [max(map(len, (row[i] for row in hosts))) for i in range(3)]
  3259. header = [('Host', 'User', 'Which file'), ['=' * l for l in lengths]]
  3260. print('Your .gitcookies have credentials for these hosts:')
  3261. for row in (header + hosts):
  3262. print('\t'.join((('%%+%ds' % l) % s) for l, s in zip(lengths, row)))
  3263. @staticmethod
  3264. def _parse_identity(identity):
  3265. """Parses identity "git-<username>.domain" into <username> and domain."""
  3266. # Special case: usernames that contain ".", which are generally not
  3267. # distinguishable from sub-domains. But we do know typical domains:
  3268. if identity.endswith('.chromium.org'):
  3269. domain = 'chromium.org'
  3270. username = identity[:-len('.chromium.org')]
  3271. else:
  3272. username, domain = identity.split('.', 1)
  3273. if username.startswith('git-'):
  3274. username = username[len('git-'):]
  3275. return username, domain
  3276. def has_generic_host(self):
  3277. """Returns whether generic .googlesource.com has been configured.
  3278. Chrome Infra recommends to use explicit ${host}.googlesource.com instead.
  3279. """
  3280. for host, _, _ in self.get_hosts_with_creds():
  3281. if host == '.' + _GOOGLESOURCE:
  3282. return True
  3283. return False
  3284. def _get_git_gerrit_identity_pairs(self):
  3285. """Returns map from canonic host to pair of identities (Git, Gerrit).
  3286. One of identities might be None, meaning not configured.
  3287. """
  3288. host_to_identity_pairs = {}
  3289. for host, identity, _ in self.get_hosts_with_creds():
  3290. canonical = _canonical_git_googlesource_host(host)
  3291. pair = host_to_identity_pairs.setdefault(canonical, [None, None])
  3292. idx = 0 if canonical == host else 1
  3293. pair[idx] = identity
  3294. return host_to_identity_pairs
  3295. def get_partially_configured_hosts(self):
  3296. return set(
  3297. (host if i1 else _canonical_gerrit_googlesource_host(host))
  3298. for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items()
  3299. if None in (i1, i2) and host != '.' + _GOOGLESOURCE)
  3300. def get_conflicting_hosts(self):
  3301. return set(
  3302. host
  3303. for host, (i1, i2) in self._get_git_gerrit_identity_pairs().items()
  3304. if None not in (i1, i2) and i1 != i2)
  3305. def get_duplicated_hosts(self):
  3306. counters = collections.Counter(
  3307. h for h, _, _ in self.get_hosts_with_creds())
  3308. return set(host for host, count in counters.items() if count > 1)
  3309. @staticmethod
  3310. def _format_hosts(hosts, extra_column_func=None):
  3311. hosts = sorted(hosts)
  3312. assert hosts
  3313. if extra_column_func is None:
  3314. extras = [''] * len(hosts)
  3315. else:
  3316. extras = [extra_column_func(host) for host in hosts]
  3317. tmpl = '%%-%ds %%-%ds' % (max(map(len, hosts)), max(map(len,
  3318. extras)))
  3319. lines = []
  3320. for he in zip(hosts, extras):
  3321. lines.append(tmpl % he)
  3322. return lines
  3323. def _find_problems(self):
  3324. if self.has_generic_host():
  3325. yield ('.googlesource.com wildcard record detected', [
  3326. 'Chrome Infrastructure team recommends to list full host names '
  3327. 'explicitly.'
  3328. ], None)
  3329. dups = self.get_duplicated_hosts()
  3330. if dups:
  3331. yield ('The following hosts were defined twice',
  3332. self._format_hosts(dups), None)
  3333. partial = self.get_partially_configured_hosts()
  3334. if partial:
  3335. yield ('Credentials should come in pairs for Git and Gerrit hosts. '
  3336. 'These hosts are missing',
  3337. self._format_hosts(
  3338. partial, lambda host: 'but %s defined' %
  3339. _get_counterpart_host(host)), partial)
  3340. conflicting = self.get_conflicting_hosts()
  3341. if conflicting:
  3342. yield (
  3343. 'The following Git hosts have differing credentials from their '
  3344. 'Gerrit counterparts',
  3345. self._format_hosts(
  3346. conflicting, lambda host: '%s vs %s' % tuple(
  3347. self._get_git_gerrit_identity_pairs()[host])),
  3348. conflicting)
  3349. def find_and_report_problems(self):
  3350. """Returns True if there was at least one problem, else False."""
  3351. found = False
  3352. bad_hosts = set()
  3353. for title, sublines, hosts in self._find_problems():
  3354. if not found:
  3355. found = True
  3356. print('\n\n.gitcookies problem report:\n')
  3357. bad_hosts.update(hosts or [])
  3358. print(' %s%s' % (title, (':' if sublines else '')))
  3359. if sublines:
  3360. print()
  3361. print(' %s' % '\n '.join(sublines))
  3362. print()
  3363. if bad_hosts:
  3364. assert found
  3365. print(
  3366. ' You can manually remove corresponding lines in your %s file and '
  3367. 'visit the following URLs with correct account to generate '
  3368. 'correct credential lines:\n' %
  3369. gerrit_util.CookiesAuthenticator.get_gitcookies_path())
  3370. print(' %s' % '\n '.join(
  3371. sorted(
  3372. set(gerrit_util.CookiesAuthenticator().get_new_password_url(
  3373. _canonical_git_googlesource_host(host))
  3374. for host in bad_hosts))))
  3375. return found
  3376. @metrics.collector.collect_metrics('git cl creds-check')
  3377. def CMDcreds_check(parser, args):
  3378. """Checks credentials and suggests changes."""
  3379. _, _ = parser.parse_args(args)
  3380. if newauth.Enabled():
  3381. ConfigureGitAuth()
  3382. return 0
  3383. if newauth.ExplicitlyDisabled():
  3384. ClearGitRepoAuth()
  3385. # Code below checks .gitcookies. Abort if using something else.
  3386. auth_name, _ = gerrit_util.debug_auth()
  3387. if auth_name != "CookiesAuthenticator":
  3388. message = (
  3389. 'This command is not designed for bot environment. It checks '
  3390. '~/.gitcookies file not generally used on bots.')
  3391. # TODO(crbug.com/1059384): Automatically detect when running on
  3392. # cloudtop.
  3393. if auth_name == "GceAuthenticator":
  3394. message += (
  3395. '\n'
  3396. 'If you need to run this on GCE or a cloudtop instance, '
  3397. 'export SKIP_GCE_AUTH_FOR_GIT=1 in your env.')
  3398. DieWithError(message)
  3399. checker = _GitCookiesChecker()
  3400. checker.ensure_configured_gitcookies()
  3401. checker.print_current_creds()
  3402. if not checker.find_and_report_problems():
  3403. print('\nNo problems detected in your .gitcookies file.')
  3404. return 0
  3405. return 1
  3406. @metrics.collector.collect_metrics('git cl baseurl')
  3407. def CMDbaseurl(parser, args):
  3408. """Gets or sets base-url for this branch."""
  3409. if gclient_utils.IsEnvCog():
  3410. print('baseurl command is not supported in non-git environment.',
  3411. file=sys.stderr)
  3412. return 1
  3413. _, args = parser.parse_args(args)
  3414. branchref = scm.GIT.GetBranchRef(settings.GetRoot())
  3415. branch = scm.GIT.ShortBranchName(branchref)
  3416. if not args:
  3417. print('Current base-url:')
  3418. url = scm.GIT.GetConfig(settings.GetRoot(), f'branch.{branch}.base-url')
  3419. if url is None:
  3420. raise ValueError('Missing base URL.')
  3421. return url
  3422. print('Setting base-url to %s' % args[0])
  3423. scm.GIT.SetConfig(settings.GetRoot(), f'branch.{branch}.base-url', args[0])
  3424. return 0
  3425. def color_for_status(status):
  3426. """Maps a Changelist status to color, for CMDstatus and other tools."""
  3427. BOLD = '\033[1m'
  3428. return {
  3429. 'unsent': BOLD + Fore.YELLOW,
  3430. 'waiting': BOLD + Fore.RED,
  3431. 'reply': BOLD + Fore.YELLOW,
  3432. 'not lgtm': BOLD + Fore.RED,
  3433. 'lgtm': BOLD + Fore.GREEN,
  3434. 'commit': BOLD + Fore.MAGENTA,
  3435. 'closed': BOLD + Fore.CYAN,
  3436. 'error': BOLD + Fore.WHITE,
  3437. }.get(status, Fore.WHITE)
  3438. def get_cl_statuses(changes: List[Changelist],
  3439. fine_grained,
  3440. max_processes=None):
  3441. """Returns a blocking iterable of (cl, status) for given branches.
  3442. If fine_grained is true, this will fetch CL statuses from the server.
  3443. Otherwise, simply indicate if there's a matching url for the given branches.
  3444. If max_processes is specified, it is used as the maximum number of processes
  3445. to spawn to fetch CL status from the server. Otherwise 1 process per branch
  3446. is spawned, up to max of gerrit_util.MAX_CONCURRENT_CONNECTION.
  3447. See GetStatus() for a list of possible statuses.
  3448. """
  3449. if not changes:
  3450. return
  3451. if not fine_grained:
  3452. # Fast path which doesn't involve querying codereview servers.
  3453. # Do not use get_approving_reviewers(), since it requires an HTTP
  3454. # request.
  3455. for cl in changes:
  3456. yield (cl, 'waiting' if cl.GetIssueURL() else 'error')
  3457. return
  3458. # First, sort out authentication issues.
  3459. logging.debug('ensuring credentials exist')
  3460. for cl in changes:
  3461. cl.EnsureAuthenticated(force=False)
  3462. def fetch(cl):
  3463. try:
  3464. return (cl, cl.GetStatus())
  3465. except:
  3466. # See http://crbug.com/629863.
  3467. logging.exception('failed to fetch status for cl %s:',
  3468. cl.GetIssue())
  3469. raise
  3470. threads_count = min(gerrit_util.MAX_CONCURRENT_CONNECTION, len(changes))
  3471. if max_processes:
  3472. threads_count = max(1, min(threads_count, max_processes))
  3473. logging.debug('querying %d CLs using %d threads', len(changes),
  3474. threads_count)
  3475. pool = multiprocessing.pool.ThreadPool(threads_count)
  3476. fetched_cls = set()
  3477. try:
  3478. it = pool.imap_unordered(fetch, changes).__iter__()
  3479. while True:
  3480. try:
  3481. cl, status = it.next(timeout=5)
  3482. except (multiprocessing.TimeoutError, StopIteration):
  3483. break
  3484. fetched_cls.add(cl)
  3485. yield cl, status
  3486. finally:
  3487. pool.close()
  3488. # Add any branches that failed to fetch.
  3489. for cl in set(changes) - fetched_cls:
  3490. yield (cl, 'error')
  3491. def upload_branch_deps(cl, args, force=False):
  3492. """Uploads CLs of local branches that are dependents of the current branch.
  3493. If the local branch dependency tree looks like:
  3494. test1 -> test2.1 -> test3.1
  3495. -> test3.2
  3496. -> test2.2 -> test3.3
  3497. and you run "git cl upload --dependencies" from test1 then "git cl upload" is
  3498. run on the dependent branches in this order:
  3499. test2.1, test3.1, test3.2, test2.2, test3.3
  3500. Note: This function does not rebase your local dependent branches. Use it
  3501. when you make a change to the parent branch that will not conflict
  3502. with its dependent branches, and you would like their dependencies
  3503. updated in Gerrit.
  3504. If the new stacked change flow is used, and ancestor diverged, upload
  3505. will fail. To recover, `git rebase-update [-n]` must be executed.
  3506. """
  3507. if git_common.is_dirty_git_tree('upload-branch-deps'):
  3508. return 1
  3509. root_branch = cl.GetBranch()
  3510. if root_branch is None:
  3511. DieWithError('Can\'t find dependent branches from detached HEAD state. '
  3512. 'Get on a branch!')
  3513. if not cl.GetIssue():
  3514. DieWithError(
  3515. 'Current branch does not have an uploaded CL. We cannot set '
  3516. 'patchset dependencies without an uploaded CL.')
  3517. branches = RunGit([
  3518. 'for-each-ref', '--format=%(refname:short) %(upstream:short)',
  3519. 'refs/heads'
  3520. ])
  3521. if not branches:
  3522. print('No local branches found.')
  3523. return 0
  3524. # Create a dictionary of all local branches to the branches that are
  3525. # dependent on it.
  3526. tracked_to_dependents = collections.defaultdict(list)
  3527. for b in branches.splitlines():
  3528. tokens = b.split()
  3529. if len(tokens) == 2:
  3530. branch_name, tracked = tokens
  3531. tracked_to_dependents[tracked].append(branch_name)
  3532. print()
  3533. print('The dependent local branches of %s are:' % root_branch)
  3534. dependents = []
  3535. def traverse_dependents_preorder(branch, padding=''):
  3536. dependents_to_process = tracked_to_dependents.get(branch, [])
  3537. padding += ' '
  3538. for dependent in dependents_to_process:
  3539. print('%s%s' % (padding, dependent))
  3540. dependents.append(dependent)
  3541. traverse_dependents_preorder(dependent, padding)
  3542. traverse_dependents_preorder(root_branch)
  3543. print()
  3544. if not dependents:
  3545. print('There are no dependent local branches for %s' % root_branch)
  3546. return 0
  3547. # Record all dependents that failed to upload.
  3548. failures = {}
  3549. # Go through all dependents, checkout the branch and upload.
  3550. try:
  3551. for dependent_branch in dependents:
  3552. print()
  3553. print('--------------------------------------')
  3554. print('Running "git cl upload" from %s:' % dependent_branch)
  3555. RunGit(['checkout', '-q', dependent_branch])
  3556. print()
  3557. try:
  3558. if CMDupload(OptionParser(), args) != 0:
  3559. print('Upload failed for %s!' % dependent_branch)
  3560. failures[dependent_branch] = 1
  3561. except Exception as e:
  3562. print(f"Unexpected exception: {e}")
  3563. failures[dependent_branch] = 1
  3564. print()
  3565. finally:
  3566. # Swap back to the original root branch.
  3567. RunGit(['checkout', '-q', root_branch])
  3568. print()
  3569. print('Upload complete for dependent branches!')
  3570. for dependent_branch in dependents:
  3571. upload_status = 'failed' if failures.get(
  3572. dependent_branch) else 'succeeded'
  3573. print(' %s : %s' % (dependent_branch, upload_status))
  3574. print()
  3575. return 0
  3576. def GetArchiveTagForBranch(issue_num, branch_name, existing_tags, pattern):
  3577. """Given a proposed tag name, returns a tag name that is guaranteed to be
  3578. unique. If 'foo' is proposed but already exists, then 'foo-2' is used,
  3579. or 'foo-3', and so on."""
  3580. proposed_tag = pattern.format(**{'issue': issue_num, 'branch': branch_name})
  3581. for suffix_num in itertools.count(1):
  3582. if suffix_num == 1:
  3583. to_check = proposed_tag
  3584. else:
  3585. to_check = '%s-%d' % (proposed_tag, suffix_num)
  3586. if to_check not in existing_tags:
  3587. return to_check
  3588. @metrics.collector.collect_metrics('git cl archive')
  3589. def CMDarchive(parser, args):
  3590. """Archives and deletes branches associated with closed changelists."""
  3591. if gclient_utils.IsEnvCog():
  3592. print('archive command is not supported in non-git environment.',
  3593. file=sys.stderr)
  3594. return 1
  3595. parser.add_option(
  3596. '-j',
  3597. '--maxjobs',
  3598. action='store',
  3599. type=int,
  3600. help='The maximum number of jobs to use when retrieving review status.')
  3601. parser.add_option('-f',
  3602. '--force',
  3603. action='store_true',
  3604. help='Bypasses the confirmation prompt.')
  3605. parser.add_option('-d',
  3606. '--dry-run',
  3607. action='store_true',
  3608. help='Skip the branch tagging and removal steps.')
  3609. parser.add_option('-t',
  3610. '--notags',
  3611. action='store_true',
  3612. help='Do not tag archived branches. '
  3613. 'Note: local commit history may be lost.')
  3614. parser.add_option('-p',
  3615. '--pattern',
  3616. default='git-cl-archived-{issue}-{branch}',
  3617. help='Format string for archive tags. '
  3618. 'E.g. \'archived-{issue}-{branch}\'.')
  3619. options, args = parser.parse_args(args)
  3620. if args:
  3621. parser.error('Unsupported args: %s' % ' '.join(args))
  3622. branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
  3623. if not branches:
  3624. return 0
  3625. tags = RunGit(['for-each-ref', '--format=%(refname)', 'refs/tags'
  3626. ]).splitlines() or []
  3627. tags = [t.split('/')[-1] for t in tags]
  3628. print('Finding all branches associated with closed issues...')
  3629. changes = [Changelist(branchref=b) for b in branches.splitlines()]
  3630. alignment = max(5, max(len(c.GetBranch()) for c in changes))
  3631. statuses = get_cl_statuses(changes,
  3632. fine_grained=True,
  3633. max_processes=options.maxjobs)
  3634. proposal = [(cl.GetBranch(),
  3635. GetArchiveTagForBranch(cl.GetIssue(), cl.GetBranch(), tags,
  3636. options.pattern))
  3637. for cl, status in statuses
  3638. if status in ('closed', 'rietveld-not-supported')]
  3639. proposal.sort()
  3640. if not proposal:
  3641. print('No branches with closed codereview issues found.')
  3642. return 0
  3643. current_branch = scm.GIT.GetBranch(settings.GetRoot())
  3644. print('\nBranches with closed issues that will be archived:\n')
  3645. if options.notags:
  3646. for next_item in proposal:
  3647. print(' ' + next_item[0])
  3648. else:
  3649. print('%*s | %s' % (alignment, 'Branch name', 'Archival tag name'))
  3650. for next_item in proposal:
  3651. print('%*s %s' % (alignment, next_item[0], next_item[1]))
  3652. # Quit now on precondition failure or if instructed by the user, either
  3653. # via an interactive prompt or by command line flags.
  3654. if options.dry_run:
  3655. print('\nNo changes were made (dry run).\n')
  3656. return 0
  3657. if any(branch == current_branch for branch, _ in proposal):
  3658. print('You are currently on a branch \'%s\' which is associated with a '
  3659. 'closed codereview issue, so archive cannot proceed. Please '
  3660. 'checkout another branch and run this command again.' %
  3661. current_branch)
  3662. return 1
  3663. if not options.force:
  3664. answer = gclient_utils.AskForData(
  3665. '\nProceed with deletion (Y/n)? ').lower()
  3666. if answer not in ('y', ''):
  3667. print('Aborted.')
  3668. return 1
  3669. for branch, tagname in proposal:
  3670. if not options.notags:
  3671. RunGit(['tag', tagname, branch])
  3672. if RunGitWithCode(['branch', '-D', branch])[0] != 0:
  3673. # Clean up the tag if we failed to delete the branch.
  3674. RunGit(['tag', '-d', tagname])
  3675. print('\nJob\'s done!')
  3676. return 0
  3677. @metrics.collector.collect_metrics('git cl status')
  3678. def CMDstatus(parser, args):
  3679. """Show status of changelists.
  3680. Colors are used to tell the state of the CL unless --fast is used:
  3681. - Blue waiting for review
  3682. - Yellow waiting for you to reply to review, or not yet sent
  3683. - Green LGTM'ed
  3684. - Red 'not LGTM'ed
  3685. - Magenta in the CQ
  3686. - Cyan was committed, branch can be deleted
  3687. - White error, or unknown status
  3688. Also see 'git cl comments'.
  3689. """
  3690. if gclient_utils.IsEnvCog():
  3691. print(
  3692. 'status command is not supported. Please go to the Gerrit CL '
  3693. 'page to check the CL status directly.',
  3694. file=sys.stderr)
  3695. return 1
  3696. parser.add_option('--no-branch-color',
  3697. action='store_true',
  3698. help='Disable colorized branch names')
  3699. parser.add_option(
  3700. '--field', help='print only specific field (desc|id|patch|status|url)')
  3701. parser.add_option('-f',
  3702. '--fast',
  3703. action='store_true',
  3704. help='Do not retrieve review status')
  3705. parser.add_option(
  3706. '-j',
  3707. '--maxjobs',
  3708. action='store',
  3709. type=int,
  3710. help='The maximum number of jobs to use when retrieving review status')
  3711. parser.add_option(
  3712. '-i',
  3713. '--issue',
  3714. type=int,
  3715. help='Operate on this issue instead of the current branch\'s implicit '
  3716. 'issue. Requires --field to be set.')
  3717. parser.add_option('-d',
  3718. '--date-order',
  3719. action='store_true',
  3720. help='Order branches by committer date.')
  3721. options, args = parser.parse_args(args)
  3722. if args:
  3723. parser.error('Unsupported args: %s' % args)
  3724. if options.issue is not None and not options.field:
  3725. parser.error('--field must be given when --issue is set.')
  3726. if options.field:
  3727. cl = Changelist(issue=options.issue)
  3728. if options.field.startswith('desc'):
  3729. if cl.GetIssue():
  3730. print(cl.FetchDescription())
  3731. elif options.field == 'id':
  3732. issueid = cl.GetIssue()
  3733. if issueid:
  3734. print(issueid)
  3735. elif options.field == 'patch':
  3736. patchset = cl.GetMostRecentPatchset()
  3737. if patchset:
  3738. print(patchset)
  3739. elif options.field == 'status':
  3740. print(cl.GetStatus())
  3741. elif options.field == 'url':
  3742. url = cl.GetIssueURL()
  3743. if url:
  3744. print(url)
  3745. return 0
  3746. branches = RunGit([
  3747. 'for-each-ref', '--format=%(refname) %(committerdate:unix)',
  3748. 'refs/heads'
  3749. ])
  3750. if not branches:
  3751. print('No local branch found.')
  3752. return 0
  3753. changes = [
  3754. Changelist(branchref=b, commit_date=ct)
  3755. for b, ct in map(lambda line: line.split(' '), branches.splitlines())
  3756. ]
  3757. print('Branches associated with reviews:')
  3758. output = get_cl_statuses(changes,
  3759. fine_grained=not options.fast,
  3760. max_processes=options.maxjobs)
  3761. current_branch = scm.GIT.GetBranch(settings.GetRoot())
  3762. def FormatBranchName(branch, colorize=False):
  3763. """Simulates 'git branch' behavior. Colorizes and prefixes branch name with
  3764. an asterisk when it is the current branch."""
  3765. asterisk = ""
  3766. color = Fore.RESET
  3767. if branch == current_branch:
  3768. asterisk = "* "
  3769. color = Fore.GREEN
  3770. branch_name = scm.GIT.ShortBranchName(branch)
  3771. if colorize:
  3772. return asterisk + color + branch_name + Fore.RESET
  3773. return asterisk + branch_name
  3774. branch_statuses = {}
  3775. alignment = max(5,
  3776. max(len(FormatBranchName(c.GetBranch())) for c in changes))
  3777. if options.date_order or settings.IsStatusCommitOrderByDate():
  3778. sorted_changes = sorted(changes,
  3779. key=lambda c: c.GetCommitDate(),
  3780. reverse=True)
  3781. else:
  3782. sorted_changes = sorted(changes, key=lambda c: c.GetBranch())
  3783. for cl in sorted_changes:
  3784. branch = cl.GetBranch()
  3785. while branch not in branch_statuses:
  3786. c, status = next(output)
  3787. branch_statuses[c.GetBranch()] = status
  3788. status = branch_statuses.pop(branch)
  3789. url = cl.GetIssueURL(short=True)
  3790. if url and (not status or status == 'error'):
  3791. # The issue probably doesn't exist anymore.
  3792. url += ' (broken)'
  3793. color = color_for_status(status)
  3794. # Turn off bold as well as colors.
  3795. END = '\033[0m'
  3796. reset = Fore.RESET + END
  3797. if not setup_color.IS_TTY:
  3798. color = ''
  3799. reset = ''
  3800. status_str = '(%s)' % status if status else ''
  3801. branch_display = FormatBranchName(branch)
  3802. padding = ' ' * (alignment - len(branch_display))
  3803. if not options.no_branch_color:
  3804. branch_display = FormatBranchName(branch, colorize=True)
  3805. print(' %s : %s%s %s%s' %
  3806. (padding + branch_display, color, url, status_str, reset))
  3807. print()
  3808. print('Current branch: %s' % current_branch)
  3809. for cl in changes:
  3810. if cl.GetBranch() == current_branch:
  3811. break
  3812. if not cl.GetIssue():
  3813. print('No issue assigned.')
  3814. return 0
  3815. print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()))
  3816. if not options.fast:
  3817. print('Issue description:')
  3818. print(cl.FetchDescription(pretty=True))
  3819. return 0
  3820. def colorize_CMDstatus_doc():
  3821. """To be called once in main() to add colors to git cl status help."""
  3822. colors = [i for i in dir(Fore) if i[0].isupper()]
  3823. def colorize_line(line):
  3824. for color in colors:
  3825. if color in line.upper():
  3826. # Extract whitespace first and the leading '-'.
  3827. indent = len(line) - len(line.lstrip(' ')) + 1
  3828. return line[:indent] + getattr(
  3829. Fore, color) + line[indent:] + Fore.RESET
  3830. return line
  3831. lines = CMDstatus.__doc__.splitlines()
  3832. CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines)
  3833. def write_json(path, contents):
  3834. if path == '-':
  3835. json.dump(contents, sys.stdout)
  3836. else:
  3837. with open(path, 'w') as f:
  3838. json.dump(contents, f)
  3839. @subcommand.usage('[issue_number]')
  3840. @metrics.collector.collect_metrics('git cl issue')
  3841. def CMDissue(parser, args):
  3842. """Sets or displays the current code review issue number.
  3843. Pass issue number 0 to clear the current issue.
  3844. """
  3845. if gclient_utils.IsEnvCog():
  3846. print(
  3847. 'issue command is not supported. CL number is available in the '
  3848. 'primary side bar at the bottom of your editor. Setting the CL '
  3849. 'number is not supported, you can open a new workspace from the '
  3850. 'Gerrit CL directly.',
  3851. file=sys.stderr)
  3852. return 1
  3853. parser.add_option('-r',
  3854. '--reverse',
  3855. action='store_true',
  3856. help='Lookup the branch(es) for the specified issues. If '
  3857. 'no issues are specified, all branches with mapped '
  3858. 'issues will be listed.')
  3859. parser.add_option('--json',
  3860. help='Path to JSON output file, or "-" for stdout.')
  3861. options, args = parser.parse_args(args)
  3862. if options.reverse:
  3863. branches = RunGit(['for-each-ref', 'refs/heads',
  3864. '--format=%(refname)']).splitlines()
  3865. # Reverse issue lookup.
  3866. issue_branch_map = {}
  3867. git_config = {}
  3868. for name, val in scm.GIT.YieldConfigRegexp(
  3869. settings.GetRoot(), re.compile(r'branch\..*issue')):
  3870. git_config[name] = val
  3871. for branch in branches:
  3872. issue = git_config.get(
  3873. 'branch.%s.%s' %
  3874. (scm.GIT.ShortBranchName(branch), ISSUE_CONFIG_KEY))
  3875. if issue:
  3876. issue_branch_map.setdefault(int(issue), []).append(branch)
  3877. if not args:
  3878. args = sorted(issue_branch_map.keys())
  3879. result = {}
  3880. for issue in args:
  3881. try:
  3882. issue_num = int(issue)
  3883. except ValueError:
  3884. print('ERROR cannot parse issue number: %s' % issue,
  3885. file=sys.stderr)
  3886. continue
  3887. result[issue_num] = issue_branch_map.get(issue_num)
  3888. print('Branch for issue number %s: %s' % (issue, ', '.join(
  3889. issue_branch_map.get(issue_num) or ('None', ))))
  3890. if options.json:
  3891. write_json(options.json, result)
  3892. return 0
  3893. if len(args) > 0:
  3894. issue = ParseIssueNumberArgument(args[0])
  3895. if not issue.valid:
  3896. DieWithError(
  3897. 'Pass a url or number to set the issue, 0 to unset it, '
  3898. 'or no argument to list it.\n'
  3899. 'Maybe you want to run git cl status?')
  3900. cl = Changelist()
  3901. cl.SetIssue(issue.issue)
  3902. else:
  3903. cl = Changelist()
  3904. print('Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL()))
  3905. if options.json:
  3906. write_json(
  3907. options.json, {
  3908. 'gerrit_host': cl.GetGerritHost(),
  3909. 'gerrit_project': cl.GetGerritProject(),
  3910. 'issue_url': cl.GetIssueURL(),
  3911. 'issue': cl.GetIssue(),
  3912. })
  3913. return 0
  3914. @metrics.collector.collect_metrics('git cl comments')
  3915. def CMDcomments(parser, args):
  3916. """Shows or posts review comments for any changelist."""
  3917. if gclient_utils.IsEnvCog():
  3918. print(
  3919. 'comments command is not supported in non-git environment. '
  3920. 'Comments on the CL should show up inline in your editor. To '
  3921. 'post comments, please visit Gerrit CL page.',
  3922. file=sys.stderr)
  3923. return 1
  3924. parser.add_option('-a',
  3925. '--add-comment',
  3926. dest='comment',
  3927. help='comment to add to an issue')
  3928. parser.add_option('-p',
  3929. '--publish',
  3930. action='store_true',
  3931. help='marks CL as ready and sends comment to reviewers')
  3932. parser.add_option('-i',
  3933. '--issue',
  3934. dest='issue',
  3935. help='review issue id (defaults to current issue).')
  3936. parser.add_option('-m',
  3937. '--machine-readable',
  3938. dest='readable',
  3939. action='store_false',
  3940. default=True,
  3941. help='output comments in a format compatible with '
  3942. 'editor parsing')
  3943. parser.add_option('-j',
  3944. '--json-file',
  3945. help='File to write JSON summary to, or "-" for stdout')
  3946. options, args = parser.parse_args(args)
  3947. issue = None
  3948. if options.issue:
  3949. try:
  3950. issue = int(options.issue)
  3951. except ValueError:
  3952. DieWithError('A review issue ID is expected to be a number.')
  3953. cl = Changelist(issue=issue)
  3954. if options.comment:
  3955. cl.AddComment(options.comment, options.publish)
  3956. return 0
  3957. summary = sorted(cl.GetCommentsSummary(readable=options.readable),
  3958. key=lambda c: c.date)
  3959. for comment in summary:
  3960. if comment.disapproval:
  3961. color = Fore.RED
  3962. elif comment.approval:
  3963. color = Fore.GREEN
  3964. elif comment.sender == cl.GetIssueOwner():
  3965. color = Fore.MAGENTA
  3966. elif comment.autogenerated:
  3967. color = Fore.CYAN
  3968. else:
  3969. color = Fore.BLUE
  3970. print('\n%s%s %s%s\n%s' %
  3971. (color, comment.date.strftime('%Y-%m-%d %H:%M:%S UTC'),
  3972. comment.sender, Fore.RESET, '\n'.join(
  3973. ' ' + l for l in comment.message.strip().splitlines())))
  3974. if options.json_file:
  3975. def pre_serialize(c):
  3976. dct = c._asdict().copy()
  3977. dct['date'] = dct['date'].strftime('%Y-%m-%d %H:%M:%S.%f')
  3978. return dct
  3979. write_json(options.json_file, [pre_serialize(x) for x in summary])
  3980. return 0
  3981. @subcommand.usage('[codereview url or issue id]')
  3982. @metrics.collector.collect_metrics('git cl description')
  3983. def CMDdescription(parser, args):
  3984. """Brings up the editor for the current CL's description."""
  3985. if gclient_utils.IsEnvCog():
  3986. print(
  3987. 'description command is not supported. Please use "Gerrit: Edit '
  3988. 'Change Information" functionality in the command palatte to edit '
  3989. 'the CL description.',
  3990. file=sys.stderr)
  3991. return 1
  3992. parser.add_option(
  3993. '-d',
  3994. '--display',
  3995. action='store_true',
  3996. help='Display the description instead of opening an editor')
  3997. parser.add_option(
  3998. '-n',
  3999. '--new-description',
  4000. help='New description to set for this issue (- for stdin, '
  4001. '+ to load from local commit HEAD)')
  4002. parser.add_option('-f',
  4003. '--force',
  4004. action='store_true',
  4005. help='Delete any unpublished Gerrit edits for this issue '
  4006. 'without prompting')
  4007. options, args = parser.parse_args(args)
  4008. target_issue_arg = None
  4009. if len(args) > 0:
  4010. target_issue_arg = ParseIssueNumberArgument(args[0])
  4011. if not target_issue_arg.valid:
  4012. parser.error('Invalid issue ID or URL.')
  4013. kwargs = {}
  4014. if target_issue_arg:
  4015. kwargs['issue'] = target_issue_arg.issue
  4016. kwargs['codereview_host'] = target_issue_arg.hostname
  4017. cl = Changelist(**kwargs)
  4018. if not cl.GetIssue():
  4019. DieWithError('This branch has no associated changelist.')
  4020. if args and not args[0].isdigit():
  4021. logging.info('canonical issue/change URL: %s\n', cl.GetIssueURL())
  4022. description = ChangeDescription(cl.FetchDescription())
  4023. if options.display:
  4024. print(description.description)
  4025. return 0
  4026. if options.new_description:
  4027. text = options.new_description
  4028. if text == '-':
  4029. text = '\n'.join(l.rstrip() for l in sys.stdin)
  4030. elif text == '+':
  4031. base_branch = cl.GetCommonAncestorWithUpstream()
  4032. text = _create_description_from_log([base_branch])
  4033. description.set_description(text)
  4034. else:
  4035. description.prompt()
  4036. if cl.FetchDescription().strip() != description.description:
  4037. cl.UpdateDescription(description.description, force=options.force)
  4038. return 0
  4039. def FindFilesForLint(options, args):
  4040. """Returns the base folder and a list of files to lint."""
  4041. files = []
  4042. cwd = os.getcwd()
  4043. if len(args) > 0:
  4044. # If file paths are given in positional args, run the lint tools
  4045. # against them without using git commands. This allows git_cl.py
  4046. # runnable against any files even out of git checkouts.
  4047. for fn in args:
  4048. if os.path.isfile(fn):
  4049. files.append(fn)
  4050. else:
  4051. print('%s is not a file' % fn)
  4052. return None, None
  4053. elif gclient_utils.IsEnvCog():
  4054. print('Error: missing files to lint')
  4055. return None, None
  4056. else:
  4057. # If file names are omitted, use the git APIs to find the files to lint.
  4058. include_regex = re.compile(settings.GetLintRegex())
  4059. ignore_regex = re.compile(settings.GetLintIgnoreRegex())
  4060. cl = Changelist()
  4061. cwd = settings.GetRoot()
  4062. affectedFiles = cl.GetAffectedFiles(cl.GetCommonAncestorWithUpstream())
  4063. if not affectedFiles:
  4064. print('Cannot lint an empty CL')
  4065. return None, None
  4066. for fn in affectedFiles:
  4067. if not include_regex.match(fn):
  4068. print('Skipping file %s' % fn)
  4069. elif ignore_regex.match(fn):
  4070. print('Ignoring file %s' % fn)
  4071. else:
  4072. files.append(fn)
  4073. return cwd, files
  4074. @subcommand.usage('[files ...]')
  4075. @metrics.collector.collect_metrics('git cl lint')
  4076. def CMDlint(parser, args):
  4077. """Runs cpplint on the current changelist or given files.
  4078. positional arguments:
  4079. files Files to lint. If omitted in the current git checkout, it
  4080. will run cpplint against all the affected files. If it is
  4081. not executed in git checkouts, files to lint must be
  4082. provided.
  4083. """
  4084. parser.add_option(
  4085. '--filter',
  4086. action='append',
  4087. metavar='-x,+y',
  4088. help='Comma-separated list of cpplint\'s category-filters')
  4089. options, args = parser.parse_args(args)
  4090. root_path, files = FindFilesForLint(options, args)
  4091. if files is None:
  4092. return 1
  4093. # Access to a protected member _XX of a client class
  4094. # pylint: disable=protected-access
  4095. try:
  4096. import cpplint
  4097. import cpplint_chromium
  4098. # Process cpplint arguments, if any.
  4099. filters = presubmit_canned_checks.GetCppLintFilters(options.filter)
  4100. command = ['--filter=' + ','.join(filters)]
  4101. command.extend(files)
  4102. files_to_lint = cpplint.ParseArguments(command)
  4103. except ImportError:
  4104. print(
  4105. 'Your depot_tools is missing cpplint.py and/or cpplint_chromium.py.'
  4106. )
  4107. return 1
  4108. # Change the current working directory before calling lint so that it
  4109. # shows the correct base.
  4110. previous_cwd = os.getcwd()
  4111. try:
  4112. os.chdir(root_path)
  4113. extra_check_functions = [
  4114. cpplint_chromium.CheckPointerDeclarationWhitespace
  4115. ]
  4116. for file in files_to_lint:
  4117. cpplint.ProcessFile(file, cpplint._cpplint_state.verbose_level,
  4118. extra_check_functions)
  4119. finally:
  4120. os.chdir(previous_cwd)
  4121. print('Total errors found: %d\n' % cpplint._cpplint_state.error_count)
  4122. if cpplint._cpplint_state.error_count != 0:
  4123. return 1
  4124. return 0
  4125. @metrics.collector.collect_metrics('git cl presubmit')
  4126. @subcommand.usage('[base branch]')
  4127. def CMDpresubmit(parser, args):
  4128. """Runs presubmit tests on the current changelist."""
  4129. if gclient_utils.IsEnvCog():
  4130. # TODO - crbug/336555565: give user more instructions on how to
  4131. # trigger presubmit in Cog once the UX is finalized.
  4132. print('presubmit command is not supported in non-git environment.',
  4133. file=sys.stderr)
  4134. return 1
  4135. parser.add_option('-u',
  4136. '--upload',
  4137. action='store_true',
  4138. help='Run upload hook instead of the push hook')
  4139. parser.add_option('-f',
  4140. '--force',
  4141. action='store_true',
  4142. help='Run checks even if tree is dirty')
  4143. parser.add_option(
  4144. '--all',
  4145. action='store_true',
  4146. help='Run checks against all files, not just modified ones')
  4147. parser.add_option('--files',
  4148. nargs=1,
  4149. help='Semicolon-separated list of files to be marked as '
  4150. 'modified when executing presubmit or post-upload hooks. '
  4151. 'fnmatch wildcards can also be used.')
  4152. parser.add_option(
  4153. '--parallel',
  4154. action='store_true',
  4155. help='Run all tests specified by input_api.RunTests in all '
  4156. 'PRESUBMIT files in parallel.')
  4157. parser.add_option('--resultdb',
  4158. action='store_true',
  4159. help='Run presubmit checks in the ResultSink environment '
  4160. 'and send results to the ResultDB database.')
  4161. parser.add_option('--realm', help='LUCI realm if reporting to ResultDB')
  4162. parser.add_option('-j',
  4163. '--json',
  4164. help='File to write JSON results to, or "-" for stdout')
  4165. options, args = parser.parse_args(args)
  4166. if not options.force and git_common.is_dirty_git_tree('presubmit'):
  4167. print('use --force to check even if tree is dirty.')
  4168. return 1
  4169. cl = Changelist()
  4170. if args:
  4171. base_branch = args[0]
  4172. else:
  4173. # Default to diffing against the common ancestor of the upstream branch.
  4174. base_branch = cl.GetCommonAncestorWithUpstream()
  4175. start = time.time()
  4176. try:
  4177. if not 'PRESUBMIT_SKIP_NETWORK' in os.environ and cl.GetIssue():
  4178. description = cl.FetchDescription()
  4179. else:
  4180. description = _create_description_from_log([base_branch])
  4181. except Exception as e:
  4182. print('Failed to fetch CL description - %s' % str(e))
  4183. description = _create_description_from_log([base_branch])
  4184. elapsed = time.time() - start
  4185. if elapsed > 5:
  4186. print('%.1f s to get CL description.' % elapsed)
  4187. if not base_branch:
  4188. if not options.force:
  4189. print('use --force to check even when not on a branch.')
  4190. return 1
  4191. base_branch = 'HEAD'
  4192. result = cl.RunHook(committing=not options.upload,
  4193. may_prompt=False,
  4194. verbose=options.verbose,
  4195. parallel=options.parallel,
  4196. upstream=base_branch,
  4197. description=description,
  4198. all_files=options.all,
  4199. files=options.files,
  4200. resultdb=options.resultdb,
  4201. realm=options.realm)
  4202. if options.json:
  4203. write_json(options.json, result)
  4204. return 0
  4205. def GenerateGerritChangeId(message):
  4206. """Returns the Change ID footer value (Ixxxxxx...xxx).
  4207. Works the same way as
  4208. https://gerrit-review.googlesource.com/tools/hooks/commit-msg
  4209. but can be called on demand on all platforms.
  4210. The basic idea is to generate git hash of a state of the tree, original
  4211. commit message, author/committer info and timestamps.
  4212. """
  4213. lines = []
  4214. tree_hash = RunGitSilent(['write-tree'])
  4215. lines.append('tree %s' % tree_hash.strip())
  4216. code, parent = RunGitWithCode(['rev-parse', 'HEAD~0'],
  4217. suppress_stderr=False)
  4218. if code == 0:
  4219. lines.append('parent %s' % parent.strip())
  4220. author = RunGitSilent(['var', 'GIT_AUTHOR_IDENT'])
  4221. lines.append('author %s' % author.strip())
  4222. committer = RunGitSilent(['var', 'GIT_COMMITTER_IDENT'])
  4223. lines.append('committer %s' % committer.strip())
  4224. lines.append('')
  4225. # Note: Gerrit's commit-hook actually cleans message of some lines and
  4226. # whitespace. This code is not doing this, but it clearly won't decrease
  4227. # entropy.
  4228. lines.append(message)
  4229. change_hash = RunCommand(['git', 'hash-object', '-t', 'commit', '--stdin'],
  4230. stdin=('\n'.join(lines)).encode())
  4231. return 'I%s' % change_hash.strip()
  4232. def GetTargetRef(remote, remote_branch, target_branch):
  4233. """Computes the remote branch ref to use for the CL.
  4234. Args:
  4235. remote (str): The git remote for the CL.
  4236. remote_branch (str): The git remote branch for the CL.
  4237. target_branch (str): The target branch specified by the user.
  4238. """
  4239. if not (remote and remote_branch):
  4240. return None
  4241. if target_branch:
  4242. # Canonicalize branch references to the equivalent local full symbolic
  4243. # refs, which are then translated into the remote full symbolic refs
  4244. # below.
  4245. if '/' not in target_branch:
  4246. remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch)
  4247. else:
  4248. prefix_replacements = (
  4249. ('^((refs/)?remotes/)?branch-heads/',
  4250. 'refs/remotes/branch-heads/'),
  4251. ('^((refs/)?remotes/)?%s/' % remote,
  4252. 'refs/remotes/%s/' % remote),
  4253. ('^(refs/)?heads/', 'refs/remotes/%s/' % remote),
  4254. )
  4255. match = None
  4256. for regex, replacement in prefix_replacements:
  4257. match = re.search(regex, target_branch)
  4258. if match:
  4259. remote_branch = target_branch.replace(
  4260. match.group(0), replacement)
  4261. break
  4262. if not match:
  4263. # This is a branch path but not one we recognize; use as-is.
  4264. remote_branch = target_branch
  4265. # pylint: disable=consider-using-get
  4266. elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS:
  4267. # pylint: enable=consider-using-get
  4268. # Handle the refs that need to land in different refs.
  4269. remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch]
  4270. # Create the true path to the remote branch.
  4271. # Does the following translation:
  4272. # * refs/remotes/origin/refs/diff/test -> refs/diff/test
  4273. # * refs/remotes/origin/main -> refs/heads/main
  4274. # * refs/remotes/branch-heads/test -> refs/branch-heads/test
  4275. if remote_branch.startswith('refs/remotes/%s/refs/' % remote):
  4276. remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '')
  4277. elif remote_branch.startswith('refs/remotes/%s/' % remote):
  4278. remote_branch = remote_branch.replace('refs/remotes/%s/' % remote,
  4279. 'refs/heads/')
  4280. elif remote_branch.startswith('refs/remotes/branch-heads'):
  4281. remote_branch = remote_branch.replace('refs/remotes/', 'refs/')
  4282. return remote_branch
  4283. def cleanup_list(l):
  4284. """Fixes a list so that comma separated items are put as individual items.
  4285. So that "--reviewers joe@c,john@c --reviewers joa@c" results in
  4286. options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']).
  4287. """
  4288. items = sum((i.split(',') for i in l), [])
  4289. stripped_items = (i.strip() for i in items)
  4290. return sorted(filter(None, stripped_items))
  4291. @subcommand.usage('[flags]')
  4292. @metrics.collector.collect_metrics('git cl upload')
  4293. def CMDupload(parser, args):
  4294. """Uploads the current changelist to codereview.
  4295. Can skip dependency patchset uploads for a branch by running:
  4296. git config branch.branch_name.skip-deps-uploads True
  4297. To unset, run:
  4298. git config --unset branch.branch_name.skip-deps-uploads
  4299. Can also set the above globally by using the --global flag.
  4300. If the name of the checked out branch starts with "bug-" or "fix-" followed
  4301. by a bug number, this bug number is automatically populated in the CL
  4302. description.
  4303. If subject contains text in square brackets or has "<text>: " prefix, such
  4304. text(s) is treated as Gerrit hashtags. For example, CLs with subjects:
  4305. [git-cl] add support for hashtags
  4306. Foo bar: implement foo
  4307. will be hashtagged with "git-cl" and "foo-bar" respectively.
  4308. """
  4309. if gclient_utils.IsEnvCog():
  4310. print(
  4311. 'upload command is not supported. Please navigate to source '
  4312. 'control view in the activity bar to upload changes to Gerrit.',
  4313. file=sys.stderr)
  4314. return 1
  4315. parser.add_option('--bypass-hooks',
  4316. action='store_true',
  4317. dest='bypass_hooks',
  4318. help='bypass upload presubmit hook')
  4319. parser.add_option('--bypass-watchlists',
  4320. action='store_true',
  4321. dest='bypass_watchlists',
  4322. help='bypass watchlists auto CC-ing reviewers')
  4323. parser.add_option('-f',
  4324. '--force',
  4325. action='store_true',
  4326. dest='force',
  4327. help="force yes to questions (don't prompt)")
  4328. parser.add_option('--message',
  4329. '-m',
  4330. dest='message',
  4331. help='DEPRECATED: use --commit-description and/or '
  4332. '--title instead. message for patchset')
  4333. parser.add_option('-b',
  4334. '--bug',
  4335. help='pre-populate the bug number(s) for this issue. '
  4336. 'If several, separate with commas')
  4337. parser.add_option('--message-file',
  4338. dest='message_file',
  4339. help='DEPRECATED: use `--commit-description -` and pipe '
  4340. 'the file to stdin instead. File which contains message '
  4341. 'for patchset')
  4342. parser.add_option('--title', '-t', dest='title', help='title for patchset')
  4343. parser.add_option('-T',
  4344. '--skip-title',
  4345. action='store_true',
  4346. dest='skip_title',
  4347. help='Use the most recent commit message as the title of '
  4348. 'the patchset')
  4349. parser.add_option('-r',
  4350. '--reviewers',
  4351. action='append',
  4352. default=[],
  4353. help='reviewer email addresses')
  4354. parser.add_option('--cc',
  4355. action='append',
  4356. default=[],
  4357. help='cc email addresses')
  4358. parser.add_option('--hashtag',
  4359. dest='hashtags',
  4360. action='append',
  4361. default=[],
  4362. help=('Gerrit hashtag for new CL; '
  4363. 'can be applied multiple times'))
  4364. parser.add_option('-s',
  4365. '--send-mail',
  4366. '--send-email',
  4367. dest='send_mail',
  4368. action='store_true',
  4369. help='send email to reviewer(s) and cc(s) immediately')
  4370. parser.add_option('--target_branch',
  4371. '--target-branch',
  4372. metavar='TARGET',
  4373. help='Apply CL to remote ref TARGET. ' +
  4374. 'Default: remote branch head, or main')
  4375. parser.add_option('--squash',
  4376. action='store_true',
  4377. help='Squash multiple commits into one')
  4378. parser.add_option('--no-squash',
  4379. action='store_false',
  4380. dest='squash',
  4381. help='Don\'t squash multiple commits into one')
  4382. parser.add_option('--topic',
  4383. default=None,
  4384. help='Topic to specify when uploading')
  4385. parser.add_option('--r-owners',
  4386. dest='add_owners_to',
  4387. action='store_const',
  4388. const='R',
  4389. help='add a set of OWNERS to R')
  4390. parser.add_option('-c',
  4391. '--use-commit-queue',
  4392. action='store_true',
  4393. default=False,
  4394. help='tell the CQ to commit this patchset; '
  4395. 'implies --send-mail')
  4396. parser.add_option('-d',
  4397. '--dry-run',
  4398. '--cq-dry-run',
  4399. action='store_true',
  4400. dest='cq_dry_run',
  4401. default=False,
  4402. help='Send the patchset to do a CQ dry run right after '
  4403. 'upload.')
  4404. parser.add_option('--set-bot-commit',
  4405. action='store_true',
  4406. help=optparse.SUPPRESS_HELP)
  4407. parser.add_option('--preserve-tryjobs',
  4408. action='store_true',
  4409. help='instruct the CQ to let tryjobs running even after '
  4410. 'new patchsets are uploaded instead of canceling '
  4411. 'prior patchset\' tryjobs')
  4412. parser.add_option(
  4413. '--dependencies',
  4414. action='store_true',
  4415. help='Uploads CLs of all the local branches that depend on '
  4416. 'the current branch')
  4417. parser.add_option(
  4418. '-a',
  4419. '--auto-submit',
  4420. '--enable-auto-submit',
  4421. action='store_true',
  4422. dest='enable_auto_submit',
  4423. help='Sends your change to the CQ after an approval. Only '
  4424. 'works on repos that have the Auto-Submit label '
  4425. 'enabled')
  4426. parser.add_option(
  4427. '--parallel',
  4428. action='store_true',
  4429. help='Run all tests specified by input_api.RunTests in all '
  4430. 'PRESUBMIT files in parallel.')
  4431. parser.add_option('--no-autocc',
  4432. action='store_true',
  4433. help='Disables automatic addition of CC emails')
  4434. parser.add_option('--private',
  4435. action='store_true',
  4436. help='Set the review private. This implies --no-autocc.')
  4437. parser.add_option('-R',
  4438. '--retry-failed',
  4439. action='store_true',
  4440. help='Retry failed tryjobs from old patchset immediately '
  4441. 'after uploading new patchset. Cannot be used with '
  4442. '--use-commit-queue or --cq-dry-run.')
  4443. parser.add_option('--fixed',
  4444. '-x',
  4445. help='List of bugs that will be commented on and marked '
  4446. 'fixed (pre-populates "Fixed:" tag). Same format as '
  4447. '-b option / "Bug:" tag. If fixing several issues, '
  4448. 'separate with commas.')
  4449. parser.add_option('--edit-description',
  4450. action='store_true',
  4451. default=False,
  4452. help='Modify description before upload. Cannot be used '
  4453. 'with --force or --commit-description. It is a noop when '
  4454. '--no-squash is set or a new commit is created.')
  4455. parser.add_option('--commit-description',
  4456. dest='commit_description',
  4457. help='Description to set for this issue/CL (- for stdin'
  4458. ', + to load from local commit HEAD). Can not be used '
  4459. 'with --edit-description, --message or --message-file.'
  4460. 'if `-` is provided, force will be implicitly enabled.')
  4461. parser.add_option('--git-completion-helper',
  4462. action="store_true",
  4463. help=optparse.SUPPRESS_HELP)
  4464. parser.add_option('-o',
  4465. '--push-options',
  4466. action='append',
  4467. default=[],
  4468. help='Transmit the given string to the server when '
  4469. 'performing git push (pass-through). See git-push '
  4470. 'documentation for more details.')
  4471. parser.add_option('--no-add-changeid',
  4472. action='store_true',
  4473. dest='no_add_changeid',
  4474. help='Do not add change-ids to messages.')
  4475. parser.add_option('--cherry-pick-stacked',
  4476. '--cp',
  4477. dest='cherry_pick_stacked',
  4478. action='store_true',
  4479. help='If parent branch has un-uploaded updates, '
  4480. 'automatically skip parent branches and just upload '
  4481. 'the current branch cherry-pick on its parent\'s last '
  4482. 'uploaded commit. Allows users to skip the potential '
  4483. 'interactive confirmation step.')
  4484. # TODO(b/265929888): Add --wip option of --cl-status option.
  4485. orig_args = args
  4486. (options, args) = parser.parse_args(args)
  4487. if options.git_completion_helper:
  4488. print(' '.join(opt.get_opt_string() for opt in parser.option_list
  4489. if opt.help != optparse.SUPPRESS_HELP))
  4490. return
  4491. # TODO(crbug.com/1475405): Warn users if the project uses submodules and
  4492. # they have fsmonitor enabled.
  4493. if os.path.isfile('.gitmodules'):
  4494. git_common.warn_submodule()
  4495. if git_common.is_dirty_git_tree('upload'):
  4496. return 1
  4497. options.reviewers = cleanup_list(options.reviewers)
  4498. options.cc = cleanup_list(options.cc)
  4499. if options.edit_description and options.force:
  4500. parser.error('Only one of --force and --edit-description allowed')
  4501. if options.edit_description and options.commit_description:
  4502. parser.error('Only one of --commit-description and --edit-description '
  4503. 'allowed')
  4504. if options.message and options.commit_description:
  4505. parser.error('Only one of --commit-description and --message allowed')
  4506. if options.commit_description and options.commit_description == '-':
  4507. options.force = True
  4508. if options.message_file:
  4509. if options.message:
  4510. parser.error('Only one of --message and --message-file allowed.')
  4511. if options.commit_description:
  4512. parser.error('Only one of --commit-description and --message-file '
  4513. 'allowed.')
  4514. options.message = gclient_utils.FileRead(options.message_file)
  4515. if ([options.cq_dry_run, options.use_commit_queue, options.retry_failed
  4516. ].count(True) > 1):
  4517. parser.error('Only one of --use-commit-queue, --cq-dry-run or '
  4518. '--retry-failed is allowed.')
  4519. if options.skip_title and options.title:
  4520. parser.error('Only one of --title and --skip-title allowed.')
  4521. if options.use_commit_queue:
  4522. options.send_mail = True
  4523. if options.squash is None:
  4524. # Load default for user, repo, squash=true, in this order.
  4525. options.squash = settings.GetSquashGerritUploads()
  4526. cl = Changelist(branchref=options.target_branch)
  4527. # Warm change details cache now to avoid RPCs later, reducing latency for
  4528. # developers.
  4529. if cl.GetIssue():
  4530. cl._GetChangeDetail([
  4531. 'DETAILED_ACCOUNTS', 'CURRENT_REVISION', 'CURRENT_COMMIT', 'LABELS'
  4532. ])
  4533. if options.retry_failed and not cl.GetIssue():
  4534. print('No previous patchsets, so --retry-failed has no effect.')
  4535. options.retry_failed = False
  4536. if options.squash:
  4537. if options.cherry_pick_stacked:
  4538. try:
  4539. orig_args.remove('--cherry-pick-stacked')
  4540. except ValueError:
  4541. orig_args.remove('--cp')
  4542. UploadAllSquashed(options, orig_args)
  4543. if options.dependencies:
  4544. orig_args.remove('--dependencies')
  4545. if not cl.GetIssue():
  4546. # UploadAllSquashed stored an issue number for cl, but it
  4547. # doesn't have access to cl object. By unsetting lookedup_issue,
  4548. # we force code path that will read issue from the config.
  4549. cl.lookedup_issue = False
  4550. return upload_branch_deps(cl, orig_args, options.force)
  4551. return 0
  4552. if options.cherry_pick_stacked:
  4553. parser.error(
  4554. '--cherry-pick-stacked is not available without squash=true,')
  4555. # cl.GetMostRecentPatchset uses cached information, and can return the last
  4556. # patchset before upload. Calling it here makes it clear that it's the
  4557. # last patchset before upload. Note that GetMostRecentPatchset will fail
  4558. # if no CL has been uploaded yet.
  4559. if options.retry_failed:
  4560. patchset = cl.GetMostRecentPatchset()
  4561. ret = cl.CMDUpload(options, args, orig_args)
  4562. if options.retry_failed:
  4563. if ret != 0:
  4564. print('Upload failed, so --retry-failed has no effect.')
  4565. return ret
  4566. builds, _ = _fetch_latest_builds(cl,
  4567. DEFAULT_BUILDBUCKET_HOST,
  4568. latest_patchset=patchset)
  4569. jobs = _filter_failed_for_retry(builds)
  4570. if len(jobs) == 0:
  4571. print('No failed tryjobs, so --retry-failed has no effect.')
  4572. return ret
  4573. _trigger_tryjobs(cl, jobs, options, patchset + 1)
  4574. return ret
  4575. def UploadAllSquashed(options: optparse.Values,
  4576. orig_args: Sequence[str]) -> int:
  4577. """Uploads the current and upstream branches (if necessary)."""
  4578. cls, cherry_pick_current = _UploadAllPrecheck(options, orig_args)
  4579. # Create commits.
  4580. uploads_by_cl: List[Tuple[Changelist, _NewUpload]] = []
  4581. if cherry_pick_current:
  4582. parent = cls[1]._GitGetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY)
  4583. new_upload = cls[0].PrepareCherryPickSquashedCommit(options, parent)
  4584. uploads_by_cl.append((cls[0], new_upload))
  4585. else:
  4586. ordered_cls = list(reversed(cls))
  4587. cl = ordered_cls[0]
  4588. # We can only support external changes when we're only uploading one
  4589. # branch.
  4590. parent = cl._UpdateWithExternalChanges() if len(
  4591. ordered_cls) == 1 else None
  4592. orig_parent = None
  4593. if parent is None:
  4594. origin = '.'
  4595. branch = cl.GetBranch()
  4596. while origin == '.':
  4597. # Search for cl's closest ancestor with a gerrit hash.
  4598. origin, upstream_branch_ref = Changelist.FetchUpstreamTuple(
  4599. branch)
  4600. if origin == '.':
  4601. upstream_branch = scm.GIT.ShortBranchName(
  4602. upstream_branch_ref)
  4603. # Support the `git merge` and `git pull` workflow.
  4604. if upstream_branch in ['master', 'main']:
  4605. parent = cl.GetCommonAncestorWithUpstream()
  4606. else:
  4607. orig_parent = scm.GIT.GetBranchConfig(
  4608. settings.GetRoot(), upstream_branch,
  4609. LAST_UPLOAD_HASH_CONFIG_KEY)
  4610. parent = scm.GIT.GetBranchConfig(
  4611. settings.GetRoot(), upstream_branch,
  4612. GERRIT_SQUASH_HASH_CONFIG_KEY)
  4613. if parent:
  4614. break
  4615. branch = upstream_branch
  4616. else:
  4617. # Either the root of the tree is the cl's direct parent and the
  4618. # while loop above only found empty branches between cl and the
  4619. # root of the tree.
  4620. parent = cl.GetCommonAncestorWithUpstream()
  4621. if orig_parent is None:
  4622. orig_parent = parent
  4623. for i, cl in enumerate(ordered_cls):
  4624. # If we're in the middle of the stack, set end_commit to
  4625. # downstream's direct ancestor.
  4626. if i + 1 < len(ordered_cls):
  4627. child_base_commit = ordered_cls[
  4628. i + 1].GetCommonAncestorWithUpstream()
  4629. else:
  4630. child_base_commit = None
  4631. new_upload = cl.PrepareSquashedCommit(options,
  4632. parent,
  4633. orig_parent,
  4634. end_commit=child_base_commit)
  4635. uploads_by_cl.append((cl, new_upload))
  4636. parent = new_upload.commit_to_push
  4637. orig_parent = child_base_commit
  4638. # Create refspec options
  4639. cl, new_upload = uploads_by_cl[-1]
  4640. refspec_opts = cl._GetRefSpecOptions(
  4641. options,
  4642. new_upload.change_desc,
  4643. multi_change_upload=len(uploads_by_cl) > 1,
  4644. dogfood_path=True)
  4645. refspec_suffix = ''
  4646. if refspec_opts:
  4647. refspec_suffix = '%' + ','.join(refspec_opts)
  4648. assert ' ' not in refspec_suffix, (
  4649. 'spaces not allowed in refspec: "%s"' % refspec_suffix)
  4650. remote, remote_branch = cl.GetRemoteBranch()
  4651. branch = GetTargetRef(remote, remote_branch, options.target_branch)
  4652. refspec = '%s:refs/for/%s%s' % (new_upload.commit_to_push, branch,
  4653. refspec_suffix)
  4654. # Git push
  4655. git_push_metadata = {
  4656. 'gerrit_host':
  4657. cl.GetGerritHost(),
  4658. 'title':
  4659. options.title or '<untitled>',
  4660. 'change_id':
  4661. git_footers.get_footer_change_id(new_upload.change_desc.description),
  4662. 'description':
  4663. new_upload.change_desc.description,
  4664. }
  4665. push_stdout = cl._RunGitPushWithTraces(refspec, refspec_opts,
  4666. git_push_metadata,
  4667. options.push_options)
  4668. # Post push updates
  4669. regex = re.compile(r'remote:\s+https?://[\w\-\.\+\/#]*/(\d+)\s.*')
  4670. change_numbers = [
  4671. m.group(1) for m in map(regex.match, push_stdout.splitlines()) if m
  4672. ]
  4673. for i, (cl, new_upload) in enumerate(uploads_by_cl):
  4674. cl.PostUploadUpdates(options, new_upload, change_numbers[i])
  4675. return 0
  4676. def _UploadAllPrecheck(
  4677. options: optparse.Values,
  4678. orig_args: Sequence[str]) -> Tuple[Sequence[Changelist], bool]:
  4679. """Checks the state of the tree and gives the user uploading options
  4680. Returns: A tuple of the ordered list of changes that have new commits
  4681. since their last upload and a boolean of whether the user wants to
  4682. cherry-pick and upload the current branch instead of uploading all cls.
  4683. """
  4684. cl = Changelist()
  4685. if cl.GetBranch() is None:
  4686. DieWithError('Can\'t upload from detached HEAD state. Get on a branch!')
  4687. branch_ref = None
  4688. cls: List[Changelist] = []
  4689. must_upload_upstream = False
  4690. first_pass = True
  4691. Changelist._GerritCommitMsgHookCheck(offer_removal=not options.force)
  4692. while True:
  4693. if len(cls) > _MAX_STACKED_BRANCHES_UPLOAD:
  4694. DieWithError(
  4695. 'More than %s branches in the stack have not been uploaded.\n'
  4696. 'Are your branches in a misconfigured state?\n'
  4697. 'If not, please upload some upstream changes first.' %
  4698. (_MAX_STACKED_BRANCHES_UPLOAD))
  4699. cl = Changelist(branchref=branch_ref)
  4700. # Only add CL if it has anything to commit.
  4701. base_commit = cl.GetCommonAncestorWithUpstream()
  4702. end_commit = RunGit(['rev-parse', cl.GetBranchRef()]).strip()
  4703. commit_summary = _GetCommitCountSummary(base_commit, end_commit)
  4704. if commit_summary:
  4705. cls.append(cl)
  4706. if (not first_pass and
  4707. cl._GitGetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY)
  4708. is None):
  4709. # We are mid-stack and the user must upload their upstream
  4710. # branches.
  4711. must_upload_upstream = True
  4712. print(f'Found change with {commit_summary}...')
  4713. elif first_pass: # The current branch has nothing to commit. Exit.
  4714. DieWithError('Branch %s has nothing to commit' % cl.GetBranch())
  4715. # Else: A mid-stack branch has nothing to commit. We do not add it to
  4716. # cls.
  4717. first_pass = False
  4718. # Cases below determine if we should continue to traverse up the tree.
  4719. origin, upstream_branch_ref = Changelist.FetchUpstreamTuple(
  4720. cl.GetBranch())
  4721. branch_ref = upstream_branch_ref # set branch for next run.
  4722. upstream_branch = scm.GIT.ShortBranchName(upstream_branch_ref)
  4723. upstream_last_upload = scm.GIT.GetBranchConfig(
  4724. settings.GetRoot(), upstream_branch, LAST_UPLOAD_HASH_CONFIG_KEY)
  4725. # Case 1: We've reached the beginning of the tree.
  4726. if origin != '.':
  4727. break
  4728. # Case 2: If any upstream branches have never been uploaded,
  4729. # the user MUST upload them unless they are empty. Continue to
  4730. # next loop to add upstream if it is not empty.
  4731. if not upstream_last_upload:
  4732. continue
  4733. # Case 3: If upstream's last_upload == cl.base_commit we do
  4734. # not need to upload any more upstreams from this point on.
  4735. # (Even if there may be diverged branches higher up the tree)
  4736. if base_commit == upstream_last_upload:
  4737. break
  4738. # Case 4: If upstream's last_upload < cl.base_commit we are
  4739. # uploading cl and upstream_cl.
  4740. # Continue up the tree to check other branch relations.
  4741. if scm.GIT.IsAncestor(upstream_last_upload, base_commit):
  4742. continue
  4743. # Case 5: If cl.base_commit < upstream's last_upload the user
  4744. # must rebase before uploading.
  4745. if scm.GIT.IsAncestor(base_commit, upstream_last_upload):
  4746. DieWithError(
  4747. 'At least one branch in the stack has diverged from its upstream '
  4748. 'branch and does not contain its upstream\'s last upload.\n'
  4749. 'Please rebase the stack with `git rebase-update` before uploading.'
  4750. )
  4751. # The tree went through a rebase. LAST_UPLOAD_HASH_CONFIG_KEY no longer
  4752. # has any relation to commits in the tree. Continue up the tree until we
  4753. # hit the root.
  4754. # We assume all cls in the stack have the same auth requirements and only
  4755. # check this once.
  4756. cls[0].EnsureAuthenticated(force=options.force)
  4757. cherry_pick = False
  4758. if len(cls) > 1:
  4759. opt_message = ''
  4760. branches = ', '.join([cl.branch for cl in cls])
  4761. if len(orig_args):
  4762. opt_message = ('options %s will be used for all uploads.\n' %
  4763. orig_args)
  4764. if must_upload_upstream:
  4765. msg = ('At least one parent branch in `%s` has never been uploaded '
  4766. 'and must be uploaded before/with `%s`.\n' %
  4767. (branches, cls[1].branch))
  4768. if options.cherry_pick_stacked:
  4769. DieWithError(msg)
  4770. if not options.force:
  4771. confirm_or_exit('\n' + opt_message + msg)
  4772. else:
  4773. if options.cherry_pick_stacked:
  4774. print('cherry-picking `%s` on %s\'s last upload' %
  4775. (cls[0].branch, cls[1].branch))
  4776. cherry_pick = True
  4777. elif not options.force:
  4778. answer = gclient_utils.AskForData(
  4779. '\n' + opt_message +
  4780. 'Press enter to update branches %s.\nOr type `n` to upload only '
  4781. '`%s` cherry-picked on %s\'s last upload:' %
  4782. (branches, cls[0].branch, cls[1].branch))
  4783. if answer.lower() == 'n':
  4784. cherry_pick = True
  4785. return cls, cherry_pick
  4786. @subcommand.usage('--description=<description file>')
  4787. @metrics.collector.collect_metrics('git cl split')
  4788. def CMDsplit(parser, args):
  4789. """Splits a branch into smaller branches and uploads CLs.
  4790. Creates a branch and uploads a CL for each group of files modified in the
  4791. current branch that share a common OWNERS file. In the CL description and
  4792. comment, the string '$directory', is replaced with the directory containing
  4793. the shared OWNERS file.
  4794. """
  4795. if gclient_utils.IsEnvCog():
  4796. print('split command is not supported in non-git environment.',
  4797. file=sys.stderr)
  4798. return 1
  4799. parser.add_option('-d',
  4800. '--description',
  4801. dest='description_file',
  4802. help='A text file containing a CL description in which '
  4803. '$directory will be replaced by each CL\'s directory.')
  4804. parser.add_option('-c',
  4805. '--comment',
  4806. dest='comment_file',
  4807. help='A text file containing a CL comment.')
  4808. parser.add_option(
  4809. '-n',
  4810. '--dry-run',
  4811. dest='dry_run',
  4812. action='store_true',
  4813. default=False,
  4814. help='List the files and reviewers for each CL that would '
  4815. 'be created, but don\'t create branches or CLs.')
  4816. parser.add_option('--cq-dry-run',
  4817. action='store_true',
  4818. default=False,
  4819. help='If set, will do a cq dry run for each uploaded CL. '
  4820. 'Please be careful when doing this; more than ~10 CLs '
  4821. 'has the potential to overload our build '
  4822. 'infrastructure. Try to upload these not during high '
  4823. 'load times (usually 11-3 Mountain View time). Email '
  4824. 'infra-dev@chromium.org with any questions.')
  4825. parser.add_option(
  4826. '-a',
  4827. '--auto-submit',
  4828. '--enable-auto-submit',
  4829. action='store_true',
  4830. dest='enable_auto_submit',
  4831. default=True,
  4832. help='Sends your change to the CQ after an approval. Only '
  4833. 'works on repos that have the Auto-Submit label '
  4834. 'enabled')
  4835. parser.add_option(
  4836. '--disable-auto-submit',
  4837. action='store_false',
  4838. dest='enable_auto_submit',
  4839. help='Disables automatic sending of the changes to the CQ '
  4840. 'after approval. Note that auto-submit only works for '
  4841. 'repos that have the Auto-Submit label enabled.')
  4842. parser.add_option('--max-depth',
  4843. type='int',
  4844. default=0,
  4845. help='The max depth to look for OWNERS files. Useful for '
  4846. 'controlling the granularity of the split CLs, e.g. '
  4847. '--max-depth=1 will only split by top-level '
  4848. 'directory. Specifying a value less than 1 means no '
  4849. 'limit on max depth.')
  4850. parser.add_option('--topic',
  4851. default=None,
  4852. help='Topic to specify when uploading')
  4853. options, _ = parser.parse_args(args)
  4854. if not options.description_file:
  4855. parser.error('No --description flag specified.')
  4856. def WrappedCMDupload(args):
  4857. return CMDupload(OptionParser(), args)
  4858. return split_cl.SplitCl(options.description_file, options.comment_file,
  4859. Changelist, WrappedCMDupload, options.dry_run,
  4860. options.cq_dry_run, options.enable_auto_submit,
  4861. options.max_depth, options.topic,
  4862. settings.GetRoot())
  4863. @subcommand.usage('DEPRECATED')
  4864. @metrics.collector.collect_metrics('git cl commit')
  4865. def CMDdcommit(parser, args):
  4866. """DEPRECATED: Used to commit the current changelist via git-svn."""
  4867. message = ('git-cl no longer supports committing to SVN repositories via '
  4868. 'git-svn. You probably want to use `git cl land` instead.')
  4869. print(message)
  4870. return 1
  4871. @subcommand.usage('[upstream branch to apply against]')
  4872. @metrics.collector.collect_metrics('git cl land')
  4873. def CMDland(parser, args):
  4874. """Commits the current changelist via git.
  4875. In case of Gerrit, uses Gerrit REST api to "submit" the issue, which pushes
  4876. upstream and closes the issue automatically and atomically.
  4877. """
  4878. if gclient_utils.IsEnvCog():
  4879. print(
  4880. 'land command is not supported. Please go to the Gerrit CL '
  4881. 'directly to submit the CL',
  4882. file=sys.stderr)
  4883. return 1
  4884. parser.add_option('--bypass-hooks',
  4885. action='store_true',
  4886. dest='bypass_hooks',
  4887. help='bypass upload presubmit hook')
  4888. parser.add_option('-f',
  4889. '--force',
  4890. action='store_true',
  4891. dest='force',
  4892. help="force yes to questions (don't prompt)")
  4893. parser.add_option(
  4894. '--parallel',
  4895. action='store_true',
  4896. help='Run all tests specified by input_api.RunTests in all '
  4897. 'PRESUBMIT files in parallel.')
  4898. parser.add_option('--resultdb',
  4899. action='store_true',
  4900. help='Run presubmit checks in the ResultSink environment '
  4901. 'and send results to the ResultDB database.')
  4902. parser.add_option('--realm', help='LUCI realm if reporting to ResultDB')
  4903. (options, args) = parser.parse_args(args)
  4904. cl = Changelist()
  4905. if not cl.GetIssue():
  4906. DieWithError('You must upload the change first to Gerrit.\n'
  4907. ' If you would rather have `git cl land` upload '
  4908. 'automatically for you, see http://crbug.com/642759')
  4909. return cl.CMDLand(options.force, options.bypass_hooks, options.verbose,
  4910. options.parallel, options.resultdb, options.realm)
  4911. @subcommand.usage('<patch url or issue id or issue url>')
  4912. @metrics.collector.collect_metrics('git cl patch')
  4913. def CMDpatch(parser, args):
  4914. """Applies (cherry-picks) a Gerrit changelist locally."""
  4915. if gclient_utils.IsEnvCog():
  4916. print(
  4917. 'patch command is not supported. Please create a new workspace '
  4918. 'from the Gerrit CL directly',
  4919. file=sys.stderr)
  4920. return 1
  4921. parser.add_option('-b',
  4922. '--branch',
  4923. dest='newbranch',
  4924. help='create a new branch off trunk for the patch')
  4925. parser.add_option('-f',
  4926. '--force',
  4927. action='store_true',
  4928. help='overwrite state on the current or chosen branch')
  4929. parser.add_option('-n',
  4930. '--no-commit',
  4931. action='store_true',
  4932. dest='nocommit',
  4933. help='don\'t commit after patch applies.')
  4934. group = optparse.OptionGroup(
  4935. parser,
  4936. 'Options for continuing work on the current issue uploaded from a '
  4937. 'different clone (e.g. different machine). Must be used independently '
  4938. 'from the other options. No issue number should be specified, and the '
  4939. 'branch must have an issue number associated with it')
  4940. group.add_option('--reapply',
  4941. action='store_true',
  4942. dest='reapply',
  4943. help='Reset the branch and reapply the issue.\n'
  4944. 'CAUTION: This will undo any local changes in this '
  4945. 'branch')
  4946. group.add_option('--pull',
  4947. action='store_true',
  4948. dest='pull',
  4949. help='Performs a pull before reapplying.')
  4950. parser.add_option_group(group)
  4951. (options, args) = parser.parse_args(args)
  4952. if options.reapply:
  4953. if options.newbranch:
  4954. parser.error('--reapply works on the current branch only.')
  4955. if len(args) > 0:
  4956. parser.error('--reapply implies no additional arguments.')
  4957. cl = Changelist()
  4958. if not cl.GetIssue():
  4959. parser.error('Current branch must have an associated issue.')
  4960. upstream = cl.GetUpstreamBranch()
  4961. if upstream is None:
  4962. parser.error('No upstream branch specified. Cannot reset branch.')
  4963. RunGit(['reset', '--hard', upstream])
  4964. if options.pull:
  4965. RunGit(['pull'])
  4966. target_issue_arg = ParseIssueNumberArgument(cl.GetIssue())
  4967. return cl.CMDPatchWithParsedIssue(target_issue_arg, options.nocommit,
  4968. options.force)
  4969. if len(args) != 1 or not args[0]:
  4970. parser.error('Must specify issue number or URL.')
  4971. target_issue_arg = ParseIssueNumberArgument(args[0])
  4972. if not target_issue_arg.valid:
  4973. parser.error('Invalid issue ID or URL.')
  4974. # We don't want uncommitted changes mixed up with the patch.
  4975. if git_common.is_dirty_git_tree('patch'):
  4976. return 1
  4977. if options.newbranch:
  4978. if options.force:
  4979. RunGit(['branch', '-D', options.newbranch],
  4980. stderr=subprocess2.PIPE,
  4981. error_ok=True)
  4982. git_new_branch.create_new_branch(options.newbranch)
  4983. cl = Changelist(codereview_host=target_issue_arg.hostname,
  4984. issue=target_issue_arg.issue)
  4985. if not args[0].isdigit():
  4986. print('canonical issue/change URL: %s\n' % cl.GetIssueURL())
  4987. return cl.CMDPatchWithParsedIssue(target_issue_arg, options.nocommit,
  4988. options.force)
  4989. def GetTreeStatus(url=None):
  4990. """Fetches the tree status and returns either 'open', 'closed',
  4991. 'unknown' or 'unset'."""
  4992. url = url or settings.GetTreeStatusUrl(error_ok=True)
  4993. if url:
  4994. status = str(urllib.request.urlopen(url).read().lower())
  4995. if status.find('closed') != -1 or status == '0':
  4996. return 'closed'
  4997. if status.find('open') != -1 or status == '1':
  4998. return 'open'
  4999. return 'unknown'
  5000. return 'unset'
  5001. def GetTreeStatusReason():
  5002. """Fetches the tree status from a json url and returns the message
  5003. with the reason for the tree to be opened or closed."""
  5004. url = settings.GetTreeStatusUrl()
  5005. json_url = urllib.parse.urljoin(url, '/current?format=json')
  5006. connection = urllib.request.urlopen(json_url)
  5007. status = json.loads(connection.read())
  5008. connection.close()
  5009. return status['message']
  5010. @metrics.collector.collect_metrics('git cl tree')
  5011. def CMDtree(parser, args):
  5012. """Shows the status of the tree."""
  5013. if gclient_utils.IsEnvCog():
  5014. print(
  5015. 'tree command is not supported. Please go to the tree '
  5016. 'status UI to check the status of the tree directly.',
  5017. file=sys.stderr)
  5018. return 1
  5019. _, args = parser.parse_args(args)
  5020. status = GetTreeStatus()
  5021. if 'unset' == status:
  5022. print(
  5023. 'You must configure your tree status URL by running "git cl config".'
  5024. )
  5025. return 2
  5026. print('The tree is %s' % status)
  5027. print()
  5028. print(GetTreeStatusReason())
  5029. if status != 'open':
  5030. return 1
  5031. return 0
  5032. @metrics.collector.collect_metrics('git cl try')
  5033. def CMDtry(parser, args):
  5034. """Triggers tryjobs using either Buildbucket or CQ dry run."""
  5035. if gclient_utils.IsEnvCog():
  5036. print(
  5037. 'try command is not supported. Please go to the Gerrit CL '
  5038. 'page to trigger individual builds or CQ dry run.',
  5039. file=sys.stderr)
  5040. return 1
  5041. group = optparse.OptionGroup(parser, 'Tryjob options')
  5042. group.add_option(
  5043. '-b',
  5044. '--bot',
  5045. action='append',
  5046. help=('IMPORTANT: specify ONE builder per --bot flag. Use it multiple '
  5047. 'times to specify multiple builders. ex: '
  5048. '"-b win_rel -b win_layout". See '
  5049. 'the try server waterfall for the builders name and the tests '
  5050. 'available.'))
  5051. group.add_option(
  5052. '-B',
  5053. '--bucket',
  5054. default='',
  5055. help=('Buildbucket bucket to send the try requests. Format: '
  5056. '"luci.$LUCI_PROJECT.$LUCI_BUCKET". eg: "luci.chromium.try"'))
  5057. group.add_option(
  5058. '-r',
  5059. '--revision',
  5060. help='Revision to use for the tryjob; default: the revision will '
  5061. 'be determined by the try recipe that builder runs, which usually '
  5062. 'defaults to HEAD of origin/master or origin/main')
  5063. group.add_option('--category',
  5064. default='git_cl_try',
  5065. help='Specify custom build category.')
  5066. group.add_option(
  5067. '--project',
  5068. help='Override which project to use. Projects are defined '
  5069. 'in recipe to determine to which repository or directory to '
  5070. 'apply the patch')
  5071. group.add_option(
  5072. '-p',
  5073. '--property',
  5074. dest='properties',
  5075. action='append',
  5076. default=[],
  5077. help='Specify generic properties in the form -p key1=value1 -p '
  5078. 'key2=value2 etc. The value will be treated as '
  5079. 'json if decodable, or as string otherwise. '
  5080. 'NOTE: using this may make your tryjob not usable for CQ, '
  5081. 'which will then schedule another tryjob with default properties')
  5082. group.add_option('--buildbucket-host',
  5083. default='cr-buildbucket.appspot.com',
  5084. help='Host of buildbucket. The default host is %default.')
  5085. parser.add_option_group(group)
  5086. parser.add_option('-R',
  5087. '--retry-failed',
  5088. action='store_true',
  5089. default=False,
  5090. help='Retry failed jobs from the latest set of tryjobs. '
  5091. 'Not allowed with --bucket and --bot options.')
  5092. parser.add_option(
  5093. '-i',
  5094. '--issue',
  5095. type=int,
  5096. help='Operate on this issue instead of the current branch\'s implicit '
  5097. 'issue.')
  5098. options, args = parser.parse_args(args)
  5099. # Make sure that all properties are prop=value pairs.
  5100. bad_params = [x for x in options.properties if '=' not in x]
  5101. if bad_params:
  5102. parser.error('Got properties with missing "=": %s' % bad_params)
  5103. if args:
  5104. parser.error('Unknown arguments: %s' % args)
  5105. cl = Changelist(issue=options.issue)
  5106. if not cl.GetIssue():
  5107. parser.error('Need to upload first.')
  5108. # HACK: warm up Gerrit change detail cache to save on RPCs.
  5109. cl._GetChangeDetail(['DETAILED_ACCOUNTS', 'ALL_REVISIONS'])
  5110. error_message = cl.CannotTriggerTryJobReason()
  5111. if error_message:
  5112. parser.error('Can\'t trigger tryjobs: %s' % error_message)
  5113. if options.bot:
  5114. if options.retry_failed:
  5115. parser.error('--bot is not compatible with --retry-failed.')
  5116. if not options.bucket:
  5117. parser.error('A bucket (e.g. "chromium/try") is required.')
  5118. triggered = [b for b in options.bot if 'triggered' in b]
  5119. if triggered:
  5120. parser.error(
  5121. 'Cannot schedule builds on triggered bots: %s.\n'
  5122. 'This type of bot requires an initial job from a parent (usually a '
  5123. 'builder). Schedule a job on the parent instead.\n' % triggered)
  5124. if options.bucket.startswith('.master'):
  5125. parser.error('Buildbot masters are not supported.')
  5126. project, bucket = _parse_bucket(options.bucket)
  5127. if project is None or bucket is None:
  5128. parser.error('Invalid bucket: %s.' % options.bucket)
  5129. jobs = sorted((project, bucket, bot) for bot in options.bot)
  5130. elif options.retry_failed:
  5131. print('Searching for failed tryjobs...')
  5132. builds, patchset = _fetch_latest_builds(cl, DEFAULT_BUILDBUCKET_HOST)
  5133. if options.verbose:
  5134. print('Got %d builds in patchset #%d' % (len(builds), patchset))
  5135. jobs = _filter_failed_for_retry(builds)
  5136. if not jobs:
  5137. print('There are no failed jobs in the latest set of jobs '
  5138. '(patchset #%d), doing nothing.' % patchset)
  5139. return 0
  5140. num_builders = len(jobs)
  5141. if num_builders > 10:
  5142. confirm_or_exit('There are %d builders with failed builds.' %
  5143. num_builders,
  5144. action='continue')
  5145. else:
  5146. if options.verbose:
  5147. print('git cl try with no bots now defaults to CQ dry run.')
  5148. print('Scheduling CQ dry run on: %s' % cl.GetIssueURL())
  5149. return cl.SetCQState(_CQState.DRY_RUN)
  5150. patchset = cl.GetMostRecentPatchset()
  5151. try:
  5152. _trigger_tryjobs(cl, jobs, options, patchset)
  5153. except BuildbucketResponseException as ex:
  5154. print('ERROR: %s' % ex)
  5155. return 1
  5156. return 0
  5157. @metrics.collector.collect_metrics('git cl try-results')
  5158. def CMDtry_results(parser, args):
  5159. """Prints info about results for tryjobs associated with the current CL."""
  5160. if gclient_utils.IsEnvCog():
  5161. print(
  5162. 'try-results command is not supported. Please go to the Gerrit '
  5163. 'CL page to see the tryjob results instead.',
  5164. file=sys.stderr)
  5165. return 1
  5166. group = optparse.OptionGroup(parser, 'Tryjob results options')
  5167. group.add_option('-p',
  5168. '--patchset',
  5169. type=int,
  5170. help='patchset number if not current.')
  5171. group.add_option('--print-master',
  5172. action='store_true',
  5173. help='print master name as well.')
  5174. group.add_option('--color',
  5175. action='store_true',
  5176. default=setup_color.IS_TTY,
  5177. help='force color output, useful when piping output.')
  5178. group.add_option('--buildbucket-host',
  5179. default='cr-buildbucket.appspot.com',
  5180. help='Host of buildbucket. The default host is %default.')
  5181. group.add_option(
  5182. '--json',
  5183. help=('Path of JSON output file to write tryjob results to,'
  5184. 'or "-" for stdout.'))
  5185. parser.add_option_group(group)
  5186. parser.add_option(
  5187. '-i',
  5188. '--issue',
  5189. type=int,
  5190. help='Operate on this issue instead of the current branch\'s implicit '
  5191. 'issue.')
  5192. options, args = parser.parse_args(args)
  5193. if args:
  5194. parser.error('Unrecognized args: %s' % ' '.join(args))
  5195. cl = Changelist(issue=options.issue)
  5196. if not cl.GetIssue():
  5197. parser.error('Need to upload first.')
  5198. patchset = options.patchset
  5199. if not patchset:
  5200. patchset = cl.GetMostRecentDryRunPatchset()
  5201. if not patchset:
  5202. parser.error('Code review host doesn\'t know about issue %s. '
  5203. 'No access to issue or wrong issue number?\n'
  5204. 'Either upload first, or pass --patchset explicitly.' %
  5205. cl.GetIssue())
  5206. try:
  5207. jobs = _fetch_tryjobs(cl, DEFAULT_BUILDBUCKET_HOST, patchset)
  5208. except BuildbucketResponseException as ex:
  5209. print('Buildbucket error: %s' % ex)
  5210. return 1
  5211. if options.json:
  5212. write_json(options.json, jobs)
  5213. else:
  5214. _print_tryjobs(options, jobs)
  5215. return 0
  5216. @subcommand.usage('[new upstream branch]')
  5217. @metrics.collector.collect_metrics('git cl upstream')
  5218. def CMDupstream(parser, args):
  5219. """Prints or sets the name of the upstream branch, if any."""
  5220. if gclient_utils.IsEnvCog():
  5221. print('upstream command is not supported in non-git environment.',
  5222. file=sys.stderr)
  5223. return 1
  5224. _, args = parser.parse_args(args)
  5225. if len(args) > 1:
  5226. parser.error('Unrecognized args: %s' % ' '.join(args))
  5227. cl = Changelist()
  5228. if args:
  5229. # One arg means set upstream branch.
  5230. branch = cl.GetBranch()
  5231. RunGit(['branch', '--set-upstream-to', args[0], branch])
  5232. # Clear configured merge-base, if there is one.
  5233. git_common.remove_merge_base(branch)
  5234. cl = Changelist()
  5235. print('Upstream branch set to %s' % (cl.GetUpstreamBranch(), ))
  5236. else:
  5237. print(cl.GetUpstreamBranch())
  5238. return 0
  5239. @metrics.collector.collect_metrics('git cl web')
  5240. def CMDweb(parser, args):
  5241. """Opens the current CL in the web browser."""
  5242. if gclient_utils.IsEnvCog():
  5243. print(
  5244. 'web command is not supported. Please use "Gerrit: Open Changes '
  5245. 'in Gerrit" functionality in the command palette in the Editor '
  5246. 'instead.',
  5247. file=sys.stderr)
  5248. return 1
  5249. parser.add_option('-p',
  5250. '--print-only',
  5251. action='store_true',
  5252. dest='print_only',
  5253. help='Only print the Gerrit URL, don\'t open it in the '
  5254. 'browser.')
  5255. (options, args) = parser.parse_args(args)
  5256. if args:
  5257. parser.error('Unrecognized args: %s' % ' '.join(args))
  5258. issue_url = Changelist().GetIssueURL()
  5259. if not issue_url:
  5260. print('ERROR No issue to open', file=sys.stderr)
  5261. return 1
  5262. if options.print_only:
  5263. print(issue_url)
  5264. return 0
  5265. # Redirect I/O before invoking browser to hide its output. For example, this
  5266. # allows us to hide the "Created new window in existing browser session."
  5267. # message from Chrome. Based on https://stackoverflow.com/a/2323563.
  5268. saved_stdout = os.dup(1)
  5269. saved_stderr = os.dup(2)
  5270. os.close(1)
  5271. os.close(2)
  5272. os.open(os.devnull, os.O_RDWR)
  5273. try:
  5274. webbrowser.open(issue_url)
  5275. finally:
  5276. os.dup2(saved_stdout, 1)
  5277. os.dup2(saved_stderr, 2)
  5278. return 0
  5279. @metrics.collector.collect_metrics('git cl set-commit')
  5280. def CMDset_commit(parser, args):
  5281. """Sets the commit bit to trigger the CQ."""
  5282. if gclient_utils.IsEnvCog():
  5283. print(
  5284. 'set-commit command is not supported. Please go to the Gerrit CL '
  5285. 'page directly to submit the CL.',
  5286. file=sys.stderr)
  5287. return 1
  5288. parser.add_option('-d',
  5289. '--dry-run',
  5290. action='store_true',
  5291. help='trigger in dry run mode')
  5292. parser.add_option('-c',
  5293. '--clear',
  5294. action='store_true',
  5295. help='stop CQ run, if any')
  5296. parser.add_option(
  5297. '-i',
  5298. '--issue',
  5299. type=int,
  5300. help='Operate on this issue instead of the current branch\'s implicit '
  5301. 'issue.')
  5302. options, args = parser.parse_args(args)
  5303. if args:
  5304. parser.error('Unrecognized args: %s' % ' '.join(args))
  5305. if [options.dry_run, options.clear].count(True) > 1:
  5306. parser.error('Only one of --dry-run, and --clear are allowed.')
  5307. cl = Changelist(issue=options.issue)
  5308. if not cl.GetIssue():
  5309. parser.error('Must upload the issue first.')
  5310. if options.clear:
  5311. state = _CQState.NONE
  5312. elif options.dry_run:
  5313. state = _CQState.DRY_RUN
  5314. else:
  5315. state = _CQState.COMMIT
  5316. cl.SetCQState(state)
  5317. return 0
  5318. @metrics.collector.collect_metrics('git cl set-close')
  5319. def CMDset_close(parser, args):
  5320. """Closes the issue."""
  5321. if gclient_utils.IsEnvCog():
  5322. print(
  5323. 'set-close command is not supported. Please go to the Gerrit CL '
  5324. 'page to abandon the CL instead.',
  5325. file=sys.stderr)
  5326. return 1
  5327. parser.add_option(
  5328. '-i',
  5329. '--issue',
  5330. type=int,
  5331. help='Operate on this issue instead of the current branch\'s implicit '
  5332. 'issue.')
  5333. options, args = parser.parse_args(args)
  5334. if args:
  5335. parser.error('Unrecognized args: %s' % ' '.join(args))
  5336. cl = Changelist(issue=options.issue)
  5337. # Ensure there actually is an issue to close.
  5338. if not cl.GetIssue():
  5339. DieWithError('ERROR: No issue to close.')
  5340. cl.CloseIssue()
  5341. return 0
  5342. @metrics.collector.collect_metrics('git cl diff')
  5343. def CMDdiff(parser, args):
  5344. """Shows differences between local tree and last upload."""
  5345. if gclient_utils.IsEnvCog():
  5346. print(
  5347. 'diff command is not supported. Please navigate to source '
  5348. 'control view in the activity bar to check the diff.',
  5349. file=sys.stderr)
  5350. return 1
  5351. parser.add_option('--stat',
  5352. action='store_true',
  5353. dest='stat',
  5354. help='Generate a diffstat')
  5355. options, args = parser.parse_args(args)
  5356. if args:
  5357. parser.error('Unrecognized args: %s' % ' '.join(args))
  5358. cl = Changelist()
  5359. issue = cl.GetIssue()
  5360. branch = cl.GetBranch()
  5361. if not issue:
  5362. DieWithError('No issue found for current branch (%s)' % branch)
  5363. base = cl._GitGetBranchConfigValue(LAST_UPLOAD_HASH_CONFIG_KEY)
  5364. if not base:
  5365. base = cl._GitGetBranchConfigValue(GERRIT_SQUASH_HASH_CONFIG_KEY)
  5366. if not base:
  5367. detail = cl._GetChangeDetail(['CURRENT_REVISION', 'CURRENT_COMMIT'])
  5368. revision_info = detail['revisions'][detail['current_revision']]
  5369. fetch_info = revision_info['fetch']['http']
  5370. RunGit(['fetch', fetch_info['url'], fetch_info['ref']])
  5371. base = 'FETCH_HEAD'
  5372. cmd = ['git', 'diff']
  5373. if options.stat:
  5374. cmd.append('--stat')
  5375. cmd.append(base)
  5376. subprocess2.check_call(cmd)
  5377. return 0
  5378. @metrics.collector.collect_metrics('git cl owners')
  5379. def CMDowners(parser, args):
  5380. """Finds potential owners for reviewing."""
  5381. if gclient_utils.IsEnvCog():
  5382. print('owners command is not supported in non-git environment.',
  5383. file=sys.stderr)
  5384. return 1
  5385. parser.add_option(
  5386. '--ignore-current',
  5387. action='store_true',
  5388. help='Ignore the CL\'s current reviewers and start from scratch.')
  5389. parser.add_option('--ignore-self',
  5390. action='store_true',
  5391. help='Do not consider CL\'s author as an owners.')
  5392. parser.add_option('--no-color',
  5393. action='store_true',
  5394. help='Use this option to disable color output')
  5395. parser.add_option('--batch',
  5396. action='store_true',
  5397. help='Do not run interactively, just suggest some')
  5398. # TODO: Consider moving this to another command, since other
  5399. # git-cl owners commands deal with owners for a given CL.
  5400. parser.add_option('--show-all',
  5401. action='store_true',
  5402. help='Show all owners for a particular file')
  5403. options, args = parser.parse_args(args)
  5404. cl = Changelist()
  5405. author = cl.GetAuthor()
  5406. if options.show_all:
  5407. if len(args) == 0:
  5408. print('No files specified for --show-all. Nothing to do.')
  5409. return 0
  5410. owners_by_path = cl.owners_client.BatchListOwners(args)
  5411. for path in args:
  5412. print('Owners for %s:' % path)
  5413. print('\n'.join(
  5414. ' - %s' % owner
  5415. for owner in owners_by_path.get(path, ['No owners found'])))
  5416. return 0
  5417. if args:
  5418. if len(args) > 1:
  5419. parser.error('Unknown args.')
  5420. base_branch = args[0]
  5421. else:
  5422. # Default to diffing against the common ancestor of the upstream branch.
  5423. base_branch = cl.GetCommonAncestorWithUpstream()
  5424. affected_files = cl.GetAffectedFiles(base_branch)
  5425. if options.batch:
  5426. owners = cl.owners_client.SuggestOwners(affected_files,
  5427. exclude=[author])
  5428. print('\n'.join(owners))
  5429. return 0
  5430. return owners_finder.OwnersFinder(
  5431. affected_files,
  5432. author, [] if options.ignore_current else cl.GetReviewers(),
  5433. cl.owners_client,
  5434. disable_color=options.no_color,
  5435. ignore_author=options.ignore_self).run()
  5436. def _SplitArgsByCmdLineLimit(args):
  5437. """Splits a list of arguments into shorter lists that fit within the command
  5438. line limit."""
  5439. # The maximum command line length is 32768 characters on Windows and 2097152
  5440. # characters on other platforms. Use a lower limit to be safe.
  5441. command_line_limit = 30000 if sys.platform.startswith('win32') else 2000000
  5442. batch_args = []
  5443. batch_length = 0
  5444. for arg in args:
  5445. # Add 1 to account for the space between arguments.
  5446. arg_length = len(arg) + 1
  5447. # If the current argument is too long to fit in a single command line,
  5448. # split it into smaller parts.
  5449. if batch_length + arg_length > command_line_limit and batch_args:
  5450. yield batch_args
  5451. batch_args = []
  5452. batch_length = 0
  5453. batch_args.append(arg)
  5454. batch_length += arg_length
  5455. if batch_args:
  5456. yield batch_args
  5457. def RunGitDiffCmd(diff_type,
  5458. upstream_commit,
  5459. files,
  5460. allow_prefix=False,
  5461. **kwargs):
  5462. """Generates and runs diff command."""
  5463. # Generate diff for the current branch's changes.
  5464. diff_cmd = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff']
  5465. if allow_prefix:
  5466. # explicitly setting --src-prefix and --dst-prefix is necessary in the
  5467. # case that diff.noprefix is set in the user's git config.
  5468. diff_cmd += ['--src-prefix=a/', '--dst-prefix=b/']
  5469. else:
  5470. diff_cmd += ['--no-prefix']
  5471. diff_cmd += diff_type
  5472. diff_cmd += [upstream_commit, '--']
  5473. if not files:
  5474. return RunGit(diff_cmd, **kwargs)
  5475. for file in files:
  5476. if file != '-' and not os.path.isdir(file) and not os.path.isfile(file):
  5477. DieWithError('Argument "%s" is not a file or a directory' % file)
  5478. output = ''
  5479. for files_batch in _SplitArgsByCmdLineLimit(files):
  5480. output += RunGit(diff_cmd + files_batch, **kwargs)
  5481. return output
  5482. def _RunClangFormatDiff(opts, clang_diff_files, top_dir, upstream_commit):
  5483. """Runs clang-format-diff and sets a return value if necessary."""
  5484. # Set to 2 to signal to CheckPatchFormatted() that this patch isn't
  5485. # formatted. This is used to block during the presubmit.
  5486. return_value = 0
  5487. # Locate the clang-format binary in the checkout
  5488. try:
  5489. clang_format_tool = clang_format.FindClangFormatToolInChromiumTree()
  5490. except clang_format.NotFoundError as e:
  5491. DieWithError(e)
  5492. if opts.full or settings.GetFormatFullByDefault():
  5493. cmd = [clang_format_tool]
  5494. if not opts.dry_run and not opts.diff:
  5495. cmd.append('-i')
  5496. if opts.dry_run:
  5497. for diff_file in clang_diff_files:
  5498. with open(diff_file, 'r') as myfile:
  5499. code = myfile.read().replace('\r\n', '\n')
  5500. stdout = RunCommand(cmd + [diff_file], cwd=top_dir)
  5501. stdout = stdout.replace('\r\n', '\n')
  5502. if opts.diff:
  5503. sys.stdout.write(stdout)
  5504. if code != stdout:
  5505. return_value = 2
  5506. else:
  5507. stdout = RunCommand(cmd + clang_diff_files, cwd=top_dir)
  5508. if opts.diff:
  5509. sys.stdout.write(stdout)
  5510. else:
  5511. try:
  5512. script = clang_format.FindClangFormatScriptInChromiumTree(
  5513. 'clang-format-diff.py')
  5514. except clang_format.NotFoundError as e:
  5515. DieWithError(e)
  5516. cmd = ['vpython3', script, '-p0']
  5517. if not opts.dry_run and not opts.diff:
  5518. cmd.append('-i')
  5519. diff_output = RunGitDiffCmd(['-U0'], upstream_commit, clang_diff_files)
  5520. env = os.environ.copy()
  5521. env['PATH'] = (str(os.path.dirname(clang_format_tool)) + os.pathsep +
  5522. env['PATH'])
  5523. # If `clang-format-diff.py` is run without `-i` and the diff is
  5524. # non-empty, it returns an error code of 1. This will cause `RunCommand`
  5525. # to die with an error if `error_ok` is not set.
  5526. stdout = RunCommand(cmd,
  5527. error_ok=True,
  5528. stdin=diff_output.encode(),
  5529. cwd=top_dir,
  5530. env=env,
  5531. shell=sys.platform.startswith('win32'))
  5532. if opts.diff:
  5533. sys.stdout.write(stdout)
  5534. if opts.dry_run and len(stdout) > 0:
  5535. return_value = 2
  5536. return return_value
  5537. def _RunGoogleJavaFormat(opts, paths, top_dir, upstream_commit):
  5538. """Runs google-java-format and sets a return value if necessary."""
  5539. tool = google_java_format.FindGoogleJavaFormat()
  5540. if tool is None:
  5541. # Fail silently. It could be we are on an old chromium revision, or that
  5542. # it is a non-chromium project. https://crbug.com/1491627
  5543. print('google-java-format not found, skipping java formatting.')
  5544. return 0
  5545. base_cmd = [tool, '--aosp']
  5546. if not opts.diff:
  5547. if opts.dry_run:
  5548. base_cmd += ['--dry-run']
  5549. else:
  5550. base_cmd += ['--replace']
  5551. changed_lines_only = not (opts.full or settings.GetFormatFullByDefault())
  5552. if changed_lines_only:
  5553. # Format two lines around each changed line so that the correct amount
  5554. # of blank lines will be added between symbols.
  5555. line_diffs = _ComputeFormatDiffLineRanges(paths,
  5556. upstream_commit,
  5557. expand=2)
  5558. def RunFormat(cmd, path, range_args, **kwds):
  5559. stdout = RunCommand(cmd + range_args + [path], **kwds)
  5560. if changed_lines_only:
  5561. # google-java-format will not remove unused imports because they
  5562. # do not fall within the changed lines. Run the command again to
  5563. # remove them.
  5564. if opts.diff:
  5565. stdout = RunCommand(cmd + ['--fix-imports-only', '-'],
  5566. stdin=stdout.encode(),
  5567. **kwds)
  5568. else:
  5569. stdout += RunCommand(cmd + ['--fix-imports-only', path], **kwds)
  5570. # If --diff is passed, google-java-format will output formatted content.
  5571. # Diff it with the existing file in the checkout and output the result.
  5572. if opts.diff:
  5573. stdout = RunGitDiffCmd(['-U3'],
  5574. '--no-index', [path, '-'],
  5575. stdin=stdout.encode(),
  5576. **kwds)
  5577. return stdout
  5578. results = []
  5579. kwds = {'error_ok': True, 'cwd': top_dir}
  5580. with multiprocessing.pool.ThreadPool() as pool:
  5581. for path in paths:
  5582. cmd = base_cmd.copy()
  5583. range_args = []
  5584. if changed_lines_only:
  5585. ranges = line_diffs.get(path)
  5586. if not ranges:
  5587. # E.g. There were only deleted lines.
  5588. continue
  5589. range_args = ['--lines={}:{}'.format(a, b) for a, b in ranges]
  5590. results.append(
  5591. pool.apply_async(RunFormat,
  5592. args=[cmd, path, range_args],
  5593. kwds=kwds))
  5594. return_value = 0
  5595. for result in results:
  5596. stdout = result.get()
  5597. if stdout:
  5598. if opts.diff:
  5599. sys.stdout.write('Requires formatting: ' + stdout)
  5600. else:
  5601. return_value = 2
  5602. return return_value
  5603. def _RunRustFmt(opts, rust_diff_files, top_dir, upstream_commit):
  5604. """Runs rustfmt. Just like _RunClangFormatDiff returns 2 to indicate that
  5605. presubmit checks have failed (and returns 0 otherwise)."""
  5606. # Locate the rustfmt binary.
  5607. try:
  5608. rustfmt_tool = rustfmt.FindRustfmtToolInChromiumTree()
  5609. except rustfmt.NotFoundError as e:
  5610. DieWithError(e)
  5611. chromium_src_path = gclient_paths.GetPrimarySolutionPath()
  5612. rustfmt_toml_path = os.path.join(chromium_src_path, '.rustfmt.toml')
  5613. # TODO(crbug.com/1440869): Support formatting only the changed lines
  5614. # if `opts.full or settings.GetFormatFullByDefault()` is False.
  5615. cmd = [rustfmt_tool, f'--config-path={rustfmt_toml_path}']
  5616. if opts.dry_run:
  5617. cmd.append('--check')
  5618. cmd += rust_diff_files
  5619. rustfmt_exitcode = subprocess2.call(cmd)
  5620. if opts.presubmit and rustfmt_exitcode != 0:
  5621. return 2
  5622. return 0
  5623. def _RunSwiftFormat(opts, swift_diff_files, top_dir, upstream_commit):
  5624. """Runs swift-format. Just like _RunClangFormatDiff returns 2 to indicate
  5625. that presubmit checks have failed (and returns 0 otherwise)."""
  5626. if sys.platform != 'darwin':
  5627. DieWithError('swift-format is only supported on macOS.')
  5628. # Locate the swift-format binary.
  5629. try:
  5630. swift_format_tool = swift_format.FindSwiftFormatToolInChromiumTree()
  5631. except swift_format.NotFoundError as e:
  5632. DieWithError(e)
  5633. cmd = [swift_format_tool]
  5634. if opts.dry_run:
  5635. cmd += ['lint', '-s']
  5636. else:
  5637. cmd += ['format', '-i']
  5638. cmd += swift_diff_files
  5639. swift_format_exitcode = subprocess2.call(cmd)
  5640. if opts.presubmit and swift_format_exitcode != 0:
  5641. return 2
  5642. return 0
  5643. def _RunYapf(opts, paths, top_dir, upstream_commit):
  5644. depot_tools_path = os.path.dirname(os.path.abspath(__file__))
  5645. yapf_tool = os.path.join(depot_tools_path, 'yapf')
  5646. # Used for caching.
  5647. yapf_configs = {}
  5648. for p in paths:
  5649. # Find the yapf style config for the current file, defaults to depot
  5650. # tools default.
  5651. _FindYapfConfigFile(p, yapf_configs, top_dir)
  5652. # Turn on python formatting by default if a yapf config is specified.
  5653. # This breaks in the case of this repo though since the specified
  5654. # style file is also the global default.
  5655. if opts.python is None:
  5656. paths = [
  5657. p for p in paths
  5658. if _FindYapfConfigFile(p, yapf_configs, top_dir) is not None
  5659. ]
  5660. # Note: yapf still seems to fix indentation of the entire file
  5661. # even if line ranges are specified.
  5662. # See https://github.com/google/yapf/issues/499
  5663. if not opts.full and paths:
  5664. line_diffs = _ComputeFormatDiffLineRanges(paths, upstream_commit)
  5665. yapfignore_patterns = _GetYapfIgnorePatterns(top_dir)
  5666. paths = _FilterYapfIgnoredFiles(paths, yapfignore_patterns)
  5667. return_value = 0
  5668. for path in paths:
  5669. yapf_style = _FindYapfConfigFile(path, yapf_configs, top_dir)
  5670. # Default to pep8 if not .style.yapf is found.
  5671. if not yapf_style:
  5672. yapf_style = 'pep8'
  5673. cmd = ['vpython3', yapf_tool, '--style', yapf_style, path]
  5674. if not opts.full:
  5675. ranges = line_diffs.get(path)
  5676. if not ranges:
  5677. continue
  5678. # Only run yapf over changed line ranges.
  5679. for diff_start, diff_end in ranges:
  5680. cmd += ['-l', '{}-{}'.format(diff_start, diff_end)]
  5681. if opts.diff or opts.dry_run:
  5682. cmd += ['--diff']
  5683. # Will return non-zero exit code if non-empty diff.
  5684. stdout = RunCommand(cmd,
  5685. error_ok=True,
  5686. stderr=subprocess2.PIPE,
  5687. cwd=top_dir,
  5688. shell=sys.platform.startswith('win32'))
  5689. if opts.diff:
  5690. sys.stdout.write(stdout)
  5691. elif len(stdout) > 0:
  5692. return_value = 2
  5693. else:
  5694. cmd += ['-i']
  5695. RunCommand(cmd, cwd=top_dir, shell=sys.platform.startswith('win32'))
  5696. return return_value
  5697. def _RunGnFormat(opts, paths, top_dir, upstream_commit):
  5698. cmd = ['gn', 'format']
  5699. if opts.dry_run or opts.diff:
  5700. cmd.append('--dry-run')
  5701. return_value = 0
  5702. for path in paths:
  5703. gn_ret = subprocess2.call(cmd + [path],
  5704. shell=sys.platform.startswith('win'),
  5705. cwd=top_dir)
  5706. if opts.dry_run and gn_ret == 2:
  5707. return_value = 2 # Not formatted.
  5708. elif opts.diff and gn_ret == 2:
  5709. # TODO this should compute and print the actual diff.
  5710. print('This change has GN build file diff for ' + path)
  5711. elif gn_ret != 0:
  5712. # For non-dry run cases (and non-2 return values for dry-run), a
  5713. # nonzero error code indicates a failure, probably because the
  5714. # file doesn't parse.
  5715. DieWithError('gn format failed on ' + path +
  5716. '\nTry running `gn format` on this file manually.')
  5717. return return_value
  5718. def _RunMojomFormat(opts, paths, top_dir, upstream_commit):
  5719. primary_solution_path = gclient_paths.GetPrimarySolutionPath()
  5720. if not primary_solution_path:
  5721. DieWithError('Could not find the primary solution path (e.g. '
  5722. 'the chromium checkout)')
  5723. mojom_format_path = os.path.join(primary_solution_path, 'mojo', 'public',
  5724. 'tools', 'mojom', 'mojom_format.py')
  5725. if not os.path.exists(mojom_format_path):
  5726. DieWithError('Could not find mojom formater at '
  5727. f'"{mojom_format_path}"')
  5728. cmd = ['vpython3', mojom_format_path]
  5729. if opts.dry_run:
  5730. cmd.append('--dry-run')
  5731. cmd.extend(paths)
  5732. ret = subprocess2.call(cmd)
  5733. if opts.dry_run and ret != 0:
  5734. return 2
  5735. return ret
  5736. def _FormatXml(opts, paths, top_dir, upstream_commit):
  5737. # Skip the metrics formatting from the global presubmit hook. These files
  5738. # have a separate presubmit hook that issues an error if the files need
  5739. # formatting, whereas the top-level presubmit script merely issues a
  5740. # warning. Formatting these files is somewhat slow, so it's important not to
  5741. # duplicate the work.
  5742. if opts.presubmit:
  5743. return 0
  5744. return_value = 0
  5745. for path in paths:
  5746. xml_dir = GetMetricsDir(path)
  5747. if not xml_dir:
  5748. continue
  5749. tool_dir = os.path.join(top_dir, xml_dir.replace('/', os.path.sep))
  5750. pretty_print_tool = os.path.join(tool_dir, 'pretty_print.py')
  5751. cmd = [shutil.which('vpython3'), pretty_print_tool, '--non-interactive']
  5752. # If the XML file is histograms.xml or enums.xml, add the xml path
  5753. # to the command as histograms/pretty_print.py now needs a relative
  5754. # path argument after splitting the histograms into multiple
  5755. # directories. For example, in tools/metrics/ukm, pretty-print could
  5756. # be run using: $ python pretty_print.py But in
  5757. # tools/metrics/histogrmas, pretty-print should be run with an
  5758. # additional relative path argument, like: $ python pretty_print.py
  5759. # metadata/UMA/histograms.xml $ python pretty_print.py enums.xml
  5760. if xml_dir == 'tools/metrics/histograms':
  5761. if os.path.basename(path) not in ('histograms.xml', 'enums.xml',
  5762. 'histogram_suffixes_list.xml'):
  5763. # Skip this XML file if it's not one of the known types.
  5764. continue
  5765. cmd.append(path.replace('/', os.path.sep))
  5766. if opts.dry_run or opts.diff:
  5767. cmd.append('--diff')
  5768. stdout = RunCommand(cmd, cwd=top_dir)
  5769. if opts.diff:
  5770. sys.stdout.write(stdout)
  5771. if opts.dry_run and stdout:
  5772. return_value = 2 # Not formatted.
  5773. return return_value
  5774. def MatchingFileType(file_name, extensions):
  5775. """Returns True if the file name ends with one of the given extensions."""
  5776. return bool([ext for ext in extensions if file_name.lower().endswith(ext)])
  5777. @subcommand.usage('[files or directories to diff]')
  5778. @metrics.collector.collect_metrics('git cl format')
  5779. def CMDformat(parser, args):
  5780. """Runs auto-formatting tools (clang-format etc.) on the diff."""
  5781. if gclient_utils.IsEnvCog():
  5782. print(
  5783. 'format command is not supported. Please use the "Format '
  5784. 'Document" functionality in command palette in the Editor '
  5785. 'instead.',
  5786. file=sys.stderr)
  5787. return 1
  5788. clang_exts = ['.cc', '.cpp', '.h', '.m', '.mm', '.proto']
  5789. GN_EXTS = ['.gn', '.gni', '.typemap']
  5790. parser.add_option('--full',
  5791. action='store_true',
  5792. help='Reformat the full content of all touched files')
  5793. parser.add_option('--upstream', help='Branch to check against')
  5794. parser.add_option('--dry-run',
  5795. action='store_true',
  5796. help='Don\'t modify any file on disk.')
  5797. parser.add_option(
  5798. '--no-clang-format',
  5799. dest='clang_format',
  5800. action='store_false',
  5801. default=True,
  5802. help='Disables formatting of various file types using clang-format.')
  5803. parser.add_option('--python',
  5804. action='store_true',
  5805. help='Enables python formatting on all python files.')
  5806. parser.add_option(
  5807. '--no-python',
  5808. action='store_false',
  5809. dest='python',
  5810. help='Disables python formatting on all python files. '
  5811. 'If neither --python or --no-python are set, python files that have a '
  5812. '.style.yapf file in an ancestor directory will be formatted. '
  5813. 'It is an error to set both.')
  5814. parser.add_option('--js',
  5815. action='store_true',
  5816. help='Format javascript code with clang-format. '
  5817. 'Has no effect if --no-clang-format is set.')
  5818. parser.add_option('--diff',
  5819. action='store_true',
  5820. help='Print diff to stdout rather than modifying files.')
  5821. parser.add_option('--presubmit',
  5822. action='store_true',
  5823. help='Used when running the script from a presubmit.')
  5824. parser.add_option(
  5825. '--rust-fmt',
  5826. dest='use_rust_fmt',
  5827. action='store_true',
  5828. default=rustfmt.IsRustfmtSupported(),
  5829. help='Enables formatting of Rust file types using rustfmt.')
  5830. parser.add_option(
  5831. '--no-rust-fmt',
  5832. dest='use_rust_fmt',
  5833. action='store_false',
  5834. help='Disables formatting of Rust file types using rustfmt.')
  5835. parser.add_option(
  5836. '--swift-format',
  5837. dest='use_swift_format',
  5838. action='store_true',
  5839. default=swift_format.IsSwiftFormatSupported(),
  5840. help='Enables formatting of Swift file types using swift-format '
  5841. '(macOS host only).')
  5842. parser.add_option(
  5843. '--no-swift-format',
  5844. dest='use_swift_format',
  5845. action='store_false',
  5846. help='Disables formatting of Swift file types using swift-format.')
  5847. parser.add_option('--mojom',
  5848. action='store_true',
  5849. help='Enables formatting of .mojom files.')
  5850. parser.add_option('--no-java',
  5851. action='store_true',
  5852. help='Disable auto-formatting of .java')
  5853. opts, files = parser.parse_args(args)
  5854. # Normalize files against the current path, so paths relative to the
  5855. # current directory are still resolved as expected.
  5856. files = [os.path.join(os.getcwd(), file) for file in files]
  5857. # git diff generates paths against the root of the repository. Change
  5858. # to that directory so clang-format can find files even within subdirs.
  5859. rel_base_path = settings.GetRelativeRoot()
  5860. if rel_base_path:
  5861. os.chdir(rel_base_path)
  5862. # Grab the merge-base commit, i.e. the upstream commit of the current
  5863. # branch when it was created or the last time it was rebased. This is
  5864. # to cover the case where the user may have called "git fetch origin",
  5865. # moving the origin branch to a newer commit, but hasn't rebased yet.
  5866. upstream_commit = None
  5867. upstream_branch = opts.upstream
  5868. if not upstream_branch:
  5869. cl = Changelist()
  5870. upstream_branch = cl.GetUpstreamBranch()
  5871. if upstream_branch:
  5872. upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch])
  5873. upstream_commit = upstream_commit.strip()
  5874. if not upstream_commit:
  5875. DieWithError('Could not find base commit for this branch. '
  5876. 'Are you in detached state?')
  5877. # Filter out copied/renamed/deleted files
  5878. diff_output = RunGitDiffCmd(['--name-only', '--diff-filter=crd'],
  5879. upstream_commit, files)
  5880. diff_files = diff_output.splitlines()
  5881. if opts.js:
  5882. clang_exts.extend(['.js', '.ts'])
  5883. formatters = [
  5884. (GN_EXTS, _RunGnFormat),
  5885. (['.xml'], _FormatXml),
  5886. ]
  5887. if not opts.no_java:
  5888. formatters += [(['.java'], _RunGoogleJavaFormat)]
  5889. if opts.clang_format:
  5890. formatters += [(clang_exts, _RunClangFormatDiff)]
  5891. if opts.use_rust_fmt:
  5892. formatters += [(['.rs'], _RunRustFmt)]
  5893. if opts.use_swift_format:
  5894. formatters += [(['.swift'], _RunSwiftFormat)]
  5895. if opts.python is not False:
  5896. formatters += [(['.py'], _RunYapf)]
  5897. if opts.mojom:
  5898. formatters += [(['.mojom'], _RunMojomFormat)]
  5899. top_dir = settings.GetRoot()
  5900. return_value = 0
  5901. for file_types, format_func in formatters:
  5902. paths = [p for p in diff_files if MatchingFileType(p, file_types)]
  5903. if not paths:
  5904. continue
  5905. ret = format_func(opts, paths, top_dir, upstream_commit)
  5906. return_value = return_value or ret
  5907. return return_value
  5908. def GetMetricsDir(diff_xml):
  5909. metrics_xml_dirs = [
  5910. 'tools/metrics/actions',
  5911. 'tools/metrics/histograms',
  5912. 'tools/metrics/structured',
  5913. 'tools/metrics/ukm',
  5914. ]
  5915. for xml_dir in metrics_xml_dirs:
  5916. if diff_xml.startswith(xml_dir):
  5917. return xml_dir
  5918. return None
  5919. @subcommand.usage('<codereview url or issue id>')
  5920. @metrics.collector.collect_metrics('git cl checkout')
  5921. def CMDcheckout(parser, args):
  5922. """Checks out a branch associated with a given Gerrit issue."""
  5923. if gclient_utils.IsEnvCog():
  5924. print('checkout command is not supported in non-git environment.',
  5925. file=sys.stderr)
  5926. return 1
  5927. _, args = parser.parse_args(args)
  5928. if len(args) != 1:
  5929. parser.print_help()
  5930. return 1
  5931. issue_arg = ParseIssueNumberArgument(args[0])
  5932. if not issue_arg.valid:
  5933. parser.error('Invalid issue ID or URL.')
  5934. target_issue = str(issue_arg.issue)
  5935. output = scm.GIT.YieldConfigRegexp(
  5936. settings.GetRoot(), re.compile(r'branch\..*\.' + ISSUE_CONFIG_KEY))
  5937. branches = []
  5938. for key, issue in output:
  5939. if issue == target_issue:
  5940. branches.append(
  5941. re.sub(r'branch\.(.*)\.' + ISSUE_CONFIG_KEY, r'\1', key))
  5942. if len(branches) == 0:
  5943. print('No branch found for issue %s.' % target_issue)
  5944. return 1
  5945. if len(branches) == 1:
  5946. RunGit(['checkout', branches[0]])
  5947. else:
  5948. print('Multiple branches match issue %s:' % target_issue)
  5949. for i in range(len(branches)):
  5950. print('%d: %s' % (i, branches[i]))
  5951. which = gclient_utils.AskForData('Choose by index: ')
  5952. try:
  5953. RunGit(['checkout', branches[int(which)]])
  5954. except (IndexError, ValueError):
  5955. print('Invalid selection, not checking out any branch.')
  5956. return 1
  5957. return 0
  5958. def CMDlol(parser, args):
  5959. # This command is intentionally undocumented.
  5960. print(
  5961. zlib.decompress(
  5962. base64.b64decode(
  5963. 'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE'
  5964. 'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9'
  5965. 'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W'
  5966. 'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY')).decode('utf-8'))
  5967. return 0
  5968. def CMDversion(parser, args):
  5969. import utils
  5970. print(utils.depot_tools_version())
  5971. class OptionParser(optparse.OptionParser):
  5972. """Creates the option parse and add --verbose support."""
  5973. def __init__(self, *args, **kwargs):
  5974. optparse.OptionParser.__init__(self,
  5975. *args,
  5976. prog='git cl',
  5977. version=__version__,
  5978. **kwargs)
  5979. self.add_option('-v',
  5980. '--verbose',
  5981. action='count',
  5982. default=0,
  5983. help='Use 2 times for more debugging info')
  5984. def parse_args(self, args=None, _values=None):
  5985. try:
  5986. return self._parse_args(args)
  5987. finally:
  5988. if metrics.collector.config.should_collect_metrics:
  5989. try:
  5990. # GetViewVCUrl ultimately calls logging method.
  5991. project_url = settings.GetViewVCUrl().strip('/+')
  5992. if project_url in metrics_utils.KNOWN_PROJECT_URLS:
  5993. metrics.collector.add('project_urls', [project_url])
  5994. except subprocess2.CalledProcessError:
  5995. # Occurs when command is not executed in a git repository
  5996. # We should not fail here. If the command needs to be
  5997. # executed in a repo, it will be raised later.
  5998. pass
  5999. def _parse_args(self, args=None):
  6000. # Create an optparse.Values object that will store only the actual
  6001. # passed options, without the defaults.
  6002. actual_options = optparse.Values()
  6003. _, args = optparse.OptionParser.parse_args(self, args, actual_options)
  6004. # Create an optparse.Values object with the default options.
  6005. options = optparse.Values(self.get_default_values().__dict__)
  6006. # Update it with the options passed by the user.
  6007. options._update_careful(actual_options.__dict__)
  6008. # Store the options passed by the user in an _actual_options attribute.
  6009. # We store only the keys, and not the values, since the values can
  6010. # contain arbitrary information, which might be PII.
  6011. metrics.collector.add('arguments', list(actual_options.__dict__.keys()))
  6012. levels = [logging.WARNING, logging.INFO, logging.DEBUG]
  6013. logging.basicConfig(
  6014. level=levels[min(options.verbose,
  6015. len(levels) - 1)],
  6016. format='[%(levelname).1s%(asctime)s %(process)d %(thread)d '
  6017. '%(filename)s] %(message)s')
  6018. return options, args
  6019. def main(argv):
  6020. colorize_CMDstatus_doc()
  6021. dispatcher = subcommand.CommandDispatcher(__name__)
  6022. try:
  6023. return dispatcher.execute(OptionParser(), argv)
  6024. except gerrit_util.GerritError as e:
  6025. DieWithError(str(e))
  6026. except auth.LoginRequiredError as e:
  6027. DieWithError(str(e))
  6028. except urllib.error.HTTPError as e:
  6029. if e.code != 500:
  6030. raise
  6031. DieWithError((
  6032. 'App Engine is misbehaving and returned HTTP %d, again. Keep faith '
  6033. 'and retry or visit go/isgaeup.\n%s') % (e.code, str(e)))
  6034. return 0
  6035. if __name__ == '__main__':
  6036. # These affect sys.stdout, so do it outside of main() to simplify mocks in
  6037. # the unit tests.
  6038. setup_color.init()
  6039. with metrics.collector.print_notice_and_exit():
  6040. sys.exit(main(sys.argv[1:]))