/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 GitRepository.revision_graph_can_have_wrong_parents().

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
    )
19
23
import os
 
24
import threading
20
25
 
21
26
import bzrlib
 
27
from bzrlib import (
 
28
    trace,
 
29
    )
22
30
from bzrlib.errors import (
23
31
    NoSuchRevision,
24
32
    )
25
33
 
26
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
 
27
46
def check_pysqlite_version(sqlite3):
28
47
    """Check that sqlite library is compatible.
29
48
 
47
66
    raise bzrlib.errors.BzrError("missing sqlite library")
48
67
 
49
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
 
50
79
class GitShaMap(object):
51
80
    """Git<->Bzr revision id mapping database."""
52
81
 
55
84
        """
56
85
        raise NotImplementedError(self.add_entry)
57
86
 
58
 
    def lookup_tree(self, path, revid):
 
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):
59
94
        """Lookup the SHA of a git tree."""
60
95
        raise NotImplementedError(self.lookup_tree)
61
96
 
62
97
    def lookup_blob(self, fileid, revid):
 
98
        """Lookup a blob by the fileid it has in a bzr revision."""
63
99
        raise NotImplementedError(self.lookup_blob)
64
100
 
65
101
    def lookup_git_sha(self, sha):
75
111
        """List the revision ids known."""
76
112
        raise NotImplementedError(self.revids)
77
113
 
 
114
    def sha1s(Self):
 
115
        """List the SHA1s."""
 
116
        raise NotImplementedError(self.sha1s)
 
117
 
78
118
    def commit(self):
79
119
        """Commit any pending changes."""
80
120
 
90
130
    def lookup_git_sha(self, sha):
91
131
        return self.dict[sha]
92
132
 
93
 
    def lookup_tree(self, path, revid):
 
133
    def lookup_tree(self, fileid, revid):
94
134
        for k, v in self.dict.iteritems():
95
 
            if v == ("tree", (path, revid)):
 
135
            if v == ("tree", (fileid, revid)):
96
136
                return k
97
 
        raise KeyError((path, revid))
 
137
        raise KeyError((fileid, revid))
98
138
 
99
139
    def lookup_blob(self, fileid, revid):
100
140
        for k, v in self.dict.iteritems():
107
147
            if type == "commit":
108
148
                yield type_data[0]
109
149
 
 
150
    def sha1s(self):
 
151
        return self.dict.iterkeys()
 
152
 
110
153
 
111
154
class SqliteGitShaMap(GitShaMap):
112
155
 
113
 
    def __init__(self, transport=None):
114
 
        self.transport = transport
115
 
        if transport is None:
 
156
    def __init__(self, path=None):
 
157
        self.path = path
 
158
        if path is None:
116
159
            self.db = sqlite3.connect(":memory:")
117
160
        else:
118
 
            self.db = sqlite3.connect(
119
 
                os.path.join(self.transport.local_abspath("."), "git.db"))
 
161
            if not mapdbs().has_key(path):
 
162
                mapdbs()[path] = sqlite3.connect(path)
 
163
            self.db = mapdbs()[path]    
120
164
        self.db.executescript("""
121
165
        create table if not exists commits(sha1 text, revid text, tree_sha text);
122
166
        create index if not exists commit_sha1 on commits(sha1);
124
168
        create table if not exists blobs(sha1 text, fileid text, revid text);
125
169
        create index if not exists blobs_sha1 on blobs(sha1);
126
170
        create unique index if not exists blobs_fileid_revid on blobs(fileid, revid);
127
 
        create table if not exists trees(sha1 text, path text, revid text);
 
171
        create table if not exists trees(sha1 text, fileid text, revid text);
128
172
        create index if not exists trees_sha1 on trees(sha1);
129
 
        create unique index if not exists trees_path_revid on trees(path, revid);
 
173
        create unique index if not exists trees_fileid_revid on trees(fileid, revid);
130
174
""")
131
175
 
132
 
    def _parent_lookup(self, revid):
133
 
        return self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()[0].encode("utf-8")
 
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
134
191
 
135
192
    def commit(self):
136
193
        self.db.commit()
137
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
 
138
215
    def add_entry(self, sha, type, type_data):
139
216
        """Add a new entry to the database.
140
217
        """
142
219
        assert isinstance(sha, str), "type was %r" % sha
143
220
        if type == "commit":
144
221
            self.db.execute("replace into commits (sha1, revid, tree_sha) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
145
 
        elif type == "blob":
146
 
            self.db.execute("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
147
 
        elif type == "tree":
148
 
            self.db.execute("replace into trees (sha1, path, revid) 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]))
149
224
        else:
150
225
            raise AssertionError("Unknown type %s" % type)
151
226
 
152
 
    def lookup_tree(self, path, revid):
153
 
        row = self.db.execute("select sha1 from trees where path = ? and revid = ?", (path,revid)).fetchone()
 
227
    def lookup_tree(self, fileid, revid):
 
228
        row = self.db.execute("select sha1 from trees where fileid = ? and revid = ?", (fileid,revid)).fetchone()
154
229
        if row is None:
155
 
            raise KeyError((path, revid))
156
 
        return row[0]
 
230
            raise KeyError((fileid, revid))
 
231
        return row[0].encode("utf-8")
157
232
 
158
233
    def lookup_blob(self, fileid, revid):
159
234
        row = self.db.execute("select sha1 from blobs where fileid = ? and revid = ?", (fileid, revid)).fetchone()
160
235
        if row is None:
161
236
            raise KeyError((fileid, revid))
162
 
        return row[0]
 
237
        return row[0].encode("utf-8")
163
238
 
164
239
    def lookup_git_sha(self, sha):
165
240
        """Lookup a Git sha in the database.
168
243
        :return: (type, type_data) with type_data:
169
244
            revision: revid, tree sha
170
245
        """
 
246
        def format(type, row):
 
247
            return (type, (row[0].encode("utf-8"), row[1].encode("utf-8")))
171
248
        row = self.db.execute("select revid, tree_sha from commits where sha1 = ?", (sha,)).fetchone()
172
249
        if row is not None:
173
 
            return ("commit", row)
 
250
            return format("commit", row)
174
251
        row = self.db.execute("select fileid, revid from blobs where sha1 = ?", (sha,)).fetchone()
175
252
        if row is not None:
176
 
            return ("blob", row)
177
 
        row = self.db.execute("select path, revid from trees where sha1 = ?", (sha,)).fetchone()
 
253
            return format("blob", row)
 
254
        row = self.db.execute("select fileid, revid from trees where sha1 = ?", (sha,)).fetchone()
178
255
        if row is not None:
179
 
            return ("tree", row)
 
256
            return format("tree", row)
180
257
        raise KeyError(sha)
181
258
 
182
259
    def revids(self):
183
260
        """List the revision ids known."""
184
261
        for row in self.db.execute("select revid from commits").fetchall():
185
 
            yield row[0]
 
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
TDB_HASH_SIZE = 10000
 
273
 
 
274
 
 
275
class TdbGitShaMap(GitShaMap):
 
276
    """SHA Map that uses a TDB database.
 
277
 
 
278
    Entries:
 
279
 
 
280
    "git <sha1>" -> "<type> <type-data1> <type-data2>"
 
281
    "commit revid" -> "<sha1> <tree-id>"
 
282
    "tree fileid revid" -> "<sha1>"
 
283
    "blob fileid revid" -> "<sha1>"
 
284
    """
 
285
 
 
286
    def __init__(self, path=None):
 
287
        import tdb
 
288
        self.path = path
 
289
        if path is None:
 
290
            self.db = {}
 
291
        else:
 
292
            if not mapdbs().has_key(path):
 
293
                mapdbs()[path] = tdb.Tdb(path, TDB_HASH_SIZE, tdb.DEFAULT, 
 
294
                                          os.O_RDWR|os.O_CREAT)
 
295
            self.db = mapdbs()[path]    
 
296
        if not "version" in self.db:
 
297
            self.db["version"] = str(TDB_MAP_VERSION)
 
298
        else:
 
299
            if int(self.db["version"]) != TDB_MAP_VERSION:
 
300
                trace.warning("SHA Map is incompatible (%s -> %d), rebuilding database.",
 
301
                              self.db["version"], TDB_MAP_VERSION)
 
302
                self.db.clear()
 
303
            self.db["version"] = str(TDB_MAP_VERSION)
 
304
 
 
305
    @classmethod
 
306
    def from_repository(cls, repository):
 
307
        try:
 
308
            transport = getattr(repository, "_transport", None)
 
309
            if transport is not None:
 
310
                return cls(os.path.join(transport.local_abspath("."), "git.tdb"))
 
311
        except bzrlib.errors.NotLocalUrl:
 
312
            pass
 
313
        return cls(os.path.join(get_cache_dir(), "remote.tdb"))
 
314
 
 
315
    def lookup_commit(self, revid):
 
316
        return sha_to_hex(self.db["commit\0" + revid][:20])
 
317
 
 
318
    def commit(self):
 
319
        pass
 
320
 
 
321
    def add_entry(self, sha, type, type_data):
 
322
        """Add a new entry to the database.
 
323
        """
 
324
        self.db["git\0" + hex_to_sha(sha)] = "\0".join((type, type_data[0], type_data[1]))
 
325
        if type == "commit":
 
326
            self.db["commit\0" + type_data[0]] = "\0".join((hex_to_sha(sha), type_data[1]))
 
327
        else:
 
328
            self.db["\0".join((type, type_data[0], type_data[1]))] = hex_to_sha(sha)
 
329
 
 
330
    def lookup_tree(self, fileid, revid):
 
331
        return sha_to_hex(self.db["\0".join(("tree", fileid, revid))])
 
332
 
 
333
    def lookup_blob(self, fileid, revid):
 
334
        return sha_to_hex(self.db["\0".join(("blob", fileid, revid))])
 
335
 
 
336
    def lookup_git_sha(self, sha):
 
337
        """Lookup a Git sha in the database.
 
338
 
 
339
        :param sha: Git object sha
 
340
        :return: (type, type_data) with type_data:
 
341
            revision: revid, tree sha
 
342
        """
 
343
        data = self.db["git\0" + hex_to_sha(sha)].split("\0")
 
344
        return (data[0], (data[1], data[2]))
 
345
 
 
346
    def revids(self):
 
347
        """List the revision ids known."""
 
348
        for key in self.db.iterkeys():
 
349
            if key.startswith("commit\0"):
 
350
                yield key[7:]
 
351
 
 
352
    def sha1s(self):
 
353
        """List the SHA1s."""
 
354
        for key in self.db.iterkeys():
 
355
            if key.startswith("git\0"):
 
356
                yield sha_to_hex(key[4:])