summaryrefslogtreecommitdiffstats
path: root/src/nbblib/vcs.py
blob: f9b7dd3cc6312820737c436c47e01b880f74bed3 (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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import os
import logging
import urlparse

from nbblib.package import *
from nbblib.plugins import *
from nbblib.progutils import *


class AbstractConfig(object):
    """Return static config until we implement real config reading"""

    def __init__(self, srcdir, nick):
        super(AbstractConfig, self).__init__()
        self._srcdir = srcdir
        self._nick = nick

    def get_srcdir(self):
        return os.path.join(self._srcdir)
    srcdir = property(get_srcdir)

    def get_builddir(self):
        return os.path.join(self._srcdir, "_build", self._nick)
    builddir = property(get_builddir)

    def get_installdir(self):
        return os.path.join(self._srcdir, "_install", self._nick)
    installdir = property(get_installdir)


########################################################################
# VCS Source Tree plugin system
########################################################################

class NotAVCSourceTree(Exception):
    pass


class AmbigousVCSource(Exception):
    def __init__(self, srcdir, matches):
        super(AmbigousVCSource, self).__init__()
        self.srcdir = srcdir
        self.matches = matches
    def __str__(self):
        fmt = "  %-9s %-15s %s"
        def strmatch(m):
            return fmt % (m.name, m.branch_name(), m.tree_root())
        alist = ([fmt % ('VCS Type', 'Branch Name', 'Source tree root')] +
                 [fmt % (m.name, m.branch_name(), m.tree_root()) for m in self.matches])
        return ("More than one source tree VCS type detected for '%s':\n#%s"
                % (self.srcdir, '\n '.join(alist)))


class VCSourceTree(object):
    """
    Mount point for plugins which refer to actions that can be performed.

    Plugins implementing this reference should provide the following
    interface:

    name  attribute
        The text to be displayed, describing the version control system
    __init__  function
        Must raise NotAVCSourceTree() if it is not a VCS source tree
    """
    __metaclass__ = GenericPluginMeta

    def __init__(self, context):
        super(VCSourceTree, self).__init__()
        self.context = context

    @classmethod
    def detect(cls, srcdir, context):
        """Detect VCS tree type and return object representing it"""
        if len(cls.plugins) < 1:
            raise NoPluginsRegistered(cls)
        #logging.debug("CLASS %s", cls)
        matches = PluginDict()
        for key, klass in cls.plugins.iteritems():
            try:
                t = klass(srcdir, context)
                if t.tree_root() == srcdir:
                    #logging.debug("KLASS %s", klass)
                    matches[key] = t
            except NotAVCSourceTree, e:
                pass
        if len(matches) > 1:
            raise AmbigousVCSource(srcdir, matches.values())
        elif len(matches) < 1:
            raise NotAVCSourceTree(srcdir)
        return matches[matches.keys()[0]]

    def get_config(self):
        """Get configuration object which determines builddir etc"""
        return AbstractConfig(self.tree_root(), self.branch_name())
    config = property(get_config)

    def tree_root(self):
        """Get absolute path to source tree root"""
        raise NotImplementedError()

    def branch_name(self):
        """Return name identifying the branch"""
        raise NotImplementedError()

    def __str__(self):
        return repr(self)

    def __repr__(self):
        return "<%s(%s, %s)>" % (self.__class__.__name__,
                                 repr(self.tree_root()),
                                 repr(self.branch_name()))


########################################################################
# VCS Source Tree plugins
########################################################################

class GitSourceTree(VCSourceTree):

    name = 'git'

    def __init__(self, srcdir, context):
        super(GitSourceTree, self).__init__(context)
        os.chdir(srcdir)
        if "true" != prog_stdout(["git", "rev-parse",
                                  "--is-inside-work-tree"]):
            raise NotAVCSourceTree()
        reldir = prog_stdout(["git", "rev-parse", "--show-cdup"])
        if reldir:
            os.chdir(reldir)
        self.__tree_root = os.getcwd()

    def get_config(self):
        return GitConfig(self.tree_root(), self.branch_name())
    config = property(get_config)

    def tree_root(self):
        return self.__tree_root

    def branch_name(self):
        bname = prog_stdout(["git", "symbolic-ref", "HEAD"])
        refs,heads,branch = bname.split('/')
        assert(refs=='refs' and heads=='heads')
        return branch


class GitConfig(AbstractConfig):
    """git config interface"""

    def __init__(self, *args, **kwargs):
        super(GitConfig, self).__init__(*args, **kwargs)

    def _itemname(self, item): return '.'.join((GIT_CONFIG_PREFIX, item, ))
    def _myreldir(self, rdir):
        return os.path.join(self._srcdir, rdir, self._nick)

    def get_builddir(self):
        ret, stdout, stderr = prog_retstd(['git', 'config', self._itemname('builddir')])
        assert(stderr == "")
	if ret == 0 and stdout:
            return self._myreldir(stdout)
        else:
            return super(GitConfig, self).get_builddir()

    def set_builddir(self, value):
        ret, stdout, stderr = prog_retstd(['git', 'config', self._itemname('builddir'), value])
        assert(ret == 0 and stdout == "" and stderr == "")

    builddir = property(get_builddir, set_builddir)

    def get_installdir(self):
        ret, stdout, stderr = prog_retstd(['git', 'config', self._itemname('installdir')])
        assert(stderr == "")
	if ret == 0 and stdout:
            return self._myreldir(stdout)
        else:
            return super(GitConfig, self).get_installdir()

    def set_installdir(self, value):
        ret, stdout, stderr = prog_retstd(['git', 'config', self._itemname('installdir'), value])
        assert(ret == 0 and stdout == "" and stderr == "")

    installdir = property(get_installdir, set_installdir)


class BzrSourceTree(VCSourceTree):

    name = 'bzr'

    def __init__(self, srcdir, context):
        super(BzrSourceTree, self).__init__(context)
        try:
            import bzrlib.workingtree
            wt,b = bzrlib.workingtree.WorkingTree.open_containing(srcdir)
        except bzrlib.errors.NotBranchError:
            raise NotAVCSourceTree()
        except ImportError:
            raise NotAVCSourceTree()
        self.wt = wt
        #print "wt:", wt
        #print "wt:", dir(wt)
        #print "wt.branch:", wt.branch
        #print "wt.branch:", dir(wt.branch)
        #print "wt.branch.nick:", wt.branch.nick
        #print "wt.branch.abspath:", wt.branch.abspath
        #print "wt.branch.base:", wt.branch.base
        #print "wt.branch.basis_tree:", wt.branch.basis_tree()

    def tree_root(self):
        proto,host,path,some,thing = urlparse.urlsplit(self.wt.branch.base)
        assert(proto == "file" and host == "")
        assert(some == "" and thing == "")
        return os.path.abspath(path)

    def branch_name(self):
        return self.wt.branch.nick