git_cl.py 111 KB

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