~launchpad-pqm/bzr-svn/devel

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
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


"""TDB implementation of the bzr-svn cache."""

import os
import tdb
try:
    tdb.Tdb.get
except AttributeError:
    raise ImportError("tdb is out of date: doesn't have a Tdb.get attribute")

from bzrlib import (
    bencode,
    debug,
    errors,
    trace,
    )

from bzrlib.plugins.svn.cache import (
    RepositoryCache,
    )
from bzrlib.plugins.svn.mapping import (
    mapping_registry,
    )
from bzrlib.plugins.svn.revids import (
    RevisionIdMapCache,
    )
from bzrlib.plugins.svn.revmeta import (
    RevisionInfoCache,
    )
from bzrlib.plugins.svn.logwalker import (
    LogCache,
    )
from bzrlib.plugins.svn.parents import (
    ParentsCache,
    )

from subvertpy import NODE_UNKNOWN

from tdb import Tdb as tdb_open


CACHE_DB_VERSION = 1


class CacheTable(object):

    def __init__(self, db):
        self.db = db

    def commit(self):
        pass

    def mutter(self, text, *args, **kwargs):
        if "cache" in debug.debug_flags:
            trace.mutter(text, *args, **kwargs)


class TdbRevisionIdMapCache(RevisionIdMapCache, CacheTable):

    def set_last_revnum_checked(self, layout, revnum):
        """See RevisionIdMapCache.set_last_revnum_checked."""

        self.db["revidmap-last/%s" % str(layout)] = str(revnum)

    def last_revnum_checked(self, layout):
        """See RevisionIdMapCache.last_revnum_checked."""

        try:
            return int(self.db["revidmap-last/%s" % str(layout)])
        except KeyError:
            return 0

    def lookup_revid(self, revid):
        """See RevisionIdMapCache.lookup_revid."""

        self.mutter('lookup-revid %s', revid)
        try:
            (min_revnum, max_revnum, mapping_name, path) = self.db["native-revid/" + revid].split(" ", 3)
        except KeyError:
            raise errors.NoSuchRevision(self, revid)
        return (path, int(min_revnum), int(max_revnum), mapping_name)

    def lookup_branch_revnum(self, revnum, path, mapping):
        """See RevisionIdMapCache.lookup_branch_revnum."""

        self.mutter('lookup-branch-revnum %s:%d', path, revnum)
        try:
            return self.db["foreign-revid/%d %s %s" % (revnum, getattr(mapping, "name", mapping), path)]
        except KeyError:
            return None

    def insert_revid(self, revid, branch, min_revnum, max_revnum, mapping):
        """See RevisionIdMapCache.insert_revid."""

        mappingname = getattr(mapping, "name", mapping)
        self.db["native-revid/" + revid] = "%d %d %s %s" % (min_revnum, max_revnum, mappingname, branch)
        if min_revnum == max_revnum:
            self.db["foreign-revid/%d %s %s" % (min_revnum, mappingname, branch)] = revid


class TdbRevisionInfoCache(RevisionInfoCache, CacheTable):

    def set_original_mapping(self, foreign_revid, original_mapping):
        """See RevisionInfoCache.set_original_mapping."""

        if original_mapping is not None:
            orig_mapping_name = original_mapping.name
        else:
            orig_mapping_name = ""
        self.db["original-mapping/%d %s" % (foreign_revid[2], foreign_revid[1])] = orig_mapping_name

    def insert_revision(self, foreign_revid, mapping, (revno, revid, hidden),
            stored_lhs_parent_revid):
        """See RevisionInfoCache.insert_revision."""

        if revid is None:
            revid = mapping.revision_id_foreign_to_bzr(foreign_revid)
        self.db["foreign-revid/%d %d %s %s" % (foreign_revid[2], foreign_revid[2], mapping.name, foreign_revid[1])] = revid
        basekey = "%d %s %s" % (foreign_revid[2], mapping.name, foreign_revid[1])
        assert not hidden or revno is None
        if revno is not None:
            self.db["revno/%s" % basekey] = "%d" % revno
        elif hidden:
            self.db["revno/%s" % basekey] = ""
        if stored_lhs_parent_revid is not None:
            self.db["lhs-parent-revid/%s" % basekey] = stored_lhs_parent_revid

    def get_revision(self, foreign_revid, mapping):
        """See RevisionInfoCache.get_revision."""

        self.mutter("get-revision %r,%r", foreign_revid, mapping)
        basekey = "%d %s %s" % (foreign_revid[2], mapping.name, foreign_revid[1])
        revid = self.db["foreign-revid/%d %d %s %s" % (foreign_revid[2], foreign_revid[2], mapping.name, foreign_revid[1])]
        stored_lhs_parent_revid = self.db.get("lhs-parent-revid/%s" % basekey)
        try:
            revno = int(self.db["revno/%s" % basekey])
            hidden = False
        except KeyError:
            revno = None
            hidden = False
        except ValueError: # empty string
            hidden = True
            revno = None
        return ((revno, revid, hidden), stored_lhs_parent_revid)

    def get_original_mapping(self, foreign_revid):
        """See RevisionInfoCache.get_original_mapping."""

        self.mutter("get-original-mapping %r", foreign_revid)
        ret = self.db["original-mapping/%d %s" % (foreign_revid[2], foreign_revid[1])]
        if ret == "":
            return None
        return mapping_registry.parse_mapping_name("svn-" + ret)


class TdbLogCache(LogCache, CacheTable):

    def find_latest_change(self, path, revnum):
        """See LogCache.find_latest_change."""

        raise NotImplementedError(self.find_latest_change)

    def get_revision_paths(self, revnum):
        """See LogCache.get_revision_paths."""

        self.mutter("get-revision-paths %d", revnum)
        ret = {}
        try:
            db = bencode.bdecode(self.db["paths/%d" % revnum])
        except KeyError:
            raise KeyError("missing revision paths for %d" % revnum)
        for key, v in db.iteritems():
            try:
                (action, cp, cr, kind) = v
            except ValueError:
                (action, cp, cr) = v
                kind = NODE_UNKNOWN
            if cp == "" and cr == -1:
                cp = None
            ret[key] = (action, cp, cr, kind)
        return ret

    def insert_paths(self, rev, orig_paths, revprops, all_revprops):
        """See LogCache.insert_paths."""
        self.db.transaction_start()
        try:
            self.insert_revprops(rev, revprops, all_revprops)
            if orig_paths is None:
                orig_paths = {}
            new_paths = {}
            for p in orig_paths:
                v = orig_paths[p]
                copyfrom_path = v[1]
                if copyfrom_path is not None:
                    copyfrom_path = copyfrom_path.strip("/")
                else:
                    copyfrom_path = ""
                    assert orig_paths[p][2] == -1
                try:
                    kind = v[3]
                except IndexError:
                    kind = NODE_UNKNOWN
                new_paths[p.strip("/")] = (v[0], copyfrom_path, v[2], kind)
            self.db["paths/%d" % rev] = bencode.bencode(new_paths)
            min_revnum = self.min_revnum()
            if min_revnum is None:
                min_revnum = rev
            else:
                min_revnum = min(min_revnum, rev)
            self.db["log-min"] = str(min_revnum)
            self.db["log-last"] = str(max(self.max_revnum(), rev))
        except:
            self.db.transaction_cancel()
            raise
        else:
            self.db.transaction_commit()

    def drop_revprops(self, revnum):
        """See LogCache.drop_revprops."""

        self.db["revprops/%d" % revnum] = bencode.bencode({})

    def get_revprops(self, revnum):
        """See LogCache.get_revprops."""

        self.mutter("get-revision-properties %d", revnum)
        ret = bencode.bdecode(self.db["revprops/%d" % revnum])
        return (ret[0], bool(ret[1]))

    def insert_revprops(self, revision, revprops, all_revprops):
        """See LogCache.insert_revprops."""

        if revprops is None:
            revprops = {}
        self.db["revprops/%d" % revision] = bencode.bencode((revprops, all_revprops))

    def max_revnum(self):
        """See LogCache.last_revnum."""

        try:
            return int(self.db["log-last"])
        except KeyError:
            return 0

    def min_revnum(self):
        """See LogCache.min_revnum."""

        try:
            return int(self.db["log-min"])
        except KeyError:
            return None


class TdbParentsCache(ParentsCache, CacheTable):

    def insert_parents(self, revid, parents):
        """See ParentsCache.insert_parents."""

        self.db["parents/%s" % revid] = " ".join(parents)

    def lookup_parents(self, revid):
        """See ParentsCache.lookup_parents."""

        self.mutter("lookup-parents %s", revid)
        try:
            return tuple(
                [p for p in self.db["parents/%s" % revid].split(" ")
                    if p != ""])
        except KeyError:
            return None


TDB_HASH_SIZE = 10000


class TdbRepositoryCache(RepositoryCache):
    """Object that provides a cache related to a particular UUID."""

    def __init__(self, uuid):
        super(TdbRepositoryCache, self).__init__(uuid)
        cache_file = os.path.join(self.create_cache_dir(), 'cache.tdb')
        assert isinstance(cache_file, str)
        db = tdb_open(cache_file, TDB_HASH_SIZE, tdb.DEFAULT,
                os.O_RDWR|os.O_CREAT)
        try:
            assert int(db["version"]) == CACHE_DB_VERSION
        except KeyError:
            db["version"] = str(CACHE_DB_VERSION)
        self._db = db

    def open_revid_map(self):
        return TdbRevisionIdMapCache(self._db)

    def open_logwalker(self):
        return TdbLogCache(self._db)

    def open_revision_cache(self):
        return TdbRevisionInfoCache(self._db)

    def open_parents(self):
        return TdbParentsCache(self._db)