git_cl.py 278 KB

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