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 (
26
from dulwich.object_store import (
37
from bzrlib.revision import (
40
from bzrlib.testament import(
44
from bzrlib.plugins.git.mapping import (
47
extract_unusual_modes,
51
from bzrlib.plugins.git.cache import (
52
from_repository as cache_from_repository,
59
def get_object_store(repo, mapping=None):
60
git = getattr(repo, "_git", None)
62
return git.object_store
63
return BazaarObjectStore(repo, mapping)
66
MAX_TREE_CACHE_SIZE = 50 * 1024 * 1024
69
class LRUTreeCache(object):
71
def __init__(self, repository):
72
def approx_tree_size(tree):
73
# Very rough estimate, 1k per inventory entry
74
return len(tree.inventory) * 1024
75
self.repository = repository
76
self._cache = lru_cache.LRUSizeCache(max_size=MAX_TREE_CACHE_SIZE,
77
after_cleanup_size=None, compute_size=approx_tree_size)
79
def revision_tree(self, revid):
81
tree = self._cache[revid]
83
tree = self.repository.revision_tree(revid)
85
assert tree.get_revision_id() == tree.inventory.revision_id
88
def iter_revision_trees(self, revids):
93
tree = self._cache[revid]
97
assert tree.get_revision_id() == revid
98
assert tree.inventory.revision_id == revid
100
for tree in self.repository.revision_trees(todo):
101
trees[tree.get_revision_id()] = tree
103
return (trees[r] for r in revids)
105
def revision_trees(self, revids):
106
return list(self.iter_revision_trees(revids))
109
self._cache.add(tree.get_revision_id(), tree)
112
def _find_missing_bzr_revids(graph, want, have):
113
"""Find the revisions that have to be pushed.
115
:param get_parent_map: Function that returns the parents for a sequence
117
:param want: Revisions the target wants
118
:param have: Revisions the target already has
119
:return: Set of revisions to fetch
123
todo.update(graph.find_unique_ancestors(rev, have))
124
if NULL_REVISION in todo:
125
todo.remove(NULL_REVISION)
129
def _check_expected_sha(expected_sha, object):
130
"""Check whether an object matches an expected SHA.
132
:param expected_sha: None or expected SHA as either binary or as hex digest
133
:param object: Object to verify
135
if expected_sha is None:
137
if len(expected_sha) == 40:
138
if expected_sha != object.sha().hexdigest():
139
raise AssertionError("Invalid sha for %r: %s" % (object,
141
elif len(expected_sha) == 20:
142
if expected_sha != object.sha().digest():
143
raise AssertionError("Invalid sha for %r: %s" % (object,
144
sha_to_hex(expected_sha)))
146
raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
150
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes,
151
dummy_file_name=None):
152
"""Iterate over the objects that were introduced in a revision.
155
:param parent_trees: Parent revision trees
156
:param unusual_modes: Unusual file modes dictionary
157
:param dummy_file_name: File name to use for dummy files
158
in empty directories. None to skip empty directories
159
:return: Yields (path, object, ie) entries
165
base_tree = parent_trees[0]
166
other_parent_trees = parent_trees[1:]
168
base_tree = tree._repository.revision_tree(NULL_REVISION)
169
other_parent_trees = []
170
def find_unchanged_parent_ie(ie, parent_trees):
171
assert ie.kind in ("symlink", "file")
172
for ptree in parent_trees:
174
pie = ptree.inventory[ie.file_id]
175
except errors.NoSuchId:
178
if (pie.text_sha1 == ie.text_sha1 and
179
pie.kind == ie.kind and
180
pie.symlink_target == ie.symlink_target):
184
# Find all the changed blobs
185
for (file_id, path, changed_content, versioned, parent, name, kind,
186
executable) in tree.iter_changes(base_tree):
187
if kind[1] == "file":
188
ie = tree.inventory[file_id]
191
pie = find_unchanged_parent_ie(ie, other_parent_trees)
196
shamap[ie.file_id] = idmap.lookup_blob_id(
197
pie.file_id, pie.revision)
201
blob.data = tree.get_file_text(ie.file_id)
202
shamap[ie.file_id] = blob.id
203
if not file_id in shamap:
204
new_blobs.append((path[1], ie))
205
new_trees[posixpath.dirname(path[1])] = parent[1]
206
elif kind[1] == "symlink":
207
ie = tree.inventory[file_id]
209
blob = symlink_to_blob(ie)
210
shamap[file_id] = blob.id
212
find_unchanged_parent_ie(ie, other_parent_trees)
214
yield path[1], blob, ie
215
new_trees[posixpath.dirname(path[1])] = parent[1]
216
elif kind[1] not in (None, "directory"):
217
raise AssertionError(kind[1])
218
if (path[0] not in (None, "") and
219
parent[0] in tree.inventory and
220
tree.inventory[parent[0]].kind == "directory"):
222
new_trees[posixpath.dirname(path[0])] = parent[0]
224
# Fetch contents of the blobs that were changed
225
for (path, ie), chunks in tree.iter_files_bytes(
226
[(ie.file_id, (path, ie)) for (path, ie) in new_blobs]):
230
shamap[ie.file_id] = obj.id
232
for path in unusual_modes:
233
parent_path = posixpath.dirname(path)
234
new_trees[parent_path] = tree.path2id(parent_path)
238
items = new_trees.items()
240
for path, file_id in items:
241
parent_id = tree.inventory[file_id].parent_id
242
if parent_id is not None:
243
parent_path = urlutils.dirname(path)
244
new_trees[parent_path] = parent_id
245
trees[path] = file_id
247
def ie_to_hexsha(ie):
249
return shamap[ie.file_id]
251
# FIXME: Should be the same as in parent
252
if ie.kind in ("file", "symlink"):
254
return idmap.lookup_blob_id(ie.file_id, ie.revision)
258
blob.data = tree.get_file_text(ie.file_id)
260
elif ie.kind == "directory":
261
# Not all cache backends store the tree information,
262
# calculate again from scratch
263
ret = directory_to_tree(ie, ie_to_hexsha, unusual_modes,
271
for path in sorted(trees.keys(), reverse=True):
272
ie = tree.inventory[trees[path]]
273
assert ie.kind == "directory"
274
obj = directory_to_tree(ie, ie_to_hexsha, unusual_modes,
278
shamap[ie.file_id] = obj.id
281
class BazaarObjectStore(BaseObjectStore):
282
"""A Git-style object store backed onto a Bazaar repository."""
284
def __init__(self, repository, mapping=None):
285
self.repository = repository
287
self.mapping = default_mapping
289
self.mapping = mapping
290
self._cache = cache_from_repository(repository)
291
self._content_cache_types = ("tree")
292
self.start_write_group = self._cache.idmap.start_write_group
293
self.abort_write_group = self._cache.idmap.abort_write_group
294
self.commit_write_group = self._cache.idmap.commit_write_group
295
self.tree_cache = LRUTreeCache(self.repository)
297
def _update_sha_map(self, stop_revision=None):
298
graph = self.repository.get_graph()
299
if stop_revision is None:
300
heads = graph.heads(self.repository.all_revision_ids())
302
heads = set([stop_revision])
303
missing_revids = self._cache.idmap.missing_revisions(heads)
305
parents = graph.get_parent_map(heads)
307
for p in parents.values():
308
todo.update([x for x in p if x not in missing_revids])
309
heads = self._cache.idmap.missing_revisions(todo)
310
missing_revids.update(heads)
311
if NULL_REVISION in missing_revids:
312
missing_revids.remove(NULL_REVISION)
313
missing_revids = self.repository.has_revisions(missing_revids)
314
if not missing_revids:
316
self.start_write_group()
318
pb = ui.ui_factory.nested_progress_bar()
320
for i, revid in enumerate(graph.iter_topo_order(missing_revids)):
321
trace.mutter('processing %r', revid)
322
pb.update("updating git map", i, len(missing_revids))
323
self._update_sha_map_revision(revid)
327
self.abort_write_group()
330
self.commit_write_group()
333
self._update_sha_map()
334
return iter(self._cache.idmap.sha1s())
336
def _reconstruct_commit(self, rev, tree_sha, roundtrip, verifiers):
337
"""Reconstruct a Commit object.
339
:param rev: Revision object
340
:param tree_sha: SHA1 of the root tree object
341
:param roundtrip: Whether or not to roundtrip bzr metadata
342
:param verifiers: Verifiers for the commits
343
:return: Commit object
345
def parent_lookup(revid):
347
return self._lookup_revision_sha1(revid)
348
except errors.NoSuchRevision:
350
return self.mapping.export_commit(rev, tree_sha, parent_lookup,
351
roundtrip, verifiers)
353
def _create_fileid_map_blob(self, inv):
354
# FIXME: This can probably be a lot more efficient,
355
# not all files necessarily have to be processed.
357
for (path, ie) in inv.iter_entries():
358
if self.mapping.generate_file_id(path) != ie.file_id:
359
file_ids[path] = ie.file_id
360
return self.mapping.export_fileid_map(file_ids)
362
def _revision_to_objects(self, rev, tree, roundtrip):
363
"""Convert a revision to a set of git objects.
365
:param rev: Bazaar revision object
366
:param tree: Bazaar revision tree
367
:param roundtrip: Whether to roundtrip all Bazaar revision data
369
unusual_modes = extract_unusual_modes(rev)
370
present_parents = self.repository.has_revisions(rev.parent_ids)
371
parent_trees = self.tree_cache.revision_trees(
372
[p for p in rev.parent_ids if p in present_parents])
374
for path, obj, ie in _tree_to_objects(tree, parent_trees,
375
self._cache.idmap, unusual_modes, self.mapping.BZR_DUMMY_FILE):
379
# Don't yield just yet
382
if root_tree is None:
383
# Pointless commit - get the tree sha elsewhere
384
if not rev.parent_ids:
387
base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
388
root_tree = self[self[base_sha1].tree]
389
root_ie = tree.inventory.root
390
if roundtrip and self.mapping.BZR_FILE_IDS_FILE is not None:
391
b = self._create_fileid_map_blob(tree.inventory)
393
root_tree[self.mapping.BZR_FILE_IDS_FILE] = ((stat.S_IFREG | 0644), b.id)
394
yield self.mapping.BZR_FILE_IDS_FILE, b, None
395
yield "", root_tree, root_ie
397
testament3 = StrictTestament3(rev, tree.inventory)
398
verifiers = { "testament3-sha1": testament3.as_sha1() }
401
commit_obj = self._reconstruct_commit(rev, root_tree.id,
402
roundtrip=roundtrip, verifiers=verifiers)
404
foreign_revid, mapping = mapping_registry.parse_revision_id(
406
except errors.InvalidRevisionId:
409
_check_expected_sha(foreign_revid, commit_obj)
410
yield None, commit_obj, None
412
def _get_updater(self, rev):
413
return self._cache.get_updater(rev)
415
def _update_sha_map_revision(self, revid):
416
rev = self.repository.get_revision(revid)
417
tree = self.tree_cache.revision_tree(rev.revision_id)
418
updater = self._get_updater(rev)
419
for path, obj, ie in self._revision_to_objects(rev, tree,
421
if isinstance(obj, Commit):
422
testament3 = StrictTestament3(rev, tree.inventory)
423
ie = { "testament3-sha1": testament3.as_sha1() }
424
updater.add_object(obj, ie, path)
425
commit_obj = updater.finish()
428
def _reconstruct_blobs(self, keys):
429
"""Return a Git Blob object from a fileid and revision stored in bzr.
431
:param fileid: File id of the text
432
:param revision: Revision of the text
434
stream = self.repository.iter_files_bytes(
435
((key[0], key[1], key) for key in keys))
436
for (fileid, revision, expected_sha), chunks in stream:
438
blob.chunked = chunks
439
if blob.id != expected_sha and blob.data == "":
440
# Perhaps it's a symlink ?
441
tree = self.tree_cache.revision_tree(revision)
442
entry = tree.inventory[fileid]
443
if entry.kind == 'symlink':
444
blob = symlink_to_blob(entry)
445
_check_expected_sha(expected_sha, blob)
448
def _reconstruct_tree(self, fileid, revid, inv, unusual_modes,
450
"""Return a Git Tree object from a file id and a revision stored in bzr.
452
:param fileid: fileid in the tree.
453
:param revision: Revision of the tree.
455
def get_ie_sha1(entry):
456
if entry.kind == "directory":
458
return self._cache.idmap.lookup_tree_id(entry.file_id,
460
except (NotImplementedError, KeyError):
461
obj = self._reconstruct_tree(entry.file_id, revid, inv,
467
elif entry.kind in ("file", "symlink"):
469
return self._cache.idmap.lookup_blob_id(entry.file_id,
473
return self._reconstruct_blobs(
474
[(entry.file_id, entry.revision, None)]).next().id
476
raise AssertionError("unknown entry kind '%s'" % entry.kind)
477
tree = directory_to_tree(inv[fileid], get_ie_sha1, unusual_modes,
478
self.mapping.BZR_DUMMY_FILE)
479
if (inv.root.file_id == fileid and
480
self.mapping.BZR_FILE_IDS_FILE is not None):
481
b = self._create_fileid_map_blob(inv)
482
# If this is the root tree, add the file ids
483
tree[self.mapping.BZR_FILE_IDS_FILE] = ((stat.S_IFREG | 0644), b.id)
484
_check_expected_sha(expected_sha, tree)
487
def get_parents(self, sha):
488
"""Retrieve the parents of a Git commit by SHA1.
490
:param sha: SHA1 of the commit
491
:raises: KeyError, NotCommitError
493
return self[sha].parents
495
def _lookup_revision_sha1(self, revid):
496
"""Return the SHA1 matching a Bazaar revision."""
497
if revid == NULL_REVISION:
500
return self._cache.idmap.lookup_commit(revid)
503
return mapping_registry.parse_revision_id(revid)[0]
504
except errors.InvalidRevisionId:
505
self.repository.lock_read()
507
self._update_sha_map(revid)
509
self.repository.unlock()
510
return self._cache.idmap.lookup_commit(revid)
512
def get_raw(self, sha):
513
"""Get the raw representation of a Git object by SHA1.
515
:param sha: SHA1 of the git object
518
return (obj.type, obj.as_raw_string())
520
def __contains__(self, sha):
521
# See if sha is in map
523
for (type, type_data) in self.lookup_git_sha(sha):
525
if self.repository.has_revision(type_data[0]):
528
if self.repository.texts.has_key(type_data):
531
if self.repository.has_revision(type_data[1]):
534
raise AssertionError("Unknown object type '%s'" % type)
540
def lookup_git_shas(self, shas, update_map=True):
544
ret[sha] = [("commit", (NULL_REVISION, None, {}))]
547
ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
550
# if not, see if there are any unconverted revisions and add
551
# them to the map, search for sha in map again
552
self._update_sha_map()
555
ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
560
def lookup_git_sha(self, sha, update_map=True):
561
return self.lookup_git_shas([sha], update_map=update_map)[sha]
563
def __getitem__(self, sha):
564
if self._cache.content_cache is not None:
566
return self._cache.content_cache[sha]
569
for (kind, type_data) in self.lookup_git_sha(sha):
570
# convert object to git object
572
(revid, tree_sha, verifiers) = type_data
574
rev = self.repository.get_revision(revid)
575
except errors.NoSuchRevision:
576
trace.mutter('entry for %s %s in shamap: %r, but not '
577
'found in repository', kind, sha, type_data)
579
commit = self._reconstruct_commit(rev, tree_sha, roundtrip=True,
581
_check_expected_sha(sha, commit)
584
(fileid, revision) = type_data
585
return self._reconstruct_blobs([(fileid, revision, sha)]).next()
587
(fileid, revid) = type_data
589
tree = self.tree_cache.revision_tree(revid)
590
rev = self.repository.get_revision(revid)
591
except errors.NoSuchRevision:
592
trace.mutter('entry for %s %s in shamap: %r, but not found in repository', kind, sha, type_data)
594
unusual_modes = extract_unusual_modes(rev)
596
return self._reconstruct_tree(fileid, revid,
597
tree.inventory, unusual_modes, expected_sha=sha)
598
except errors.NoSuchRevision:
601
raise AssertionError("Unknown object type '%s'" % kind)
605
def generate_lossy_pack_contents(self, have, want, progress=None,
607
return self.generate_pack_contents(have, want, progress, get_tagged,
610
def generate_pack_contents(self, have, want, progress=None,
611
get_tagged=None, lossy=False):
612
"""Iterate over the contents of a pack file.
614
:param have: List of SHA1s of objects that should not be sent
615
:param want: List of SHA1s of objects that should be sent
618
ret = self.lookup_git_shas(have + want)
619
for commit_sha in have:
621
(type, (revid, tree_sha, verifiers)) = ret[commit_sha]
625
assert type == "commit"
628
for commit_sha in want:
629
if commit_sha in have:
632
(type, (revid, tree_sha, verifiers)) = ret[commit_sha]
636
assert type == "commit"
639
graph = self.repository.get_graph()
640
todo = _find_missing_bzr_revids(graph, pending, processed)
641
trace.mutter('sending revisions %r', todo)
643
pb = ui.ui_factory.nested_progress_bar()
645
for i, revid in enumerate(todo):
646
pb.update("generating git objects", i, len(todo))
648
rev = self.repository.get_revision(revid)
649
except errors.NoSuchRevision:
651
tree = self.tree_cache.revision_tree(revid)
652
for path, obj, ie in self._revision_to_objects(rev, tree,
653
roundtrip=not lossy):
654
ret.append((obj, path))
659
def add_thin_pack(self):
662
fd, path = tempfile.mkstemp(suffix=".pack")
663
f = os.fdopen(fd, 'wb')
665
from dulwich.pack import PackData, Pack
666
from bzrlib.plugins.git.fetch import import_git_objects
669
if os.path.getsize(path) == 0:
672
pd.create_index_v2(path[:-5]+".idx", self.object_store.get_raw)
675
self.repository.lock_write()
677
self.repository.start_write_group()
679
import_git_objects(self.repository, self.mapping,
680
p.iterobjects(get_raw=self.get_raw),
683
self.repository.abort_write_group()
686
self.repository.commit_write_group()
688
self.repository.unlock()
691
# The pack isn't kept around anyway, so no point
692
# in treating full packs different from thin packs
693
add_pack = add_thin_pack