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
with ui.ui_factory.nested_progress_bar() as pb:
222
for revid in stop_revids:
223
sha1 = revid_sha_map.get(revid)
224
if (revid not in missing and
225
self._revision_needs_fetching(sha1, revid)):
227
new_stop_revids.append(revid)
229
parent_map = graph.get_parent_map(new_stop_revids)
230
for parent_revids in viewvalues(parent_map):
231
stop_revids.update(parent_revids)
232
pb.update("determining revisions to fetch", len(missing))
233
return graph.iter_topo_order(missing)
235
def _get_target_bzr_refs(self):
236
"""Return a dictionary with references.
238
:return: Dictionary with reference names as keys and tuples
239
with Git SHA, Bazaar revid as values.
242
for k in self.target._git.refs.allkeys():
244
v = self.target._git.refs.read_ref(k)
249
if not v.startswith(SYMREF):
251
for (kind, type_data) in self.source_store.lookup_git_sha(
253
if kind == "commit" and self.source.has_revision(
259
bzr_refs[k] = (v, revid)
262
def fetch_refs(self, update_refs, lossy, overwrite=False):
265
with self.source_store.lock_read():
266
old_refs = self._get_target_bzr_refs()
267
new_refs = update_refs(old_refs)
268
revidmap = self.fetch_objects(
269
[(git_sha, bzr_revid)
270
for (git_sha, bzr_revid) in new_refs.values()
271
if git_sha is None or not git_sha.startswith(SYMREF)],
273
for name, (gitid, revid) in viewitems(new_refs):
276
gitid = revidmap[revid][0]
278
gitid = self.source_store._lookup_revision_sha1(revid)
279
if gitid.startswith(SYMREF):
280
self.target_refs.set_symbolic_ref(
281
name, gitid[len(SYMREF):])
284
old_git_id = old_refs[name][0]
286
self.target_refs.add_if_new(name, gitid)
288
self.target_refs.set_if_equals(name, old_git_id, gitid)
289
result_refs[name] = (gitid, revid if not lossy else self.mapping.revision_id_foreign_to_bzr(gitid))
290
return revidmap, old_refs, result_refs
292
def fetch_objects(self, revs, lossy, limit=None):
293
if not lossy and not self.mapping.roundtripping:
294
for git_sha, bzr_revid in revs:
295
if (bzr_revid is not None and
296
needs_roundtripping(self.source, bzr_revid)):
297
raise NoPushSupport(self.source, self.target, self.mapping,
299
with self.source_store.lock_read():
300
todo = list(self.missing_revisions(revs))[:limit]
302
with ui.ui_factory.nested_progress_bar() as pb:
303
object_generator = MissingObjectsIterator(
304
self.source_store, self.source, pb)
305
for (old_revid, git_sha) in object_generator.import_revisions(
308
new_revid = self.mapping.revision_id_foreign_to_bzr(
311
new_revid = old_revid
313
self.mapping.revision_id_bzr_to_foreign(old_revid)
314
except InvalidRevisionId:
315
refname = self.mapping.revid_as_refname(old_revid)
316
self.target_refs[refname] = git_sha
317
revidmap[old_revid] = (git_sha, new_revid)
318
self.target_store.add_objects(object_generator)
321
def fetch(self, revision_id=None, pb=None, find_ghosts=False,
322
fetch_spec=None, mapped_refs=None):
323
if mapped_refs is not None:
324
stop_revisions = mapped_refs
325
elif revision_id is not None:
326
stop_revisions = [(None, revision_id)]
327
elif fetch_spec is not None:
328
recipe = fetch_spec.get_recipe()
329
if recipe[0] in ("search", "proxy-search"):
330
stop_revisions = [(None, revid) for revid in recipe[1]]
332
raise AssertionError(
333
"Unsupported search result type %s" % recipe[0])
335
stop_revisions = [(None, revid)
336
for revid in self.source.all_revision_ids()]
339
self.fetch_objects(stop_revisions, lossy=False)
340
except NoPushSupport:
341
raise NoRoundtrippingSupport(self.source, self.target)
344
def is_compatible(source, target):
345
"""Be compatible with GitRepository."""
346
return (not isinstance(source, GitRepository) and
347
isinstance(target, LocalGitRepository))
350
class InterToRemoteGitRepository(InterToGitRepository):
352
def fetch_refs(self, update_refs, lossy, overwrite=False):
353
"""Import the gist of the ancestry of a particular revision."""
354
if not lossy and not self.mapping.roundtripping:
355
raise NoPushSupport(self.source, self.target, self.mapping)
356
unpeel_map = UnpeelMap.from_repository(self.source)
359
def git_update_refs(old_refs):
362
k: (v, None) for (k, v) in viewitems(old_refs)}
363
new_refs = update_refs(self.old_refs)
364
for name, (gitid, revid) in viewitems(new_refs):
366
git_sha = self.source_store._lookup_revision_sha1(revid)
367
gitid = unpeel_map.re_unpeel_tag(
368
git_sha, old_refs.get(name))
370
if remote_divergence(
371
old_refs.get(name), gitid, self.source_store):
372
raise DivergedBranches(self.source, self.target)
376
with self.source_store.lock_read():
377
new_refs = self.target.send_pack(
378
git_update_refs, self.source_store.generate_lossy_pack_data)
380
return revidmap, self.old_refs, new_refs
383
def is_compatible(source, target):
384
"""Be compatible with GitRepository."""
385
return (not isinstance(source, GitRepository) and
386
isinstance(target, RemoteGitRepository))
389
class GitSearchResult(object):
391
def __init__(self, start, exclude, keys):
393
self._exclude = exclude
399
def get_recipe(self):
400
return ('search', self._start, self._exclude, len(self._keys))
403
class InterFromGitRepository(InterRepository):
405
_matching_repo_format = GitRepositoryFormat()
407
def _target_has_shas(self, shas):
408
raise NotImplementedError(self._target_has_shas)
410
def get_determine_wants_heads(self, wants, include_tags=False):
413
def determine_wants(refs):
415
for k, v in viewitems(refs):
416
if k.endswith(ANNOTATED_TAG_SUFFIX):
417
unpeel_lookup[v] = refs[k[:-len(ANNOTATED_TAG_SUFFIX)]]
418
potential = set([unpeel_lookup.get(w, w) for w in wants])
420
for k, sha in viewitems(refs):
421
if k.endswith(ANNOTATED_TAG_SUFFIX):
428
return list(potential - self._target_has_shas(potential))
429
return determine_wants
431
def determine_wants_all(self, refs):
432
raise NotImplementedError(self.determine_wants_all)
435
def _get_repo_format_to_test():
438
def copy_content(self, revision_id=None):
439
"""See InterRepository.copy_content."""
440
self.fetch(revision_id, find_ghosts=False)
442
def search_missing_revision_ids(self,
443
find_ghosts=True, revision_ids=None,
444
if_present_ids=None, limit=None):
445
if limit is not None:
446
raise FetchLimitUnsupported(self)
447
if revision_ids is None and if_present_ids is None:
448
todo = set(self.source.all_revision_ids())
451
if revision_ids is not None:
452
for revid in revision_ids:
453
if not self.source.has_revision(revid):
454
raise NoSuchRevision(revid, self.source)
455
todo.update(revision_ids)
456
if if_present_ids is not None:
457
todo.update(if_present_ids)
458
result_set = todo.difference(self.target.all_revision_ids())
459
result_parents = set(itertools.chain.from_iterable(viewvalues(
460
self.source.get_graph().get_parent_map(result_set))))
461
included_keys = result_set.intersection(result_parents)
462
start_keys = result_set.difference(included_keys)
463
exclude_keys = result_parents.difference(result_set)
464
return GitSearchResult(start_keys, exclude_keys, result_set)
467
class InterGitNonGitRepository(InterFromGitRepository):
468
"""Base InterRepository that copies revisions from a Git into a non-Git
471
def _target_has_shas(self, shas):
475
revid = self.source.lookup_foreign_revision_id(sha)
476
except NotCommitError:
477
# Commit is definitely not present
481
return set([revids[r] for r in self.target.has_revisions(revids)])
483
def determine_wants_all(self, refs):
485
for k, v in viewitems(refs):
486
# For non-git target repositories, only worry about peeled
489
potential.add(self.source.controldir.get_peeled(k) or v)
490
return list(potential - self._target_has_shas(potential))
492
def _warn_slow(self):
493
if not config.GlobalConfig().suppress_warning('slow_intervcs_push'):
495
'Fetching from Git to Bazaar repository. '
496
'For better performance, fetch into a Git repository.')
498
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
499
"""Fetch objects from a remote server.
501
:param determine_wants: determine_wants callback
502
:param mapping: BzrGitMapping to use
503
:param limit: Maximum number of commits to import.
504
:return: Tuple with pack hint, last imported revision id and remote
507
raise NotImplementedError(self.fetch_objects)
509
def get_determine_wants_revids(self, revids, include_tags=False):
511
for revid in set(revids):
512
if self.target.has_revision(revid):
514
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
516
return self.get_determine_wants_heads(wants, include_tags=include_tags)
518
def fetch(self, revision_id=None, find_ghosts=False,
519
mapping=None, fetch_spec=None, include_tags=False):
521
mapping = self.source.get_mapping()
522
if revision_id is not None:
523
interesting_heads = [revision_id]
524
elif fetch_spec is not None:
525
recipe = fetch_spec.get_recipe()
526
if recipe[0] in ("search", "proxy-search"):
527
interesting_heads = recipe[1]
529
raise AssertionError("Unsupported search result type %s" %
532
interesting_heads = None
534
if interesting_heads is not None:
535
determine_wants = self.get_determine_wants_revids(
536
interesting_heads, include_tags=include_tags)
538
determine_wants = self.determine_wants_all
540
(pack_hint, _, remote_refs) = self.fetch_objects(determine_wants,
542
if pack_hint is not None and self.target._format.pack_compresses:
543
self.target.pack(hint=pack_hint)
547
class InterRemoteGitNonGitRepository(InterGitNonGitRepository):
548
"""InterRepository that copies revisions from a remote Git into a non-Git
551
def get_target_heads(self):
552
# FIXME: This should be more efficient
553
all_revs = self.target.all_revision_ids()
554
parent_map = self.target.get_parent_map(all_revs)
556
for values in viewvalues(parent_map):
557
all_parents.update(values)
558
return set(all_revs) - all_parents
560
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
561
"""See `InterGitNonGitRepository`."""
563
store = get_object_store(self.target, mapping)
564
with store.lock_write():
565
heads = self.get_target_heads()
566
graph_walker = ObjectStoreGraphWalker(
567
[store._lookup_revision_sha1(head) for head in heads],
568
lambda sha: store[sha].parents)
569
wants_recorder = DetermineWantsRecorder(determine_wants)
571
with ui.ui_factory.nested_progress_bar() as pb:
572
objects_iter = self.source.fetch_objects(
573
wants_recorder, graph_walker, store.get_raw)
574
trace.mutter("Importing %d new revisions",
575
len(wants_recorder.wants))
576
(pack_hint, last_rev) = import_git_objects(
577
self.target, mapping, objects_iter, store,
578
wants_recorder.wants, pb, limit)
579
return (pack_hint, last_rev, wants_recorder.remote_refs)
582
def is_compatible(source, target):
583
"""Be compatible with GitRepository."""
584
if not isinstance(source, RemoteGitRepository):
586
if not target.supports_rich_root():
588
if isinstance(target, GitRepository):
590
if not getattr(target._format, "supports_full_versioned_files", True):
595
class InterLocalGitNonGitRepository(InterGitNonGitRepository):
596
"""InterRepository that copies revisions from a local Git into a non-Git
599
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
600
"""See `InterGitNonGitRepository`."""
602
remote_refs = self.source.controldir.get_refs_container().as_dict()
603
wants = determine_wants(remote_refs)
604
target_git_object_retriever = get_object_store(self.target, mapping)
605
with ui.ui_factory.nested_progress_bar() as pb:
606
target_git_object_retriever.lock_write()
608
(pack_hint, last_rev) = import_git_objects(
609
self.target, mapping, self.source._git.object_store,
610
target_git_object_retriever, wants, pb, limit)
611
return (pack_hint, last_rev, remote_refs)
613
target_git_object_retriever.unlock()
616
def is_compatible(source, target):
617
"""Be compatible with GitRepository."""
618
if not isinstance(source, LocalGitRepository):
620
if not target.supports_rich_root():
622
if isinstance(target, GitRepository):
624
if not getattr(target._format, "supports_full_versioned_files", True):
629
class InterGitGitRepository(InterFromGitRepository):
630
"""InterRepository that copies between Git repositories."""
632
def fetch_refs(self, update_refs, lossy, overwrite=False):
634
raise LossyPushToSameVCS(self.source, self.target)
635
old_refs = self.target.controldir.get_refs_container()
638
def determine_wants(heads):
639
old_refs = dict([(k, (v, None))
640
for (k, v) in viewitems(heads.as_dict())])
641
new_refs = update_refs(old_refs)
642
ref_changes.update(new_refs)
643
return [sha1 for (sha1, bzr_revid) in viewvalues(new_refs)]
644
self.fetch_objects(determine_wants, lossy=lossy)
645
for k, (git_sha, bzr_revid) in viewitems(ref_changes):
646
self.target._git.refs[k] = git_sha
647
new_refs = self.target.controldir.get_refs_container()
648
return None, old_refs, new_refs
650
def fetch_objects(self, determine_wants, mapping=None, limit=None,
652
raise NotImplementedError(self.fetch_objects)
654
def _target_has_shas(self, shas):
656
[sha for sha in shas if sha in self.target._git.object_store])
658
def fetch(self, revision_id=None, find_ghosts=False,
659
mapping=None, fetch_spec=None, branches=None, limit=None,
662
mapping = self.source.get_mapping()
663
if revision_id is not None:
665
elif fetch_spec is not None:
666
recipe = fetch_spec.get_recipe()
667
if recipe[0] in ("search", "proxy-search"):
670
raise AssertionError(
671
"Unsupported search result type %s" % recipe[0])
673
if branches is not None:
674
def determine_wants(refs):
676
for name, value in viewitems(refs):
677
if value == ZERO_SHA:
680
if name in branches or (include_tags and is_tag(name)):
683
elif fetch_spec is None and revision_id is None:
684
determine_wants = self.determine_wants_all
686
determine_wants = self.get_determine_wants_revids(
687
args, include_tags=include_tags)
688
wants_recorder = DetermineWantsRecorder(determine_wants)
689
self.fetch_objects(wants_recorder, mapping, limit=limit)
690
return wants_recorder.remote_refs
692
def get_determine_wants_revids(self, revids, include_tags=False):
694
for revid in set(revids):
695
if revid == NULL_REVISION:
697
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
699
return self.get_determine_wants_heads(wants, include_tags=include_tags)
701
def determine_wants_all(self, refs):
703
v for k, v in refs.items()
704
if not v == ZERO_SHA and not k.endswith(ANNOTATED_TAG_SUFFIX)])
705
return list(potential - self._target_has_shas(potential))
708
class InterLocalGitLocalGitRepository(InterGitGitRepository):
710
def fetch_objects(self, determine_wants, mapping=None, limit=None,
713
raise LossyPushToSameVCS(self.source, self.target)
714
if limit is not None:
715
raise FetchLimitUnsupported(self)
716
from .remote import DefaultProgressReporter
717
with ui.ui_factory.nested_progress_bar() as pb:
718
progress = DefaultProgressReporter(pb).progress
719
refs = self.source._git.fetch(
720
self.target._git, determine_wants,
722
return (None, None, refs)
725
def is_compatible(source, target):
726
"""Be compatible with GitRepository."""
727
return (isinstance(source, LocalGitRepository) and
728
isinstance(target, LocalGitRepository))
731
class InterRemoteGitLocalGitRepository(InterGitGitRepository):
733
def fetch_objects(self, determine_wants, mapping=None, limit=None,
736
raise LossyPushToSameVCS(self.source, self.target)
737
if limit is not None:
738
raise FetchLimitUnsupported(self)
739
graphwalker = self.target._git.get_graph_walker()
740
if (CAPABILITY_THIN_PACK in
741
self.source.controldir._client._fetch_capabilities):
742
# TODO(jelmer): Avoid reading entire file into memory and
743
# only processing it after the whole file has been fetched.
749
self.target._git.object_store.move_in_thin_pack(f)
754
f, commit, abort = self.target._git.object_store.add_pack()
756
refs = self.source.controldir.fetch_pack(
757
determine_wants, graphwalker, f.write)
759
return (None, None, refs)
760
except BaseException:
765
def is_compatible(source, target):
766
"""Be compatible with GitRepository."""
767
return (isinstance(source, RemoteGitRepository) and
768
isinstance(target, LocalGitRepository))