git_cl.py 200 KB

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