/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 network name.

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