1
# Copyright (C) 2007,2012 Canonical Ltd
2
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
"""An adapter between a Git Branch and a Bazaar Branch"""
22
from io import BytesIO
23
from collections import defaultdict
25
from dulwich.config import (
26
ConfigFile as GitConfigFile,
30
from dulwich.objects import (
34
from dulwich.repo import check_ref_format
42
repository as _mod_repository,
49
from ..foreign import ForeignBranch
50
from ..revision import (
74
remote_refs_dict_to_tag_refs,
77
from .unpeel_map import (
86
def _calculate_revnos(branch):
87
if branch._format.stores_revno():
89
config = branch.get_config_stack()
90
return config.get('calculate_revnos')
93
class GitPullResult(branch.PullResult):
94
"""Result of a pull from a Git branch."""
96
def _lookup_revno(self, revid):
97
if not isinstance(revid, bytes):
98
raise TypeError(revid)
99
if not _calculate_revnos(self.target_branch):
101
# Try in source branch first, it'll be faster
102
with self.target_branch.lock_read():
103
return self.target_branch.revision_id_to_revno(revid)
107
return self._lookup_revno(self.old_revid)
111
return self._lookup_revno(self.new_revid)
114
class GitTags(tag.BasicTags):
115
"""Ref-based tag dictionary."""
117
def __init__(self, branch):
119
self.repository = branch.repository
121
def _merge_to_remote_git(self, target_repo, source_tag_refs,
126
def get_changed_refs(old_refs):
128
for ref_name, tag_name, peeled, unpeeled in (
129
source_tag_refs.iteritems()):
130
if old_refs.get(ref_name) == unpeeled:
132
elif overwrite or ref_name not in old_refs:
133
ret[ref_name] = unpeeled
134
updates[tag_name] = target_repo.lookup_foreign_revision_id(
139
self.repository.lookup_foreign_revision_id(peeled),
140
target_repo.lookup_foreign_revision_id(
141
old_refs[ref_name])))
143
target_repo.controldir.send_pack(
144
get_changed_refs, lambda have, want: [])
145
return updates, conflicts
147
def _merge_to_local_git(self, target_repo, source_tag_refs,
151
for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
152
if target_repo._git.refs.get(ref_name) == unpeeled:
154
elif overwrite or ref_name not in target_repo._git.refs:
156
updates[tag_name] = (
157
target_repo.lookup_foreign_revision_id(peeled))
159
trace.warning('%s does not point to a valid object',
162
except NotCommitError:
163
trace.warning('%s points to a non-commit object',
166
target_repo._git.refs[ref_name] = unpeeled or peeled
169
source_revid = self.repository.lookup_foreign_revision_id(
171
target_revid = target_repo.lookup_foreign_revision_id(
172
target_repo._git.refs[ref_name])
174
trace.warning('%s does not point to a valid object',
177
except NotCommitError:
178
trace.warning('%s points to a non-commit object',
181
conflicts.append((tag_name, source_revid, target_revid))
182
return updates, conflicts
184
def _merge_to_git(self, to_tags, source_tag_refs, overwrite=False):
185
target_repo = to_tags.repository
186
if self.repository.has_same_location(target_repo):
189
if getattr(target_repo, "_git", None):
190
return self._merge_to_local_git(
191
target_repo, source_tag_refs, overwrite)
193
return self._merge_to_remote_git(
194
target_repo, source_tag_refs, overwrite)
196
to_tags.branch._tag_refs = None
198
def _merge_to_non_git(self, to_tags, source_tag_refs, overwrite=False):
199
unpeeled_map = defaultdict(set)
202
result = dict(to_tags.get_tag_dict())
203
for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
204
if unpeeled is not None:
205
unpeeled_map[peeled].add(unpeeled)
207
bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
208
except NotCommitError:
210
if result.get(tag_name) == bzr_revid:
212
elif tag_name not in result or overwrite:
213
result[tag_name] = bzr_revid
214
updates[tag_name] = bzr_revid
216
conflicts.append((tag_name, bzr_revid, result[tag_name]))
217
to_tags._set_tag_dict(result)
218
if len(unpeeled_map) > 0:
219
map_file = UnpeelMap.from_repository(to_tags.branch.repository)
220
map_file.update(unpeeled_map)
221
map_file.save_in_repository(to_tags.branch.repository)
222
return updates, conflicts
224
def merge_to(self, to_tags, overwrite=False, ignore_master=False,
225
source_tag_refs=None):
226
"""See Tags.merge_to."""
227
if source_tag_refs is None:
228
source_tag_refs = self.branch.get_tag_refs()
231
if isinstance(to_tags, GitTags):
232
return self._merge_to_git(to_tags, source_tag_refs,
238
master = to_tags.branch.get_master_branch()
239
with contextlib.ExitStack() as es:
240
if master is not None:
241
es.enter_context(master.lock_write())
242
updates, conflicts = self._merge_to_non_git(
243
to_tags, source_tag_refs, overwrite=overwrite)
244
if master is not None:
245
extra_updates, extra_conflicts = self.merge_to(
246
master.tags, overwrite=overwrite,
247
source_tag_refs=source_tag_refs,
248
ignore_master=ignore_master)
249
updates.update(extra_updates)
250
conflicts += extra_conflicts
251
return updates, conflicts
253
def get_tag_dict(self):
255
for (ref_name, tag_name, peeled, unpeeled) in (
256
self.branch.get_tag_refs()):
258
bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
259
except NotCommitError:
262
ret[tag_name] = bzr_revid
266
class LocalGitTagDict(GitTags):
267
"""Dictionary with tags in a local repository."""
269
def __init__(self, branch):
270
super(LocalGitTagDict, self).__init__(branch)
271
self.refs = self.repository.controldir._git.refs
273
def _set_tag_dict(self, to_dict):
274
extra = set(self.refs.allkeys())
275
for k, revid in to_dict.items():
276
name = tag_name_to_ref(k)
280
self.set_tag(k, revid)
281
except errors.GhostTagsNotSupported:
285
del self.repository._git[name]
287
def set_tag(self, name, revid):
289
git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
290
except errors.NoSuchRevision:
291
raise errors.GhostTagsNotSupported(self)
292
self.refs[tag_name_to_ref(name)] = git_sha
293
self.branch._tag_refs = None
295
def delete_tag(self, name):
296
ref = tag_name_to_ref(name)
297
if ref not in self.refs:
298
raise errors.NoSuchTag(name)
300
self.branch._tag_refs = None
303
class GitBranchFormat(branch.BranchFormat):
305
def network_name(self):
308
def supports_tags(self):
311
def supports_leaving_lock(self):
314
def supports_tags_referencing_ghosts(self):
317
def tags_are_versioned(self):
320
def get_foreign_tests_branch_factory(self):
321
from .tests.test_branch import ForeignTestsBranchFactory
322
return ForeignTestsBranchFactory()
324
def make_tags(self, branch):
327
except AttributeError:
329
if getattr(branch.repository, "_git", None) is None:
330
from .remote import RemoteGitTagDict
331
return RemoteGitTagDict(branch)
333
return LocalGitTagDict(branch)
335
def initialize(self, a_controldir, name=None, repository=None,
336
append_revisions_only=None):
337
raise NotImplementedError(self.initialize)
339
def get_reference(self, controldir, name=None):
340
return controldir.get_branch_reference(name=name)
342
def set_reference(self, controldir, name, target):
343
return controldir.set_branch_reference(target, name)
345
def stores_revno(self):
346
"""True if this branch format store revision numbers."""
349
supports_reference_locations = False
352
class LocalGitBranchFormat(GitBranchFormat):
354
def get_format_description(self):
355
return 'Local Git Branch'
358
def _matchingcontroldir(self):
359
from .dir import LocalGitControlDirFormat
360
return LocalGitControlDirFormat()
362
def initialize(self, a_controldir, name=None, repository=None,
363
append_revisions_only=None):
364
from .dir import LocalGitDir
365
if not isinstance(a_controldir, LocalGitDir):
366
raise errors.IncompatibleFormat(self, a_controldir._format)
367
return a_controldir.create_branch(
368
repository=repository, name=name,
369
append_revisions_only=append_revisions_only)
372
class GitBranch(ForeignBranch):
373
"""An adapter to git repositories for bzr Branch objects."""
376
def control_transport(self):
377
return self._control_transport
380
def user_transport(self):
381
return self._user_transport
383
def __init__(self, controldir, repository, ref, format):
384
self.repository = repository
385
self._format = format
386
self.controldir = controldir
387
self._lock_mode = None
389
super(GitBranch, self).__init__(repository.get_mapping())
392
self._user_transport = controldir.user_transport.clone('.')
393
self._control_transport = controldir.control_transport.clone('.')
394
self._tag_refs = None
397
self.name = ref_to_branch_name(ref)
400
if self.ref is not None:
401
params = {"ref": urlutils.escape(self.ref)}
404
params = {"branch": urlutils.escape(self.name)}
405
for k, v in params.items():
406
self._user_transport.set_segment_parameter(k, v)
407
self._control_transport.set_segment_parameter(k, v)
408
self.base = controldir.user_transport.base
410
def _get_checkout_format(self, lightweight=False):
411
"""Return the most suitable metadir for a checkout of this branch.
412
Weaves are used if this branch's repository uses weaves.
415
return controldir.format_registry.make_controldir("git")
417
return controldir.format_registry.make_controldir("default")
419
def get_child_submit_format(self):
420
"""Return the preferred format of submissions to this branch."""
421
ret = self.get_config_stack().get("child_submit_format")
426
def get_config(self):
427
return GitBranchConfig(self)
429
def get_config_stack(self):
430
return GitBranchStack(self)
432
def _get_nick(self, local=False, possible_master_transports=None):
433
"""Find the nick name for this branch.
437
if getattr(self.repository, '_git', None):
438
cs = self.repository._git.get_config_stack()
440
return cs.get((b"branch", self.name.encode('utf-8')),
441
b"nick").decode("utf-8")
444
return self.name or u"HEAD"
446
def _set_nick(self, nick):
447
cf = self.repository._git.get_config()
448
cf.set((b"branch", self.name.encode('utf-8')),
449
b"nick", nick.encode("utf-8"))
452
self.repository._git._put_named_file('config', f.getvalue())
454
nick = property(_get_nick, _set_nick)
457
return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
460
def generate_revision_history(self, revid, last_rev=None,
462
if last_rev is not None:
463
graph = self.repository.get_graph()
464
if not graph.is_ancestor(last_rev, revid):
465
# our previous tip is not merged into stop_revision
466
raise errors.DivergedBranches(self, other_branch)
468
self.set_last_revision(revid)
470
def lock_write(self, token=None):
471
if token is not None:
472
raise errors.TokenLockingNotSupported(self)
474
if self._lock_mode == 'r':
475
raise errors.ReadOnlyError(self)
476
self._lock_count += 1
479
self._lock_mode = 'w'
481
self.repository.lock_write()
482
return lock.LogicalLockResult(self.unlock)
484
def leave_lock_in_place(self):
485
raise NotImplementedError(self.leave_lock_in_place)
487
def dont_leave_lock_in_place(self):
488
raise NotImplementedError(self.dont_leave_lock_in_place)
490
def get_stacked_on_url(self):
491
# Git doesn't do stacking (yet...)
492
raise branch.UnstackableBranchFormat(self._format, self.base)
494
def _get_push_origin(self, cs):
495
"""Get the name for the push origin.
497
The exact behaviour is documented in the git-config(1) manpage.
500
return cs.get((b'branch', self.name.encode('utf-8')), b'pushRemote')
503
return cs.get((b'branch', ), b'remote')
506
return cs.get((b'branch', self.name.encode('utf-8')), b'remote')
510
def _get_origin(self, cs):
512
return cs.get((b'branch', self.name.encode('utf-8')), b'remote')
516
def _get_related_push_branch(self, cs):
517
remote = self._get_push_origin(cs)
519
location = cs.get((b"remote", remote), b"url")
523
return git_url_to_bzr_url(location.decode('utf-8'), ref=self.ref)
525
def _get_related_merge_branch(self, cs):
526
remote = self._get_origin(cs)
528
location = cs.get((b"remote", remote), b"url")
533
ref = cs.get((b"branch", remote), b"merge")
537
return git_url_to_bzr_url(location.decode('utf-8'), ref=ref)
539
def _get_parent_location(self):
540
"""See Branch.get_parent()."""
541
cs = self.repository._git.get_config_stack()
542
return self._get_related_merge_branch(cs)
544
def _write_git_config(self, cs):
547
self.repository._git._put_named_file('config', f.getvalue())
549
def set_parent(self, location):
550
cs = self.repository._git.get_config()
551
remote = self._get_origin(cs)
552
this_url = urlutils.strip_segment_parameters(self.user_url)
553
target_url, branch, ref = bzr_url_to_git_url(location)
554
location = urlutils.relative_url(this_url, target_url)
555
cs.set((b"remote", remote), b"url", location)
557
cs.set((b"branch", remote), b"merge", branch_name_to_ref(branch))
559
cs.set((b"branch", remote), b"merge", ref)
561
# TODO(jelmer): Maybe unset rather than setting to HEAD?
562
cs.set((b"branch", remote), b"merge", b'HEAD')
563
self._write_git_config(cs)
565
def break_lock(self):
566
raise NotImplementedError(self.break_lock)
570
if self._lock_mode not in ('r', 'w'):
571
raise ValueError(self._lock_mode)
572
self._lock_count += 1
574
self._lock_mode = 'r'
576
self.repository.lock_read()
577
return lock.LogicalLockResult(self.unlock)
579
def peek_lock_mode(self):
580
return self._lock_mode
583
return (self._lock_mode is not None)
588
def _unlock_ref(self):
592
"""See Branch.unlock()."""
593
if self._lock_count == 0:
594
raise errors.LockNotHeld(self)
596
self._lock_count -= 1
597
if self._lock_count == 0:
598
if self._lock_mode == 'w':
600
self._lock_mode = None
601
self._clear_cached_state()
603
self.repository.unlock()
605
def get_physical_lock_status(self):
608
def last_revision(self):
609
with self.lock_read():
610
# perhaps should escape this ?
611
if self.head is None:
612
return revision.NULL_REVISION
613
return self.lookup_foreign_revision_id(self.head)
615
def _basic_push(self, target, overwrite=False, stop_revision=None):
616
return branch.InterBranch.get(self, target)._basic_push(
617
overwrite, stop_revision)
619
def lookup_foreign_revision_id(self, foreign_revid):
621
return self.repository.lookup_foreign_revision_id(foreign_revid,
625
return self.mapping.revision_id_foreign_to_bzr(foreign_revid)
627
def lookup_bzr_revision_id(self, revid):
628
return self.repository.lookup_bzr_revision_id(
629
revid, mapping=self.mapping)
631
def get_unshelver(self, tree):
632
raise errors.StoringUncommittedNotSupported(self)
634
def _clear_cached_state(self):
635
super(GitBranch, self)._clear_cached_state()
636
self._tag_refs = None
638
def _iter_tag_refs(self, refs):
639
"""Iterate over the tag refs.
641
:param refs: Refs dictionary (name -> git sha1)
642
:return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
644
raise NotImplementedError(self._iter_tag_refs)
646
def get_tag_refs(self):
647
with self.lock_read():
648
if self._tag_refs is None:
649
self._tag_refs = list(self._iter_tag_refs())
650
return self._tag_refs
652
def import_last_revision_info_and_tags(self, source, revno, revid,
654
"""Set the last revision info, importing from another repo if necessary.
656
This is used by the bound branch code to upload a revision to
657
the master branch first before updating the tip of the local branch.
658
Revisions referenced by source's tags are also transferred.
660
:param source: Source branch to optionally fetch from
661
:param revno: Revision number of the new tip
662
:param revid: Revision id of the new tip
663
:param lossy: Whether to discard metadata that can not be
665
:return: Tuple with the new revision number and revision id
666
(should only be different from the arguments when lossy=True)
668
push_result = source.push(
669
self, stop_revision=revid, lossy=lossy, _stop_revno=revno)
670
return (push_result.new_revno, push_result.new_revid)
672
def reconcile(self, thorough=True):
673
"""Make sure the data stored in this branch is consistent."""
674
from ..reconcile import ReconcileResult
676
return ReconcileResult()
679
class LocalGitBranch(GitBranch):
680
"""A local Git branch."""
682
def __init__(self, controldir, repository, ref):
683
super(LocalGitBranch, self).__init__(controldir, repository, ref,
684
LocalGitBranchFormat())
686
def create_checkout(self, to_location, revision_id=None, lightweight=False,
687
accelerator_tree=None, hardlink=False):
688
t = transport.get_transport(to_location)
690
format = self._get_checkout_format(lightweight=lightweight)
691
checkout = format.initialize_on_transport(t)
693
from_branch = checkout.set_branch_reference(target_branch=self)
695
policy = checkout.determine_repository_policy()
696
policy.acquire_repository()
697
checkout_branch = checkout.create_branch()
698
checkout_branch.bind(self)
699
checkout_branch.pull(self, stop_revision=revision_id)
701
return checkout.create_workingtree(
702
revision_id, from_branch=from_branch, hardlink=hardlink)
705
self._ref_lock = self.repository._git.refs.lock_ref(self.ref)
707
def _unlock_ref(self):
708
self._ref_lock.unlock()
710
def break_lock(self):
711
self.repository._git.refs.unlock_ref(self.ref)
713
def _gen_revision_history(self):
714
if self.head is None:
716
last_revid = self.last_revision()
717
graph = self.repository.get_graph()
719
ret = list(graph.iter_lefthand_ancestry(
720
last_revid, (revision.NULL_REVISION, )))
721
except errors.RevisionNotPresent as e:
722
raise errors.GhostRevisionsHaveNoRevno(last_revid, e.revision_id)
728
return self.repository._git.refs[self.ref]
732
def _read_last_revision_info(self):
733
last_revid = self.last_revision()
734
graph = self.repository.get_graph()
736
revno = graph.find_distance_to_null(
737
last_revid, [(revision.NULL_REVISION, 0)])
738
except errors.GhostRevisionsHaveNoRevno:
740
return revno, last_revid
742
def set_last_revision_info(self, revno, revision_id):
743
self.set_last_revision(revision_id)
744
self._last_revision_info_cache = revno, revision_id
746
def set_last_revision(self, revid):
747
if not revid or not isinstance(revid, bytes):
748
raise errors.InvalidRevisionId(revision_id=revid, branch=self)
749
if revid == NULL_REVISION:
752
(newhead, self.mapping) = self.repository.lookup_bzr_revision_id(
754
if self.mapping is None:
756
self._set_head(newhead)
758
def _set_head(self, value):
759
if value == ZERO_SHA:
760
raise ValueError(value)
763
del self.repository._git.refs[self.ref]
765
self.repository._git.refs[self.ref] = self._head
766
self._clear_cached_state()
768
head = property(_get_head, _set_head)
770
def get_push_location(self):
771
"""See Branch.get_push_location."""
772
push_loc = self.get_config_stack().get('push_location')
773
if push_loc is not None:
775
cs = self.repository._git.get_config_stack()
776
return self._get_related_push_branch(cs)
778
def set_push_location(self, location):
779
"""See Branch.set_push_location."""
780
self.get_config().set_user_option('push_location', location,
781
store=config.STORE_LOCATION)
783
def supports_tags(self):
786
def store_uncommitted(self, creator):
787
raise errors.StoringUncommittedNotSupported(self)
789
def _iter_tag_refs(self):
790
"""Iterate over the tag refs.
792
:param refs: Refs dictionary (name -> git sha1)
793
:return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
795
refs = self.repository.controldir.get_refs_container()
796
for ref_name, unpeeled in refs.as_dict().items():
798
tag_name = ref_to_tag_name(ref_name)
799
except (ValueError, UnicodeDecodeError):
801
peeled = refs.get_peeled(ref_name)
804
if not isinstance(tag_name, str):
805
raise TypeError(tag_name)
806
yield (ref_name, tag_name, peeled, unpeeled)
808
def create_memorytree(self):
809
from .memorytree import GitMemoryTree
810
return GitMemoryTree(self, self.repository._git.object_store,
814
def _quick_lookup_revno(local_branch, remote_branch, revid):
815
if not isinstance(revid, bytes):
816
raise TypeError(revid)
817
# Try in source branch first, it'll be faster
818
with local_branch.lock_read():
819
if not _calculate_revnos(local_branch):
822
return local_branch.revision_id_to_revno(revid)
823
except errors.NoSuchRevision:
824
graph = local_branch.repository.get_graph()
826
return graph.find_distance_to_null(
827
revid, [(revision.NULL_REVISION, 0)])
828
except errors.GhostRevisionsHaveNoRevno:
829
if not _calculate_revnos(remote_branch):
831
# FIXME: Check using graph.find_distance_to_null() ?
832
with remote_branch.lock_read():
833
return remote_branch.revision_id_to_revno(revid)
836
class GitBranchPullResult(branch.PullResult):
839
super(GitBranchPullResult, self).__init__()
840
self.new_git_head = None
841
self._old_revno = None
842
self._new_revno = None
844
def report(self, to_file):
846
if self.old_revid == self.new_revid:
847
to_file.write('No revisions to pull.\n')
848
elif self.new_git_head is not None:
849
to_file.write('Now on revision %d (git sha: %s).\n' %
850
(self.new_revno, self.new_git_head))
852
to_file.write('Now on revision %d.\n' % (self.new_revno,))
853
self._show_tag_conficts(to_file)
855
def _lookup_revno(self, revid):
856
return _quick_lookup_revno(self.target_branch, self.source_branch,
859
def _get_old_revno(self):
860
if self._old_revno is not None:
861
return self._old_revno
862
return self._lookup_revno(self.old_revid)
864
def _set_old_revno(self, revno):
865
self._old_revno = revno
867
old_revno = property(_get_old_revno, _set_old_revno)
869
def _get_new_revno(self):
870
if self._new_revno is not None:
871
return self._new_revno
872
return self._lookup_revno(self.new_revid)
874
def _set_new_revno(self, revno):
875
self._new_revno = revno
877
new_revno = property(_get_new_revno, _set_new_revno)
880
class GitBranchPushResult(branch.BranchPushResult):
882
def _lookup_revno(self, revid):
883
return _quick_lookup_revno(self.source_branch, self.target_branch,
888
return self._lookup_revno(self.old_revid)
892
new_original_revno = getattr(self, "new_original_revno", None)
893
if new_original_revno:
894
return new_original_revno
895
if getattr(self, "new_original_revid", None) is not None:
896
return self._lookup_revno(self.new_original_revid)
897
return self._lookup_revno(self.new_revid)
900
class InterFromGitBranch(branch.GenericInterBranch):
901
"""InterBranch implementation that pulls from Git into bzr."""
904
def _get_branch_formats_to_test():
906
default_format = branch.format_registry.get_default()
907
except AttributeError:
908
default_format = branch.BranchFormat._default_format
909
from .remote import RemoteGitBranchFormat
911
(RemoteGitBranchFormat(), default_format),
912
(LocalGitBranchFormat(), default_format)]
915
def _get_interrepo(self, source, target):
916
return _mod_repository.InterRepository.get(
917
source.repository, target.repository)
920
def is_compatible(cls, source, target):
921
if not isinstance(source, GitBranch):
923
if isinstance(target, GitBranch):
924
# InterLocalGitRemoteGitBranch or InterToGitBranch should be used
926
if (getattr(cls._get_interrepo(source, target), "fetch_objects", None)
928
# fetch_objects is necessary for this to work
932
def fetch(self, stop_revision=None, fetch_tags=None, limit=None, lossy=False):
934
stop_revision, fetch_tags=fetch_tags, limit=limit, lossy=lossy)
935
return _mod_repository.FetchResult()
937
def fetch_objects(self, stop_revision, fetch_tags, limit=None, lossy=False):
938
interrepo = self._get_interrepo(self.source, self.target)
939
if fetch_tags is None:
940
c = self.source.get_config_stack()
941
fetch_tags = c.get('branch.fetch_tags')
943
def determine_wants(heads):
944
if stop_revision is None:
946
head = heads[self.source.ref]
948
self._last_revid = revision.NULL_REVISION
950
self._last_revid = self.source.lookup_foreign_revision_id(
953
self._last_revid = stop_revision
954
real = interrepo.get_determine_wants_revids(
955
[self._last_revid], include_tags=fetch_tags)
957
pack_hint, head, refs = interrepo.fetch_objects(
958
determine_wants, self.source.mapping, limit=limit,
960
if (pack_hint is not None and
961
self.target.repository._format.pack_compresses):
962
self.target.repository.pack(hint=pack_hint)
965
def _update_revisions(self, stop_revision=None, overwrite=False):
966
head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
968
prev_last_revid = None
970
prev_last_revid = self.target.last_revision()
971
self.target.generate_revision_history(
972
self._last_revid, last_rev=prev_last_revid,
973
other_branch=self.source)
976
def update_references(self, revid=None):
978
revid = self.target.last_revision()
979
tree = self.target.repository.revision_tree(revid)
981
with tree.get_file('.gitmodules') as f:
982
for path, url, section in parse_submodules(
983
GitConfigFile.from_file(f)):
984
self.target.set_reference_info(
985
tree.path2id(path.decode('utf-8')), url.decode('utf-8'),
986
path.decode('utf-8'))
987
except errors.NoSuchFile:
990
def _basic_pull(self, stop_revision, overwrite, run_hooks,
991
_override_hook_target, _hook_master):
992
if overwrite is True:
993
overwrite = set(["history", "tags"])
996
result = GitBranchPullResult()
997
result.source_branch = self.source
998
if _override_hook_target is None:
999
result.target_branch = self.target
1001
result.target_branch = _override_hook_target
1002
with self.target.lock_write(), self.source.lock_read():
1003
# We assume that during 'pull' the target repository is closer than
1005
(result.old_revno, result.old_revid) = \
1006
self.target.last_revision_info()
1007
result.new_git_head, remote_refs = self._update_revisions(
1008
stop_revision, overwrite=("history" in overwrite))
1009
tags_ret = self.source.tags.merge_to(
1010
self.target.tags, ("tags" in overwrite), ignore_master=True)
1011
if isinstance(tags_ret, tuple):
1012
result.tag_updates, result.tag_conflicts = tags_ret
1014
result.tag_conflicts = tags_ret
1015
(result.new_revno, result.new_revid) = \
1016
self.target.last_revision_info()
1017
self.update_references(revid=result.new_revid)
1019
result.master_branch = _hook_master
1020
result.local_branch = result.target_branch
1022
result.master_branch = result.target_branch
1023
result.local_branch = None
1025
for hook in branch.Branch.hooks['post_pull']:
1029
def pull(self, overwrite=False, stop_revision=None,
1030
possible_transports=None, _hook_master=None, run_hooks=True,
1031
_override_hook_target=None, local=False):
1034
:param _hook_master: Private parameter - set the branch to
1035
be supplied as the master to pull hooks.
1036
:param run_hooks: Private parameter - if false, this branch
1037
is being called because it's the master of the primary branch,
1038
so it should not run its hooks.
1039
:param _override_hook_target: Private parameter - set the branch to be
1040
supplied as the target_branch to pull hooks.
1042
# This type of branch can't be bound.
1043
bound_location = self.target.get_bound_location()
1044
if local and not bound_location:
1045
raise errors.LocalRequiresBoundBranch()
1046
source_is_master = False
1047
with contextlib.ExitStack() as es:
1048
es.enter_context(self.source.lock_read())
1050
# bound_location comes from a config file, some care has to be
1051
# taken to relate it to source.user_url
1052
normalized = urlutils.normalize_url(bound_location)
1054
relpath = self.source.user_transport.relpath(normalized)
1055
source_is_master = (relpath == '')
1056
except (errors.PathNotChild, urlutils.InvalidURL):
1057
source_is_master = False
1058
if not local and bound_location and not source_is_master:
1059
# not pulling from master, so we need to update master.
1060
master_branch = self.target.get_master_branch(possible_transports)
1061
es.enter_context(master_branch.lock_write())
1062
# pull from source into master.
1063
master_branch.pull(self.source, overwrite, stop_revision,
1066
master_branch = None
1067
return self._basic_pull(stop_revision, overwrite, run_hooks,
1068
_override_hook_target,
1069
_hook_master=master_branch)
1071
def _basic_push(self, overwrite, stop_revision):
1072
if overwrite is True:
1073
overwrite = set(["history", "tags"])
1076
result = branch.BranchPushResult()
1077
result.source_branch = self.source
1078
result.target_branch = self.target
1079
result.old_revno, result.old_revid = self.target.last_revision_info()
1080
result.new_git_head, remote_refs = self._update_revisions(
1081
stop_revision, overwrite=("history" in overwrite))
1082
tags_ret = self.source.tags.merge_to(
1083
self.target.tags, "tags" in overwrite, ignore_master=True)
1084
(result.tag_updates, result.tag_conflicts) = tags_ret
1085
result.new_revno, result.new_revid = self.target.last_revision_info()
1086
self.update_references(revid=result.new_revid)
1090
class InterGitBranch(branch.GenericInterBranch):
1091
"""InterBranch implementation that pulls between Git branches."""
1093
def fetch(self, stop_revision=None, fetch_tags=None, limit=None, lossy=False):
1094
raise NotImplementedError(self.fetch)
1097
class InterLocalGitRemoteGitBranch(InterGitBranch):
1098
"""InterBranch that copies from a local to a remote git branch."""
1101
def _get_branch_formats_to_test():
1102
from .remote import RemoteGitBranchFormat
1104
(LocalGitBranchFormat(), RemoteGitBranchFormat())]
1107
def is_compatible(self, source, target):
1108
from .remote import RemoteGitBranch
1109
return (isinstance(source, LocalGitBranch) and
1110
isinstance(target, RemoteGitBranch))
1112
def _basic_push(self, overwrite, stop_revision):
1113
result = GitBranchPushResult()
1114
result.source_branch = self.source
1115
result.target_branch = self.target
1116
if stop_revision is None:
1117
stop_revision = self.source.last_revision()
1119
def get_changed_refs(old_refs):
1120
old_ref = old_refs.get(self.target.ref, None)
1122
result.old_revid = revision.NULL_REVISION
1124
result.old_revid = self.target.lookup_foreign_revision_id(
1126
new_ref = self.source.repository.lookup_bzr_revision_id(
1129
if remote_divergence(
1131
self.source.repository._git.object_store):
1132
raise errors.DivergedBranches(self.source, self.target)
1133
refs = {self.target.ref: new_ref}
1134
result.new_revid = stop_revision
1136
self.source.repository._git.refs.as_dict(b"refs/tags").items()):
1137
if sha not in self.source.repository._git:
1138
trace.mutter('Ignoring missing SHA: %s', sha)
1140
refs[tag_name_to_ref(name)] = sha
1142
self.target.repository.send_pack(
1144
self.source.repository._git.object_store.generate_pack_data)
1148
class InterGitLocalGitBranch(InterGitBranch):
1149
"""InterBranch that copies from a remote to a local git branch."""
1152
def _get_branch_formats_to_test():
1153
from .remote import RemoteGitBranchFormat
1155
(RemoteGitBranchFormat(), LocalGitBranchFormat()),
1156
(LocalGitBranchFormat(), LocalGitBranchFormat())]
1159
def is_compatible(self, source, target):
1160
return (isinstance(source, GitBranch) and
1161
isinstance(target, LocalGitBranch))
1163
def fetch(self, stop_revision=None, fetch_tags=None, limit=None, lossy=False):
1164
interrepo = _mod_repository.InterRepository.get(
1165
self.source.repository, self.target.repository)
1166
if stop_revision is None:
1167
stop_revision = self.source.last_revision()
1168
if fetch_tags is None:
1169
c = self.source.get_config_stack()
1170
fetch_tags = c.get('branch.fetch_tags')
1171
determine_wants = interrepo.get_determine_wants_revids(
1172
[stop_revision], include_tags=fetch_tags)
1173
interrepo.fetch_objects(determine_wants, limit=limit, lossy=lossy)
1174
return _mod_repository.FetchResult()
1176
def _basic_push(self, overwrite=False, stop_revision=None):
1177
if overwrite is True:
1178
overwrite = set(["history", "tags"])
1181
result = GitBranchPushResult()
1182
result.source_branch = self.source
1183
result.target_branch = self.target
1184
result.old_revid = self.target.last_revision()
1185
refs, stop_revision = self.update_refs(stop_revision)
1186
self.target.generate_revision_history(
1188
(result.old_revid if ("history" not in overwrite) else None),
1189
other_branch=self.source)
1190
tags_ret = self.source.tags.merge_to(
1192
source_tag_refs=remote_refs_dict_to_tag_refs(refs),
1193
overwrite=("tags" in overwrite))
1194
if isinstance(tags_ret, tuple):
1195
(result.tag_updates, result.tag_conflicts) = tags_ret
1197
result.tag_conflicts = tags_ret
1198
result.new_revid = self.target.last_revision()
1201
def update_refs(self, stop_revision=None):
1202
interrepo = _mod_repository.InterRepository.get(
1203
self.source.repository, self.target.repository)
1204
c = self.source.get_config_stack()
1205
fetch_tags = c.get('branch.fetch_tags')
1207
if stop_revision is None:
1208
result = interrepo.fetch(branches=[self.source.ref], include_tags=fetch_tags)
1210
head = result.refs[self.source.ref]
1212
stop_revision = revision.NULL_REVISION
1214
stop_revision = self.target.lookup_foreign_revision_id(head)
1216
result = interrepo.fetch(
1217
revision_id=stop_revision, include_tags=fetch_tags)
1218
return result.refs, stop_revision
1220
def pull(self, stop_revision=None, overwrite=False,
1221
possible_transports=None, run_hooks=True, local=False):
1222
# This type of branch can't be bound.
1224
raise errors.LocalRequiresBoundBranch()
1225
if overwrite is True:
1226
overwrite = set(["history", "tags"])
1230
result = GitPullResult()
1231
result.source_branch = self.source
1232
result.target_branch = self.target
1233
with self.target.lock_write(), self.source.lock_read():
1234
result.old_revid = self.target.last_revision()
1235
refs, stop_revision = self.update_refs(stop_revision)
1236
self.target.generate_revision_history(
1238
(result.old_revid if ("history" not in overwrite) else None),
1239
other_branch=self.source)
1240
tags_ret = self.source.tags.merge_to(
1241
self.target.tags, overwrite=("tags" in overwrite),
1242
source_tag_refs=remote_refs_dict_to_tag_refs(refs))
1243
if isinstance(tags_ret, tuple):
1244
(result.tag_updates, result.tag_conflicts) = tags_ret
1246
result.tag_conflicts = tags_ret
1247
result.new_revid = self.target.last_revision()
1248
result.local_branch = None
1249
result.master_branch = result.target_branch
1251
for hook in branch.Branch.hooks['post_pull']:
1256
class InterToGitBranch(branch.GenericInterBranch):
1257
"""InterBranch implementation that pulls into a Git branch."""
1259
def __init__(self, source, target):
1260
super(InterToGitBranch, self).__init__(source, target)
1261
self.interrepo = _mod_repository.InterRepository.get(source.repository,
1265
def _get_branch_formats_to_test():
1267
default_format = branch.format_registry.get_default()
1268
except AttributeError:
1269
default_format = branch.BranchFormat._default_format
1270
from .remote import RemoteGitBranchFormat
1272
(default_format, LocalGitBranchFormat()),
1273
(default_format, RemoteGitBranchFormat())]
1276
def is_compatible(self, source, target):
1277
return (not isinstance(source, GitBranch) and
1278
isinstance(target, GitBranch))
1280
def _get_new_refs(self, stop_revision=None, fetch_tags=None,
1282
if not self.source.is_locked():
1283
raise errors.ObjectNotLocked(self.source)
1284
if stop_revision is None:
1285
(stop_revno, stop_revision) = self.source.last_revision_info()
1286
elif stop_revno is None:
1288
stop_revno = self.source.revision_id_to_revno(stop_revision)
1289
except errors.NoSuchRevision:
1291
if not isinstance(stop_revision, bytes):
1292
raise TypeError(stop_revision)
1293
main_ref = self.target.ref
1294
refs = {main_ref: (None, stop_revision)}
1295
if fetch_tags is None:
1296
c = self.source.get_config_stack()
1297
fetch_tags = c.get('branch.fetch_tags')
1298
for name, revid in self.source.tags.get_tag_dict().items():
1299
if self.source.repository.has_revision(revid):
1300
ref = tag_name_to_ref(name)
1301
if not check_ref_format(ref):
1302
warning("skipping tag with invalid characters %s (%s)",
1306
# FIXME: Skip tags that are not in the ancestry
1307
refs[ref] = (None, revid)
1308
return refs, main_ref, (stop_revno, stop_revision)
1310
def _update_refs(self, result, old_refs, new_refs, overwrite):
1311
mutter("updating refs. old refs: %r, new refs: %r",
1313
result.tag_updates = {}
1314
result.tag_conflicts = []
1315
ret = dict(old_refs)
1317
def ref_equals(refs, ref, git_sha, revid):
1322
if (value[0] is not None and
1323
git_sha is not None and
1324
value[0] == git_sha):
1326
if (value[1] is not None and
1327
revid is not None and
1330
# FIXME: If one side only has the git sha available and the other
1331
# only has the bzr revid, then this will cause us to show a tag as
1332
# updated that hasn't actually been updated.
1334
# FIXME: Check for diverged branches
1335
for ref, (git_sha, revid) in new_refs.items():
1336
if ref_equals(ret, ref, git_sha, revid):
1337
# Already up to date
1339
git_sha = old_refs[ref][0]
1341
revid = old_refs[ref][1]
1342
ret[ref] = new_refs[ref] = (git_sha, revid)
1343
elif ref not in ret or overwrite:
1345
tag_name = ref_to_tag_name(ref)
1349
result.tag_updates[tag_name] = revid
1350
ret[ref] = (git_sha, revid)
1352
# FIXME: Check diverged
1356
name = ref_to_tag_name(ref)
1360
result.tag_conflicts.append(
1361
(name, revid, ret[name][1]))
1363
ret[ref] = (git_sha, revid)
1366
def fetch(self, stop_revision=None, fetch_tags=None, lossy=False,
1368
if stop_revision is None:
1369
stop_revision = self.source.last_revision()
1372
for k, v in self.source.tags.get_tag_dict().items():
1373
ret.append((None, v))
1374
ret.append((None, stop_revision))
1376
revidmap = self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
1377
except NoPushSupport:
1378
raise errors.NoRoundtrippingSupport(self.source, self.target)
1379
return _mod_repository.FetchResult(revidmap={
1380
old_revid: new_revid
1381
for (old_revid, (new_sha, new_revid)) in revidmap.items()})
1383
def pull(self, overwrite=False, stop_revision=None, local=False,
1384
possible_transports=None, run_hooks=True, _stop_revno=None):
1385
result = GitBranchPullResult()
1386
result.source_branch = self.source
1387
result.target_branch = self.target
1388
with self.source.lock_read(), self.target.lock_write():
1389
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1390
stop_revision, stop_revno=_stop_revno)
1392
def update_refs(old_refs):
1393
return self._update_refs(result, old_refs, new_refs, overwrite)
1395
result.revidmap, old_refs, new_refs = (
1396
self.interrepo.fetch_refs(update_refs, lossy=False))
1397
except NoPushSupport:
1398
raise errors.NoRoundtrippingSupport(self.source, self.target)
1399
(old_sha1, result.old_revid) = old_refs.get(
1400
main_ref, (ZERO_SHA, NULL_REVISION))
1401
if result.old_revid is None:
1402
result.old_revid = self.target.lookup_foreign_revision_id(
1404
result.new_revid = new_refs[main_ref][1]
1405
result.local_branch = None
1406
result.master_branch = self.target
1408
for hook in branch.Branch.hooks['post_pull']:
1412
def push(self, overwrite=False, stop_revision=None, lossy=False,
1413
_override_hook_source_branch=None, _stop_revno=None):
1414
result = GitBranchPushResult()
1415
result.source_branch = self.source
1416
result.target_branch = self.target
1417
result.local_branch = None
1418
result.master_branch = result.target_branch
1419
with self.source.lock_read(), self.target.lock_write():
1420
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1421
stop_revision, stop_revno=_stop_revno)
1423
def update_refs(old_refs):
1424
return self._update_refs(result, old_refs, new_refs, overwrite)
1426
result.revidmap, old_refs, new_refs = (
1427
self.interrepo.fetch_refs(
1428
update_refs, lossy=lossy, overwrite=overwrite))
1429
except NoPushSupport:
1430
raise errors.NoRoundtrippingSupport(self.source, self.target)
1431
(old_sha1, result.old_revid) = old_refs.get(
1432
main_ref, (ZERO_SHA, NULL_REVISION))
1433
if lossy or result.old_revid is None:
1434
result.old_revid = self.target.lookup_foreign_revision_id(
1436
result.new_revid = new_refs[main_ref][1]
1437
(result.new_original_revno,
1438
result.new_original_revid) = stop_revinfo
1439
for hook in branch.Branch.hooks['post_push']:
1444
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
1445
branch.InterBranch.register_optimiser(InterFromGitBranch)
1446
branch.InterBranch.register_optimiser(InterToGitBranch)
1447
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)