1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
2
# Copyright (C) 2012 Canonical Ltd
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
"""Map from Git sha's to Bazaar objects."""
20
from __future__ import absolute_import
22
from dulwich.objects import (
29
from dulwich.object_store import (
32
from dulwich.pack import (
45
from ..lock import LogicalLockResult
46
from ..revision import (
49
from ..sixish import viewitems
50
from ..bzr.testament import (
55
from_repository as cache_from_repository,
57
from .mapping import (
60
extract_unusual_modes,
64
from .unpeel_map import (
72
BANNED_FILENAMES = ['.git']
75
def get_object_store(repo, mapping=None):
76
git = getattr(repo, "_git", None)
78
git.object_store.unlock = lambda: None
79
git.object_store.lock_read = lambda: LogicalLockResult(lambda: None)
80
git.object_store.lock_write = lambda: LogicalLockResult(lambda: None)
81
return git.object_store
82
return BazaarObjectStore(repo, mapping)
85
MAX_TREE_CACHE_SIZE = 50 * 1024 * 1024
88
class LRUTreeCache(object):
90
def __init__(self, repository):
91
def approx_tree_size(tree):
92
# Very rough estimate, 250 per inventory entry
94
inv = tree.root_inventory
95
except AttributeError:
98
self.repository = repository
99
self._cache = lru_cache.LRUSizeCache(
100
max_size=MAX_TREE_CACHE_SIZE, after_cleanup_size=None,
101
compute_size=approx_tree_size)
103
def revision_tree(self, revid):
105
tree = self._cache[revid]
107
tree = self.repository.revision_tree(revid)
111
def iter_revision_trees(self, revids):
116
tree = self._cache[revid]
120
if tree.get_revision_id() != revid:
121
raise AssertionError(
122
"revision id did not match: %s != %s" % (
123
tree.get_revision_id(), revid))
125
for tree in self.repository.revision_trees(todo):
126
trees[tree.get_revision_id()] = tree
128
return (trees[r] for r in revids)
130
def revision_trees(self, revids):
131
return list(self.iter_revision_trees(revids))
134
self._cache[tree.get_revision_id()] = tree
137
def _find_missing_bzr_revids(graph, want, have):
138
"""Find the revisions that have to be pushed.
140
:param get_parent_map: Function that returns the parents for a sequence
142
:param want: Revisions the target wants
143
:param have: Revisions the target already has
144
:return: Set of revisions to fetch
149
extra_todo = graph.find_unique_ancestors(rev, handled)
150
todo.update(extra_todo)
151
handled.update(extra_todo)
152
if NULL_REVISION in todo:
153
todo.remove(NULL_REVISION)
157
def _check_expected_sha(expected_sha, object):
158
"""Check whether an object matches an expected SHA.
160
:param expected_sha: None or expected SHA as either binary or as hex digest
161
:param object: Object to verify
163
if expected_sha is None:
165
if len(expected_sha) == 40:
166
if expected_sha != object.sha().hexdigest().encode('ascii'):
167
raise AssertionError("Invalid sha for %r: %s" % (object,
169
elif len(expected_sha) == 20:
170
if expected_sha != object.sha().digest():
171
raise AssertionError("Invalid sha for %r: %s" % (
172
object, sha_to_hex(expected_sha)))
174
raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
178
def directory_to_tree(path, children, lookup_ie_sha1, unusual_modes,
179
empty_file_name, allow_empty=False):
180
"""Create a Git Tree object from a Bazaar directory.
182
:param path: directory path
183
:param children: Children inventory entries
184
:param lookup_ie_sha1: Lookup the Git SHA1 for a inventory entry
185
:param unusual_modes: Dictionary with unusual file modes by file ids
186
:param empty_file_name: Name to use for dummy files in empty directories,
187
None to ignore empty directories.
190
for value in children:
191
if value.name in BANNED_FILENAMES:
193
child_path = osutils.pathjoin(path, value.name)
195
mode = unusual_modes[child_path]
197
mode = entry_mode(value)
198
hexsha = lookup_ie_sha1(child_path, value)
199
if hexsha is not None:
200
tree.add(value.name.encode("utf-8"), mode, hexsha)
201
if not allow_empty and len(tree) == 0:
202
# Only the root can be an empty tree
203
if empty_file_name is not None:
204
tree.add(empty_file_name, stat.S_IFREG | 0o644, Blob().id)
210
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes,
211
dummy_file_name=None, add_cache_entry=None):
212
"""Iterate over the objects that were introduced in a revision.
215
:param parent_trees: Parent revision trees
216
:param unusual_modes: Unusual file modes dictionary
217
:param dummy_file_name: File name to use for dummy files
218
in empty directories. None to skip empty directories
219
:return: Yields (path, object, ie) entries
225
base_tree = parent_trees[0]
226
other_parent_trees = parent_trees[1:]
228
base_tree = tree._repository.revision_tree(NULL_REVISION)
229
other_parent_trees = []
231
def find_unchanged_parent_ie(file_id, kind, other, parent_trees):
232
for ptree in parent_trees:
234
ppath = ptree.id2path(file_id)
235
except errors.NoSuchId:
238
pkind = ptree.kind(ppath)
240
if (pkind == "file" and
241
ptree.get_file_sha1(ppath) == other):
243
file_id, ptree.get_file_revision(ppath))
244
if kind == "symlink":
245
if (pkind == "symlink" and
246
ptree.get_symlink_target(ppath) == other):
248
file_id, ptree.get_file_revision(ppath))
251
# Find all the changed blobs
252
for (file_id, path, changed_content, versioned, parent, name, kind,
253
executable) in tree.iter_changes(base_tree):
254
if name[1] in BANNED_FILENAMES:
256
if kind[1] == "file":
257
sha1 = tree.get_file_sha1(path[1])
260
(pfile_id, prevision) = find_unchanged_parent_ie(
261
file_id, kind[1], sha1, other_parent_trees)
265
# It existed in one of the parents, with the same contents.
266
# So no need to yield any new git objects.
268
blob_id = idmap.lookup_blob_id(
271
if not changed_content:
274
blob.data = tree.get_file_text(path[1])
277
new_blobs.append((path[1], file_id))
279
shamap[path[1]] = blob_id
280
if add_cache_entry is not None:
283
(file_id, tree.get_file_revision(path[1])), path[1])
284
elif kind[1] == "symlink":
285
target = tree.get_symlink_target(path[1])
286
blob = symlink_to_blob(target)
287
shamap[path[1]] = blob.id
288
if add_cache_entry is not None:
290
blob, (file_id, tree.get_file_revision(path[1])), path[1])
292
find_unchanged_parent_ie(
293
file_id, kind[1], target, other_parent_trees)
296
yield (path[1], blob,
297
(file_id, tree.get_file_revision(path[1])))
298
elif kind[1] is None:
299
shamap[path[1]] = None
300
elif kind[1] != 'directory':
301
raise AssertionError(kind[1])
305
dirty_dirs.add(osutils.dirname(p))
307
# Fetch contents of the blobs that were changed
308
for (path, file_id), chunks in tree.iter_files_bytes(
309
[(path, (path, file_id)) for (path, file_id) in new_blobs]):
312
if add_cache_entry is not None:
313
add_cache_entry(obj, (file_id, tree.get_file_revision(path)), path)
314
yield path, obj, (file_id, tree.get_file_revision(path))
315
shamap[path] = obj.id
317
for path in unusual_modes:
318
dirty_dirs.add(posixpath.dirname(path))
320
for dir in list(dirty_dirs):
321
for parent in osutils.parent_directories(dir):
322
if parent in dirty_dirs:
324
dirty_dirs.add(parent)
329
def ie_to_hexsha(path, ie):
334
# FIXME: Should be the same as in parent
335
if ie.kind == "file":
337
return idmap.lookup_blob_id(ie.file_id, ie.revision)
341
blob.data = tree.get_file_text(path)
342
if add_cache_entry is not None:
343
add_cache_entry(blob, (ie.file_id, ie.revision), path)
345
elif ie.kind == "symlink":
347
return idmap.lookup_blob_id(ie.file_id, ie.revision)
350
target = tree.get_symlink_target(path)
351
blob = symlink_to_blob(target)
352
if add_cache_entry is not None:
353
add_cache_entry(blob, (ie.file_id, ie.revision), path)
355
elif ie.kind == "directory":
356
# Not all cache backends store the tree information,
357
# calculate again from scratch
358
ret = directory_to_tree(
359
path, ie.children.values(), ie_to_hexsha, unusual_modes,
360
dummy_file_name, ie.parent_id is None)
367
for path in sorted(dirty_dirs, reverse=True):
368
if not tree.has_filename(path):
371
if tree.kind(path) != 'directory':
374
obj = directory_to_tree(
375
path, tree.iter_child_entries(path), ie_to_hexsha, unusual_modes,
376
dummy_file_name, path == '')
379
file_id = tree.path2id(path)
380
if add_cache_entry is not None:
381
add_cache_entry(obj, (file_id, tree.get_revision_id()), path)
382
yield path, obj, (file_id, tree.get_revision_id())
383
shamap[path] = obj.id
386
class PackTupleIterable(object):
388
def __init__(self, store):
390
self.store.lock_read()
396
def add(self, sha, path):
397
self.objects[sha] = path
400
return len(self.objects)
403
return ((self.store[object_id], path) for (object_id, path) in
404
viewitems(self.objects))
407
class BazaarObjectStore(BaseObjectStore):
408
"""A Git-style object store backed onto a Bazaar repository."""
410
def __init__(self, repository, mapping=None):
411
self.repository = repository
412
self._map_updated = False
415
self.mapping = default_mapping
417
self.mapping = mapping
418
self._cache = cache_from_repository(repository)
419
self._content_cache_types = ("tree",)
420
self.start_write_group = self._cache.idmap.start_write_group
421
self.abort_write_group = self._cache.idmap.abort_write_group
422
self.commit_write_group = self._cache.idmap.commit_write_group
423
self.tree_cache = LRUTreeCache(self.repository)
424
self.unpeel_map = UnpeelMap.from_repository(self.repository)
426
def _missing_revisions(self, revisions):
427
return self._cache.idmap.missing_revisions(revisions)
429
def _update_sha_map(self, stop_revision=None):
430
if not self.is_locked():
431
raise errors.LockNotHeld(self)
432
if self._map_updated:
434
if (stop_revision is not None and
435
not self._missing_revisions([stop_revision])):
437
graph = self.repository.get_graph()
438
if stop_revision is None:
439
all_revids = self.repository.all_revision_ids()
440
missing_revids = self._missing_revisions(all_revids)
442
heads = set([stop_revision])
443
missing_revids = self._missing_revisions(heads)
445
parents = graph.get_parent_map(heads)
447
for p in parents.values():
448
todo.update([x for x in p if x not in missing_revids])
449
heads = self._missing_revisions(todo)
450
missing_revids.update(heads)
451
if NULL_REVISION in missing_revids:
452
missing_revids.remove(NULL_REVISION)
453
missing_revids = self.repository.has_revisions(missing_revids)
454
if not missing_revids:
455
if stop_revision is None:
456
self._map_updated = True
458
self.start_write_group()
460
pb = ui.ui_factory.nested_progress_bar()
462
for i, revid in enumerate(graph.iter_topo_order(
464
trace.mutter('processing %r', revid)
465
pb.update("updating git map", i, len(missing_revids))
466
self._update_sha_map_revision(revid)
469
if stop_revision is None:
470
self._map_updated = True
471
except BaseException:
472
self.abort_write_group()
475
self.commit_write_group()
478
self._update_sha_map()
479
return iter(self._cache.idmap.sha1s())
481
def _reconstruct_commit(self, rev, tree_sha, lossy, verifiers):
482
"""Reconstruct a Commit object.
484
:param rev: Revision object
485
:param tree_sha: SHA1 of the root tree object
486
:param lossy: Whether or not to roundtrip bzr metadata
487
:param verifiers: Verifiers for the commits
488
:return: Commit object
490
def parent_lookup(revid):
492
return self._lookup_revision_sha1(revid)
493
except errors.NoSuchRevision:
495
return self.mapping.export_commit(rev, tree_sha, parent_lookup,
498
def _create_fileid_map_blob(self, tree):
499
# FIXME: This can probably be a lot more efficient,
500
# not all files necessarily have to be processed.
502
for (path, ie) in tree.iter_entries_by_dir():
503
if self.mapping.generate_file_id(path) != ie.file_id:
504
file_ids[path] = ie.file_id
505
return self.mapping.export_fileid_map(file_ids)
507
def _revision_to_objects(self, rev, tree, lossy, add_cache_entry=None):
508
"""Convert a revision to a set of git objects.
510
:param rev: Bazaar revision object
511
:param tree: Bazaar revision tree
512
:param lossy: Whether to not roundtrip all Bazaar revision data
514
unusual_modes = extract_unusual_modes(rev)
515
present_parents = self.repository.has_revisions(rev.parent_ids)
516
parent_trees = self.tree_cache.revision_trees(
517
[p for p in rev.parent_ids if p in present_parents])
519
for path, obj, bzr_key_data in _tree_to_objects(
520
tree, parent_trees, self._cache.idmap, unusual_modes,
521
self.mapping.BZR_DUMMY_FILE, add_cache_entry):
524
root_key_data = bzr_key_data
525
# Don't yield just yet
528
if root_tree is None:
529
# Pointless commit - get the tree sha elsewhere
530
if not rev.parent_ids:
533
base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
534
root_tree = self[self[base_sha1].tree]
535
root_key_data = (tree.get_root_id(), tree.get_revision_id())
536
if not lossy and self.mapping.BZR_FILE_IDS_FILE is not None:
537
b = self._create_fileid_map_blob(tree)
539
root_tree[self.mapping.BZR_FILE_IDS_FILE] = (
540
(stat.S_IFREG | 0o644), b.id)
541
yield self.mapping.BZR_FILE_IDS_FILE, b
542
if add_cache_entry is not None:
543
add_cache_entry(root_tree, root_key_data, "")
546
testament3 = StrictTestament3(rev, tree)
547
verifiers = {"testament3-sha1": testament3.as_sha1()}
550
commit_obj = self._reconstruct_commit(rev, root_tree.id,
551
lossy=lossy, verifiers=verifiers)
553
foreign_revid, mapping = mapping_registry.parse_revision_id(
555
except errors.InvalidRevisionId:
558
_check_expected_sha(foreign_revid, commit_obj)
559
if add_cache_entry is not None:
560
add_cache_entry(commit_obj, verifiers, None)
562
yield None, commit_obj
564
def _get_updater(self, rev):
565
return self._cache.get_updater(rev)
567
def _update_sha_map_revision(self, revid):
568
rev = self.repository.get_revision(revid)
569
tree = self.tree_cache.revision_tree(rev.revision_id)
570
updater = self._get_updater(rev)
571
# FIXME JRV 2011-12-15: Shouldn't we try both values for lossy ?
572
for path, obj in self._revision_to_objects(
573
rev, tree, lossy=(not self.mapping.roundtripping),
574
add_cache_entry=updater.add_object):
575
if isinstance(obj, Commit):
577
commit_obj = updater.finish()
580
def _reconstruct_blobs(self, keys):
581
"""Return a Git Blob object from a fileid and revision stored in bzr.
583
:param fileid: File id of the text
584
:param revision: Revision of the text
586
stream = self.repository.iter_files_bytes(
587
((key[0], key[1], key) for key in keys))
588
for (file_id, revision, expected_sha), chunks in stream:
590
blob.chunked = chunks
591
if blob.id != expected_sha and blob.data == b"":
592
# Perhaps it's a symlink ?
593
tree = self.tree_cache.revision_tree(revision)
594
path = tree.id2path(file_id)
595
if tree.kind(path) == 'symlink':
596
blob = symlink_to_blob(tree.get_symlink_target(path))
597
_check_expected_sha(expected_sha, blob)
600
def _reconstruct_tree(self, fileid, revid, bzr_tree, unusual_modes,
602
"""Return a Git Tree object from a file id and a revision stored in bzr.
604
:param fileid: fileid in the tree.
605
:param revision: Revision of the tree.
607
def get_ie_sha1(path, entry):
608
if entry.kind == "directory":
610
return self._cache.idmap.lookup_tree_id(entry.file_id,
612
except (NotImplementedError, KeyError):
613
obj = self._reconstruct_tree(
614
entry.file_id, revid, bzr_tree, unusual_modes)
619
elif entry.kind in ("file", "symlink"):
621
return self._cache.idmap.lookup_blob_id(entry.file_id,
625
return next(self._reconstruct_blobs(
626
[(entry.file_id, entry.revision, None)])).id
627
elif entry.kind == 'tree-reference':
628
# FIXME: Make sure the file id is the root id
629
return self._lookup_revision_sha1(entry.reference_revision)
631
raise AssertionError("unknown entry kind '%s'" % entry.kind)
632
path = bzr_tree.id2path(fileid)
633
tree = directory_to_tree(
635
bzr_tree.iter_child_entries(path),
636
get_ie_sha1, unusual_modes, self.mapping.BZR_DUMMY_FILE,
637
bzr_tree.get_root_id() == fileid)
638
if (bzr_tree.get_root_id() == fileid and
639
self.mapping.BZR_FILE_IDS_FILE is not None):
642
b = self._create_fileid_map_blob(bzr_tree)
643
# If this is the root tree, add the file ids
644
tree[self.mapping.BZR_FILE_IDS_FILE] = (
645
(stat.S_IFREG | 0o644), b.id)
647
_check_expected_sha(expected_sha, tree)
650
def get_parents(self, sha):
651
"""Retrieve the parents of a Git commit by SHA1.
653
:param sha: SHA1 of the commit
654
:raises: KeyError, NotCommitError
656
return self[sha].parents
658
def _lookup_revision_sha1(self, revid):
659
"""Return the SHA1 matching a Bazaar revision."""
660
if revid == NULL_REVISION:
663
return self._cache.idmap.lookup_commit(revid)
666
return mapping_registry.parse_revision_id(revid)[0]
667
except errors.InvalidRevisionId:
668
self._update_sha_map(revid)
669
return self._cache.idmap.lookup_commit(revid)
671
def get_raw(self, sha):
672
"""Get the raw representation of a Git object by SHA1.
674
:param sha: SHA1 of the git object
677
sha = sha_to_hex(sha)
679
return (obj.type, obj.as_raw_string())
681
def __contains__(self, sha):
682
# See if sha is in map
684
for (type, type_data) in self.lookup_git_sha(sha):
686
if self.repository.has_revision(type_data[0]):
689
if type_data in self.repository.texts:
692
if self.repository.has_revision(type_data[1]):
695
raise AssertionError("Unknown object type '%s'" % type)
703
self._map_updated = False
704
self.repository.lock_read()
705
return LogicalLockResult(self.unlock)
707
def lock_write(self):
709
self._map_updated = False
710
self.repository.lock_write()
711
return LogicalLockResult(self.unlock)
714
return (self._locked is not None)
718
self._map_updated = False
719
self.repository.unlock()
721
def lookup_git_shas(self, shas):
725
ret[sha] = [("commit", (NULL_REVISION, None, {}))]
728
ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
730
# if not, see if there are any unconverted revisions and
731
# add them to the map, search for sha in map again
732
self._update_sha_map()
734
ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
739
def lookup_git_sha(self, sha):
740
return self.lookup_git_shas([sha])[sha]
742
def __getitem__(self, sha):
743
for (kind, type_data) in self.lookup_git_sha(sha):
744
# convert object to git object
746
(revid, tree_sha, verifiers) = type_data
748
rev = self.repository.get_revision(revid)
749
except errors.NoSuchRevision:
750
if revid == NULL_REVISION:
751
raise AssertionError(
752
"should not try to look up NULL_REVISION")
753
trace.mutter('entry for %s %s in shamap: %r, but not '
754
'found in repository', kind, sha, type_data)
756
# FIXME: the type data should say whether conversion was
758
commit = self._reconstruct_commit(
759
rev, tree_sha, lossy=(not self.mapping.roundtripping),
761
_check_expected_sha(sha, commit)
764
(fileid, revision) = type_data
765
blobs = self._reconstruct_blobs([(fileid, revision, sha)])
768
(fileid, revid) = type_data
770
tree = self.tree_cache.revision_tree(revid)
771
rev = self.repository.get_revision(revid)
772
except errors.NoSuchRevision:
774
'entry for %s %s in shamap: %r, but not found in '
775
'repository', kind, sha, type_data)
777
unusual_modes = extract_unusual_modes(rev)
779
return self._reconstruct_tree(
780
fileid, revid, tree, unusual_modes, expected_sha=sha)
781
except errors.NoSuchRevision:
784
raise AssertionError("Unknown object type '%s'" % kind)
788
def generate_lossy_pack_data(self, have, want, progress=None,
789
get_tagged=None, ofs_delta=False):
790
return pack_objects_to_data(
791
self.generate_pack_contents(have, want, progress, get_tagged,
794
def generate_pack_contents(self, have, want, progress=None,
795
ofs_delta=False, get_tagged=None, lossy=False):
796
"""Iterate over the contents of a pack file.
798
:param have: List of SHA1s of objects that should not be sent
799
:param want: List of SHA1s of objects that should be sent
802
ret = self.lookup_git_shas(have + want)
803
for commit_sha in have:
804
commit_sha = self.unpeel_map.peel_tag(commit_sha, commit_sha)
806
for (type, type_data) in ret[commit_sha]:
808
raise AssertionError("Type was %s, not commit" % type)
809
processed.add(type_data[0])
811
trace.mutter("unable to find remote ref %s", commit_sha)
813
for commit_sha in want:
814
if commit_sha in have:
817
for (type, type_data) in ret[commit_sha]:
819
raise AssertionError("Type was %s, not commit" % type)
820
pending.add(type_data[0])
824
graph = self.repository.get_graph()
825
todo = _find_missing_bzr_revids(graph, pending, processed)
826
ret = PackTupleIterable(self)
827
pb = ui.ui_factory.nested_progress_bar()
829
for i, revid in enumerate(graph.iter_topo_order(todo)):
830
pb.update("generating git objects", i, len(todo))
832
rev = self.repository.get_revision(revid)
833
except errors.NoSuchRevision:
835
tree = self.tree_cache.revision_tree(revid)
836
for path, obj in self._revision_to_objects(
837
rev, tree, lossy=lossy):
838
ret.add(obj.id, path)
843
def add_thin_pack(self):
846
fd, path = tempfile.mkstemp(suffix=".pack")
847
f = os.fdopen(fd, 'wb')
850
from .fetch import import_git_objects
853
if os.path.getsize(path) == 0:
856
pd.create_index_v2(path[:-5] + ".idx", self.object_store.get_raw)
859
with self.repository.lock_write():
860
self.repository.start_write_group()
862
import_git_objects(self.repository, self.mapping,
863
p.iterobjects(get_raw=self.get_raw),
865
except BaseException:
866
self.repository.abort_write_group()
869
self.repository.commit_write_group()
872
# The pack isn't kept around anyway, so no point
873
# in treating full packs different from thin packs
874
add_pack = add_thin_pack