git-cl.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. #!/usr/bin/python
  2. # git-cl -- a git-command for integrating reviews on Rietveld
  3. # Copyright (C) 2008 Evan Martin <martine@danga.com>
  4. import getpass
  5. import optparse
  6. import os
  7. import re
  8. import readline
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import textwrap
  13. import upload
  14. import urllib2
  15. DEFAULT_SERVER = 'codereview.appspot.com'
  16. def DieWithError(message):
  17. print >>sys.stderr, message
  18. sys.exit(1)
  19. def RunGit(args, error_ok=False, error_message=None, exit_code=False):
  20. cmd = ['git'] + args
  21. # Useful for debugging:
  22. # print >>sys.stderr, ' '.join(cmd)
  23. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  24. output = proc.communicate()[0]
  25. if exit_code:
  26. return proc.returncode
  27. if not error_ok and proc.returncode != 0:
  28. DieWithError('Command "%s" failed.\n' % (' '.join(cmd)) +
  29. (error_message or output))
  30. return output
  31. class Settings:
  32. def __init__(self):
  33. self.server = None
  34. self.cc = None
  35. self.is_git_svn = None
  36. self.svn_branch = None
  37. self.tree_status_url = None
  38. self.viewvc_url = None
  39. def GetServer(self, error_ok=False):
  40. if not self.server:
  41. if not error_ok:
  42. error_message = ('You must configure your review setup by running '
  43. '"git cl config".')
  44. self.server = self._GetConfig('rietveld.server',
  45. error_message=error_message)
  46. else:
  47. self.server = self._GetConfig('rietveld.server', error_ok=True)
  48. return self.server
  49. def GetCCList(self):
  50. if self.cc is None:
  51. self.cc = self._GetConfig('rietveld.cc', error_ok=True)
  52. return self.cc
  53. def GetIsGitSvn(self):
  54. """Return true if this repo looks like it's using git-svn."""
  55. if self.is_git_svn is None:
  56. # If you have any "svn-remote.*" config keys, we think you're using svn.
  57. self.is_git_svn = RunGit(['config', '--get-regexp', r'^svn-remote\.'],
  58. exit_code=True) == 0
  59. return self.is_git_svn
  60. def GetSVNBranch(self):
  61. if self.svn_branch is None:
  62. if not self.GetIsGitSvn():
  63. raise "Repo doesn't appear to be a git-svn repo."
  64. # Try to figure out which remote branch we're based on.
  65. # Strategy:
  66. # 1) find all git-svn branches and note their svn URLs.
  67. # 2) iterate through our branch history and match up the URLs.
  68. # regexp matching the git-svn line that contains the URL.
  69. git_svn_re = re.compile(r'^\s*git-svn-id: (\S+)@', re.MULTILINE)
  70. # Get the refname and svn url for all refs/remotes/*.
  71. remotes = RunGit(['for-each-ref', '--format=%(refname)',
  72. 'refs/remotes']).splitlines()
  73. svn_refs = {}
  74. for ref in remotes:
  75. # git-svn remote refs are generally directly in the refs/remotes/dir,
  76. # not a subdirectory (like refs/remotes/origin/master).
  77. if '/' in ref[len('refs/remotes/'):]:
  78. continue
  79. match = git_svn_re.search(RunGit(['cat-file', '-p', ref]))
  80. if match:
  81. svn_refs[match.group(1)] = ref
  82. if len(svn_refs) == 1:
  83. # Only one svn branch exists -- seems like a good candidate.
  84. self.svn_branch = svn_refs.values()[0]
  85. elif len(svn_refs) > 1:
  86. # We have more than one remote branch available. We don't
  87. # want to go through all of history, so read a line from the
  88. # pipe at a time.
  89. # The -100 is an arbitrary limit so we don't search forever.
  90. cmd = ['git', 'log', '-100']
  91. proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  92. for line in proc.stdout:
  93. match = git_svn_re.match(line)
  94. if match:
  95. url = match.group(1)
  96. if url in svn_refs:
  97. self.svn_branch = svn_refs[url]
  98. proc.stdout.close() # Cut pipe.
  99. break
  100. if not self.svn_branch:
  101. raise "Can't guess svn branch -- try specifying it on the command line"
  102. return self.svn_branch
  103. def GetTreeStatusUrl(self, error_ok=False):
  104. if not self.tree_status_url:
  105. error_message = ('You must configure your tree status URL by running '
  106. '"git cl config".')
  107. self.tree_status_url = self._GetConfig('rietveld.tree-status-url',
  108. error_ok=error_ok,
  109. error_message=error_message)
  110. return self.tree_status_url
  111. def GetViewVCUrl(self):
  112. if not self.viewvc_url:
  113. self.viewvc_url = self._GetConfig('rietveld.viewvc-url', error_ok=True)
  114. return self.viewvc_url
  115. def _GetConfig(self, param, **kwargs):
  116. return RunGit(['config', param], **kwargs).strip()
  117. settings = Settings()
  118. did_migrate_check = False
  119. def CheckForMigration():
  120. """Migrate from the old issue format, if found.
  121. We used to store the branch<->issue mapping in a file in .git, but it's
  122. better to store it in the .git/config, since deleting a branch deletes that
  123. branch's entry there.
  124. """
  125. # Don't run more than once.
  126. global did_migrate_check
  127. if did_migrate_check:
  128. return
  129. gitdir = RunGit(['rev-parse', '--git-dir']).strip()
  130. storepath = os.path.join(gitdir, 'cl-mapping')
  131. if os.path.exists(storepath):
  132. print "old-style git-cl mapping file (%s) found; migrating." % storepath
  133. store = open(storepath, 'r')
  134. for line in store:
  135. branch, issue = line.strip().split()
  136. RunGit(['config', 'branch.%s.rietveldissue' % ShortBranchName(branch),
  137. issue])
  138. store.close()
  139. os.remove(storepath)
  140. did_migrate_check = True
  141. def IssueURL(issue):
  142. """Get the URL for a particular issue."""
  143. return 'http://%s/%s' % (settings.GetServer(), issue)
  144. def ShortBranchName(branch):
  145. """Convert a name like 'refs/heads/foo' to just 'foo'."""
  146. return branch.replace('refs/heads/', '')
  147. class Changelist:
  148. def __init__(self, branchref=None):
  149. # Poke settings so we get the "configure your server" message if necessary.
  150. settings.GetServer()
  151. self.branchref = branchref
  152. if self.branchref:
  153. self.branch = ShortBranchName(self.branchref)
  154. else:
  155. self.branch = None
  156. self.upstream_branch = None
  157. self.has_issue = False
  158. self.issue = None
  159. self.has_description = False
  160. self.description = None
  161. def GetBranch(self):
  162. """Returns the short branch name, e.g. 'master'."""
  163. if not self.branch:
  164. self.branchref = RunGit(['symbolic-ref', 'HEAD']).strip()
  165. self.branch = ShortBranchName(self.branchref)
  166. return self.branch
  167. def GetBranchRef(self):
  168. """Returns the full branch name, e.g. 'refs/heads/master'."""
  169. self.GetBranch() # Poke the lazy loader.
  170. return self.branchref
  171. def GetUpstreamBranch(self):
  172. if self.upstream_branch is None:
  173. branch = self.GetBranch()
  174. upstream_branch = RunGit(['config', 'branch.%s.merge' % branch],
  175. error_ok=True).strip()
  176. if upstream_branch:
  177. remote = RunGit(['config', 'branch.%s.remote' % branch]).strip()
  178. # We have remote=origin and branch=refs/heads/foobar; convert to
  179. # refs/remotes/origin/foobar.
  180. self.upstream_branch = upstream_branch.replace('heads',
  181. 'remotes/' + remote)
  182. if not self.upstream_branch:
  183. # Fall back on trying a git-svn upstream branch.
  184. if settings.GetIsGitSvn():
  185. self.upstream_branch = settings.GetSVNBranch()
  186. if not self.upstream_branch:
  187. DieWithError("""Unable to determine default branch to diff against.
  188. Either pass complete "git diff"-style arguments, like
  189. git cl upload origin/master
  190. or verify this branch is set up to track another (via the --track argument to
  191. "git checkout -b ...").""")
  192. return self.upstream_branch
  193. def GetIssue(self):
  194. if not self.has_issue:
  195. CheckForMigration()
  196. issue = RunGit(['config', self._IssueSetting()], error_ok=True).strip()
  197. if issue:
  198. self.issue = issue
  199. else:
  200. self.issue = None
  201. self.has_issue = True
  202. return self.issue
  203. def GetIssueURL(self):
  204. return IssueURL(self.GetIssue())
  205. def GetDescription(self, pretty=False):
  206. if not self.has_description:
  207. if self.GetIssue():
  208. url = self.GetIssueURL() + '/description'
  209. self.description = urllib2.urlopen(url).read().strip()
  210. self.has_description = True
  211. if pretty:
  212. wrapper = textwrap.TextWrapper()
  213. wrapper.initial_indent = wrapper.subsequent_indent = ' '
  214. return wrapper.fill(self.description)
  215. return self.description
  216. def GetPatchset(self):
  217. if not self.has_patchset:
  218. patchset = RunGit(['config', self._PatchsetSetting()],
  219. error_ok=True).strip()
  220. if patchset:
  221. self.patchset = patchset
  222. else:
  223. self.patchset = None
  224. self.has_patchset = True
  225. return self.patchset
  226. def SetPatchset(self, patchset):
  227. """Set this branch's patchset. If patchset=0, clears the patchset."""
  228. if patchset:
  229. RunGit(['config', self._PatchsetSetting(), str(patchset)])
  230. else:
  231. RunGit(['config', '--unset', self._PatchsetSetting()])
  232. self.has_patchset = False
  233. def SetIssue(self, issue):
  234. """Set this branch's issue. If issue=0, clears the issue."""
  235. if issue:
  236. RunGit(['config', self._IssueSetting(), str(issue)])
  237. else:
  238. RunGit(['config', '--unset', self._IssueSetting()])
  239. self.SetPatchset(0)
  240. self.has_issue = False
  241. def CloseIssue(self):
  242. def GetUserCredentials():
  243. email = raw_input('Email: ').strip()
  244. password = getpass.getpass('Password for %s: ' % email)
  245. return email, password
  246. rpc_server = upload.HttpRpcServer(settings.GetServer(),
  247. GetUserCredentials,
  248. host_override=settings.GetServer(),
  249. save_cookies=True)
  250. # You cannot close an issue with a GET.
  251. # We pass an empty string for the data so it is a POST rather than a GET.
  252. data = [("description", self.description),]
  253. ctype, body = upload.EncodeMultipartFormData(data, [])
  254. rpc_server.Send('/' + self.GetIssue() + '/close', body, ctype)
  255. def _IssueSetting(self):
  256. """Return the git setting that stores this change's issue."""
  257. return 'branch.%s.rietveldissue' % self.GetBranch()
  258. def _PatchsetSetting(self):
  259. """Return the git setting that stores this change's most recent patchset."""
  260. return 'branch.%s.rietveldpatchset' % self.GetBranch()
  261. def CmdConfig(args):
  262. server = settings.GetServer(error_ok=True)
  263. prompt = 'Rietveld server (host[:port])'
  264. prompt += ' [%s]' % (server or DEFAULT_SERVER)
  265. newserver = raw_input(prompt + ': ')
  266. if not server and not newserver:
  267. newserver = DEFAULT_SERVER
  268. if newserver and newserver != server:
  269. RunGit(['config', 'rietveld.server', newserver])
  270. def SetProperty(initial, caption, name):
  271. prompt = caption
  272. if initial:
  273. prompt += ' ("x" to clear) [%s]' % initial
  274. new_val = raw_input(prompt + ': ')
  275. if new_val == 'x':
  276. RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True)
  277. elif new_val and new_val != initial:
  278. RunGit(['config', 'rietveld.' + name, new_val])
  279. SetProperty(settings.GetCCList(), 'CC list', 'cc')
  280. SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL',
  281. 'tree-status-url')
  282. SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url')
  283. # TODO: configure a default branch to diff against, rather than this
  284. # svn-based hackery.
  285. def CmdStatus(args):
  286. branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
  287. if branches:
  288. print 'Branches associated with reviews:'
  289. for branch in sorted(branches.splitlines()):
  290. cl = Changelist(branchref=branch)
  291. print " %10s: %s" % (cl.GetBranch(), cl.GetIssue())
  292. cl = Changelist()
  293. print
  294. print 'Current branch:',
  295. if not cl.GetIssue():
  296. print 'no issue assigned.'
  297. return 0
  298. print cl.GetBranch()
  299. print 'Issue number:', cl.GetIssue(), '(%s)' % cl.GetIssueURL()
  300. print 'Issue description:'
  301. print cl.GetDescription(pretty=True)
  302. def CmdIssue(args):
  303. cl = Changelist()
  304. if len(args) > 0:
  305. cl.SetIssue(int(args[0]))
  306. print 'Issue number:', cl.GetIssue(), '(%s)' % cl.GetIssueURL()
  307. def UserEditedLog(starting_text):
  308. """Given some starting text, let the user edit it and return the result."""
  309. editor = os.getenv('EDITOR', 'vi')
  310. file = tempfile.NamedTemporaryFile()
  311. filename = file.name
  312. file.write(starting_text)
  313. file.flush()
  314. ret = subprocess.call(editor + ' ' + filename, shell=True)
  315. if ret != 0:
  316. return
  317. text = open(filename).read()
  318. file.close()
  319. stripcomment_re = re.compile(r'^#.*$', re.MULTILINE)
  320. return stripcomment_re.sub('', text).strip()
  321. def CmdUpload(args):
  322. parser = optparse.OptionParser(
  323. usage='git cl upload [options] [args to "git diff"]')
  324. parser.add_option('-m', dest='message', help='message for patch')
  325. parser.add_option('-r', '--reviewers',
  326. help='reviewer email addresses')
  327. parser.add_option('--send-mail', action='store_true',
  328. help='send email to reviewer immediately')
  329. (options, args) = parser.parse_args(args)
  330. cl = Changelist()
  331. if not args:
  332. # Default to diffing against the "upstream" branch.
  333. args = [cl.GetUpstreamBranch()]
  334. # --no-ext-diff is broken in some versions of Git, so try to work around
  335. # this by overriding the environment (but there is still a problem if the
  336. # git config key "diff.external" is used).
  337. env = os.environ.copy()
  338. if 'GIT_EXTERNAL_DIFF' in env: del env['GIT_EXTERNAL_DIFF']
  339. subprocess.call(['git', 'diff', '--no-ext-diff', '--stat', ] + args, env=env)
  340. upload_args = ['--assume_yes'] # Don't ask about untracked files.
  341. upload_args.extend(['--server', settings.GetServer()])
  342. if options.reviewers:
  343. upload_args.extend(['--reviewers', options.reviewers])
  344. upload_args.extend(['--cc', settings.GetCCList()])
  345. if options.message:
  346. upload_args.extend(['--message', options.message])
  347. if options.send_mail:
  348. if not options.reviewers:
  349. DieWithError("Must specify reviewers to send email.")
  350. upload_args.append('--send_mail')
  351. if cl.GetIssue():
  352. upload_args.extend(['--issue', cl.GetIssue()])
  353. print ("This branch is associated with issue %s. "
  354. "Adding patch to that issue." % cl.GetIssue())
  355. else:
  356. # Construct a description for this change from the log.
  357. # We need to convert diff options to log options.
  358. log_args = []
  359. if len(args) == 1 and not args[0].endswith('.'):
  360. log_args = [args[0] + '..']
  361. elif len(args) == 2:
  362. log_args = [args[0] + '..' + args[1]]
  363. else:
  364. log_args = args[:] # Hope for the best!
  365. desc = RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args)
  366. initial_text = """# Enter a description of the change.
  367. # This will displayed on the codereview site.
  368. # The first line will also be used as the subject of the review."""
  369. desc = UserEditedLog(initial_text + '\n' + desc)
  370. if not desc:
  371. print "Description empty; aborting."
  372. return 1
  373. subject = desc.splitlines()[0]
  374. upload_args.extend(['--message', subject])
  375. upload_args.extend(['--description', desc])
  376. issue, patchset = upload.RealMain(['upload'] + upload_args + args)
  377. if not cl.GetIssue():
  378. cl.SetIssue(issue)
  379. cl.SetPatchset(patchset)
  380. def CmdDCommit(args):
  381. parser = optparse.OptionParser(
  382. usage='git cl dcommit [options] [git-svn branch to apply against]')
  383. parser.add_option('-f', action='store_true', dest='force',
  384. help="force yes to questions (don't prompt)")
  385. parser.add_option('-c', dest='contributor',
  386. help="external contributor for patch (appended to " +
  387. "description)")
  388. (options, args) = parser.parse_args(args)
  389. cl = Changelist()
  390. if not args:
  391. # Default to merging against our best guess of the upstream branch.
  392. args = [cl.GetUpstreamBranch()]
  393. base_branch = args[0]
  394. # It is important to have these checks at the top. Not only for user
  395. # convenience, but also because the cl object then caches the correct values
  396. # of these fields even as we're juggling branches for setting up the commit.
  397. if not cl.GetIssue():
  398. print 'Current issue unknown -- has this branch been uploaded?'
  399. return 1
  400. if not cl.GetDescription():
  401. print 'No description set.'
  402. print 'Visit %s/edit to set it.' % (cl.GetIssueURL())
  403. return 1
  404. if RunGit(['diff-index', 'HEAD']):
  405. print 'Cannot dcommit with a dirty tree. You must commit locally first.'
  406. return 1
  407. # This rev-list syntax means "show all commits not in my branch that
  408. # are in base_branch".
  409. upstream_commits = RunGit(['rev-list', '^' + cl.GetBranchRef(),
  410. base_branch]).splitlines()
  411. if upstream_commits:
  412. print ('Base branch "%s" has %d commits '
  413. 'not in this branch.' % (base_branch, len(upstream_commits)))
  414. print 'Run "git merge %s" before attempting to dcommit.' % base_branch
  415. return 1
  416. if not options.force:
  417. # Check the tree status if the tree status URL is set.
  418. status = GetTreeStatus()
  419. if 'closed' == status:
  420. print ('The tree is closed. Please wait for it to reopen. Use '
  421. '"git cl dcommit -f" to commit on a closed tree.')
  422. return 1
  423. elif 'unknown' == status:
  424. print ('Unable to determine tree status. Please verify manually and '
  425. 'use "git cl dcommit -f" to commit on a closed tree.')
  426. description = cl.GetDescription()
  427. description += "\n\nReview URL: %s" % cl.GetIssueURL()
  428. if options.contributor:
  429. description += "\nPatch from %s." % options.contributor
  430. print 'Description:', repr(description)
  431. branches = [base_branch, cl.GetBranchRef()]
  432. if not options.force:
  433. subprocess.call(['git', 'diff', '--stat'] + branches)
  434. raw_input("About to commit; enter to confirm.")
  435. # We want to squash all this branch's commits into one commit with the
  436. # proper description.
  437. # We do this by doing a "merge --squash" into a new commit branch, then
  438. # dcommitting that.
  439. MERGE_BRANCH = 'git-cl-commit'
  440. # Delete the merge branch if it already exists.
  441. if RunGit(['show-ref', '--quiet', '--verify', 'refs/heads/' + MERGE_BRANCH],
  442. exit_code=True) == 0:
  443. RunGit(['branch', '-D', MERGE_BRANCH])
  444. # Stuff our change into the merge branch.
  445. RunGit(['checkout', '-q', '-b', MERGE_BRANCH, base_branch])
  446. RunGit(['merge', '--squash', cl.GetBranchRef()])
  447. RunGit(['commit', '-m', description])
  448. # dcommit the merge branch.
  449. output = RunGit(['svn', 'dcommit'])
  450. # And then swap back to the original branch and clean up.
  451. RunGit(['checkout', '-q', cl.GetBranch()])
  452. RunGit(['branch', '-D', MERGE_BRANCH])
  453. if output.find("Committed r") != -1:
  454. print "Closing issue (you may be prompted for your codereview password)..."
  455. if cl.has_issue:
  456. viewvc_url = settings.GetViewVCUrl()
  457. if viewvc_url:
  458. revision = re.compile(".*?\nCommitted r(\d+)",
  459. re.DOTALL).match(output).group(1)
  460. cl.description = (cl.description +
  461. "\n\nCommitted: " + viewvc_url + revision)
  462. cl.CloseIssue()
  463. cl.SetIssue(0)
  464. def CmdPatch(args):
  465. parser = optparse.OptionParser(usage=('git cl patch [options] '
  466. '<patch url or issue id>'))
  467. parser.add_option('-b', dest='newbranch',
  468. help='create a new branch off trunk for the patch')
  469. parser.add_option('-f', action='store_true', dest='force',
  470. help='with -b, clobber any existing branch')
  471. parser.add_option('--reject', action='store_true', dest='reject',
  472. help='allow failed patches and spew .rej files')
  473. parser.add_option('-n', '--no-commit', action='store_true', dest='nocommit',
  474. help="don't commit after patch applies")
  475. (options, args) = parser.parse_args(args)
  476. if len(args) != 1:
  477. return parser.print_help()
  478. input = args[0]
  479. if re.match(r'\d+', input):
  480. # Input is an issue id. Figure out the URL.
  481. issue = input
  482. fetch = "curl --silent http://%s/%s" % (settings.GetServer(), issue)
  483. grep = "grep -E -o '/download/issue[0-9]+_[0-9]+.diff'"
  484. pipe = subprocess.Popen("%s | %s" % (fetch, grep), shell=True,
  485. stdout=subprocess.PIPE)
  486. path = pipe.stdout.read().strip()
  487. url = 'http://%s%s' % (settings.GetServer(), path)
  488. else:
  489. # Assume it's a URL to the patch.
  490. match = re.match(r'http://.*?/issue(\d+)_\d+.diff', input)
  491. if match:
  492. issue = match.group(1)
  493. url = input
  494. else:
  495. print "Must pass an issue ID or full URL for 'Download raw patch set'"
  496. return 1
  497. if options.newbranch:
  498. if options.force:
  499. RunGit(['branch', '-D', options.newbranch], error_ok=True)
  500. RunGit(['checkout', '-b', options.newbranch])
  501. # Switch up to the top-level directory, if necessary, in preparation for
  502. # applying the patch.
  503. top = RunGit(['rev-parse', '--show-cdup']).strip()
  504. if top:
  505. os.chdir(top)
  506. # Construct a pipeline to feed the patch into "git apply".
  507. # We use "git apply" to apply the patch instead of "patch" so that we can
  508. # pick up file adds.
  509. # 1) Fetch the patch.
  510. fetch = "curl --silent %s" % url
  511. # 2) Munge the patch.
  512. # Git patches have a/ at the beginning of source paths. We strip that out
  513. # with a sed script rather than the -p flag to patch so we can feed either
  514. # Git or svn-style patches into the same apply command.
  515. gitsed = "sed -e 's|^--- a/|--- |; s|^+++ b/|+++ |'"
  516. # 3) Apply the patch.
  517. # The --index flag means: also insert into the index (so we catch adds).
  518. apply = "git apply --index -p0"
  519. if options.reject:
  520. apply += " --reject"
  521. subprocess.check_call(' | '.join([fetch, gitsed, apply]), shell=True)
  522. # If we had an issue, commit the current state and register the issue.
  523. if not options.nocommit:
  524. RunGit(['commit', '-m', 'patch from issue %s' % issue])
  525. cl = Changelist()
  526. cl.SetIssue(issue)
  527. print "Committed patch."
  528. else:
  529. print "Patch applied to index."
  530. def CmdRebase(args):
  531. # Provide a wrapper for git svn rebase to help avoid accidental
  532. # git svn dcommit.
  533. RunGit(['svn', 'rebase'])
  534. def GetTreeStatus():
  535. """Fetches the tree status and returns either 'open', 'closed',
  536. 'unknown' or 'unset'."""
  537. url = settings.GetTreeStatusUrl(error_ok=True)
  538. if url:
  539. status = urllib2.urlopen(url).read().lower()
  540. if status.find('closed') != -1:
  541. return 'closed'
  542. elif status.find('open') != -1:
  543. return 'open'
  544. return 'unknown'
  545. return 'unset'
  546. def CmdTreeStatus(args):
  547. status = GetTreeStatus()
  548. if 'unset' == status:
  549. print 'You must configure your tree status URL by running "git cl config".'
  550. else:
  551. print "The tree is %s" % status
  552. def CmdUpstream(args):
  553. cl = Changelist()
  554. print cl.GetUpstreamBranch()
  555. COMMANDS = [
  556. ('config', 'edit configuration for this tree', CmdConfig),
  557. ('status', 'show status of changelists', CmdStatus),
  558. ('issue', 'show/set current branch\'s issue number', CmdIssue),
  559. ('upload', 'upload the current changelist to codereview', CmdUpload),
  560. ('dcommit', 'commit the current changelist via git-svn', CmdDCommit),
  561. ('patch', 'patch in a code review', CmdPatch),
  562. ('rebase', 'rebase current branch on top of svn repo', CmdRebase),
  563. ('tree', 'show the status of the tree', CmdTreeStatus),
  564. ('upstream', 'print the name of the upstream branch, if any', CmdUpstream),
  565. ]
  566. def Usage(name):
  567. print 'usage: %s <command>' % name
  568. print 'commands are:'
  569. for name, desc, _ in COMMANDS:
  570. print ' %-10s %s' % (name, desc)
  571. sys.exit(1)
  572. def main(argv):
  573. if len(argv) < 2:
  574. Usage(argv[0])
  575. command = argv[1]
  576. for name, _, func in COMMANDS:
  577. if name == command:
  578. return func(argv[2:])
  579. print 'unknown command: %s' % command
  580. Usage(argv[0])
  581. if __name__ == '__main__':
  582. sys.exit(main(sys.argv))