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 (
24
from dulwich.object_store import (
35
from bzrlib.revision import (
39
from bzrlib.plugins.git.mapping import (
42
extract_unusual_modes,
46
from bzrlib.plugins.git.shamap import (
47
from_repository as cache_from_repository,
53
def get_object_store(repo, mapping=None):
54
git = getattr(repo, "_git", None)
56
return git.object_store
57
return BazaarObjectStore(repo, mapping)
60
MAX_TREE_CACHE_SIZE = 50 * 1024 * 1024
63
class LRUTreeCache(object):
65
def __init__(self, repository):
66
def approx_tree_size(tree):
67
# Very rough estimate, 1k per inventory entry
68
return len(tree.inventory) * 1024
69
self.repository = repository
70
self._cache = lru_cache.LRUSizeCache(max_size=MAX_TREE_CACHE_SIZE,
71
after_cleanup_size=None, compute_size=approx_tree_size)
73
def revision_tree(self, revid):
75
return self._cache[revid]
77
tree = self.repository.revision_tree(revid)
81
def iter_revision_trees(self, revids):
82
trees = dict([(k, self._cache.get(k)) for k in revids])
83
for tree in self.repository.revision_trees(
84
[r for r, v in trees.iteritems() if v is None]):
85
trees[tree.get_revision_id()] = tree
87
return (trees[r] for r in revids)
89
def revision_trees(self, revids):
90
return list(self.iter_revision_trees(revids))
93
self._cache.add(tree.get_revision_id(), tree)
96
def _find_missing_bzr_revids(get_parent_map, want, have):
97
"""Find the revisions that have to be pushed.
99
:param get_parent_map: Function that returns the parents for a sequence
101
:param want: Revisions the target wants
102
:param have: Revisions the target already has
103
:return: Set of revisions to fetch
105
pending = want - have
109
processed.update(pending)
110
next_map = get_parent_map(pending)
112
for item in next_map.iteritems():
116
next_pending.update(p for p in item[1] if p not in processed)
117
pending = next_pending
118
if NULL_REVISION in todo:
119
todo.remove(NULL_REVISION)
123
def _check_expected_sha(expected_sha, object):
124
"""Check whether an object matches an expected SHA.
126
:param expected_sha: None or expected SHA as either binary or as hex digest
127
:param object: Object to verify
129
if expected_sha is None:
131
if len(expected_sha) == 40:
132
if expected_sha != object.sha().hexdigest():
133
raise AssertionError("Invalid sha for %r: %s" % (object,
135
elif len(expected_sha) == 20:
136
if expected_sha != object.sha().digest():
137
raise AssertionError("Invalid sha for %r: %s" % (object,
138
sha_to_hex(expected_sha)))
140
raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
144
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes):
145
"""Iterate over the objects that were introduced in a revision.
148
:param unusual_modes: Unusual file modes
149
:return: Yields (path, object, ie) entries
155
base_tree = parent_trees[0]
156
other_parent_trees = parent_trees[1:]
158
base_tree = tree._repository.revision_tree(NULL_REVISION)
159
other_parent_trees = []
160
def find_unchanged_parent_ie(ie, parent_trees):
161
assert ie.kind in ("symlink", "file")
162
for ptree in parent_trees:
164
pie = ptree.inventory[ie.file_id]
165
except errors.NoSuchId:
168
if (pie.text_sha1 == ie.text_sha1 and
169
pie.kind == ie.kind and
170
pie.symlink_target == ie.symlink_target):
173
for (file_id, path, changed_content, versioned, parent, name, kind,
174
executable) in tree.iter_changes(base_tree):
175
if kind[1] == "file":
176
ie = tree.inventory[file_id]
180
pie = find_unchanged_parent_ie(ie, other_parent_trees)
184
shamap[ie.file_id] = idmap.lookup_blob_id(
185
pie.file_id, pie.revision)
186
if not file_id in shamap:
187
new_blobs.append((path[1], ie))
188
new_trees[posixpath.dirname(path[1])] = parent[1]
189
elif kind[1] == "symlink":
190
ie = tree.inventory[file_id]
192
blob = symlink_to_blob(ie)
193
shamap[file_id] = blob.id
195
find_unchanged_parent_ie(ie, other_parent_trees)
197
yield path[1], blob, ie
198
new_trees[posixpath.dirname(path[1])] = parent[1]
199
elif kind[1] not in (None, "directory"):
200
raise AssertionError(kind[1])
201
if path[0] is not None:
202
new_trees[posixpath.dirname(path[0])] = parent[0]
204
for (path, ie), chunks in tree.iter_files_bytes(
205
[(ie.file_id, (path, ie)) for (path, ie) in new_blobs]):
209
shamap[ie.file_id] = obj.id
211
for path in unusual_modes:
212
parent_path = posixpath.dirname(path)
213
new_trees[parent_path] = tree.path2id(parent_path)
217
items = new_trees.items()
219
for path, file_id in items:
221
parent_id = tree.inventory[file_id].parent_id
222
except errors.NoSuchId:
223
# Directory was removed recursively perhaps ?
225
if parent_id is not None:
226
parent_path = urlutils.dirname(path)
227
new_trees[parent_path] = parent_id
228
trees[path] = file_id
230
def ie_to_hexsha(ie):
232
return shamap[ie.file_id]
234
# FIXME: Should be the same as in parent
235
if ie.kind in ("file", "symlink"):
237
return idmap.lookup_blob_id(ie.file_id, ie.revision)
241
blob.data = tree.get_file_text(ie.file_id)
243
elif ie.kind == "directory":
244
# Not all cache backends store the tree information,
245
# calculate again from scratch
246
ret = directory_to_tree(ie, ie_to_hexsha, unusual_modes)
253
for path in sorted(trees.keys(), reverse=True):
254
ie = tree.inventory[trees[path]]
255
assert ie.kind == "directory"
256
obj = directory_to_tree(ie, ie_to_hexsha, unusual_modes)
259
shamap[ie.file_id] = obj.id
262
class BazaarObjectStore(BaseObjectStore):
263
"""A Git-style object store backed onto a Bazaar repository."""
265
def __init__(self, repository, mapping=None):
266
self.repository = repository
268
self.mapping = default_mapping
270
self.mapping = mapping
271
self._cache = cache_from_repository(repository)
272
self._content_cache_types = ("tree")
273
self.start_write_group = self._cache.idmap.start_write_group
274
self.abort_write_group = self._cache.idmap.abort_write_group
275
self.commit_write_group = self._cache.idmap.commit_write_group
276
self.tree_cache = LRUTreeCache(self.repository)
278
def _update_sha_map(self, stop_revision=None):
279
graph = self.repository.get_graph()
280
if stop_revision is None:
281
heads = graph.heads(self.repository.all_revision_ids())
283
heads = set([stop_revision])
284
missing_revids = self._cache.idmap.missing_revisions(heads)
286
parents = graph.get_parent_map(heads)
288
for p in parents.values():
289
todo.update([x for x in p if x not in missing_revids])
290
heads = self._cache.idmap.missing_revisions(todo)
291
missing_revids.update(heads)
292
if NULL_REVISION in missing_revids:
293
missing_revids.remove(NULL_REVISION)
294
missing_revids = self.repository.has_revisions(missing_revids)
295
if not missing_revids:
297
self.start_write_group()
299
pb = ui.ui_factory.nested_progress_bar()
301
for i, revid in enumerate(graph.iter_topo_order(missing_revids)):
302
trace.mutter('processing %r', revid)
303
pb.update("updating git map", i, len(missing_revids))
304
self._update_sha_map_revision(revid)
308
self.abort_write_group()
311
self.commit_write_group()
314
self._update_sha_map()
315
return iter(self._cache.idmap.sha1s())
317
def _reconstruct_commit(self, rev, tree_sha):
318
def parent_lookup(revid):
320
return self._lookup_revision_sha1(revid)
321
except errors.NoSuchRevision:
322
trace.warning("Ignoring ghost parent %s", revid)
324
return self.mapping.export_commit(rev, tree_sha, parent_lookup)
326
def _revision_to_objects(self, rev, tree):
327
unusual_modes = extract_unusual_modes(rev)
328
present_parents = self.repository.has_revisions(rev.parent_ids)
329
parent_trees = self.tree_cache.revision_trees(
330
[p for p in rev.parent_ids if p in present_parents])
332
for path, obj, ie in _tree_to_objects(tree, parent_trees,
333
self._cache.idmap, unusual_modes):
338
# Pointless commit - get the tree sha elsewhere
339
if not rev.parent_ids:
342
base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
343
tree_sha = self[base_sha1].tree
344
commit_obj = self._reconstruct_commit(rev, tree_sha)
346
foreign_revid, mapping = mapping_registry.parse_revision_id(
348
except errors.InvalidRevisionId:
351
_check_expected_sha(foreign_revid, commit_obj)
352
yield None, commit_obj, None
354
def _get_updater(self, rev):
355
return self._cache.get_updater(rev)
357
def _update_sha_map_revision(self, revid):
358
rev = self.repository.get_revision(revid)
359
tree = self.tree_cache.revision_tree(rev.revision_id)
360
updater = self._get_updater(rev)
361
for path, obj, ie in self._revision_to_objects(rev, tree):
362
updater.add_object(obj, ie)
363
commit_obj = updater.finish()
366
def _reconstruct_blobs(self, keys):
367
"""Return a Git Blob object from a fileid and revision stored in bzr.
369
:param fileid: File id of the text
370
:param revision: Revision of the text
372
stream = self.repository.iter_files_bytes(
373
((key[0], key[1], key) for key in keys))
374
for (fileid, revision, expected_sha), chunks in stream:
376
blob.chunked = chunks
377
if blob.id != expected_sha and blob.data == "":
378
# Perhaps it's a symlink ?
379
tree = self.tree_cache.revision_tree(revision)
380
entry = tree.inventory[fileid]
381
if entry.kind == 'symlink':
382
blob = symlink_to_blob(entry)
383
_check_expected_sha(expected_sha, blob)
386
def _reconstruct_tree(self, fileid, revid, inv, unusual_modes,
388
"""Return a Git Tree object from a file id and a revision stored in bzr.
390
:param fileid: fileid in the tree.
391
:param revision: Revision of the tree.
393
def get_ie_sha1(entry):
394
if entry.kind == "directory":
396
return self._cache.idmap.lookup_tree_id(entry.file_id,
398
except (NotImplementedError, KeyError):
399
obj = self._reconstruct_tree(entry.file_id, revid, inv,
405
elif entry.kind in ("file", "symlink"):
407
return self._cache.idmap.lookup_blob_id(entry.file_id,
411
return self._reconstruct_blobs(
412
[(entry.file_id, entry.revision, None)]).next().id
414
raise AssertionError("unknown entry kind '%s'" % entry.kind)
415
tree = directory_to_tree(inv[fileid], get_ie_sha1, unusual_modes)
416
_check_expected_sha(expected_sha, tree)
419
def get_parents(self, sha):
420
"""Retrieve the parents of a Git commit by SHA1.
422
:param sha: SHA1 of the commit
423
:raises: KeyError, NotCommitError
425
return self[sha].parents
427
def _lookup_revision_sha1(self, revid):
428
"""Return the SHA1 matching a Bazaar revision."""
429
from dulwich.protocol import ZERO_SHA
430
if revid == NULL_REVISION:
433
return self._cache.idmap.lookup_commit(revid)
436
return mapping_registry.parse_revision_id(revid)[0]
437
except errors.InvalidRevisionId:
438
self._update_sha_map(revid)
439
return self._cache.idmap.lookup_commit(revid)
441
def get_raw(self, sha):
442
"""Get the raw representation of a Git object by SHA1.
444
:param sha: SHA1 of the git object
447
return (obj.type, obj.as_raw_string())
449
def __contains__(self, sha):
450
# See if sha is in map
452
(type, type_data) = self.lookup_git_sha(sha)
454
return self.repository.has_revision(type_data[0])
456
return self.repository.texts.has_version(type_data)
458
return self.repository.has_revision(type_data[1])
460
raise AssertionError("Unknown object type '%s'" % type)
464
def lookup_git_shas(self, shas, update_map=True):
468
ret[sha] = self._cache.idmap.lookup_git_sha(sha)
471
# if not, see if there are any unconverted revisions and add
472
# them to the map, search for sha in map again
473
self._update_sha_map()
476
ret[sha] = self._cache.idmap.lookup_git_sha(sha)
481
def lookup_git_sha(self, sha, update_map=True):
482
return self.lookup_git_shas([sha], update_map=update_map)[sha]
484
def __getitem__(self, sha):
485
if self._cache.content_cache is not None:
487
return self._cache.content_cache[sha]
490
(type, type_data) = self.lookup_git_sha(sha)
491
# convert object to git object
493
(revid, tree_sha) = type_data
495
rev = self.repository.get_revision(revid)
496
except errors.NoSuchRevision:
497
trace.mutter('entry for %s %s in shamap: %r, but not found in '
498
'repository', type, sha, type_data)
500
commit = self._reconstruct_commit(rev, tree_sha)
501
_check_expected_sha(sha, commit)
504
(fileid, revision) = type_data
505
return self._reconstruct_blobs([(fileid, revision, sha)]).next()
507
(fileid, revid) = type_data
509
tree = self.tree_cache.revision_tree(revid)
510
rev = self.repository.get_revision(revid)
511
except errors.NoSuchRevision:
512
trace.mutter('entry for %s %s in shamap: %r, but not found in repository', type, sha, type_data)
514
unusual_modes = extract_unusual_modes(rev)
516
return self._reconstruct_tree(fileid, revid, tree.inventory,
517
unusual_modes, expected_sha=sha)
518
except errors.NoSuchRevision:
521
raise AssertionError("Unknown object type '%s'" % type)
523
def generate_pack_contents(self, have, want, progress=None,
525
"""Iterate over the contents of a pack file.
527
:param have: List of SHA1s of objects that should not be sent
528
:param want: List of SHA1s of objects that should be sent
531
ret = self.lookup_git_shas(have + want)
532
for commit_sha in have:
534
(type, (revid, tree_sha)) = ret[commit_sha]
538
assert type == "commit"
541
for commit_sha in want:
542
if commit_sha in have:
545
(type, (revid, tree_sha)) = ret[commit_sha]
549
assert type == "commit"
552
todo = _find_missing_bzr_revids(self.repository.get_parent_map,
554
trace.mutter('sending revisions %r', todo)
556
pb = ui.ui_factory.nested_progress_bar()
558
for i, revid in enumerate(todo):
559
pb.update("generating git objects", i, len(todo))
560
rev = self.repository.get_revision(revid)
561
tree = self.tree_cache.revision_tree(revid)
562
for path, obj, ie in self._revision_to_objects(rev, tree):
563
ret.append((obj, path))
568
def add_thin_pack(self):
571
fd, path = tempfile.mkstemp(suffix=".pack")
572
f = os.fdopen(fd, 'wb')
574
from dulwich.pack import PackData, Pack
575
from bzrlib.plugins.git.fetch import import_git_objects
578
if os.path.getsize(path) == 0:
581
pd.create_index_v2(path[:-5]+".idx", self.object_store.get_raw)
584
self.repository.lock_write()
586
self.repository.start_write_group()
588
import_git_objects(self.repository, self.mapping,
589
p.iterobjects(get_raw=self.get_raw),
592
self.repository.abort_write_group()
595
self.repository.commit_write_group()
597
self.repository.unlock()
600
# The pack isn't kept around anyway, so no point
601
# in treating full packs different from thin packs
602
add_pack = add_thin_pack