git-remote-testgit.pyon commit Merge branch 'en/merge-recursive-2' (96b7c4d)
   1#!/usr/bin/env python
   2
   3# hashlib is only available in python >= 2.5
   4try:
   5    import hashlib
   6    _digest = hashlib.sha1
   7except ImportError:
   8    import sha
   9    _digest = sha.new
  10import sys
  11import os
  12sys.path.insert(0, os.getenv("GITPYTHONLIB","."))
  13
  14from git_remote_helpers.util import die, debug, warn
  15from git_remote_helpers.git.repo import GitRepo
  16from git_remote_helpers.git.exporter import GitExporter
  17from git_remote_helpers.git.importer import GitImporter
  18from git_remote_helpers.git.non_local import NonLocalGit
  19
  20def get_repo(alias, url):
  21    """Returns a git repository object initialized for usage.
  22    """
  23
  24    repo = GitRepo(url)
  25    repo.get_revs()
  26    repo.get_head()
  27
  28    hasher = _digest()
  29    hasher.update(repo.path)
  30    repo.hash = hasher.hexdigest()
  31
  32    repo.get_base_path = lambda base: os.path.join(
  33        base, 'info', 'fast-import', repo.hash)
  34
  35    prefix = 'refs/testgit/%s/' % alias
  36    debug("prefix: '%s'", prefix)
  37
  38    repo.gitdir = os.environ["GIT_DIR"]
  39    repo.alias = alias
  40    repo.prefix = prefix
  41
  42    repo.exporter = GitExporter(repo)
  43    repo.importer = GitImporter(repo)
  44    repo.non_local = NonLocalGit(repo)
  45
  46    return repo
  47
  48
  49def local_repo(repo, path):
  50    """Returns a git repository object initalized for usage.
  51    """
  52
  53    local = GitRepo(path)
  54
  55    local.non_local = None
  56    local.gitdir = repo.gitdir
  57    local.alias = repo.alias
  58    local.prefix = repo.prefix
  59    local.hash = repo.hash
  60    local.get_base_path = repo.get_base_path
  61    local.exporter = GitExporter(local)
  62    local.importer = GitImporter(local)
  63
  64    return local
  65
  66
  67def do_capabilities(repo, args):
  68    """Prints the supported capabilities.
  69    """
  70
  71    print "import"
  72    print "export"
  73    print "refspec refs/heads/*:%s*" % repo.prefix
  74
  75    dirname = repo.get_base_path(repo.gitdir)
  76
  77    if not os.path.exists(dirname):
  78        os.makedirs(dirname)
  79
  80    path = os.path.join(dirname, 'testgit.marks')
  81
  82    print "*export-marks %s" % path
  83    if os.path.exists(path):
  84        print "*import-marks %s" % path
  85
  86    print # end capabilities
  87
  88
  89def do_list(repo, args):
  90    """Lists all known references.
  91
  92    Bug: This will always set the remote head to master for non-local
  93    repositories, since we have no way of determining what the remote
  94    head is at clone time.
  95    """
  96
  97    for ref in repo.revs:
  98        debug("? refs/heads/%s", ref)
  99        print "? refs/heads/%s" % ref
 100
 101    if repo.head:
 102        debug("@refs/heads/%s HEAD" % repo.head)
 103        print "@refs/heads/%s HEAD" % repo.head
 104    else:
 105        debug("@refs/heads/master HEAD")
 106        print "@refs/heads/master HEAD"
 107
 108    print # end list
 109
 110
 111def update_local_repo(repo):
 112    """Updates (or clones) a local repo.
 113    """
 114
 115    if repo.local:
 116        return repo
 117
 118    path = repo.non_local.clone(repo.gitdir)
 119    repo.non_local.update(repo.gitdir)
 120    repo = local_repo(repo, path)
 121    return repo
 122
 123
 124def do_import(repo, args):
 125    """Exports a fast-import stream from testgit for git to import.
 126    """
 127
 128    if len(args) != 1:
 129        die("Import needs exactly one ref")
 130
 131    if not repo.gitdir:
 132        die("Need gitdir to import")
 133
 134    ref = args[0]
 135    refs = [ref]
 136
 137    while True:
 138        line = sys.stdin.readline()
 139        if line == '\n':
 140            break
 141        if not line.startswith('import '):
 142            die("Expected import line.")
 143
 144        # strip of leading 'import '
 145        ref = line[7:].strip()
 146        refs.append(ref)
 147
 148    repo = update_local_repo(repo)
 149    repo.exporter.export_repo(repo.gitdir, refs)
 150
 151    print "done"
 152
 153
 154def do_export(repo, args):
 155    """Imports a fast-import stream from git to testgit.
 156    """
 157
 158    if not repo.gitdir:
 159        die("Need gitdir to export")
 160
 161    update_local_repo(repo)
 162    changed = repo.importer.do_import(repo.gitdir)
 163
 164    if not repo.local:
 165        repo.non_local.push(repo.gitdir)
 166
 167    for ref in changed:
 168        print "ok %s" % ref
 169    print
 170
 171
 172COMMANDS = {
 173    'capabilities': do_capabilities,
 174    'list': do_list,
 175    'import': do_import,
 176    'export': do_export,
 177}
 178
 179
 180def sanitize(value):
 181    """Cleans up the url.
 182    """
 183
 184    if value.startswith('testgit::'):
 185        value = value[9:]
 186
 187    return value
 188
 189
 190def read_one_line(repo):
 191    """Reads and processes one command.
 192    """
 193
 194    line = sys.stdin.readline()
 195
 196    cmdline = line
 197
 198    if not cmdline:
 199        warn("Unexpected EOF")
 200        return False
 201
 202    cmdline = cmdline.strip().split()
 203    if not cmdline:
 204        # Blank line means we're about to quit
 205        return False
 206
 207    cmd = cmdline.pop(0)
 208    debug("Got command '%s' with args '%s'", cmd, ' '.join(cmdline))
 209
 210    if cmd not in COMMANDS:
 211        die("Unknown command, %s", cmd)
 212
 213    func = COMMANDS[cmd]
 214    func(repo, cmdline)
 215    sys.stdout.flush()
 216
 217    return True
 218
 219
 220def main(args):
 221    """Starts a new remote helper for the specified repository.
 222    """
 223
 224    if len(args) != 3:
 225        die("Expecting exactly three arguments.")
 226        sys.exit(1)
 227
 228    if os.getenv("GIT_DEBUG_TESTGIT"):
 229        import git_remote_helpers.util
 230        git_remote_helpers.util.DEBUG = True
 231
 232    alias = sanitize(args[1])
 233    url = sanitize(args[2])
 234
 235    if not alias.isalnum():
 236        warn("non-alnum alias '%s'", alias)
 237        alias = "tmp"
 238
 239    args[1] = alias
 240    args[2] = url
 241
 242    repo = get_repo(alias, url)
 243
 244    debug("Got arguments %s", args[1:])
 245
 246    more = True
 247
 248    while (more):
 249        more = read_one_line(repo)
 250
 251if __name__ == '__main__':
 252    sys.exit(main(sys.argv))