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 io import BytesIO
22
from dulwich.errors import (
25
from dulwich.object_store import (
26
ObjectStoreGraphWalker,
28
from dulwich.protocol import (
32
from dulwich.refs import (
36
from dulwich.walk import Walker
38
from ..errors import (
40
FetchLimitUnsupported,
43
NoRoundtrippingSupport,
46
from ..repository import (
50
from ..revision import (
64
DetermineWantsRecorder,
66
from .mapping import (
69
from .object_store import (
73
MissingObjectsIterator,
80
from .repository import (
88
from .unpeel_map import (
93
class InterToGitRepository(InterRepository):
94
"""InterRepository that copies into a Git repository."""
96
_matching_repo_format = GitRepositoryFormat()
98
def __init__(self, source, target):
99
super(InterToGitRepository, self).__init__(source, target)
100
self.mapping = self.target.get_mapping()
101
self.source_store = get_object_store(self.source, self.mapping)
104
def _get_repo_format_to_test():
107
def copy_content(self, revision_id=None, pb=None):
108
"""See InterRepository.copy_content."""
109
self.fetch(revision_id, pb, find_ghosts=False)
111
def fetch_refs(self, update_refs, lossy, overwrite=False):
112
"""Fetch possibly roundtripped revisions into the target repository
115
:param update_refs: Generate refs to fetch. Receives dictionary
116
with old refs (git shas), returns dictionary of new names to
118
:param lossy: Whether to roundtrip
119
:return: old refs, new refs
121
raise NotImplementedError(self.fetch_refs)
123
def search_missing_revision_ids(self,
124
find_ghosts=True, revision_ids=None,
125
if_present_ids=None, limit=None):
126
if limit is not None:
127
raise FetchLimitUnsupported(self)
131
todo.extend(revision_ids)
133
todo.extend(revision_ids)
134
with self.source_store.lock_read():
135
for revid in revision_ids:
136
if revid == NULL_REVISION:
139
git_sha = self.source_store._lookup_revision_sha1(revid)
141
raise NoSuchRevision(revid, self.source)
142
git_shas.append(git_sha)
147
sha for sha in self.target.controldir.get_refs_container().as_dict().values()
149
missing_revids = set()
151
for (kind, type_data) in self.source_store.lookup_git_sha(
154
missing_revids.add(type_data[0])
155
return self.source.revision_ids_to_search_result(missing_revids)
157
def _warn_slow(self):
158
if not config.GlobalConfig().suppress_warning('slow_intervcs_push'):
160
'Pushing from a Bazaar to a Git repository. '
161
'For better performance, push into a Bazaar repository.')
164
class InterToLocalGitRepository(InterToGitRepository):
165
"""InterBranch implementation between a Bazaar and a Git repository."""
167
def __init__(self, source, target):
168
super(InterToLocalGitRepository, self).__init__(source, target)
169
self.target_store = self.target.controldir._git.object_store
170
self.target_refs = self.target.controldir._git.refs
172
def _commit_needs_fetching(self, sha_id):
174
return (sha_id not in self.target_store)
175
except NoSuchRevision:
179
def _revision_needs_fetching(self, sha_id, revid):
180
if revid == NULL_REVISION:
184
sha_id = self.source_store._lookup_revision_sha1(revid)
187
return self._commit_needs_fetching(sha_id)
189
def missing_revisions(self, stop_revisions):
190
"""Find the revisions that are missing from the target repository.
192
:param stop_revisions: Revisions to check for (tuples with
194
:return: sequence of missing revisions, in topological order
195
:raise: NoSuchRevision if the stop_revisions are not present in
200
for (sha1, revid) in stop_revisions:
201
if sha1 is not None and revid is not None:
202
revid_sha_map[revid] = sha1
203
stop_revids.append(revid)
204
elif sha1 is not None:
205
if self._commit_needs_fetching(sha1):
206
for (kind, (revid, tree_sha, verifiers)) in self.source_store.lookup_git_sha(sha1):
207
revid_sha_map[revid] = sha1
208
stop_revids.append(revid)
212
stop_revids.append(revid)
214
graph = self.source.get_graph()
215
with ui.ui_factory.nested_progress_bar() as pb:
218
for revid in stop_revids:
219
sha1 = revid_sha_map.get(revid)
220
if (revid not in missing and
221
self._revision_needs_fetching(sha1, revid)):
223
new_stop_revids.append(revid)
225
parent_map = graph.get_parent_map(new_stop_revids)
226
for parent_revids in parent_map.values():
227
stop_revids.update(parent_revids)
228
pb.update("determining revisions to fetch", len(missing))
229
return graph.iter_topo_order(missing)
231
def _get_target_bzr_refs(self):
232
"""Return a dictionary with references.
234
:return: Dictionary with reference names as keys and tuples
235
with Git SHA, Bazaar revid as values.
238
for k in self.target._git.refs.allkeys():
240
v = self.target._git.refs.read_ref(k)
245
if not v.startswith(SYMREF):
247
for (kind, type_data) in self.source_store.lookup_git_sha(
249
if kind == "commit" and self.source.has_revision(
255
bzr_refs[k] = (v, revid)
258
def fetch_refs(self, update_refs, lossy, overwrite=False):
261
with self.source_store.lock_read():
262
old_refs = self._get_target_bzr_refs()
263
new_refs = update_refs(old_refs)
264
revidmap = self.fetch_objects(
265
[(git_sha, bzr_revid)
266
for (git_sha, bzr_revid) in new_refs.values()
267
if git_sha is None or not git_sha.startswith(SYMREF)],
269
for name, (gitid, revid) in new_refs.items():
272
gitid = revidmap[revid][0]
274
gitid = self.source_store._lookup_revision_sha1(revid)
275
if gitid.startswith(SYMREF):
276
self.target_refs.set_symbolic_ref(
277
name, gitid[len(SYMREF):])
280
old_git_id = old_refs[name][0]
282
self.target_refs.add_if_new(name, gitid)
284
self.target_refs.set_if_equals(name, old_git_id, gitid)
285
result_refs[name] = (gitid, revid if not lossy else self.mapping.revision_id_foreign_to_bzr(gitid))
286
return revidmap, old_refs, result_refs
288
def fetch_objects(self, revs, lossy, limit=None):
289
if not lossy and not self.mapping.roundtripping:
290
for git_sha, bzr_revid in revs:
291
if (bzr_revid is not None and
292
needs_roundtripping(self.source, bzr_revid)):
293
raise NoPushSupport(self.source, self.target, self.mapping,
295
with self.source_store.lock_read():
296
todo = list(self.missing_revisions(revs))[:limit]
298
with ui.ui_factory.nested_progress_bar() as pb:
299
object_generator = MissingObjectsIterator(
300
self.source_store, self.source, pb)
301
for (old_revid, git_sha) in object_generator.import_revisions(
304
new_revid = self.mapping.revision_id_foreign_to_bzr(
307
new_revid = old_revid
309
self.mapping.revision_id_bzr_to_foreign(old_revid)
310
except InvalidRevisionId:
311
refname = self.mapping.revid_as_refname(old_revid)
312
self.target_refs[refname] = git_sha
313
revidmap[old_revid] = (git_sha, new_revid)
314
self.target_store.add_objects(object_generator)
317
def fetch(self, revision_id=None, pb=None, find_ghosts=False,
318
fetch_spec=None, mapped_refs=None, lossy=False):
319
if mapped_refs is not None:
320
stop_revisions = mapped_refs
321
elif revision_id is not None:
322
stop_revisions = [(None, revision_id)]
323
elif fetch_spec is not None:
324
recipe = fetch_spec.get_recipe()
325
if recipe[0] in ("search", "proxy-search"):
326
stop_revisions = [(None, revid) for revid in recipe[1]]
328
raise AssertionError(
329
"Unsupported search result type %s" % recipe[0])
331
stop_revisions = [(None, revid)
332
for revid in self.source.all_revision_ids()]
335
revidmap = self.fetch_objects(stop_revisions, lossy=lossy)
336
except NoPushSupport:
337
raise NoRoundtrippingSupport(self.source, self.target)
338
return FetchResult(revidmap)
341
def is_compatible(source, target):
342
"""Be compatible with GitRepository."""
343
return (not isinstance(source, GitRepository) and
344
isinstance(target, LocalGitRepository))
347
class InterToRemoteGitRepository(InterToGitRepository):
349
def fetch_refs(self, update_refs, lossy, overwrite=False):
350
"""Import the gist of the ancestry of a particular revision."""
351
if not lossy and not self.mapping.roundtripping:
352
raise NoPushSupport(self.source, self.target, self.mapping)
353
unpeel_map = UnpeelMap.from_repository(self.source)
356
def git_update_refs(old_refs):
359
k: (v, None) for (k, v) in old_refs.items()}
360
new_refs = update_refs(self.old_refs)
361
for name, (gitid, revid) in new_refs.items():
363
git_sha = self.source_store._lookup_revision_sha1(revid)
364
gitid = unpeel_map.re_unpeel_tag(
365
git_sha, old_refs.get(name))
367
if remote_divergence(
368
old_refs.get(name), gitid, self.source_store):
369
raise DivergedBranches(self.source, self.target)
373
with self.source_store.lock_read():
374
new_refs = self.target.send_pack(
375
git_update_refs, self.source_store.generate_lossy_pack_data)
377
return revidmap, self.old_refs, new_refs
380
def is_compatible(source, target):
381
"""Be compatible with GitRepository."""
382
return (not isinstance(source, GitRepository) and
383
isinstance(target, RemoteGitRepository))
386
class GitSearchResult(object):
388
def __init__(self, start, exclude, keys):
390
self._exclude = exclude
396
def get_recipe(self):
397
return ('search', self._start, self._exclude, len(self._keys))
400
class InterFromGitRepository(InterRepository):
402
_matching_repo_format = GitRepositoryFormat()
404
def _target_has_shas(self, shas):
405
raise NotImplementedError(self._target_has_shas)
407
def get_determine_wants_heads(self, wants, include_tags=False, tag_selector=None):
410
def determine_wants(refs):
412
for k, v in refs.items():
413
if k.endswith(ANNOTATED_TAG_SUFFIX):
414
unpeel_lookup[v] = refs[k[:-len(ANNOTATED_TAG_SUFFIX)]]
415
potential = set([unpeel_lookup.get(w, w) for w in wants])
417
for k, sha in refs.items():
418
if k.endswith(ANNOTATED_TAG_SUFFIX):
421
tag_name = ref_to_tag_name(k)
424
if tag_selector and not tag_selector(tag_name):
429
return list(potential - self._target_has_shas(potential))
430
return determine_wants
432
def determine_wants_all(self, refs):
433
raise NotImplementedError(self.determine_wants_all)
436
def _get_repo_format_to_test():
439
def copy_content(self, revision_id=None):
440
"""See InterRepository.copy_content."""
441
self.fetch(revision_id, find_ghosts=False)
443
def search_missing_revision_ids(self,
444
find_ghosts=True, revision_ids=None,
445
if_present_ids=None, limit=None):
446
if limit is not None:
447
raise FetchLimitUnsupported(self)
448
if revision_ids is None and if_present_ids is None:
449
todo = set(self.source.all_revision_ids())
452
if revision_ids is not None:
453
for revid in revision_ids:
454
if not self.source.has_revision(revid):
455
raise NoSuchRevision(revid, self.source)
456
todo.update(revision_ids)
457
if if_present_ids is not None:
458
todo.update(if_present_ids)
459
result_set = todo.difference(self.target.all_revision_ids())
460
result_parents = set(itertools.chain.from_iterable(
461
self.source.get_graph().get_parent_map(result_set).values()))
462
included_keys = result_set.intersection(result_parents)
463
start_keys = result_set.difference(included_keys)
464
exclude_keys = result_parents.difference(result_set)
465
return GitSearchResult(start_keys, exclude_keys, result_set)
468
class InterGitNonGitRepository(InterFromGitRepository):
469
"""Base InterRepository that copies revisions from a Git into a non-Git
472
def _target_has_shas(self, shas):
476
revid = self.source.lookup_foreign_revision_id(sha)
477
except NotCommitError:
478
# Commit is definitely not present
482
return set([revids[r] for r in self.target.has_revisions(revids)])
484
def determine_wants_all(self, refs):
486
for k, v in refs.items():
487
# For non-git target repositories, only worry about peeled
490
potential.add(self.source.controldir.get_peeled(k) or v)
491
return list(potential - self._target_has_shas(potential))
493
def _warn_slow(self):
494
if not config.GlobalConfig().suppress_warning('slow_intervcs_push'):
496
'Fetching from Git to Bazaar repository. '
497
'For better performance, fetch into a Git repository.')
499
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
500
"""Fetch objects from a remote server.
502
:param determine_wants: determine_wants callback
503
:param mapping: BzrGitMapping to use
504
:param limit: Maximum number of commits to import.
505
:return: Tuple with pack hint, last imported revision id and remote
508
raise NotImplementedError(self.fetch_objects)
510
def get_determine_wants_revids(self, revids, include_tags=False, tag_selector=None):
512
for revid in set(revids):
513
if self.target.has_revision(revid):
515
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
517
return self.get_determine_wants_heads(
518
wants, include_tags=include_tags, tag_selector=tag_selector)
520
def fetch(self, revision_id=None, find_ghosts=False,
521
mapping=None, fetch_spec=None, include_tags=False, lossy=False):
523
mapping = self.source.get_mapping()
524
if revision_id is not None:
525
interesting_heads = [revision_id]
526
elif fetch_spec is not None:
527
recipe = fetch_spec.get_recipe()
528
if recipe[0] in ("search", "proxy-search"):
529
interesting_heads = recipe[1]
531
raise AssertionError("Unsupported search result type %s" %
534
interesting_heads = None
536
if interesting_heads is not None:
537
determine_wants = self.get_determine_wants_revids(
538
interesting_heads, include_tags=include_tags)
540
determine_wants = self.determine_wants_all
542
(pack_hint, _, remote_refs) = self.fetch_objects(
543
determine_wants, mapping, lossy=lossy)
544
if pack_hint is not None and self.target._format.pack_compresses:
545
self.target.pack(hint=pack_hint)
546
result = FetchResult()
547
result.refs = remote_refs
551
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
552
"""InterRepository that copies revisions from a remote Git into a non-Git
555
def get_target_heads(self):
556
# FIXME: This should be more efficient
557
all_revs = self.target.all_revision_ids()
558
parent_map = self.target.get_parent_map(all_revs)
560
for values in parent_map.values():
561
all_parents.update(values)
562
return set(all_revs) - all_parents
564
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
565
"""See `InterGitNonGitRepository`."""
567
store = get_object_store(self.target, mapping)
568
with store.lock_write():
569
heads = self.get_target_heads()
570
graph_walker = ObjectStoreGraphWalker(
571
[store._lookup_revision_sha1(head) for head in heads],
572
lambda sha: store[sha].parents)
573
wants_recorder = DetermineWantsRecorder(determine_wants)
575
with ui.ui_factory.nested_progress_bar() as pb:
576
objects_iter = self.source.fetch_objects(
577
wants_recorder, graph_walker, store.get_raw)
578
trace.mutter("Importing %d new revisions",
579
len(wants_recorder.wants))
580
(pack_hint, last_rev) = import_git_objects(
581
self.target, mapping, objects_iter, store,
582
wants_recorder.wants, pb, limit)
583
return (pack_hint, last_rev, wants_recorder.remote_refs)
586
def is_compatible(source, target):
587
"""Be compatible with GitRepository."""
588
if not isinstance(source, RemoteGitRepository):
590
if not target.supports_rich_root():
592
if isinstance(target, GitRepository):
594
if not getattr(target._format, "supports_full_versioned_files", True):
599
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
600
"""InterRepository that copies revisions from a local Git into a non-Git
603
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
604
"""See `InterGitNonGitRepository`."""
606
remote_refs = self.source.controldir.get_refs_container().as_dict()
607
wants = determine_wants(remote_refs)
608
target_git_object_retriever = get_object_store(self.target, mapping)
609
with ui.ui_factory.nested_progress_bar() as pb:
610
target_git_object_retriever.lock_write()
612
(pack_hint, last_rev) = import_git_objects(
613
self.target, mapping, self.source._git.object_store,
614
target_git_object_retriever, wants, pb, limit)
615
return (pack_hint, last_rev, remote_refs)
617
target_git_object_retriever.unlock()
620
def is_compatible(source, target):
621
"""Be compatible with GitRepository."""
622
if not isinstance(source, LocalGitRepository):
624
if not target.supports_rich_root():
626
if isinstance(target, GitRepository):
628
if not getattr(target._format, "supports_full_versioned_files", True):
633
class InterGitGitRepository(InterFromGitRepository):
634
"""InterRepository that copies between Git repositories."""
636
def fetch_refs(self, update_refs, lossy, overwrite=False):
638
raise LossyPushToSameVCS(self.source, self.target)
639
old_refs = self.target.controldir.get_refs_container()
642
def determine_wants(heads):
643
old_refs = dict([(k, (v, None))
644
for (k, v) in heads.as_dict().items()])
645
new_refs = update_refs(old_refs)
646
ref_changes.update(new_refs)
647
return [sha1 for (sha1, bzr_revid) in new_refs.values()]
648
self.fetch_objects(determine_wants, lossy=lossy)
649
for k, (git_sha, bzr_revid) in ref_changes.items():
650
self.target._git.refs[k] = git_sha
651
new_refs = self.target.controldir.get_refs_container()
652
return None, old_refs, new_refs
654
def fetch_objects(self, determine_wants, mapping=None, limit=None,
656
raise NotImplementedError(self.fetch_objects)
658
def _target_has_shas(self, shas):
660
[sha for sha in shas if sha in self.target._git.object_store])
662
def fetch(self, revision_id=None, find_ghosts=False,
663
mapping=None, fetch_spec=None, branches=None, limit=None,
664
include_tags=False, lossy=False):
666
mapping = self.source.get_mapping()
667
if revision_id is not None:
669
elif fetch_spec is not None:
670
recipe = fetch_spec.get_recipe()
671
if recipe[0] in ("search", "proxy-search"):
674
raise AssertionError(
675
"Unsupported search result type %s" % recipe[0])
677
if branches is not None:
678
determine_wants = self.get_determine_wants_branches(
679
branches, include_tags=include_tags)
680
elif fetch_spec is None and revision_id is None:
681
determine_wants = self.determine_wants_all
683
determine_wants = self.get_determine_wants_revids(
684
args, include_tags=include_tags)
685
wants_recorder = DetermineWantsRecorder(determine_wants)
686
self.fetch_objects(wants_recorder, mapping, limit=limit, lossy=lossy)
687
result = FetchResult()
688
result.refs = wants_recorder.remote_refs
691
def get_determine_wants_revids(self, revids, include_tags=False, tag_selector=None):
693
for revid in set(revids):
694
if revid == NULL_REVISION:
696
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
698
return self.get_determine_wants_heads(wants, include_tags=include_tags, tag_selector=tag_selector)
700
def get_determine_wants_branches(self, branches, include_tags=False):
701
def determine_wants(refs):
703
for name, value in refs.items():
704
if value == ZERO_SHA:
707
if name.endswith(ANNOTATED_TAG_SUFFIX):
710
if name in branches or (include_tags and is_tag(name)):
713
return determine_wants
715
def determine_wants_all(self, refs):
717
v for k, v in refs.items()
718
if not v == ZERO_SHA and not k.endswith(ANNOTATED_TAG_SUFFIX)])
719
return list(potential - self._target_has_shas(potential))
722
class InterLocalGitLocalGitRepository(InterGitGitRepository):
724
def fetch_objects(self, determine_wants, mapping=None, limit=None,
727
raise LossyPushToSameVCS(self.source, self.target)
728
if limit is not None:
729
raise FetchLimitUnsupported(self)
730
from .remote import DefaultProgressReporter
731
with ui.ui_factory.nested_progress_bar() as pb:
732
progress = DefaultProgressReporter(pb).progress
733
refs = self.source._git.fetch(
734
self.target._git, determine_wants,
736
return (None, None, refs)
739
def is_compatible(source, target):
740
"""Be compatible with GitRepository."""
741
return (isinstance(source, LocalGitRepository) and
742
isinstance(target, LocalGitRepository))
745
class InterRemoteGitLocalGitRepository(InterGitGitRepository):
747
def fetch_objects(self, determine_wants, mapping=None, limit=None,
750
raise LossyPushToSameVCS(self.source, self.target)
751
if limit is not None:
752
raise FetchLimitUnsupported(self)
753
graphwalker = self.target._git.get_graph_walker()
754
if (CAPABILITY_THIN_PACK in
755
self.source.controldir._client._fetch_capabilities):
756
# TODO(jelmer): Avoid reading entire file into memory and
757
# only processing it after the whole file has been fetched.
763
self.target._git.object_store.move_in_thin_pack(f)
768
f, commit, abort = self.target._git.object_store.add_pack()
770
refs = self.source.controldir.fetch_pack(
771
determine_wants, graphwalker, f.write)
773
return (None, None, refs)
774
except BaseException:
779
def is_compatible(source, target):
780
"""Be compatible with GitRepository."""
781
return (isinstance(source, RemoteGitRepository) and
782
isinstance(target, LocalGitRepository))