/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to shamap.py

Implement TdbCache.missing_revisions().

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2009 Canonical Ltd
 
1
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
16
16
 
17
17
"""Map from Git sha's to Bazaar objects."""
18
18
 
 
19
from dulwich.objects import (
 
20
    sha_to_hex,
 
21
    hex_to_sha,
 
22
    )
 
23
import os
 
24
import threading
 
25
 
19
26
import bzrlib
20
 
 
21
 
from bzrlib.errors import NoSuchRevision
22
 
 
23
 
import os
 
27
from bzrlib import (
 
28
    trace,
 
29
    )
 
30
 
 
31
 
 
32
def get_cache_dir():
 
33
    try:
 
34
        from xdg.BaseDirectory import xdg_cache_home
 
35
    except ImportError:
 
36
        from bzrlib.config import config_dir
 
37
        ret = os.path.join(config_dir(), "git")
 
38
    else:
 
39
        ret = os.path.join(xdg_cache_home, "bazaar", "git")
 
40
    if not os.path.isdir(ret):
 
41
        os.makedirs(ret)
 
42
    return ret
24
43
 
25
44
 
26
45
def check_pysqlite_version(sqlite3):
27
46
    """Check that sqlite library is compatible.
28
47
 
29
48
    """
30
 
    if (sqlite3.sqlite_version_info[0] < 3 or 
31
 
            (sqlite3.sqlite_version_info[0] == 3 and 
 
49
    if (sqlite3.sqlite_version_info[0] < 3 or
 
50
            (sqlite3.sqlite_version_info[0] == 3 and
32
51
             sqlite3.sqlite_version_info[1] < 3)):
33
 
        warning('Needs at least sqlite 3.3.x')
 
52
        trace.warning('Needs at least sqlite 3.3.x')
34
53
        raise bzrlib.errors.BzrError("incompatible sqlite library")
35
54
 
36
55
try:
37
56
    try:
38
57
        import sqlite3
39
58
        check_pysqlite_version(sqlite3)
40
 
    except (ImportError, bzrlib.errors.BzrError), e: 
 
59
    except (ImportError, bzrlib.errors.BzrError), e:
41
60
        from pysqlite2 import dbapi2 as sqlite3
42
61
        check_pysqlite_version(sqlite3)
43
62
except:
44
 
    warning('Needs at least Python2.5 or Python2.4 with the pysqlite2 '
 
63
    trace.warning('Needs at least Python2.5 or Python2.4 with the pysqlite2 '
45
64
            'module')
46
65
    raise bzrlib.errors.BzrError("missing sqlite library")
47
66
 
48
67
 
 
68
_mapdbs = threading.local()
 
69
def mapdbs():
 
70
    """Get a cache for this thread's db connections."""
 
71
    try:
 
72
        return _mapdbs.cache
 
73
    except AttributeError:
 
74
        _mapdbs.cache = {}
 
75
        return _mapdbs.cache
 
76
 
 
77
 
49
78
class GitShaMap(object):
50
 
 
51
 
    def __init__(self, transport):
52
 
        self.transport = transport
53
 
        self.db = sqlite3.connect(
54
 
            os.path.join(self.transport.local_abspath("."), "git.db"))
 
79
    """Git<->Bzr revision id mapping database."""
 
80
 
 
81
    def add_entry(self, sha, type, type_data):
 
82
        """Add a new entry to the database.
 
83
        """
 
84
        raise NotImplementedError(self.add_entry)
 
85
 
 
86
    def add_entries(self, entries):
 
87
        """Add multiple new entries to the database.
 
88
        """
 
89
        for e in entries:
 
90
            self.add_entry(*e)
 
91
 
 
92
    def lookup_tree(self, fileid, revid):
 
93
        """Lookup the SHA of a git tree."""
 
94
        raise NotImplementedError(self.lookup_tree)
 
95
 
 
96
    def lookup_blob(self, fileid, revid):
 
97
        """Lookup a blob by the fileid it has in a bzr revision."""
 
98
        raise NotImplementedError(self.lookup_blob)
 
99
 
 
100
    def lookup_git_sha(self, sha):
 
101
        """Lookup a Git sha in the database.
 
102
 
 
103
        :param sha: Git object sha
 
104
        :return: (type, type_data) with type_data:
 
105
            revision: revid, tree sha
 
106
        """
 
107
        raise NotImplementedError(self.lookup_git_sha)
 
108
 
 
109
    def revids(self):
 
110
        """List the revision ids known."""
 
111
        raise NotImplementedError(self.revids)
 
112
 
 
113
    def missing_revisions(self, revids):
 
114
        """Return set of all the revisions that are not present."""
 
115
        present_revids = set(self.revids())
 
116
        if not isinstance(revids, set):
 
117
            revids = set(revids)
 
118
        return revids - present_revids
 
119
 
 
120
    def sha1s(self):
 
121
        """List the SHA1s."""
 
122
        raise NotImplementedError(self.sha1s)
 
123
 
 
124
    def commit(self):
 
125
        """Commit any pending changes."""
 
126
 
 
127
 
 
128
class DictGitShaMap(GitShaMap):
 
129
 
 
130
    def __init__(self):
 
131
        self.dict = {}
 
132
 
 
133
    def add_entry(self, sha, type, type_data):
 
134
        self.dict[sha] = (type, type_data)
 
135
 
 
136
    def lookup_git_sha(self, sha):
 
137
        return self.dict[sha]
 
138
 
 
139
    def lookup_tree(self, fileid, revid):
 
140
        for k, v in self.dict.iteritems():
 
141
            if v == ("tree", (fileid, revid)):
 
142
                return k
 
143
        raise KeyError((fileid, revid))
 
144
 
 
145
    def lookup_blob(self, fileid, revid):
 
146
        for k, v in self.dict.iteritems():
 
147
            if v == ("blob", (fileid, revid)):
 
148
                return k
 
149
        raise KeyError((fileid, revid))
 
150
 
 
151
    def revids(self):
 
152
        for key, (type, type_data) in self.dict.iteritems():
 
153
            if type == "commit":
 
154
                yield type_data[0]
 
155
 
 
156
    def sha1s(self):
 
157
        return self.dict.iterkeys()
 
158
 
 
159
 
 
160
class SqliteGitShaMap(GitShaMap):
 
161
 
 
162
    def __init__(self, path=None):
 
163
        self.path = path
 
164
        if path is None:
 
165
            self.db = sqlite3.connect(":memory:")
 
166
        else:
 
167
            if not mapdbs().has_key(path):
 
168
                mapdbs()[path] = sqlite3.connect(path)
 
169
            self.db = mapdbs()[path]
55
170
        self.db.executescript("""
56
171
        create table if not exists commits(sha1 text, revid text, tree_sha text);
57
172
        create index if not exists commit_sha1 on commits(sha1);
 
173
        create unique index if not exists commit_revid on commits(revid);
58
174
        create table if not exists blobs(sha1 text, fileid text, revid text);
59
175
        create index if not exists blobs_sha1 on blobs(sha1);
 
176
        create unique index if not exists blobs_fileid_revid on blobs(fileid, revid);
60
177
        create table if not exists trees(sha1 text, fileid text, revid text);
61
178
        create index if not exists trees_sha1 on trees(sha1);
 
179
        create unique index if not exists trees_fileid_revid on trees(fileid, revid);
62
180
""")
63
181
 
64
 
    def _parent_lookup(self, revid):
65
 
        return self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()[0].encode("utf-8")
 
182
    @classmethod
 
183
    def from_repository(cls, repository):
 
184
        try:
 
185
            transport = getattr(repository, "_transport", None)
 
186
            if transport is not None:
 
187
                return cls(os.path.join(transport.local_abspath("."), "git.db"))
 
188
        except bzrlib.errors.NotLocalUrl:
 
189
            pass
 
190
        return cls(os.path.join(get_cache_dir(), "remote.db"))
 
191
 
 
192
    def lookup_commit(self, revid):
 
193
        row = self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()
 
194
        if row is not None:
 
195
            return row[0].encode("utf-8")
 
196
        raise KeyError
 
197
 
 
198
    def commit(self):
 
199
        self.db.commit()
 
200
 
 
201
    def add_entries(self, entries):
 
202
        trees = []
 
203
        blobs = []
 
204
        for sha, type, type_data in entries:
 
205
            assert isinstance(type_data[0], str)
 
206
            assert isinstance(type_data[1], str)
 
207
            entry = (sha.decode("utf-8"), type_data[0].decode("utf-8"), 
 
208
                     type_data[1].decode("utf-8"))
 
209
            if type == "tree":
 
210
                trees.append(entry)
 
211
            elif type == "blob":
 
212
                blobs.append(entry)
 
213
            else:
 
214
                raise AssertionError
 
215
        if trees:
 
216
            self.db.executemany("replace into trees (sha1, fileid, revid) values (?, ?, ?)", trees)
 
217
        if blobs:
 
218
            self.db.executemany("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", blobs)
 
219
 
66
220
 
67
221
    def add_entry(self, sha, type, type_data):
68
222
        """Add a new entry to the database.
71
225
        assert isinstance(sha, str), "type was %r" % sha
72
226
        if type == "commit":
73
227
            self.db.execute("replace into commits (sha1, revid, tree_sha) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
74
 
        elif type == "blob":
75
 
            self.db.execute("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
76
 
        elif type == "tree":
77
 
            self.db.execute("replace into trees (sha1, fileid, revid) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
 
228
        elif type in ("blob", "tree"):
 
229
            self.db.execute("replace into %ss (sha1, fileid, revid) values (?, ?, ?)" % type, (sha, type_data[0], type_data[1]))
78
230
        else:
79
231
            raise AssertionError("Unknown type %s" % type)
80
232
 
 
233
    def lookup_tree(self, fileid, revid):
 
234
        row = self.db.execute("select sha1 from trees where fileid = ? and revid = ?", (fileid,revid)).fetchone()
 
235
        if row is None:
 
236
            raise KeyError((fileid, revid))
 
237
        return row[0].encode("utf-8")
 
238
 
 
239
    def lookup_blob(self, fileid, revid):
 
240
        row = self.db.execute("select sha1 from blobs where fileid = ? and revid = ?", (fileid, revid)).fetchone()
 
241
        if row is None:
 
242
            raise KeyError((fileid, revid))
 
243
        return row[0].encode("utf-8")
 
244
 
81
245
    def lookup_git_sha(self, sha):
82
246
        """Lookup a Git sha in the database.
83
247
 
85
249
        :return: (type, type_data) with type_data:
86
250
            revision: revid, tree sha
87
251
        """
 
252
        def format(type, row):
 
253
            return (type, (row[0].encode("utf-8"), row[1].encode("utf-8")))
88
254
        row = self.db.execute("select revid, tree_sha from commits where sha1 = ?", (sha,)).fetchone()
89
255
        if row is not None:
90
 
            return ("commit", row)
 
256
            return format("commit", row)
91
257
        row = self.db.execute("select fileid, revid from blobs where sha1 = ?", (sha,)).fetchone()
92
258
        if row is not None:
93
 
            return ("blob", row)
 
259
            return format("blob", row)
94
260
        row = self.db.execute("select fileid, revid from trees where sha1 = ?", (sha,)).fetchone()
95
261
        if row is not None:
96
 
            return ("tree", row)
 
262
            return format("tree", row)
97
263
        raise KeyError(sha)
98
264
 
99
265
    def revids(self):
 
266
        """List the revision ids known."""
100
267
        for row in self.db.execute("select revid from commits").fetchall():
101
 
            yield row[0]
 
268
            yield row[0].encode("utf-8")
 
269
 
 
270
    def sha1s(self):
 
271
        """List the SHA1s."""
 
272
        for table in ("blobs", "commits", "trees"):
 
273
            for row in self.db.execute("select sha1 from %s" % table).fetchall():
 
274
                yield row[0].encode("utf-8")
 
275
 
 
276
 
 
277
TDB_MAP_VERSION = 2
 
278
TDB_HASH_SIZE = 50000
 
279
 
 
280
 
 
281
class TdbGitShaMap(GitShaMap):
 
282
    """SHA Map that uses a TDB database.
 
283
 
 
284
    Entries:
 
285
 
 
286
    "git <sha1>" -> "<type> <type-data1> <type-data2>"
 
287
    "commit revid" -> "<sha1> <tree-id>"
 
288
    "tree fileid revid" -> "<sha1>"
 
289
    "blob fileid revid" -> "<sha1>"
 
290
    """
 
291
 
 
292
    def __init__(self, path=None):
 
293
        import tdb
 
294
        self.path = path
 
295
        if path is None:
 
296
            self.db = {}
 
297
        else:
 
298
            if not mapdbs().has_key(path):
 
299
                mapdbs()[path] = tdb.Tdb(path, TDB_HASH_SIZE, tdb.DEFAULT,
 
300
                                          os.O_RDWR|os.O_CREAT)
 
301
            self.db = mapdbs()[path]
 
302
        try:
 
303
            if int(self.db["version"]) != TDB_MAP_VERSION:
 
304
                trace.warning("SHA Map is incompatible (%s -> %d), rebuilding database.",
 
305
                              self.db["version"], TDB_MAP_VERSION)
 
306
                self.db.clear()
 
307
                self.db["version"] = str(TDB_MAP_VERSION)
 
308
        except KeyError:
 
309
            self.db["version"] = str(TDB_MAP_VERSION)
 
310
 
 
311
    @classmethod
 
312
    def from_repository(cls, repository):
 
313
        try:
 
314
            transport = getattr(repository, "_transport", None)
 
315
            if transport is not None:
 
316
                return cls(os.path.join(transport.local_abspath("."), "git.tdb"))
 
317
        except bzrlib.errors.NotLocalUrl:
 
318
            pass
 
319
        return cls(os.path.join(get_cache_dir(), "remote.tdb"))
 
320
 
 
321
    def lookup_commit(self, revid):
 
322
        return sha_to_hex(self.db["commit\0" + revid][:20])
 
323
 
 
324
    def commit(self):
 
325
        pass
 
326
 
 
327
    def add_entry(self, hexsha, type, type_data):
 
328
        """Add a new entry to the database.
 
329
        """
 
330
        if hexsha is None:
 
331
            sha = ""
 
332
        else:
 
333
            sha = hex_to_sha(hexsha)
 
334
            self.db["git\0" + sha] = "\0".join((type, type_data[0], type_data[1]))
 
335
        if type == "commit":
 
336
            self.db["commit\0" + type_data[0]] = "\0".join((sha, type_data[1]))
 
337
        else:
 
338
            self.db["\0".join((type, type_data[0], type_data[1]))] = sha
 
339
 
 
340
    def lookup_tree(self, fileid, revid):
 
341
        sha = self.db["\0".join(("tree", fileid, revid))]
 
342
        if sha == "":
 
343
            return None
 
344
        else:
 
345
            return sha_to_hex(sha)
 
346
 
 
347
    def lookup_blob(self, fileid, revid):
 
348
        return sha_to_hex(self.db["\0".join(("blob", fileid, revid))])
 
349
 
 
350
    def lookup_git_sha(self, sha):
 
351
        """Lookup a Git sha in the database.
 
352
 
 
353
        :param sha: Git object sha
 
354
        :return: (type, type_data) with type_data:
 
355
            revision: revid, tree sha
 
356
        """
 
357
        if len(sha) == 40:
 
358
            sha = hex_to_sha(sha)
 
359
        data = self.db["git\0" + sha].split("\0")
 
360
        return (data[0], (data[1], data[2]))
 
361
 
 
362
    def missing_revisions(self, revids):
 
363
        ret = set()
 
364
        for revid in revids:
 
365
            if self.db.get("commit\0" + revid) is None:
 
366
                ret.add(revid)
 
367
        return ret
 
368
 
 
369
    def revids(self):
 
370
        """List the revision ids known."""
 
371
        for key in self.db.iterkeys():
 
372
            if key.startswith("commit\0"):
 
373
                yield key[7:]
 
374
 
 
375
    def sha1s(self):
 
376
        """List the SHA1s."""
 
377
        for key in self.db.iterkeys():
 
378
            if key.startswith("git\0"):
 
379
                yield sha_to_hex(key[4:])