git_cl.py 92 KB

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