17
17
"""Map from Git sha's to Bazaar objects."""
19
from dulwich.objects import (
21
from bzrlib.errors import NoSuchRevision
34
from xdg.BaseDirectory import xdg_cache_home
36
from bzrlib.config import config_dir
37
ret = os.path.join(config_dir(), "git")
39
ret = os.path.join(xdg_cache_home, "bazaar", "git")
40
if not os.path.isdir(ret):
26
45
def check_pysqlite_version(sqlite3):
27
46
"""Check that sqlite library is compatible.
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")
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)
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 '
46
65
raise bzrlib.errors.BzrError("missing sqlite library")
68
_mapdbs = threading.local()
70
"""Get a cache for this thread's db connections."""
73
except AttributeError:
49
78
class GitShaMap(object):
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."""
81
def add_entry(self, sha, type, type_data):
82
"""Add a new entry to the database.
84
raise NotImplementedError(self.add_entry)
86
def add_entries(self, entries):
87
"""Add multiple new entries to the database.
92
def lookup_tree(self, fileid, revid):
93
"""Lookup the SHA of a git tree."""
94
raise NotImplementedError(self.lookup_tree)
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)
100
def lookup_git_sha(self, sha):
101
"""Lookup a Git sha in the database.
103
:param sha: Git object sha
104
:return: (type, type_data) with type_data:
105
revision: revid, tree sha
107
raise NotImplementedError(self.lookup_git_sha)
110
"""List the revision ids known."""
111
raise NotImplementedError(self.revids)
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):
118
return revids - present_revids
121
"""List the SHA1s."""
122
raise NotImplementedError(self.sha1s)
124
def start_write_group(self):
125
"""Start writing changes."""
127
def commit_write_group(self):
128
"""Commit any pending changes."""
130
def abort_write_group(self):
131
"""Abort any pending changes."""
134
class DictGitShaMap(GitShaMap):
139
def add_entry(self, sha, type, type_data):
140
self.dict[sha] = (type, type_data)
142
def lookup_git_sha(self, sha):
143
return self.dict[sha]
145
def lookup_tree(self, fileid, revid):
146
for k, v in self.dict.iteritems():
147
if v == ("tree", (fileid, revid)):
149
raise KeyError((fileid, revid))
151
def lookup_blob(self, fileid, revid):
152
for k, v in self.dict.iteritems():
153
if v == ("blob", (fileid, revid)):
155
raise KeyError((fileid, revid))
158
for key, (type, type_data) in self.dict.iteritems():
163
return self.dict.iterkeys()
166
class SqliteGitShaMap(GitShaMap):
168
def __init__(self, path=None):
171
self.db = sqlite3.connect(":memory:")
173
if not mapdbs().has_key(path):
174
mapdbs()[path] = sqlite3.connect(path)
175
self.db = mapdbs()[path]
55
176
self.db.executescript("""
56
177
create table if not exists commits(sha1 text, revid text, tree_sha text);
57
178
create index if not exists commit_sha1 on commits(sha1);
179
create unique index if not exists commit_revid on commits(revid);
58
180
create table if not exists blobs(sha1 text, fileid text, revid text);
59
181
create index if not exists blobs_sha1 on blobs(sha1);
182
create unique index if not exists blobs_fileid_revid on blobs(fileid, revid);
60
183
create table if not exists trees(sha1 text, fileid text, revid text);
61
184
create index if not exists trees_sha1 on trees(sha1);
185
create unique index if not exists trees_fileid_revid on trees(fileid, revid);
64
def _parent_lookup(self, revid):
65
return self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()[0].encode("utf-8")
189
def from_repository(cls, repository):
191
transport = getattr(repository, "_transport", None)
192
if transport is not None:
193
return cls(os.path.join(transport.local_abspath("."), "git.db"))
194
except bzrlib.errors.NotLocalUrl:
196
return cls(os.path.join(get_cache_dir(), "remote.db"))
198
def lookup_commit(self, revid):
199
row = self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()
201
return row[0].encode("utf-8")
204
def commit_write_group(self):
207
def add_entries(self, entries):
210
for sha, type, type_data in entries:
211
assert isinstance(type_data[0], str)
212
assert isinstance(type_data[1], str)
213
entry = (sha.decode("utf-8"), type_data[0].decode("utf-8"),
214
type_data[1].decode("utf-8"))
222
self.db.executemany("replace into trees (sha1, fileid, revid) values (?, ?, ?)", trees)
224
self.db.executemany("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", blobs)
67
227
def add_entry(self, sha, type, type_data):
68
228
"""Add a new entry to the database.
71
231
assert isinstance(sha, str), "type was %r" % sha
72
232
if type == "commit":
73
233
self.db.execute("replace into commits (sha1, revid, tree_sha) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
75
self.db.execute("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
77
self.db.execute("replace into trees (sha1, fileid, revid) 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]))
79
237
raise AssertionError("Unknown type %s" % type)
239
def lookup_tree(self, fileid, revid):
240
row = self.db.execute("select sha1 from trees where fileid = ? and revid = ?", (fileid,revid)).fetchone()
242
raise KeyError((fileid, revid))
243
return row[0].encode("utf-8")
245
def lookup_blob(self, fileid, revid):
246
row = self.db.execute("select sha1 from blobs where fileid = ? and revid = ?", (fileid, revid)).fetchone()
248
raise KeyError((fileid, revid))
249
return row[0].encode("utf-8")
81
251
def lookup_git_sha(self, sha):
82
252
"""Lookup a Git sha in the database.
85
255
:return: (type, type_data) with type_data:
86
256
revision: revid, tree sha
258
def format(type, row):
259
return (type, (row[0].encode("utf-8"), row[1].encode("utf-8")))
88
260
row = self.db.execute("select revid, tree_sha from commits where sha1 = ?", (sha,)).fetchone()
89
261
if row is not None:
90
return ("commit", row)
262
return format("commit", row)
91
263
row = self.db.execute("select fileid, revid from blobs where sha1 = ?", (sha,)).fetchone()
92
264
if row is not None:
265
return format("blob", row)
94
266
row = self.db.execute("select fileid, revid from trees where sha1 = ?", (sha,)).fetchone()
95
267
if row is not None:
268
return format("tree", row)
97
269
raise KeyError(sha)
272
"""List the revision ids known."""
100
273
for row in self.db.execute("select revid from commits").fetchall():
274
yield row[0].encode("utf-8")
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].encode("utf-8")
284
TDB_HASH_SIZE = 50000
287
class TdbGitShaMap(GitShaMap):
288
"""SHA Map that uses a TDB database.
292
"git <sha1>" -> "<type> <type-data1> <type-data2>"
293
"commit revid" -> "<sha1> <tree-id>"
294
"tree fileid revid" -> "<sha1>"
295
"blob fileid revid" -> "<sha1>"
298
def __init__(self, path=None):
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]
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)
313
self.db["version"] = str(TDB_MAP_VERSION)
315
self.db["version"] = str(TDB_MAP_VERSION)
318
def from_repository(cls, repository):
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:
325
return cls(os.path.join(get_cache_dir(), "remote.tdb"))
327
def lookup_commit(self, revid):
328
return sha_to_hex(self.db["commit\0" + revid][:20])
330
def add_entry(self, hexsha, type, type_data):
331
"""Add a new entry to the database.
336
sha = hex_to_sha(hexsha)
337
self.db["git\0" + sha] = "\0".join((type, type_data[0], type_data[1]))
339
self.db["commit\0" + type_data[0]] = "\0".join((sha, type_data[1]))
341
self.db["\0".join((type, type_data[0], type_data[1]))] = sha
343
def lookup_tree(self, fileid, revid):
344
sha = self.db["\0".join(("tree", fileid, revid))]
348
return sha_to_hex(sha)
350
def lookup_blob(self, fileid, revid):
351
return sha_to_hex(self.db["\0".join(("blob", fileid, revid))])
353
def lookup_git_sha(self, sha):
354
"""Lookup a Git sha in the database.
356
:param sha: Git object sha
357
:return: (type, type_data) with type_data:
358
revision: revid, tree sha
361
sha = hex_to_sha(sha)
362
data = self.db["git\0" + sha].split("\0")
363
return (data[0], (data[1], data[2]))
365
def missing_revisions(self, revids):
368
if self.db.get("commit\0" + revid) is None:
373
"""List the revision ids known."""
374
for key in self.db.iterkeys():
375
if key.startswith("commit\0"):
379
"""List the SHA1s."""
380
for key in self.db.iterkeys():
381
if key.startswith("git\0"):
382
yield sha_to_hex(key[4:])