git_cl.py 219 KB

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