Skip to content

Commit

Permalink
Use the gitify entry point for all commands.
Browse files Browse the repository at this point in the history
* Refactored the entry points to just gitify. All other commands are now
  sub-commands of ``gitify``.

* Added usage and help output for each command

* Removed the clone command as it was only ever used together with the
  main gitify command anyway

* Use proper logging instead of just printing to stdout

* Removed dependency on jarn.mkrelease. We only used one private helper
  function (``popen``) anyway, and due to mkrelease's recent git and hg
  support its dependencies have grown so large as to no longer justify them
  for gitify. ``popen`` now lives in ``tee.py`` as an abridged copy from
  jarn.mkrelease
  • Loading branch information
tomster committed Jul 12, 2009
1 parent b4cfd26 commit 7db433a
Show file tree
Hide file tree
Showing 5 changed files with 237 additions and 114 deletions.
20 changes: 18 additions & 2 deletions HISTORY.txt
@@ -1,5 +1,21 @@
0.3.2 - Unreleased
------------------
0.4 - Unreleased
----------------

* Refactored the entry points to just gitify. All other commands are now
sub-commands of ``gitify``.

* Added usage and help output for each command

* Removed the clone command as it was only ever used together with the
main gitify command anyway

* Use proper logging instead of just printing to stdout

* Removed dependency on jarn.mkrelease. We only used one private helper
function (``popen``) anyway, and due to mkrelease's recent git and hg
support its dependencies have grown so large as to no longer justify them
for gitify. ``popen`` now lives in ``tee.py`` as an abridged copy from
jarn.mkrelease

0.3.1 - 2009-07-09
------------------
Expand Down
122 changes: 73 additions & 49 deletions gitsvnhelpers/commands.py
@@ -1,16 +1,19 @@
import logging
import optparse
import sys
import os
from os.path import exists
from optparse import OptionParser
from os.path import abspath
from glob import glob
from jarn.mkrelease.tee import popen
from tee import popen
from config import GIT_CACHE
from utils import basename
from utils import is_svn
from utils import svn_log
from utils import base_url

logger = logging.getLogger("gitify")


def clone():

Expand Down Expand Up @@ -55,50 +58,71 @@ def clone():
return 0


def fetch():

"""
Performs a git-svn fetch operation for the given packages inside the
cache directory. If no parameter is passed, all cached packages are
updated.
"""

global options, args
usage = "%prog [options] package ..."
parser = OptionParser(usage)
parser.add_option('-v', '--verbose', default=0, action='count',
help="print git-svn output")

options, args = parser.parse_args()

try:
input = args[0]
except IndexError:
input = '*'

cwd = os.getcwd()
updated = 0
for package in glob(abspath("%s/%s" % (GIT_CACHE, input))):
os.chdir(package)
print "fetching %s" % package
popen("git svn fetch", options.verbose, True)
updated += 1

if updated > 0:
print "Done. %d packages updated." % updated
else:
print "No packages found for %s" % input
os.chdir(cwd)
return 0


def commit():
""" performs a dcommit with an ensuing svn update, to keep git and svn
in sync.
"""
status, dummy = popen('git svn dcommit', True, True)
if status == 0:
popen('svn up --force', True, True)

if __name__ == '__main__':
sys.exit(clone())
class Command(object):

def __init__(self, gitify):
self.gitify = gitify


class CmdFetch(Command):

def __init__(self, gitify):
Command.__init__(self, gitify)
self.parser = optparse.OptionParser(
usage = "%prog fetch [<package-wildcard>]",
description = """
Performs a git-svn fetch operation for the given packages inside the
cache directory. If no parameter is passed, all cached packages are
updated.
""",
add_help_option=False)
self.parser.add_option("-v", "--verbose", dest="verbose",
action="store_true", default=False,
help="""Show svn output.""")

def __call__(self):
options, args = self.parser.parse_args(sys.argv[2:])

try:
input = args[0]
except IndexError:
input = '*'

cwd = os.getcwd()
updated = 0
for package in glob(abspath("%s/%s" % (GIT_CACHE, input))):
os.chdir(package)
print "fetching %s" % package
popen("git svn fetch", options.verbose, True)
updated += 1

if updated > 0:
print "Done. %d packages updated." % updated
else:
print "No packages found for %s" % input
os.chdir(cwd)


class CmdPush(Command):

def __init__(self, gitify):
Command.__init__(self, gitify)
self.parser = optparse.OptionParser(
usage = "%prog push",
description = """
Performs a dcommit with an ensuing svn update, to keep git and svn
in sync.
""",
add_help_option=False)
self.parser.add_option("-v", "--verbose", dest="verbose",
action="store_true", default=False,
help="""Show git-svn output.""")

def __call__(self):
options, args = self.parser.parse_args(sys.argv[2:])
status, dummy = popen('git svn dcommit', options.verbose, True)
if status == 0:
popen('svn up --force', options.verbose, True)
logger.info("Pushed local changes to svn.")
else:
logger.error("An error occurred, consult output above.")
199 changes: 143 additions & 56 deletions gitsvnhelpers/gitify.py
@@ -1,70 +1,157 @@
import logging
import optparse
import sys
import os
from os.path import exists
from jarn.mkrelease.tee import popen

from config import GIT_CACHE
from tee import popen
from utils import basename
from utils import is_git
from utils import is_svn
from utils import svn_type
from utils import svn_branch
from commands import clone


def main(args=None):

if is_git():
print "This seems to be a local git repository!"
sys.exit(1)

if not is_svn():
print "This only works on svn checkouts!"
sys.exit(1)

package_name = basename()
svntype = svn_type()

if svntype == 'tags':
print "Can't work on tags!"
from commands import Command
from commands import CmdPush
from commands import CmdFetch

logger = logging.getLogger("gitify")


class CmdGitify(Command):

def __init__(self, gitify):
Command.__init__(self, gitify)
self.parser = optparse.OptionParser(
usage = "%prog",
description = """
""",
add_help_option=False)
self.parser.add_option("-v", "--verbose", dest="verbose",
action="store_true", default=False,
help="""Show git-svn output.""")

def __call__(self):
options, args = self.parser.parse_args(sys.argv[2:])

package_name = basename()
svntype = svn_type()

if svntype == 'tags':
print "Can't work on tags!"
sys.exit(1)
elif svntype == 'unrecognized':
print "Unrecognized svn structure!"
sys.exit(1)

if not exists(GIT_CACHE + package_name):
print "No git repository found in %s." % GIT_CACHE
print "Initiating cloning into cache."
clone()

# get the branch svn is on
remote_branch = svn_branch()
# the following is just convention:
local_branch = "local/%s" % remote_branch

cwd = os.getcwd()
# perform all index updates in the cache to avoid conflicts
os.chdir(GIT_CACHE + package_name)

dummy, existing_branches = popen('git b', False, False)
existing_branches = [b.strip() for b in existing_branches]
if local_branch in existing_branches:
popen('git checkout -f %s' % local_branch, False, False)
else:
popen('git checkout -f -b %s %s' % (local_branch, remote_branch),
False, False)

os.chdir(cwd)
if not exists('.git'):
popen('ln -s %s%s/.git' % (GIT_CACHE, package_name), False, False)

print "Git branch '%s' is now following svn branch '%s':" % (
local_branch, remote_branch)
popen('svn status')
popen('git status')


class CmdHelp(Command):
def __init__(self, gitify):
Command.__init__(self, gitify)
self.parser = optparse.OptionParser(
usage="%prog help [<command>]",
description="Show help on the given command or about the whole script if none given.",
add_help_option=False)

def __call__(self):
gitify = self.gitify
if len(sys.argv) != 3 or sys.argv[2] not in gitify.commands:
print("usage: %s <command> [options] [args]" % os.path.basename(sys.argv[0]))
print("\nType '%s help <command>' for help on a specific command." % os.path.basename(sys.argv[0]))
print("\nAvailable commands:")
f_to_name = {}
for name, f in gitify.commands.iteritems():
f_to_name.setdefault(f, []).append(name)
for cmd in sorted(x for x in dir(gitify) if x.startswith('cmd_')):
name = cmd[4:]
if name == 'pony':
continue
f = getattr(gitify, cmd)
aliases = [x for x in f_to_name[f] if x != name]
if len(aliases):
print(" %s (%s)" % (name, ", ".join(aliases)))
else:
print(" %s" % name)
else:
print gitify.commands[sys.argv[2]].parser.format_help()



class Gitify(object):

def __call__(self, **kwargs):
logger.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(ch)

if len(kwargs) == 0:
if is_git():
logger.error("This seems to be a local git repository!")
return

if not is_svn():
logger.error("This only works on svn checkouts!")
return

self.cmd_push = CmdPush(self)
self.cmd_fetch = CmdFetch(self)
self.cmd_gitify = CmdGitify(self)
self.cmd_help = CmdHelp(self)

self.commands = dict(
help=self.cmd_help,
h=self.cmd_help,
up = self.cmd_fetch,
fetch = self.cmd_fetch,
push = self.cmd_push,
gitify = self.cmd_gitify,
)

try:
command = sys.argv[1]
except IndexError:
command = 'gitify'

self.commands.get(command, self.unknown)()

def unknown(self):
logger.error("Unknown command '%s'." % sys.argv[1])
logger.info("Type '%s help' for usage." % \
os.path.basename(sys.argv[0]))
sys.exit(1)
elif svntype == 'unrecognized':
print "Unrecognized svn structure!"
sys.exit(1)

if not exists(GIT_CACHE + package_name):
print "No git repository found in %s." % GIT_CACHE
print "Initiating cloning into cache."
clone()

# get the branch svn is on
remote_branch = svn_branch()
# the following is just convention:
local_branch = "local/%s" % remote_branch

cwd = os.getcwd()
# perform all index updates in the cache to avoid conflicts
os.chdir(GIT_CACHE + package_name)

dummy, existing_branches = popen('git b', False, False)
existing_branches = [b.strip() for b in existing_branches]
if local_branch in existing_branches:
popen('git checkout -f %s' % local_branch, False, False)
else:
popen('git checkout -f -b %s %s' % (local_branch, remote_branch), False,
False)

os.chdir(cwd)
if not exists('.git'):
popen('ln -s %s%s/.git' % (GIT_CACHE, package_name), False, False)

print "Git branch '%s' is now following svn branch '%s':" % (
local_branch, remote_branch)
popen('svn status')
popen('git status')

return 0


if __name__ == '__main__':
sys.exit(main())
gitify = Gitify()
2 changes: 1 addition & 1 deletion gitsvnhelpers/utils.py
@@ -1,6 +1,6 @@
from os.path import exists, isdir, islink
from elementtree import ElementTree
from jarn.mkrelease.tee import popen
from tee import popen


def basename():
Expand Down

0 comments on commit 7db433a

Please sign in to comment.