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 (
37
from xdg.BaseDirectory import xdg_cache_home
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")
46
def check_pysqlite_version(sqlite3):
47
"""Check that sqlite library is compatible.
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")
59
check_pysqlite_version(sqlite3)
60
except (ImportError, bzrlib.errors.BzrError), e:
61
from pysqlite2 import dbapi2 as sqlite3
62
check_pysqlite_version(sqlite3)
64
warning('Needs at least Python2.5 or Python2.4 with the pysqlite2 '
66
raise bzrlib.errors.BzrError("missing sqlite library")
69
_mapdbs = threading.local()
71
"""Get a cache for this thread's db connections."""
74
except AttributeError:
79
class GitShaMap(object):
80
"""Git<->Bzr revision id mapping database."""
82
def add_entry(self, sha, type, type_data):
83
"""Add a new entry to the database.
85
raise NotImplementedError(self.add_entry)
87
def add_entries(self, entries):
88
"""Add multiple new entries to the database.
93
def lookup_tree(self, fileid, revid):
94
"""Lookup the SHA of a git tree."""
95
raise NotImplementedError(self.lookup_tree)
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)
101
def lookup_git_sha(self, sha):
102
"""Lookup a Git sha in the database.
104
:param sha: Git object sha
105
:return: (type, type_data) with type_data:
106
revision: revid, tree sha
108
raise NotImplementedError(self.lookup_git_sha)
111
"""List the revision ids known."""
112
raise NotImplementedError(self.revids)
115
"""List the SHA1s."""
116
raise NotImplementedError(self.sha1s)
119
"""Commit any pending changes."""
122
class DictGitShaMap(GitShaMap):
127
def add_entry(self, sha, type, type_data):
128
self.dict[sha] = (type, type_data)
130
def lookup_git_sha(self, sha):
131
return self.dict[sha]
133
def lookup_tree(self, fileid, revid):
134
for k, v in self.dict.iteritems():
135
if v == ("tree", (fileid, revid)):
137
raise KeyError((fileid, revid))
139
def lookup_blob(self, fileid, revid):
140
for k, v in self.dict.iteritems():
141
if v == ("blob", (fileid, revid)):
143
raise KeyError((fileid, revid))
146
for key, (type, type_data) in self.dict.iteritems():
151
return self.dict.iterkeys()
154
class SqliteGitShaMap(GitShaMap):
156
def __init__(self, path=None):
159
self.db = sqlite3.connect(":memory:")
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);
177
def from_repository(cls, repository):
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:
184
return cls(os.path.join(get_cache_dir(), "remote.db"))
186
def lookup_commit(self, revid):
187
row = self.db.execute("select sha1 from commits where revid = ?", (revid,)).fetchone()
189
return row[0].encode("utf-8")
195
def add_entries(self, entries):
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"))
210
self.db.executemany("replace into trees (sha1, fileid, revid) values (?, ?, ?)", trees)
212
self.db.executemany("replace into blobs (sha1, fileid, revid) values (?, ?, ?)", blobs)
215
def add_entry(self, sha, type, type_data):
216
"""Add a new entry to the database.
218
assert isinstance(type_data, tuple)
219
assert isinstance(sha, str), "type was %r" % sha
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]))
225
raise AssertionError("Unknown type %s" % type)
227
def lookup_tree(self, fileid, revid):
228
row = self.db.execute("select sha1 from trees where fileid = ? and revid = ?", (fileid,revid)).fetchone()
230
raise KeyError((fileid, revid))
231
return row[0].encode("utf-8")
233
def lookup_blob(self, fileid, revid):
234
row = self.db.execute("select sha1 from blobs where fileid = ? and revid = ?", (fileid, revid)).fetchone()
236
raise KeyError((fileid, revid))
237
return row[0].encode("utf-8")
239
def lookup_git_sha(self, sha):
240
"""Lookup a Git sha in the database.
242
:param sha: Git object sha
243
:return: (type, type_data) with type_data:
244
revision: revid, tree sha
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()
250
return format("commit", row)
251
row = self.db.execute("select fileid, revid from blobs where sha1 = ?", (sha,)).fetchone()
253
return format("blob", row)
254
row = self.db.execute("select fileid, revid from trees where sha1 = ?", (sha,)).fetchone()
256
return format("tree", row)
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")
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")
272
TDB_HASH_SIZE = 10000
275
class TdbGitShaMap(GitShaMap):
276
"""SHA Map that uses a TDB database.
280
"git <sha1>" -> "<type> <type-data1> <type-data2>"
281
"commit revid" -> "<sha1> <tree-id>"
282
"tree fileid revid" -> "<sha1>"
283
"blob fileid revid" -> "<sha1>"
286
def __init__(self, path=None):
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)
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)
303
self.db["version"] = str(TDB_MAP_VERSION)
306
def from_repository(cls, repository):
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:
313
return cls(os.path.join(get_cache_dir(), "remote.tdb"))
315
def lookup_commit(self, revid):
316
return sha_to_hex(self.db["commit\0" + revid][:20])
321
def add_entry(self, sha, type, type_data):
322
"""Add a new entry to the database.
324
self.db["git\0" + hex_to_sha(sha)] = "\0".join((type, type_data[0], type_data[1]))
326
self.db["commit\0" + type_data[0]] = "\0".join((hex_to_sha(sha), type_data[1]))
328
self.db["\0".join((type, type_data[0], type_data[1]))] = hex_to_sha(sha)
330
def lookup_tree(self, fileid, revid):
331
return sha_to_hex(self.db["\0".join(("tree", fileid, revid))])
333
def lookup_blob(self, fileid, revid):
334
return sha_to_hex(self.db["\0".join(("blob", fileid, revid))])
336
def lookup_git_sha(self, sha):
337
"""Lookup a Git sha in the database.
339
:param sha: Git object sha
340
:return: (type, type_data) with type_data:
341
revision: revid, tree sha
343
data = self.db["git\0" + hex_to_sha(sha)].split("\0")
344
return (data[0], (data[1], data[2]))
347
"""List the revision ids known."""
348
for key in self.db.iterkeys():
349
if key.startswith("commit\0"):
353
"""List the SHA1s."""
354
for key in self.db.iterkeys():
355
if key.startswith("git\0"):
356
yield sha_to_hex(key[4:])