git_cl.py 90 KB

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