git_cl.py 196 KB

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