/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

Depend on newer version of Dulwich.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Map from Git sha's to Bazaar objects."""
 
18
 
 
19
from dulwich.objects import (
 
20
    sha_to_hex,
 
21
    hex_to_sha,
 
22
    )
 
23
import os
 
24
import threading
 
25
 
 
26
import bzrlib
 
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
 
43
 
 
44
 
 
45
def check_pysqlite_version(sqlite3):
 
46
    """Check that sqlite library is compatible.
 
47
 
 
48
    """
 
49
    if (sqlite3.sqlite_version_info[0] < 3 or
 
50
            (sqlite3.sqlite_version_info[0] == 3 and
 
51
             sqlite3.sqlite_version_info[1] < 3)):
 
52
        trace.warning('Needs at least sqlite 3.3.x')
 
53
        raise bzrlib.errors.BzrError("incompatible sqlite library")
 
54
 
 
55
try:
 
56
    try:
 
57
        import sqlite3
 
58
        check_pysqlite_version(sqlite3)
 
59
    except (ImportError, bzrlib.errors.BzrError), e:
 
60
        from pysqlite2 import dbapi2 as sqlite3
 
61
        check_pysqlite_version(sqlite3)
 
62
except:
 
63
    trace.warning('Needs at least Python2.5 or Python2.4 with the pysqlite2 '
 
64
            'module')
 
65
    raise bzrlib.errors.BzrError("missing sqlite library")
 
66
 
 
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
 
 
78
class GitShaMap(object):
 
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 start_write_group(self):
 
125
        """Start writing changes."""
 
126
 
 
127
    def commit_write_group(self):
 
128
        """Commit any pending changes."""
 
129
 
 
130
    def abort_write_group(self):
 
131
        """Abort any pending changes."""
 
132
 
 
133
 
 
134
class DictGitShaMap(GitShaMap):
 
135
 
 
136
    def __init__(self):
 
137
        self.dict = {}
 
138
 
 
139
    def add_entry(self, sha, type, type_data):
 
140
        self.dict[sha] = (type, type_data)
 
141
 
 
142
    def lookup_git_sha(self, sha):
 
143
        return self.dict[sha]
 
144
 
 
145
    def lookup_tree(self, fileid, revid):
 
146
        for k, v in self.dict.iteritems():
 
147
            if v == ("tree", (fileid, revid)):
 
148
                return k
 
149
        raise KeyError((fileid, revid))
 
150
 
 
151
    def lookup_blob(self, fileid, revid):
 
152
        for k, v in self.dict.iteritems():
 
153
            if v == ("blob", (fileid, revid)):
 
154
                return k
 
155
        raise KeyError((fileid, revid))
 
156
 
 
157
    def revids(self):
 
158
        for key, (type, type_data) in self.dict.iteritems():
 
159
            if type == "commit":
 
160
                yield type_data[0]
 
161
 
 
162
    def sha1s(self):
 
163
        return self.dict.iterkeys()
 
164
 
 
165
 
 
166
class SqliteGitShaMap(GitShaMap):
 
167
 
 
168
    def __init__(self, path=None):
 
169
        self.path = path
 
170
        if path is None:
 
171
            self.db = sqlite3.connect(":memory:")
 
172
        else:
 
173
            if not mapdbs().has_key(path):
 
174
                mapdbs()[path] = sqlite3.connect(path)
 
175
            self.db = mapdbs()[path]
 
176
        self.db.text_factory = str
 
177
        self.db.executescript("""
 
178
        create table if not exists commits(sha1 text, revid text, tree_sha text);
 
179
        create index if not exists commit_sha1 on commits(sha1);
 
180
        create unique index if not exists commit_revid on commits(revid);
 
181
        create table if not exists blobs(sha1 text, fileid text, revid text);
 
182
        create index if not exists blobs_sha1 on blobs(sha1);
 
183
        create unique index if not exists blobs_fileid_revid on blobs(fileid, revid);
 
184
        create table if not exists trees(sha1 text, fileid text, revid text);
 
185
        create index if not exists trees_sha1 on trees(sha1);
 
186
        create unique index if not exists trees_fileid_revid on trees(fileid, revid);
 
187
""")
 
188
 
 
189
    @classmethod
 
190
    def from_repository(cls, repository):
 
191
        try:
 
192
            transport = getattr(repository, "_transport", None)
 
193
            if transport is not None:
 
194
                return cls(os.path.join(transport.local_abspath("."), "git.db"))
 
195
        except bzrlib.errors.NotLocalUrl:
 
196
            pass
 
197
        return cls(os.path.join(get_cache_dir(), "remote.db"))
 
198
 
 
199
    def lookup_commit(self, revid):
 
200
        row = self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()
 
201
        if row is not None:
 
202
            return row[0]
 
203
        raise KeyError
 
204
 
 
205
    def commit_write_group(self):
 
206
        self.db.commit()
 
207
 
 
208
    def add_entries(self, entries):
 
209
        trees = []
 
210
        blobs = []
 
211
        for sha, type, type_data in entries:
 
212
            assert isinstance(type_data[0], str)
 
213
            assert isinstance(type_data[1], str)
 
214
            entry = (sha, type_data[0], type_data[1])
 
215
            if type == "tree":
 
216
                trees.append(entry)
 
217
            elif type == "blob":
 
218
                blobs.append(entry)
 
219
            else:
 
220
                raise AssertionError
 
221
        if trees:
 
222
            self.db.executemany("replace into trees (sha1, fileid, revid) values (?, ?, ?)", trees)
 
223
        if blobs:
 
224
            self.db.executemany("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", blobs)
 
225
 
 
226
 
 
227
    def add_entry(self, sha, type, type_data):
 
228
        """Add a new entry to the database.
 
229
        """
 
230
        assert isinstance(type_data, tuple)
 
231
        assert isinstance(sha, str), "type was %r" % sha
 
232
        if type == "commit":
 
233
            self.db.execute("replace into commits (sha1, revid, tree_sha) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
 
234
        elif type in ("blob", "tree"):
 
235
            self.db.execute("replace into %ss (sha1, fileid, revid) values (?, ?, ?)" % type, (sha, type_data[0], type_data[1]))
 
236
        else:
 
237
            raise AssertionError("Unknown type %s" % type)
 
238
 
 
239
    def lookup_tree(self, fileid, revid):
 
240
        row = self.db.execute("select sha1 from trees where fileid = ? and revid = ?", (fileid,revid)).fetchone()
 
241
        if row is None:
 
242
            raise KeyError((fileid, revid))
 
243
        return row[0]
 
244
 
 
245
    def lookup_blob(self, fileid, revid):
 
246
        row = self.db.execute("select sha1 from blobs where fileid = ? and revid = ?", (fileid, revid)).fetchone()
 
247
        if row is None:
 
248
            raise KeyError((fileid, revid))
 
249
        return row[0]
 
250
 
 
251
    def lookup_git_sha(self, sha):
 
252
        """Lookup a Git sha in the database.
 
253
 
 
254
        :param sha: Git object sha
 
255
        :return: (type, type_data) with type_data:
 
256
            revision: revid, tree sha
 
257
        """
 
258
        def format(type, row):
 
259
            return (type, (row[0], row[1]))
 
260
        row = self.db.execute("select revid, tree_sha from commits where sha1 = ?", (sha,)).fetchone()
 
261
        if row is not None:
 
262
            return format("commit", row)
 
263
        row = self.db.execute("select fileid, revid from blobs where sha1 = ?", (sha,)).fetchone()
 
264
        if row is not None:
 
265
            return format("blob", row)
 
266
        row = self.db.execute("select fileid, revid from trees where sha1 = ?", (sha,)).fetchone()
 
267
        if row is not None:
 
268
            return format("tree", row)
 
269
        raise KeyError(sha)
 
270
 
 
271
    def revids(self):
 
272
        """List the revision ids known."""
 
273
        for row in self.db.execute("select revid from commits").fetchall():
 
274
            yield row[0]
 
275
 
 
276
    def sha1s(self):
 
277
        """List the SHA1s."""
 
278
        for table in ("blobs", "commits", "trees"):
 
279
            for row in self.db.execute("select sha1 from %s" % table).fetchall():
 
280
                yield row[0]
 
281
 
 
282
 
 
283
TDB_MAP_VERSION = 2
 
284
TDB_HASH_SIZE = 50000
 
285
 
 
286
 
 
287
class TdbGitShaMap(GitShaMap):
 
288
    """SHA Map that uses a TDB database.
 
289
 
 
290
    Entries:
 
291
 
 
292
    "git <sha1>" -> "<type> <type-data1> <type-data2>"
 
293
    "commit revid" -> "<sha1> <tree-id>"
 
294
    "tree fileid revid" -> "<sha1>"
 
295
    "blob fileid revid" -> "<sha1>"
 
296
    """
 
297
 
 
298
    def __init__(self, path=None):
 
299
        import tdb
 
300
        self.path = path
 
301
        if path is None:
 
302
            self.db = {}
 
303
        else:
 
304
            if not mapdbs().has_key(path):
 
305
                mapdbs()[path] = tdb.Tdb(path, TDB_HASH_SIZE, tdb.DEFAULT,
 
306
                                          os.O_RDWR|os.O_CREAT)
 
307
            self.db = mapdbs()[path]
 
308
        try:
 
309
            if int(self.db["version"]) != TDB_MAP_VERSION:
 
310
                trace.warning("SHA Map is incompatible (%s -> %d), rebuilding database.",
 
311
                              self.db["version"], TDB_MAP_VERSION)
 
312
                self.db.clear()
 
313
                self.db["version"] = str(TDB_MAP_VERSION)
 
314
        except KeyError:
 
315
            self.db["version"] = str(TDB_MAP_VERSION)
 
316
 
 
317
    @classmethod
 
318
    def from_repository(cls, repository):
 
319
        try:
 
320
            transport = getattr(repository, "_transport", None)
 
321
            if transport is not None:
 
322
                return cls(os.path.join(transport.local_abspath("."), "git.tdb"))
 
323
        except bzrlib.errors.NotLocalUrl:
 
324
            pass
 
325
        return cls(os.path.join(get_cache_dir(), "remote.tdb"))
 
326
 
 
327
    def lookup_commit(self, revid):
 
328
        return sha_to_hex(self.db["commit\0" + revid][:20])
 
329
 
 
330
    def add_entry(self, hexsha, type, type_data):
 
331
        """Add a new entry to the database.
 
332
        """
 
333
        if hexsha is None:
 
334
            sha = ""
 
335
        else:
 
336
            sha = hex_to_sha(hexsha)
 
337
            self.db["git\0" + sha] = "\0".join((type, type_data[0], type_data[1]))
 
338
        if type == "commit":
 
339
            self.db["commit\0" + type_data[0]] = "\0".join((sha, type_data[1]))
 
340
        else:
 
341
            self.db["\0".join((type, type_data[0], type_data[1]))] = sha
 
342
 
 
343
    def lookup_tree(self, fileid, revid):
 
344
        sha = self.db["\0".join(("tree", fileid, revid))]
 
345
        if sha == "":
 
346
            return None
 
347
        else:
 
348
            return sha_to_hex(sha)
 
349
 
 
350
    def lookup_blob(self, fileid, revid):
 
351
        return sha_to_hex(self.db["\0".join(("blob", fileid, revid))])
 
352
 
 
353
    def lookup_git_sha(self, sha):
 
354
        """Lookup a Git sha in the database.
 
355
 
 
356
        :param sha: Git object sha
 
357
        :return: (type, type_data) with type_data:
 
358
            revision: revid, tree sha
 
359
        """
 
360
        if len(sha) == 40:
 
361
            sha = hex_to_sha(sha)
 
362
        data = self.db["git\0" + sha].split("\0")
 
363
        return (data[0], (data[1], data[2]))
 
364
 
 
365
    def missing_revisions(self, revids):
 
366
        ret = set()
 
367
        for revid in revids:
 
368
            if self.db.get("commit\0" + revid) is None:
 
369
                ret.add(revid)
 
370
        return ret
 
371
 
 
372
    def revids(self):
 
373
        """List the revision ids known."""
 
374
        for key in self.db.iterkeys():
 
375
            if key.startswith("commit\0"):
 
376
                yield key[7:]
 
377
 
 
378
    def sha1s(self):
 
379
        """List the SHA1s."""
 
380
        for key in self.db.iterkeys():
 
381
            if key.startswith("git\0"):
 
382
                yield sha_to_hex(key[4:])