1
# Copyright (C) 2009-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
"""InterRepository operations."""
19
from __future__ import absolute_import
21
from io import BytesIO
24
from dulwich.errors import (
27
from dulwich.object_store import (
28
ObjectStoreGraphWalker,
30
from dulwich.protocol import (
34
from dulwich.refs import (
38
from dulwich.walk import Walker
40
from ..errors import (
42
FetchLimitUnsupported,
45
NoRoundtrippingSupport,
48
from ..repository import (
51
from ..revision import (
54
from ..sixish import (
69
DetermineWantsRecorder,
71
from .mapping import (
74
from .object_store import (
78
MissingObjectsIterator,
84
from .repository import (
92
from .unpeel_map import (
97
class InterToGitRepository(InterRepository):
98
"""InterRepository that copies into a Git repository."""
100
_matching_repo_format = GitRepositoryFormat()
102
def __init__(self, source, target):
103
super(InterToGitRepository, self).__init__(source, target)
104
self.mapping = self.target.get_mapping()
105
self.source_store = get_object_store(self.source, self.mapping)
108
def _get_repo_format_to_test():
111
def copy_content(self, revision_id=None, pb=None):
112
"""See InterRepository.copy_content."""
113
self.fetch(revision_id, pb, find_ghosts=False)
115
def fetch_refs(self, update_refs, lossy, overwrite=False):
116
"""Fetch possibly roundtripped revisions into the target repository
119
:param update_refs: Generate refs to fetch. Receives dictionary
120
with old refs (git shas), returns dictionary of new names to
122
:param lossy: Whether to roundtrip
123
:return: old refs, new refs
125
raise NotImplementedError(self.fetch_refs)
127
def search_missing_revision_ids(self,
128
find_ghosts=True, revision_ids=None,
129
if_present_ids=None, limit=None):
130
if limit is not None:
131
raise FetchLimitUnsupported(self)
135
todo.extend(revision_ids)
137
todo.extend(revision_ids)
138
with self.source_store.lock_read():
139
for revid in revision_ids:
140
if revid == NULL_REVISION:
143
git_sha = self.source_store._lookup_revision_sha1(revid)
145
raise NoSuchRevision(revid, self.source)
146
git_shas.append(git_sha)
151
sha for sha in self.target.controldir.get_refs_container().as_dict().values()
153
missing_revids = set()
155
for (kind, type_data) in self.source_store.lookup_git_sha(
158
missing_revids.add(type_data[0])
159
return self.source.revision_ids_to_search_result(missing_revids)
161
def _warn_slow(self):
162
if not config.GlobalConfig().suppress_warning('slow_intervcs_push'):
164
'Pushing from a Bazaar to a Git repository. '
165
'For better performance, push into a Bazaar repository.')
168
class InterToLocalGitRepository(InterToGitRepository):
169
"""InterBranch implementation between a Bazaar and a Git repository."""
171
def __init__(self, source, target):
172
super(InterToLocalGitRepository, self).__init__(source, target)
173
self.target_store = self.target.controldir._git.object_store
174
self.target_refs = self.target.controldir._git.refs
176
def _commit_needs_fetching(self, sha_id):
178
return (sha_id not in self.target_store)
179
except NoSuchRevision:
183
def _revision_needs_fetching(self, sha_id, revid):
184
if revid == NULL_REVISION:
188
sha_id = self.source_store._lookup_revision_sha1(revid)
191
return self._commit_needs_fetching(sha_id)
193
def missing_revisions(self, stop_revisions):
194
"""Find the revisions that are missing from the target repository.
196
:param stop_revisions: Revisions to check for (tuples with
198
:return: sequence of missing revisions, in topological order
199
:raise: NoSuchRevision if the stop_revisions are not present in
204
for (sha1, revid) in stop_revisions:
205
if sha1 is not None and revid is not None:
206
revid_sha_map[revid] = sha1
207
stop_revids.append(revid)
208
elif sha1 is not None:
209
if self._commit_needs_fetching(sha1):
210
for (kind, (revid, tree_sha, verifiers)) in self.source_store.lookup_git_sha(sha1):
211
revid_sha_map[revid] = sha1
212
stop_revids.append(revid)
216
stop_revids.append(revid)
218
graph = self.source.get_graph()
219
pb = ui.ui_factory.nested_progress_bar()
223
for revid in stop_revids:
224
sha1 = revid_sha_map.get(revid)
225
if (revid not in missing and
226
self._revision_needs_fetching(sha1, revid)):
228
new_stop_revids.append(revid)
230
parent_map = graph.get_parent_map(new_stop_revids)
231
for parent_revids in viewvalues(parent_map):
232
stop_revids.update(parent_revids)
233
pb.update("determining revisions to fetch", len(missing))
236
return graph.iter_topo_order(missing)
238
def _get_target_bzr_refs(self):
239
"""Return a dictionary with references.
241
:return: Dictionary with reference names as keys and tuples
242
with Git SHA, Bazaar revid as values.
245
for k in self.target._git.refs.allkeys():
247
v = self.target._git.refs.read_ref(k)
252
if not v.startswith(SYMREF):
254
for (kind, type_data) in self.source_store.lookup_git_sha(
256
if kind == "commit" and self.source.has_revision(
262
bzr_refs[k] = (v, revid)
265
def fetch_refs(self, update_refs, lossy, overwrite=False):
268
with self.source_store.lock_read():
269
old_refs = self._get_target_bzr_refs()
270
new_refs = update_refs(old_refs)
271
revidmap = self.fetch_objects(
272
[(git_sha, bzr_revid)
273
for (git_sha, bzr_revid) in new_refs.values()
274
if git_sha is None or not git_sha.startswith(SYMREF)],
276
for name, (gitid, revid) in viewitems(new_refs):
279
gitid = revidmap[revid][0]
281
gitid = self.source_store._lookup_revision_sha1(revid)
282
if gitid.startswith(SYMREF):
283
self.target_refs.set_symbolic_ref(
284
name, gitid[len(SYMREF):])
287
old_git_id = old_refs[name][0]
289
self.target_refs.add_if_new(name, gitid)
291
self.target_refs.set_if_equals(name, old_git_id, gitid)
292
result_refs[name] = (gitid, revid if not lossy else self.mapping.revision_id_foreign_to_bzr(gitid))
293
return revidmap, old_refs, result_refs
295
def fetch_objects(self, revs, lossy, limit=None):
296
if not lossy and not self.mapping.roundtripping:
297
for git_sha, bzr_revid in revs:
298
if (bzr_revid is not None and
299
needs_roundtripping(self.source, bzr_revid)):
300
raise NoPushSupport(self.source, self.target, self.mapping,
302
with self.source_store.lock_read():
303
todo = list(self.missing_revisions(revs))[:limit]
305
pb = ui.ui_factory.nested_progress_bar()
307
object_generator = MissingObjectsIterator(
308
self.source_store, self.source, pb)
309
for (old_revid, git_sha) in object_generator.import_revisions(
312
new_revid = self.mapping.revision_id_foreign_to_bzr(
315
new_revid = old_revid
317
self.mapping.revision_id_bzr_to_foreign(old_revid)
318
except InvalidRevisionId:
319
refname = self.mapping.revid_as_refname(old_revid)
320
self.target_refs[refname] = git_sha
321
revidmap[old_revid] = (git_sha, new_revid)
322
self.target_store.add_objects(object_generator)
327
def fetch(self, revision_id=None, pb=None, find_ghosts=False,
328
fetch_spec=None, mapped_refs=None):
329
if mapped_refs is not None:
330
stop_revisions = mapped_refs
331
elif revision_id is not None:
332
stop_revisions = [(None, revision_id)]
333
elif fetch_spec is not None:
334
recipe = fetch_spec.get_recipe()
335
if recipe[0] in ("search", "proxy-search"):
336
stop_revisions = [(None, revid) for revid in recipe[1]]
338
raise AssertionError(
339
"Unsupported search result type %s" % recipe[0])
341
stop_revisions = [(None, revid)
342
for revid in self.source.all_revision_ids()]
345
self.fetch_objects(stop_revisions, lossy=False)
346
except NoPushSupport:
347
raise NoRoundtrippingSupport(self.source, self.target)
350
def is_compatible(source, target):
351
"""Be compatible with GitRepository."""
352
return (not isinstance(source, GitRepository) and
353
isinstance(target, LocalGitRepository))
356
class InterToRemoteGitRepository(InterToGitRepository):
358
def fetch_refs(self, update_refs, lossy, overwrite=False):
359
"""Import the gist of the ancestry of a particular revision."""
360
if not lossy and not self.mapping.roundtripping:
361
raise NoPushSupport(self.source, self.target, self.mapping)
362
unpeel_map = UnpeelMap.from_repository(self.source)
365
def git_update_refs(old_refs):
368
k: (v, None) for (k, v) in viewitems(old_refs)}
369
new_refs = update_refs(self.old_refs)
370
for name, (gitid, revid) in viewitems(new_refs):
372
git_sha = self.source_store._lookup_revision_sha1(revid)
373
gitid = unpeel_map.re_unpeel_tag(
374
git_sha, old_refs.get(name))
376
if remote_divergence(
377
old_refs.get(name), gitid, self.source_store):
378
raise DivergedBranches(self.source, self.target)
382
with self.source_store.lock_read():
383
new_refs = self.target.send_pack(
384
git_update_refs, self.source_store.generate_lossy_pack_data)
386
return revidmap, self.old_refs, new_refs
389
def is_compatible(source, target):
390
"""Be compatible with GitRepository."""
391
return (not isinstance(source, GitRepository) and
392
isinstance(target, RemoteGitRepository))
395
class GitSearchResult(object):
397
def __init__(self, start, exclude, keys):
399
self._exclude = exclude
405
def get_recipe(self):
406
return ('search', self._start, self._exclude, len(self._keys))
409
class InterFromGitRepository(InterRepository):
411
_matching_repo_format = GitRepositoryFormat()
413
def _target_has_shas(self, shas):
414
raise NotImplementedError(self._target_has_shas)
416
def get_determine_wants_heads(self, wants, include_tags=False):
419
def determine_wants(refs):
421
for k, v in viewitems(refs):
422
if k.endswith(ANNOTATED_TAG_SUFFIX):
423
unpeel_lookup[v] = refs[k[:-len(ANNOTATED_TAG_SUFFIX)]]
424
potential = set([unpeel_lookup.get(w, w) for w in wants])
426
for k, sha in viewitems(refs):
427
if k.endswith(ANNOTATED_TAG_SUFFIX):
434
return list(potential - self._target_has_shas(potential))
435
return determine_wants
437
def determine_wants_all(self, refs):
438
raise NotImplementedError(self.determine_wants_all)
441
def _get_repo_format_to_test():
444
def copy_content(self, revision_id=None):
445
"""See InterRepository.copy_content."""
446
self.fetch(revision_id, find_ghosts=False)
448
def search_missing_revision_ids(self,
449
find_ghosts=True, revision_ids=None,
450
if_present_ids=None, limit=None):
451
if limit is not None:
452
raise FetchLimitUnsupported(self)
453
if revision_ids is None and if_present_ids is None:
454
todo = set(self.source.all_revision_ids())
457
if revision_ids is not None:
458
for revid in revision_ids:
459
if not self.source.has_revision(revid):
460
raise NoSuchRevision(revid, self.source)
461
todo.update(revision_ids)
462
if if_present_ids is not None:
463
todo.update(if_present_ids)
464
result_set = todo.difference(self.target.all_revision_ids())
465
result_parents = set(itertools.chain.from_iterable(viewvalues(
466
self.source.get_graph().get_parent_map(result_set))))
467
included_keys = result_set.intersection(result_parents)
468
start_keys = result_set.difference(included_keys)
469
exclude_keys = result_parents.difference(result_set)
470
return GitSearchResult(start_keys, exclude_keys, result_set)
473
class InterGitNonGitRepository(InterFromGitRepository):
474
"""Base InterRepository that copies revisions from a Git into a non-Git
477
def _target_has_shas(self, shas):
481
revid = self.source.lookup_foreign_revision_id(sha)
482
except NotCommitError:
483
# Commit is definitely not present
487
return set([revids[r] for r in self.target.has_revisions(revids)])
489
def determine_wants_all(self, refs):
491
for k, v in viewitems(refs):
492
# For non-git target repositories, only worry about peeled
495
potential.add(self.source.controldir.get_peeled(k) or v)
496
return list(potential - self._target_has_shas(potential))
498
def _warn_slow(self):
499
if not config.GlobalConfig().suppress_warning('slow_intervcs_push'):
501
'Fetching from Git to Bazaar repository. '
502
'For better performance, fetch into a Git repository.')
504
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
505
"""Fetch objects from a remote server.
507
:param determine_wants: determine_wants callback
508
:param mapping: BzrGitMapping to use
509
:param limit: Maximum number of commits to import.
510
:return: Tuple with pack hint, last imported revision id and remote
513
raise NotImplementedError(self.fetch_objects)
515
def get_determine_wants_revids(self, revids, include_tags=False):
517
for revid in set(revids):
518
if self.target.has_revision(revid):
520
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
522
return self.get_determine_wants_heads(wants, include_tags=include_tags)
524
def fetch(self, revision_id=None, find_ghosts=False,
525
mapping=None, fetch_spec=None, include_tags=False):
527
mapping = self.source.get_mapping()
528
if revision_id is not None:
529
interesting_heads = [revision_id]
530
elif fetch_spec is not None:
531
recipe = fetch_spec.get_recipe()
532
if recipe[0] in ("search", "proxy-search"):
533
interesting_heads = recipe[1]
535
raise AssertionError("Unsupported search result type %s" %
538
interesting_heads = None
540
if interesting_heads is not None:
541
determine_wants = self.get_determine_wants_revids(
542
interesting_heads, include_tags=include_tags)
544
determine_wants = self.determine_wants_all
546
(pack_hint, _, remote_refs) = self.fetch_objects(determine_wants,
548
if pack_hint is not None and self.target._format.pack_compresses:
549
self.target.pack(hint=pack_hint)
553
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
554
"""InterRepository that copies revisions from a remote Git into a non-Git
557
def get_target_heads(self):
558
# FIXME: This should be more efficient
559
all_revs = self.target.all_revision_ids()
560
parent_map = self.target.get_parent_map(all_revs)
562
for values in viewvalues(parent_map):
563
all_parents.update(values)
564
return set(all_revs) - all_parents
566
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
567
"""See `InterGitNonGitRepository`."""
569
store = get_object_store(self.target, mapping)
570
with store.lock_write():
571
heads = self.get_target_heads()
572
graph_walker = ObjectStoreGraphWalker(
573
[store._lookup_revision_sha1(head) for head in heads],
574
lambda sha: store[sha].parents)
575
wants_recorder = DetermineWantsRecorder(determine_wants)
577
pb = ui.ui_factory.nested_progress_bar()
579
objects_iter = self.source.fetch_objects(
580
wants_recorder, graph_walker, store.get_raw)
581
trace.mutter("Importing %d new revisions",
582
len(wants_recorder.wants))
583
(pack_hint, last_rev) = import_git_objects(
584
self.target, mapping, objects_iter, store,
585
wants_recorder.wants, pb, limit)
586
return (pack_hint, last_rev, wants_recorder.remote_refs)
591
def is_compatible(source, target):
592
"""Be compatible with GitRepository."""
593
if not isinstance(source, RemoteGitRepository):
595
if not target.supports_rich_root():
597
if isinstance(target, GitRepository):
599
if not getattr(target._format, "supports_full_versioned_files", True):
604
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
605
"""InterRepository that copies revisions from a local Git into a non-Git
608
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
609
"""See `InterGitNonGitRepository`."""
611
remote_refs = self.source.controldir.get_refs_container().as_dict()
612
wants = determine_wants(remote_refs)
613
pb = ui.ui_factory.nested_progress_bar()
614
target_git_object_retriever = get_object_store(self.target, mapping)
616
target_git_object_retriever.lock_write()
618
(pack_hint, last_rev) = import_git_objects(
619
self.target, mapping, self.source._git.object_store,
620
target_git_object_retriever, wants, pb, limit)
621
return (pack_hint, last_rev, remote_refs)
623
target_git_object_retriever.unlock()
628
def is_compatible(source, target):
629
"""Be compatible with GitRepository."""
630
if not isinstance(source, LocalGitRepository):
632
if not target.supports_rich_root():
634
if isinstance(target, GitRepository):
636
if not getattr(target._format, "supports_full_versioned_files", True):
641
class InterGitGitRepository(InterFromGitRepository):
642
"""InterRepository that copies between Git repositories."""
644
def fetch_refs(self, update_refs, lossy, overwrite=False):
646
raise LossyPushToSameVCS(self.source, self.target)
647
old_refs = self.target.controldir.get_refs_container()
650
def determine_wants(heads):
651
old_refs = dict([(k, (v, None))
652
for (k, v) in viewitems(heads.as_dict())])
653
new_refs = update_refs(old_refs)
654
ref_changes.update(new_refs)
655
return [sha1 for (sha1, bzr_revid) in viewvalues(new_refs)]
656
self.fetch_objects(determine_wants, lossy=lossy)
657
for k, (git_sha, bzr_revid) in viewitems(ref_changes):
658
self.target._git.refs[k] = git_sha
659
new_refs = self.target.controldir.get_refs_container()
660
return None, old_refs, new_refs
662
def fetch_objects(self, determine_wants, mapping=None, limit=None,
664
raise NotImplementedError(self.fetch_objects)
666
def _target_has_shas(self, shas):
668
[sha for sha in shas if sha in self.target._git.object_store])
670
def fetch(self, revision_id=None, find_ghosts=False,
671
mapping=None, fetch_spec=None, branches=None, limit=None,
674
mapping = self.source.get_mapping()
675
if revision_id is not None:
677
elif fetch_spec is not None:
678
recipe = fetch_spec.get_recipe()
679
if recipe[0] in ("search", "proxy-search"):
682
raise AssertionError(
683
"Unsupported search result type %s" % recipe[0])
685
if branches is not None:
686
def determine_wants(refs):
688
for name, value in viewitems(refs):
689
if value == ZERO_SHA:
692
if name in branches or (include_tags and is_tag(name)):
695
elif fetch_spec is None and revision_id is None:
696
determine_wants = self.determine_wants_all
698
determine_wants = self.get_determine_wants_revids(
699
args, include_tags=include_tags)
700
wants_recorder = DetermineWantsRecorder(determine_wants)
701
self.fetch_objects(wants_recorder, mapping, limit=limit)
702
return wants_recorder.remote_refs
704
def get_determine_wants_revids(self, revids, include_tags=False):
706
for revid in set(revids):
707
if revid == NULL_REVISION:
709
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
711
return self.get_determine_wants_heads(wants, include_tags=include_tags)
713
def determine_wants_all(self, refs):
715
v for k, v in refs.items()
716
if not v == ZERO_SHA and not k.endswith(ANNOTATED_TAG_SUFFIX)])
717
return list(potential - self._target_has_shas(potential))
720
class InterLocalGitLocalGitRepository(InterGitGitRepository):
722
def fetch_objects(self, determine_wants, mapping=None, limit=None,
725
raise LossyPushToSameVCS(self.source, self.target)
726
if limit is not None:
727
raise FetchLimitUnsupported(self)
728
from .remote import DefaultProgressReporter
729
pb = ui.ui_factory.nested_progress_bar()
730
progress = DefaultProgressReporter(pb).progress
732
refs = self.source._git.fetch(
733
self.target._git, determine_wants,
737
return (None, None, refs)
740
def is_compatible(source, target):
741
"""Be compatible with GitRepository."""
742
return (isinstance(source, LocalGitRepository) and
743
isinstance(target, LocalGitRepository))
746
class InterRemoteGitLocalGitRepository(InterGitGitRepository):
748
def fetch_objects(self, determine_wants, mapping=None, limit=None,
751
raise LossyPushToSameVCS(self.source, self.target)
752
if limit is not None:
753
raise FetchLimitUnsupported(self)
754
graphwalker = self.target._git.get_graph_walker()
755
if (CAPABILITY_THIN_PACK in
756
self.source.controldir._client._fetch_capabilities):
757
# TODO(jelmer): Avoid reading entire file into memory and
758
# only processing it after the whole file has been fetched.
764
self.target._git.object_store.move_in_thin_pack(f)
769
f, commit, abort = self.target._git.object_store.add_pack()
771
refs = self.source.controldir.fetch_pack(
772
determine_wants, graphwalker, f.write)
774
return (None, None, refs)
775
except BaseException:
780
def is_compatible(source, target):
781
"""Be compatible with GitRepository."""
782
return (isinstance(source, RemoteGitRepository) and
783
isinstance(target, LocalGitRepository))