aboutsummaryrefslogtreecommitdiffstats
path: root/confman.py
blob: fefb7a363c3df75bbc4ad1d1bfbf015ce47bd0f0 (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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
from __future__ import with_statement

import os
import re
import os.path as osp

# Python <2.6 compatibility
try:
    from os.path import relpath as osp_relpath
except ImportError:
    def osp_relpath(path, start=osp.curdir):
        """Return a relative version of a path"""

        if not path:
            raise ValueError("no path specified")

        start_list = osp.abspath(start).split(osp.sep)
        path_list = osp.abspath(path).split(osp.sep)

        # Work out how much of the filepath is shared by start and path.
        i = len(osp.commonprefix([start_list, path_list]))

        rel_list = [osp.pardir] * (len(start_list)-i) + path_list[i:]
        if not rel_list:
            return osp.curdir
        return osp.join(*rel_list)


class ActionException(Exception):
    def __init__(self, action, value):
        self.action = action
        super(self.__class__, self).__init__(value)

    def __str__(self):
        return super(self.__class__, self).__str__() + " (" + repr(self.action) + ")"


class Action(object):
    @classmethod
    def matches(cls, filename):
        """
        Tells if the file should be associated with this action.
        Returns False if not; confman will try with the next class.
        Returns None if the file should be ignored.
        Returns the destination filename (str) if it matches.
        """
        raise NotImplementedError()

    def __init__(self, config, relpath, source, dest):
        self.source = source
        self.dest = dest
        self.relpath = relpath
        self.config = config

    def __repr__(self):
        return self.__class__.__name__+": "+self.relpath+"/"+self.source+" => "+self.dest

    def check(self):
        raise NotImplementedError()

    def sync(self):
        raise NotImplementedError()

    def dest_path(self):
        return osp.normpath(\
            osp.join(self.config.dest, self.relpath, self.dest))

    def source_path(self):
        return osp.normpath(\
            osp.join(self.config.source, self.relpath, self.source))

    def _makedirs(self):
        dir = osp.dirname(self.dest_path())
        if not osp.isdir(dir):
            os.makedirs(dir)


class SymlinkAction(Action):
    @classmethod
    def matches(cls, filename):
        return filename

    def check(self):
        source = self.source_path()
        if not osp.exists(source):
            raise ActionException(self, "Source does not exists")

        dest = self.dest_path()
        if osp.lexists(dest):
            if not osp.islink(dest):
                raise ActionException(self, "Destination exists and is not a link")

    def sync(self):
        source = self.source_path()
        dest = self.dest_path()
        if osp.lexists(dest):
            # if the link already exists
            if osp.islink(dest):
                # if the old link is broken or incorrect
                if not osp.exists(dest) \
                or not osp.samefile(dest, source):
                    os.unlink(dest)
                    print "Link target altered"
                else:
                    return
        else:
            self._makedirs()

        relsource = osp.normpath(osp_relpath(source, osp.join(self.config.dest, self.relpath)))
        os.symlink(relsource, dest)
        print "Created new link: "+dest+" => "+source


class EmptyAction(Action):
    """
    Ensures the destination file exists.
    Creates an empty one if not.
    """
    matched = re.compile("\.empty$")

    @classmethod
    def matches(cls, filename):
        if cls.matched.search(filename):
            return cls.matched.sub("", filename)
        return False

    def check(self):
        pass

    def sync(self):
        dest = self.dest_path()
        # if the file does not exist
        if not osp.exists(dest):
            # but it's a broken link
            if osp.islink(dest):
                raise ActionException(self, "Destination is a broken link")
            else:
                self._makedirs()
                open(dest, "w").close()
                print "Created new empty file: "+dest

    def __repr__(self):
        return self.__class__.__name__+": EMPTY => "+self.dest


class CopyAction(Action):
    pass #TODO


class Forwarder(Exception):
    def get_proxy(self, parent):
        raise NotImplementedError()


class SymlinkForwarder(Forwarder):
    def __init__(self, filename):
        self.filename = filename

    def get_proxy(self, parent):
        return SymlinkAction(parent.config, parent.relpath, self.filename, parent.dest)


class EmptyForwarder(Forwarder):
    def get_proxy(self, parent):
        return EmptyAction(parent.config, parent.relpath, None, parent.dest)


class IgnoreForwarder(Forwarder):
    def get_proxy(self, parent):
        return None


class ProgrammableAction(Action):
    matched = re.compile("\.p\.py$")

    @classmethod
    def matches(cls, filename):
        if cls.matched.search(filename):
            return cls.matched.sub("", filename)
        return False

    def get_env(self):
        """
        Get limited environment execution.
        This function could be overloaded to add some custom methods.
        """
        def redirect(filename):
            raise SymlinkForwarder("_"+filename)

        def empty():
            raise EmptyForwarder()

        def ignore():
            raise IgnoreForwarder()

        exec_env = \
        {
            "options": self.config.options,
            "redirect": redirect,
            "empty": empty,
            "ignore": ignore,
        }

        return exec_env

    def check(self):
        source = self.source_path()
        try:
            with open(source, "r") as file:
                exec_env = self.get_env()
                exec compile(file.read(), source, "exec") in exec_env
        except Forwarder, e:
            self.proxy = e.get_proxy(self)
        else:
            raise ActionException(self, "Unknown result")

        if not self.proxy is None:
            return self.proxy.check()

    def sync(self):
        if not self.proxy is None:
            return self.proxy.sync()

    def __repr__(self):
        return self.__class__.__name__+": "+self.source+" => PROXY "+repr(self.proxy)


class IgnoreAction(Action):
    ignored = re.compile("_|\.git$|\.gitignore$")

    @classmethod
    def matches(cls, filename):
        if cls.ignored.match(filename):
            return None
        return False

    def __repr__(self):
        return self.__class__.__name__+": "+self.source+" => IGNORED"


class ConfigSource(object):
    def __init__(self, source, dest, classes = None, options = None):
        # handle '~'
        self.source = osp.expanduser(source)
        self.dest = osp.expanduser(dest)

        if classes:
            self.classes = classes
        else:
            self.classes = [
                ProgrammableAction,
                IgnoreAction,
                EmptyAction,
                SymlinkAction,
            ]

        if options:
            self.options = options
        else:
            self.options = []

    def sync(self):
        "Gather files and synchronize them."
        self.analyze()
        self.execute()

    def analyze(self):
        "Gather all files."
        def walker(_, path, files):
            relpath = osp_relpath(path, self.source)
            for filename in (file for file in files \
            if not osp.isdir(osp.join(path, file))):
                self.add(relpath, filename)

        self.tree = {}
        osp.walk(self.source, walker, None)

    def _get_file_class(self, filename):
        """
        Returns the first class that accepts (matches) the file.
        It will fail if no class accepts or tells to ignore.
        """
        for cls in self.classes:
            dest = cls.matches(filename)
            if dest is not False:
                return (cls, dest)
        raise Exception("No class found for "+filename)

    def add(self, relpath, filename):
        """
        Add a file if it can be associated to an action.
        filename is the destination filename; it will check for conflicts
        """
        cls, dest = self._get_file_class(filename)

        if dest is not None:
            files = self.tree.setdefault(relpath, {})
            if files.has_key(dest):
                raise Exception("Conflict: "+filename+" with "+files[dest])
            files[dest] = cls(self, relpath, filename, dest)

    def execute(self):
        "Executes all actions if everything is alright."
        for file in self:
            file.check()
        for file in self:
            file.sync()

    def __iter__(self):
        "Iterates over all analyzed files."
        for files in self.tree.itervalues():
            for file in files.itervalues():
                yield file

    def __repr__(self):
        return "\n".join(\
            (action.relpath+": "+repr(action) for action in self))