git_cl.py 259 KB

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