git_cl.py 261 KB

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