git_cl.py 232 KB

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