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        """
  22        args = ["git", "--git-dir=" + gitdir, "for-each-ref", "refs/heads"]
  23        lines = check_output(args).strip().split('\n')
  24        refs = {}
  25        for line in lines:
  26            value, name = line.split(' ')
  27            name = name.strip('commit\t')
  28            refs[name] = value
  29        return refs
  30    def do_import(self, base):
  32        """Imports a fast-import stream to the given directory.
  33        Simply delegates to git fast-import.
  35        """
  36        dirname = self.repo.get_base_path(base)
  38        if self.repo.local:
  39            gitdir = self.repo.gitpath
  40        else:
  41            gitdir = os.path.abspath(os.path.join(dirname, '.git'))
  42        path = os.path.abspath(os.path.join(dirname, 'git.marks'))
  43        if not os.path.exists(dirname):
  45            os.makedirs(dirname)
  46        refs_before = self.get_refs(gitdir)
  48        args = ["git", "--git-dir=" + gitdir, "fast-import", "--quiet", "--export-marks=" + path]
  50        if os.path.exists(path):
  52            args.append("--import-marks=" + path)
  53        check_call(args)
  55        refs_after = self.get_refs(gitdir)
  57        changed = {}
  59        for name, value in refs_after.iteritems():
  61            if refs_before.get(name) == value:
  62                continue
  63            changed[name] = value
  65        return changed