git_cl.py 207 KB

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