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, if_present_ids=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)
147
walker = Walker(self.source_store,
148
include=git_shas, exclude=[
149
sha for sha in self.target.controldir.get_refs_container().as_dict().values()
151
missing_revids = set()
153
for (kind, type_data) in self.source_store.lookup_git_sha(entry.commit.id):
155
missing_revids.add(type_data[0])
156
return self.source.revision_ids_to_search_result(missing_revids)
158
def _warn_slow(self):
159
if not config.GlobalConfig().suppress_warning('slow_intervcs_push'):
161
'Pushing from a Bazaar to a Git repository. '
162
'For better performance, push into a Bazaar repository.')
165
class InterToLocalGitRepository(InterToGitRepository):
166
"""InterBranch implementation between a Bazaar and a Git repository."""
168
def __init__(self, source, target):
169
super(InterToLocalGitRepository, self).__init__(source, target)
170
self.target_store = self.target.controldir._git.object_store
171
self.target_refs = self.target.controldir._git.refs
173
def _commit_needs_fetching(self, sha_id):
175
return (sha_id not in self.target_store)
176
except NoSuchRevision:
180
def _revision_needs_fetching(self, sha_id, revid):
181
if revid == NULL_REVISION:
185
sha_id = self.source_store._lookup_revision_sha1(revid)
188
return self._commit_needs_fetching(sha_id)
190
def missing_revisions(self, stop_revisions):
191
"""Find the revisions that are missing from the target repository.
193
:param stop_revisions: Revisions to check for (tuples with
195
:return: sequence of missing revisions, in topological order
196
:raise: NoSuchRevision if the stop_revisions are not present in
201
for (sha1, revid) in stop_revisions:
202
if sha1 is not None and revid is not None:
203
revid_sha_map[revid] = sha1
204
stop_revids.append(revid)
205
elif sha1 is not None:
206
if self._commit_needs_fetching(sha1):
207
for (kind, (revid, tree_sha, verifiers)) in self.source_store.lookup_git_sha(sha1):
208
revid_sha_map[revid] = sha1
209
stop_revids.append(revid)
213
stop_revids.append(revid)
215
graph = self.source.get_graph()
216
pb = ui.ui_factory.nested_progress_bar()
220
for revid in stop_revids:
221
sha1 = revid_sha_map.get(revid)
222
if (not revid in missing and
223
self._revision_needs_fetching(sha1, revid)):
225
new_stop_revids.append(revid)
227
parent_map = graph.get_parent_map(new_stop_revids)
228
for parent_revids in viewvalues(parent_map):
229
stop_revids.update(parent_revids)
230
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.
243
for k in self.target._git.refs.allkeys():
245
v = self.target._git.refs.read_ref(k)
250
if not v.startswith(SYMREF):
252
for (kind, type_data) in self.source_store.lookup_git_sha(v):
253
if kind == "commit" and self.source.has_revision(type_data[0]):
258
bzr_refs[k] = (v, revid)
261
def fetch_refs(self, update_refs, lossy, overwrite=False):
263
with self.source_store.lock_read():
264
old_refs = self._get_target_bzr_refs()
265
new_refs = update_refs(old_refs)
266
revidmap = self.fetch_objects(
267
[(git_sha, bzr_revid) for (git_sha, bzr_revid) in new_refs.values() if git_sha is None or not git_sha.startswith(SYMREF)], lossy=lossy)
268
for name, (gitid, revid) in viewitems(new_refs):
271
gitid = revidmap[revid][0]
273
gitid = self.source_store._lookup_revision_sha1(revid)
274
if gitid.startswith(SYMREF):
275
self.target_refs.set_symbolic_ref(
276
name, gitid[len(SYMREF):])
279
old_git_id = old_refs[name][0]
281
self.target_refs.add_if_new(name, gitid)
283
self.target_refs.set_if_equals(name, old_git_id, gitid)
284
return revidmap, old_refs, new_refs
286
def fetch_objects(self, revs, lossy, limit=None):
287
if not lossy and not self.mapping.roundtripping:
288
for git_sha, bzr_revid in revs:
289
if bzr_revid is not None and needs_roundtripping(self.source, bzr_revid):
290
raise NoPushSupport(self.source, self.target, self.mapping,
292
with self.source_store.lock_read():
293
todo = list(self.missing_revisions(revs))[:limit]
295
pb = ui.ui_factory.nested_progress_bar()
297
object_generator = MissingObjectsIterator(
298
self.source_store, self.source, pb)
299
for (old_revid, git_sha) in object_generator.import_revisions(
302
new_revid = self.mapping.revision_id_foreign_to_bzr(
305
new_revid = old_revid
307
self.mapping.revision_id_bzr_to_foreign(old_revid)
308
except InvalidRevisionId:
309
refname = self.mapping.revid_as_refname(old_revid)
310
self.target_refs[refname] = git_sha
311
revidmap[old_revid] = (git_sha, new_revid)
312
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):
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
self.fetch_objects(stop_revisions, lossy=False)
336
except NoPushSupport:
337
raise NoRoundtrippingSupport(self.source, self.target)
340
def is_compatible(source, target):
341
"""Be compatible with GitRepository."""
342
return (not isinstance(source, GitRepository) and
343
isinstance(target, LocalGitRepository))
346
class InterToRemoteGitRepository(InterToGitRepository):
348
def fetch_refs(self, update_refs, lossy, overwrite=False):
349
"""Import the gist of the ancestry of a particular revision."""
350
if not lossy and not self.mapping.roundtripping:
351
raise NoPushSupport(self.source, self.target, self.mapping)
352
unpeel_map = UnpeelMap.from_repository(self.source)
355
def git_update_refs(old_refs):
357
self.old_refs = dict([(k, (v, None))
358
for (k, v) in viewitems(old_refs)])
359
self.new_refs = update_refs(self.old_refs)
360
for name, (gitid, revid) in viewitems(self.new_refs):
362
git_sha = self.source_store._lookup_revision_sha1(revid)
363
gitid = unpeel_map.re_unpeel_tag(
364
git_sha, old_refs.get(name))
366
if remote_divergence(old_refs.get(name), gitid, self.source_store):
367
raise DivergedBranches(self.source, self.target)
371
with self.source_store.lock_read():
372
new_refs = self.target.send_pack(git_update_refs,
373
self.source_store.generate_lossy_pack_data)
375
return revidmap, self.old_refs, self.new_refs
378
def is_compatible(source, target):
379
"""Be compatible with GitRepository."""
380
return (not isinstance(source, GitRepository) and
381
isinstance(target, RemoteGitRepository))
384
class GitSearchResult(object):
386
def __init__(self, start, exclude, keys):
388
self._exclude = exclude
394
def get_recipe(self):
395
return ('search', self._start, self._exclude, len(self._keys))
398
class InterFromGitRepository(InterRepository):
400
_matching_repo_format = GitRepositoryFormat()
402
def _target_has_shas(self, shas):
403
raise NotImplementedError(self._target_has_shas)
405
def get_determine_wants_heads(self, wants, include_tags=False):
408
def determine_wants(refs):
409
potential = set(wants)
411
for k, unpeeled in viewitems(refs):
412
if k.endswith(ANNOTATED_TAG_SUFFIX):
416
if unpeeled == ZERO_SHA:
418
potential.add(unpeeled)
419
return list(potential - self._target_has_shas(potential))
420
return determine_wants
422
def determine_wants_all(self, refs):
423
raise NotImplementedError(self.determine_wants_all)
426
def _get_repo_format_to_test():
429
def copy_content(self, revision_id=None):
430
"""See InterRepository.copy_content."""
431
self.fetch(revision_id, find_ghosts=False)
433
def search_missing_revision_ids(self,
434
find_ghosts=True, revision_ids=None, if_present_ids=None,
436
if limit is not None:
437
raise FetchLimitUnsupported(self)
438
if revision_ids is None and if_present_ids is None:
439
todo = set(self.source.all_revision_ids())
442
if revision_ids is not None:
443
for revid in revision_ids:
444
if not self.source.has_revision(revid):
445
raise NoSuchRevision(revid, self.source)
446
todo.update(revision_ids)
447
if if_present_ids is not None:
448
todo.update(if_present_ids)
449
result_set = todo.difference(self.target.all_revision_ids())
450
result_parents = set(itertools.chain.from_iterable(viewvalues(
451
self.source.get_graph().get_parent_map(result_set))))
452
included_keys = result_set.intersection(result_parents)
453
start_keys = result_set.difference(included_keys)
454
exclude_keys = result_parents.difference(result_set)
455
return GitSearchResult(start_keys, exclude_keys, result_set)
458
class InterGitNonGitRepository(InterFromGitRepository):
459
"""Base InterRepository that copies revisions from a Git into a non-Git
462
def _target_has_shas(self, shas):
466
revid = self.source.lookup_foreign_revision_id(sha)
467
except NotCommitError:
468
# Commit is definitely not present
472
return set([revids[r] for r in self.target.has_revisions(revids)])
474
def determine_wants_all(self, refs):
476
for k, v in viewitems(refs):
477
# For non-git target repositories, only worry about peeled
480
potential.add(self.source.controldir.get_peeled(k) or v)
481
return list(potential - self._target_has_shas(potential))
483
def get_determine_wants_heads(self, wants, include_tags=False):
486
def determine_wants(refs):
487
potential = set(wants)
489
for k, unpeeled in viewitems(refs):
492
if unpeeled == ZERO_SHA:
495
self.source.controldir.get_peeled(k) or unpeeled)
496
return list(potential - self._target_has_shas(potential))
497
return determine_wants
499
def _warn_slow(self):
500
if not config.GlobalConfig().suppress_warning('slow_intervcs_push'):
502
'Fetching from Git to Bazaar repository. '
503
'For better performance, fetch into a Git repository.')
505
def fetch_objects(self, determine_wants, mapping, limit=None, lossy=False):
506
"""Fetch objects from a remote server.
508
:param determine_wants: determine_wants callback
509
:param mapping: BzrGitMapping to use
510
:param limit: Maximum number of commits to import.
511
:return: Tuple with pack hint, last imported revision id and remote refs
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(self.target,
584
mapping, objects_iter, store, wants_recorder.wants, pb,
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)
614
pb = ui.ui_factory.nested_progress_bar()
615
target_git_object_retriever = get_object_store(self.target, mapping)
617
target_git_object_retriever.lock_write()
619
(pack_hint, last_rev) = import_git_objects(self.target,
620
mapping, self.source._git.object_store,
621
target_git_object_retriever, wants, pb, limit)
622
return (pack_hint, last_rev, remote_refs)
624
target_git_object_retriever.unlock()
629
def is_compatible(source, target):
630
"""Be compatible with GitRepository."""
631
if not isinstance(source, LocalGitRepository):
633
if not target.supports_rich_root():
635
if isinstance(target, GitRepository):
637
if not getattr(target._format, "supports_full_versioned_files", True):
642
class InterGitGitRepository(InterFromGitRepository):
643
"""InterRepository that copies between Git repositories."""
645
def fetch_refs(self, update_refs, lossy, overwrite=False):
647
raise LossyPushToSameVCS(self.source, self.target)
648
old_refs = self.target.controldir.get_refs_container()
651
def determine_wants(heads):
652
old_refs = dict([(k, (v, None))
653
for (k, v) in viewitems(heads.as_dict())])
654
new_refs = update_refs(old_refs)
655
ref_changes.update(new_refs)
656
return [sha1 for (sha1, bzr_revid) in viewvalues(new_refs)]
657
self.fetch_objects(determine_wants, lossy=lossy)
658
for k, (git_sha, bzr_revid) in viewitems(ref_changes):
659
self.target._git.refs[k] = git_sha
660
new_refs = self.target.controldir.get_refs_container()
661
return None, old_refs, new_refs
663
def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
664
raise NotImplementedError(self.fetch_objects)
666
def _target_has_shas(self, shas):
667
return set([sha for sha in shas if sha in self.target._git.object_store])
669
def fetch(self, revision_id=None, find_ghosts=False,
670
mapping=None, fetch_spec=None, branches=None, limit=None, include_tags=False):
672
mapping = self.source.get_mapping()
673
if revision_id is not None:
675
elif fetch_spec is not None:
676
recipe = fetch_spec.get_recipe()
677
if recipe[0] in ("search", "proxy-search"):
680
raise AssertionError(
681
"Unsupported search result type %s" % recipe[0])
683
if branches is not None:
684
def determine_wants(refs):
686
for name, value in viewitems(refs):
687
if value == ZERO_SHA:
690
if name in branches or (include_tags and is_tag(name)):
693
elif fetch_spec is None and revision_id is None:
694
determine_wants = self.determine_wants_all
696
determine_wants = self.get_determine_wants_revids(
697
args, include_tags=include_tags)
698
wants_recorder = DetermineWantsRecorder(determine_wants)
699
self.fetch_objects(wants_recorder, mapping, limit=limit)
700
return wants_recorder.remote_refs
702
def get_determine_wants_revids(self, revids, include_tags=False):
704
for revid in set(revids):
705
if revid == NULL_REVISION:
707
git_sha, mapping = self.source.lookup_bzr_revision_id(revid)
709
return self.get_determine_wants_heads(wants, include_tags=include_tags)
711
def determine_wants_all(self, refs):
713
v for k, v in refs.items()
714
if not v == ZERO_SHA and not k.endswith(ANNOTATED_TAG_SUFFIX)])
715
return list(potential - self._target_has_shas(potential))
718
class InterLocalGitLocalGitRepository(InterGitGitRepository):
720
def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
722
raise LossyPushToSameVCS(self.source, self.target)
723
if limit is not None:
724
raise FetchLimitUnsupported(self)
725
from .remote import DefaultProgressReporter
726
pb = ui.ui_factory.nested_progress_bar()
727
progress = DefaultProgressReporter(pb).progress
729
refs = self.source._git.fetch(
730
self.target._git, determine_wants,
734
return (None, None, refs)
737
def is_compatible(source, target):
738
"""Be compatible with GitRepository."""
739
return (isinstance(source, LocalGitRepository) and
740
isinstance(target, LocalGitRepository))
743
class InterRemoteGitLocalGitRepository(InterGitGitRepository):
745
def fetch_objects(self, determine_wants, mapping=None, limit=None, lossy=False):
747
raise LossyPushToSameVCS(self.source, self.target)
748
if limit is not None:
749
raise FetchLimitUnsupported(self)
750
graphwalker = self.target._git.get_graph_walker()
751
if CAPABILITY_THIN_PACK in self.source.controldir._client._fetch_capabilities:
752
# TODO(jelmer): Avoid reading entire file into memory and
753
# only processing it after the whole file has been fetched.
759
self.target._git.object_store.move_in_thin_pack(f)
764
f, commit, abort = self.target._git.object_store.add_pack()
766
refs = self.source.controldir.fetch_pack(
767
determine_wants, graphwalker, f.write)
769
return (None, None, refs)
770
except BaseException:
775
def is_compatible(source, target):
776
"""Be compatible with GitRepository."""
777
return (isinstance(source, RemoteGitRepository) and
778
isinstance(target, LocalGitRepository))