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"""
20
from __future__ import absolute_import
22
from io import BytesIO
23
from collections import defaultdict
25
from dulwich.objects import (
29
from dulwich.repo import check_ref_format
37
repository as _mod_repository,
44
from ..foreign import ForeignBranch
45
from ..revision import (
48
from ..sixish import (
73
remote_refs_dict_to_tag_refs,
76
from .unpeel_map import (
79
from .urls import git_url_to_bzr_url
82
class GitPullResult(branch.PullResult):
83
"""Result of a pull from a Git branch."""
85
def _lookup_revno(self, revid):
86
if not isinstance(revid, bytes):
87
raise TypeError(revid)
88
# Try in source branch first, it'll be faster
89
with self.target_branch.lock_read():
90
return self.target_branch.revision_id_to_revno(revid)
94
return self._lookup_revno(self.old_revid)
98
return self._lookup_revno(self.new_revid)
101
class GitTags(tag.BasicTags):
102
"""Ref-based tag dictionary."""
104
def __init__(self, branch):
106
self.repository = branch.repository
108
def _merge_to_remote_git(self, target_repo, source_tag_refs,
113
def get_changed_refs(old_refs):
115
for ref_name, tag_name, peeled, unpeeled in (
116
source_tag_refs.iteritems()):
117
if old_refs.get(ref_name) == unpeeled:
119
elif overwrite or ref_name not in old_refs:
120
ret[ref_name] = unpeeled
121
updates[tag_name] = target_repo.lookup_foreign_revision_id(
126
self.repository.lookup_foreign_revision_id(peeled),
127
target_repo.lookup_foreign_revision_id(
128
old_refs[ref_name])))
130
target_repo.controldir.send_pack(
131
get_changed_refs, lambda have, want: [])
132
return updates, conflicts
134
def _merge_to_local_git(self, target_repo, source_tag_refs,
138
for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
139
if target_repo._git.refs.get(ref_name) == unpeeled:
141
elif overwrite or ref_name not in target_repo._git.refs:
142
target_repo._git.refs[ref_name] = unpeeled or peeled
144
updates[tag_name] = (
145
self.repository.lookup_foreign_revision_id(peeled))
147
trace.warning('%s does not point to a valid object',
152
source_revid = self.repository.lookup_foreign_revision_id(
154
target_revid = target_repo.lookup_foreign_revision_id(
155
target_repo._git.refs[ref_name])
157
trace.warning('%s does not point to a valid object',
160
conflicts.append((tag_name, source_revid, target_revid))
161
return updates, conflicts
163
def _merge_to_git(self, to_tags, source_tag_refs, overwrite=False):
164
target_repo = to_tags.repository
165
if self.repository.has_same_location(target_repo):
168
if getattr(target_repo, "_git", None):
169
return self._merge_to_local_git(
170
target_repo, source_tag_refs, overwrite)
172
return self._merge_to_remote_git(
173
target_repo, source_tag_refs, overwrite)
175
to_tags.branch._tag_refs = None
177
def _merge_to_non_git(self, to_tags, source_tag_refs, overwrite=False):
178
unpeeled_map = defaultdict(set)
181
result = dict(to_tags.get_tag_dict())
182
for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
183
if unpeeled is not None:
184
unpeeled_map[peeled].add(unpeeled)
186
bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
187
except NotCommitError:
189
if result.get(tag_name) == bzr_revid:
191
elif tag_name not in result or overwrite:
192
result[tag_name] = bzr_revid
193
updates[tag_name] = bzr_revid
195
conflicts.append((tag_name, bzr_revid, result[tag_name]))
196
to_tags._set_tag_dict(result)
197
if len(unpeeled_map) > 0:
198
map_file = UnpeelMap.from_repository(to_tags.branch.repository)
199
map_file.update(unpeeled_map)
200
map_file.save_in_repository(to_tags.branch.repository)
201
return updates, conflicts
203
def merge_to(self, to_tags, overwrite=False, ignore_master=False,
204
source_tag_refs=None):
205
"""See Tags.merge_to."""
206
if source_tag_refs is None:
207
source_tag_refs = self.branch.get_tag_refs()
210
if isinstance(to_tags, GitTags):
211
return self._merge_to_git(to_tags, source_tag_refs,
217
master = to_tags.branch.get_master_branch()
218
if master is not None:
221
updates, conflicts = self._merge_to_non_git(
222
to_tags, source_tag_refs, overwrite=overwrite)
223
if master is not None:
224
extra_updates, extra_conflicts = self.merge_to(
225
master.tags, overwrite=overwrite,
226
source_tag_refs=source_tag_refs,
227
ignore_master=ignore_master)
228
updates.update(extra_updates)
229
conflicts += extra_conflicts
230
return updates, conflicts
232
if master is not None:
235
def get_tag_dict(self):
237
for (ref_name, tag_name, peeled, unpeeled) in (
238
self.branch.get_tag_refs()):
240
bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
241
except NotCommitError:
244
ret[tag_name] = bzr_revid
248
class LocalGitTagDict(GitTags):
249
"""Dictionary with tags in a local repository."""
251
def __init__(self, branch):
252
super(LocalGitTagDict, self).__init__(branch)
253
self.refs = self.repository.controldir._git.refs
255
def _set_tag_dict(self, to_dict):
256
extra = set(self.refs.allkeys())
257
for k, revid in viewitems(to_dict):
258
name = tag_name_to_ref(k)
261
self.set_tag(k, revid)
264
del self.repository._git[name]
266
def set_tag(self, name, revid):
268
git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
269
except errors.NoSuchRevision:
270
raise errors.GhostTagsNotSupported(self)
271
self.refs[tag_name_to_ref(name)] = git_sha
272
self.branch._tag_refs = None
274
def delete_tag(self, name):
275
ref = tag_name_to_ref(name)
276
if ref not in self.refs:
277
raise errors.NoSuchTag(name)
279
self.branch._tag_refs = None
282
class GitBranchFormat(branch.BranchFormat):
284
def network_name(self):
287
def supports_tags(self):
290
def supports_leaving_lock(self):
293
def supports_tags_referencing_ghosts(self):
296
def tags_are_versioned(self):
299
def get_foreign_tests_branch_factory(self):
300
from .tests.test_branch import ForeignTestsBranchFactory
301
return ForeignTestsBranchFactory()
303
def make_tags(self, branch):
306
except AttributeError:
308
if getattr(branch.repository, "_git", None) is None:
309
from .remote import RemoteGitTagDict
310
return RemoteGitTagDict(branch)
312
return LocalGitTagDict(branch)
314
def initialize(self, a_controldir, name=None, repository=None,
315
append_revisions_only=None):
316
raise NotImplementedError(self.initialize)
318
def get_reference(self, controldir, name=None):
319
return controldir.get_branch_reference(name)
321
def set_reference(self, controldir, name, target):
322
return controldir.set_branch_reference(target, name)
325
class LocalGitBranchFormat(GitBranchFormat):
327
def get_format_description(self):
328
return 'Local Git Branch'
331
def _matchingcontroldir(self):
332
from .dir import LocalGitControlDirFormat
333
return LocalGitControlDirFormat()
335
def initialize(self, a_controldir, name=None, repository=None,
336
append_revisions_only=None):
337
from .dir import LocalGitDir
338
if not isinstance(a_controldir, LocalGitDir):
339
raise errors.IncompatibleFormat(self, a_controldir._format)
340
return a_controldir.create_branch(
341
repository=repository, name=name,
342
append_revisions_only=append_revisions_only)
345
class GitBranch(ForeignBranch):
346
"""An adapter to git repositories for bzr Branch objects."""
349
def control_transport(self):
350
return self._control_transport
353
def user_transport(self):
354
return self._user_transport
356
def __init__(self, controldir, repository, ref, format):
357
self.repository = repository
358
self._format = format
359
self.controldir = controldir
360
self._lock_mode = None
362
super(GitBranch, self).__init__(repository.get_mapping())
365
self._user_transport = controldir.user_transport.clone('.')
366
self._control_transport = controldir.control_transport.clone('.')
367
self._tag_refs = None
370
self.name = ref_to_branch_name(ref)
373
if self.ref is not None:
374
params = {"ref": urlutils.escape(self.ref)}
377
params = {"branch": urlutils.escape(self.name)}
378
for k, v in params.items():
379
self._user_transport.set_segment_parameter(k, v)
380
self._control_transport.set_segment_parameter(k, v)
381
self.base = controldir.user_transport.base
383
def _get_checkout_format(self, lightweight=False):
384
"""Return the most suitable metadir for a checkout of this branch.
385
Weaves are used if this branch's repository uses weaves.
388
return controldir.format_registry.make_controldir("git")
390
return controldir.format_registry.make_controldir("default")
392
def get_child_submit_format(self):
393
"""Return the preferred format of submissions to this branch."""
394
ret = self.get_config_stack().get("child_submit_format")
399
def get_config(self):
400
return GitBranchConfig(self)
402
def get_config_stack(self):
403
return GitBranchStack(self)
405
def _get_nick(self, local=False, possible_master_transports=None):
406
"""Find the nick name for this branch.
410
cs = self.repository._git.get_config_stack()
412
nick = cs.get((b"branch", self.name.encode('utf-8')), b"nick")
416
return nick.decode("utf-8")
417
return self.name or u"HEAD"
419
def _set_nick(self, nick):
420
cf = self.repository._git.get_config()
421
cf.set((b"branch", self.name.encode('utf-8')),
422
b"nick", nick.encode("utf-8"))
425
self.repository._git._put_named_file('config', f.getvalue())
427
nick = property(_get_nick, _set_nick)
430
return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
433
def generate_revision_history(self, revid, last_rev=None,
435
if last_rev is not None:
436
graph = self.repository.get_graph()
437
if not graph.is_ancestor(last_rev, revid):
438
# our previous tip is not merged into stop_revision
439
raise errors.DivergedBranches(self, other_branch)
441
self.set_last_revision(revid)
443
def lock_write(self, token=None):
444
if token is not None:
445
raise errors.TokenLockingNotSupported(self)
447
if self._lock_mode == 'r':
448
raise errors.ReadOnlyError(self)
449
self._lock_count += 1
452
self._lock_mode = 'w'
454
self.repository.lock_write()
455
return lock.LogicalLockResult(self.unlock)
457
def leave_lock_in_place(self):
458
raise NotImplementedError(self.leave_lock_in_place)
460
def dont_leave_lock_in_place(self):
461
raise NotImplementedError(self.dont_leave_lock_in_place)
463
def get_stacked_on_url(self):
464
# Git doesn't do stacking (yet...)
465
raise branch.UnstackableBranchFormat(self._format, self.base)
467
def _get_parent_location(self):
468
"""See Branch.get_parent()."""
469
# FIXME: Set "origin" url from .git/config ?
470
cs = self.repository._git.get_config_stack()
472
location = cs.get((b"remote", b'origin'), b"url")
478
ref = cs.get((b"remote", b"origin"), b"merge")
484
params['branch'] = urlutils.escape(ref_to_branch_name(ref))
486
params['ref'] = urlutils.quote_from_bytes(ref)
488
url = git_url_to_bzr_url(location.decode('utf-8'))
489
return urlutils.join_segment_parameters(url, params)
491
def set_parent(self, location):
492
# FIXME: Set "origin" url in .git/config ?
493
cs = self.repository._git.get_config()
494
this_url = urlutils.split_segment_parameters(self.user_url)[0]
495
target_url, target_params = urlutils.split_segment_parameters(location)
496
location = urlutils.relative_url(this_url, target_url)
497
cs.set((b"remote", b"origin"), b"url", location)
498
if 'branch' in target_params:
499
cs.set((b"remote", b"origin"), b"merge",
500
branch_name_to_ref(target_params['branch']))
501
elif 'ref' in target_params:
502
cs.set((b"remote", b"origin"), b"merge",
503
target_params['ref'])
505
# TODO(jelmer): Maybe unset rather than setting to HEAD?
506
cs.set((b"remote", b"origin"), b"merge", 'HEAD')
509
self.repository._git._put_named_file('config', f.getvalue())
511
def break_lock(self):
512
raise NotImplementedError(self.break_lock)
516
if self._lock_mode not in ('r', 'w'):
517
raise ValueError(self._lock_mode)
518
self._lock_count += 1
520
self._lock_mode = 'r'
522
self.repository.lock_read()
523
return lock.LogicalLockResult(self.unlock)
525
def peek_lock_mode(self):
526
return self._lock_mode
529
return (self._lock_mode is not None)
534
def _unlock_ref(self):
538
"""See Branch.unlock()."""
539
if self._lock_count == 0:
540
raise errors.LockNotHeld(self)
542
self._lock_count -= 1
543
if self._lock_count == 0:
544
if self._lock_mode == 'w':
546
self._lock_mode = None
547
self._clear_cached_state()
549
self.repository.unlock()
551
def get_physical_lock_status(self):
554
def last_revision(self):
555
with self.lock_read():
556
# perhaps should escape this ?
557
if self.head is None:
558
return revision.NULL_REVISION
559
return self.lookup_foreign_revision_id(self.head)
561
def _basic_push(self, target, overwrite=False, stop_revision=None):
562
return branch.InterBranch.get(self, target)._basic_push(
563
overwrite, stop_revision)
565
def lookup_foreign_revision_id(self, foreign_revid):
567
return self.repository.lookup_foreign_revision_id(foreign_revid,
571
return self.mapping.revision_id_foreign_to_bzr(foreign_revid)
573
def lookup_bzr_revision_id(self, revid):
574
return self.repository.lookup_bzr_revision_id(
575
revid, mapping=self.mapping)
577
def get_unshelver(self, tree):
578
raise errors.StoringUncommittedNotSupported(self)
580
def _clear_cached_state(self):
581
super(GitBranch, self)._clear_cached_state()
582
self._tag_refs = None
584
def _iter_tag_refs(self, refs):
585
"""Iterate over the tag refs.
587
:param refs: Refs dictionary (name -> git sha1)
588
:return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
590
raise NotImplementedError(self._iter_tag_refs)
592
def get_tag_refs(self):
593
with self.lock_read():
594
if self._tag_refs is None:
595
self._tag_refs = list(self._iter_tag_refs())
596
return self._tag_refs
599
class LocalGitBranch(GitBranch):
600
"""A local Git branch."""
602
def __init__(self, controldir, repository, ref):
603
super(LocalGitBranch, self).__init__(controldir, repository, ref,
604
LocalGitBranchFormat())
606
def create_checkout(self, to_location, revision_id=None, lightweight=False,
607
accelerator_tree=None, hardlink=False):
608
t = transport.get_transport(to_location)
610
format = self._get_checkout_format(lightweight=lightweight)
611
checkout = format.initialize_on_transport(t)
613
from_branch = checkout.set_branch_reference(target_branch=self)
615
checkout_branch = checkout.create_branch()
616
checkout_branch.bind(self)
617
checkout_branch.pull(self, stop_revision=revision_id)
619
return checkout.create_workingtree(
620
revision_id, from_branch=from_branch, hardlink=hardlink)
623
self._ref_lock = self.repository._git.refs.lock_ref(self.ref)
625
def _unlock_ref(self):
626
self._ref_lock.unlock()
628
def break_lock(self):
629
self.repository._git.refs.unlock_ref(self.ref)
631
def fetch(self, from_branch, last_revision=None, limit=None):
632
return branch.InterBranch.get(from_branch, self).fetch(
633
stop_revision=last_revision, limit=limit)
635
def _gen_revision_history(self):
636
if self.head is None:
638
last_revid = self.last_revision()
639
graph = self.repository.get_graph()
641
ret = list(graph.iter_lefthand_ancestry(
642
last_revid, (revision.NULL_REVISION, )))
643
except errors.RevisionNotPresent as e:
644
raise errors.GhostRevisionsHaveNoRevno(last_revid, e.revision_id)
650
return self.repository._git.refs[self.ref]
654
def _read_last_revision_info(self):
655
last_revid = self.last_revision()
656
graph = self.repository.get_graph()
658
revno = graph.find_distance_to_null(
659
last_revid, [(revision.NULL_REVISION, 0)])
660
except errors.GhostRevisionsHaveNoRevno:
662
return revno, last_revid
664
def set_last_revision_info(self, revno, revision_id):
665
self.set_last_revision(revision_id)
666
self._last_revision_info_cache = revno, revision_id
668
def set_last_revision(self, revid):
669
if not revid or not isinstance(revid, bytes):
670
raise errors.InvalidRevisionId(revision_id=revid, branch=self)
671
if revid == NULL_REVISION:
674
(newhead, self.mapping) = self.repository.lookup_bzr_revision_id(
676
if self.mapping is None:
678
self._set_head(newhead)
680
def _set_head(self, value):
681
if value == ZERO_SHA:
682
raise ValueError(value)
685
del self.repository._git.refs[self.ref]
687
self.repository._git.refs[self.ref] = self._head
688
self._clear_cached_state()
690
head = property(_get_head, _set_head)
692
def get_push_location(self):
693
"""See Branch.get_push_location."""
694
push_loc = self.get_config_stack().get('push_location')
697
def set_push_location(self, location):
698
"""See Branch.set_push_location."""
699
self.get_config().set_user_option('push_location', location,
700
store=config.STORE_LOCATION)
702
def supports_tags(self):
705
def store_uncommitted(self, creator):
706
raise errors.StoringUncommittedNotSupported(self)
708
def _iter_tag_refs(self):
709
"""Iterate over the tag refs.
711
:param refs: Refs dictionary (name -> git sha1)
712
:return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
714
refs = self.repository._git.refs
715
for ref_name, unpeeled in viewitems(refs.as_dict()):
717
tag_name = ref_to_tag_name(ref_name)
718
except (ValueError, UnicodeDecodeError):
720
peeled = refs.get_peeled(ref_name)
723
if not isinstance(tag_name, text_type):
724
raise TypeError(tag_name)
725
yield (ref_name, tag_name, peeled, unpeeled)
727
def create_memorytree(self):
728
from .memorytree import GitMemoryTree
729
return GitMemoryTree(self, self.repository._git.object_store,
732
def reference_parent(self, path, file_id=None, possible_transports=None):
733
"""Return the parent branch for a tree-reference file_id
735
:param path: The path of the file_id in the tree
736
:param file_id: Optional file_id of the tree reference
737
:return: A branch associated with the file_id
739
# FIXME should provide multiple branches, based on config
740
url = urlutils.join(self.user_url, path)
741
return branch.Branch.open(
743
possible_transports=possible_transports)
746
def _quick_lookup_revno(local_branch, remote_branch, revid):
747
if not isinstance(revid, bytes):
748
raise TypeError(revid)
749
# Try in source branch first, it'll be faster
750
with local_branch.lock_read():
752
return local_branch.revision_id_to_revno(revid)
753
except errors.NoSuchRevision:
754
graph = local_branch.repository.get_graph()
756
return graph.find_distance_to_null(
757
revid, [(revision.NULL_REVISION, 0)])
758
except errors.GhostRevisionsHaveNoRevno:
759
# FIXME: Check using graph.find_distance_to_null() ?
760
with remote_branch.lock_read():
761
return remote_branch.revision_id_to_revno(revid)
764
class GitBranchPullResult(branch.PullResult):
767
super(GitBranchPullResult, self).__init__()
768
self.new_git_head = None
769
self._old_revno = None
770
self._new_revno = None
772
def report(self, to_file):
774
if self.old_revid == self.new_revid:
775
to_file.write('No revisions to pull.\n')
776
elif self.new_git_head is not None:
777
to_file.write('Now on revision %d (git sha: %s).\n' %
778
(self.new_revno, self.new_git_head))
780
to_file.write('Now on revision %d.\n' % (self.new_revno,))
781
self._show_tag_conficts(to_file)
783
def _lookup_revno(self, revid):
784
return _quick_lookup_revno(self.target_branch, self.source_branch,
787
def _get_old_revno(self):
788
if self._old_revno is not None:
789
return self._old_revno
790
return self._lookup_revno(self.old_revid)
792
def _set_old_revno(self, revno):
793
self._old_revno = revno
795
old_revno = property(_get_old_revno, _set_old_revno)
797
def _get_new_revno(self):
798
if self._new_revno is not None:
799
return self._new_revno
800
return self._lookup_revno(self.new_revid)
802
def _set_new_revno(self, revno):
803
self._new_revno = revno
805
new_revno = property(_get_new_revno, _set_new_revno)
808
class GitBranchPushResult(branch.BranchPushResult):
810
def _lookup_revno(self, revid):
811
return _quick_lookup_revno(self.source_branch, self.target_branch,
816
return self._lookup_revno(self.old_revid)
820
new_original_revno = getattr(self, "new_original_revno", None)
821
if new_original_revno:
822
return new_original_revno
823
if getattr(self, "new_original_revid", None) is not None:
824
return self._lookup_revno(self.new_original_revid)
825
return self._lookup_revno(self.new_revid)
828
class InterFromGitBranch(branch.GenericInterBranch):
829
"""InterBranch implementation that pulls from Git into bzr."""
832
def _get_branch_formats_to_test():
834
default_format = branch.format_registry.get_default()
835
except AttributeError:
836
default_format = branch.BranchFormat._default_format
837
from .remote import RemoteGitBranchFormat
839
(RemoteGitBranchFormat(), default_format),
840
(LocalGitBranchFormat(), default_format)]
843
def _get_interrepo(self, source, target):
844
return _mod_repository.InterRepository.get(
845
source.repository, target.repository)
848
def is_compatible(cls, source, target):
849
if not isinstance(source, GitBranch):
851
if isinstance(target, GitBranch):
852
# InterLocalGitRemoteGitBranch or InterToGitBranch should be used
854
if (getattr(cls._get_interrepo(source, target), "fetch_objects", None)
856
# fetch_objects is necessary for this to work
860
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
861
self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
863
def fetch_objects(self, stop_revision, fetch_tags, limit=None):
864
interrepo = self._get_interrepo(self.source, self.target)
865
if fetch_tags is None:
866
c = self.source.get_config_stack()
867
fetch_tags = c.get('branch.fetch_tags')
869
def determine_wants(heads):
870
if stop_revision is None:
872
head = heads[self.source.ref]
874
self._last_revid = revision.NULL_REVISION
876
self._last_revid = self.source.lookup_foreign_revision_id(
879
self._last_revid = stop_revision
880
real = interrepo.get_determine_wants_revids(
881
[self._last_revid], include_tags=fetch_tags)
883
pack_hint, head, refs = interrepo.fetch_objects(
884
determine_wants, self.source.mapping, limit=limit)
885
if (pack_hint is not None and
886
self.target.repository._format.pack_compresses):
887
self.target.repository.pack(hint=pack_hint)
890
def _update_revisions(self, stop_revision=None, overwrite=False):
891
head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
893
prev_last_revid = None
895
prev_last_revid = self.target.last_revision()
896
self.target.generate_revision_history(
897
self._last_revid, last_rev=prev_last_revid,
898
other_branch=self.source)
901
def _basic_pull(self, stop_revision, overwrite, run_hooks,
902
_override_hook_target, _hook_master):
903
if overwrite is True:
904
overwrite = set(["history", "tags"])
907
result = GitBranchPullResult()
908
result.source_branch = self.source
909
if _override_hook_target is None:
910
result.target_branch = self.target
912
result.target_branch = _override_hook_target
913
with self.target.lock_write(), self.source.lock_read():
914
# We assume that during 'pull' the target repository is closer than
916
(result.old_revno, result.old_revid) = \
917
self.target.last_revision_info()
918
result.new_git_head, remote_refs = self._update_revisions(
919
stop_revision, overwrite=("history" in overwrite))
920
tags_ret = self.source.tags.merge_to(
921
self.target.tags, ("tags" in overwrite), ignore_master=True)
922
if isinstance(tags_ret, tuple):
923
result.tag_updates, result.tag_conflicts = tags_ret
925
result.tag_conflicts = tags_ret
926
(result.new_revno, result.new_revid) = \
927
self.target.last_revision_info()
929
result.master_branch = _hook_master
930
result.local_branch = result.target_branch
932
result.master_branch = result.target_branch
933
result.local_branch = None
935
for hook in branch.Branch.hooks['post_pull']:
939
def pull(self, overwrite=False, stop_revision=None,
940
possible_transports=None, _hook_master=None, run_hooks=True,
941
_override_hook_target=None, local=False):
944
:param _hook_master: Private parameter - set the branch to
945
be supplied as the master to pull hooks.
946
:param run_hooks: Private parameter - if false, this branch
947
is being called because it's the master of the primary branch,
948
so it should not run its hooks.
949
:param _override_hook_target: Private parameter - set the branch to be
950
supplied as the target_branch to pull hooks.
952
# This type of branch can't be bound.
953
bound_location = self.target.get_bound_location()
954
if local and not bound_location:
955
raise errors.LocalRequiresBoundBranch()
957
source_is_master = False
958
self.source.lock_read()
960
# bound_location comes from a config file, some care has to be
961
# taken to relate it to source.user_url
962
normalized = urlutils.normalize_url(bound_location)
964
relpath = self.source.user_transport.relpath(normalized)
965
source_is_master = (relpath == '')
966
except (errors.PathNotChild, urlutils.InvalidURL):
967
source_is_master = False
968
if not local and bound_location and not source_is_master:
969
# not pulling from master, so we need to update master.
970
master_branch = self.target.get_master_branch(possible_transports)
971
master_branch.lock_write()
975
# pull from source into master.
976
master_branch.pull(self.source, overwrite, stop_revision,
978
result = self._basic_pull(stop_revision, overwrite, run_hooks,
979
_override_hook_target,
980
_hook_master=master_branch)
985
master_branch.unlock()
988
def _basic_push(self, overwrite, stop_revision):
989
if overwrite is True:
990
overwrite = set(["history", "tags"])
993
result = branch.BranchPushResult()
994
result.source_branch = self.source
995
result.target_branch = self.target
996
result.old_revno, result.old_revid = self.target.last_revision_info()
997
result.new_git_head, remote_refs = self._update_revisions(
998
stop_revision, overwrite=("history" in overwrite))
999
tags_ret = self.source.tags.merge_to(
1000
self.target.tags, "tags" in overwrite, ignore_master=True)
1001
(result.tag_updates, result.tag_conflicts) = tags_ret
1002
result.new_revno, result.new_revid = self.target.last_revision_info()
1006
class InterGitBranch(branch.GenericInterBranch):
1007
"""InterBranch implementation that pulls between Git branches."""
1009
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
1010
raise NotImplementedError(self.fetch)
1013
class InterLocalGitRemoteGitBranch(InterGitBranch):
1014
"""InterBranch that copies from a local to a remote git branch."""
1017
def _get_branch_formats_to_test():
1018
from .remote import RemoteGitBranchFormat
1020
(LocalGitBranchFormat(), RemoteGitBranchFormat())]
1023
def is_compatible(self, source, target):
1024
from .remote import RemoteGitBranch
1025
return (isinstance(source, LocalGitBranch) and
1026
isinstance(target, RemoteGitBranch))
1028
def _basic_push(self, overwrite, stop_revision):
1029
result = GitBranchPushResult()
1030
result.source_branch = self.source
1031
result.target_branch = self.target
1032
if stop_revision is None:
1033
stop_revision = self.source.last_revision()
1035
def get_changed_refs(old_refs):
1036
old_ref = old_refs.get(self.target.ref, None)
1038
result.old_revid = revision.NULL_REVISION
1040
result.old_revid = self.target.lookup_foreign_revision_id(
1042
new_ref = self.source.repository.lookup_bzr_revision_id(
1045
if remote_divergence(
1047
self.source.repository._git.object_store):
1048
raise errors.DivergedBranches(self.source, self.target)
1049
refs = {self.target.ref: new_ref}
1050
result.new_revid = stop_revision
1051
for name, sha in viewitems(
1052
self.source.repository._git.refs.as_dict(b"refs/tags")):
1053
refs[tag_name_to_ref(name)] = sha
1055
self.target.repository.send_pack(
1057
self.source.repository._git.object_store.generate_pack_data)
1061
class InterGitLocalGitBranch(InterGitBranch):
1062
"""InterBranch that copies from a remote to a local git branch."""
1065
def _get_branch_formats_to_test():
1066
from .remote import RemoteGitBranchFormat
1068
(RemoteGitBranchFormat(), LocalGitBranchFormat()),
1069
(LocalGitBranchFormat(), LocalGitBranchFormat())]
1072
def is_compatible(self, source, target):
1073
return (isinstance(source, GitBranch) and
1074
isinstance(target, LocalGitBranch))
1076
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
1077
interrepo = _mod_repository.InterRepository.get(self.source.repository,
1078
self.target.repository)
1079
if stop_revision is None:
1080
stop_revision = self.source.last_revision()
1081
determine_wants = interrepo.get_determine_wants_revids(
1082
[stop_revision], include_tags=fetch_tags)
1083
interrepo.fetch_objects(determine_wants, limit=limit)
1085
def _basic_push(self, overwrite=False, stop_revision=None):
1086
if overwrite is True:
1087
overwrite = set(["history", "tags"])
1090
result = GitBranchPushResult()
1091
result.source_branch = self.source
1092
result.target_branch = self.target
1093
result.old_revid = self.target.last_revision()
1094
refs, stop_revision = self.update_refs(stop_revision)
1095
self.target.generate_revision_history(
1097
(result.old_revid if ("history" not in overwrite) else None),
1098
other_branch=self.source)
1099
tags_ret = self.source.tags.merge_to(
1101
source_tag_refs=remote_refs_dict_to_tag_refs(refs),
1102
overwrite=("tags" in overwrite))
1103
if isinstance(tags_ret, tuple):
1104
(result.tag_updates, result.tag_conflicts) = tags_ret
1106
result.tag_conflicts = tags_ret
1107
result.new_revid = self.target.last_revision()
1110
def update_refs(self, stop_revision=None):
1111
interrepo = _mod_repository.InterRepository.get(
1112
self.source.repository, self.target.repository)
1113
c = self.source.get_config_stack()
1114
fetch_tags = c.get('branch.fetch_tags')
1116
if stop_revision is None:
1117
refs = interrepo.fetch(branches=[self.source.ref], include_tags=fetch_tags)
1119
head = refs[self.source.ref]
1121
stop_revision = revision.NULL_REVISION
1123
stop_revision = self.target.lookup_foreign_revision_id(head)
1125
refs = interrepo.fetch(
1126
revision_id=stop_revision, include_tags=fetch_tags)
1127
return refs, stop_revision
1129
def pull(self, stop_revision=None, overwrite=False,
1130
possible_transports=None, run_hooks=True, local=False):
1131
# This type of branch can't be bound.
1133
raise errors.LocalRequiresBoundBranch()
1134
if overwrite is True:
1135
overwrite = set(["history", "tags"])
1139
result = GitPullResult()
1140
result.source_branch = self.source
1141
result.target_branch = self.target
1142
with self.target.lock_write(), self.source.lock_read():
1143
result.old_revid = self.target.last_revision()
1144
refs, stop_revision = self.update_refs(stop_revision)
1145
self.target.generate_revision_history(
1147
(result.old_revid if ("history" not in overwrite) else None),
1148
other_branch=self.source)
1149
tags_ret = self.source.tags.merge_to(
1150
self.target.tags, overwrite=("tags" in overwrite),
1151
source_tag_refs=remote_refs_dict_to_tag_refs(refs))
1152
if isinstance(tags_ret, tuple):
1153
(result.tag_updates, result.tag_conflicts) = tags_ret
1155
result.tag_conflicts = tags_ret
1156
result.new_revid = self.target.last_revision()
1157
result.local_branch = None
1158
result.master_branch = result.target_branch
1160
for hook in branch.Branch.hooks['post_pull']:
1165
class InterToGitBranch(branch.GenericInterBranch):
1166
"""InterBranch implementation that pulls into a Git branch."""
1168
def __init__(self, source, target):
1169
super(InterToGitBranch, self).__init__(source, target)
1170
self.interrepo = _mod_repository.InterRepository.get(source.repository,
1174
def _get_branch_formats_to_test():
1176
default_format = branch.format_registry.get_default()
1177
except AttributeError:
1178
default_format = branch.BranchFormat._default_format
1179
from .remote import RemoteGitBranchFormat
1181
(default_format, LocalGitBranchFormat()),
1182
(default_format, RemoteGitBranchFormat())]
1185
def is_compatible(self, source, target):
1186
return (not isinstance(source, GitBranch) and
1187
isinstance(target, GitBranch))
1189
def _get_new_refs(self, stop_revision=None, fetch_tags=None):
1190
if not self.source.is_locked():
1191
raise errors.ObjectNotLocked(self.source)
1192
if stop_revision is None:
1193
(stop_revno, stop_revision) = self.source.last_revision_info()
1195
stop_revno = self.source.revision_id_to_revno(stop_revision)
1196
if not isinstance(stop_revision, bytes):
1197
raise TypeError(stop_revision)
1198
main_ref = self.target.ref
1199
refs = {main_ref: (None, stop_revision)}
1200
if fetch_tags is None:
1201
c = self.source.get_config_stack()
1202
fetch_tags = c.get('branch.fetch_tags')
1203
for name, revid in viewitems(self.source.tags.get_tag_dict()):
1204
if self.source.repository.has_revision(revid):
1205
ref = tag_name_to_ref(name)
1206
if not check_ref_format(ref):
1207
warning("skipping tag with invalid characters %s (%s)",
1211
# FIXME: Skip tags that are not in the ancestry
1212
refs[ref] = (None, revid)
1213
return refs, main_ref, (stop_revno, stop_revision)
1215
def _update_refs(self, result, old_refs, new_refs, overwrite):
1216
mutter("updating refs. old refs: %r, new refs: %r",
1218
result.tag_updates = {}
1219
result.tag_conflicts = []
1220
ret = dict(old_refs)
1222
def ref_equals(refs, ref, git_sha, revid):
1227
if (value[0] is not None and
1228
git_sha is not None and
1229
value[0] == git_sha):
1231
if (value[1] is not None and
1232
revid is not None and
1235
# FIXME: If one side only has the git sha available and the other
1236
# only has the bzr revid, then this will cause us to show a tag as
1237
# updated that hasn't actually been updated.
1239
# FIXME: Check for diverged branches
1240
for ref, (git_sha, revid) in viewitems(new_refs):
1241
if ref_equals(ret, ref, git_sha, revid):
1242
# Already up to date
1244
git_sha = old_refs[ref][0]
1246
revid = old_refs[ref][1]
1247
ret[ref] = new_refs[ref] = (git_sha, revid)
1248
elif ref not in ret or overwrite:
1250
tag_name = ref_to_tag_name(ref)
1254
result.tag_updates[tag_name] = revid
1255
ret[ref] = (git_sha, revid)
1257
# FIXME: Check diverged
1261
name = ref_to_tag_name(ref)
1265
result.tag_conflicts.append(
1266
(name, revid, ret[name][1]))
1268
ret[ref] = (git_sha, revid)
1271
def fetch(self, stop_revision=None, fetch_tags=None, lossy=False,
1273
if stop_revision is None:
1274
stop_revision = self.source.last_revision()
1277
for k, v in viewitems(self.source.tags.get_tag_dict()):
1278
ret.append((None, v))
1279
ret.append((None, stop_revision))
1281
self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
1282
except NoPushSupport:
1283
raise errors.NoRoundtrippingSupport(self.source, self.target)
1285
def pull(self, overwrite=False, stop_revision=None, local=False,
1286
possible_transports=None, run_hooks=True):
1287
result = GitBranchPullResult()
1288
result.source_branch = self.source
1289
result.target_branch = self.target
1290
with self.source.lock_read(), self.target.lock_write():
1291
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1294
def update_refs(old_refs):
1295
return self._update_refs(result, old_refs, new_refs, overwrite)
1297
result.revidmap, old_refs, new_refs = (
1298
self.interrepo.fetch_refs(update_refs, lossy=False))
1299
except NoPushSupport:
1300
raise errors.NoRoundtrippingSupport(self.source, self.target)
1301
(old_sha1, result.old_revid) = old_refs.get(
1302
main_ref, (ZERO_SHA, NULL_REVISION))
1303
if result.old_revid is None:
1304
result.old_revid = self.target.lookup_foreign_revision_id(
1306
result.new_revid = new_refs[main_ref][1]
1307
result.local_branch = None
1308
result.master_branch = self.target
1310
for hook in branch.Branch.hooks['post_pull']:
1314
def push(self, overwrite=False, stop_revision=None, lossy=False,
1315
_override_hook_source_branch=None):
1316
result = GitBranchPushResult()
1317
result.source_branch = self.source
1318
result.target_branch = self.target
1319
result.local_branch = None
1320
result.master_branch = result.target_branch
1321
with self.source.lock_read(), self.target.lock_write():
1322
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1325
def update_refs(old_refs):
1326
return self._update_refs(result, old_refs, new_refs, overwrite)
1328
result.revidmap, old_refs, new_refs = (
1329
self.interrepo.fetch_refs(
1330
update_refs, lossy=lossy, overwrite=overwrite))
1331
except NoPushSupport:
1332
raise errors.NoRoundtrippingSupport(self.source, self.target)
1333
(old_sha1, result.old_revid) = old_refs.get(
1334
main_ref, (ZERO_SHA, NULL_REVISION))
1335
if result.old_revid is None:
1336
result.old_revid = self.target.lookup_foreign_revision_id(
1338
result.new_revid = new_refs[main_ref][1]
1339
(result.new_original_revno,
1340
result.new_original_revid) = stop_revinfo
1341
for hook in branch.Branch.hooks['post_push']:
1346
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
1347
branch.InterBranch.register_optimiser(InterFromGitBranch)
1348
branch.InterBranch.register_optimiser(InterToGitBranch)
1349
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)