1
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
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.
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.
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
17
"""Map from Git sha's to Bazaar objects."""
19
from dulwich.objects import (
30
from bzrlib.errors import (
35
def check_pysqlite_version(sqlite3):
36
"""Check that sqlite library is compatible.
39
if (sqlite3.sqlite_version_info[0] < 3 or
40
(sqlite3.sqlite_version_info[0] == 3 and
41
sqlite3.sqlite_version_info[1] < 3)):
42
warning('Needs at least sqlite 3.3.x')
43
raise bzrlib.errors.BzrError("incompatible sqlite library")
48
check_pysqlite_version(sqlite3)
49
except (ImportError, bzrlib.errors.BzrError), e:
50
from pysqlite2 import dbapi2 as sqlite3
51
check_pysqlite_version(sqlite3)
53
warning('Needs at least Python2.5 or Python2.4 with the pysqlite2 '
55
raise bzrlib.errors.BzrError("missing sqlite library")
58
_mapdbs = threading.local()
60
"""Get a cache for this thread's db connections."""
63
except AttributeError:
68
class GitShaMap(object):
69
"""Git<->Bzr revision id mapping database."""
71
def add_entry(self, sha, type, type_data):
72
"""Add a new entry to the database.
74
raise NotImplementedError(self.add_entry)
76
def add_entries(self, entries):
77
"""Add multiple new entries to the database.
82
def lookup_tree(self, fileid, revid):
83
"""Lookup the SHA of a git tree."""
84
raise NotImplementedError(self.lookup_tree)
86
def lookup_blob(self, fileid, revid):
87
"""Lookup a blob by the fileid it has in a bzr revision."""
88
raise NotImplementedError(self.lookup_blob)
90
def lookup_git_sha(self, sha):
91
"""Lookup a Git sha in the database.
93
:param sha: Git object sha
94
:return: (type, type_data) with type_data:
95
revision: revid, tree sha
97
raise NotImplementedError(self.lookup_git_sha)
100
"""List the revision ids known."""
101
raise NotImplementedError(self.revids)
104
"""List the SHA1s."""
105
raise NotImplementedError(self.sha1s)
108
"""Commit any pending changes."""
111
class DictGitShaMap(GitShaMap):
116
def add_entry(self, sha, type, type_data):
117
self.dict[sha] = (type, type_data)
119
def lookup_git_sha(self, sha):
120
return self.dict[sha]
122
def lookup_tree(self, fileid, revid):
123
for k, v in self.dict.iteritems():
124
if v == ("tree", (fileid, revid)):
126
raise KeyError((fileid, revid))
128
def lookup_blob(self, fileid, revid):
129
for k, v in self.dict.iteritems():
130
if v == ("blob", (fileid, revid)):
132
raise KeyError((fileid, revid))
135
for key, (type, type_data) in self.dict.iteritems():
140
return self.dict.iterkeys()
143
class SqliteGitShaMap(GitShaMap):
145
def __init__(self, path=None):
148
self.db = sqlite3.connect(":memory:")
150
if not mapdbs().has_key(path):
151
mapdbs()[path] = sqlite3.connect(path)
152
self.db = mapdbs()[path]
153
self.db.executescript("""
154
create table if not exists commits(sha1 text, revid text, tree_sha text);
155
create index if not exists commit_sha1 on commits(sha1);
156
create unique index if not exists commit_revid on commits(revid);
157
create table if not exists blobs(sha1 text, fileid text, revid text);
158
create index if not exists blobs_sha1 on blobs(sha1);
159
create unique index if not exists blobs_fileid_revid on blobs(fileid, revid);
160
create table if not exists trees(sha1 text, fileid text, revid text);
161
create index if not exists trees_sha1 on trees(sha1);
162
create unique index if not exists trees_fileid_revid on trees(fileid, revid);
166
def from_repository(cls, repository):
167
return cls(os.path.join(repository._transport.local_abspath("."), "git.db"))
169
def lookup_commit(self, revid):
170
row = self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()
172
return row[0].encode("utf-8")
178
def add_entries(self, entries):
181
for sha, type, type_data in entries:
182
assert isinstance(type_data[0], str)
183
assert isinstance(type_data[1], str)
184
entry = (sha.decode("utf-8"), type_data[0].decode("utf-8"),
185
type_data[1].decode("utf-8"))
193
self.db.executemany("replace into trees (sha1, fileid, revid) values (?, ?, ?)", trees)
195
self.db.executemany("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", blobs)
198
def add_entry(self, sha, type, type_data):
199
"""Add a new entry to the database.
201
assert isinstance(type_data, tuple)
202
assert isinstance(sha, str), "type was %r" % sha
204
self.db.execute("replace into commits (sha1, revid, tree_sha) values (?, ?, ?)", (sha, type_data[0], type_data[1]))
205
elif type in ("blob", "tree"):
206
self.db.execute("replace into %ss (sha1, fileid, revid) values (?, ?, ?)" % type, (sha, type_data[0], type_data[1]))
208
raise AssertionError("Unknown type %s" % type)
210
def lookup_tree(self, fileid, revid):
211
row = self.db.execute("select sha1 from trees where fileid = ? and revid = ?", (fileid,revid)).fetchone()
213
raise KeyError((fileid, revid))
214
return row[0].encode("utf-8")
216
def lookup_blob(self, fileid, revid):
217
row = self.db.execute("select sha1 from blobs where fileid = ? and revid = ?", (fileid, revid)).fetchone()
219
raise KeyError((fileid, revid))
220
return row[0].encode("utf-8")
222
def lookup_git_sha(self, sha):
223
"""Lookup a Git sha in the database.
225
:param sha: Git object sha
226
:return: (type, type_data) with type_data:
227
revision: revid, tree sha
229
def format(type, row):
230
return (type, (row[0].encode("utf-8"), row[1].encode("utf-8")))
231
row = self.db.execute("select revid, tree_sha from commits where sha1 = ?", (sha,)).fetchone()
233
return format("commit", row)
234
row = self.db.execute("select fileid, revid from blobs where sha1 = ?", (sha,)).fetchone()
236
return format("blob", row)
237
row = self.db.execute("select fileid, revid from trees where sha1 = ?", (sha,)).fetchone()
239
return format("tree", row)
243
"""List the revision ids known."""
244
for row in self.db.execute("select revid from commits").fetchall():
245
yield row[0].encode("utf-8")
248
"""List the SHA1s."""
249
for table in ("blobs", "commits", "trees"):
250
for row in self.db.execute("select sha1 from %s" % table).fetchall():
251
yield row[0].encode("utf-8")
257
class TdbGitShaMap(GitShaMap):
258
"""SHA Map that uses a TDB database.
262
"git <sha1>" -> "<type> <type-data1> <type-data2>"
263
"commit revid" -> "<sha1> <tree-id>"
264
"tree fileid revid" -> "<sha1>"
265
"blob fileid revid" -> "<sha1>"
268
def __init__(self, path=None):
274
if not mapdbs().has_key(path):
275
mapdbs()[path] = tdb.open(path, 0, tdb.DEFAULT,
276
os.O_RDWR|os.O_CREAT)
277
self.db = mapdbs()[path]
278
if not "version" in self.db:
279
self.db["version"] = str(TDB_MAP_VERSION)
281
if int(self.db["version"]) != TDB_MAP_VERSION:
282
trace.warning("SHA Map is incompatible (%s -> %d), rebuilding database.",
283
self.db["version"], TDB_MAP_VERSION)
285
self.db["version"] = str(TDB_MAP_VERSION)
288
def from_repository(cls, repository):
290
transport = getattr(repository, "_transport", None)
291
if transport is not None:
292
return cls(os.path.join(transport.local_abspath("."), "git.tdb"))
293
except bzrlib.errors.NotLocalUrl:
295
from bzrlib.config import config_dir
296
return cls(os.path.join(config_dir(), "remote-git.tdb"))
298
def lookup_commit(self, revid):
299
return sha_to_hex(self.db["commit\0" + revid][:20])
304
def add_entry(self, sha, type, type_data):
305
"""Add a new entry to the database.
307
self.db["git\0" + hex_to_sha(sha)] = "\0".join((type, type_data[0], type_data[1]))
309
self.db["commit\0" + type_data[0]] = "\0".join((hex_to_sha(sha), type_data[1]))
311
self.db["\0".join((type, type_data[0], type_data[1]))] = hex_to_sha(sha)
313
def lookup_tree(self, fileid, revid):
314
return sha_to_hex(self.db["\0".join(("tree", fileid, revid))])
316
def lookup_blob(self, fileid, revid):
317
return sha_to_hex(self.db["\0".join(("blob", fileid, revid))])
319
def lookup_git_sha(self, sha):
320
"""Lookup a Git sha in the database.
322
:param sha: Git object sha
323
:return: (type, type_data) with type_data:
324
revision: revid, tree sha
326
data = self.db["git\0" + hex_to_sha(sha)].split("\0")
327
return (data[0], (data[1], data[2]))
330
"""List the revision ids known."""
331
for key in self.db.iterkeys():
332
if key.startswith("commit\0"):
336
"""List the SHA1s."""
337
for key in self.db.iterkeys():
338
if key.startswith("git\0"):
339
yield sha_to_hex(key[4:])