git_cl.py 276 KB

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