git_cl.py 134 KB

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