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 (
43
from ...lock import LogicalLockResult
44
from ...revision import (
47
from ...testament import(
52
from_repository as cache_from_repository,
54
from .mapping import (
57
extract_unusual_modes,
61
from .unpeel_map import (
69
def get_object_store(repo, mapping=None):
70
git = getattr(repo, "_git", None)
72
git.object_store.unlock = lambda: None
73
git.object_store.lock_read = lambda: LogicalLockResult(lambda: None)
74
git.object_store.lock_write = lambda: LogicalLockResult(lambda: None)
75
return git.object_store
76
return BazaarObjectStore(repo, mapping)
79
MAX_TREE_CACHE_SIZE = 50 * 1024 * 1024
82
class LRUTreeCache(object):
84
def __init__(self, repository):
85
def approx_tree_size(tree):
86
# Very rough estimate, 250 per inventory entry
88
inv = tree.root_inventory
89
except AttributeError:
92
self.repository = repository
93
self._cache = lru_cache.LRUSizeCache(max_size=MAX_TREE_CACHE_SIZE,
94
after_cleanup_size=None, compute_size=approx_tree_size)
96
def revision_tree(self, revid):
98
tree = self._cache[revid]
100
tree = self.repository.revision_tree(revid)
104
def iter_revision_trees(self, revids):
109
tree = self._cache[revid]
113
if tree.get_revision_id() != revid:
114
raise AssertionError(
115
"revision id did not match: %s != %s" % (
116
tree.get_revision_id(), revid))
118
for tree in self.repository.revision_trees(todo):
119
trees[tree.get_revision_id()] = tree
121
return (trees[r] for r in revids)
123
def revision_trees(self, revids):
124
return list(self.iter_revision_trees(revids))
127
self._cache[tree.get_revision_id()] = tree
130
def _find_missing_bzr_revids(graph, want, have):
131
"""Find the revisions that have to be pushed.
133
:param get_parent_map: Function that returns the parents for a sequence
135
:param want: Revisions the target wants
136
:param have: Revisions the target already has
137
:return: Set of revisions to fetch
142
extra_todo = graph.find_unique_ancestors(rev, handled)
143
todo.update(extra_todo)
144
handled.update(extra_todo)
145
if NULL_REVISION in todo:
146
todo.remove(NULL_REVISION)
150
def _check_expected_sha(expected_sha, object):
151
"""Check whether an object matches an expected SHA.
153
:param expected_sha: None or expected SHA as either binary or as hex digest
154
:param object: Object to verify
156
if expected_sha is None:
158
if len(expected_sha) == 40:
159
if expected_sha != object.sha().hexdigest():
160
raise AssertionError("Invalid sha for %r: %s" % (object,
162
elif len(expected_sha) == 20:
163
if expected_sha != object.sha().digest():
164
raise AssertionError("Invalid sha for %r: %s" % (object,
165
sha_to_hex(expected_sha)))
167
raise AssertionError("Unknown length %d for %r" % (len(expected_sha),
171
def _tree_to_objects(tree, parent_trees, idmap, unusual_modes,
172
dummy_file_name=None):
173
"""Iterate over the objects that were introduced in a revision.
176
:param parent_trees: Parent revision trees
177
:param unusual_modes: Unusual file modes dictionary
178
:param dummy_file_name: File name to use for dummy files
179
in empty directories. None to skip empty directories
180
:return: Yields (path, object, ie) entries
186
base_tree = parent_trees[0]
187
other_parent_trees = parent_trees[1:]
189
base_tree = tree._repository.revision_tree(NULL_REVISION)
190
other_parent_trees = []
191
def find_unchanged_parent_ie(file_id, kind, other, parent_trees):
192
for ptree in parent_trees:
194
ppath = ptree.id2path(file_id)
195
except errors.NoSuchId:
198
pkind = ptree.kind(ppath, file_id)
200
if (pkind == "file" and
201
ptree.get_file_sha1(ppath, file_id) == other):
202
return (file_id, ptree.get_file_revision(ppath, file_id))
203
if kind == "symlink":
204
if (pkind == "symlink" and
205
ptree.get_symlink_target(ppath, file_id) == other):
206
return (file_id, ptree.get_file_revision(ppath, file_id))
209
# Find all the changed blobs
210
for (file_id, path, changed_content, versioned, parent, name, kind,
211
executable) in tree.iter_changes(base_tree):
212
if kind[1] == "file":
215
(pfile_id, prevision) = find_unchanged_parent_ie(file_id, kind[1], tree.get_file_sha1(path[1], file_id), other_parent_trees)
220
shamap[file_id] = idmap.lookup_blob_id(
225
blob.data = tree.get_file_text(path[1], file_id)
226
shamap[file_id] = blob.id
227
if not file_id in shamap:
228
new_blobs.append((path[1], file_id))
229
elif kind[1] == "symlink":
231
target = tree.get_symlink_target(path[1], file_id)
232
blob = symlink_to_blob(target)
233
shamap[file_id] = blob.id
235
find_unchanged_parent_ie(file_id, kind[1], target, other_parent_trees)
237
yield path[1], blob, (file_id, tree.get_file_revision(path[1], file_id))
238
elif kind[1] not in (None, "directory"):
239
raise AssertionError(kind[1])
241
if p and tree.has_id(p) and tree.kind(tree.id2path(p)) == "directory":
244
# Fetch contents of the blobs that were changed
245
for (path, file_id), chunks in tree.iter_files_bytes(
246
[(path, (path, file_id)) for (path, file_id) in new_blobs]):
249
yield path, obj, (file_id, tree.get_file_revision(path, file_id))
250
shamap[file_id] = obj.id
252
for path in unusual_modes:
253
parent_path = posixpath.dirname(path)
254
file_id = tree.path2id(parent_path)
256
raise AssertionError("Unable to find file id for %r" % parent_path)
257
dirty_dirs.add(file_id)
260
inv = tree.root_inventory
261
except AttributeError:
267
for file_id in dirty_dirs:
268
if file_id is None or not inv.has_id(file_id):
270
trees[inv.id2path(file_id)] = file_id
271
ie = inv.get_entry(file_id)
272
if ie.parent_id is not None:
273
new_dirs.add(ie.parent_id)
274
dirty_dirs = new_dirs
276
def ie_to_hexsha(ie):
278
return shamap[ie.file_id]
280
# FIXME: Should be the same as in parent
281
if ie.kind in ("file", "symlink"):
283
return idmap.lookup_blob_id(ie.file_id, ie.revision)
287
path = tree.id2path(ie.file_id)
288
blob.data = tree.get_file_text(path, ie.file_id)
290
elif ie.kind == "directory":
291
# Not all cache backends store the tree information,
292
# calculate again from scratch
293
ret = directory_to_tree(ie.children, ie_to_hexsha,
294
unusual_modes, dummy_file_name, ie.parent_id is None)
301
for path in sorted(trees.keys(), reverse=True):
302
file_id = trees[path]
303
if tree.kind(path, file_id) != 'directory':
305
ie = inv.get_entry(file_id)
306
obj = directory_to_tree(ie.children, ie_to_hexsha, unusual_modes,
307
dummy_file_name, path == "")
309
yield path, obj, (file_id, )
310
shamap[file_id] = obj.id
313
class PackTupleIterable(object):
315
def __init__(self, store):
317
self.store.lock_read()
323
def add(self, sha, path):
324
self.objects[sha] = path
327
return len(self.objects)
330
return ((self.store[object_id], path) for (object_id, path) in
331
self.objects.iteritems())
334
class BazaarObjectStore(BaseObjectStore):
335
"""A Git-style object store backed onto a Bazaar repository."""
337
def __init__(self, repository, mapping=None):
338
self.repository = repository
339
self._map_updated = False
342
self.mapping = default_mapping
344
self.mapping = mapping
345
self._cache = cache_from_repository(repository)
346
self._content_cache_types = ("tree",)
347
self.start_write_group = self._cache.idmap.start_write_group
348
self.abort_write_group = self._cache.idmap.abort_write_group
349
self.commit_write_group = self._cache.idmap.commit_write_group
350
self.tree_cache = LRUTreeCache(self.repository)
351
self.unpeel_map = UnpeelMap.from_repository(self.repository)
353
def _missing_revisions(self, revisions):
354
return self._cache.idmap.missing_revisions(revisions)
356
def _update_sha_map(self, stop_revision=None):
357
if not self.is_locked():
358
raise errors.LockNotHeld(self)
359
if self._map_updated:
361
if (stop_revision is not None and
362
not self._missing_revisions([stop_revision])):
364
graph = self.repository.get_graph()
365
if stop_revision is None:
366
all_revids = self.repository.all_revision_ids()
367
missing_revids = self._missing_revisions(all_revids)
369
heads = set([stop_revision])
370
missing_revids = self._missing_revisions(heads)
372
parents = graph.get_parent_map(heads)
374
for p in parents.values():
375
todo.update([x for x in p if x not in missing_revids])
376
heads = self._missing_revisions(todo)
377
missing_revids.update(heads)
378
if NULL_REVISION in missing_revids:
379
missing_revids.remove(NULL_REVISION)
380
missing_revids = self.repository.has_revisions(missing_revids)
381
if not missing_revids:
382
if stop_revision is None:
383
self._map_updated = True
385
self.start_write_group()
387
pb = ui.ui_factory.nested_progress_bar()
389
for i, revid in enumerate(graph.iter_topo_order(missing_revids)):
390
trace.mutter('processing %r', revid)
391
pb.update("updating git map", i, len(missing_revids))
392
self._update_sha_map_revision(revid)
395
if stop_revision is None:
396
self._map_updated = True
398
self.abort_write_group()
401
self.commit_write_group()
404
self._update_sha_map()
405
return iter(self._cache.idmap.sha1s())
407
def _reconstruct_commit(self, rev, tree_sha, lossy, verifiers):
408
"""Reconstruct a Commit object.
410
:param rev: Revision object
411
:param tree_sha: SHA1 of the root tree object
412
:param lossy: Whether or not to roundtrip bzr metadata
413
:param verifiers: Verifiers for the commits
414
:return: Commit object
416
def parent_lookup(revid):
418
return self._lookup_revision_sha1(revid)
419
except errors.NoSuchRevision:
421
return self.mapping.export_commit(rev, tree_sha, parent_lookup,
424
def _create_fileid_map_blob(self, tree):
425
# FIXME: This can probably be a lot more efficient,
426
# not all files necessarily have to be processed.
428
for (path, ie) in tree.iter_entries_by_dir():
429
if self.mapping.generate_file_id(path) != ie.file_id:
430
file_ids[path] = ie.file_id
431
return self.mapping.export_fileid_map(file_ids)
433
def _revision_to_objects(self, rev, tree, lossy):
434
"""Convert a revision to a set of git objects.
436
:param rev: Bazaar revision object
437
:param tree: Bazaar revision tree
438
:param lossy: Whether to not roundtrip all Bazaar revision data
440
unusual_modes = extract_unusual_modes(rev)
441
present_parents = self.repository.has_revisions(rev.parent_ids)
442
parent_trees = self.tree_cache.revision_trees(
443
[p for p in rev.parent_ids if p in present_parents])
445
for path, obj, bzr_key_data in _tree_to_objects(tree, parent_trees,
446
self._cache.idmap, unusual_modes, self.mapping.BZR_DUMMY_FILE):
449
root_key_data = bzr_key_data
450
# Don't yield just yet
452
yield path, obj, bzr_key_data
453
if root_tree is None:
454
# Pointless commit - get the tree sha elsewhere
455
if not rev.parent_ids:
458
base_sha1 = self._lookup_revision_sha1(rev.parent_ids[0])
459
root_tree = self[self[base_sha1].tree]
460
root_key_data = (tree.get_root_id(), )
461
if not lossy and self.mapping.BZR_FILE_IDS_FILE is not None:
462
b = self._create_fileid_map_blob(tree)
464
root_tree[self.mapping.BZR_FILE_IDS_FILE] = (
465
(stat.S_IFREG | 0644), b.id)
466
yield self.mapping.BZR_FILE_IDS_FILE, b, None
467
yield "", root_tree, root_key_data
469
testament3 = StrictTestament3(rev, tree)
470
verifiers = { "testament3-sha1": testament3.as_sha1() }
473
commit_obj = self._reconstruct_commit(rev, root_tree.id,
474
lossy=lossy, verifiers=verifiers)
476
foreign_revid, mapping = mapping_registry.parse_revision_id(
478
except errors.InvalidRevisionId:
481
_check_expected_sha(foreign_revid, commit_obj)
482
yield None, commit_obj, None
484
def _get_updater(self, rev):
485
return self._cache.get_updater(rev)
487
def _update_sha_map_revision(self, revid):
488
rev = self.repository.get_revision(revid)
489
tree = self.tree_cache.revision_tree(rev.revision_id)
490
updater = self._get_updater(rev)
491
# FIXME JRV 2011-12-15: Shouldn't we try both values for lossy ?
492
for path, obj, ie in self._revision_to_objects(rev, tree, lossy=(not self.mapping.roundtripping)):
493
if isinstance(obj, Commit):
494
testament3 = StrictTestament3(rev, tree)
495
ie = { "testament3-sha1": testament3.as_sha1() }
496
updater.add_object(obj, ie, path)
497
commit_obj = updater.finish()
500
def _reconstruct_blobs(self, keys):
501
"""Return a Git Blob object from a fileid and revision stored in bzr.
503
:param fileid: File id of the text
504
:param revision: Revision of the text
506
stream = self.repository.iter_files_bytes(
507
((key[0], key[1], key) for key in keys))
508
for (file_id, revision, expected_sha), chunks in stream:
510
blob.chunked = chunks
511
if blob.id != expected_sha and blob.data == "":
512
# Perhaps it's a symlink ?
513
tree = self.tree_cache.revision_tree(revision)
514
path = tree.id2path(file_id)
515
if tree.kind(path, file_id) == 'symlink':
516
blob = symlink_to_blob(tree.get_symlink_target(path, file_id))
517
_check_expected_sha(expected_sha, blob)
520
def _reconstruct_tree(self, fileid, revid, bzr_tree, unusual_modes,
522
"""Return a Git Tree object from a file id and a revision stored in bzr.
524
:param fileid: fileid in the tree.
525
:param revision: Revision of the tree.
527
def get_ie_sha1(entry):
528
if entry.kind == "directory":
530
return self._cache.idmap.lookup_tree_id(entry.file_id,
532
except (NotImplementedError, KeyError):
533
obj = self._reconstruct_tree(entry.file_id, revid, bzr_tree,
539
elif entry.kind in ("file", "symlink"):
541
return self._cache.idmap.lookup_blob_id(entry.file_id,
545
return self._reconstruct_blobs(
546
[(entry.file_id, entry.revision, None)]).next().id
547
elif entry.kind == 'tree-reference':
548
# FIXME: Make sure the file id is the root id
549
return self._lookup_revision_sha1(entry.reference_revision)
551
raise AssertionError("unknown entry kind '%s'" % entry.kind)
553
inv = bzr_tree.root_inventory
554
except AttributeError:
555
inv = bzr_tree.inventory
556
tree = directory_to_tree(inv.get_entry(fileid).children,
557
get_ie_sha1, unusual_modes, self.mapping.BZR_DUMMY_FILE,
558
bzr_tree.get_root_id() == fileid)
559
if (bzr_tree.get_root_id() == fileid and
560
self.mapping.BZR_FILE_IDS_FILE is not None):
563
b = self._create_fileid_map_blob(bzr_tree)
564
# If this is the root tree, add the file ids
565
tree[self.mapping.BZR_FILE_IDS_FILE] = (
566
(stat.S_IFREG | 0644), b.id)
568
_check_expected_sha(expected_sha, tree)
571
def get_parents(self, sha):
572
"""Retrieve the parents of a Git commit by SHA1.
574
:param sha: SHA1 of the commit
575
:raises: KeyError, NotCommitError
577
return self[sha].parents
579
def _lookup_revision_sha1(self, revid):
580
"""Return the SHA1 matching a Bazaar revision."""
581
if revid == NULL_REVISION:
584
return self._cache.idmap.lookup_commit(revid)
587
return mapping_registry.parse_revision_id(revid)[0]
588
except errors.InvalidRevisionId:
589
self._update_sha_map(revid)
590
return self._cache.idmap.lookup_commit(revid)
592
def get_raw(self, sha):
593
"""Get the raw representation of a Git object by SHA1.
595
:param sha: SHA1 of the git object
598
sha = sha_to_hex(sha)
600
return (obj.type, obj.as_raw_string())
602
def __contains__(self, sha):
603
# See if sha is in map
605
for (type, type_data) in self.lookup_git_sha(sha):
607
if self.repository.has_revision(type_data[0]):
610
if type_data in self.repository.texts:
613
if self.repository.has_revision(type_data[1]):
616
raise AssertionError("Unknown object type '%s'" % type)
624
self._map_updated = False
625
self.repository.lock_read()
626
return LogicalLockResult(self.unlock)
628
def lock_write(self):
630
self._map_updated = False
631
self.repository.lock_write()
632
return LogicalLockResult(self.unlock)
635
return (self._locked is not None)
639
self._map_updated = False
640
self.repository.unlock()
642
def lookup_git_shas(self, shas):
646
ret[sha] = [("commit", (NULL_REVISION, None, {}))]
649
ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
651
# if not, see if there are any unconverted revisions and
652
# add them to the map, search for sha in map again
653
self._update_sha_map()
655
ret[sha] = list(self._cache.idmap.lookup_git_sha(sha))
660
def lookup_git_sha(self, sha):
661
return self.lookup_git_shas([sha])[sha]
663
def __getitem__(self, sha):
664
if self._cache.content_cache is not None:
666
return self._cache.content_cache[sha]
669
for (kind, type_data) in self.lookup_git_sha(sha):
670
# convert object to git object
672
(revid, tree_sha, verifiers) = type_data
674
rev = self.repository.get_revision(revid)
675
except errors.NoSuchRevision:
676
if revid == NULL_REVISION:
677
raise AssertionError(
678
"should not try to look up NULL_REVISION")
679
trace.mutter('entry for %s %s in shamap: %r, but not '
680
'found in repository', kind, sha, type_data)
682
# FIXME: the type data should say whether conversion was lossless
683
commit = self._reconstruct_commit(rev, tree_sha,
684
lossy=(not self.mapping.roundtripping), verifiers=verifiers)
685
_check_expected_sha(sha, commit)
688
(fileid, revision) = type_data
689
blobs = self._reconstruct_blobs([(fileid, revision, sha)])
692
(fileid, revid) = type_data
694
tree = self.tree_cache.revision_tree(revid)
695
rev = self.repository.get_revision(revid)
696
except errors.NoSuchRevision:
697
trace.mutter('entry for %s %s in shamap: %r, but not found in '
698
'repository', kind, sha, type_data)
700
unusual_modes = extract_unusual_modes(rev)
702
return self._reconstruct_tree(fileid, revid,
703
tree, unusual_modes, expected_sha=sha)
704
except errors.NoSuchRevision:
707
raise AssertionError("Unknown object type '%s'" % kind)
711
def generate_lossy_pack_data(self, have, want, progress=None,
712
get_tagged=None, ofs_delta=False):
713
return pack_objects_to_data(
714
self.generate_pack_contents(have, want, progress, get_tagged,
717
def generate_pack_contents(self, have, want, progress=None,
718
ofs_delta=False, get_tagged=None, lossy=False):
719
"""Iterate over the contents of a pack file.
721
:param have: List of SHA1s of objects that should not be sent
722
:param want: List of SHA1s of objects that should be sent
725
ret = self.lookup_git_shas(have + want)
726
for commit_sha in have:
727
commit_sha = self.unpeel_map.peel_tag(commit_sha, commit_sha)
729
for (type, type_data) in ret[commit_sha]:
731
raise AssertionError("Type was %s, not commit" % type)
732
processed.add(type_data[0])
734
trace.mutter("unable to find remote ref %s", commit_sha)
736
for commit_sha in want:
737
if commit_sha in have:
740
for (type, type_data) in ret[commit_sha]:
742
raise AssertionError("Type was %s, not commit" % type)
743
pending.add(type_data[0])
747
graph = self.repository.get_graph()
748
todo = _find_missing_bzr_revids(graph, pending, processed)
749
ret = PackTupleIterable(self)
750
pb = ui.ui_factory.nested_progress_bar()
752
for i, revid in enumerate(todo):
753
pb.update("generating git objects", i, len(todo))
755
rev = self.repository.get_revision(revid)
756
except errors.NoSuchRevision:
758
tree = self.tree_cache.revision_tree(revid)
759
for path, obj, ie in self._revision_to_objects(rev, tree, lossy=lossy):
760
ret.add(obj.id, path)
765
def add_thin_pack(self):
768
fd, path = tempfile.mkstemp(suffix=".pack")
769
f = os.fdopen(fd, 'wb')
771
from dulwich.pack import PackData, Pack
772
from .fetch import import_git_objects
775
if os.path.getsize(path) == 0:
778
pd.create_index_v2(path[:-5]+".idx", self.object_store.get_raw)
781
with self.repository.lock_write():
782
self.repository.start_write_group()
784
import_git_objects(self.repository, self.mapping,
785
p.iterobjects(get_raw=self.get_raw),
788
self.repository.abort_write_group()
791
self.repository.commit_write_group()
794
# The pack isn't kept around anyway, so no point
795
# in treating full packs different from thin packs
796
add_pack = add_thin_pack