Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

moving through the commands and changing styles

  • Loading branch information...
commit 8e0663f6e529b2072a8b0e9183897bcbcb6beff9 1 parent 309ff42
Andy Smith authored
Showing with 321 additions and 430 deletions.
  1. +27 −0 LICENSE
  2. +294 −430 git-lp
27 LICENSE
View
@@ -0,0 +1,27 @@
+Copyright (c) 2008 Evan Martin <martine@danga.com>
+Copyright (c) 2010 Andy Smith <andy@term.ie>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+* Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+* Neither the name of the author nor the names of contributors may be
+ used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
724 git-lp
View
@@ -1,6 +1,7 @@
#!/usr/bin/python
# git-cl -- a git-command for integrating reviews on Rietveld
# Copyright (C) 2008 Evan Martin <martine@danga.com>
+# Copyright (C) 2010 Andy Smith <andy@term.ie>
import getpass
import optparse
@@ -12,7 +13,6 @@ import subprocess
import sys
import tempfile
import textwrap
-import upload
import urllib2
try:
@@ -20,441 +20,307 @@ try:
except ImportError:
pass
-DEFAULT_SERVER = 'codereview.appspot.com'
-PREDCOMMIT_HOOK = '.git/hooks/pre-cl-dcommit'
-PREUPLOAD_HOOK = '.git/hooks/pre-cl-upload'
-def DieWithError(message):
- print >>sys.stderr, message
+NAMESPACE = 'bzr'
+MAIN_BRANCH = 'trunk'
+
+def die(message, *args):
+ print >>sys.stderr, message % args
sys.exit(1)
-def RunCommand(cmd, error_ok=False, error_message=None, exit_code=False,
- redirect_stdout=True):
+def run_command(cmd, error_ok=False, error_message=None, exit_code=False,
+ redirect_stdout=True, return_proc=False, stdout=None,
+ stdin=None):
# Useful for debugging:
- # print >>sys.stderr, ' '.join(cmd)
- if redirect_stdout:
+ print >>sys.stderr, ' '.join(cmd)
+ #raw_input()
+ if redirect_stdout and stdout is None:
stdout = subprocess.PIPE
+
+ proc = subprocess.Popen(cmd, stdout=stdout, stdin=stdin)
+
+ if return_proc:
+ return proc
+
+ if stdout == subprocess.PIPE:
+ output = proc.communicate()[0]
else:
- stdout = None
- proc = subprocess.Popen(cmd, stdout=stdout)
- output = proc.communicate()[0]
+ output = ''
+ proc.wait()
+
if exit_code:
return proc.returncode
if not error_ok and proc.returncode != 0:
- DieWithError('Command "%s" failed.\n' % (' '.join(cmd)) +
+ die('Command "%s" failed.\n' % (' '.join(cmd)) +
(error_message or output))
return output
-def RunGit(args, **kwargs):
+def git(args, **kwargs):
cmd = ['git'] + args
- return RunCommand(cmd, **kwargs)
-
-
-class Settings(object):
- def __init__(self):
- self.server = None
- self.cc = None
- self.root = None
- self.is_git_svn = None
- self.svn_branch = None
- self.tree_status_url = None
- self.viewvc_url = None
-
- def VerifyGitSvnVersion(self):
- git_svn_version = string.strip(RunGit(['svn', '--version']))
- match = re.match(r'^git-svn version (\d+)\.(\d+)\.(\S*) \([^\)]+\)',
- git_svn_version)
- if not match:
- DieWithError('git-svn --version is broken, please check your git-svn '
- 'install.')
- if int(match.group(1)) == 1 and int(match.group(2)) < 6:
- DieWithError('git-svn version is "%s", please update to a version later '
- 'than 1.5.x' % match.group(0))
-
- def GetServer(self, error_ok=False):
- if not self.server:
- if not error_ok:
- error_message = ('You must configure your review setup by running '
- '"git cl config".')
- self.server = self._GetConfig('rietveld.server',
- error_message=error_message)
- else:
- self.server = self._GetConfig('rietveld.server', error_ok=True)
- return self.server
-
- def GetCCList(self):
- """Return the users cc'd on this CL.
-
- Return is a string suitable for passing to gcl with the --cc flag.
- """
- if self.cc is None:
- self.cc = self._GetConfig('rietveld.cc', error_ok=True)
- more_cc = self._GetConfig('rietveld.extra_cc', error_ok=True)
- self.cc = ','.join(x for x in (self.cc, more_cc) if x)
- return self.cc
-
- def GetRoot(self):
- if not self.root:
- self.root = os.path.abspath(RunGit(['rev-parse', '--show-cdup']).strip())
- return self.root
-
- def GetIsGitSvn(self):
- """Return true if this repo looks like it's using git-svn."""
- if self.is_git_svn is None:
- # If you have any "svn-remote.*" config keys, we think you're using svn.
- self.is_git_svn = RunGit(['config', '--get-regexp', r'^svn-remote\.'],
- exit_code=True) == 0
- if self.is_git_svn:
- self.VerifyGitSvnVersion()
- return self.is_git_svn
-
- def GetSVNBranch(self):
- if self.svn_branch is None:
- if not self.GetIsGitSvn():
- raise "Repo doesn't appear to be a git-svn repo."
-
- # Try to figure out which remote branch we're based on.
- # Strategy:
- # 1) find all git-svn branches and note their svn URLs.
- # 2) iterate through our branch history and match up the URLs.
-
- # regexp matching the git-svn line that contains the URL.
- git_svn_re = re.compile(r'^\s*git-svn-id: (\S+)@', re.MULTILINE)
-
- # Get the refname and svn url for all refs/remotes/*.
- remotes = RunGit(['for-each-ref', '--format=%(refname)',
- 'refs/remotes']).splitlines()
- svn_refs = {}
- for ref in remotes:
- match = git_svn_re.search(RunGit(['cat-file', '-p', ref]))
- if match:
- svn_refs[match.group(1)] = ref
-
- if len(svn_refs) == 1:
- # Only one svn branch exists -- seems like a good candidate.
- self.svn_branch = svn_refs.values()[0]
- elif len(svn_refs) > 1:
- # We have more than one remote branch available. We don't
- # want to go through all of history, so read a line from the
- # pipe at a time.
- # The -100 is an arbitrary limit so we don't search forever.
- cmd = ['git', 'log', '-100', '--pretty=medium']
- proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
- for line in proc.stdout:
- match = git_svn_re.match(line)
- if match:
- url = match.group(1)
- if url in svn_refs:
- self.svn_branch = svn_refs[url]
- proc.stdout.close() # Cut pipe.
- break
-
- if not self.svn_branch:
- raise "Can't guess svn branch -- try specifying it on the command line"
-
- return self.svn_branch
-
- def GetTreeStatusUrl(self, error_ok=False):
- if not self.tree_status_url:
- error_message = ('You must configure your tree status URL by running '
- '"git cl config".')
- self.tree_status_url = self._GetConfig('rietveld.tree-status-url',
- error_ok=error_ok,
- error_message=error_message)
- return self.tree_status_url
-
- def GetViewVCUrl(self):
- if not self.viewvc_url:
- self.viewvc_url = self._GetConfig('rietveld.viewvc-url', error_ok=True)
- return self.viewvc_url
-
- def _GetConfig(self, param, **kwargs):
- return RunGit(['config', param], **kwargs).strip()
-
-
-settings = Settings()
-
-
-did_migrate_check = False
-def CheckForMigration():
- """Migrate from the old issue format, if found.
-
- We used to store the branch<->issue mapping in a file in .git, but it's
- better to store it in the .git/config, since deleting a branch deletes that
- branch's entry there.
- """
-
- # Don't run more than once.
- global did_migrate_check
- if did_migrate_check:
- return
+ return run_command(cmd, **kwargs)
- gitdir = RunGit(['rev-parse', '--git-dir']).strip()
- storepath = os.path.join(gitdir, 'cl-mapping')
- if os.path.exists(storepath):
- print "old-style git-cl mapping file (%s) found; migrating." % storepath
- store = open(storepath, 'r')
- for line in store:
- branch, issue = line.strip().split()
- RunGit(['config', 'branch.%s.rietveldissue' % ShortBranchName(branch),
- issue])
- store.close()
- os.remove(storepath)
- did_migrate_check = True
+def bzr(args, **kwargs):
+ cmd = ['bzr'] + args
+ return run_command(cmd, **kwargs)
-def IssueURL(issue):
- """Get the URL for a particular issue."""
- return 'http://%s/%s' % (settings.GetServer(), issue)
-
-def ShortBranchName(branch):
+def short_branch_name(branch):
"""Convert a name like 'refs/heads/foo' to just 'foo'."""
return branch.replace('refs/heads/', '')
+def set_cfg(key, value):
+ git(['config', '%s.%s' % (NAMESPACE, key), value])
+
+
+def get_cfg(key, **kwargs):
+ return git(['config', '%s.%s' % (NAMESPACE, key)]).strip()
+
+
class Changelist(object):
def __init__(self, branchref=None):
- # Poke settings so we get the "configure your server" message if necessary.
- settings.GetServer()
- self.branchref = branchref
- if self.branchref:
- self.branch = ShortBranchName(self.branchref)
+ self._branchref = branchref
+ if self._branchref:
+ self._branch = short_branch_name(self._branchref)
else:
- self.branch = None
- self.upstream_branch = None
- self.has_issue = False
- self.issue = None
- self.has_description = False
- self.description = None
-
- def GetBranch(self):
+ self._branch = None
+ self._git_dir = None
+ self._root_dir = None
+ self._bzr_dir = None
+ self._map_dir = None
+
+ def branch(self):
"""Returns the short branch name, e.g. 'master'."""
- if not self.branch:
- self.branchref = RunGit(['symbolic-ref', 'HEAD']).strip()
- self.branch = ShortBranchName(self.branchref)
- return self.branch
- def GetBranchRef(self):
+ if not self._branch:
+ self._branchref = git(['symbolic-ref', 'HEAD']).strip()
+ self._branch = short_branch_name(self._branchref)
+ return self._branch
+
+ def branch_ref(self):
"""Returns the full branch name, e.g. 'refs/heads/master'."""
- self.GetBranch() # Poke the lazy loader.
- return self.branchref
-
- def GetUpstreamTuple(self):
- """Returns a tuple containg remote and remote ref,
- e.g. 'origin', 'refs/heads/master'
- """
- branch = self.GetBranch()
- remote = RunGit(['config', 'branch.%s.remote' % branch]).strip()
- if not remote:
- # We aren't a tracking branch, assume origin
- remote = 'origin'
- branch = RunGit(['config', 'branch.%s.merge' % branch],
- error_ok=True).strip()
- if not branch:
- # We aren't a tracking branch, assume origin/master
- branch = 'master'
- return remote, branch
-
- def GetUpstreamBranch(self):
- if self.upstream_branch is None:
- branch = self.GetBranch()
- upstream_branch = RunGit(['config', 'branch.%s.merge' % branch],
- error_ok=True).strip()
- if upstream_branch:
- remote = RunGit(['config', 'branch.%s.remote' % branch]).strip()
- # We have remote=origin and branch=refs/heads/foobar; convert to
- # refs/remotes/origin/foobar.
- self.upstream_branch = upstream_branch.replace('heads',
- 'remotes/' + remote)
-
- if not self.upstream_branch:
- # Fall back on trying a git-svn upstream branch.
- if settings.GetIsGitSvn():
- self.upstream_branch = settings.GetSVNBranch()
-
- if not self.upstream_branch:
- DieWithError("""Unable to determine default branch to diff against.
-Either pass complete "git diff"-style arguments, like
- git cl upload origin/master
-or verify this branch is set up to track another (via the --track argument to
-"git checkout -b ...").""")
-
- return self.upstream_branch
-
- def GetIssue(self):
- if not self.has_issue:
- CheckForMigration()
- issue = RunGit(['config', self._IssueSetting()], error_ok=True).strip()
- if issue:
- self.issue = issue
- else:
- self.issue = None
- self.has_issue = True
- return self.issue
-
- def GetIssueURL(self):
- return IssueURL(self.GetIssue())
-
- def GetDescription(self, pretty=False):
- if not self.has_description:
- if self.GetIssue():
- url = self.GetIssueURL() + '/description'
- self.description = urllib2.urlopen(url).read().strip()
- self.has_description = True
- if pretty:
- wrapper = textwrap.TextWrapper()
- wrapper.initial_indent = wrapper.subsequent_indent = ' '
- return wrapper.fill(self.description)
- return self.description
-
- def GetPatchset(self):
- if not self.has_patchset:
- patchset = RunGit(['config', self._PatchsetSetting()],
- error_ok=True).strip()
- if patchset:
- self.patchset = patchset
- else:
- self.patchset = None
- self.has_patchset = True
- return self.patchset
-
- def SetPatchset(self, patchset):
- """Set this branch's patchset. If patchset=0, clears the patchset."""
- if patchset:
- RunGit(['config', self._PatchsetSetting(), str(patchset)])
- else:
- RunGit(['config', '--unset', self._PatchsetSetting()])
- self.has_patchset = False
+ self.branch() # Poke the lazy loader.
+ return self._branchref
+
+ def git_dir(self, path=None):
+ if not self._git_dir:
+ self._git_dir = os.path.abspath(git(['rev-parse', '--git-dir']).strip())
+ if path:
+ return os.path.join(self._git_dir, path)
+ return self._git_dir
+
+ def root_dir(self, path=None):
+ if not self._root_dir:
+ self._root_dir = os.path.dirname(self.git_dir())
+ if path:
+ return os.path.join(self._root_dir, path)
+ return self._root_dir
+
+ def bzr_dir(self, path=None):
+ if not self._bzr_dir:
+ self._bzr_dir = os.path.join(self.git_dir(), NAMESPACE, 'repo')
+ if path:
+ return os.path.join(self._bzr_dir, path)
+ return self._bzr_dir
+
+ def map_dir(self, path=None):
+ if not self._map_dir:
+ self._map_dir = os.path.join(self.git_dir(), NAMESPACE, 'map')
+ if path:
+ return os.path.join(self._map_dir, path)
+ return self._map_dir
+
+
+def export_bzr(branch, git_branch=None, cl=None):
+ if cl is None:
+ cl = Changelist()
+ if git_branch is None:
+ git_branch = '%s/%s' % (NAMESPACE, branch)
+
+ bzr_export = cl.map_dir('%s-bzr-export' % branch)
+ git_import = cl.map_dir('%s-git-import' % branch)
+
+ # TODO(termie): sanity checks
+ if os.path.exists(bzr_export):
+ bzr_export_arg = ['--import-marks=%s' % bzr_export]
+ git_import_arg = ['--import-marks=%s' % git_import]
+ else:
+ bzr_export_arg = git_import_arg = []
+
+ # NOTE(termie): this happens in reverse because we're piping
+ git_proc = git(['fast-import'] + git_import_arg + [
+ '--export-marks=%s' % git_import],
+ stdin=subprocess.PIPE,
+ return_proc=True)
+
+ bzr_proc = bzr(['fast-export'] + bzr_export_arg + [
+ '--export-marks=%s' % bzr_export,
+ '--git-branch=%s' % git_branch,
+ cl.bzr_dir(branch)],
+ stdout=git_proc.stdin,
+ return_proc=True)
+ bzr_proc.wait()
+ git_proc.stdin.close()
+ git_proc.wait()
+ return git_branch
+
+
+def cmd_clone(args):
+ parser = optparse.OptionParser(usage='git lp clone <url> <target>')
+ parser.description = ('Effectively a bzr branch lp_url'
+ ' but using fast-import')
+ (options, args) = parser.parse_args(args)
- def SetIssue(self, issue):
- """Set this branch's issue. If issue=0, clears the issue."""
- if issue:
- RunGit(['config', self._IssueSetting(), str(issue)])
- else:
- RunGit(['config', '--unset', self._IssueSetting()])
- self.SetPatchset(0)
- self.has_issue = False
-
- def CloseIssue(self):
- def GetUserCredentials():
- email = raw_input('Email: ').strip()
- password = getpass.getpass('Password for %s: ' % email)
- return email, password
-
- rpc_server = upload.HttpRpcServer(settings.GetServer(),
- GetUserCredentials,
- host_override=settings.GetServer(),
- save_cookies=True)
- # You cannot close an issue with a GET.
- # We pass an empty string for the data so it is a POST rather than a GET.
- data = [("description", self.description),]
- ctype, body = upload.EncodeMultipartFormData(data, [])
- rpc_server.Send('/' + self.GetIssue() + '/close', body, ctype)
-
- def _IssueSetting(self):
- """Return the git setting that stores this change's issue."""
- return 'branch.%s.rietveldissue' % self.GetBranch()
-
- def _PatchsetSetting(self):
- """Return the git setting that stores this change's most recent patchset."""
- return 'branch.%s.rietveldpatchset' % self.GetBranch()
-
-
-def GetCodereviewSettingsInteractively():
- """Prompt the user for settings."""
- server = settings.GetServer(error_ok=True)
- prompt = 'Rietveld server (host[:port])'
- prompt += ' [%s]' % (server or DEFAULT_SERVER)
- newserver = raw_input(prompt + ': ')
- if not server and not newserver:
- newserver = DEFAULT_SERVER
- if newserver and newserver != server:
- RunGit(['config', 'rietveld.server', newserver])
-
- def SetProperty(initial, caption, name):
- prompt = caption
- if initial:
- prompt += ' ("x" to clear) [%s]' % initial
- new_val = raw_input(prompt + ': ')
- if new_val == 'x':
- RunGit(['config', '--unset-all', 'rietveld.' + name], error_ok=True)
- elif new_val and new_val != initial:
- RunGit(['config', 'rietveld.' + name, new_val])
-
- SetProperty(settings.GetCCList(), 'CC list', 'cc')
- SetProperty(settings.GetTreeStatusUrl(error_ok=True), 'Tree status URL',
- 'tree-status-url')
- SetProperty(settings.GetViewVCUrl(), 'ViewVC URL', 'viewvc-url')
-
- # TODO: configure a default branch to diff against, rather than this
- # svn-based hackery.
-
-
-def LoadCodereviewSettingsFromFile(file):
- """Parse a codereview.settings file."""
- settings = {}
- for line in file.read().splitlines():
- if not line or line.startswith("#"):
- continue
- k, v = line.split(": ", 1)
- settings[k] = v
-
- def GetProperty(name):
- return settings.get(name)
-
- def SetProperty(name, setting, unset_error_ok=False):
- fullname = 'rietveld.' + name
- if setting in settings:
- RunGit(['config', fullname, settings[setting]])
- else:
- RunGit(['config', '--unset-all', fullname], error_ok=unset_error_ok)
-
- SetProperty('server', 'CODE_REVIEW_SERVER')
- # Only server setting is required. Other settings can be absent.
- # In that case, we ignore errors raised during option deletion attempt.
- SetProperty('cc', 'CC_LIST', unset_error_ok=True)
- SetProperty('tree-status-url', 'STATUS', unset_error_ok=True)
- SetProperty('viewvc-url', 'VIEW_VC', unset_error_ok=True)
- hooks = {}
- if GetProperty('GITCL_PREUPLOAD'):
- hooks['preupload'] = GetProperty('GITCL_PREUPLOAD')
- if GetProperty('GITCL_PREDCOMMIT'):
- hooks['predcommit'] = GetProperty('GITCL_PREDCOMMIT')
- return hooks
-
-
-def CmdConfig(args):
- def DownloadToFile(url, filename):
- filename = os.path.join(settings.GetRoot(), filename)
- if os.path.exists(filename):
- print '%s exists, skipping' % filename
- return False
- contents = urllib2.urlopen(url).read()
- file = open(filename, 'w')
- file.write(contents)
- file.close()
- os.chmod(filename, 0755)
- return True
+ # TODO(termie): command-line validation
+ url = args[0]
+ target = args[1]
- parser = optparse.OptionParser(
- usage='git cl config [repo root containing codereview.settings]')
+ # TODO(termie): sanity checking
+ if ':' not in url:
+ url = os.path.abspath(url)
+
+ target = os.path.abspath(target)
+ branch = os.path.basename(target)
+
+ if os.path.exists(target):
+ die('%s already exists', target)
+
+ git(['init', target])
+ os.chdir(target)
+
+ cl = Changelist()
+
+ # Ensure our directories exist
+ os.makedirs(cl.bzr_dir())
+ os.makedirs(cl.map_dir())
+
+ # Initialize a bzr repo
+ bzr(['init-repo', cl.bzr_dir()])
+
+ # Do the actual bzr fetch
+ bzr(['branch', url, cl.bzr_dir(branch)])
+
+ # Fast export from
+ bzr_ref = export_bzr(branch, cl=cl)
+
+ git(['checkout', '-b', branch, bzr_ref])
+ set_cfg('%s.bzr' % branch, bzr_ref)
+ set_cfg('%s.upstream' % bzr_ref, url)
+
+
+
+
+def PushBzrBranch(url, bzr_branch=None):
+ cl = Changelist()
+
+ #if bzr(['info', '-q', url], exit_code=True):
+ # die('Not a valid bzr url')
+
+ branch = cl.GetBranch()
+ if not bzr_branch:
+ bzr_branch = BzrUrlToBranchName(url)
+
+ # We have to make some fast-export stuff now
+ map_dir = GetMapDir()
+ bzr_dir = GetBzrDir()
+
+ trunk_bzr_branch = BzrUrlToBranchName(cl.GetTrunkUrl())
+
+ git_map = os.path.join(map_dir, '%s-git' % bzr_branch)
+ bzr_map = os.path.join(map_dir, '%s-bzr' % bzr_branch)
+ trunk_git_map = os.path.join(map_dir, '%s-git' % trunk_bzr_branch)
+ trunk_bzr_map = os.path.join(map_dir, '%s-bzr' % trunk_bzr_branch)
+ bzr_path = os.path.join(bzr_dir, bzr_branch)
+
+ if not os.path.exists(map_dir):
+ die('No Map Dir?')
+
+ if not os.path.exists(bzr_dir):
+ die('No Bzr Dir?')
+
+ if not os.path.exists(git_map) and not os.path.exists(bzr_map):
+ bzr(['branch', cl.GetTrunkUrl(), bzr_path])
+
+ proc = git(['fast-export',
+ '--export-marks=%s' % git_map,
+ '--import-marks=%s' % trunk_git_map,
+ branch],
+ return_proc=True)
+ os.chdir(bzr_path)
+ out = bzr(['fast-import',
+ '--export-marks=%s' % bzr_map,
+ '-'],
+ input=proc)
+ proc.wait()
+ elif os.path.exists(git_map) or os.path.exists(bzr_map):
+ print "Already seen it"
+ proc = git(['fast-export',
+ '--export-marks=%s' % git_map,
+ '--import-marks=%s' % trunk_git_map,
+ branch],
+ return_proc=True)
+ os.chdir(bzr_path)
+ out = bzr(['fast-import',
+ #'--import-marks=%s' % bzr_map,
+ '--export-marks=%s' % bzr_map,
+ '-'],
+ input=proc)
+ proc.wait()
+
+ bzr(['push', url])
+
+
+def CmdFetch(args):
+ # TODO(termie): check that we are in a git repo
+ parser = optparse.OptionParser(usage='git lp fetch <lp_url>')
+ parser.description = ('Effectively a bzr fetch lp_url'
+ ' but using fast-import')
(options, args) = parser.parse_args(args)
+
+ cl = Changelist()
+
if len(args) == 0:
- GetCodereviewSettingsInteractively()
- return
+ url = cl.GetUpstream()
+ elif len(args) == 1:
+ url = args[0]
+ # TEMPORARY FOR TESTING
+ #if not url.startswith('lp:'):
+ # url = 'lp:' + url
+ else:
+ die('Need a single lp_url')
+
+ if not url:
+ die('Need a fetch url')
+
+ FetchBzrBranch(url)
+
+ git(['fetch', bzr_branch])
+
+
+
+
+def CmdPush(args):
+ parser = optparse.OptionParser(usage='git lp push <lp_url>')
+ parser.description = ('Effectively a bzr push lp_url'
+ ' but using fast-import')
+ (options, args) = parser.parse_args(args)
+
+ cl = Changelist()
+
+ if len(args) == 0:
+ url = cl.GetUpstream()
+ elif len(args) == 1:
+ url = args[0]
+ else:
+ die('Need a single lp_url')
+
+ bzr_branch = BzrUrlToBranchName(url)
+
+ PushBzrBranch(url)
- url = args[0]
- if not url.endswith('codereview.settings'):
- url = os.path.join(url, 'codereview.settings')
- # Load Codereview settings and download hooks (if available).
- hooks = LoadCodereviewSettingsFromFile(urllib2.urlopen(url))
- for key, filename in (('predcommit', PREDCOMMIT_HOOK),
- ('preupload', PREUPLOAD_HOOK)):
- if key in hooks:
- DownloadToFile(hooks[key], filename)
def CmdStatus(args):
@@ -466,7 +332,7 @@ def CmdStatus(args):
show_branches = not options.field
if show_branches:
- branches = RunGit(['for-each-ref', '--format=%(refname)', 'refs/heads'])
+ branches = git(['for-each-ref', '--format=%(refname)', 'refs/heads'])
if branches:
print 'Branches associated with reviews:'
for branch in sorted(branches.splitlines()):
@@ -532,7 +398,7 @@ def RunHook(hook, upstream_branch='origin', error_ok=False):
hook = '%s/%s' % (settings.GetRoot(), hook)
if not os.path.exists(hook):
return
- output = RunCommand([hook, upstream_branch], error_ok).strip()
+ output = run_command([hook, upstream_branch], error_ok).strip()
if output != '':
print output
@@ -543,7 +409,7 @@ def CmdPresubmit(args):
usage='git cl presubmit [options]')
(options, args) = parser.parse_args(args)
- if RunGit(['diff-index', 'HEAD']):
+ if git(['diff-index', 'HEAD']):
print 'Cannot presubmit with a dirty tree. You must commit locally first.'
return 1
@@ -566,7 +432,7 @@ def CmdUpload(args):
help='send email to reviewer immediately')
(options, args) = parser.parse_args(args)
- if RunGit(['diff-index', 'HEAD']):
+ if git(['diff-index', 'HEAD']):
print 'Cannot upload with a dirty tree. You must commit locally first.'
return 1
@@ -598,7 +464,7 @@ def CmdUpload(args):
upload_args.extend(['--message', options.message])
if options.send_mail:
if not options.reviewers:
- DieWithError("Must specify reviewers to send email.")
+ die("Must specify reviewers to send email.")
upload_args.append('--send_mail')
if cl.GetIssue():
upload_args.extend(['--issue', cl.GetIssue()])
@@ -616,7 +482,7 @@ def CmdUpload(args):
log_args = [args[0] + '..' + args[1]]
else:
log_args = args[:] # Hope for the best!
- desc = RunGit(['log', '--pretty=format:%s\n\n%b'] + log_args)
+ desc = git(['log', '--pretty=format:%s\n\n%b'] + log_args)
initial_text = """# Enter a description of the change.
# This will displayed on the codereview site.
# The first line will also be used as the subject of the review."""
@@ -666,13 +532,13 @@ def SendUpstream(args, cmd='dcommit'):
base_branch = cl.GetUpstreamBranch()
- if RunGit(['diff-index', 'HEAD']):
+ if git(['diff-index', 'HEAD']):
print 'Cannot %s with a dirty tree. You must commit locally first.' % cmd
return 1
# This rev-list syntax means "show all commits not in my branch that
# are in base_branch".
- upstream_commits = RunGit(['rev-list', '^' + cl.GetBranchRef(),
+ upstream_commits = git(['rev-list', '^' + cl.GetBranchRef(),
base_branch]).splitlines()
if upstream_commits:
print ('Base branch "%s" has %d commits '
@@ -737,14 +603,14 @@ def SendUpstream(args, cmd='dcommit'):
# dcommitting that.
MERGE_BRANCH = 'git-cl-commit'
# Delete the merge branch if it already exists.
- if RunGit(['show-ref', '--quiet', '--verify', 'refs/heads/' + MERGE_BRANCH],
+ if git(['show-ref', '--quiet', '--verify', 'refs/heads/' + MERGE_BRANCH],
exit_code=True) == 0:
- RunGit(['branch', '-D', MERGE_BRANCH])
+ git(['branch', '-D', MERGE_BRANCH])
# We might be in a directory that's present in this branch but not in the
# trunk. Move up to the top of the tree so that git commands that expect a
# valid CWD won't fail after we check out the merge branch.
- rel_base_path = RunGit(['rev-parse', '--show-cdup']).strip()
+ rel_base_path = git(['rev-parse', '--show-cdup']).strip()
if rel_base_path:
os.chdir(rel_base_path)
@@ -752,20 +618,20 @@ def SendUpstream(args, cmd='dcommit'):
# We wrap in a try...finally block so if anything goes wrong,
# we clean up the branches.
try:
- RunGit(['checkout', '-q', '-b', MERGE_BRANCH, base_branch])
- RunGit(['merge', '--squash', cl.GetBranchRef()])
- RunGit(['commit', '-m', description])
+ git(['checkout', '-q', '-b', MERGE_BRANCH, base_branch])
+ git(['merge', '--squash', cl.GetBranchRef()])
+ git(['commit', '-m', description])
if cmd == 'push':
# push the merge branch.
remote, branch = cl.GetUpstreamTuple()
- output = RunGit(['push', remote, 'HEAD:%s' % branch], exit_code=True)
+ output = git(['push', remote, 'HEAD:%s' % branch], exit_code=True)
else:
# dcommit the merge branch.
- output = RunGit(['svn', 'dcommit', '--no-rebase'])
+ output = git(['svn', 'dcommit', '--no-rebase'])
finally:
# And then swap back to the original branch and clean up.
- RunGit(['checkout', '-q', cl.GetBranch()])
- RunGit(['branch', '-D', MERGE_BRANCH])
+ git(['checkout', '-q', cl.GetBranch()])
+ git(['branch', '-D', MERGE_BRANCH])
if cl.has_issue:
if cmd == 'dcommit' and output.find("Committed r") != -1:
@@ -790,9 +656,6 @@ def CmdDCommit(args):
return SendUpstream(args, cmd='dcommit')
-def CmdPush(args):
- return SendUpstream(args, cmd='push')
-
def CmdPatch(args):
parser = optparse.OptionParser(usage=('git cl patch [options] '
@@ -831,12 +694,12 @@ def CmdPatch(args):
if options.newbranch:
if options.force:
- RunGit(['branch', '-D', options.newbranch], error_ok=True)
- RunGit(['checkout', '-b', options.newbranch])
+ git(['branch', '-D', options.newbranch], error_ok=True)
+ git(['checkout', '-b', options.newbranch])
# Switch up to the top-level directory, if necessary, in preparation for
# applying the patch.
- top = RunGit(['rev-parse', '--show-cdup']).strip()
+ top = git(['rev-parse', '--show-cdup']).strip()
if top:
os.chdir(top)
@@ -859,7 +722,7 @@ def CmdPatch(args):
# If we had an issue, commit the current state and register the issue.
if not options.nocommit:
- RunGit(['commit', '-m', 'patch from issue %s' % issue])
+ git(['commit', '-m', 'patch from issue %s' % issue])
cl = Changelist()
cl.SetIssue(issue)
print "Committed patch."
@@ -869,7 +732,7 @@ def CmdPatch(args):
def CmdRebase(args):
# Provide a wrapper for git svn rebase to help avoid accidental
# git svn dcommit.
- RunGit(['svn', 'rebase'], redirect_stdout=False)
+ git(['svn', 'rebase'], redirect_stdout=False)
def GetTreeStatus():
"""Fetches the tree status and returns either 'open', 'closed',
@@ -901,9 +764,10 @@ def CmdUpstream(args):
print cl.GetUpstreamBranch()
COMMANDS = [
- ('config', 'edit configuration for this tree', CmdConfig),
+ ('clone', 'clone a bazaar repo', cmd_clone),
+ ('fetch', 'fetch updates from branch', CmdFetch),
+ ('push', 'clone a bazaar repo', CmdPush),
('dcommit', 'commit the current changelist via git-svn', CmdDCommit),
- ('push', 'commit the current changelist via git', CmdPush),
('issue', 'show/set current branch\'s issue number', CmdIssue),
('patch', 'patch in a code review', CmdPatch),
('presubmit', 'run presubmit tests on the current changelist', CmdPresubmit),
Please sign in to comment.
Something went wrong with that request. Please try again.