git_cl.py 90 KB

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