git_cl.py 225 KB

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