1
# Copyright (C) 2008-2018 Jelmer Vernooij <jelmer@jelmer.uk>
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Fetching from git into bzr."""
19
from __future__ import absolute_import
21
from dulwich.errors import (
24
from dulwich.objects import (
32
from dulwich.object_store import (
33
ObjectStoreGraphWalker,
36
from dulwich.protocol import CAPABILITY_THIN_PACK
37
from dulwich.walk import Walker
38
from itertools import (
41
from io import BytesIO
53
from ...errors import (
56
from ...bzr.inventory import (
62
from ...repository import (
65
from ...revision import (
68
from ...bzr.inventorytree import InventoryRevisionTree
69
from ...testament import (
72
from ...tsort import (
75
from ...bzr.versionedfile import (
76
ChunkedContentFactory,
79
from .mapping import (
85
from .object_store import (
96
from .repository import (
103
def import_git_blob(texts, mapping, path, name, (base_hexsha, hexsha),
104
base_bzr_tree, parent_id, revision_id,
105
parent_bzr_trees, lookup_object, (base_mode, mode), store_updater,
107
"""Import a git blob object into a bzr repository.
109
:param texts: VersionedFiles to add to
110
:param path: Path in the tree
111
:param blob: A git blob
112
:return: Inventory delta for this file
114
if mapping.is_special_file(path):
116
if base_hexsha == hexsha and base_mode == mode:
117
# If nothing has changed since the base revision, we're done
119
file_id = lookup_file_id(path)
120
if stat.S_ISLNK(mode):
124
ie = cls(file_id, name.decode("utf-8"), parent_id)
125
if ie.kind == "file":
126
ie.executable = mode_is_executable(mode)
127
if base_hexsha == hexsha and mode_kind(base_mode) == mode_kind(mode):
128
base_exec = base_bzr_tree.is_executable(path)
129
if ie.kind == "symlink":
130
ie.symlink_target = base_bzr_tree.get_symlink_target(path)
132
ie.text_size = base_bzr_tree.get_file_size(path)
133
ie.text_sha1 = base_bzr_tree.get_file_sha1(path)
134
if ie.kind == "symlink" or ie.executable == base_exec:
135
ie.revision = base_bzr_tree.get_file_revision(path)
137
blob = lookup_object(hexsha)
139
blob = lookup_object(hexsha)
140
if ie.kind == "symlink":
142
ie.symlink_target = blob.data.decode("utf-8")
144
ie.text_size = sum(imap(len, blob.chunked))
145
ie.text_sha1 = osutils.sha_strings(blob.chunked)
146
# Check what revision we should store
148
for ptree in parent_bzr_trees:
150
ppath = ptree.id2path(file_id)
151
except errors.NoSuchId:
153
pkind = ptree.kind(ppath, file_id)
154
if (pkind == ie.kind and
155
((pkind == "symlink" and ptree.get_symlink_target(ppath, file_id) == ie.symlink_target) or
156
(pkind == "file" and ptree.get_file_sha1(ppath, file_id) == ie.text_sha1 and
157
ptree.is_executable(ppath, file_id) == ie.executable))):
158
# found a revision in one of the parents to use
159
ie.revision = ptree.get_file_revision(ppath, file_id)
161
parent_key = (file_id, ptree.get_file_revision(ppath, file_id))
162
if not parent_key in parent_keys:
163
parent_keys.append(parent_key)
164
if ie.revision is None:
165
# Need to store a new revision
166
ie.revision = revision_id
167
if ie.revision is None:
168
raise ValueError("no file revision set")
169
if ie.kind == 'symlink':
172
chunks = blob.chunked
173
texts.insert_record_stream([
174
ChunkedContentFactory((file_id, ie.revision),
175
tuple(parent_keys), ie.text_sha1, chunks)])
177
if base_hexsha is not None:
178
old_path = path.decode("utf-8") # Renames are not supported yet
179
if stat.S_ISDIR(base_mode):
180
invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
181
lookup_object(base_hexsha), [], lookup_object))
184
new_path = path.decode("utf-8")
185
invdelta.append((old_path, new_path, file_id, ie))
186
if base_hexsha != hexsha:
187
store_updater.add_object(blob, (ie.file_id, ie.revision), path)
191
class SubmodulesRequireSubtrees(BzrError):
192
_fmt = ("The repository you are fetching from contains submodules, "
193
"which are not yet supported.")
197
def import_git_submodule(texts, mapping, path, name, (base_hexsha, hexsha),
198
base_bzr_tree, parent_id, revision_id, parent_bzr_trees, lookup_object,
199
(base_mode, mode), store_updater, lookup_file_id):
200
"""Import a git submodule."""
201
if base_hexsha == hexsha and base_mode == mode:
203
file_id = lookup_file_id(path)
205
ie = TreeReference(file_id, name.decode("utf-8"), parent_id)
206
ie.revision = revision_id
207
if base_hexsha is not None:
208
old_path = path.decode("utf-8") # Renames are not supported yet
209
if stat.S_ISDIR(base_mode):
210
invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
211
lookup_object(base_hexsha), [], lookup_object))
214
ie.reference_revision = mapping.revision_id_foreign_to_bzr(hexsha)
215
texts.insert_record_stream([
216
ChunkedContentFactory((file_id, ie.revision), (), None, [])])
217
invdelta.append((old_path, path, file_id, ie))
221
def remove_disappeared_children(base_bzr_tree, path, base_tree, existing_children,
223
"""Generate an inventory delta for removed children.
225
:param base_bzr_tree: Base bzr tree against which to generate the
227
:param path: Path to process (unicode)
228
:param base_tree: Git Tree base object
229
:param existing_children: Children that still exist
230
:param lookup_object: Lookup a git object by its SHA1
231
:return: Inventory delta, as list
233
if type(path) is not unicode:
234
raise TypeError(path)
236
for name, mode, hexsha in base_tree.iteritems():
237
if name in existing_children:
239
c_path = posixpath.join(path, name.decode("utf-8"))
240
file_id = base_bzr_tree.path2id(c_path)
242
raise TypeError(file_id)
243
ret.append((c_path, None, file_id, None))
244
if stat.S_ISDIR(mode):
245
ret.extend(remove_disappeared_children(
246
base_bzr_tree, c_path, lookup_object(hexsha), [], lookup_object))
250
def import_git_tree(texts, mapping, path, name, (base_hexsha, hexsha),
251
base_bzr_tree, parent_id, revision_id, parent_bzr_trees,
252
lookup_object, (base_mode, mode), store_updater,
253
lookup_file_id, allow_submodules=False):
254
"""Import a git tree object into a bzr repository.
256
:param texts: VersionedFiles object to add to
257
:param path: Path in the tree (str)
258
:param name: Name of the tree (str)
259
:param tree: A git tree object
260
:param base_bzr_tree: Base inventory against which to return inventory delta
261
:return: Inventory delta for this subtree
263
if type(path) is not str:
264
raise TypeError(path)
265
if type(name) is not str:
266
raise TypeError(name)
267
if base_hexsha == hexsha and base_mode == mode:
268
# If nothing has changed since the base revision, we're done
271
file_id = lookup_file_id(path)
272
# We just have to hope this is indeed utf-8:
273
ie = InventoryDirectory(file_id, name.decode("utf-8"), parent_id)
274
tree = lookup_object(hexsha)
275
if base_hexsha is None:
277
old_path = None # Newly appeared here
279
base_tree = lookup_object(base_hexsha)
280
old_path = path.decode("utf-8") # Renames aren't supported yet
281
new_path = path.decode("utf-8")
282
if base_tree is None or type(base_tree) is not Tree:
283
ie.revision = revision_id
284
invdelta.append((old_path, new_path, ie.file_id, ie))
285
texts.insert_record_stream([
286
ChunkedContentFactory((ie.file_id, ie.revision), (), None, [])])
287
# Remember for next time
288
existing_children = set()
290
for name, child_mode, child_hexsha in tree.iteritems():
291
existing_children.add(name)
292
child_path = posixpath.join(path, name)
293
if type(base_tree) is Tree:
295
child_base_mode, child_base_hexsha = base_tree[name]
297
child_base_hexsha = None
300
child_base_hexsha = None
302
if stat.S_ISDIR(child_mode):
303
subinvdelta, grandchildmodes = import_git_tree(texts, mapping,
304
child_path, name, (child_base_hexsha, child_hexsha),
305
base_bzr_tree, file_id, revision_id, parent_bzr_trees,
306
lookup_object, (child_base_mode, child_mode), store_updater,
307
lookup_file_id, allow_submodules=allow_submodules)
308
elif S_ISGITLINK(child_mode): # submodule
309
if not allow_submodules:
310
raise SubmodulesRequireSubtrees()
311
subinvdelta, grandchildmodes = import_git_submodule(texts, mapping,
312
child_path, name, (child_base_hexsha, child_hexsha),
313
base_bzr_tree, file_id, revision_id, parent_bzr_trees,
314
lookup_object, (child_base_mode, child_mode), store_updater,
317
if not mapping.is_special_file(name):
318
subinvdelta = import_git_blob(texts, mapping, child_path, name,
319
(child_base_hexsha, child_hexsha), base_bzr_tree, file_id,
320
revision_id, parent_bzr_trees, lookup_object,
321
(child_base_mode, child_mode), store_updater, lookup_file_id)
325
child_modes.update(grandchildmodes)
326
invdelta.extend(subinvdelta)
327
if child_mode not in (stat.S_IFDIR, DEFAULT_FILE_MODE,
328
stat.S_IFLNK, DEFAULT_FILE_MODE|0111,
330
child_modes[child_path] = child_mode
331
# Remove any children that have disappeared
332
if base_tree is not None and type(base_tree) is Tree:
333
invdelta.extend(remove_disappeared_children(base_bzr_tree, old_path,
334
base_tree, existing_children, lookup_object))
335
store_updater.add_object(tree, (file_id, ), path)
336
return invdelta, child_modes
339
def verify_commit_reconstruction(target_git_object_retriever, lookup_object,
340
o, rev, ret_tree, parent_trees, mapping, unusual_modes, verifiers):
341
new_unusual_modes = mapping.export_unusual_file_modes(rev)
342
if new_unusual_modes != unusual_modes:
343
raise AssertionError("unusual modes don't match: %r != %r" % (
344
unusual_modes, new_unusual_modes))
345
# Verify that we can reconstruct the commit properly
346
rec_o = target_git_object_retriever._reconstruct_commit(rev, o.tree, True,
349
raise AssertionError("Reconstructed commit differs: %r != %r" % (
353
for path, obj, ie in _tree_to_objects(ret_tree, parent_trees,
354
target_git_object_retriever._cache.idmap, unusual_modes,
355
mapping.BZR_DUMMY_FILE):
356
old_obj_id = tree_lookup_path(lookup_object, o.tree, path)[1]
358
if obj.id != old_obj_id:
359
diff.append((path, lookup_object(old_obj_id), obj))
360
for (path, old_obj, new_obj) in diff:
361
while (old_obj.type_name == "tree" and
362
new_obj.type_name == "tree" and
363
sorted(old_obj) == sorted(new_obj)):
365
if old_obj[name][0] != new_obj[name][0]:
366
raise AssertionError("Modes for %s differ: %o != %o" %
367
(path, old_obj[name][0], new_obj[name][0]))
368
if old_obj[name][1] != new_obj[name][1]:
369
# Found a differing child, delve deeper
370
path = posixpath.join(path, name)
371
old_obj = lookup_object(old_obj[name][1])
372
new_obj = new_objs[path]
374
raise AssertionError("objects differ for %s: %r != %r" % (path,
378
def ensure_inventories_in_repo(repo, trees):
379
real_inv_vf = repo.inventories.without_fallbacks()
381
revid = t.get_revision_id()
382
if not real_inv_vf.get_parent_map([(revid, )]):
383
repo.add_inventory(revid, t.inventory, t.get_parent_ids())
386
def import_git_commit(repo, mapping, head, lookup_object,
387
target_git_object_retriever, trees_cache):
388
o = lookup_object(head)
389
# Note that this uses mapping.revision_id_foreign_to_bzr. If the parents
390
# were bzr roundtripped revisions they would be specified in the
392
rev, roundtrip_revid, verifiers = mapping.import_commit(
393
o, mapping.revision_id_foreign_to_bzr)
394
if roundtrip_revid is not None:
395
original_revid = rev.revision_id
396
rev.revision_id = roundtrip_revid
397
# We have to do this here, since we have to walk the tree and
398
# we need to make sure to import the blobs / trees with the right
399
# path; this may involve adding them more than once.
400
parent_trees = trees_cache.revision_trees(rev.parent_ids)
401
ensure_inventories_in_repo(repo, parent_trees)
402
if parent_trees == []:
403
base_bzr_tree = trees_cache.revision_tree(NULL_REVISION)
407
base_bzr_tree = parent_trees[0]
408
base_tree = lookup_object(o.parents[0]).tree
409
base_mode = stat.S_IFDIR
410
store_updater = target_git_object_retriever._get_updater(rev)
411
tree_supplement = mapping.get_fileid_map(lookup_object, o.tree)
412
inv_delta, unusual_modes = import_git_tree(repo.texts,
413
mapping, "", "", (base_tree, o.tree), base_bzr_tree,
414
None, rev.revision_id, parent_trees,
415
lookup_object, (base_mode, stat.S_IFDIR), store_updater,
416
tree_supplement.lookup_file_id,
417
allow_submodules=getattr(repo._format, "supports_tree_reference",
419
if unusual_modes != {}:
420
for path, mode in unusual_modes.iteritems():
421
warn_unusual_mode(rev.foreign_revid, path, mode)
422
mapping.import_unusual_file_modes(rev, unusual_modes)
424
basis_id = rev.parent_ids[0]
426
basis_id = NULL_REVISION
427
base_bzr_inventory = None
430
base_bzr_inventory = base_bzr_tree.root_inventory
431
except AttributeError: # bzr < 2.6
432
base_bzr_inventory = base_bzr_tree.inventory
433
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
434
inv_delta, rev.revision_id, rev.parent_ids,
436
ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
438
if verifiers and roundtrip_revid is not None:
439
testament = StrictTestament3(rev, ret_tree)
440
calculated_verifiers = { "testament3-sha1": testament.as_sha1() }
441
if calculated_verifiers != verifiers:
442
trace.mutter("Testament SHA1 %r for %r did not match %r.",
443
calculated_verifiers["testament3-sha1"],
444
rev.revision_id, verifiers["testament3-sha1"])
445
rev.revision_id = original_revid
446
rev.inventory_sha1, inv = repo.add_inventory_by_delta(basis_id,
447
inv_delta, rev.revision_id, rev.parent_ids, base_bzr_tree)
448
ret_tree = InventoryRevisionTree(repo, inv, rev.revision_id)
450
calculated_verifiers = {}
451
store_updater.add_object(o, calculated_verifiers, None)
452
store_updater.finish()
453
trees_cache.add(ret_tree)
454
repo.add_revision(rev.revision_id, rev)
455
if "verify" in debug.debug_flags:
456
verify_commit_reconstruction(target_git_object_retriever,
457
lookup_object, o, rev, ret_tree, parent_trees, mapping,
458
unusual_modes, verifiers)
461
def import_git_objects(repo, mapping, object_iter,
462
target_git_object_retriever, heads, pb=None, limit=None):
463
"""Import a set of git objects into a bzr repository.
465
:param repo: Target Bazaar repository
466
:param mapping: Mapping to use
467
:param object_iter: Iterator over Git objects.
468
:return: Tuple with pack hints and last imported revision id
470
def lookup_object(sha):
472
return object_iter[sha]
474
return target_git_object_retriever[sha]
477
heads = list(set(heads))
478
trees_cache = LRUTreeCache(repo)
479
# Find and convert commit objects
482
pb.update("finding revisions to fetch", len(graph), None)
486
if type(head) is not str:
487
raise TypeError(head)
489
o = lookup_object(head)
492
if isinstance(o, Commit):
493
rev, roundtrip_revid, verifiers = mapping.import_commit(o,
494
mapping.revision_id_foreign_to_bzr)
495
if (repo.has_revision(rev.revision_id) or
496
(roundtrip_revid and repo.has_revision(roundtrip_revid))):
498
graph.append((o.id, o.parents))
499
heads.extend([p for p in o.parents if p not in checked])
500
elif isinstance(o, Tag):
501
if o.object[1] not in checked:
502
heads.append(o.object[1])
504
trace.warning("Unable to import head object %r" % o)
507
# Order the revisions
508
# Create the inventory objects
510
revision_ids = topo_sort(graph)
512
if limit is not None:
513
revision_ids = revision_ids[:limit]
515
for offset in range(0, len(revision_ids), batch_size):
516
target_git_object_retriever.start_write_group()
518
repo.start_write_group()
520
for i, head in enumerate(
521
revision_ids[offset:offset+batch_size]):
523
pb.update("fetching revisions", offset+i,
525
import_git_commit(repo, mapping, head, lookup_object,
526
target_git_object_retriever, trees_cache)
529
repo.abort_write_group()
532
hint = repo.commit_write_group()
534
pack_hints.extend(hint)
536
target_git_object_retriever.abort_write_group()
539
target_git_object_retriever.commit_write_group()
540
return pack_hints, last_imported
543
class InterFromGitRepository(InterRepository):
545
_matching_repo_format = GitRepositoryFormat()
547
def _target_has_shas(self, shas):
548
raise NotImplementedError(self._target_has_shas)
550
def get_determine_wants_heads(self, wants, include_tags=False):
552
def determine_wants(refs):
553
potential = set(wants)
555
for k, unpeeled in refs.iteritems():
556
if k.endswith("^{}"):
560
if unpeeled == ZERO_SHA:
562
potential.add(unpeeled)
563
return list(potential - self._target_has_shas(potential))
564
return determine_wants
566
def determine_wants_all(self, refs):
567
raise NotImplementedError(self.determine_wants_all)
570
def _get_repo_format_to_test():
573
def copy_content(self, revision_id=None):
574
"""See InterRepository.copy_content."""
575
self.fetch(revision_id, find_ghosts=False)
577
def search_missing_revision_ids(self,
578
find_ghosts=True, revision_ids=None, if_present_ids=None,
580
if limit is not None:
581
raise errors.FetchLimitUnsupported(self)
585
todo.extend(revision_ids)
587
todo.extend(revision_ids)
588
for revid in revision_ids:
589
if revid == NULL_REVISION:
591
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
592
git_shas.append(git_sha)
593
walker = Walker(self.source._git.object_store,
594
include=git_shas, exclude=[
595
sha for sha in self.target.controldir.get_refs_container().as_dict().values()
597
missing_revids = set()
599
missing_revids.add(self.source.lookup_foreign_revision_id(entry.commit.id))
600
return self.source.revision_ids_to_search_result(missing_revids)
603
class InterGitNonGitRepository(InterFromGitRepository):
604
"""Base InterRepository that copies revisions from a Git into a non-Git
607
def _target_has_shas(self, shas):
611
revid = self.source.lookup_foreign_revision_id(sha)
612
except NotCommitError:
613
# Commit is definitely not present
617
return set([revids[r] for r in self.target.has_revisions(revids)])
619
def determine_wants_all(self, refs):
621
for k, v in refs.iteritems():
622
# For non-git target repositories, only worry about peeled
625
potential.add(self.source.controldir.get_peeled(k) or v)
626
return list(potential - self._target_has_shas(potential))
628
def get_determine_wants_heads(self, wants, include_tags=False):
630
def determine_wants(refs):
631
potential = set(wants)
633
for k, unpeeled in refs.iteritems():
636
if unpeeled == ZERO_SHA:
638
potential.add(self.source.controldir.get_peeled(k) or unpeeled)
639
return list(potential - self._target_has_shas(potential))
640
return determine_wants
642
def _warn_slow(self):
644
'Fetching from Git to Bazaar repository. '
645
'For better performance, fetch into a Git repository.')
647
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
648
"""Fetch objects from a remote server.
650
:param determine_wants: determine_wants callback
651
:param mapping: BzrGitMapping to use
652
:param limit: Maximum number of commits to import.
653
:return: Tuple with pack hint, last imported revision id and remote refs
655
raise NotImplementedError(self.fetch_objects)
657
def get_determine_wants_revids(self, revids, include_tags=False):
659
for revid in set(revids):
660
if self.target.has_revision(revid):
662
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
664
return self.get_determine_wants_heads(wants, include_tags=include_tags)
666
def fetch(self, revision_id=None, find_ghosts=False,
667
mapping=None, fetch_spec=None, include_tags=False):
669
mapping = self.source.get_mapping()
670
if revision_id is not None:
671
interesting_heads = [revision_id]
672
elif fetch_spec is not None:
673
recipe = fetch_spec.get_recipe()
674
if recipe[0] in ("search", "proxy-search"):
675
interesting_heads = recipe[1]
677
raise AssertionError("Unsupported search result type %s" %
680
interesting_heads = None
682
if interesting_heads is not None:
683
determine_wants = self.get_determine_wants_revids(
684
interesting_heads, include_tags=include_tags)
686
determine_wants = self.determine_wants_all
688
(pack_hint, _, remote_refs) = self.fetch_objects(determine_wants,
690
if pack_hint is not None and self.target._format.pack_compresses:
691
self.target.pack(hint=pack_hint)
695
_GIT_PROGRESS_RE = re.compile(r"(.*?): +(\d+)% \((\d+)/(\d+)\)")
696
def report_git_progress(pb, text):
697
text = text.rstrip("\r\n")
698
trace.mutter('git: %s', text)
699
g = _GIT_PROGRESS_RE.match(text)
701
(text, pct, current, total) = g.groups()
702
pb.update(text, int(current), int(total))
704
pb.update(text, 0, 0)
707
class DetermineWantsRecorder(object):
709
def __init__(self, actual):
712
self.remote_refs = {}
714
def __call__(self, refs):
715
if type(refs) is not dict:
716
raise TypeError(refs)
717
self.remote_refs = refs
718
self.wants = self.actual(refs)
722
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
723
"""InterRepository that copies revisions from a remote Git into a non-Git
726
def get_target_heads(self):
727
# FIXME: This should be more efficient
728
all_revs = self.target.all_revision_ids()
729
parent_map = self.target.get_parent_map(all_revs)
731
map(all_parents.update, parent_map.itervalues())
732
return set(all_revs) - all_parents
734
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
735
"""See `InterGitNonGitRepository`."""
737
store = BazaarObjectStore(self.target, mapping)
738
with store.lock_write():
739
heads = self.get_target_heads()
740
graph_walker = ObjectStoreGraphWalker(
741
[store._lookup_revision_sha1(head) for head in heads],
742
lambda sha: store[sha].parents)
743
wants_recorder = DetermineWantsRecorder(determine_wants)
745
pb = ui.ui_factory.nested_progress_bar()
747
objects_iter = self.source.fetch_objects(
748
wants_recorder, graph_walker, store.get_raw,
749
progress=lambda text: report_git_progress(pb, text),)
750
trace.mutter("Importing %d new revisions",
751
len(wants_recorder.wants))
752
(pack_hint, last_rev) = import_git_objects(self.target,
753
mapping, objects_iter, store, wants_recorder.wants, pb,
755
return (pack_hint, last_rev, wants_recorder.remote_refs)
760
def is_compatible(source, target):
761
"""Be compatible with GitRepository."""
762
if not isinstance(source, RemoteGitRepository):
764
if not target.supports_rich_root():
766
if isinstance(target, GitRepository):
768
if not getattr(target._format, "supports_full_versioned_files", True):
773
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
774
"""InterRepository that copies revisions from a local Git into a non-Git
777
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
778
"""See `InterGitNonGitRepository`."""
780
remote_refs = self.source.controldir.get_refs_container().as_dict()
781
wants = determine_wants(remote_refs)
783
pb = ui.ui_factory.nested_progress_bar()
784
target_git_object_retriever = BazaarObjectStore(self.target, mapping)
786
target_git_object_retriever.lock_write()
788
(pack_hint, last_rev) = import_git_objects(self.target,
789
mapping, self.source._git.object_store,
790
target_git_object_retriever, wants, pb, limit)
791
return (pack_hint, last_rev, remote_refs)
793
target_git_object_retriever.unlock()
798
def is_compatible(source, target):
799
"""Be compatible with GitRepository."""
800
if not isinstance(source, LocalGitRepository):
802
if not target.supports_rich_root():
804
if isinstance(target, GitRepository):
806
if not getattr(target._format, "supports_full_versioned_files", True):
811
class InterGitGitRepository(InterFromGitRepository):
812
"""InterRepository that copies between Git repositories."""
814
def fetch_refs(self, update_refs, lossy=False):
816
raise errors.LossyPushToSameVCS(self.source, self.target)
817
old_refs = self.target.controldir.get_refs_container()
819
def determine_wants(heads):
820
old_refs = dict([(k, (v, None)) for (k, v) in heads.as_dict().iteritems()])
821
new_refs = update_refs(old_refs)
822
ref_changes.update(new_refs)
823
return [sha1 for (sha1, bzr_revid) in new_refs.itervalues()]
824
self.fetch_objects(determine_wants, lossy=lossy)
825
for k, (git_sha, bzr_revid) in ref_changes.iteritems():
826
self.target._git.refs[k] = git_sha
827
new_refs = self.target.controldir.get_refs_container()
828
return None, old_refs, new_refs
830
def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
832
raise errors.LossyPushToSameVCS(self.source, self.target)
833
if limit is not None:
834
raise errors.FetchLimitUnsupported(self)
835
graphwalker = self.target._git.get_graph_walker()
836
if (isinstance(self.source, LocalGitRepository) and
837
isinstance(self.target, LocalGitRepository)):
838
pb = ui.ui_factory.nested_progress_bar()
840
refs = self.source._git.fetch(self.target._git, determine_wants,
841
lambda text: report_git_progress(pb, text))
844
return (None, None, refs)
845
elif (isinstance(self.source, LocalGitRepository) and
846
isinstance(self.target, RemoteGitRepository)):
847
raise NotImplementedError
848
elif (isinstance(self.source, RemoteGitRepository) and
849
isinstance(self.target, LocalGitRepository)):
850
pb = ui.ui_factory.nested_progress_bar()
852
if CAPABILITY_THIN_PACK in self.source.controldir._client._fetch_capabilities:
853
# TODO(jelmer): Avoid reading entire file into memory and
854
# only processing it after the whole file has been fetched.
860
self.target._git.object_store.move_in_thin_pack(f)
865
f, commit, abort = self.target._git.object_store.add_pack()
867
refs = self.source.controldir.fetch_pack(
868
determine_wants, graphwalker, f.write,
869
lambda text: report_git_progress(pb, text))
871
return (None, None, refs)
872
except BaseException:
878
raise AssertionError("fetching between %r and %r not supported" %
879
(self.source, self.target))
881
def _target_has_shas(self, shas):
882
return set([sha for sha in shas if sha in self.target._git.object_store])
884
def fetch(self, revision_id=None, find_ghosts=False,
885
mapping=None, fetch_spec=None, branches=None, limit=None, include_tags=False):
887
mapping = self.source.get_mapping()
889
if revision_id is not None:
891
elif fetch_spec is not None:
892
recipe = fetch_spec.get_recipe()
893
if recipe[0] in ("search", "proxy-search"):
896
raise AssertionError(
897
"Unsupported search result type %s" % recipe[0])
899
if branches is not None:
900
def determine_wants(refs):
902
for name, value in refs.iteritems():
903
if value == ZERO_SHA:
906
if name in branches or (include_tags and is_tag(name)):
909
elif fetch_spec is None and revision_id is None:
910
determine_wants = self.determine_wants_all
912
determine_wants = self.get_determine_wants_revids(args, include_tags=include_tags)
913
wants_recorder = DetermineWantsRecorder(determine_wants)
914
self.fetch_objects(wants_recorder, mapping, limit=limit)
915
return wants_recorder.remote_refs
918
def is_compatible(source, target):
919
"""Be compatible with GitRepository."""
920
return (isinstance(source, GitRepository) and
921
isinstance(target, GitRepository))
923
def get_determine_wants_revids(self, revids, include_tags=False):
925
for revid in set(revids):
926
if self.target.has_revision(revid):
928
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
930
return self.get_determine_wants_heads(wants, include_tags=include_tags)
932
def determine_wants_all(self, refs):
933
potential = set([v for v in refs.values() if not v == ZERO_SHA])
934
return list(potential - self._target_has_shas(potential))