1import os
   2import subprocess
   3from git_remote_helpers.util import check_call, check_output
   5class GitImporter(object):
   8    """An importer for testgit repositories.
   9    This importer simply delegates to git fast-import.
  11    """
  12    def __init__(self, repo):
  14        """Creates a new importer for the specified repo.
  15        """
  16        self.repo = repo
  18    def get_refs(self, gitdir):
  20        """Returns a dictionary with refs.
  21        Note that the keys in the returned dictionary are byte strings as
  23        read from git.
  24        """
  25        args = ["git", "--git-dir=" + gitdir, "for-each-ref", "refs/heads"]
  26        lines = check_output(args).strip().split('\n'.encode('ascii'))
  27        refs = {}
  28        for line in lines:
  29            value, name = line.split(' '.encode('ascii'))
  30            name = name.strip('commit\t'.encode('ascii'))
  31            refs[name] = value
  32        return refs
  33    def do_import(self, base):
  35        """Imports a fast-import stream to the given directory.
  36        Simply delegates to git fast-import.
  38        """
  39        dirname = self.repo.get_base_path(base)
  41        if self.repo.local:
  42            gitdir = self.repo.gitpath
  43        else:
  44            gitdir = os.path.abspath(os.path.join(dirname, '.git'))
  45        path = os.path.abspath(os.path.join(dirname, 'testgit.marks'))
  46        if not os.path.exists(dirname):
  48            os.makedirs(dirname)
  49        refs_before = self.get_refs(gitdir)
  51        args = ["git", "--git-dir=" + gitdir, "fast-import", "--quiet", "--export-marks=" + path]
  53        if os.path.exists(path):
  55            args.append("--import-marks=" + path)
  56        check_call(args)
  58        refs_after = self.get_refs(gitdir)
  60        changed = {}
  62        for name, value in refs_after.iteritems():
  64            if refs_before.get(name) == value:
  65                continue
  66            changed[name] = value
  68        return changed