git_cl.py 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679
  1. #!/usr/bin/env python
  2. # Copyright (c) 2012 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. # Copyright (C) 2008 Evan Martin <martine@danga.com>
  6. """A git-command for integrating reviews on Rietveld."""
  7. from distutils.version import LooseVersion
  8. from multiprocessing.pool import ThreadPool
  9. import base64
  10. import collections
  11. import glob
  12. import httplib
  13. import json
  14. import logging
  15. import optparse
  16. import os
  17. import Queue
  18. import re
  19. import stat
  20. import sys
  21. import tempfile
  22. import textwrap
  23. import time
  24. import traceback
  25. import urllib2
  26. import urlparse
  27. import webbrowser
  28. import zlib
  29. try:
  30. import readline # pylint: disable=F0401,W0611
  31. except ImportError:
  32. pass
  33. from third_party import colorama
  34. from third_party import httplib2
  35. from third_party import upload
  36. import auth
  37. from luci_hacks import trigger_luci_job as luci_trigger
  38. import breakpad # pylint: disable=W0611
  39. import clang_format
  40. import dart_format
  41. import fix_encoding
  42. import gclient_utils
  43. import git_common
  44. from git_footers import get_footer_svn_id
  45. import owners
  46. import owners_finder
  47. import presubmit_support
  48. import rietveld
  49. import scm
  50. import subcommand
  51. import subprocess2
  52. import watchlists
  53. __version__ = '1.0'
  54. DEFAULT_SERVER = 'https://codereview.appspot.com'
  55. POSTUPSTREAM_HOOK_PATTERN = '.git/hooks/post-cl-%s'
  56. DESCRIPTION_BACKUP_FILE = '~/.git_cl_description_backup'
  57. GIT_INSTRUCTIONS_URL = 'http://code.google.com/p/chromium/wiki/UsingGit'
  58. CHANGE_ID = 'Change-Id:'
  59. REFS_THAT_ALIAS_TO_OTHER_REFS = {
  60. 'refs/remotes/origin/lkgr': 'refs/remotes/origin/master',
  61. 'refs/remotes/origin/lkcr': 'refs/remotes/origin/master',
  62. }
  63. # Valid extensions for files we want to lint.
  64. DEFAULT_LINT_REGEX = r"(.*\.cpp|.*\.cc|.*\.h)"
  65. DEFAULT_LINT_IGNORE_REGEX = r"$^"
  66. # Shortcut since it quickly becomes redundant.
  67. Fore = colorama.Fore
  68. # Initialized in main()
  69. settings = None
  70. def DieWithError(message):
  71. print >> sys.stderr, message
  72. sys.exit(1)
  73. def GetNoGitPagerEnv():
  74. env = os.environ.copy()
  75. # 'cat' is a magical git string that disables pagers on all platforms.
  76. env['GIT_PAGER'] = 'cat'
  77. return env
  78. def RunCommand(args, error_ok=False, error_message=None, **kwargs):
  79. try:
  80. return subprocess2.check_output(args, shell=False, **kwargs)
  81. except subprocess2.CalledProcessError as e:
  82. logging.debug('Failed running %s', args)
  83. if not error_ok:
  84. DieWithError(
  85. 'Command "%s" failed.\n%s' % (
  86. ' '.join(args), error_message or e.stdout or ''))
  87. return e.stdout
  88. def RunGit(args, **kwargs):
  89. """Returns stdout."""
  90. return RunCommand(['git'] + args, **kwargs)
  91. def RunGitWithCode(args, suppress_stderr=False):
  92. """Returns return code and stdout."""
  93. try:
  94. if suppress_stderr:
  95. stderr = subprocess2.VOID
  96. else:
  97. stderr = sys.stderr
  98. out, code = subprocess2.communicate(['git'] + args,
  99. env=GetNoGitPagerEnv(),
  100. stdout=subprocess2.PIPE,
  101. stderr=stderr)
  102. return code, out[0]
  103. except ValueError:
  104. # When the subprocess fails, it returns None. That triggers a ValueError
  105. # when trying to unpack the return value into (out, code).
  106. return 1, ''
  107. def RunGitSilent(args):
  108. """Returns stdout, suppresses stderr and ingores the return code."""
  109. return RunGitWithCode(args, suppress_stderr=True)[1]
  110. def IsGitVersionAtLeast(min_version):
  111. prefix = 'git version '
  112. version = RunGit(['--version']).strip()
  113. return (version.startswith(prefix) and
  114. LooseVersion(version[len(prefix):]) >= LooseVersion(min_version))
  115. def BranchExists(branch):
  116. """Return True if specified branch exists."""
  117. code, _ = RunGitWithCode(['rev-parse', '--verify', branch],
  118. suppress_stderr=True)
  119. return not code
  120. def ask_for_data(prompt):
  121. try:
  122. return raw_input(prompt)
  123. except KeyboardInterrupt:
  124. # Hide the exception.
  125. sys.exit(1)
  126. def git_set_branch_value(key, value):
  127. branch = Changelist().GetBranch()
  128. if not branch:
  129. return
  130. cmd = ['config']
  131. if isinstance(value, int):
  132. cmd.append('--int')
  133. git_key = 'branch.%s.%s' % (branch, key)
  134. RunGit(cmd + [git_key, str(value)])
  135. def git_get_branch_default(key, default):
  136. branch = Changelist().GetBranch()
  137. if branch:
  138. git_key = 'branch.%s.%s' % (branch, key)
  139. (_, stdout) = RunGitWithCode(['config', '--int', '--get', git_key])
  140. try:
  141. return int(stdout.strip())
  142. except ValueError:
  143. pass
  144. return default
  145. def add_git_similarity(parser):
  146. parser.add_option(
  147. '--similarity', metavar='SIM', type='int', action='store',
  148. help='Sets the percentage that a pair of files need to match in order to'
  149. ' be considered copies (default 50)')
  150. parser.add_option(
  151. '--find-copies', action='store_true',
  152. help='Allows git to look for copies.')
  153. parser.add_option(
  154. '--no-find-copies', action='store_false', dest='find_copies',
  155. help='Disallows git from looking for copies.')
  156. old_parser_args = parser.parse_args
  157. def Parse(args):
  158. options, args = old_parser_args(args)
  159. if options.similarity is None:
  160. options.similarity = git_get_branch_default('git-cl-similarity', 50)
  161. else:
  162. print('Note: Saving similarity of %d%% in git config.'
  163. % options.similarity)
  164. git_set_branch_value('git-cl-similarity', options.similarity)
  165. options.similarity = max(0, min(options.similarity, 100))
  166. if options.find_copies is None:
  167. options.find_copies = bool(
  168. git_get_branch_default('git-find-copies', True))
  169. else:
  170. git_set_branch_value('git-find-copies', int(options.find_copies))
  171. print('Using %d%% similarity for rename/copy detection. '
  172. 'Override with --similarity.' % options.similarity)
  173. return options, args
  174. parser.parse_args = Parse
  175. def _get_properties_from_options(options):
  176. properties = dict(x.split('=', 1) for x in options.properties)
  177. for key, val in properties.iteritems():
  178. try:
  179. properties[key] = json.loads(val)
  180. except ValueError:
  181. pass # If a value couldn't be evaluated, treat it as a string.
  182. return properties
  183. def _prefix_master(master):
  184. """Convert user-specified master name to full master name.
  185. Buildbucket uses full master name(master.tryserver.chromium.linux) as bucket
  186. name, while the developers always use shortened master name
  187. (tryserver.chromium.linux) by stripping off the prefix 'master.'. This
  188. function does the conversion for buildbucket migration.
  189. """
  190. prefix = 'master.'
  191. if master.startswith(prefix):
  192. return master
  193. return '%s%s' % (prefix, master)
  194. def trigger_luci_job(changelist, masters, options):
  195. """Send a job to run on LUCI."""
  196. issue_props = changelist.GetIssueProperties()
  197. issue = changelist.GetIssue()
  198. patchset = changelist.GetMostRecentPatchset()
  199. for builders_and_tests in sorted(masters.itervalues()):
  200. # TODO(hinoka et al): add support for other properties.
  201. # Currently, this completely ignores testfilter and other properties.
  202. for builder in sorted(builders_and_tests):
  203. luci_trigger.trigger(
  204. builder, 'HEAD', issue, patchset, issue_props['project'])
  205. def trigger_try_jobs(auth_config, changelist, options, masters, category):
  206. rietveld_url = settings.GetDefaultServerUrl()
  207. rietveld_host = urlparse.urlparse(rietveld_url).hostname
  208. authenticator = auth.get_authenticator_for_host(rietveld_host, auth_config)
  209. http = authenticator.authorize(httplib2.Http())
  210. http.force_exception_to_status_code = True
  211. issue_props = changelist.GetIssueProperties()
  212. issue = changelist.GetIssue()
  213. patchset = changelist.GetMostRecentPatchset()
  214. properties = _get_properties_from_options(options)
  215. buildbucket_put_url = (
  216. 'https://{hostname}/_ah/api/buildbucket/v1/builds/batch'.format(
  217. hostname=options.buildbucket_host))
  218. buildset = 'patch/rietveld/{hostname}/{issue}/{patch}'.format(
  219. hostname=rietveld_host,
  220. issue=issue,
  221. patch=patchset)
  222. batch_req_body = {'builds': []}
  223. print_text = []
  224. print_text.append('Tried jobs on:')
  225. for master, builders_and_tests in sorted(masters.iteritems()):
  226. print_text.append('Master: %s' % master)
  227. bucket = _prefix_master(master)
  228. for builder, tests in sorted(builders_and_tests.iteritems()):
  229. print_text.append(' %s: %s' % (builder, tests))
  230. parameters = {
  231. 'builder_name': builder,
  232. 'changes': [{
  233. 'author': {'email': issue_props['owner_email']},
  234. 'revision': options.revision,
  235. }],
  236. 'properties': {
  237. 'category': category,
  238. 'issue': issue,
  239. 'master': master,
  240. 'patch_project': issue_props['project'],
  241. 'patch_storage': 'rietveld',
  242. 'patchset': patchset,
  243. 'reason': options.name,
  244. 'rietveld': rietveld_url,
  245. },
  246. }
  247. if tests:
  248. parameters['properties']['testfilter'] = tests
  249. if properties:
  250. parameters['properties'].update(properties)
  251. if options.clobber:
  252. parameters['properties']['clobber'] = True
  253. batch_req_body['builds'].append(
  254. {
  255. 'bucket': bucket,
  256. 'parameters_json': json.dumps(parameters),
  257. 'tags': ['builder:%s' % builder,
  258. 'buildset:%s' % buildset,
  259. 'master:%s' % master,
  260. 'user_agent:git_cl_try']
  261. }
  262. )
  263. for try_count in xrange(3):
  264. response, content = http.request(
  265. buildbucket_put_url,
  266. 'PUT',
  267. body=json.dumps(batch_req_body),
  268. headers={'Content-Type': 'application/json'},
  269. )
  270. content_json = None
  271. try:
  272. content_json = json.loads(content)
  273. except ValueError:
  274. pass
  275. # Buildbucket could return an error even if status==200.
  276. if content_json and content_json.get('error'):
  277. msg = 'Error in response. Code: %d. Reason: %s. Message: %s.' % (
  278. content_json['error'].get('code', ''),
  279. content_json['error'].get('reason', ''),
  280. content_json['error'].get('message', ''))
  281. raise BuildbucketResponseException(msg)
  282. if response.status == 200:
  283. if not content_json:
  284. raise BuildbucketResponseException(
  285. 'Buildbucket returns invalid json content: %s.\n'
  286. 'Please file bugs at crbug.com, label "Infra-BuildBucket".' %
  287. content)
  288. break
  289. if response.status < 500 or try_count >= 2:
  290. raise httplib2.HttpLib2Error(content)
  291. # status >= 500 means transient failures.
  292. logging.debug('Transient errors when triggering tryjobs. Will retry.')
  293. time.sleep(0.5 + 1.5*try_count)
  294. print '\n'.join(print_text)
  295. def MatchSvnGlob(url, base_url, glob_spec, allow_wildcards):
  296. """Return the corresponding git ref if |base_url| together with |glob_spec|
  297. matches the full |url|.
  298. If |allow_wildcards| is true, |glob_spec| can contain wildcards (see below).
  299. """
  300. fetch_suburl, as_ref = glob_spec.split(':')
  301. if allow_wildcards:
  302. glob_match = re.match('(.+/)?(\*|{[^/]*})(/.+)?', fetch_suburl)
  303. if glob_match:
  304. # Parse specs like "branches/*/src:refs/remotes/svn/*" or
  305. # "branches/{472,597,648}/src:refs/remotes/svn/*".
  306. branch_re = re.escape(base_url)
  307. if glob_match.group(1):
  308. branch_re += '/' + re.escape(glob_match.group(1))
  309. wildcard = glob_match.group(2)
  310. if wildcard == '*':
  311. branch_re += '([^/]*)'
  312. else:
  313. # Escape and replace surrounding braces with parentheses and commas
  314. # with pipe symbols.
  315. wildcard = re.escape(wildcard)
  316. wildcard = re.sub('^\\\\{', '(', wildcard)
  317. wildcard = re.sub('\\\\,', '|', wildcard)
  318. wildcard = re.sub('\\\\}$', ')', wildcard)
  319. branch_re += wildcard
  320. if glob_match.group(3):
  321. branch_re += re.escape(glob_match.group(3))
  322. match = re.match(branch_re, url)
  323. if match:
  324. return re.sub('\*$', match.group(1), as_ref)
  325. # Parse specs like "trunk/src:refs/remotes/origin/trunk".
  326. if fetch_suburl:
  327. full_url = base_url + '/' + fetch_suburl
  328. else:
  329. full_url = base_url
  330. if full_url == url:
  331. return as_ref
  332. return None
  333. def print_stats(similarity, find_copies, args):
  334. """Prints statistics about the change to the user."""
  335. # --no-ext-diff is broken in some versions of Git, so try to work around
  336. # this by overriding the environment (but there is still a problem if the
  337. # git config key "diff.external" is used).
  338. env = GetNoGitPagerEnv()
  339. if 'GIT_EXTERNAL_DIFF' in env:
  340. del env['GIT_EXTERNAL_DIFF']
  341. if find_copies:
  342. similarity_options = ['--find-copies-harder', '-l100000',
  343. '-C%s' % similarity]
  344. else:
  345. similarity_options = ['-M%s' % similarity]
  346. try:
  347. stdout = sys.stdout.fileno()
  348. except AttributeError:
  349. stdout = None
  350. return subprocess2.call(
  351. ['git',
  352. 'diff', '--no-ext-diff', '--stat'] + similarity_options + args,
  353. stdout=stdout, env=env)
  354. class BuildbucketResponseException(Exception):
  355. pass
  356. class Settings(object):
  357. def __init__(self):
  358. self.default_server = None
  359. self.cc = None
  360. self.root = None
  361. self.is_git_svn = None
  362. self.svn_branch = None
  363. self.tree_status_url = None
  364. self.viewvc_url = None
  365. self.updated = False
  366. self.is_gerrit = None
  367. self.git_editor = None
  368. self.project = None
  369. self.force_https_commit_url = None
  370. self.pending_ref_prefix = None
  371. def LazyUpdateIfNeeded(self):
  372. """Updates the settings from a codereview.settings file, if available."""
  373. if not self.updated:
  374. # The only value that actually changes the behavior is
  375. # autoupdate = "false". Everything else means "true".
  376. autoupdate = RunGit(['config', 'rietveld.autoupdate'],
  377. error_ok=True
  378. ).strip().lower()
  379. cr_settings_file = FindCodereviewSettingsFile()
  380. if autoupdate != 'false' and cr_settings_file:
  381. LoadCodereviewSettingsFromFile(cr_settings_file)
  382. # set updated to True to avoid infinite calling loop
  383. # through DownloadHooks
  384. self.updated = True
  385. DownloadHooks(False)
  386. self.updated = True
  387. def GetDefaultServerUrl(self, error_ok=False):
  388. if not self.default_server:
  389. self.LazyUpdateIfNeeded()
  390. self.default_server = gclient_utils.UpgradeToHttps(
  391. self._GetRietveldConfig('server', error_ok=True))
  392. if error_ok:
  393. return self.default_server
  394. if not self.default_server:
  395. error_message = ('Could not find settings file. You must configure '
  396. 'your review setup by running "git cl config".')
  397. self.default_server = gclient_utils.UpgradeToHttps(
  398. self._GetRietveldConfig('server', error_message=error_message))
  399. return self.default_server
  400. @staticmethod
  401. def GetRelativeRoot():
  402. return RunGit(['rev-parse', '--show-cdup']).strip()
  403. def GetRoot(self):
  404. if self.root is None:
  405. self.root = os.path.abspath(self.GetRelativeRoot())
  406. return self.root
  407. def GetIsGitSvn(self):
  408. """Return true if this repo looks like it's using git-svn."""
  409. if self.is_git_svn is None:
  410. if self.GetPendingRefPrefix():
  411. # If PENDING_REF_PREFIX is set then it's a pure git repo no matter what.
  412. self.is_git_svn = False
  413. else:
  414. # If you have any "svn-remote.*" config keys, we think you're using svn.
  415. self.is_git_svn = RunGitWithCode(
  416. ['config', '--local', '--get-regexp', r'^svn-remote\.'])[0] == 0
  417. return self.is_git_svn
  418. def GetSVNBranch(self):
  419. if self.svn_branch is None:
  420. if not self.GetIsGitSvn():
  421. DieWithError('Repo doesn\'t appear to be a git-svn repo.')
  422. # Try to figure out which remote branch we're based on.
  423. # Strategy:
  424. # 1) iterate through our branch history and find the svn URL.
  425. # 2) find the svn-remote that fetches from the URL.
  426. # regexp matching the git-svn line that contains the URL.
  427. git_svn_re = re.compile(r'^\s*git-svn-id: (\S+)@', re.MULTILINE)
  428. # We don't want to go through all of history, so read a line from the
  429. # pipe at a time.
  430. # The -100 is an arbitrary limit so we don't search forever.
  431. cmd = ['git', 'log', '-100', '--pretty=medium']
  432. proc = subprocess2.Popen(cmd, stdout=subprocess2.PIPE,
  433. env=GetNoGitPagerEnv())
  434. url = None
  435. for line in proc.stdout:
  436. match = git_svn_re.match(line)
  437. if match:
  438. url = match.group(1)
  439. proc.stdout.close() # Cut pipe.
  440. break
  441. if url:
  442. svn_remote_re = re.compile(r'^svn-remote\.([^.]+)\.url (.*)$')
  443. remotes = RunGit(['config', '--get-regexp',
  444. r'^svn-remote\..*\.url']).splitlines()
  445. for remote in remotes:
  446. match = svn_remote_re.match(remote)
  447. if match:
  448. remote = match.group(1)
  449. base_url = match.group(2)
  450. rewrite_root = RunGit(
  451. ['config', 'svn-remote.%s.rewriteRoot' % remote],
  452. error_ok=True).strip()
  453. if rewrite_root:
  454. base_url = rewrite_root
  455. fetch_spec = RunGit(
  456. ['config', 'svn-remote.%s.fetch' % remote],
  457. error_ok=True).strip()
  458. if fetch_spec:
  459. self.svn_branch = MatchSvnGlob(url, base_url, fetch_spec, False)
  460. if self.svn_branch:
  461. break
  462. branch_spec = RunGit(
  463. ['config', 'svn-remote.%s.branches' % remote],
  464. error_ok=True).strip()
  465. if branch_spec:
  466. self.svn_branch = MatchSvnGlob(url, base_url, branch_spec, True)
  467. if self.svn_branch:
  468. break
  469. tag_spec = RunGit(
  470. ['config', 'svn-remote.%s.tags' % remote],
  471. error_ok=True).strip()
  472. if tag_spec:
  473. self.svn_branch = MatchSvnGlob(url, base_url, tag_spec, True)
  474. if self.svn_branch:
  475. break
  476. if not self.svn_branch:
  477. DieWithError('Can\'t guess svn branch -- try specifying it on the '
  478. 'command line')
  479. return self.svn_branch
  480. def GetTreeStatusUrl(self, error_ok=False):
  481. if not self.tree_status_url:
  482. error_message = ('You must configure your tree status URL by running '
  483. '"git cl config".')
  484. self.tree_status_url = self._GetRietveldConfig(
  485. 'tree-status-url', error_ok=error_ok, error_message=error_message)
  486. return self.tree_status_url
  487. def GetViewVCUrl(self):
  488. if not self.viewvc_url:
  489. self.viewvc_url = self._GetRietveldConfig('viewvc-url', error_ok=True)
  490. return self.viewvc_url
  491. def GetBugPrefix(self):
  492. return self._GetRietveldConfig('bug-prefix', error_ok=True)
  493. def GetIsSkipDependencyUpload(self, branch_name):
  494. """Returns true if specified branch should skip dep uploads."""
  495. return self._GetBranchConfig(branch_name, 'skip-deps-uploads',
  496. error_ok=True)
  497. def GetRunPostUploadHook(self):
  498. run_post_upload_hook = self._GetRietveldConfig(
  499. 'run-post-upload-hook', error_ok=True)
  500. return run_post_upload_hook == "True"
  501. def GetDefaultCCList(self):
  502. return self._GetRietveldConfig('cc', error_ok=True)
  503. def GetDefaultPrivateFlag(self):
  504. return self._GetRietveldConfig('private', error_ok=True)
  505. def GetIsGerrit(self):
  506. """Return true if this repo is assosiated with gerrit code review system."""
  507. if self.is_gerrit is None:
  508. self.is_gerrit = self._GetConfig('gerrit.host', error_ok=True)
  509. return self.is_gerrit
  510. def GetGitEditor(self):
  511. """Return the editor specified in the git config, or None if none is."""
  512. if self.git_editor is None:
  513. self.git_editor = self._GetConfig('core.editor', error_ok=True)
  514. return self.git_editor or None
  515. def GetLintRegex(self):
  516. return (self._GetRietveldConfig('cpplint-regex', error_ok=True) or
  517. DEFAULT_LINT_REGEX)
  518. def GetLintIgnoreRegex(self):
  519. return (self._GetRietveldConfig('cpplint-ignore-regex', error_ok=True) or
  520. DEFAULT_LINT_IGNORE_REGEX)
  521. def GetProject(self):
  522. if not self.project:
  523. self.project = self._GetRietveldConfig('project', error_ok=True)
  524. return self.project
  525. def GetForceHttpsCommitUrl(self):
  526. if not self.force_https_commit_url:
  527. self.force_https_commit_url = self._GetRietveldConfig(
  528. 'force-https-commit-url', error_ok=True)
  529. return self.force_https_commit_url
  530. def GetPendingRefPrefix(self):
  531. if not self.pending_ref_prefix:
  532. self.pending_ref_prefix = self._GetRietveldConfig(
  533. 'pending-ref-prefix', error_ok=True)
  534. return self.pending_ref_prefix
  535. def _GetRietveldConfig(self, param, **kwargs):
  536. return self._GetConfig('rietveld.' + param, **kwargs)
  537. def _GetBranchConfig(self, branch_name, param, **kwargs):
  538. return self._GetConfig('branch.' + branch_name + '.' + param, **kwargs)
  539. def _GetConfig(self, param, **kwargs):
  540. self.LazyUpdateIfNeeded()
  541. return RunGit(['config', param], **kwargs).strip()
  542. def ShortBranchName(branch):
  543. """Convert a name like 'refs/heads/foo' to just 'foo'."""
  544. return branch.replace('refs/heads/', '')
  545. class Changelist(object):
  546. def __init__(self, branchref=None, issue=None, auth_config=None):
  547. # Poke settings so we get the "configure your server" message if necessary.
  548. global settings
  549. if not settings:
  550. # Happens when git_cl.py is used as a utility library.
  551. settings = Settings()
  552. settings.GetDefaultServerUrl()
  553. self.branchref = branchref
  554. if self.branchref:
  555. self.branch = ShortBranchName(self.branchref)
  556. else:
  557. self.branch = None
  558. self.rietveld_server = None
  559. self.upstream_branch = None
  560. self.lookedup_issue = False
  561. self.issue = issue or None
  562. self.has_description = False
  563. self.description = None
  564. self.lookedup_patchset = False
  565. self.patchset = None
  566. self.cc = None
  567. self.watchers = ()
  568. self._auth_config = auth_config
  569. self._props = None
  570. self._remote = None
  571. self._rpc_server = None
  572. @property
  573. def auth_config(self):
  574. return self._auth_config
  575. def GetCCList(self):
  576. """Return the users cc'd on this CL.
  577. Return is a string suitable for passing to gcl with the --cc flag.
  578. """
  579. if self.cc is None:
  580. base_cc = settings.GetDefaultCCList()
  581. more_cc = ','.join(self.watchers)
  582. self.cc = ','.join(filter(None, (base_cc, more_cc))) or ''
  583. return self.cc
  584. def GetCCListWithoutDefault(self):
  585. """Return the users cc'd on this CL excluding default ones."""
  586. if self.cc is None:
  587. self.cc = ','.join(self.watchers)
  588. return self.cc
  589. def SetWatchers(self, watchers):
  590. """Set the list of email addresses that should be cc'd based on the changed
  591. files in this CL.
  592. """
  593. self.watchers = watchers
  594. def GetBranch(self):
  595. """Returns the short branch name, e.g. 'master'."""
  596. if not self.branch:
  597. branchref = RunGit(['symbolic-ref', 'HEAD'],
  598. stderr=subprocess2.VOID, error_ok=True).strip()
  599. if not branchref:
  600. return None
  601. self.branchref = branchref
  602. self.branch = ShortBranchName(self.branchref)
  603. return self.branch
  604. def GetBranchRef(self):
  605. """Returns the full branch name, e.g. 'refs/heads/master'."""
  606. self.GetBranch() # Poke the lazy loader.
  607. return self.branchref
  608. @staticmethod
  609. def FetchUpstreamTuple(branch):
  610. """Returns a tuple containing remote and remote ref,
  611. e.g. 'origin', 'refs/heads/master'
  612. """
  613. remote = '.'
  614. upstream_branch = RunGit(['config', 'branch.%s.merge' % branch],
  615. error_ok=True).strip()
  616. if upstream_branch:
  617. remote = RunGit(['config', 'branch.%s.remote' % branch]).strip()
  618. else:
  619. upstream_branch = RunGit(['config', 'rietveld.upstream-branch'],
  620. error_ok=True).strip()
  621. if upstream_branch:
  622. remote = RunGit(['config', 'rietveld.upstream-remote']).strip()
  623. else:
  624. # Fall back on trying a git-svn upstream branch.
  625. if settings.GetIsGitSvn():
  626. upstream_branch = settings.GetSVNBranch()
  627. else:
  628. # Else, try to guess the origin remote.
  629. remote_branches = RunGit(['branch', '-r']).split()
  630. if 'origin/master' in remote_branches:
  631. # Fall back on origin/master if it exits.
  632. remote = 'origin'
  633. upstream_branch = 'refs/heads/master'
  634. elif 'origin/trunk' in remote_branches:
  635. # Fall back on origin/trunk if it exists. Generally a shared
  636. # git-svn clone
  637. remote = 'origin'
  638. upstream_branch = 'refs/heads/trunk'
  639. else:
  640. DieWithError("""Unable to determine default branch to diff against.
  641. Either pass complete "git diff"-style arguments, like
  642. git cl upload origin/master
  643. or verify this branch is set up to track another (via the --track argument to
  644. "git checkout -b ...").""")
  645. return remote, upstream_branch
  646. def GetCommonAncestorWithUpstream(self):
  647. upstream_branch = self.GetUpstreamBranch()
  648. if not BranchExists(upstream_branch):
  649. DieWithError('The upstream for the current branch (%s) does not exist '
  650. 'anymore.\nPlease fix it and try again.' % self.GetBranch())
  651. return git_common.get_or_create_merge_base(self.GetBranch(),
  652. upstream_branch)
  653. def GetUpstreamBranch(self):
  654. if self.upstream_branch is None:
  655. remote, upstream_branch = self.FetchUpstreamTuple(self.GetBranch())
  656. if remote is not '.':
  657. upstream_branch = upstream_branch.replace('refs/heads/',
  658. 'refs/remotes/%s/' % remote)
  659. upstream_branch = upstream_branch.replace('refs/branch-heads/',
  660. 'refs/remotes/branch-heads/')
  661. self.upstream_branch = upstream_branch
  662. return self.upstream_branch
  663. def GetRemoteBranch(self):
  664. if not self._remote:
  665. remote, branch = None, self.GetBranch()
  666. seen_branches = set()
  667. while branch not in seen_branches:
  668. seen_branches.add(branch)
  669. remote, branch = self.FetchUpstreamTuple(branch)
  670. branch = ShortBranchName(branch)
  671. if remote != '.' or branch.startswith('refs/remotes'):
  672. break
  673. else:
  674. remotes = RunGit(['remote'], error_ok=True).split()
  675. if len(remotes) == 1:
  676. remote, = remotes
  677. elif 'origin' in remotes:
  678. remote = 'origin'
  679. logging.warning('Could not determine which remote this change is '
  680. 'associated with, so defaulting to "%s". This may '
  681. 'not be what you want. You may prevent this message '
  682. 'by running "git svn info" as documented here: %s',
  683. self._remote,
  684. GIT_INSTRUCTIONS_URL)
  685. else:
  686. logging.warn('Could not determine which remote this change is '
  687. 'associated with. You may prevent this message by '
  688. 'running "git svn info" as documented here: %s',
  689. GIT_INSTRUCTIONS_URL)
  690. branch = 'HEAD'
  691. if branch.startswith('refs/remotes'):
  692. self._remote = (remote, branch)
  693. elif branch.startswith('refs/branch-heads/'):
  694. self._remote = (remote, branch.replace('refs/', 'refs/remotes/'))
  695. else:
  696. self._remote = (remote, 'refs/remotes/%s/%s' % (remote, branch))
  697. return self._remote
  698. def GitSanityChecks(self, upstream_git_obj):
  699. """Checks git repo status and ensures diff is from local commits."""
  700. if upstream_git_obj is None:
  701. if self.GetBranch() is None:
  702. print >> sys.stderr, (
  703. 'ERROR: unable to determine current branch (detached HEAD?)')
  704. else:
  705. print >> sys.stderr, (
  706. 'ERROR: no upstream branch')
  707. return False
  708. # Verify the commit we're diffing against is in our current branch.
  709. upstream_sha = RunGit(['rev-parse', '--verify', upstream_git_obj]).strip()
  710. common_ancestor = RunGit(['merge-base', upstream_sha, 'HEAD']).strip()
  711. if upstream_sha != common_ancestor:
  712. print >> sys.stderr, (
  713. 'ERROR: %s is not in the current branch. You may need to rebase '
  714. 'your tracking branch' % upstream_sha)
  715. return False
  716. # List the commits inside the diff, and verify they are all local.
  717. commits_in_diff = RunGit(
  718. ['rev-list', '^%s' % upstream_sha, 'HEAD']).splitlines()
  719. code, remote_branch = RunGitWithCode(['config', 'gitcl.remotebranch'])
  720. remote_branch = remote_branch.strip()
  721. if code != 0:
  722. _, remote_branch = self.GetRemoteBranch()
  723. commits_in_remote = RunGit(
  724. ['rev-list', '^%s' % upstream_sha, remote_branch]).splitlines()
  725. common_commits = set(commits_in_diff) & set(commits_in_remote)
  726. if common_commits:
  727. print >> sys.stderr, (
  728. 'ERROR: Your diff contains %d commits already in %s.\n'
  729. 'Run "git log --oneline %s..HEAD" to get a list of commits in '
  730. 'the diff. If you are using a custom git flow, you can override'
  731. ' the reference used for this check with "git config '
  732. 'gitcl.remotebranch <git-ref>".' % (
  733. len(common_commits), remote_branch, upstream_git_obj))
  734. return False
  735. return True
  736. def GetGitBaseUrlFromConfig(self):
  737. """Return the configured base URL from branch.<branchname>.baseurl.
  738. Returns None if it is not set.
  739. """
  740. return RunGit(['config', 'branch.%s.base-url' % self.GetBranch()],
  741. error_ok=True).strip()
  742. def GetGitSvnRemoteUrl(self):
  743. """Return the configured git-svn remote URL parsed from git svn info.
  744. Returns None if it is not set.
  745. """
  746. # URL is dependent on the current directory.
  747. data = RunGit(['svn', 'info'], cwd=settings.GetRoot())
  748. if data:
  749. keys = dict(line.split(': ', 1) for line in data.splitlines()
  750. if ': ' in line)
  751. return keys.get('URL', None)
  752. return None
  753. def GetRemoteUrl(self):
  754. """Return the configured remote URL, e.g. 'git://example.org/foo.git/'.
  755. Returns None if there is no remote.
  756. """
  757. remote, _ = self.GetRemoteBranch()
  758. url = RunGit(['config', 'remote.%s.url' % remote], error_ok=True).strip()
  759. # If URL is pointing to a local directory, it is probably a git cache.
  760. if os.path.isdir(url):
  761. url = RunGit(['config', 'remote.%s.url' % remote],
  762. error_ok=True,
  763. cwd=url).strip()
  764. return url
  765. def GetIssue(self):
  766. """Returns the issue number as a int or None if not set."""
  767. if self.issue is None and not self.lookedup_issue:
  768. issue = RunGit(['config', self._IssueSetting()], error_ok=True).strip()
  769. self.issue = int(issue) or None if issue else None
  770. self.lookedup_issue = True
  771. return self.issue
  772. def GetRietveldServer(self):
  773. if not self.rietveld_server:
  774. # If we're on a branch then get the server potentially associated
  775. # with that branch.
  776. if self.GetIssue():
  777. rietveld_server_config = self._RietveldServer()
  778. if rietveld_server_config:
  779. self.rietveld_server = gclient_utils.UpgradeToHttps(RunGit(
  780. ['config', rietveld_server_config], error_ok=True).strip())
  781. if not self.rietveld_server:
  782. self.rietveld_server = settings.GetDefaultServerUrl()
  783. return self.rietveld_server
  784. def GetIssueURL(self):
  785. """Get the URL for a particular issue."""
  786. if not self.GetIssue():
  787. return None
  788. return '%s/%s' % (self.GetRietveldServer(), self.GetIssue())
  789. def GetDescription(self, pretty=False):
  790. if not self.has_description:
  791. if self.GetIssue():
  792. issue = self.GetIssue()
  793. try:
  794. self.description = self.RpcServer().get_description(issue).strip()
  795. except urllib2.HTTPError as e:
  796. if e.code == 404:
  797. DieWithError(
  798. ('\nWhile fetching the description for issue %d, received a '
  799. '404 (not found)\n'
  800. 'error. It is likely that you deleted this '
  801. 'issue on the server. If this is the\n'
  802. 'case, please run\n\n'
  803. ' git cl issue 0\n\n'
  804. 'to clear the association with the deleted issue. Then run '
  805. 'this command again.') % issue)
  806. else:
  807. DieWithError(
  808. '\nFailed to fetch issue description. HTTP error %d' % e.code)
  809. except urllib2.URLError as e:
  810. print >> sys.stderr, (
  811. 'Warning: Failed to retrieve CL description due to network '
  812. 'failure.')
  813. self.description = ''
  814. self.has_description = True
  815. if pretty:
  816. wrapper = textwrap.TextWrapper()
  817. wrapper.initial_indent = wrapper.subsequent_indent = ' '
  818. return wrapper.fill(self.description)
  819. return self.description
  820. def GetPatchset(self):
  821. """Returns the patchset number as a int or None if not set."""
  822. if self.patchset is None and not self.lookedup_patchset:
  823. patchset = RunGit(['config', self._PatchsetSetting()],
  824. error_ok=True).strip()
  825. self.patchset = int(patchset) or None if patchset else None
  826. self.lookedup_patchset = True
  827. return self.patchset
  828. def SetPatchset(self, patchset):
  829. """Set this branch's patchset. If patchset=0, clears the patchset."""
  830. if patchset:
  831. RunGit(['config', self._PatchsetSetting(), str(patchset)])
  832. self.patchset = patchset
  833. else:
  834. RunGit(['config', '--unset', self._PatchsetSetting()],
  835. stderr=subprocess2.PIPE, error_ok=True)
  836. self.patchset = None
  837. def GetMostRecentPatchset(self):
  838. return self.GetIssueProperties()['patchsets'][-1]
  839. def GetPatchSetDiff(self, issue, patchset):
  840. return self.RpcServer().get(
  841. '/download/issue%s_%s.diff' % (issue, patchset))
  842. def GetIssueProperties(self):
  843. if self._props is None:
  844. issue = self.GetIssue()
  845. if not issue:
  846. self._props = {}
  847. else:
  848. self._props = self.RpcServer().get_issue_properties(issue, True)
  849. return self._props
  850. def GetApprovingReviewers(self):
  851. return get_approving_reviewers(self.GetIssueProperties())
  852. def AddComment(self, message):
  853. return self.RpcServer().add_comment(self.GetIssue(), message)
  854. def SetIssue(self, issue):
  855. """Set this branch's issue. If issue=0, clears the issue."""
  856. if issue:
  857. self.issue = issue
  858. RunGit(['config', self._IssueSetting(), str(issue)])
  859. if self.rietveld_server:
  860. RunGit(['config', self._RietveldServer(), self.rietveld_server])
  861. else:
  862. current_issue = self.GetIssue()
  863. if current_issue:
  864. RunGit(['config', '--unset', self._IssueSetting()])
  865. self.issue = None
  866. self.SetPatchset(None)
  867. def GetChange(self, upstream_branch, author):
  868. if not self.GitSanityChecks(upstream_branch):
  869. DieWithError('\nGit sanity check failure')
  870. root = settings.GetRelativeRoot()
  871. if not root:
  872. root = '.'
  873. absroot = os.path.abspath(root)
  874. # We use the sha1 of HEAD as a name of this change.
  875. name = RunGitWithCode(['rev-parse', 'HEAD'])[1].strip()
  876. # Need to pass a relative path for msysgit.
  877. try:
  878. files = scm.GIT.CaptureStatus([root], '.', upstream_branch)
  879. except subprocess2.CalledProcessError:
  880. DieWithError(
  881. ('\nFailed to diff against upstream branch %s\n\n'
  882. 'This branch probably doesn\'t exist anymore. To reset the\n'
  883. 'tracking branch, please run\n'
  884. ' git branch --set-upstream %s trunk\n'
  885. 'replacing trunk with origin/master or the relevant branch') %
  886. (upstream_branch, self.GetBranch()))
  887. issue = self.GetIssue()
  888. patchset = self.GetPatchset()
  889. if issue:
  890. description = self.GetDescription()
  891. else:
  892. # If the change was never uploaded, use the log messages of all commits
  893. # up to the branch point, as git cl upload will prefill the description
  894. # with these log messages.
  895. args = ['log', '--pretty=format:%s%n%n%b', '%s...' % (upstream_branch)]
  896. description = RunGitWithCode(args)[1].strip()
  897. if not author:
  898. author = RunGit(['config', 'user.email']).strip() or None
  899. return presubmit_support.GitChange(
  900. name,
  901. description,
  902. absroot,
  903. files,
  904. issue,
  905. patchset,
  906. author,
  907. upstream=upstream_branch)
  908. def GetStatus(self):
  909. """Apply a rough heuristic to give a simple summary of an issue's review
  910. or CQ status, assuming adherence to a common workflow.
  911. Returns None if no issue for this branch, or one of the following keywords:
  912. * 'error' - error from review tool (including deleted issues)
  913. * 'unsent' - not sent for review
  914. * 'waiting' - waiting for review
  915. * 'reply' - waiting for owner to reply to review
  916. * 'lgtm' - LGTM from at least one approved reviewer
  917. * 'commit' - in the commit queue
  918. * 'closed' - closed
  919. """
  920. if not self.GetIssue():
  921. return None
  922. try:
  923. props = self.GetIssueProperties()
  924. except urllib2.HTTPError:
  925. return 'error'
  926. if props.get('closed'):
  927. # Issue is closed.
  928. return 'closed'
  929. if props.get('commit'):
  930. # Issue is in the commit queue.
  931. return 'commit'
  932. try:
  933. reviewers = self.GetApprovingReviewers()
  934. except urllib2.HTTPError:
  935. return 'error'
  936. if reviewers:
  937. # Was LGTM'ed.
  938. return 'lgtm'
  939. messages = props.get('messages') or []
  940. if not messages:
  941. # No message was sent.
  942. return 'unsent'
  943. if messages[-1]['sender'] != props.get('owner_email'):
  944. # Non-LGTM reply from non-owner
  945. return 'reply'
  946. return 'waiting'
  947. def RunHook(self, committing, may_prompt, verbose, change):
  948. """Calls sys.exit() if the hook fails; returns a HookResults otherwise."""
  949. try:
  950. return presubmit_support.DoPresubmitChecks(change, committing,
  951. verbose=verbose, output_stream=sys.stdout, input_stream=sys.stdin,
  952. default_presubmit=None, may_prompt=may_prompt,
  953. rietveld_obj=self.RpcServer())
  954. except presubmit_support.PresubmitFailure, e:
  955. DieWithError(
  956. ('%s\nMaybe your depot_tools is out of date?\n'
  957. 'If all fails, contact maruel@') % e)
  958. def UpdateDescription(self, description):
  959. self.description = description
  960. return self.RpcServer().update_description(
  961. self.GetIssue(), self.description)
  962. def CloseIssue(self):
  963. """Updates the description and closes the issue."""
  964. return self.RpcServer().close_issue(self.GetIssue())
  965. def SetFlag(self, flag, value):
  966. """Patchset must match."""
  967. if not self.GetPatchset():
  968. DieWithError('The patchset needs to match. Send another patchset.')
  969. try:
  970. return self.RpcServer().set_flag(
  971. self.GetIssue(), self.GetPatchset(), flag, value)
  972. except urllib2.HTTPError, e:
  973. if e.code == 404:
  974. DieWithError('The issue %s doesn\'t exist.' % self.GetIssue())
  975. if e.code == 403:
  976. DieWithError(
  977. ('Access denied to issue %s. Maybe the patchset %s doesn\'t '
  978. 'match?') % (self.GetIssue(), self.GetPatchset()))
  979. raise
  980. def RpcServer(self):
  981. """Returns an upload.RpcServer() to access this review's rietveld instance.
  982. """
  983. if not self._rpc_server:
  984. self._rpc_server = rietveld.CachingRietveld(
  985. self.GetRietveldServer(),
  986. self._auth_config or auth.make_auth_config())
  987. return self._rpc_server
  988. def _IssueSetting(self):
  989. """Return the git setting that stores this change's issue."""
  990. return 'branch.%s.rietveldissue' % self.GetBranch()
  991. def _PatchsetSetting(self):
  992. """Return the git setting that stores this change's most recent patchset."""
  993. return 'branch.%s.rietveldpatchset' % self.GetBranch()
  994. def _RietveldServer(self):
  995. """Returns the git setting that stores this change's rietveld server."""
  996. branch = self.GetBranch()
  997. if branch:
  998. return 'branch.%s.rietveldserver' % branch
  999. return None
  1000. def GetCodereviewSettingsInteractively():
  1001. """Prompt the user for settings."""
  1002. # TODO(ukai): ask code review system is rietveld or gerrit?
  1003. server = settings.GetDefaultServerUrl(error_ok=True)
  1004. prompt = 'Rietveld server (host[:port])'
  1005. prompt += ' [%s]' % (server or DEFAULT_SERVER)
  1006. newserver = ask_for_data(prompt + ':')
  1007. if not server and not newserver:
  1008. newserver = DEFAULT_SERVER
  1009. if newserver:
  1010. newserver = gclient_utils.UpgradeToHttps(newserver)
  1011. if newserver != server:
  1012. RunGit(['config', 'rietveld.server', newserver])
  1013. def SetProperty(initial, caption, name, is_url):
  1014. prompt = caption
  1015. if initial:
  1016. prompt += ' ("x" to clear) [%s]' % initial
  1017. new_val = ask_for_data(prompt + ':')
  1018. if new_val == 'x':
  1019. RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True)
  1020. elif new_val:
  1021. if is_url:
  1022. new_val = gclient_utils.UpgradeToHttps(new_val)
  1023. if new_val != initial:
  1024. RunGit(['config', 'rietveld.' + name, new_val])
  1025. SetProperty(settings.GetDefaultCCList(), 'CC list', 'cc', False)
  1026. SetProperty(settings.GetDefaultPrivateFlag(),
  1027. 'Private flag (rietveld only)', 'private', False)
  1028. SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL',
  1029. 'tree-status-url', False)
  1030. SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url', True)
  1031. SetProperty(settings.GetBugPrefix(), 'Bug Prefix', 'bug-prefix', False)
  1032. SetProperty(settings.GetRunPostUploadHook(), 'Run Post Upload Hook',
  1033. 'run-post-upload-hook', False)
  1034. # TODO: configure a default branch to diff against, rather than this
  1035. # svn-based hackery.
  1036. class ChangeDescription(object):
  1037. """Contains a parsed form of the change description."""
  1038. R_LINE = r'^[ \t]*(TBR|R)[ \t]*=[ \t]*(.*?)[ \t]*$'
  1039. BUG_LINE = r'^[ \t]*(BUG)[ \t]*=[ \t]*(.*?)[ \t]*$'
  1040. def __init__(self, description):
  1041. self._description_lines = (description or '').strip().splitlines()
  1042. @property # www.logilab.org/ticket/89786
  1043. def description(self): # pylint: disable=E0202
  1044. return '\n'.join(self._description_lines)
  1045. def set_description(self, desc):
  1046. if isinstance(desc, basestring):
  1047. lines = desc.splitlines()
  1048. else:
  1049. lines = [line.rstrip() for line in desc]
  1050. while lines and not lines[0]:
  1051. lines.pop(0)
  1052. while lines and not lines[-1]:
  1053. lines.pop(-1)
  1054. self._description_lines = lines
  1055. def update_reviewers(self, reviewers, add_owners_tbr=False, change=None):
  1056. """Rewrites the R=/TBR= line(s) as a single line each."""
  1057. assert isinstance(reviewers, list), reviewers
  1058. if not reviewers and not add_owners_tbr:
  1059. return
  1060. reviewers = reviewers[:]
  1061. # Get the set of R= and TBR= lines and remove them from the desciption.
  1062. regexp = re.compile(self.R_LINE)
  1063. matches = [regexp.match(line) for line in self._description_lines]
  1064. new_desc = [l for i, l in enumerate(self._description_lines)
  1065. if not matches[i]]
  1066. self.set_description(new_desc)
  1067. # Construct new unified R= and TBR= lines.
  1068. r_names = []
  1069. tbr_names = []
  1070. for match in matches:
  1071. if not match:
  1072. continue
  1073. people = cleanup_list([match.group(2).strip()])
  1074. if match.group(1) == 'TBR':
  1075. tbr_names.extend(people)
  1076. else:
  1077. r_names.extend(people)
  1078. for name in r_names:
  1079. if name not in reviewers:
  1080. reviewers.append(name)
  1081. if add_owners_tbr:
  1082. owners_db = owners.Database(change.RepositoryRoot(),
  1083. fopen=file, os_path=os.path, glob=glob.glob)
  1084. all_reviewers = set(tbr_names + reviewers)
  1085. missing_files = owners_db.files_not_covered_by(change.LocalPaths(),
  1086. all_reviewers)
  1087. tbr_names.extend(owners_db.reviewers_for(missing_files,
  1088. change.author_email))
  1089. new_r_line = 'R=' + ', '.join(reviewers) if reviewers else None
  1090. new_tbr_line = 'TBR=' + ', '.join(tbr_names) if tbr_names else None
  1091. # Put the new lines in the description where the old first R= line was.
  1092. line_loc = next((i for i, match in enumerate(matches) if match), -1)
  1093. if 0 <= line_loc < len(self._description_lines):
  1094. if new_tbr_line:
  1095. self._description_lines.insert(line_loc, new_tbr_line)
  1096. if new_r_line:
  1097. self._description_lines.insert(line_loc, new_r_line)
  1098. else:
  1099. if new_r_line:
  1100. self.append_footer(new_r_line)
  1101. if new_tbr_line:
  1102. self.append_footer(new_tbr_line)
  1103. def prompt(self):
  1104. """Asks the user to update the description."""
  1105. self.set_description([
  1106. '# Enter a description of the change.',
  1107. '# This will be displayed on the codereview site.',
  1108. '# The first line will also be used as the subject of the review.',
  1109. '#--------------------This line is 72 characters long'
  1110. '--------------------',
  1111. ] + self._description_lines)
  1112. regexp = re.compile(self.BUG_LINE)
  1113. if not any((regexp.match(line) for line in self._description_lines)):
  1114. self.append_footer('BUG=%s' % settings.GetBugPrefix())
  1115. content = gclient_utils.RunEditor(self.description, True,
  1116. git_editor=settings.GetGitEditor())
  1117. if not content:
  1118. DieWithError('Running editor failed')
  1119. lines = content.splitlines()
  1120. # Strip off comments.
  1121. clean_lines = [line.rstrip() for line in lines if not line.startswith('#')]
  1122. if not clean_lines:
  1123. DieWithError('No CL description, aborting')
  1124. self.set_description(clean_lines)
  1125. def append_footer(self, line):
  1126. if self._description_lines:
  1127. # Add an empty line if either the last line or the new line isn't a tag.
  1128. last_line = self._description_lines[-1]
  1129. if (not presubmit_support.Change.TAG_LINE_RE.match(last_line) or
  1130. not presubmit_support.Change.TAG_LINE_RE.match(line)):
  1131. self._description_lines.append('')
  1132. self._description_lines.append(line)
  1133. def get_reviewers(self):
  1134. """Retrieves the list of reviewers."""
  1135. matches = [re.match(self.R_LINE, line) for line in self._description_lines]
  1136. reviewers = [match.group(2).strip() for match in matches if match]
  1137. return cleanup_list(reviewers)
  1138. def get_approving_reviewers(props):
  1139. """Retrieves the reviewers that approved a CL from the issue properties with
  1140. messages.
  1141. Note that the list may contain reviewers that are not committer, thus are not
  1142. considered by the CQ.
  1143. """
  1144. return sorted(
  1145. set(
  1146. message['sender']
  1147. for message in props['messages']
  1148. if message['approval'] and message['sender'] in props['reviewers']
  1149. )
  1150. )
  1151. def FindCodereviewSettingsFile(filename='codereview.settings'):
  1152. """Finds the given file starting in the cwd and going up.
  1153. Only looks up to the top of the repository unless an
  1154. 'inherit-review-settings-ok' file exists in the root of the repository.
  1155. """
  1156. inherit_ok_file = 'inherit-review-settings-ok'
  1157. cwd = os.getcwd()
  1158. root = settings.GetRoot()
  1159. if os.path.isfile(os.path.join(root, inherit_ok_file)):
  1160. root = '/'
  1161. while True:
  1162. if filename in os.listdir(cwd):
  1163. if os.path.isfile(os.path.join(cwd, filename)):
  1164. return open(os.path.join(cwd, filename))
  1165. if cwd == root:
  1166. break
  1167. cwd = os.path.dirname(cwd)
  1168. def LoadCodereviewSettingsFromFile(fileobj):
  1169. """Parse a codereview.settings file and updates hooks."""
  1170. keyvals = gclient_utils.ParseCodereviewSettingsContent(fileobj.read())
  1171. def SetProperty(name, setting, unset_error_ok=False):
  1172. fullname = 'rietveld.' + name
  1173. if setting in keyvals:
  1174. RunGit(['config', fullname, keyvals[setting]])
  1175. else:
  1176. RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok)
  1177. SetProperty('server', 'CODE_REVIEW_SERVER')
  1178. # Only server setting is required. Other settings can be absent.
  1179. # In that case, we ignore errors raised during option deletion attempt.
  1180. SetProperty('cc', 'CC_LIST', unset_error_ok=True)
  1181. SetProperty('private', 'PRIVATE', unset_error_ok=True)
  1182. SetProperty('tree-status-url', 'STATUS', unset_error_ok=True)
  1183. SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True)
  1184. SetProperty('bug-prefix', 'BUG_PREFIX', unset_error_ok=True)
  1185. SetProperty('cpplint-regex', 'LINT_REGEX', unset_error_ok=True)
  1186. SetProperty('force-https-commit-url', 'FORCE_HTTPS_COMMIT_URL',
  1187. unset_error_ok=True)
  1188. SetProperty('cpplint-ignore-regex', 'LINT_IGNORE_REGEX', unset_error_ok=True)
  1189. SetProperty('project', 'PROJECT', unset_error_ok=True)
  1190. SetProperty('pending-ref-prefix', 'PENDING_REF_PREFIX', unset_error_ok=True)
  1191. SetProperty('run-post-upload-hook', 'RUN_POST_UPLOAD_HOOK',
  1192. unset_error_ok=True)
  1193. if 'GERRIT_HOST' in keyvals:
  1194. RunGit(['config', 'gerrit.host', keyvals['GERRIT_HOST']])
  1195. if 'PUSH_URL_CONFIG' in keyvals and 'ORIGIN_URL_CONFIG' in keyvals:
  1196. #should be of the form
  1197. #PUSH_URL_CONFIG: url.ssh://gitrw.chromium.org.pushinsteadof
  1198. #ORIGIN_URL_CONFIG: http://src.chromium.org/git
  1199. RunGit(['config', keyvals['PUSH_URL_CONFIG'],
  1200. keyvals['ORIGIN_URL_CONFIG']])
  1201. def urlretrieve(source, destination):
  1202. """urllib is broken for SSL connections via a proxy therefore we
  1203. can't use urllib.urlretrieve()."""
  1204. with open(destination, 'w') as f:
  1205. f.write(urllib2.urlopen(source).read())
  1206. def hasSheBang(fname):
  1207. """Checks fname is a #! script."""
  1208. with open(fname) as f:
  1209. return f.read(2).startswith('#!')
  1210. def DownloadHooks(force):
  1211. """downloads hooks
  1212. Args:
  1213. force: True to update hooks. False to install hooks if not present.
  1214. """
  1215. if not settings.GetIsGerrit():
  1216. return
  1217. src = 'https://gerrit-review.googlesource.com/tools/hooks/commit-msg'
  1218. dst = os.path.join(settings.GetRoot(), '.git', 'hooks', 'commit-msg')
  1219. if not os.access(dst, os.X_OK):
  1220. if os.path.exists(dst):
  1221. if not force:
  1222. return
  1223. try:
  1224. urlretrieve(src, dst)
  1225. if not hasSheBang(dst):
  1226. DieWithError('Not a script: %s\n'
  1227. 'You need to download from\n%s\n'
  1228. 'into .git/hooks/commit-msg and '
  1229. 'chmod +x .git/hooks/commit-msg' % (dst, src))
  1230. os.chmod(dst, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
  1231. except Exception:
  1232. if os.path.exists(dst):
  1233. os.remove(dst)
  1234. DieWithError('\nFailed to download hooks.\n'
  1235. 'You need to download from\n%s\n'
  1236. 'into .git/hooks/commit-msg and '
  1237. 'chmod +x .git/hooks/commit-msg' % src)
  1238. @subcommand.usage('[repo root containing codereview.settings]')
  1239. def CMDconfig(parser, args):
  1240. """Edits configuration for this tree."""
  1241. parser.add_option('--activate-update', action='store_true',
  1242. help='activate auto-updating [rietveld] section in '
  1243. '.git/config')
  1244. parser.add_option('--deactivate-update', action='store_true',
  1245. help='deactivate auto-updating [rietveld] section in '
  1246. '.git/config')
  1247. options, args = parser.parse_args(args)
  1248. if options.deactivate_update:
  1249. RunGit(['config', 'rietveld.autoupdate', 'false'])
  1250. return
  1251. if options.activate_update:
  1252. RunGit(['config', '--unset', 'rietveld.autoupdate'])
  1253. return
  1254. if len(args) == 0:
  1255. GetCodereviewSettingsInteractively()
  1256. DownloadHooks(True)
  1257. return 0
  1258. url = args[0]
  1259. if not url.endswith('codereview.settings'):
  1260. url = os.path.join(url, 'codereview.settings')
  1261. # Load code review settings and download hooks (if available).
  1262. LoadCodereviewSettingsFromFile(urllib2.urlopen(url))
  1263. DownloadHooks(True)
  1264. return 0
  1265. def CMDbaseurl(parser, args):
  1266. """Gets or sets base-url for this branch."""
  1267. branchref = RunGit(['symbolic-ref', 'HEAD']).strip()
  1268. branch = ShortBranchName(branchref)
  1269. _, args = parser.parse_args(args)
  1270. if not args:
  1271. print("Current base-url:")
  1272. return RunGit(['config', 'branch.%s.base-url' % branch],
  1273. error_ok=False).strip()
  1274. else:
  1275. print("Setting base-url to %s" % args[0])
  1276. return RunGit(['config', 'branch.%s.base-url' % branch, args[0]],
  1277. error_ok=False).strip()
  1278. def color_for_status(status):
  1279. """Maps a Changelist status to color, for CMDstatus and other tools."""
  1280. return {
  1281. 'unsent': Fore.RED,
  1282. 'waiting': Fore.BLUE,
  1283. 'reply': Fore.YELLOW,
  1284. 'lgtm': Fore.GREEN,
  1285. 'commit': Fore.MAGENTA,
  1286. 'closed': Fore.CYAN,
  1287. 'error': Fore.WHITE,
  1288. }.get(status, Fore.WHITE)
  1289. def fetch_cl_status(branch, auth_config=None):
  1290. """Fetches information for an issue and returns (branch, issue, status)."""
  1291. cl = Changelist(branchref=branch, auth_config=auth_config)
  1292. url = cl.GetIssueURL()
  1293. status = cl.GetStatus()
  1294. if url and (not status or status == 'error'):
  1295. # The issue probably doesn't exist anymore.
  1296. url += ' (broken)'
  1297. return (branch, url, status)
  1298. def get_cl_statuses(
  1299. branches, fine_grained, max_processes=None, auth_config=None):
  1300. """Returns a blocking iterable of (branch, issue, color) for given branches.
  1301. If fine_grained is true, this will fetch CL statuses from the server.
  1302. Otherwise, simply indicate if there's a matching url for the given branches.
  1303. If max_processes is specified, it is used as the maximum number of processes
  1304. to spawn to fetch CL status from the server. Otherwise 1 process per branch is
  1305. spawned.
  1306. """
  1307. # Silence upload.py otherwise it becomes unwieldly.
  1308. upload.verbosity = 0
  1309. if fine_grained:
  1310. # Process one branch synchronously to work through authentication, then
  1311. # spawn processes to process all the other branches in parallel.
  1312. if branches:
  1313. fetch = lambda branch: fetch_cl_status(branch, auth_config=auth_config)
  1314. yield fetch(branches[0])
  1315. branches_to_fetch = branches[1:]
  1316. pool = ThreadPool(
  1317. min(max_processes, len(branches_to_fetch))
  1318. if max_processes is not None
  1319. else len(branches_to_fetch))
  1320. for x in pool.imap_unordered(fetch, branches_to_fetch):
  1321. yield x
  1322. else:
  1323. # Do not use GetApprovingReviewers(), since it requires an HTTP request.
  1324. for b in branches:
  1325. cl = Changelist(branchref=b, auth_config=auth_config)
  1326. url = cl.GetIssueURL()
  1327. yield (b, url, 'waiting' if url else 'error')
  1328. def upload_branch_deps(cl, args):
  1329. """Uploads CLs of local branches that are dependents of the current branch.
  1330. If the local branch dependency tree looks like:
  1331. test1 -> test2.1 -> test3.1
  1332. -> test3.2
  1333. -> test2.2 -> test3.3
  1334. and you run "git cl upload --dependencies" from test1 then "git cl upload" is
  1335. run on the dependent branches in this order:
  1336. test2.1, test3.1, test3.2, test2.2, test3.3
  1337. Note: This function does not rebase your local dependent branches. Use it when
  1338. you make a change to the parent branch that will not conflict with its
  1339. dependent branches, and you would like their dependencies updated in
  1340. Rietveld.
  1341. """
  1342. if git_common.is_dirty_git_tree('upload-branch-deps'):
  1343. return 1
  1344. root_branch = cl.GetBranch()
  1345. if root_branch is None:
  1346. DieWithError('Can\'t find dependent branches from detached HEAD state. '
  1347. 'Get on a branch!')
  1348. if not cl.GetIssue() or not cl.GetPatchset():
  1349. DieWithError('Current branch does not have an uploaded CL. We cannot set '
  1350. 'patchset dependencies without an uploaded CL.')
  1351. branches = RunGit(['for-each-ref',
  1352. '--format=%(refname:short) %(upstream:short)',
  1353. 'refs/heads'])
  1354. if not branches:
  1355. print('No local branches found.')
  1356. return 0
  1357. # Create a dictionary of all local branches to the branches that are dependent
  1358. # on it.
  1359. tracked_to_dependents = collections.defaultdict(list)
  1360. for b in branches.splitlines():
  1361. tokens = b.split()
  1362. if len(tokens) == 2:
  1363. branch_name, tracked = tokens
  1364. tracked_to_dependents[tracked].append(branch_name)
  1365. print
  1366. print 'The dependent local branches of %s are:' % root_branch
  1367. dependents = []
  1368. def traverse_dependents_preorder(branch, padding=''):
  1369. dependents_to_process = tracked_to_dependents.get(branch, [])
  1370. padding += ' '
  1371. for dependent in dependents_to_process:
  1372. print '%s%s' % (padding, dependent)
  1373. dependents.append(dependent)
  1374. traverse_dependents_preorder(dependent, padding)
  1375. traverse_dependents_preorder(root_branch)
  1376. print
  1377. if not dependents:
  1378. print 'There are no dependent local branches for %s' % root_branch
  1379. return 0
  1380. print ('This command will checkout all dependent branches and run '
  1381. '"git cl upload".')
  1382. ask_for_data('[Press enter to continue or ctrl-C to quit]')
  1383. # Add a default patchset title to all upload calls.
  1384. args.extend(['-t', 'Updated patchset dependency'])
  1385. # Record all dependents that failed to upload.
  1386. failures = {}
  1387. # Go through all dependents, checkout the branch and upload.
  1388. try:
  1389. for dependent_branch in dependents:
  1390. print
  1391. print '--------------------------------------'
  1392. print 'Running "git cl upload" from %s:' % dependent_branch
  1393. RunGit(['checkout', '-q', dependent_branch])
  1394. print
  1395. try:
  1396. if CMDupload(OptionParser(), args) != 0:
  1397. print 'Upload failed for %s!' % dependent_branch
  1398. failures[dependent_branch] = 1
  1399. except: # pylint: disable=W0702
  1400. failures[dependent_branch] = 1
  1401. print
  1402. finally:
  1403. # Swap back to the original root branch.
  1404. RunGit(['checkout', '-q', root_branch])
  1405. print
  1406. print 'Upload complete for dependent branches!'
  1407. for dependent_branch in dependents:
  1408. upload_status = 'failed' if failures.get(dependent_branch) else 'succeeded'
  1409. print ' %s : %s' % (dependent_branch, upload_status)
  1410. print
  1411. return 0
  1412. def CMDstatus(parser, args):
  1413. """Show status of changelists.
  1414. Colors are used to tell the state of the CL unless --fast is used:
  1415. - Red not sent for review or broken
  1416. - Blue waiting for review
  1417. - Yellow waiting for you to reply to review
  1418. - Green LGTM'ed
  1419. - Magenta in the commit queue
  1420. - Cyan was committed, branch can be deleted
  1421. Also see 'git cl comments'.
  1422. """
  1423. parser.add_option('--field',
  1424. help='print only specific field (desc|id|patch|url)')
  1425. parser.add_option('-f', '--fast', action='store_true',
  1426. help='Do not retrieve review status')
  1427. parser.add_option(
  1428. '-j', '--maxjobs', action='store', type=int,
  1429. help='The maximum number of jobs to use when retrieving review status')
  1430. auth.add_auth_options(parser)
  1431. options, args = parser.parse_args(args)
  1432. if args:
  1433. parser.error('Unsupported args: %s' % args)
  1434. auth_config = auth.extract_auth_config_from_options(options)
  1435. if options.field:
  1436. cl = Changelist(auth_config=auth_config)
  1437. if options.field.startswith('desc'):
  1438. print cl.GetDescription()
  1439. elif options.field == 'id':
  1440. issueid = cl.GetIssue()
  1441. if issueid:
  1442. print issueid
  1443. elif options.field == 'patch':
  1444. patchset = cl.GetPatchset()
  1445. if patchset:
  1446. print patchset
  1447. elif options.field == 'url':
  1448. url = cl.GetIssueURL()
  1449. if url:
  1450. print url
  1451. return 0
  1452. branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
  1453. if not branches:
  1454. print('No local branch found.')
  1455. return 0
  1456. changes = (
  1457. Changelist(branchref=b, auth_config=auth_config)
  1458. for b in branches.splitlines())
  1459. branches = [c.GetBranch() for c in changes]
  1460. alignment = max(5, max(len(b) for b in branches))
  1461. print 'Branches associated with reviews:'
  1462. output = get_cl_statuses(branches,
  1463. fine_grained=not options.fast,
  1464. max_processes=options.maxjobs,
  1465. auth_config=auth_config)
  1466. branch_statuses = {}
  1467. alignment = max(5, max(len(ShortBranchName(b)) for b in branches))
  1468. for branch in sorted(branches):
  1469. while branch not in branch_statuses:
  1470. b, i, status = output.next()
  1471. branch_statuses[b] = (i, status)
  1472. issue_url, status = branch_statuses.pop(branch)
  1473. color = color_for_status(status)
  1474. reset = Fore.RESET
  1475. if not sys.stdout.isatty():
  1476. color = ''
  1477. reset = ''
  1478. status_str = '(%s)' % status if status else ''
  1479. print ' %*s : %s%s %s%s' % (
  1480. alignment, ShortBranchName(branch), color, issue_url, status_str,
  1481. reset)
  1482. cl = Changelist(auth_config=auth_config)
  1483. print
  1484. print 'Current branch:',
  1485. print cl.GetBranch()
  1486. if not cl.GetIssue():
  1487. print 'No issue assigned.'
  1488. return 0
  1489. print 'Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())
  1490. if not options.fast:
  1491. print 'Issue description:'
  1492. print cl.GetDescription(pretty=True)
  1493. return 0
  1494. def colorize_CMDstatus_doc():
  1495. """To be called once in main() to add colors to git cl status help."""
  1496. colors = [i for i in dir(Fore) if i[0].isupper()]
  1497. def colorize_line(line):
  1498. for color in colors:
  1499. if color in line.upper():
  1500. # Extract whitespaces first and the leading '-'.
  1501. indent = len(line) - len(line.lstrip(' ')) + 1
  1502. return line[:indent] + getattr(Fore, color) + line[indent:] + Fore.RESET
  1503. return line
  1504. lines = CMDstatus.__doc__.splitlines()
  1505. CMDstatus.__doc__ = '\n'.join(colorize_line(l) for l in lines)
  1506. @subcommand.usage('[issue_number]')
  1507. def CMDissue(parser, args):
  1508. """Sets or displays the current code review issue number.
  1509. Pass issue number 0 to clear the current issue.
  1510. """
  1511. parser.add_option('-r', '--reverse', action='store_true',
  1512. help='Lookup the branch(es) for the specified issues. If '
  1513. 'no issues are specified, all branches with mapped '
  1514. 'issues will be listed.')
  1515. options, args = parser.parse_args(args)
  1516. if options.reverse:
  1517. branches = RunGit(['for-each-ref', 'refs/heads',
  1518. '--format=%(refname:short)']).splitlines()
  1519. # Reverse issue lookup.
  1520. issue_branch_map = {}
  1521. for branch in branches:
  1522. cl = Changelist(branchref=branch)
  1523. issue_branch_map.setdefault(cl.GetIssue(), []).append(branch)
  1524. if not args:
  1525. args = sorted(issue_branch_map.iterkeys())
  1526. for issue in args:
  1527. if not issue:
  1528. continue
  1529. print 'Branch for issue number %s: %s' % (
  1530. issue, ', '.join(issue_branch_map.get(int(issue)) or ('None',)))
  1531. else:
  1532. cl = Changelist()
  1533. if len(args) > 0:
  1534. try:
  1535. issue = int(args[0])
  1536. except ValueError:
  1537. DieWithError('Pass a number to set the issue or none to list it.\n'
  1538. 'Maybe you want to run git cl status?')
  1539. cl.SetIssue(issue)
  1540. print 'Issue number: %s (%s)' % (cl.GetIssue(), cl.GetIssueURL())
  1541. return 0
  1542. def CMDcomments(parser, args):
  1543. """Shows or posts review comments for any changelist."""
  1544. parser.add_option('-a', '--add-comment', dest='comment',
  1545. help='comment to add to an issue')
  1546. parser.add_option('-i', dest='issue',
  1547. help="review issue id (defaults to current issue)")
  1548. parser.add_option('-j', '--json-file',
  1549. help='File to write JSON summary to')
  1550. auth.add_auth_options(parser)
  1551. options, args = parser.parse_args(args)
  1552. auth_config = auth.extract_auth_config_from_options(options)
  1553. issue = None
  1554. if options.issue:
  1555. try:
  1556. issue = int(options.issue)
  1557. except ValueError:
  1558. DieWithError('A review issue id is expected to be a number')
  1559. cl = Changelist(issue=issue, auth_config=auth_config)
  1560. if options.comment:
  1561. cl.AddComment(options.comment)
  1562. return 0
  1563. data = cl.GetIssueProperties()
  1564. summary = []
  1565. for message in sorted(data.get('messages', []), key=lambda x: x['date']):
  1566. summary.append({
  1567. 'date': message['date'],
  1568. 'lgtm': False,
  1569. 'message': message['text'],
  1570. 'not_lgtm': False,
  1571. 'sender': message['sender'],
  1572. })
  1573. if message['disapproval']:
  1574. color = Fore.RED
  1575. summary[-1]['not lgtm'] = True
  1576. elif message['approval']:
  1577. color = Fore.GREEN
  1578. summary[-1]['lgtm'] = True
  1579. elif message['sender'] == data['owner_email']:
  1580. color = Fore.MAGENTA
  1581. else:
  1582. color = Fore.BLUE
  1583. print '\n%s%s %s%s' % (
  1584. color, message['date'].split('.', 1)[0], message['sender'],
  1585. Fore.RESET)
  1586. if message['text'].strip():
  1587. print '\n'.join(' ' + l for l in message['text'].splitlines())
  1588. if options.json_file:
  1589. with open(options.json_file, 'wb') as f:
  1590. json.dump(summary, f)
  1591. return 0
  1592. def CMDdescription(parser, args):
  1593. """Brings up the editor for the current CL's description."""
  1594. parser.add_option('-d', '--display', action='store_true',
  1595. help='Display the description instead of opening an editor')
  1596. auth.add_auth_options(parser)
  1597. options, _ = parser.parse_args(args)
  1598. auth_config = auth.extract_auth_config_from_options(options)
  1599. cl = Changelist(auth_config=auth_config)
  1600. if not cl.GetIssue():
  1601. DieWithError('This branch has no associated changelist.')
  1602. description = ChangeDescription(cl.GetDescription())
  1603. if options.display:
  1604. print description.description
  1605. return 0
  1606. description.prompt()
  1607. if cl.GetDescription() != description.description:
  1608. cl.UpdateDescription(description.description)
  1609. return 0
  1610. def CreateDescriptionFromLog(args):
  1611. """Pulls out the commit log to use as a base for the CL description."""
  1612. log_args = []
  1613. if len(args) == 1 and not args[0].endswith('.'):
  1614. log_args = [args[0] + '..']
  1615. elif len(args) == 1 and args[0].endswith('...'):
  1616. log_args = [args[0][:-1]]
  1617. elif len(args) == 2:
  1618. log_args = [args[0] + '..' + args[1]]
  1619. else:
  1620. log_args = args[:] # Hope for the best!
  1621. return RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args)
  1622. def CMDlint(parser, args):
  1623. """Runs cpplint on the current changelist."""
  1624. parser.add_option('--filter', action='append', metavar='-x,+y',
  1625. help='Comma-separated list of cpplint\'s category-filters')
  1626. auth.add_auth_options(parser)
  1627. options, args = parser.parse_args(args)
  1628. auth_config = auth.extract_auth_config_from_options(options)
  1629. # Access to a protected member _XX of a client class
  1630. # pylint: disable=W0212
  1631. try:
  1632. import cpplint
  1633. import cpplint_chromium
  1634. except ImportError:
  1635. print "Your depot_tools is missing cpplint.py and/or cpplint_chromium.py."
  1636. return 1
  1637. # Change the current working directory before calling lint so that it
  1638. # shows the correct base.
  1639. previous_cwd = os.getcwd()
  1640. os.chdir(settings.GetRoot())
  1641. try:
  1642. cl = Changelist(auth_config=auth_config)
  1643. change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
  1644. files = [f.LocalPath() for f in change.AffectedFiles()]
  1645. if not files:
  1646. print "Cannot lint an empty CL"
  1647. return 1
  1648. # Process cpplints arguments if any.
  1649. command = args + files
  1650. if options.filter:
  1651. command = ['--filter=' + ','.join(options.filter)] + command
  1652. filenames = cpplint.ParseArguments(command)
  1653. white_regex = re.compile(settings.GetLintRegex())
  1654. black_regex = re.compile(settings.GetLintIgnoreRegex())
  1655. extra_check_functions = [cpplint_chromium.CheckPointerDeclarationWhitespace]
  1656. for filename in filenames:
  1657. if white_regex.match(filename):
  1658. if black_regex.match(filename):
  1659. print "Ignoring file %s" % filename
  1660. else:
  1661. cpplint.ProcessFile(filename, cpplint._cpplint_state.verbose_level,
  1662. extra_check_functions)
  1663. else:
  1664. print "Skipping file %s" % filename
  1665. finally:
  1666. os.chdir(previous_cwd)
  1667. print "Total errors found: %d\n" % cpplint._cpplint_state.error_count
  1668. if cpplint._cpplint_state.error_count != 0:
  1669. return 1
  1670. return 0
  1671. def CMDpresubmit(parser, args):
  1672. """Runs presubmit tests on the current changelist."""
  1673. parser.add_option('-u', '--upload', action='store_true',
  1674. help='Run upload hook instead of the push/dcommit hook')
  1675. parser.add_option('-f', '--force', action='store_true',
  1676. help='Run checks even if tree is dirty')
  1677. auth.add_auth_options(parser)
  1678. options, args = parser.parse_args(args)
  1679. auth_config = auth.extract_auth_config_from_options(options)
  1680. if not options.force and git_common.is_dirty_git_tree('presubmit'):
  1681. print 'use --force to check even if tree is dirty.'
  1682. return 1
  1683. cl = Changelist(auth_config=auth_config)
  1684. if args:
  1685. base_branch = args[0]
  1686. else:
  1687. # Default to diffing against the common ancestor of the upstream branch.
  1688. base_branch = cl.GetCommonAncestorWithUpstream()
  1689. cl.RunHook(
  1690. committing=not options.upload,
  1691. may_prompt=False,
  1692. verbose=options.verbose,
  1693. change=cl.GetChange(base_branch, None))
  1694. return 0
  1695. def AddChangeIdToCommitMessage(options, args):
  1696. """Re-commits using the current message, assumes the commit hook is in
  1697. place.
  1698. """
  1699. log_desc = options.message or CreateDescriptionFromLog(args)
  1700. git_command = ['commit', '--amend', '-m', log_desc]
  1701. RunGit(git_command)
  1702. new_log_desc = CreateDescriptionFromLog(args)
  1703. if CHANGE_ID in new_log_desc:
  1704. print 'git-cl: Added Change-Id to commit message.'
  1705. else:
  1706. print >> sys.stderr, 'ERROR: Gerrit commit-msg hook not available.'
  1707. def GerritUpload(options, args, cl, change):
  1708. """upload the current branch to gerrit."""
  1709. # We assume the remote called "origin" is the one we want.
  1710. # It is probably not worthwhile to support different workflows.
  1711. gerrit_remote = 'origin'
  1712. remote, remote_branch = cl.GetRemoteBranch()
  1713. branch = GetTargetRef(remote, remote_branch, options.target_branch,
  1714. pending_prefix='')
  1715. change_desc = ChangeDescription(
  1716. options.message or CreateDescriptionFromLog(args))
  1717. if not change_desc.description:
  1718. print "Description is empty; aborting."
  1719. return 1
  1720. if options.squash:
  1721. # Try to get the message from a previous upload.
  1722. shadow_branch = 'refs/heads/git_cl_uploads/' + cl.GetBranch()
  1723. message = RunGitSilent(['show', '--format=%s\n\n%b', '-s', shadow_branch])
  1724. if not message:
  1725. if not options.force:
  1726. change_desc.prompt()
  1727. if CHANGE_ID not in change_desc.description:
  1728. # Run the commit-msg hook without modifying the head commit by writing
  1729. # the commit message to a temporary file and running the hook over it,
  1730. # then reading the file back in.
  1731. commit_msg_hook = os.path.join(settings.GetRoot(), '.git', 'hooks',
  1732. 'commit-msg')
  1733. file_handle, msg_file = tempfile.mkstemp(text=True,
  1734. prefix='commit_msg')
  1735. try:
  1736. try:
  1737. with os.fdopen(file_handle, 'w') as fileobj:
  1738. fileobj.write(change_desc.description)
  1739. finally:
  1740. os.close(file_handle)
  1741. RunCommand([commit_msg_hook, msg_file])
  1742. change_desc.set_description(gclient_utils.FileRead(msg_file))
  1743. finally:
  1744. os.remove(msg_file)
  1745. if not change_desc.description:
  1746. print "Description is empty; aborting."
  1747. return 1
  1748. message = change_desc.description
  1749. remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch())
  1750. if remote is '.':
  1751. # If our upstream branch is local, we base our squashed commit on its
  1752. # squashed version.
  1753. parent = ('refs/heads/git_cl_uploads/' +
  1754. scm.GIT.ShortBranchName(upstream_branch))
  1755. # Verify that the upstream branch has been uploaded too, otherwise Gerrit
  1756. # will create additional CLs when uploading.
  1757. if (RunGitSilent(['rev-parse', upstream_branch + ':']) !=
  1758. RunGitSilent(['rev-parse', parent + ':'])):
  1759. print 'Upload upstream branch ' + upstream_branch + ' first.'
  1760. return 1
  1761. else:
  1762. parent = cl.GetCommonAncestorWithUpstream()
  1763. tree = RunGit(['rev-parse', 'HEAD:']).strip()
  1764. ref_to_push = RunGit(['commit-tree', tree, '-p', parent,
  1765. '-m', message]).strip()
  1766. else:
  1767. if CHANGE_ID not in change_desc.description:
  1768. AddChangeIdToCommitMessage(options, args)
  1769. ref_to_push = 'HEAD'
  1770. parent = '%s/%s' % (gerrit_remote, branch)
  1771. commits = RunGitSilent(['rev-list', '%s..%s' % (parent,
  1772. ref_to_push)]).splitlines()
  1773. if len(commits) > 1:
  1774. print('WARNING: This will upload %d commits. Run the following command '
  1775. 'to see which commits will be uploaded: ' % len(commits))
  1776. print('git log %s..%s' % (parent, ref_to_push))
  1777. print('You can also use `git squash-branch` to squash these into a single '
  1778. 'commit.')
  1779. ask_for_data('About to upload; enter to confirm.')
  1780. if options.reviewers or options.tbr_owners:
  1781. change_desc.update_reviewers(options.reviewers, options.tbr_owners, change)
  1782. receive_options = []
  1783. cc = cl.GetCCList().split(',')
  1784. if options.cc:
  1785. cc.extend(options.cc)
  1786. cc = filter(None, cc)
  1787. if cc:
  1788. receive_options += ['--cc=' + email for email in cc]
  1789. if change_desc.get_reviewers():
  1790. receive_options.extend(
  1791. '--reviewer=' + email for email in change_desc.get_reviewers())
  1792. git_command = ['push']
  1793. if receive_options:
  1794. git_command.append('--receive-pack=git receive-pack %s' %
  1795. ' '.join(receive_options))
  1796. git_command += [gerrit_remote, ref_to_push + ':refs/for/' + branch]
  1797. RunGit(git_command)
  1798. if options.squash:
  1799. head = RunGit(['rev-parse', 'HEAD']).strip()
  1800. RunGit(['update-ref', '-m', 'Uploaded ' + head, shadow_branch, ref_to_push])
  1801. # TODO(ukai): parse Change-Id: and set issue number?
  1802. return 0
  1803. def GetTargetRef(remote, remote_branch, target_branch, pending_prefix):
  1804. """Computes the remote branch ref to use for the CL.
  1805. Args:
  1806. remote (str): The git remote for the CL.
  1807. remote_branch (str): The git remote branch for the CL.
  1808. target_branch (str): The target branch specified by the user.
  1809. pending_prefix (str): The pending prefix from the settings.
  1810. """
  1811. if not (remote and remote_branch):
  1812. return None
  1813. if target_branch:
  1814. # Cannonicalize branch references to the equivalent local full symbolic
  1815. # refs, which are then translated into the remote full symbolic refs
  1816. # below.
  1817. if '/' not in target_branch:
  1818. remote_branch = 'refs/remotes/%s/%s' % (remote, target_branch)
  1819. else:
  1820. prefix_replacements = (
  1821. ('^((refs/)?remotes/)?branch-heads/', 'refs/remotes/branch-heads/'),
  1822. ('^((refs/)?remotes/)?%s/' % remote, 'refs/remotes/%s/' % remote),
  1823. ('^(refs/)?heads/', 'refs/remotes/%s/' % remote),
  1824. )
  1825. match = None
  1826. for regex, replacement in prefix_replacements:
  1827. match = re.search(regex, target_branch)
  1828. if match:
  1829. remote_branch = target_branch.replace(match.group(0), replacement)
  1830. break
  1831. if not match:
  1832. # This is a branch path but not one we recognize; use as-is.
  1833. remote_branch = target_branch
  1834. elif remote_branch in REFS_THAT_ALIAS_TO_OTHER_REFS:
  1835. # Handle the refs that need to land in different refs.
  1836. remote_branch = REFS_THAT_ALIAS_TO_OTHER_REFS[remote_branch]
  1837. # Create the true path to the remote branch.
  1838. # Does the following translation:
  1839. # * refs/remotes/origin/refs/diff/test -> refs/diff/test
  1840. # * refs/remotes/origin/master -> refs/heads/master
  1841. # * refs/remotes/branch-heads/test -> refs/branch-heads/test
  1842. if remote_branch.startswith('refs/remotes/%s/refs/' % remote):
  1843. remote_branch = remote_branch.replace('refs/remotes/%s/' % remote, '')
  1844. elif remote_branch.startswith('refs/remotes/%s/' % remote):
  1845. remote_branch = remote_branch.replace('refs/remotes/%s/' % remote,
  1846. 'refs/heads/')
  1847. elif remote_branch.startswith('refs/remotes/branch-heads'):
  1848. remote_branch = remote_branch.replace('refs/remotes/', 'refs/')
  1849. # If a pending prefix exists then replace refs/ with it.
  1850. if pending_prefix:
  1851. remote_branch = remote_branch.replace('refs/', pending_prefix)
  1852. return remote_branch
  1853. def RietveldUpload(options, args, cl, change):
  1854. """upload the patch to rietveld."""
  1855. upload_args = ['--assume_yes'] # Don't ask about untracked files.
  1856. upload_args.extend(['--server', cl.GetRietveldServer()])
  1857. upload_args.extend(auth.auth_config_to_command_options(cl.auth_config))
  1858. if options.emulate_svn_auto_props:
  1859. upload_args.append('--emulate_svn_auto_props')
  1860. change_desc = None
  1861. if options.email is not None:
  1862. upload_args.extend(['--email', options.email])
  1863. if cl.GetIssue():
  1864. if options.title:
  1865. upload_args.extend(['--title', options.title])
  1866. if options.message:
  1867. upload_args.extend(['--message', options.message])
  1868. upload_args.extend(['--issue', str(cl.GetIssue())])
  1869. print ("This branch is associated with issue %s. "
  1870. "Adding patch to that issue." % cl.GetIssue())
  1871. else:
  1872. if options.title:
  1873. upload_args.extend(['--title', options.title])
  1874. message = options.title or options.message or CreateDescriptionFromLog(args)
  1875. change_desc = ChangeDescription(message)
  1876. if options.reviewers or options.tbr_owners:
  1877. change_desc.update_reviewers(options.reviewers,
  1878. options.tbr_owners,
  1879. change)
  1880. if not options.force:
  1881. change_desc.prompt()
  1882. if not change_desc.description:
  1883. print "Description is empty; aborting."
  1884. return 1
  1885. upload_args.extend(['--message', change_desc.description])
  1886. if change_desc.get_reviewers():
  1887. upload_args.append('--reviewers=' + ','.join(change_desc.get_reviewers()))
  1888. if options.send_mail:
  1889. if not change_desc.get_reviewers():
  1890. DieWithError("Must specify reviewers to send email.")
  1891. upload_args.append('--send_mail')
  1892. # We check this before applying rietveld.private assuming that in
  1893. # rietveld.cc only addresses which we can send private CLs to are listed
  1894. # if rietveld.private is set, and so we should ignore rietveld.cc only when
  1895. # --private is specified explicitly on the command line.
  1896. if options.private:
  1897. logging.warn('rietveld.cc is ignored since private flag is specified. '
  1898. 'You need to review and add them manually if necessary.')
  1899. cc = cl.GetCCListWithoutDefault()
  1900. else:
  1901. cc = cl.GetCCList()
  1902. cc = ','.join(filter(None, (cc, ','.join(options.cc))))
  1903. if cc:
  1904. upload_args.extend(['--cc', cc])
  1905. if options.private or settings.GetDefaultPrivateFlag() == "True":
  1906. upload_args.append('--private')
  1907. upload_args.extend(['--git_similarity', str(options.similarity)])
  1908. if not options.find_copies:
  1909. upload_args.extend(['--git_no_find_copies'])
  1910. # Include the upstream repo's URL in the change -- this is useful for
  1911. # projects that have their source spread across multiple repos.
  1912. remote_url = cl.GetGitBaseUrlFromConfig()
  1913. if not remote_url:
  1914. if settings.GetIsGitSvn():
  1915. remote_url = cl.GetGitSvnRemoteUrl()
  1916. else:
  1917. if cl.GetRemoteUrl() and '/' in cl.GetUpstreamBranch():
  1918. remote_url = (cl.GetRemoteUrl() + '@'
  1919. + cl.GetUpstreamBranch().split('/')[-1])
  1920. if remote_url:
  1921. upload_args.extend(['--base_url', remote_url])
  1922. remote, remote_branch = cl.GetRemoteBranch()
  1923. target_ref = GetTargetRef(remote, remote_branch, options.target_branch,
  1924. settings.GetPendingRefPrefix())
  1925. if target_ref:
  1926. upload_args.extend(['--target_ref', target_ref])
  1927. # Look for dependent patchsets. See crbug.com/480453 for more details.
  1928. remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch())
  1929. upstream_branch = ShortBranchName(upstream_branch)
  1930. if remote is '.':
  1931. # A local branch is being tracked.
  1932. local_branch = ShortBranchName(upstream_branch)
  1933. if settings.GetIsSkipDependencyUpload(local_branch):
  1934. print
  1935. print ('Skipping dependency patchset upload because git config '
  1936. 'branch.%s.skip-deps-uploads is set to True.' % local_branch)
  1937. print
  1938. else:
  1939. auth_config = auth.extract_auth_config_from_options(options)
  1940. branch_cl = Changelist(branchref=local_branch, auth_config=auth_config)
  1941. branch_cl_issue_url = branch_cl.GetIssueURL()
  1942. branch_cl_issue = branch_cl.GetIssue()
  1943. branch_cl_patchset = branch_cl.GetPatchset()
  1944. if branch_cl_issue_url and branch_cl_issue and branch_cl_patchset:
  1945. upload_args.extend(
  1946. ['--depends_on_patchset', '%s:%s' % (
  1947. branch_cl_issue, branch_cl_patchset)])
  1948. print
  1949. print ('The current branch (%s) is tracking a local branch (%s) with '
  1950. 'an associated CL.') % (cl.GetBranch(), local_branch)
  1951. print 'Adding %s/#ps%s as a dependency patchset.' % (
  1952. branch_cl_issue_url, branch_cl_patchset)
  1953. print
  1954. project = settings.GetProject()
  1955. if project:
  1956. upload_args.extend(['--project', project])
  1957. if options.cq_dry_run:
  1958. upload_args.extend(['--cq_dry_run'])
  1959. try:
  1960. upload_args = ['upload'] + upload_args + args
  1961. logging.info('upload.RealMain(%s)', upload_args)
  1962. issue, patchset = upload.RealMain(upload_args)
  1963. issue = int(issue)
  1964. patchset = int(patchset)
  1965. except KeyboardInterrupt:
  1966. sys.exit(1)
  1967. except:
  1968. # If we got an exception after the user typed a description for their
  1969. # change, back up the description before re-raising.
  1970. if change_desc:
  1971. backup_path = os.path.expanduser(DESCRIPTION_BACKUP_FILE)
  1972. print '\nGot exception while uploading -- saving description to %s\n' \
  1973. % backup_path
  1974. backup_file = open(backup_path, 'w')
  1975. backup_file.write(change_desc.description)
  1976. backup_file.close()
  1977. raise
  1978. if not cl.GetIssue():
  1979. cl.SetIssue(issue)
  1980. cl.SetPatchset(patchset)
  1981. if options.use_commit_queue:
  1982. cl.SetFlag('commit', '1')
  1983. return 0
  1984. def cleanup_list(l):
  1985. """Fixes a list so that comma separated items are put as individual items.
  1986. So that "--reviewers joe@c,john@c --reviewers joa@c" results in
  1987. options.reviewers == sorted(['joe@c', 'john@c', 'joa@c']).
  1988. """
  1989. items = sum((i.split(',') for i in l), [])
  1990. stripped_items = (i.strip() for i in items)
  1991. return sorted(filter(None, stripped_items))
  1992. @subcommand.usage('[args to "git diff"]')
  1993. def CMDupload(parser, args):
  1994. """Uploads the current changelist to codereview.
  1995. Can skip dependency patchset uploads for a branch by running:
  1996. git config branch.branch_name.skip-deps-uploads True
  1997. To unset run:
  1998. git config --unset branch.branch_name.skip-deps-uploads
  1999. Can also set the above globally by using the --global flag.
  2000. """
  2001. parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
  2002. help='bypass upload presubmit hook')
  2003. parser.add_option('--bypass-watchlists', action='store_true',
  2004. dest='bypass_watchlists',
  2005. help='bypass watchlists auto CC-ing reviewers')
  2006. parser.add_option('-f', action='store_true', dest='force',
  2007. help="force yes to questions (don't prompt)")
  2008. parser.add_option('-m', dest='message', help='message for patchset')
  2009. parser.add_option('-t', dest='title', help='title for patchset')
  2010. parser.add_option('-r', '--reviewers',
  2011. action='append', default=[],
  2012. help='reviewer email addresses')
  2013. parser.add_option('--cc',
  2014. action='append', default=[],
  2015. help='cc email addresses')
  2016. parser.add_option('-s', '--send-mail', action='store_true',
  2017. help='send email to reviewer immediately')
  2018. parser.add_option('--emulate_svn_auto_props',
  2019. '--emulate-svn-auto-props',
  2020. action="store_true",
  2021. dest="emulate_svn_auto_props",
  2022. help="Emulate Subversion's auto properties feature.")
  2023. parser.add_option('-c', '--use-commit-queue', action='store_true',
  2024. help='tell the commit queue to commit this patchset')
  2025. parser.add_option('--private', action='store_true',
  2026. help='set the review private (rietveld only)')
  2027. parser.add_option('--target_branch',
  2028. '--target-branch',
  2029. metavar='TARGET',
  2030. help='Apply CL to remote ref TARGET. ' +
  2031. 'Default: remote branch head, or master')
  2032. parser.add_option('--squash', action='store_true',
  2033. help='Squash multiple commits into one (Gerrit only)')
  2034. parser.add_option('--email', default=None,
  2035. help='email address to use to connect to Rietveld')
  2036. parser.add_option('--tbr-owners', dest='tbr_owners', action='store_true',
  2037. help='add a set of OWNERS to TBR')
  2038. parser.add_option('--cq-dry-run', dest='cq_dry_run', action='store_true',
  2039. help='Send the patchset to do a CQ dry run right after '
  2040. 'upload.')
  2041. parser.add_option('--dependencies', action='store_true',
  2042. help='Uploads CLs of all the local branches that depend on '
  2043. 'the current branch')
  2044. orig_args = args
  2045. add_git_similarity(parser)
  2046. auth.add_auth_options(parser)
  2047. (options, args) = parser.parse_args(args)
  2048. auth_config = auth.extract_auth_config_from_options(options)
  2049. if git_common.is_dirty_git_tree('upload'):
  2050. return 1
  2051. options.reviewers = cleanup_list(options.reviewers)
  2052. options.cc = cleanup_list(options.cc)
  2053. cl = Changelist(auth_config=auth_config)
  2054. if args:
  2055. # TODO(ukai): is it ok for gerrit case?
  2056. base_branch = args[0]
  2057. else:
  2058. if cl.GetBranch() is None:
  2059. DieWithError('Can\'t upload from detached HEAD state. Get on a branch!')
  2060. # Default to diffing against common ancestor of upstream branch
  2061. base_branch = cl.GetCommonAncestorWithUpstream()
  2062. args = [base_branch, 'HEAD']
  2063. # Make sure authenticated to Rietveld before running expensive hooks. It is
  2064. # a fast, best efforts check. Rietveld still can reject the authentication
  2065. # during the actual upload.
  2066. if not settings.GetIsGerrit() and auth_config.use_oauth2:
  2067. authenticator = auth.get_authenticator_for_host(
  2068. cl.GetRietveldServer(), auth_config)
  2069. if not authenticator.has_cached_credentials():
  2070. raise auth.LoginRequiredError(cl.GetRietveldServer())
  2071. # Apply watchlists on upload.
  2072. change = cl.GetChange(base_branch, None)
  2073. watchlist = watchlists.Watchlists(change.RepositoryRoot())
  2074. files = [f.LocalPath() for f in change.AffectedFiles()]
  2075. if not options.bypass_watchlists:
  2076. cl.SetWatchers(watchlist.GetWatchersForPaths(files))
  2077. if not options.bypass_hooks:
  2078. if options.reviewers or options.tbr_owners:
  2079. # Set the reviewer list now so that presubmit checks can access it.
  2080. change_description = ChangeDescription(change.FullDescriptionText())
  2081. change_description.update_reviewers(options.reviewers,
  2082. options.tbr_owners,
  2083. change)
  2084. change.SetDescriptionText(change_description.description)
  2085. hook_results = cl.RunHook(committing=False,
  2086. may_prompt=not options.force,
  2087. verbose=options.verbose,
  2088. change=change)
  2089. if not hook_results.should_continue():
  2090. return 1
  2091. if not options.reviewers and hook_results.reviewers:
  2092. options.reviewers = hook_results.reviewers.split(',')
  2093. if cl.GetIssue():
  2094. latest_patchset = cl.GetMostRecentPatchset()
  2095. local_patchset = cl.GetPatchset()
  2096. if latest_patchset and local_patchset and local_patchset != latest_patchset:
  2097. print ('The last upload made from this repository was patchset #%d but '
  2098. 'the most recent patchset on the server is #%d.'
  2099. % (local_patchset, latest_patchset))
  2100. print ('Uploading will still work, but if you\'ve uploaded to this issue '
  2101. 'from another machine or branch the patch you\'re uploading now '
  2102. 'might not include those changes.')
  2103. ask_for_data('About to upload; enter to confirm.')
  2104. print_stats(options.similarity, options.find_copies, args)
  2105. if settings.GetIsGerrit():
  2106. return GerritUpload(options, args, cl, change)
  2107. ret = RietveldUpload(options, args, cl, change)
  2108. if not ret:
  2109. git_set_branch_value('last-upload-hash',
  2110. RunGit(['rev-parse', 'HEAD']).strip())
  2111. # Run post upload hooks, if specified.
  2112. if settings.GetRunPostUploadHook():
  2113. presubmit_support.DoPostUploadExecuter(
  2114. change,
  2115. cl,
  2116. settings.GetRoot(),
  2117. options.verbose,
  2118. sys.stdout)
  2119. # Upload all dependencies if specified.
  2120. if options.dependencies:
  2121. print
  2122. print '--dependencies has been specified.'
  2123. print 'All dependent local branches will be re-uploaded.'
  2124. print
  2125. # Remove the dependencies flag from args so that we do not end up in a
  2126. # loop.
  2127. orig_args.remove('--dependencies')
  2128. upload_branch_deps(cl, orig_args)
  2129. return ret
  2130. def IsSubmoduleMergeCommit(ref):
  2131. # When submodules are added to the repo, we expect there to be a single
  2132. # non-git-svn merge commit at remote HEAD with a signature comment.
  2133. pattern = '^SVN changes up to revision [0-9]*$'
  2134. cmd = ['rev-list', '--merges', '--grep=%s' % pattern, '%s^!' % ref]
  2135. return RunGit(cmd) != ''
  2136. def SendUpstream(parser, args, cmd):
  2137. """Common code for CMDland and CmdDCommit
  2138. Squashes branch into a single commit.
  2139. Updates changelog with metadata (e.g. pointer to review).
  2140. Pushes/dcommits the code upstream.
  2141. Updates review and closes.
  2142. """
  2143. parser.add_option('--bypass-hooks', action='store_true', dest='bypass_hooks',
  2144. help='bypass upload presubmit hook')
  2145. parser.add_option('-m', dest='message',
  2146. help="override review description")
  2147. parser.add_option('-f', action='store_true', dest='force',
  2148. help="force yes to questions (don't prompt)")
  2149. parser.add_option('-c', dest='contributor',
  2150. help="external contributor for patch (appended to " +
  2151. "description and used as author for git). Should be " +
  2152. "formatted as 'First Last <email@example.com>'")
  2153. add_git_similarity(parser)
  2154. auth.add_auth_options(parser)
  2155. (options, args) = parser.parse_args(args)
  2156. auth_config = auth.extract_auth_config_from_options(options)
  2157. cl = Changelist(auth_config=auth_config)
  2158. current = cl.GetBranch()
  2159. remote, upstream_branch = cl.FetchUpstreamTuple(cl.GetBranch())
  2160. if not settings.GetIsGitSvn() and remote == '.':
  2161. print
  2162. print 'Attempting to push branch %r into another local branch!' % current
  2163. print
  2164. print 'Either reparent this branch on top of origin/master:'
  2165. print ' git reparent-branch --root'
  2166. print
  2167. print 'OR run `git rebase-update` if you think the parent branch is already'
  2168. print 'committed.'
  2169. print
  2170. print ' Current parent: %r' % upstream_branch
  2171. return 1
  2172. if not args or cmd == 'land':
  2173. # Default to merging against our best guess of the upstream branch.
  2174. args = [cl.GetUpstreamBranch()]
  2175. if options.contributor:
  2176. if not re.match('^.*\s<\S+@\S+>$', options.contributor):
  2177. print "Please provide contibutor as 'First Last <email@example.com>'"
  2178. return 1
  2179. base_branch = args[0]
  2180. base_has_submodules = IsSubmoduleMergeCommit(base_branch)
  2181. if git_common.is_dirty_git_tree(cmd):
  2182. return 1
  2183. # This rev-list syntax means "show all commits not in my branch that
  2184. # are in base_branch".
  2185. upstream_commits = RunGit(['rev-list', '^' + cl.GetBranchRef(),
  2186. base_branch]).splitlines()
  2187. if upstream_commits:
  2188. print ('Base branch "%s" has %d commits '
  2189. 'not in this branch.' % (base_branch, len(upstream_commits)))
  2190. print 'Run "git merge %s" before attempting to %s.' % (base_branch, cmd)
  2191. return 1
  2192. # This is the revision `svn dcommit` will commit on top of.
  2193. svn_head = None
  2194. if cmd == 'dcommit' or base_has_submodules:
  2195. svn_head = RunGit(['log', '--grep=^git-svn-id:', '-1',
  2196. '--pretty=format:%H'])
  2197. if cmd == 'dcommit':
  2198. # If the base_head is a submodule merge commit, the first parent of the
  2199. # base_head should be a git-svn commit, which is what we're interested in.
  2200. base_svn_head = base_branch
  2201. if base_has_submodules:
  2202. base_svn_head += '^1'
  2203. extra_commits = RunGit(['rev-list', '^' + svn_head, base_svn_head])
  2204. if extra_commits:
  2205. print ('This branch has %d additional commits not upstreamed yet.'
  2206. % len(extra_commits.splitlines()))
  2207. print ('Upstream "%s" or rebase this branch on top of the upstream trunk '
  2208. 'before attempting to %s.' % (base_branch, cmd))
  2209. return 1
  2210. merge_base = RunGit(['merge-base', base_branch, 'HEAD']).strip()
  2211. if not options.bypass_hooks:
  2212. author = None
  2213. if options.contributor:
  2214. author = re.search(r'\<(.*)\>', options.contributor).group(1)
  2215. hook_results = cl.RunHook(
  2216. committing=True,
  2217. may_prompt=not options.force,
  2218. verbose=options.verbose,
  2219. change=cl.GetChange(merge_base, author))
  2220. if not hook_results.should_continue():
  2221. return 1
  2222. # Check the tree status if the tree status URL is set.
  2223. status = GetTreeStatus()
  2224. if 'closed' == status:
  2225. print('The tree is closed. Please wait for it to reopen. Use '
  2226. '"git cl %s --bypass-hooks" to commit on a closed tree.' % cmd)
  2227. return 1
  2228. elif 'unknown' == status:
  2229. print('Unable to determine tree status. Please verify manually and '
  2230. 'use "git cl %s --bypass-hooks" to commit on a closed tree.' % cmd)
  2231. return 1
  2232. else:
  2233. breakpad.SendStack(
  2234. 'GitClHooksBypassedCommit',
  2235. 'Issue %s/%s bypassed hook when committing (tree status was "%s")' %
  2236. (cl.GetRietveldServer(), cl.GetIssue(), GetTreeStatus()),
  2237. verbose=False)
  2238. change_desc = ChangeDescription(options.message)
  2239. if not change_desc.description and cl.GetIssue():
  2240. change_desc = ChangeDescription(cl.GetDescription())
  2241. if not change_desc.description:
  2242. if not cl.GetIssue() and options.bypass_hooks:
  2243. change_desc = ChangeDescription(CreateDescriptionFromLog([merge_base]))
  2244. else:
  2245. print 'No description set.'
  2246. print 'Visit %s/edit to set it.' % (cl.GetIssueURL())
  2247. return 1
  2248. # Keep a separate copy for the commit message, because the commit message
  2249. # contains the link to the Rietveld issue, while the Rietveld message contains
  2250. # the commit viewvc url.
  2251. # Keep a separate copy for the commit message.
  2252. if cl.GetIssue():
  2253. change_desc.update_reviewers(cl.GetApprovingReviewers())
  2254. commit_desc = ChangeDescription(change_desc.description)
  2255. if cl.GetIssue():
  2256. # Xcode won't linkify this URL unless there is a non-whitespace character
  2257. # after it. Add a period on a new line to circumvent this. Also add a space
  2258. # before the period to make sure that Gitiles continues to correctly resolve
  2259. # the URL.
  2260. commit_desc.append_footer('Review URL: %s .' % cl.GetIssueURL())
  2261. if options.contributor:
  2262. commit_desc.append_footer('Patch from %s.' % options.contributor)
  2263. print('Description:')
  2264. print(commit_desc.description)
  2265. branches = [merge_base, cl.GetBranchRef()]
  2266. if not options.force:
  2267. print_stats(options.similarity, options.find_copies, branches)
  2268. # We want to squash all this branch's commits into one commit with the proper
  2269. # description. We do this by doing a "reset --soft" to the base branch (which
  2270. # keeps the working copy the same), then dcommitting that. If origin/master
  2271. # has a submodule merge commit, we'll also need to cherry-pick the squashed
  2272. # commit onto a branch based on the git-svn head.
  2273. MERGE_BRANCH = 'git-cl-commit'
  2274. CHERRY_PICK_BRANCH = 'git-cl-cherry-pick'
  2275. # Delete the branches if they exist.
  2276. for branch in [MERGE_BRANCH, CHERRY_PICK_BRANCH]:
  2277. showref_cmd = ['show-ref', '--quiet', '--verify', 'refs/heads/%s' % branch]
  2278. result = RunGitWithCode(showref_cmd)
  2279. if result[0] == 0:
  2280. RunGit(['branch', '-D', branch])
  2281. # We might be in a directory that's present in this branch but not in the
  2282. # trunk. Move up to the top of the tree so that git commands that expect a
  2283. # valid CWD won't fail after we check out the merge branch.
  2284. rel_base_path = settings.GetRelativeRoot()
  2285. if rel_base_path:
  2286. os.chdir(rel_base_path)
  2287. # Stuff our change into the merge branch.
  2288. # We wrap in a try...finally block so if anything goes wrong,
  2289. # we clean up the branches.
  2290. retcode = -1
  2291. pushed_to_pending = False
  2292. pending_ref = None
  2293. revision = None
  2294. try:
  2295. RunGit(['checkout', '-q', '-b', MERGE_BRANCH])
  2296. RunGit(['reset', '--soft', merge_base])
  2297. if options.contributor:
  2298. RunGit(
  2299. [
  2300. 'commit', '--author', options.contributor,
  2301. '-m', commit_desc.description,
  2302. ])
  2303. else:
  2304. RunGit(['commit', '-m', commit_desc.description])
  2305. if base_has_submodules:
  2306. cherry_pick_commit = RunGit(['rev-list', 'HEAD^!']).rstrip()
  2307. RunGit(['branch', CHERRY_PICK_BRANCH, svn_head])
  2308. RunGit(['checkout', CHERRY_PICK_BRANCH])
  2309. RunGit(['cherry-pick', cherry_pick_commit])
  2310. if cmd == 'land':
  2311. remote, branch = cl.FetchUpstreamTuple(cl.GetBranch())
  2312. pending_prefix = settings.GetPendingRefPrefix()
  2313. if not pending_prefix or branch.startswith(pending_prefix):
  2314. # If not using refs/pending/heads/* at all, or target ref is already set
  2315. # to pending, then push to the target ref directly.
  2316. retcode, output = RunGitWithCode(
  2317. ['push', '--porcelain', remote, 'HEAD:%s' % branch])
  2318. pushed_to_pending = pending_prefix and branch.startswith(pending_prefix)
  2319. else:
  2320. # Cherry-pick the change on top of pending ref and then push it.
  2321. assert branch.startswith('refs/'), branch
  2322. assert pending_prefix[-1] == '/', pending_prefix
  2323. pending_ref = pending_prefix + branch[len('refs/'):]
  2324. retcode, output = PushToGitPending(remote, pending_ref, branch)
  2325. pushed_to_pending = (retcode == 0)
  2326. if retcode == 0:
  2327. revision = RunGit(['rev-parse', 'HEAD']).strip()
  2328. else:
  2329. # dcommit the merge branch.
  2330. cmd_args = [
  2331. 'svn', 'dcommit',
  2332. '-C%s' % options.similarity,
  2333. '--no-rebase', '--rmdir',
  2334. ]
  2335. if settings.GetForceHttpsCommitUrl():
  2336. # Allow forcing https commit URLs for some projects that don't allow
  2337. # committing to http URLs (like Google Code).
  2338. remote_url = cl.GetGitSvnRemoteUrl()
  2339. if urlparse.urlparse(remote_url).scheme == 'http':
  2340. remote_url = remote_url.replace('http://', 'https://')
  2341. cmd_args.append('--commit-url=%s' % remote_url)
  2342. _, output = RunGitWithCode(cmd_args)
  2343. if 'Committed r' in output:
  2344. revision = re.match(
  2345. '.*?\nCommitted r(\\d+)', output, re.DOTALL).group(1)
  2346. logging.debug(output)
  2347. finally:
  2348. # And then swap back to the original branch and clean up.
  2349. RunGit(['checkout', '-q', cl.GetBranch()])
  2350. RunGit(['branch', '-D', MERGE_BRANCH])
  2351. if base_has_submodules:
  2352. RunGit(['branch', '-D', CHERRY_PICK_BRANCH])
  2353. if not revision:
  2354. print 'Failed to push. If this persists, please file a bug.'
  2355. return 1
  2356. killed = False
  2357. if pushed_to_pending:
  2358. try:
  2359. revision = WaitForRealCommit(remote, revision, base_branch, branch)
  2360. # We set pushed_to_pending to False, since it made it all the way to the
  2361. # real ref.
  2362. pushed_to_pending = False
  2363. except KeyboardInterrupt:
  2364. killed = True
  2365. if cl.GetIssue():
  2366. to_pending = ' to pending queue' if pushed_to_pending else ''
  2367. viewvc_url = settings.GetViewVCUrl()
  2368. if not to_pending:
  2369. if viewvc_url and revision:
  2370. change_desc.append_footer(
  2371. 'Committed: %s%s' % (viewvc_url, revision))
  2372. elif revision:
  2373. change_desc.append_footer('Committed: %s' % (revision,))
  2374. print ('Closing issue '
  2375. '(you may be prompted for your codereview password)...')
  2376. cl.UpdateDescription(change_desc.description)
  2377. cl.CloseIssue()
  2378. props = cl.GetIssueProperties()
  2379. patch_num = len(props['patchsets'])
  2380. comment = "Committed patchset #%d (id:%d)%s manually as %s" % (
  2381. patch_num, props['patchsets'][-1], to_pending, revision)
  2382. if options.bypass_hooks:
  2383. comment += ' (tree was closed).' if GetTreeStatus() == 'closed' else '.'
  2384. else:
  2385. comment += ' (presubmit successful).'
  2386. cl.RpcServer().add_comment(cl.GetIssue(), comment)
  2387. cl.SetIssue(None)
  2388. if pushed_to_pending:
  2389. _, branch = cl.FetchUpstreamTuple(cl.GetBranch())
  2390. print 'The commit is in the pending queue (%s).' % pending_ref
  2391. print (
  2392. 'It will show up on %s in ~1 min, once it gets a Cr-Commit-Position '
  2393. 'footer.' % branch)
  2394. hook = POSTUPSTREAM_HOOK_PATTERN % cmd
  2395. if os.path.isfile(hook):
  2396. RunCommand([hook, merge_base], error_ok=True)
  2397. return 1 if killed else 0
  2398. def WaitForRealCommit(remote, pushed_commit, local_base_ref, real_ref):
  2399. print
  2400. print 'Waiting for commit to be landed on %s...' % real_ref
  2401. print '(If you are impatient, you may Ctrl-C once without harm)'
  2402. target_tree = RunGit(['rev-parse', '%s:' % pushed_commit]).strip()
  2403. current_rev = RunGit(['rev-parse', local_base_ref]).strip()
  2404. loop = 0
  2405. while True:
  2406. sys.stdout.write('fetching (%d)... \r' % loop)
  2407. sys.stdout.flush()
  2408. loop += 1
  2409. RunGit(['retry', 'fetch', remote, real_ref], stderr=subprocess2.VOID)
  2410. to_rev = RunGit(['rev-parse', 'FETCH_HEAD']).strip()
  2411. commits = RunGit(['rev-list', '%s..%s' % (current_rev, to_rev)])
  2412. for commit in commits.splitlines():
  2413. if RunGit(['rev-parse', '%s:' % commit]).strip() == target_tree:
  2414. print 'Found commit on %s' % real_ref
  2415. return commit
  2416. current_rev = to_rev
  2417. def PushToGitPending(remote, pending_ref, upstream_ref):
  2418. """Fetches pending_ref, cherry-picks current HEAD on top of it, pushes.
  2419. Returns:
  2420. (retcode of last operation, output log of last operation).
  2421. """
  2422. assert pending_ref.startswith('refs/'), pending_ref
  2423. local_pending_ref = 'refs/git-cl/' + pending_ref[len('refs/'):]
  2424. cherry = RunGit(['rev-parse', 'HEAD']).strip()
  2425. code = 0
  2426. out = ''
  2427. max_attempts = 3
  2428. attempts_left = max_attempts
  2429. while attempts_left:
  2430. if attempts_left != max_attempts:
  2431. print 'Retrying, %d attempts left...' % (attempts_left - 1,)
  2432. attempts_left -= 1
  2433. # Fetch. Retry fetch errors.
  2434. print 'Fetching pending ref %s...' % pending_ref
  2435. code, out = RunGitWithCode(
  2436. ['retry', 'fetch', remote, '+%s:%s' % (pending_ref, local_pending_ref)])
  2437. if code:
  2438. print 'Fetch failed with exit code %d.' % code
  2439. if out.strip():
  2440. print out.strip()
  2441. continue
  2442. # Try to cherry pick. Abort on merge conflicts.
  2443. print 'Cherry-picking commit on top of pending ref...'
  2444. RunGitWithCode(['checkout', local_pending_ref], suppress_stderr=True)
  2445. code, out = RunGitWithCode(['cherry-pick', cherry])
  2446. if code:
  2447. print (
  2448. 'Your patch doesn\'t apply cleanly to ref \'%s\', '
  2449. 'the following files have merge conflicts:' % pending_ref)
  2450. print RunGit(['diff', '--name-status', '--diff-filter=U']).strip()
  2451. print 'Please rebase your patch and try again.'
  2452. RunGitWithCode(['cherry-pick', '--abort'])
  2453. return code, out
  2454. # Applied cleanly, try to push now. Retry on error (flake or non-ff push).
  2455. print 'Pushing commit to %s... It can take a while.' % pending_ref
  2456. code, out = RunGitWithCode(
  2457. ['retry', 'push', '--porcelain', remote, 'HEAD:%s' % pending_ref])
  2458. if code == 0:
  2459. # Success.
  2460. print 'Commit pushed to pending ref successfully!'
  2461. return code, out
  2462. print 'Push failed with exit code %d.' % code
  2463. if out.strip():
  2464. print out.strip()
  2465. if IsFatalPushFailure(out):
  2466. print (
  2467. 'Fatal push error. Make sure your .netrc credentials and git '
  2468. 'user.email are correct and you have push access to the repo.')
  2469. return code, out
  2470. print 'All attempts to push to pending ref failed.'
  2471. return code, out
  2472. def IsFatalPushFailure(push_stdout):
  2473. """True if retrying push won't help."""
  2474. return '(prohibited by Gerrit)' in push_stdout
  2475. @subcommand.usage('[upstream branch to apply against]')
  2476. def CMDdcommit(parser, args):
  2477. """Commits the current changelist via git-svn."""
  2478. if not settings.GetIsGitSvn():
  2479. if get_footer_svn_id():
  2480. # If it looks like previous commits were mirrored with git-svn.
  2481. message = """This repository appears to be a git-svn mirror, but no
  2482. upstream SVN master is set. You probably need to run 'git auto-svn' once."""
  2483. else:
  2484. message = """This doesn't appear to be an SVN repository.
  2485. If your project has a true, writeable git repository, you probably want to run
  2486. 'git cl land' instead.
  2487. If your project has a git mirror of an upstream SVN master, you probably need
  2488. to run 'git svn init'.
  2489. Using the wrong command might cause your commit to appear to succeed, and the
  2490. review to be closed, without actually landing upstream. If you choose to
  2491. proceed, please verify that the commit lands upstream as expected."""
  2492. print(message)
  2493. ask_for_data('[Press enter to dcommit or ctrl-C to quit]')
  2494. return SendUpstream(parser, args, 'dcommit')
  2495. @subcommand.usage('[upstream branch to apply against]')
  2496. def CMDland(parser, args):
  2497. """Commits the current changelist via git."""
  2498. if settings.GetIsGitSvn() or get_footer_svn_id():
  2499. print('This appears to be an SVN repository.')
  2500. print('Are you sure you didn\'t mean \'git cl dcommit\'?')
  2501. print('(Ignore if this is the first commit after migrating from svn->git)')
  2502. ask_for_data('[Press enter to push or ctrl-C to quit]')
  2503. return SendUpstream(parser, args, 'land')
  2504. def ParseIssueNum(arg):
  2505. """Parses the issue number from args if present otherwise returns None."""
  2506. if re.match(r'\d+', arg):
  2507. return arg
  2508. if arg.startswith('http'):
  2509. return re.sub(r'.*/(\d+)/?', r'\1', arg)
  2510. return None
  2511. @subcommand.usage('<patch url or issue id or issue url>')
  2512. def CMDpatch(parser, args):
  2513. """Patches in a code review."""
  2514. parser.add_option('-b', dest='newbranch',
  2515. help='create a new branch off trunk for the patch')
  2516. parser.add_option('-f', '--force', action='store_true',
  2517. help='with -b, clobber any existing branch')
  2518. parser.add_option('-d', '--directory', action='store', metavar='DIR',
  2519. help='Change to the directory DIR immediately, '
  2520. 'before doing anything else.')
  2521. parser.add_option('--reject', action='store_true',
  2522. help='failed patches spew .rej files rather than '
  2523. 'attempting a 3-way merge')
  2524. parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit',
  2525. help="don't commit after patch applies")
  2526. auth.add_auth_options(parser)
  2527. (options, args) = parser.parse_args(args)
  2528. auth_config = auth.extract_auth_config_from_options(options)
  2529. if len(args) != 1:
  2530. parser.print_help()
  2531. return 1
  2532. issue_arg = ParseIssueNum(args[0])
  2533. # The patch URL works because ParseIssueNum won't do any substitution
  2534. # as the re.sub pattern fails to match and just returns it.
  2535. if issue_arg == None:
  2536. parser.print_help()
  2537. return 1
  2538. # We don't want uncommitted changes mixed up with the patch.
  2539. if git_common.is_dirty_git_tree('patch'):
  2540. return 1
  2541. # TODO(maruel): Use apply_issue.py
  2542. # TODO(ukai): use gerrit-cherry-pick for gerrit repository?
  2543. if options.newbranch:
  2544. if options.force:
  2545. RunGit(['branch', '-D', options.newbranch],
  2546. stderr=subprocess2.PIPE, error_ok=True)
  2547. RunGit(['checkout', '-b', options.newbranch,
  2548. Changelist().GetUpstreamBranch()])
  2549. return PatchIssue(issue_arg, options.reject, options.nocommit,
  2550. options.directory, auth_config)
  2551. def PatchIssue(issue_arg, reject, nocommit, directory, auth_config):
  2552. # PatchIssue should never be called with a dirty tree. It is up to the
  2553. # caller to check this, but just in case we assert here since the
  2554. # consequences of the caller not checking this could be dire.
  2555. assert(not git_common.is_dirty_git_tree('apply'))
  2556. if type(issue_arg) is int or issue_arg.isdigit():
  2557. # Input is an issue id. Figure out the URL.
  2558. issue = int(issue_arg)
  2559. cl = Changelist(issue=issue, auth_config=auth_config)
  2560. patchset = cl.GetMostRecentPatchset()
  2561. patch_data = cl.GetPatchSetDiff(issue, patchset)
  2562. else:
  2563. # Assume it's a URL to the patch. Default to https.
  2564. issue_url = gclient_utils.UpgradeToHttps(issue_arg)
  2565. match = re.match(r'(.*?)/download/issue(\d+)_(\d+).diff', issue_url)
  2566. if not match:
  2567. DieWithError('Must pass an issue ID or full URL for '
  2568. '\'Download raw patch set\'')
  2569. issue = int(match.group(2))
  2570. cl = Changelist(issue=issue, auth_config=auth_config)
  2571. cl.rietveld_server = match.group(1)
  2572. patchset = int(match.group(3))
  2573. patch_data = urllib2.urlopen(issue_arg).read()
  2574. # Switch up to the top-level directory, if necessary, in preparation for
  2575. # applying the patch.
  2576. top = settings.GetRelativeRoot()
  2577. if top:
  2578. os.chdir(top)
  2579. # Git patches have a/ at the beginning of source paths. We strip that out
  2580. # with a sed script rather than the -p flag to patch so we can feed either
  2581. # Git or svn-style patches into the same apply command.
  2582. # re.sub() should be used but flags=re.MULTILINE is only in python 2.7.
  2583. try:
  2584. patch_data = subprocess2.check_output(
  2585. ['sed', '-e', 's|^--- a/|--- |; s|^+++ b/|+++ |'], stdin=patch_data)
  2586. except subprocess2.CalledProcessError:
  2587. DieWithError('Git patch mungling failed.')
  2588. logging.info(patch_data)
  2589. # We use "git apply" to apply the patch instead of "patch" so that we can
  2590. # pick up file adds.
  2591. # The --index flag means: also insert into the index (so we catch adds).
  2592. cmd = ['git', 'apply', '--index', '-p0']
  2593. if directory:
  2594. cmd.extend(('--directory', directory))
  2595. if reject:
  2596. cmd.append('--reject')
  2597. elif IsGitVersionAtLeast('1.7.12'):
  2598. cmd.append('--3way')
  2599. try:
  2600. subprocess2.check_call(cmd, env=GetNoGitPagerEnv(),
  2601. stdin=patch_data, stdout=subprocess2.VOID)
  2602. except subprocess2.CalledProcessError:
  2603. print 'Failed to apply the patch'
  2604. return 1
  2605. # If we had an issue, commit the current state and register the issue.
  2606. if not nocommit:
  2607. RunGit(['commit', '-m', (cl.GetDescription() + '\n\n' +
  2608. 'patch from issue %(i)s at patchset '
  2609. '%(p)s (http://crrev.com/%(i)s#ps%(p)s)'
  2610. % {'i': issue, 'p': patchset})])
  2611. cl = Changelist(auth_config=auth_config)
  2612. cl.SetIssue(issue)
  2613. cl.SetPatchset(patchset)
  2614. print "Committed patch locally."
  2615. else:
  2616. print "Patch applied to index."
  2617. return 0
  2618. def CMDrebase(parser, args):
  2619. """Rebases current branch on top of svn repo."""
  2620. # Provide a wrapper for git svn rebase to help avoid accidental
  2621. # git svn dcommit.
  2622. # It's the only command that doesn't use parser at all since we just defer
  2623. # execution to git-svn.
  2624. return RunGitWithCode(['svn', 'rebase'] + args)[1]
  2625. def GetTreeStatus(url=None):
  2626. """Fetches the tree status and returns either 'open', 'closed',
  2627. 'unknown' or 'unset'."""
  2628. url = url or settings.GetTreeStatusUrl(error_ok=True)
  2629. if url:
  2630. status = urllib2.urlopen(url).read().lower()
  2631. if status.find('closed') != -1 or status == '0':
  2632. return 'closed'
  2633. elif status.find('open') != -1 or status == '1':
  2634. return 'open'
  2635. return 'unknown'
  2636. return 'unset'
  2637. def GetTreeStatusReason():
  2638. """Fetches the tree status from a json url and returns the message
  2639. with the reason for the tree to be opened or closed."""
  2640. url = settings.GetTreeStatusUrl()
  2641. json_url = urlparse.urljoin(url, '/current?format=json')
  2642. connection = urllib2.urlopen(json_url)
  2643. status = json.loads(connection.read())
  2644. connection.close()
  2645. return status['message']
  2646. def GetBuilderMaster(bot_list):
  2647. """For a given builder, fetch the master from AE if available."""
  2648. map_url = 'https://builders-map.appspot.com/'
  2649. try:
  2650. master_map = json.load(urllib2.urlopen(map_url))
  2651. except urllib2.URLError as e:
  2652. return None, ('Failed to fetch builder-to-master map from %s. Error: %s.' %
  2653. (map_url, e))
  2654. except ValueError as e:
  2655. return None, ('Invalid json string from %s. Error: %s.' % (map_url, e))
  2656. if not master_map:
  2657. return None, 'Failed to build master map.'
  2658. result_master = ''
  2659. for bot in bot_list:
  2660. builder = bot.split(':', 1)[0]
  2661. master_list = master_map.get(builder, [])
  2662. if not master_list:
  2663. return None, ('No matching master for builder %s.' % builder)
  2664. elif len(master_list) > 1:
  2665. return None, ('The builder name %s exists in multiple masters %s.' %
  2666. (builder, master_list))
  2667. else:
  2668. cur_master = master_list[0]
  2669. if not result_master:
  2670. result_master = cur_master
  2671. elif result_master != cur_master:
  2672. return None, 'The builders do not belong to the same master.'
  2673. return result_master, None
  2674. def CMDtree(parser, args):
  2675. """Shows the status of the tree."""
  2676. _, args = parser.parse_args(args)
  2677. status = GetTreeStatus()
  2678. if 'unset' == status:
  2679. print 'You must configure your tree status URL by running "git cl config".'
  2680. return 2
  2681. print "The tree is %s" % status
  2682. print
  2683. print GetTreeStatusReason()
  2684. if status != 'open':
  2685. return 1
  2686. return 0
  2687. def CMDtry(parser, args):
  2688. """Triggers a try job through BuildBucket."""
  2689. group = optparse.OptionGroup(parser, "Try job options")
  2690. group.add_option(
  2691. "-b", "--bot", action="append",
  2692. help=("IMPORTANT: specify ONE builder per --bot flag. Use it multiple "
  2693. "times to specify multiple builders. ex: "
  2694. "'-b win_rel -b win_layout'. See "
  2695. "the try server waterfall for the builders name and the tests "
  2696. "available."))
  2697. group.add_option(
  2698. "-m", "--master", default='',
  2699. help=("Specify a try master where to run the tries."))
  2700. group.add_option( "--luci", action='store_true')
  2701. group.add_option(
  2702. "-r", "--revision",
  2703. help="Revision to use for the try job; default: the "
  2704. "revision will be determined by the try server; see "
  2705. "its waterfall for more info")
  2706. group.add_option(
  2707. "-c", "--clobber", action="store_true", default=False,
  2708. help="Force a clobber before building; e.g. don't do an "
  2709. "incremental build")
  2710. group.add_option(
  2711. "--project",
  2712. help="Override which project to use. Projects are defined "
  2713. "server-side to define what default bot set to use")
  2714. group.add_option(
  2715. "-p", "--property", dest="properties", action="append", default=[],
  2716. help="Specify generic properties in the form -p key1=value1 -p "
  2717. "key2=value2 etc (buildbucket only). The value will be treated as "
  2718. "json if decodable, or as string otherwise.")
  2719. group.add_option(
  2720. "-n", "--name", help="Try job name; default to current branch name")
  2721. group.add_option(
  2722. "--use-rietveld", action="store_true", default=False,
  2723. help="Use Rietveld to trigger try jobs.")
  2724. group.add_option(
  2725. "--buildbucket-host", default='cr-buildbucket.appspot.com',
  2726. help="Host of buildbucket. The default host is %default.")
  2727. parser.add_option_group(group)
  2728. auth.add_auth_options(parser)
  2729. options, args = parser.parse_args(args)
  2730. auth_config = auth.extract_auth_config_from_options(options)
  2731. if options.use_rietveld and options.properties:
  2732. parser.error('Properties can only be specified with buildbucket')
  2733. # Make sure that all properties are prop=value pairs.
  2734. bad_params = [x for x in options.properties if '=' not in x]
  2735. if bad_params:
  2736. parser.error('Got properties with missing "=": %s' % bad_params)
  2737. if args:
  2738. parser.error('Unknown arguments: %s' % args)
  2739. cl = Changelist(auth_config=auth_config)
  2740. if not cl.GetIssue():
  2741. parser.error('Need to upload first')
  2742. props = cl.GetIssueProperties()
  2743. if props.get('closed'):
  2744. parser.error('Cannot send tryjobs for a closed CL')
  2745. if props.get('private'):
  2746. parser.error('Cannot use trybots with private issue')
  2747. if not options.name:
  2748. options.name = cl.GetBranch()
  2749. if options.bot and not options.master:
  2750. options.master, err_msg = GetBuilderMaster(options.bot)
  2751. if err_msg:
  2752. parser.error('Tryserver master cannot be found because: %s\n'
  2753. 'Please manually specify the tryserver master'
  2754. ', e.g. "-m tryserver.chromium.linux".' % err_msg)
  2755. def GetMasterMap():
  2756. # Process --bot.
  2757. if not options.bot:
  2758. change = cl.GetChange(cl.GetCommonAncestorWithUpstream(), None)
  2759. # Get try masters from PRESUBMIT.py files.
  2760. masters = presubmit_support.DoGetTryMasters(
  2761. change,
  2762. change.LocalPaths(),
  2763. settings.GetRoot(),
  2764. None,
  2765. None,
  2766. options.verbose,
  2767. sys.stdout)
  2768. if masters:
  2769. return masters
  2770. # Fall back to deprecated method: get try slaves from PRESUBMIT.py files.
  2771. options.bot = presubmit_support.DoGetTrySlaves(
  2772. change,
  2773. change.LocalPaths(),
  2774. settings.GetRoot(),
  2775. None,
  2776. None,
  2777. options.verbose,
  2778. sys.stdout)
  2779. if not options.bot:
  2780. parser.error('No default try builder to try, use --bot')
  2781. builders_and_tests = {}
  2782. # TODO(machenbach): The old style command-line options don't support
  2783. # multiple try masters yet.
  2784. old_style = filter(lambda x: isinstance(x, basestring), options.bot)
  2785. new_style = filter(lambda x: isinstance(x, tuple), options.bot)
  2786. for bot in old_style:
  2787. if ':' in bot:
  2788. parser.error('Specifying testfilter is no longer supported')
  2789. elif ',' in bot:
  2790. parser.error('Specify one bot per --bot flag')
  2791. else:
  2792. builders_and_tests.setdefault(bot, [])
  2793. for bot, tests in new_style:
  2794. builders_and_tests.setdefault(bot, []).extend(tests)
  2795. # Return a master map with one master to be backwards compatible. The
  2796. # master name defaults to an empty string, which will cause the master
  2797. # not to be set on rietveld (deprecated).
  2798. return {options.master: builders_and_tests}
  2799. masters = GetMasterMap()
  2800. for builders in masters.itervalues():
  2801. if any('triggered' in b for b in builders):
  2802. print >> sys.stderr, (
  2803. 'ERROR You are trying to send a job to a triggered bot. This type of'
  2804. ' bot requires an\ninitial job from a parent (usually a builder). '
  2805. 'Instead send your job to the parent.\n'
  2806. 'Bot list: %s' % builders)
  2807. return 1
  2808. patchset = cl.GetMostRecentPatchset()
  2809. if patchset and patchset != cl.GetPatchset():
  2810. print(
  2811. '\nWARNING Mismatch between local config and server. Did a previous '
  2812. 'upload fail?\ngit-cl try always uses latest patchset from rietveld. '
  2813. 'Continuing using\npatchset %s.\n' % patchset)
  2814. if options.luci:
  2815. trigger_luci_job(cl, masters, options)
  2816. elif not options.use_rietveld:
  2817. try:
  2818. trigger_try_jobs(auth_config, cl, options, masters, 'git_cl_try')
  2819. except BuildbucketResponseException as ex:
  2820. print 'ERROR: %s' % ex
  2821. return 1
  2822. except Exception as e:
  2823. stacktrace = (''.join(traceback.format_stack()) + traceback.format_exc())
  2824. print 'ERROR: Exception when trying to trigger tryjobs: %s\n%s' % (
  2825. e, stacktrace)
  2826. return 1
  2827. else:
  2828. try:
  2829. cl.RpcServer().trigger_distributed_try_jobs(
  2830. cl.GetIssue(), patchset, options.name, options.clobber,
  2831. options.revision, masters)
  2832. except urllib2.HTTPError as e:
  2833. if e.code == 404:
  2834. print('404 from rietveld; '
  2835. 'did you mean to use "git try" instead of "git cl try"?')
  2836. return 1
  2837. print('Tried jobs on:')
  2838. for (master, builders) in sorted(masters.iteritems()):
  2839. if master:
  2840. print 'Master: %s' % master
  2841. length = max(len(builder) for builder in builders)
  2842. for builder in sorted(builders):
  2843. print ' %*s: %s' % (length, builder, ','.join(builders[builder]))
  2844. return 0
  2845. @subcommand.usage('[new upstream branch]')
  2846. def CMDupstream(parser, args):
  2847. """Prints or sets the name of the upstream branch, if any."""
  2848. _, args = parser.parse_args(args)
  2849. if len(args) > 1:
  2850. parser.error('Unrecognized args: %s' % ' '.join(args))
  2851. cl = Changelist()
  2852. if args:
  2853. # One arg means set upstream branch.
  2854. branch = cl.GetBranch()
  2855. RunGit(['branch', '--set-upstream', branch, args[0]])
  2856. cl = Changelist()
  2857. print "Upstream branch set to " + cl.GetUpstreamBranch()
  2858. # Clear configured merge-base, if there is one.
  2859. git_common.remove_merge_base(branch)
  2860. else:
  2861. print cl.GetUpstreamBranch()
  2862. return 0
  2863. def CMDweb(parser, args):
  2864. """Opens the current CL in the web browser."""
  2865. _, args = parser.parse_args(args)
  2866. if args:
  2867. parser.error('Unrecognized args: %s' % ' '.join(args))
  2868. issue_url = Changelist().GetIssueURL()
  2869. if not issue_url:
  2870. print >> sys.stderr, 'ERROR No issue to open'
  2871. return 1
  2872. webbrowser.open(issue_url)
  2873. return 0
  2874. def CMDset_commit(parser, args):
  2875. """Sets the commit bit to trigger the Commit Queue."""
  2876. auth.add_auth_options(parser)
  2877. options, args = parser.parse_args(args)
  2878. auth_config = auth.extract_auth_config_from_options(options)
  2879. if args:
  2880. parser.error('Unrecognized args: %s' % ' '.join(args))
  2881. cl = Changelist(auth_config=auth_config)
  2882. props = cl.GetIssueProperties()
  2883. if props.get('private'):
  2884. parser.error('Cannot set commit on private issue')
  2885. cl.SetFlag('commit', '1')
  2886. return 0
  2887. def CMDset_close(parser, args):
  2888. """Closes the issue."""
  2889. auth.add_auth_options(parser)
  2890. options, args = parser.parse_args(args)
  2891. auth_config = auth.extract_auth_config_from_options(options)
  2892. if args:
  2893. parser.error('Unrecognized args: %s' % ' '.join(args))
  2894. cl = Changelist(auth_config=auth_config)
  2895. # Ensure there actually is an issue to close.
  2896. cl.GetDescription()
  2897. cl.CloseIssue()
  2898. return 0
  2899. def CMDdiff(parser, args):
  2900. """Shows differences between local tree and last upload."""
  2901. auth.add_auth_options(parser)
  2902. options, args = parser.parse_args(args)
  2903. auth_config = auth.extract_auth_config_from_options(options)
  2904. if args:
  2905. parser.error('Unrecognized args: %s' % ' '.join(args))
  2906. # Uncommitted (staged and unstaged) changes will be destroyed by
  2907. # "git reset --hard" if there are merging conflicts in PatchIssue().
  2908. # Staged changes would be committed along with the patch from last
  2909. # upload, hence counted toward the "last upload" side in the final
  2910. # diff output, and this is not what we want.
  2911. if git_common.is_dirty_git_tree('diff'):
  2912. return 1
  2913. cl = Changelist(auth_config=auth_config)
  2914. issue = cl.GetIssue()
  2915. branch = cl.GetBranch()
  2916. if not issue:
  2917. DieWithError('No issue found for current branch (%s)' % branch)
  2918. TMP_BRANCH = 'git-cl-diff'
  2919. base_branch = cl.GetCommonAncestorWithUpstream()
  2920. # Create a new branch based on the merge-base
  2921. RunGit(['checkout', '-q', '-b', TMP_BRANCH, base_branch])
  2922. try:
  2923. # Patch in the latest changes from rietveld.
  2924. rtn = PatchIssue(issue, False, False, None, auth_config)
  2925. if rtn != 0:
  2926. RunGit(['reset', '--hard'])
  2927. return rtn
  2928. # Switch back to starting branch and diff against the temporary
  2929. # branch containing the latest rietveld patch.
  2930. subprocess2.check_call(['git', 'diff', TMP_BRANCH, branch, '--'])
  2931. finally:
  2932. RunGit(['checkout', '-q', branch])
  2933. RunGit(['branch', '-D', TMP_BRANCH])
  2934. return 0
  2935. def CMDowners(parser, args):
  2936. """Interactively find the owners for reviewing."""
  2937. parser.add_option(
  2938. '--no-color',
  2939. action='store_true',
  2940. help='Use this option to disable color output')
  2941. auth.add_auth_options(parser)
  2942. options, args = parser.parse_args(args)
  2943. auth_config = auth.extract_auth_config_from_options(options)
  2944. author = RunGit(['config', 'user.email']).strip() or None
  2945. cl = Changelist(auth_config=auth_config)
  2946. if args:
  2947. if len(args) > 1:
  2948. parser.error('Unknown args')
  2949. base_branch = args[0]
  2950. else:
  2951. # Default to diffing against the common ancestor of the upstream branch.
  2952. base_branch = cl.GetCommonAncestorWithUpstream()
  2953. change = cl.GetChange(base_branch, None)
  2954. return owners_finder.OwnersFinder(
  2955. [f.LocalPath() for f in
  2956. cl.GetChange(base_branch, None).AffectedFiles()],
  2957. change.RepositoryRoot(), author,
  2958. fopen=file, os_path=os.path, glob=glob.glob,
  2959. disable_color=options.no_color).run()
  2960. def BuildGitDiffCmd(diff_type, upstream_commit, args, extensions):
  2961. """Generates a diff command."""
  2962. # Generate diff for the current branch's changes.
  2963. diff_cmd = ['diff', '--no-ext-diff', '--no-prefix', diff_type,
  2964. upstream_commit, '--' ]
  2965. if args:
  2966. for arg in args:
  2967. if os.path.isdir(arg):
  2968. diff_cmd.extend(os.path.join(arg, '*' + ext) for ext in extensions)
  2969. elif os.path.isfile(arg):
  2970. diff_cmd.append(arg)
  2971. else:
  2972. DieWithError('Argument "%s" is not a file or a directory' % arg)
  2973. else:
  2974. diff_cmd.extend('*' + ext for ext in extensions)
  2975. return diff_cmd
  2976. @subcommand.usage('[files or directories to diff]')
  2977. def CMDformat(parser, args):
  2978. """Runs auto-formatting tools (clang-format etc.) on the diff."""
  2979. CLANG_EXTS = ['.cc', '.cpp', '.h', '.mm', '.proto', '.java']
  2980. parser.add_option('--full', action='store_true',
  2981. help='Reformat the full content of all touched files')
  2982. parser.add_option('--dry-run', action='store_true',
  2983. help='Don\'t modify any file on disk.')
  2984. parser.add_option('--python', action='store_true',
  2985. help='Format python code with yapf (experimental).')
  2986. parser.add_option('--diff', action='store_true',
  2987. help='Print diff to stdout rather than modifying files.')
  2988. opts, args = parser.parse_args(args)
  2989. # git diff generates paths against the root of the repository. Change
  2990. # to that directory so clang-format can find files even within subdirs.
  2991. rel_base_path = settings.GetRelativeRoot()
  2992. if rel_base_path:
  2993. os.chdir(rel_base_path)
  2994. # Grab the merge-base commit, i.e. the upstream commit of the current
  2995. # branch when it was created or the last time it was rebased. This is
  2996. # to cover the case where the user may have called "git fetch origin",
  2997. # moving the origin branch to a newer commit, but hasn't rebased yet.
  2998. upstream_commit = None
  2999. cl = Changelist()
  3000. upstream_branch = cl.GetUpstreamBranch()
  3001. if upstream_branch:
  3002. upstream_commit = RunGit(['merge-base', 'HEAD', upstream_branch])
  3003. upstream_commit = upstream_commit.strip()
  3004. if not upstream_commit:
  3005. DieWithError('Could not find base commit for this branch. '
  3006. 'Are you in detached state?')
  3007. if opts.full:
  3008. # Only list the names of modified files.
  3009. diff_type = '--name-only'
  3010. else:
  3011. # Only generate context-less patches.
  3012. diff_type = '-U0'
  3013. diff_cmd = BuildGitDiffCmd(diff_type, upstream_commit, args, CLANG_EXTS)
  3014. diff_output = RunGit(diff_cmd)
  3015. top_dir = os.path.normpath(
  3016. RunGit(["rev-parse", "--show-toplevel"]).rstrip('\n'))
  3017. # Locate the clang-format binary in the checkout
  3018. try:
  3019. clang_format_tool = clang_format.FindClangFormatToolInChromiumTree()
  3020. except clang_format.NotFoundError, e:
  3021. DieWithError(e)
  3022. # Set to 2 to signal to CheckPatchFormatted() that this patch isn't
  3023. # formatted. This is used to block during the presubmit.
  3024. return_value = 0
  3025. if opts.full:
  3026. # diff_output is a list of files to send to clang-format.
  3027. files = diff_output.splitlines()
  3028. if files:
  3029. cmd = [clang_format_tool]
  3030. if not opts.dry_run and not opts.diff:
  3031. cmd.append('-i')
  3032. stdout = RunCommand(cmd + files, cwd=top_dir)
  3033. if opts.diff:
  3034. sys.stdout.write(stdout)
  3035. else:
  3036. env = os.environ.copy()
  3037. env['PATH'] = str(os.path.dirname(clang_format_tool))
  3038. # diff_output is a patch to send to clang-format-diff.py
  3039. try:
  3040. script = clang_format.FindClangFormatScriptInChromiumTree(
  3041. 'clang-format-diff.py')
  3042. except clang_format.NotFoundError, e:
  3043. DieWithError(e)
  3044. cmd = [sys.executable, script, '-p0']
  3045. if not opts.dry_run and not opts.diff:
  3046. cmd.append('-i')
  3047. stdout = RunCommand(cmd, stdin=diff_output, cwd=top_dir, env=env)
  3048. if opts.diff:
  3049. sys.stdout.write(stdout)
  3050. if opts.dry_run and len(stdout) > 0:
  3051. return_value = 2
  3052. # Similar code to above, but using yapf on .py files rather than clang-format
  3053. # on C/C++ files
  3054. if opts.python:
  3055. diff_cmd = BuildGitDiffCmd(diff_type, upstream_commit, args, ['.py'])
  3056. diff_output = RunGit(diff_cmd)
  3057. yapf_tool = gclient_utils.FindExecutable('yapf')
  3058. if yapf_tool is None:
  3059. DieWithError('yapf not found in PATH')
  3060. if opts.full:
  3061. files = diff_output.splitlines()
  3062. if files:
  3063. cmd = [yapf_tool]
  3064. if not opts.dry_run and not opts.diff:
  3065. cmd.append('-i')
  3066. stdout = RunCommand(cmd + files, cwd=top_dir)
  3067. if opts.diff:
  3068. sys.stdout.write(stdout)
  3069. else:
  3070. # TODO(sbc): yapf --lines mode still has some issues.
  3071. # https://github.com/google/yapf/issues/154
  3072. DieWithError('--python currently only works with --full')
  3073. # Build a diff command that only operates on dart files. dart's formatter
  3074. # does not have the nice property of only operating on modified chunks, so
  3075. # hard code full.
  3076. dart_diff_cmd = BuildGitDiffCmd('--name-only', upstream_commit,
  3077. args, ['.dart'])
  3078. dart_diff_output = RunGit(dart_diff_cmd)
  3079. if dart_diff_output:
  3080. try:
  3081. command = [dart_format.FindDartFmtToolInChromiumTree()]
  3082. if not opts.dry_run and not opts.diff:
  3083. command.append('-w')
  3084. command.extend(dart_diff_output.splitlines())
  3085. stdout = RunCommand(command, cwd=top_dir, env=env)
  3086. if opts.dry_run and stdout:
  3087. return_value = 2
  3088. except dart_format.NotFoundError as e:
  3089. print ('Unable to check dart code formatting. Dart SDK is not in ' +
  3090. 'this checkout.')
  3091. return return_value
  3092. @subcommand.usage('<codereview url or issue id>')
  3093. def CMDcheckout(parser, args):
  3094. """Checks out a branch associated with a given Rietveld issue."""
  3095. _, args = parser.parse_args(args)
  3096. if len(args) != 1:
  3097. parser.print_help()
  3098. return 1
  3099. target_issue = ParseIssueNum(args[0])
  3100. if target_issue == None:
  3101. parser.print_help()
  3102. return 1
  3103. key_and_issues = [x.split() for x in RunGit(
  3104. ['config', '--local', '--get-regexp', r'branch\..*\.rietveldissue'])
  3105. .splitlines()]
  3106. branches = []
  3107. for key, issue in key_and_issues:
  3108. if issue == target_issue:
  3109. branches.append(re.sub(r'branch\.(.*)\.rietveldissue', r'\1', key))
  3110. if len(branches) == 0:
  3111. print 'No branch found for issue %s.' % target_issue
  3112. return 1
  3113. if len(branches) == 1:
  3114. RunGit(['checkout', branches[0]])
  3115. else:
  3116. print 'Multiple branches match issue %s:' % target_issue
  3117. for i in range(len(branches)):
  3118. print '%d: %s' % (i, branches[i])
  3119. which = raw_input('Choose by index: ')
  3120. try:
  3121. RunGit(['checkout', branches[int(which)]])
  3122. except (IndexError, ValueError):
  3123. print 'Invalid selection, not checking out any branch.'
  3124. return 1
  3125. return 0
  3126. def CMDlol(parser, args):
  3127. # This command is intentionally undocumented.
  3128. print zlib.decompress(base64.b64decode(
  3129. 'eNptkLEOwyAMRHe+wupCIqW57v0Vq84WqWtXyrcXnCBsmgMJ+/SSAxMZgRB6NzE'
  3130. 'E2ObgCKJooYdu4uAQVffUEoE1sRQLxAcqzd7uK2gmStrll1ucV3uZyaY5sXyDd9'
  3131. 'JAnN+lAXsOMJ90GANAi43mq5/VeeacylKVgi8o6F1SC63FxnagHfJUTfUYdCR/W'
  3132. 'Ofe+0dHL7PicpytKP750Fh1q2qnLVof4w8OZWNY'))
  3133. return 0
  3134. class OptionParser(optparse.OptionParser):
  3135. """Creates the option parse and add --verbose support."""
  3136. def __init__(self, *args, **kwargs):
  3137. optparse.OptionParser.__init__(
  3138. self, *args, prog='git cl', version=__version__, **kwargs)
  3139. self.add_option(
  3140. '-v', '--verbose', action='count', default=0,
  3141. help='Use 2 times for more debugging info')
  3142. def parse_args(self, args=None, values=None):
  3143. options, args = optparse.OptionParser.parse_args(self, args, values)
  3144. levels = [logging.WARNING, logging.INFO, logging.DEBUG]
  3145. logging.basicConfig(level=levels[min(options.verbose, len(levels) - 1)])
  3146. return options, args
  3147. def main(argv):
  3148. if sys.hexversion < 0x02060000:
  3149. print >> sys.stderr, (
  3150. '\nYour python version %s is unsupported, please upgrade.\n' %
  3151. sys.version.split(' ', 1)[0])
  3152. return 2
  3153. # Reload settings.
  3154. global settings
  3155. settings = Settings()
  3156. colorize_CMDstatus_doc()
  3157. dispatcher = subcommand.CommandDispatcher(__name__)
  3158. try:
  3159. return dispatcher.execute(OptionParser(), argv)
  3160. except auth.AuthenticationError as e:
  3161. DieWithError(str(e))
  3162. except urllib2.HTTPError, e:
  3163. if e.code != 500:
  3164. raise
  3165. DieWithError(
  3166. ('AppEngine is misbehaving and returned HTTP %d, again. Keep faith '
  3167. 'and retry or visit go/isgaeup.\n%s') % (e.code, str(e)))
  3168. return 0
  3169. if __name__ == '__main__':
  3170. # These affect sys.stdout so do it outside of main() to simplify mocks in
  3171. # unit testing.
  3172. fix_encoding.fix_encoding()
  3173. colorama.init()
  3174. try:
  3175. sys.exit(main(sys.argv[1:]))
  3176. except KeyboardInterrupt:
  3177. sys.stderr.write('interrupted\n')
  3178. sys.exit(1)