git_cl.py 131 KB

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