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 ..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(max_size=MAX_TREE_CACHE_SIZE,
100
after_cleanup_size=None, compute_size=approx_tree_size)
102
def revision_tree(self, revid):
104
tree = self._cache[revid]
106
tree = self.repository.revision_tree(revid)
110
def iter_revision_trees(self, revids):
115
tree = self._cache[revid]
119
if tree.get_revision_id() != revid:
120
raise AssertionError(
121
"revision id did not match: %s != %s" % (
122
tree.get_revision_id(), revid))
124
for tree in self.repository.revision_trees(todo):
125
trees[tree.get_revision_id()] = tree
127
return (trees[r] for r in revids)
129
def revision_trees(self, revids):
130
return list(self.iter_revision_trees(revids))
133
self._cache[tree.get_revision_id()] = tree
136
def _find_missing_bzr_revids(graph, want, have):
137
"""Find the revisions that have to be pushed.
139
:param get_parent_map: Function that returns the parents for a sequence
141
:param want: Revisions the target wants
142
:param have: Revisions the target already has
143
:return: Set of revisions to fetch
148
extra_todo = graph.find_unique_ancestors(rev, handled)
149
todo.update(extra_todo)
150
handled.update(extra_todo)
151
if NULL_REVISION in todo:
152
todo.remove(NULL_REVISION)
156
def _check_expected_sha(expected_sha, object):
157
"""Check whether an object matches an expected SHA.
159
:param expected_sha: None or expected SHA as either binary or as hex digest
160
:param object: Object to verify
162
if expected_sha is None:
164
if len(expected_sha) == 40:
165
if expected_sha != object.sha().hexdigest().encode('ascii'):
166
raise AssertionError("Invalid sha for %r: %s" % (object,
168
elif len(expected_sha) == 20:
169
if expected_sha != object.sha().digest():
170
raise AssertionError("Invalid sha for %r: %s" % (object,
171
sha_to_hex(expected_sha)))
173
raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
177
def directory_to_tree(path, children, lookup_ie_sha1, unusual_modes, empty_file_name,
179
"""Create a Git Tree object from a Bazaar directory.
181
:param path: directory path
182
:param children: Children inventory entries
183
:param lookup_ie_sha1: Lookup the Git SHA1 for a inventory entry
184
:param unusual_modes: Dictionary with unusual file modes by file ids
185
:param empty_file_name: Name to use for dummy files in empty directories,
186
None to ignore empty directories.
189
for value in children:
190
if value.name in BANNED_FILENAMES:
192
child_path = osutils.pathjoin(path, value.name)
194
mode = unusual_modes[child_path]
196
mode = entry_mode(value)
197
hexsha = lookup_ie_sha1(child_path, value)
198
if hexsha is not None:
199
tree.add(value.name.encode("utf-8"), mode, hexsha)
200
if not allow_empty and len(tree) == 0:
201
# Only the root can be an empty tree
202
if empty_file_name is not None:
203
tree.add(empty_file_name, stat.S_IFREG | 0o644, Blob().id)
209
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes,
210
dummy_file_name=None, add_cache_entry=None):
211
"""Iterate over the objects that were introduced in a revision.
214
:param parent_trees: Parent revision trees
215
:param unusual_modes: Unusual file modes dictionary
216
:param dummy_file_name: File name to use for dummy files
217
in empty directories. None to skip empty directories
218
: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 = []
230
def find_unchanged_parent_ie(file_id, kind, other, parent_trees):
231
for ptree in parent_trees:
233
ppath = ptree.id2path(file_id)
234
except errors.NoSuchId:
237
pkind = ptree.kind(ppath, file_id)
239
if (pkind == "file" and
240
ptree.get_file_sha1(ppath, file_id) == other):
241
return (file_id, ptree.get_file_revision(ppath, file_id))
242
if kind == "symlink":
243
if (pkind == "symlink" and
244
ptree.get_symlink_target(ppath, file_id) == other):
245
return (file_id, ptree.get_file_revision(ppath, file_id))
248
# Find all the changed blobs
249
for (file_id, path, changed_content, versioned, parent, name, kind,
250
executable) in tree.iter_changes(base_tree):
251
if name[1] in BANNED_FILENAMES:
253
if kind[1] == "file":
254
sha1 = tree.get_file_sha1(path[1], file_id)
257
(pfile_id, prevision) = find_unchanged_parent_ie(file_id, kind[1], sha1, other_parent_trees)
261
# It existed in one of the parents, with the same contents.
262
# So no need to yield any new git objects.
264
blob_id = idmap.lookup_blob_id(
267
if not changed_content:
270
blob.data = tree.get_file_text(path[1], file_id)
273
new_blobs.append((path[1], file_id))
275
shamap[path[1]] = blob_id
276
if add_cache_entry is not None:
277
add_cache_entry(("blob", blob_id), (file_id, tree.get_file_revision(path[1])), path[1])
278
elif kind[1] == "symlink":
279
target = tree.get_symlink_target(path[1], file_id)
280
blob = symlink_to_blob(target)
281
shamap[path[1]] = blob.id
282
if add_cache_entry is not None:
283
add_cache_entry(blob, (file_id, tree.get_file_revision(path[1])), path[1])
285
find_unchanged_parent_ie(file_id, kind[1], target, other_parent_trees)
288
yield path[1], blob, (file_id, tree.get_file_revision(path[1], file_id))
289
elif kind[1] is None:
290
shamap[path[1]] = None
291
elif kind[1] != 'directory':
292
raise AssertionError(kind[1])
296
dirty_dirs.add(osutils.dirname(p))
298
# Fetch contents of the blobs that were changed
299
for (path, file_id), chunks in tree.iter_files_bytes(
300
[(path, (path, file_id)) for (path, file_id) in new_blobs]):
303
if add_cache_entry is not None:
304
add_cache_entry(obj, (file_id, tree.get_file_revision(path)), path)
305
yield path, obj, (file_id, tree.get_file_revision(path, file_id))
306
shamap[path] = obj.id
308
for path in unusual_modes:
309
dirty_dirs.add(posixpath.dirname(path))
311
for dir in list(dirty_dirs):
312
for parent in osutils.parent_directories(dir):
313
if parent in dirty_dirs:
315
dirty_dirs.add(parent)
320
def ie_to_hexsha(path, ie):
325
# FIXME: Should be the same as in parent
326
if ie.kind in ("file", "symlink"):
328
return idmap.lookup_blob_id(ie.file_id, ie.revision)
332
blob.data = tree.get_file_text(path, ie.file_id)
333
if add_cache_entry is not None:
334
add_cache_entry(blob, (ie.file_id, ie.revision), path)
336
elif ie.kind == "directory":
337
# Not all cache backends store the tree information,
338
# calculate again from scratch
339
ret = directory_to_tree(path, ie.children.values(), ie_to_hexsha,
340
unusual_modes, dummy_file_name, ie.parent_id is None)
347
for path in sorted(dirty_dirs, reverse=True):
348
if not tree.has_filename(path):
351
if tree.kind(path) != 'directory':
355
for value in tree.iter_child_entries(path):
356
if value.name in BANNED_FILENAMES:
357
trace.warning('not exporting %s with banned filename %s',
358
value.kind, value.name)
360
child_path = osutils.pathjoin(path, value.name)
362
mode = unusual_modes[child_path]
364
mode = entry_mode(value)
365
hexsha = ie_to_hexsha(child_path, value)
366
if hexsha is not None:
367
obj.add(value.name.encode("utf-8"), mode, hexsha)
370
file_id = tree.path2id(path)
371
if add_cache_entry is not None:
372
add_cache_entry(obj, (file_id, tree.get_revision_id()), path)
373
yield path, obj, (file_id, tree.get_revision_id())
374
shamap[path] = obj.id
377
class PackTupleIterable(object):
379
def __init__(self, store):
381
self.store.lock_read()
387
def add(self, sha, path):
388
self.objects[sha] = path
391
return len(self.objects)
394
return ((self.store[object_id], path) for (object_id, path) in
395
viewitems(self.objects))
398
class BazaarObjectStore(BaseObjectStore):
399
"""A Git-style object store backed onto a Bazaar repository."""
401
def __init__(self, repository, mapping=None):
402
self.repository = repository
403
self._map_updated = False
406
self.mapping = default_mapping
408
self.mapping = mapping
409
self._cache = cache_from_repository(repository)
410
self._content_cache_types = ("tree",)
411
self.start_write_group = self._cache.idmap.start_write_group
412
self.abort_write_group = self._cache.idmap.abort_write_group
413
self.commit_write_group = self._cache.idmap.commit_write_group
414
self.tree_cache = LRUTreeCache(self.repository)
415
self.unpeel_map = UnpeelMap.from_repository(self.repository)
417
def _missing_revisions(self, revisions):
418
return self._cache.idmap.missing_revisions(revisions)
420
def _update_sha_map(self, stop_revision=None):
421
if not self.is_locked():
422
raise errors.LockNotHeld(self)
423
if self._map_updated:
425
if (stop_revision is not None and
426
not self._missing_revisions([stop_revision])):
428
graph = self.repository.get_graph()
429
if stop_revision is None:
430
all_revids = self.repository.all_revision_ids()
431
missing_revids = self._missing_revisions(all_revids)
433
heads = set([stop_revision])
434
missing_revids = self._missing_revisions(heads)
436
parents = graph.get_parent_map(heads)
438
for p in parents.values():
439
todo.update([x for x in p if x not in missing_revids])
440
heads = self._missing_revisions(todo)
441
missing_revids.update(heads)
442
if NULL_REVISION in missing_revids:
443
missing_revids.remove(NULL_REVISION)
444
missing_revids = self.repository.has_revisions(missing_revids)
445
if not missing_revids:
446
if stop_revision is None:
447
self._map_updated = True
449
self.start_write_group()
451
pb = ui.ui_factory.nested_progress_bar()
453
for i, revid in enumerate(graph.iter_topo_order(missing_revids)):
454
trace.mutter('processing %r', revid)
455
pb.update("updating git map", i, len(missing_revids))
456
self._update_sha_map_revision(revid)
459
if stop_revision is None:
460
self._map_updated = True
462
self.abort_write_group()
465
self.commit_write_group()
468
self._update_sha_map()
469
return iter(self._cache.idmap.sha1s())
471
def _reconstruct_commit(self, rev, tree_sha, lossy, verifiers):
472
"""Reconstruct a Commit object.
474
:param rev: Revision object
475
:param tree_sha: SHA1 of the root tree object
476
:param lossy: Whether or not to roundtrip bzr metadata
477
:param verifiers: Verifiers for the commits
478
:return: Commit object
480
def parent_lookup(revid):
482
return self._lookup_revision_sha1(revid)
483
except errors.NoSuchRevision:
485
return self.mapping.export_commit(rev, tree_sha, parent_lookup,
488
def _create_fileid_map_blob(self, tree):
489
# FIXME: This can probably be a lot more efficient,
490
# not all files necessarily have to be processed.
492
for (path, ie) in tree.iter_entries_by_dir():
493
if self.mapping.generate_file_id(path) != ie.file_id:
494
file_ids[path] = ie.file_id
495
return self.mapping.export_fileid_map(file_ids)
497
def _revision_to_objects(self, rev, tree, lossy, add_cache_entry=None):
498
"""Convert a revision to a set of git objects.
500
:param rev: Bazaar revision object
501
:param tree: Bazaar revision tree
502
:param lossy: Whether to not roundtrip all Bazaar revision data
504
unusual_modes = extract_unusual_modes(rev)
505
present_parents = self.repository.has_revisions(rev.parent_ids)
506
parent_trees = self.tree_cache.revision_trees(
507
[p for p in rev.parent_ids if p in present_parents])
509
for path, obj, bzr_key_data in _tree_to_objects(tree, parent_trees,
510
self._cache.idmap, unusual_modes,
511
self.mapping.BZR_DUMMY_FILE, add_cache_entry):
514
root_key_data = bzr_key_data
515
# Don't yield just yet
518
if root_tree is None:
519
# Pointless commit - get the tree sha elsewhere
520
if not rev.parent_ids:
523
base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
524
root_tree = self[self[base_sha1].tree]
525
root_key_data = (tree.get_root_id(), tree.get_revision_id())
526
if not lossy and self.mapping.BZR_FILE_IDS_FILE is not None:
527
b = self._create_fileid_map_blob(tree)
529
root_tree[self.mapping.BZR_FILE_IDS_FILE] = (
530
(stat.S_IFREG | 0o644), b.id)
531
yield self.mapping.BZR_FILE_IDS_FILE, b
532
if add_cache_entry is not None:
533
add_cache_entry(root_tree, root_key_data, "")
536
testament3 = StrictTestament3(rev, tree)
537
verifiers = { "testament3-sha1": testament3.as_sha1() }
540
commit_obj = self._reconstruct_commit(rev, root_tree.id,
541
lossy=lossy, verifiers=verifiers)
543
foreign_revid, mapping = mapping_registry.parse_revision_id(
545
except errors.InvalidRevisionId:
548
_check_expected_sha(foreign_revid, commit_obj)
549
if add_cache_entry is not None:
550
add_cache_entry(commit_obj, verifiers, None)
552
yield None, commit_obj
554
def _get_updater(self, rev):
555
return self._cache.get_updater(rev)
557
def _update_sha_map_revision(self, revid):
558
rev = self.repository.get_revision(revid)
559
tree = self.tree_cache.revision_tree(rev.revision_id)
560
updater = self._get_updater(rev)
561
# FIXME JRV 2011-12-15: Shouldn't we try both values for lossy ?
562
for path, obj in self._revision_to_objects(
563
rev, tree, lossy=(not self.mapping.roundtripping),
564
add_cache_entry=updater.add_object):
565
if isinstance(obj, Commit):
567
commit_obj = updater.finish()
570
def _reconstruct_blobs(self, keys):
571
"""Return a Git Blob object from a fileid and revision stored in bzr.
573
:param fileid: File id of the text
574
:param revision: Revision of the text
576
stream = self.repository.iter_files_bytes(
577
((key[0], key[1], key) for key in keys))
578
for (file_id, revision, expected_sha), chunks in stream:
580
blob.chunked = chunks
581
if blob.id != expected_sha and blob.data == "":
582
# Perhaps it's a symlink ?
583
tree = self.tree_cache.revision_tree(revision)
584
path = tree.id2path(file_id)
585
if tree.kind(path, file_id) == 'symlink':
586
blob = symlink_to_blob(tree.get_symlink_target(path, file_id))
587
_check_expected_sha(expected_sha, blob)
590
def _reconstruct_tree(self, fileid, revid, bzr_tree, unusual_modes,
592
"""Return a Git Tree object from a file id and a revision stored in bzr.
594
:param fileid: fileid in the tree.
595
:param revision: Revision of the tree.
597
def get_ie_sha1(path, entry):
598
if entry.kind == "directory":
600
return self._cache.idmap.lookup_tree_id(entry.file_id,
602
except (NotImplementedError, KeyError):
603
obj = self._reconstruct_tree(entry.file_id, revid, bzr_tree,
609
elif entry.kind in ("file", "symlink"):
611
return self._cache.idmap.lookup_blob_id(entry.file_id,
615
return next(self._reconstruct_blobs(
616
[(entry.file_id, entry.revision, None)])).id
617
elif entry.kind == 'tree-reference':
618
# FIXME: Make sure the file id is the root id
619
return self._lookup_revision_sha1(entry.reference_revision)
621
raise AssertionError("unknown entry kind '%s'" % entry.kind)
622
path = bzr_tree.id2path(fileid)
623
tree = directory_to_tree(
625
bzr_tree.iter_child_entries(path),
626
get_ie_sha1, unusual_modes, self.mapping.BZR_DUMMY_FILE,
627
bzr_tree.get_root_id() == fileid)
628
if (bzr_tree.get_root_id() == fileid and
629
self.mapping.BZR_FILE_IDS_FILE is not None):
632
b = self._create_fileid_map_blob(bzr_tree)
633
# If this is the root tree, add the file ids
634
tree[self.mapping.BZR_FILE_IDS_FILE] = (
635
(stat.S_IFREG | 0o644), b.id)
637
_check_expected_sha(expected_sha, tree)
640
def get_parents(self, sha):
641
"""Retrieve the parents of a Git commit by SHA1.
643
:param sha: SHA1 of the commit
644
:raises: KeyError, NotCommitError
646
return self[sha].parents
648
def _lookup_revision_sha1(self, revid):
649
"""Return the SHA1 matching a Bazaar revision."""
650
if revid == NULL_REVISION:
653
return self._cache.idmap.lookup_commit(revid)
656
return mapping_registry.parse_revision_id(revid)[0]
657
except errors.InvalidRevisionId:
658
self._update_sha_map(revid)
659
return self._cache.idmap.lookup_commit(revid)
661
def get_raw(self, sha):
662
"""Get the raw representation of a Git object by SHA1.
664
:param sha: SHA1 of the git object
667
sha = sha_to_hex(sha)
669
return (obj.type, obj.as_raw_string())
671
def __contains__(self, sha):
672
# See if sha is in map
674
for (type, type_data) in self.lookup_git_sha(sha):
676
if self.repository.has_revision(type_data[0]):
679
if type_data in self.repository.texts:
682
if self.repository.has_revision(type_data[1]):
685
raise AssertionError("Unknown object type '%s'" % type)
693
self._map_updated = False
694
self.repository.lock_read()
695
return LogicalLockResult(self.unlock)
697
def lock_write(self):
699
self._map_updated = False
700
self.repository.lock_write()
701
return LogicalLockResult(self.unlock)
704
return (self._locked is not None)
708
self._map_updated = False
709
self.repository.unlock()
711
def lookup_git_shas(self, shas):
715
ret[sha] = [("commit", (NULL_REVISION, None, {}))]
718
ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
720
# if not, see if there are any unconverted revisions and
721
# add them to the map, search for sha in map again
722
self._update_sha_map()
724
ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
729
def lookup_git_sha(self, sha):
730
return self.lookup_git_shas([sha])[sha]
732
def __getitem__(self, sha):
733
for (kind, type_data) in self.lookup_git_sha(sha):
734
# convert object to git object
736
(revid, tree_sha, verifiers) = type_data
738
rev = self.repository.get_revision(revid)
739
except errors.NoSuchRevision:
740
if revid == NULL_REVISION:
741
raise AssertionError(
742
"should not try to look up NULL_REVISION")
743
trace.mutter('entry for %s %s in shamap: %r, but not '
744
'found in repository', kind, sha, type_data)
746
# FIXME: the type data should say whether conversion was lossless
747
commit = self._reconstruct_commit(rev, tree_sha,
748
lossy=(not self.mapping.roundtripping), verifiers=verifiers)
749
_check_expected_sha(sha, commit)
752
(fileid, revision) = type_data
753
blobs = self._reconstruct_blobs([(fileid, revision, sha)])
756
(fileid, revid) = type_data
758
tree = self.tree_cache.revision_tree(revid)
759
rev = self.repository.get_revision(revid)
760
except errors.NoSuchRevision:
761
trace.mutter('entry for %s %s in shamap: %r, but not found in '
762
'repository', kind, sha, type_data)
764
unusual_modes = extract_unusual_modes(rev)
766
return self._reconstruct_tree(fileid, revid,
767
tree, unusual_modes, expected_sha=sha)
768
except errors.NoSuchRevision:
771
raise AssertionError("Unknown object type '%s'" % kind)
775
def generate_lossy_pack_data(self, have, want, progress=None,
776
get_tagged=None, ofs_delta=False):
777
return pack_objects_to_data(
778
self.generate_pack_contents(have, want, progress, get_tagged,
781
def generate_pack_contents(self, have, want, progress=None,
782
ofs_delta=False, get_tagged=None, lossy=False):
783
"""Iterate over the contents of a pack file.
785
:param have: List of SHA1s of objects that should not be sent
786
:param want: List of SHA1s of objects that should be sent
789
ret = self.lookup_git_shas(have + want)
790
for commit_sha in have:
791
commit_sha = self.unpeel_map.peel_tag(commit_sha, commit_sha)
793
for (type, type_data) in ret[commit_sha]:
795
raise AssertionError("Type was %s, not commit" % type)
796
processed.add(type_data[0])
798
trace.mutter("unable to find remote ref %s", commit_sha)
800
for commit_sha in want:
801
if commit_sha in have:
804
for (type, type_data) in ret[commit_sha]:
806
raise AssertionError("Type was %s, not commit" % type)
807
pending.add(type_data[0])
811
graph = self.repository.get_graph()
812
todo = _find_missing_bzr_revids(graph, pending, processed)
813
ret = PackTupleIterable(self)
814
pb = ui.ui_factory.nested_progress_bar()
816
for i, revid in enumerate(graph.iter_topo_order(todo)):
817
pb.update("generating git objects", i, len(todo))
819
rev = self.repository.get_revision(revid)
820
except errors.NoSuchRevision:
822
tree = self.tree_cache.revision_tree(revid)
823
for path, obj in self._revision_to_objects(
824
rev, tree, lossy=lossy):
825
ret.add(obj.id, path)
830
def add_thin_pack(self):
833
fd, path = tempfile.mkstemp(suffix=".pack")
834
f = os.fdopen(fd, 'wb')
836
from .fetch import import_git_objects
839
if os.path.getsize(path) == 0:
842
pd.create_index_v2(path[:-5]+".idx", self.object_store.get_raw)
845
with self.repository.lock_write():
846
self.repository.start_write_group()
848
import_git_objects(self.repository, self.mapping,
849
p.iterobjects(get_raw=self.get_raw),
852
self.repository.abort_write_group()
855
self.repository.commit_write_group()
858
# The pack isn't kept around anyway, so no point
859
# in treating full packs different from thin packs
860
add_pack = add_thin_pack