1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
|
# Copyright (C) 2007 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""An adapter between a Git Repository and a Bazaar Branch"""
import git
import os
import time
import bzrlib
from bzrlib import (
deprecated_graph,
errors,
inventory,
osutils,
repository,
revision,
revisiontree,
urlutils,
versionedfile,
)
from bzrlib.transport import get_transport
from bzrlib.plugins.git import (
cache,
ids,
)
cachedbs = {}
class GitRepository(repository.Repository):
"""An adapter to git repositories for bzr."""
_serializer = None
def __init__(self, gitdir, lockfiles):
self.base = gitdir.root_transport.base
self.bzrdir = gitdir
self.control_files = lockfiles
self._git = git.repo.Repo(gitdir.root_transport.local_abspath("."))
self._blob_cache = {}
self._blob_info_cache = {}
cache_dir = cache.create_cache_dir()
cachedir_transport = get_transport(cache_dir)
cache_file = os.path.join(cache_dir, 'cache-%s' % ids.NAMESPACE)
if not cachedbs.has_key(cache_file):
cachedbs[cache_file] = cache.sqlite3.connect(cache_file)
self.cachedb = cachedbs[cache_file]
self._init_cachedb()
self.texts = None
self.signatures = versionedfile.VirtualSignatureTexts(self)
self.revisions = None
self._format = GitFormat()
self._fallback_repositories = []
def _init_cachedb(self):
self.cachedb.executescript("""
create table if not exists inventory (
revid blob);
create unique index if not exists inventory_revid
on inventory (revid);
create table if not exists entry_revision (
inventory blob,
path blob,
gitid blob,
executable integer,
revision blob);
create unique index if not exists entry_revision_revid_path
on entry_revision (inventory, path);
""")
self.cachedb.commit()
def is_shared(self):
return True
def supports_rich_root(self):
return False
def get_ancestry(self, revision_id):
revision_id = revision.ensure_null(revision_id)
ret = []
if revision_id != revision.NULL_REVISION:
skip = 0
max_count = 1000
cms = None
while cms != []:
cms = self._git.commits(ids.convert_revision_id_bzr_to_git(revision_id), max_count=max_count, skip=skip)
skip += max_count
ret += [ids.convert_revision_id_git_to_bzr(cm.id) for cm in cms]
return [None] + ret
def get_signature_text(self, revision_id):
raise errors.NoSuchRevision(self, revision_id)
def has_signature_for_revision_id(self, revision_id):
return False
def get_parent_map(self, revision_ids):
ret = {}
for revid in revision_ids:
commit = self._git.commit(ids.convert_revision_id_bzr_to_git(revid))
ret[revid] = tuple([ids.convert_revision_id_git_to_bzr(p.id) for p in commit.parents])
return ret
def get_revision(self, revision_id):
git_commit_id = ids.convert_revision_id_bzr_to_git(revision_id)
commit = self._git.commit(git_commit_id)
# print "fetched revision:", git_commit_id
revision = self._parse_rev(commit)
return revision
def has_revision(self, revision_id):
try:
self.get_revision(revision_id)
except NoSuchRevision:
return False
else:
return True
def get_revisions(self, revisions):
return [self.get_revision(r) for r in revisions]
@classmethod
def _parse_rev(klass, commit):
"""Convert a git commit to a bzr revision.
:return: a `bzrlib.revision.Revision` object.
"""
rev = revision.Revision(ids.convert_revision_id_git_to_bzr(commit.id))
rev.parent_ids = tuple([ids.convert_revision_id_git_to_bzr(p.id) for p in commit.parents])
rev.inventory_sha1 = ""
rev.message = commit.message.decode("utf-8", "replace")
rev.committer = str(commit.committer)
rev.properties['author'] = str(commit.author)
rev.timestamp = time.mktime(commit.committed_date)
rev.timezone = 0
return rev
def revision_trees(self, revids):
for revid in revids:
yield self.revision_tree(revid)
def revision_tree(self, revision_id):
revision_id = revision.ensure_null(revision_id)
if revision_id == revision.NULL_REVISION:
inv = inventory.Inventory(root_id=None)
inv.revision_id = revision_id
return revisiontree.RevisionTree(self, inv, revision_id)
return GitRevisionTree(self, revision_id)
def _fetch_blob(self, git_id):
lines = self._git.cat_file('blob', git_id)
# print "fetched blob:", git_id
if self._building_inventory is not None:
self._building_inventory.git_file_data[git_id] = lines
return lines
def _get_blob(self, git_id):
try:
return self._blob_cache[git_id]
except KeyError:
return self._fetch_blob(git_id)
def _get_blob_caching(self, git_id):
try:
return self._blob_cache[git_id]
except KeyError:
lines = self._fetch_blob(git_id)
self._blob_cache[git_id] = lines
return lines
def _get_blob_info(self, git_id):
try:
return self._blob_info_cache[git_id]
except KeyError:
lines = self._get_blob(git_id)
size = sum(len(line) for line in lines)
sha1 = osutils.sha_strings(lines)
self._blob_info_cache[git_id] = (size, sha1)
return size, sha1
def get_inventory(self, revision_id):
assert revision_id != None
return self.revision_tree(revision_id).inventory
def _set_entry_text_info(self, inv, entry, git_id):
if entry.kind == 'directory':
return
size, sha1 = self._get_blob_info(git_id)
entry.text_size = size
entry.text_sha1 = sha1
if entry.kind == 'symlink':
lines = self._get_blob_caching(git_id)
entry.symlink_target = ''.join(lines)
def _get_file_revision(self, revision_id, path):
lines = self._git.rev_list(
[ids.convert_revision_id_bzr_to_git(revision_id)],
max_count=1, topo_order=True, paths=[path])
[line] = lines
result = ids.convert_revision_id_git_to_bzr(line[:-1])
# print "fetched file revision", line[:-1], path
return result
def _get_entry_revision_from_db(self, revid, path, git_id, executable):
result = self.cachedb.execute(
"select revision from entry_revision where"
" inventory=? and path=? and gitid=? and executable=?",
(revid, path, git_id, executable)).fetchone()
if result is None:
return None
[revision] = result
return revision
def _set_entry_revision_in_db(self, revid, path, git_id, executable, revision):
self.cachedb.execute(
"insert into entry_revision"
" (inventory, path, gitid, executable, revision)"
" values (?, ?, ?, ?, ?)",
(revid, path, git_id, executable, revision))
def _all_inventories_in_db(self, revids):
for revid in revids:
result = self.cachedb.execute(
"select count(*) from inventory where revid = ?",
(revid,)).fetchone()
if result is None:
return False
return True
def _set_entry_revision(self, entry, revid, path, git_id):
# If a revision is in the cache, we assume it contains entries for the
# whole inventory. So if all parent revisions are in the cache, but no
# parent entry is present, then the entry revision is the current
# revision. That amortizes the number of _get_file_revision calls for
# large pulls to a "small number".
entry_rev = self._get_entry_revision_from_db(
revid, path, git_id, entry.executable)
if entry_rev is not None:
entry.revision = entry_rev
return
revision = self.get_revision(revid)
for parent_id in revision.parent_ids:
entry_rev = self._get_entry_revision_from_db(
parent_id, path, git_id, entry.executable)
if entry_rev is not None:
break
else:
if self._all_inventories_in_db(revision.parent_ids):
entry_rev = revid
else:
entry_rev = self._get_file_revision(revid, path)
self._set_entry_revision_in_db(
revid, path, git_id, entry.executable, entry_rev)
#self.cachedb.commit()
entry.revision = entry_rev
def escape_file_id(file_id):
return file_id.replace('_', '__').replace(' ', '_s')
class GitRevisionTree(revisiontree.RevisionTree):
def __init__(self, repository, revision_id):
self._repository = repository
self.revision_id = revision_id
git_id = ids.convert_revision_id_bzr_to_git(revision_id)
self.tree = repository._git.commit(git_id).tree
self._inventory = inventory.Inventory(revision_id=revision_id)
self._inventory.root.revision = revision_id
self._build_inventory(self.tree, self._inventory.root, "")
def get_file_lines(self, file_id):
entry = self._inventory[file_id]
if entry.kind == 'directory': return []
git_id = self._inventory.git_ids[file_id]
if git_id in self._inventory.git_file_data:
return self._inventory.git_file_data[git_id]
return self._repository._get_blob(git_id)
def _build_inventory(self, tree, ie, path):
assert isinstance(path, str)
for b in tree.contents:
basename = b.name.decode("utf-8")
if path == "":
child_path = b.name
else:
child_path = urlutils.join(path, b.name)
file_id = escape_file_id(child_path.encode('utf-8'))
if b.mode[0] == '0':
child_ie = inventory.InventoryDirectory(file_id, basename, ie.file_id)
elif b.mode[0] == '1':
if b.mode[1] == '0':
child_ie = inventory.InventoryFile(file_id, basename, ie.file_id)
child_ie.text_sha1 = osutils.sha_string(b.data)
elif b.mode[1] == '2':
child_ie = inventory.InventoryLink(file_id, basename, ie.file_id)
child_ie.text_sha1 = osutils.sha_string("")
else:
raise AssertionError(
"Unknown file kind, perms=%r." % (b.mode,))
child_ie.text_size = b.size
else:
raise AssertionError(
"Unknown blob kind, perms=%r." % (b.mode,))
child_ie.executable = bool(int(b.mode[3:], 8) & 0111)
child_ie.revision = self.revision_id
assert not basename in ie.children
ie.children[basename] = child_ie
if b.mode[0] == '0':
self._build_inventory(b, child_ie, child_path)
class GitFormat(object):
supports_tree_reference = False
def get_format_description(self):
return "Git Repository"
|