aboutsummaryrefslogtreecommitdiffstats
path: root/MgaRepo/git.py
blob: 4e763f874f3286905aefa757b82c45b328b8b8ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
from MgaRepo import Error, config
from MgaRepo.util import execcmd
from MgaRepo.VCS import *
from MgaRepo.svn import SVN
from MgaRepo.log import UserTagParser
from os.path import basename, dirname, abspath, lexists, join
from os import chdir, getcwd
from tempfile import mkstemp
import sys
import re
import time
from xml.etree import ElementTree
import subprocess

class GITLogEntry(VCSLogEntry):
    def __init__(self, revision, author, date):
        VCSLogEntry.__init__(self, revision, author, data)

class GIT(VCS):
    vcs_dirname = ".git"
    vcs_name = "git"
    def __init__(self, path=None, url=None):
        VCS.__init__(self, path, url)
        self.vcs_command = config.get("global", "git-command", ["git"])
        self.vcs_supports['clone'] = True
        self.env_defaults = {"GIT_SSH": self.vcs_wrapper}

    def configget(self, key="", location="--local"):
        cmd = ["config", location, "--get-regexp", key]
        config = None
        status, output = self._execVcs(*cmd, noerror=True)
        if not status and output:
            config = eval("{'" + output.replace("\n", "',\n'").replace(" ", "' : '") + "'}")
        return config

    def configset(self, config, location="--local"):
        cmd = ("config", location)
        for pair in config.items():
            status, output = self._execVcs(*cmd + pair)
            if status:
                return False
        return True

    def clone(self, url, targetpath, fullnames=True, **kwargs):
        for vcs in (SVN, GIT):
            if lexists(join(targetpath, vcs.vcs_dirname)):
                raise Error("target path %s already contains %s repository, aborting..." % (targetpath, vcs.vcs_name))

        self.init(url, targetpath, fullnames=True, **kwargs)
        if url.split(':')[0].find("svn") < 0:
            return VCS.clone(self, url, **kwargs)
        else:
            return self.update(targetpath, clone=True, **kwargs)

    def init(self, url, targetpath, fullnames=True, branch=None, **kwargs):
        # verify repo url
        execcmd("svn", "info", url)

        topurl = dirname(url)
        trunk = basename(url)
        tags = "releases"
        # cloning svn braches as well should rather be optionalif reenabled..
        #cmd = ["svn", "init", topurl, "--trunk="+trunk, "--tags="+tags", targetpath]

        cmd = ["svn", "init", url, abspath(targetpath)]
        self._execVcs(*cmd, **kwargs)
        os.environ.update({"GIT_WORK_TREE" : abspath(targetpath), "GIT_DIR" : join(abspath(targetpath),".git")})

        if fullnames:
            usermap = UserTagParser()
            # store configuration in local git config so that'll be reused later when ie. updating
            gitconfig = {"svn-remote.authorlog.url" : usermap.url,
                    "svn-remote.authorlog.defaultmail": usermap.defaultmail}
            self.configset(gitconfig)

        if branch:
            execcmd(("git", "init", "-q", self.path), **kwargs)
            execcmd(("git", "checkout", "-q", branch), **kwargs)
            cmd = ["svn", "rebase", "--local"]
            status, output = self._execVcs(*cmd, **kwargs)

        return True

    def info(self, path, **kwargs):
        cmd = ["svn", "info", path + '@' if '@' in path else path]
        status, output = self._execVcs(local=True, noerror=True, *cmd, **kwargs)
        if (("Not a git repository" not in output) and \
                ("Unable to determine upstream SVN information from working tree history" not in output)):
            return output.splitlines()
        return None

    def status(self, path, **kwargs):
        cmd = ["status", path + '@' if '@' in path else path]
        if kwargs.get("verbose"):
            cmd.append("-v")
        if kwargs.get("noignore"):
            cmd.append("-u")
        if kwargs.get("quiet"):
            cmd.append("-s")
        status, output = self._execVcs(*cmd, **kwargs)
        if status == 0:
            return [(x[0], x[8:]) for x in output.splitlines()]
        return None

    def update(self, targetpath, clone=False, **kwargs):
        os.environ.update({"GIT_WORK_TREE" : abspath(targetpath), "GIT_DIR" : join(abspath(targetpath),".git")})

        if not clone:
            cmd = ["svn", "log", "--oneline", "--limit=1"]
            retval, result = self._execVcs(*cmd)
            if retval:
                return retval

            revision = result.split()

            if revision[0][0] == 'r':
                startrev = "-r"+str(int(revision[0][1:])+1)
            else:
                startrev = "BASE"

            cmd = ["svn", "propget", "svn:entry:committed-rev"]
            retval, lastrev = self._execVcs(*cmd)
            if retval:
                return retval

        #cmd = ["config", "--get-regexp", '^svn-remote.svn.(url|fetch)']
        cmd = ["config", "--get", "svn-remote.svn.url"]
        retval, result = self._execVcs(*cmd)
        if retval:
            return retval

        #result = result.strip().split()
        #url = result[1] + "/" + result[3].split(":")[0]
        url = result.strip()

        # To speed things up on huge repositories, we'll just grab all the
        # revision numbers for this specific directory and grab these only
        # in stead of having to go through each and every revision...
        cmd = ["svn", "log", "-g", "--xml", url]
        if not clone:
            cmd.append("%s:%s" % (startrev,lastrev))
        retval, result = execcmd(*cmd)
        if retval:
            return retval

        xmllog = ElementTree.fromstring(result)
        logentries = xmllog.getiterator("logentry")
        revisions = []
        for entry in logentries:
            revisions.append(int(entry.attrib["revision"]))
        revisions.sort()

        fetchcmd = ["svn", "fetch", "--log-window-size=1000"]
        gitconfig = self.configget("svn-remote.authorlog")
        if gitconfig:
            usermap = UserTagParser(url=gitconfig.get("svn-remote.authorlog.url"),defaultmail=gitconfig.get("svn-remote.authorlog.defaultmail"))
            usermapfile = usermap.get_user_map_file()
            fetchcmd.extend(("--authors-file", usermapfile))
        fetchcmd.append("")

        while revisions:
            fetchcmd[-1] = "-r%d"%revisions.pop(0)
            self._execVcs(*fetchcmd, **kwargs)
        if gitconfig:
            usermap.cleanup()

        cmd = ["svn", "rebase", "--log-window-size=1000", "--local", "--fetch-all", "git-svn"]
        status, output = self._execVcs(*cmd, **kwargs)
        if status == 0:
            return [x.split() for x in output.split()]
        return None

    def remote(self, *args, **kwargs):
        cmd = ["remote"] + list(args)
        status, output = self._execVcs(*cmd, **kwargs)
        return status, output

    def pull(self, *args, **kwargs):
        cmd = ["pull"] + list(args)
        status, output = self._execVcs(*cmd, **kwargs)
        return status, output

    def push(self, *args, **kwargs):
        cmd = ["push"] + list(args)
        status, output = self._execVcs(*cmd, **kwargs)
        return status, output

class GITLook(VCSLook):
    def __init__(self, repospath, txn=None, rev=None):
        VCSLook.__init__(self, repospath, txn, rev)

# vim:et:ts=4:sw=4