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
83
class GitPullResult(branch.PullResult):
84
"""Result of a pull from a Git branch."""
86
def _lookup_revno(self, revid):
87
if not isinstance(revid, bytes):
88
raise TypeError(revid)
89
# Try in source branch first, it'll be faster
90
with self.target_branch.lock_read():
91
return self.target_branch.revision_id_to_revno(revid)
95
return self._lookup_revno(self.old_revid)
99
return self._lookup_revno(self.new_revid)
102
class GitTags(tag.BasicTags):
103
"""Ref-based tag dictionary."""
105
def __init__(self, branch):
107
self.repository = branch.repository
109
def _merge_to_remote_git(self, target_repo, source_tag_refs, overwrite=False):
112
def get_changed_refs(old_refs):
114
for ref_name, tag_name, peeled, unpeeled in source_tag_refs.iteritems():
115
if old_refs.get(ref_name) == unpeeled:
117
elif overwrite or not ref_name in old_refs:
118
ret[ref_name] = unpeeled
119
updates[tag_name] = target_repo.lookup_foreign_revision_id(peeled)
123
self.repository.lookup_foreign_revision_id(peeled),
124
target_repo.lookup_foreign_revision_id(old_refs[ref_name])))
126
target_repo.controldir.send_pack(get_changed_refs, lambda have, want: [])
127
return updates, conflicts
129
def _merge_to_local_git(self, target_repo, source_tag_refs, overwrite=False):
132
for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
133
if target_repo._git.refs.get(ref_name) == unpeeled:
135
elif overwrite or not ref_name in target_repo._git.refs:
136
target_repo._git.refs[ref_name] = unpeeled or peeled
138
updates[tag_name] = self.repository.lookup_foreign_revision_id(peeled)
140
trace.warning('%s does not point to a valid object',
144
source_revid = self.repository.lookup_foreign_revision_id(peeled)
145
target_revid = target_repo.lookup_foreign_revision_id(
146
target_repo._git.refs[ref_name])
148
trace.warning('%s does not point to a valid object',
151
conflicts.append((tag_name, source_revid, target_revid))
152
return updates, conflicts
154
def _merge_to_git(self, to_tags, source_tag_refs, overwrite=False):
155
target_repo = to_tags.repository
156
if self.repository.has_same_location(target_repo):
159
if getattr(target_repo, "_git", None):
160
return self._merge_to_local_git(target_repo, source_tag_refs, overwrite)
162
return self._merge_to_remote_git(target_repo, source_tag_refs, overwrite)
164
to_tags.branch._tag_refs = None
166
def _merge_to_non_git(self, to_tags, source_tag_refs, overwrite=False):
167
unpeeled_map = defaultdict(set)
170
result = dict(to_tags.get_tag_dict())
171
for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
172
if unpeeled is not None:
173
unpeeled_map[peeled].add(unpeeled)
175
bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
176
except NotCommitError:
178
if result.get(tag_name) == bzr_revid:
180
elif tag_name not in result or overwrite:
181
result[tag_name] = bzr_revid
182
updates[tag_name] = bzr_revid
184
conflicts.append((tag_name, bzr_revid, result[n]))
185
to_tags._set_tag_dict(result)
186
if len(unpeeled_map) > 0:
187
map_file = UnpeelMap.from_repository(to_tags.branch.repository)
188
map_file.update(unpeeled_map)
189
map_file.save_in_repository(to_tags.branch.repository)
190
return updates, conflicts
192
def merge_to(self, to_tags, overwrite=False, ignore_master=False,
193
source_tag_refs=None):
194
"""See Tags.merge_to."""
195
if source_tag_refs is None:
196
source_tag_refs = self.branch.get_tag_refs()
199
if isinstance(to_tags, GitTags):
200
return self._merge_to_git(to_tags, source_tag_refs,
206
master = to_tags.branch.get_master_branch()
207
if master is not None:
210
updates, conflicts = self._merge_to_non_git(to_tags, source_tag_refs,
212
if master is not None:
213
extra_updates, extra_conflicts = self.merge_to(
214
master.tags, overwrite=overwrite,
215
source_tag_refs=source_tag_refs,
216
ignore_master=ignore_master)
217
updates.update(extra_updates)
218
conflicts += extra_conflicts
219
return updates, conflicts
221
if master is not None:
224
def get_tag_dict(self):
226
for (ref_name, tag_name, peeled, unpeeled) in self.branch.get_tag_refs():
228
bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
229
except NotCommitError:
232
ret[tag_name] = bzr_revid
236
class LocalGitTagDict(GitTags):
237
"""Dictionary with tags in a local repository."""
239
def __init__(self, branch):
240
super(LocalGitTagDict, self).__init__(branch)
241
self.refs = self.repository.controldir._git.refs
243
def _set_tag_dict(self, to_dict):
244
extra = set(self.refs.allkeys())
245
for k, revid in viewitems(to_dict):
246
name = tag_name_to_ref(k)
249
self.set_tag(k, revid)
252
del self.repository._git[name]
254
def set_tag(self, name, revid):
256
git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
257
except errors.NoSuchRevision:
258
raise errors.GhostTagsNotSupported(self)
259
self.refs[tag_name_to_ref(name)] = git_sha
260
self.branch._tag_refs = None
262
def delete_tag(self, name):
263
ref = tag_name_to_ref(name)
264
if not ref in self.refs:
265
raise errors.NoSuchTag(name)
267
self.branch._tag_refs = None
270
class GitBranchFormat(branch.BranchFormat):
272
def network_name(self):
275
def supports_tags(self):
278
def supports_leaving_lock(self):
281
def supports_tags_referencing_ghosts(self):
284
def tags_are_versioned(self):
287
def get_foreign_tests_branch_factory(self):
288
from .tests.test_branch import ForeignTestsBranchFactory
289
return ForeignTestsBranchFactory()
291
def make_tags(self, branch):
294
except AttributeError:
296
if getattr(branch.repository, "_git", None) is None:
297
from .remote import RemoteGitTagDict
298
return RemoteGitTagDict(branch)
300
return LocalGitTagDict(branch)
302
def initialize(self, a_controldir, name=None, repository=None,
303
append_revisions_only=None):
304
raise NotImplementedError(self.initialize)
306
def get_reference(self, controldir, name=None):
307
return controldir.get_branch_reference(name)
309
def set_reference(self, controldir, name, target):
310
return controldir.set_branch_reference(target, name)
313
class LocalGitBranchFormat(GitBranchFormat):
315
def get_format_description(self):
316
return 'Local Git Branch'
319
def _matchingcontroldir(self):
320
from .dir import LocalGitControlDirFormat
321
return LocalGitControlDirFormat()
323
def initialize(self, a_controldir, name=None, repository=None,
324
append_revisions_only=None):
325
from .dir import LocalGitDir
326
if not isinstance(a_controldir, LocalGitDir):
327
raise errors.IncompatibleFormat(self, a_controldir._format)
328
return a_controldir.create_branch(repository=repository, name=name,
329
append_revisions_only=append_revisions_only)
332
class GitBranch(ForeignBranch):
333
"""An adapter to git repositories for bzr Branch objects."""
336
def control_transport(self):
337
return self._control_transport
340
def user_transport(self):
341
return self._user_transport
343
def __init__(self, controldir, repository, ref, format):
344
self.repository = repository
345
self._format = format
346
self.controldir = controldir
347
self._lock_mode = None
349
super(GitBranch, self).__init__(repository.get_mapping())
352
self._user_transport = controldir.user_transport.clone('.')
353
self._control_transport = controldir.control_transport.clone('.')
354
self._tag_refs = None
357
self.name = ref_to_branch_name(ref)
360
if self.ref is not None:
361
params = {"ref": urlutils.escape(self.ref)}
364
params = {"branch": urlutils.escape(self.name)}
365
for k, v in params.items():
366
self._user_transport.set_segment_parameter(k, v)
367
self._control_transport.set_segment_parameter(k, v)
368
self.base = controldir.user_transport.base
370
def _get_checkout_format(self, lightweight=False):
371
"""Return the most suitable metadir for a checkout of this branch.
372
Weaves are used if this branch's repository uses weaves.
375
return controldir.format_registry.make_controldir("git")
377
return controldir.format_registry.make_controldir("default")
379
def get_child_submit_format(self):
380
"""Return the preferred format of submissions to this branch."""
381
ret = self.get_config_stack().get("child_submit_format")
386
def get_config(self):
387
return GitBranchConfig(self)
389
def get_config_stack(self):
390
return GitBranchStack(self)
392
def _get_nick(self, local=False, possible_master_transports=None):
393
"""Find the nick name for this branch.
397
cs = self.repository._git.get_config_stack()
399
return cs.get((b"branch", self.name.encode('utf-8')), b"nick").decode("utf-8")
402
return self.name or u"HEAD"
404
def _set_nick(self, nick):
405
cf = self.repository._git.get_config()
406
cf.set((b"branch", self.name.encode('utf-8')), b"nick", nick.encode("utf-8"))
409
self.repository._git._put_named_file('config', f.getvalue())
411
nick = property(_get_nick, _set_nick)
414
return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
417
def generate_revision_history(self, revid, last_rev=None, other_branch=None):
418
if last_rev is not None:
419
graph = self.repository.get_graph()
420
if not graph.is_ancestor(last_rev, revid):
421
# our previous tip is not merged into stop_revision
422
raise errors.DivergedBranches(self, other_branch)
424
self.set_last_revision(revid)
426
def lock_write(self, token=None):
427
if token is not None:
428
raise errors.TokenLockingNotSupported(self)
430
if self._lock_mode == 'r':
431
raise errors.ReadOnlyError(self)
432
self._lock_count += 1
435
self._lock_mode = 'w'
437
self.repository.lock_write()
438
return lock.LogicalLockResult(self.unlock)
440
def leave_lock_in_place(self):
441
raise NotImplementedError(self.leave_lock_in_place)
443
def dont_leave_lock_in_place(self):
444
raise NotImplementedError(self.dont_leave_lock_in_place)
446
def get_stacked_on_url(self):
447
# Git doesn't do stacking (yet...)
448
raise branch.UnstackableBranchFormat(self._format, self.base)
450
def _get_parent_location(self):
451
"""See Branch.get_parent()."""
452
# FIXME: Set "origin" url from .git/config ?
453
cs = self.repository._git.get_config_stack()
455
location = cs.get((b"remote", b'origin'), b"url")
461
ref = cs.get((b"remote", b"origin"), b"merge")
467
params['branch'] = urlutils.escape(ref_to_branch_name(ref))
469
params['ref'] = urlutils.quote_from_bytes(ref)
471
url = git_url_to_bzr_url(location.decode('utf-8'))
472
return urlutils.join_segment_parameters(url, params)
474
def set_parent(self, location):
475
# FIXME: Set "origin" url in .git/config ?
476
cs = self.repository._git.get_config()
477
this_url = urlutils.split_segment_parameters(self.user_url)[0]
478
target_url, target_params = urlutils.split_segment_parameters(location)
479
location = urlutils.relative_url(this_url, target_url)
480
cs.set((b"remote", b"origin"), b"url", location)
481
if 'branch' in target_params:
482
cs.set((b"remote", b"origin"), b"merge",
483
branch_name_to_ref(target_params['branch']))
484
elif 'ref' in target_params:
485
cs.set((b"remote", b"origin"), b"merge",
486
target_params['ref'])
488
# TODO(jelmer): Maybe unset rather than setting to HEAD?
489
cs.set((b"remote", b"origin"), b"merge", 'HEAD')
492
self.repository._git._put_named_file('config', f.getvalue())
494
def break_lock(self):
495
raise NotImplementedError(self.break_lock)
499
if self._lock_mode not in ('r', 'w'):
500
raise ValueError(self._lock_mode)
501
self._lock_count += 1
503
self._lock_mode = 'r'
505
self.repository.lock_read()
506
return lock.LogicalLockResult(self.unlock)
508
def peek_lock_mode(self):
509
return self._lock_mode
512
return (self._lock_mode is not None)
517
def _unlock_ref(self):
521
"""See Branch.unlock()."""
522
if self._lock_count == 0:
523
raise errors.LockNotHeld(self)
525
self._lock_count -= 1
526
if self._lock_count == 0:
527
if self._lock_mode == 'w':
529
self._lock_mode = None
530
self._clear_cached_state()
532
self.repository.unlock()
534
def get_physical_lock_status(self):
537
def last_revision(self):
538
with self.lock_read():
539
# perhaps should escape this ?
540
if self.head is None:
541
return revision.NULL_REVISION
542
return self.lookup_foreign_revision_id(self.head)
544
def _basic_push(self, target, overwrite=False, stop_revision=None):
545
return branch.InterBranch.get(self, target)._basic_push(
546
overwrite, stop_revision)
548
def lookup_foreign_revision_id(self, foreign_revid):
550
return self.repository.lookup_foreign_revision_id(foreign_revid,
554
return self.mapping.revision_id_foreign_to_bzr(foreign_revid)
556
def lookup_bzr_revision_id(self, revid):
557
return self.repository.lookup_bzr_revision_id(
558
revid, mapping=self.mapping)
560
def get_unshelver(self, tree):
561
raise errors.StoringUncommittedNotSupported(self)
563
def _clear_cached_state(self):
564
super(GitBranch, self)._clear_cached_state()
565
self._tag_refs = None
567
def _iter_tag_refs(self, refs):
568
"""Iterate over the tag refs.
570
:param refs: Refs dictionary (name -> git sha1)
571
:return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
573
raise NotImplementedError(self._iter_tag_refs)
575
def get_tag_refs(self):
576
with self.lock_read():
577
if self._tag_refs is None:
578
self._tag_refs = list(self._iter_tag_refs())
579
return self._tag_refs
582
class LocalGitBranch(GitBranch):
583
"""A local Git branch."""
585
def __init__(self, controldir, repository, ref):
586
super(LocalGitBranch, self).__init__(controldir, repository, ref,
587
LocalGitBranchFormat())
589
def create_checkout(self, to_location, revision_id=None, lightweight=False,
590
accelerator_tree=None, hardlink=False):
591
t = transport.get_transport(to_location)
593
format = self._get_checkout_format(lightweight=lightweight)
594
checkout = format.initialize_on_transport(t)
596
from_branch = checkout.set_branch_reference(target_branch=self)
598
policy = checkout.determine_repository_policy()
599
repo = policy.acquire_repository()[0]
601
checkout_branch = checkout.create_branch()
602
checkout_branch.bind(self)
603
checkout_branch.pull(self, stop_revision=revision_id)
605
return checkout.create_workingtree(revision_id,
606
from_branch=from_branch, hardlink=hardlink)
609
self._ref_lock = self.repository._git.refs.lock_ref(self.ref)
611
def _unlock_ref(self):
612
self._ref_lock.unlock()
614
def break_lock(self):
615
self.repository._git.refs.unlock_ref(self.ref)
617
def fetch(self, from_branch, last_revision=None, limit=None):
618
return branch.InterBranch.get(from_branch, self).fetch(
619
stop_revision=last_revision, limit=limit)
621
def _gen_revision_history(self):
622
if self.head is None:
624
last_revid = self.last_revision()
625
graph = self.repository.get_graph()
627
ret = list(graph.iter_lefthand_ancestry(last_revid,
628
(revision.NULL_REVISION, )))
629
except errors.RevisionNotPresent as e:
630
raise errors.GhostRevisionsHaveNoRevno(last_revid, e.revision_id)
636
return self.repository._git.refs[self.ref]
640
def _read_last_revision_info(self):
641
last_revid = self.last_revision()
642
graph = self.repository.get_graph()
644
revno = graph.find_distance_to_null(last_revid,
645
[(revision.NULL_REVISION, 0)])
646
except errors.GhostRevisionsHaveNoRevno:
648
return revno, last_revid
650
def set_last_revision_info(self, revno, revision_id):
651
self.set_last_revision(revision_id)
652
self._last_revision_info_cache = revno, revision_id
654
def set_last_revision(self, revid):
655
if not revid or not isinstance(revid, bytes):
656
raise errors.InvalidRevisionId(revision_id=revid, branch=self)
657
if revid == NULL_REVISION:
660
(newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
661
if self.mapping is None:
663
self._set_head(newhead)
665
def _set_head(self, value):
666
if value == ZERO_SHA:
667
raise ValueError(value)
670
del self.repository._git.refs[self.ref]
672
self.repository._git.refs[self.ref] = self._head
673
self._clear_cached_state()
675
head = property(_get_head, _set_head)
677
def get_push_location(self):
678
"""See Branch.get_push_location."""
679
push_loc = self.get_config_stack().get('push_location')
682
def set_push_location(self, location):
683
"""See Branch.set_push_location."""
684
self.get_config().set_user_option('push_location', location,
685
store=config.STORE_LOCATION)
687
def supports_tags(self):
690
def store_uncommitted(self, creator):
691
raise errors.StoringUncommittedNotSupported(self)
693
def _iter_tag_refs(self):
694
"""Iterate over the tag refs.
696
:param refs: Refs dictionary (name -> git sha1)
697
:return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
699
refs = self.repository._git.refs
700
for ref_name, unpeeled in viewitems(refs.as_dict()):
702
tag_name = ref_to_tag_name(ref_name)
703
except (ValueError, UnicodeDecodeError):
705
peeled = refs.get_peeled(ref_name)
708
if not isinstance(tag_name, text_type):
709
raise TypeError(tag_name)
710
yield (ref_name, tag_name, peeled, unpeeled)
712
def create_memorytree(self):
713
from .memorytree import GitMemoryTree
714
return GitMemoryTree(self, self.repository._git.object_store, self.head)
716
def reference_parent(self, path, file_id=None, possible_transports=None):
717
"""Return the parent branch for a tree-reference file_id
719
:param path: The path of the file_id in the tree
720
:param file_id: Optional file_id of the tree reference
721
:return: A branch associated with the file_id
723
# FIXME should provide multiple branches, based on config
724
url = urlutils.join(self.user_url, path)
725
return branch.Branch.open(
727
possible_transports=possible_transports)
731
def _quick_lookup_revno(local_branch, remote_branch, revid):
732
if not isinstance(revid, bytes):
733
raise TypeError(revid)
734
# Try in source branch first, it'll be faster
735
with local_branch.lock_read():
737
return local_branch.revision_id_to_revno(revid)
738
except errors.NoSuchRevision:
739
graph = local_branch.repository.get_graph()
741
return graph.find_distance_to_null(revid,
742
[(revision.NULL_REVISION, 0)])
743
except errors.GhostRevisionsHaveNoRevno:
744
# FIXME: Check using graph.find_distance_to_null() ?
745
with remote_branch.lock_read():
746
return remote_branch.revision_id_to_revno(revid)
749
class GitBranchPullResult(branch.PullResult):
752
super(GitBranchPullResult, self).__init__()
753
self.new_git_head = None
754
self._old_revno = None
755
self._new_revno = None
757
def report(self, to_file):
759
if self.old_revid == self.new_revid:
760
to_file.write('No revisions to pull.\n')
761
elif self.new_git_head is not None:
762
to_file.write('Now on revision %d (git sha: %s).\n' %
763
(self.new_revno, self.new_git_head))
765
to_file.write('Now on revision %d.\n' % (self.new_revno,))
766
self._show_tag_conficts(to_file)
768
def _lookup_revno(self, revid):
769
return _quick_lookup_revno(self.target_branch, self.source_branch,
772
def _get_old_revno(self):
773
if self._old_revno is not None:
774
return self._old_revno
775
return self._lookup_revno(self.old_revid)
777
def _set_old_revno(self, revno):
778
self._old_revno = revno
780
old_revno = property(_get_old_revno, _set_old_revno)
782
def _get_new_revno(self):
783
if self._new_revno is not None:
784
return self._new_revno
785
return self._lookup_revno(self.new_revid)
787
def _set_new_revno(self, revno):
788
self._new_revno = revno
790
new_revno = property(_get_new_revno, _set_new_revno)
793
class GitBranchPushResult(branch.BranchPushResult):
795
def _lookup_revno(self, revid):
796
return _quick_lookup_revno(self.source_branch, self.target_branch,
801
return self._lookup_revno(self.old_revid)
805
new_original_revno = getattr(self, "new_original_revno", None)
806
if new_original_revno:
807
return new_original_revno
808
if getattr(self, "new_original_revid", None) is not None:
809
return self._lookup_revno(self.new_original_revid)
810
return self._lookup_revno(self.new_revid)
813
class InterFromGitBranch(branch.GenericInterBranch):
814
"""InterBranch implementation that pulls from Git into bzr."""
817
def _get_branch_formats_to_test():
819
default_format = branch.format_registry.get_default()
820
except AttributeError:
821
default_format = branch.BranchFormat._default_format
822
from .remote import RemoteGitBranchFormat
824
(RemoteGitBranchFormat(), default_format),
825
(LocalGitBranchFormat(), default_format)]
828
def _get_interrepo(self, source, target):
829
return _mod_repository.InterRepository.get(source.repository, target.repository)
832
def is_compatible(cls, source, target):
833
if not isinstance(source, GitBranch):
835
if isinstance(target, GitBranch):
836
# InterLocalGitRemoteGitBranch or InterToGitBranch should be used
838
if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
839
# fetch_objects is necessary for this to work
843
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
844
self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
846
def fetch_objects(self, stop_revision, fetch_tags, limit=None):
847
interrepo = self._get_interrepo(self.source, self.target)
848
if fetch_tags is None:
849
c = self.source.get_config_stack()
850
fetch_tags = c.get('branch.fetch_tags')
851
def determine_wants(heads):
852
if stop_revision is None:
854
head = heads[self.source.ref]
856
self._last_revid = revision.NULL_REVISION
858
self._last_revid = self.source.lookup_foreign_revision_id(head)
860
self._last_revid = stop_revision
861
real = interrepo.get_determine_wants_revids(
862
[self._last_revid], include_tags=fetch_tags)
864
pack_hint, head, refs = interrepo.fetch_objects(
865
determine_wants, self.source.mapping, limit=limit)
866
if (pack_hint is not None and
867
self.target.repository._format.pack_compresses):
868
self.target.repository.pack(hint=pack_hint)
871
def _update_revisions(self, stop_revision=None, overwrite=False):
872
head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
874
prev_last_revid = None
876
prev_last_revid = self.target.last_revision()
877
self.target.generate_revision_history(self._last_revid,
878
last_rev=prev_last_revid, other_branch=self.source)
881
def _basic_pull(self, stop_revision, overwrite, run_hooks,
882
_override_hook_target, _hook_master):
883
if overwrite is True:
884
overwrite = set(["history", "tags"])
887
result = GitBranchPullResult()
888
result.source_branch = self.source
889
if _override_hook_target is None:
890
result.target_branch = self.target
892
result.target_branch = _override_hook_target
893
with self.target.lock_write(), self.source.lock_read():
894
# We assume that during 'pull' the target repository is closer than
896
(result.old_revno, result.old_revid) = \
897
self.target.last_revision_info()
898
result.new_git_head, remote_refs = self._update_revisions(
899
stop_revision, overwrite=("history" in overwrite))
900
tags_ret = self.source.tags.merge_to(
901
self.target.tags, ("tags" in overwrite), ignore_master=True)
902
if isinstance(tags_ret, tuple):
903
result.tag_updates, result.tag_conflicts = tags_ret
905
result.tag_conflicts = tags_ret
906
(result.new_revno, result.new_revid) = \
907
self.target.last_revision_info()
909
result.master_branch = _hook_master
910
result.local_branch = result.target_branch
912
result.master_branch = result.target_branch
913
result.local_branch = None
915
for hook in branch.Branch.hooks['post_pull']:
919
def pull(self, overwrite=False, stop_revision=None,
920
possible_transports=None, _hook_master=None, run_hooks=True,
921
_override_hook_target=None, local=False):
924
:param _hook_master: Private parameter - set the branch to
925
be supplied as the master to pull hooks.
926
:param run_hooks: Private parameter - if false, this branch
927
is being called because it's the master of the primary branch,
928
so it should not run its hooks.
929
:param _override_hook_target: Private parameter - set the branch to be
930
supplied as the target_branch to pull hooks.
932
# This type of branch can't be bound.
933
bound_location = self.target.get_bound_location()
934
if local and not bound_location:
935
raise errors.LocalRequiresBoundBranch()
937
source_is_master = False
938
self.source.lock_read()
940
# bound_location comes from a config file, some care has to be
941
# taken to relate it to source.user_url
942
normalized = urlutils.normalize_url(bound_location)
944
relpath = self.source.user_transport.relpath(normalized)
945
source_is_master = (relpath == '')
946
except (errors.PathNotChild, urlutils.InvalidURL):
947
source_is_master = False
948
if not local and bound_location and not source_is_master:
949
# not pulling from master, so we need to update master.
950
master_branch = self.target.get_master_branch(possible_transports)
951
master_branch.lock_write()
955
# pull from source into master.
956
master_branch.pull(self.source, overwrite, stop_revision,
958
result = self._basic_pull(stop_revision, overwrite, run_hooks,
959
_override_hook_target, _hook_master=master_branch)
964
master_branch.unlock()
967
def _basic_push(self, overwrite, stop_revision):
968
if overwrite is True:
969
overwrite = set(["history", "tags"])
972
result = branch.BranchPushResult()
973
result.source_branch = self.source
974
result.target_branch = self.target
975
result.old_revno, result.old_revid = self.target.last_revision_info()
976
result.new_git_head, remote_refs = self._update_revisions(
977
stop_revision, overwrite=("history" in overwrite))
978
tags_ret = self.source.tags.merge_to(self.target.tags,
979
"tags" in overwrite, ignore_master=True)
980
(result.tag_updates, result.tag_conflicts) = tags_ret
981
result.new_revno, result.new_revid = self.target.last_revision_info()
985
class InterGitBranch(branch.GenericInterBranch):
986
"""InterBranch implementation that pulls between Git branches."""
988
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
989
raise NotImplementedError(self.fetch)
992
class InterLocalGitRemoteGitBranch(InterGitBranch):
993
"""InterBranch that copies from a local to a remote git branch."""
996
def _get_branch_formats_to_test():
997
from .remote import RemoteGitBranchFormat
999
(LocalGitBranchFormat(), RemoteGitBranchFormat())]
1002
def is_compatible(self, source, target):
1003
from .remote import RemoteGitBranch
1004
return (isinstance(source, LocalGitBranch) and
1005
isinstance(target, RemoteGitBranch))
1007
def _basic_push(self, overwrite, stop_revision):
1008
result = GitBranchPushResult()
1009
result.source_branch = self.source
1010
result.target_branch = self.target
1011
if stop_revision is None:
1012
stop_revision = self.source.last_revision()
1013
def get_changed_refs(old_refs):
1014
old_ref = old_refs.get(self.target.ref, None)
1016
result.old_revid = revision.NULL_REVISION
1018
result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
1019
new_ref = self.source.repository.lookup_bzr_revision_id(stop_revision)[0]
1021
if remote_divergence(old_ref, new_ref, self.source.repository._git.object_store):
1022
raise errors.DivergedBranches(self.source, self.target)
1023
refs = { self.target.ref: new_ref }
1024
result.new_revid = stop_revision
1025
for name, sha in viewitems(self.source.repository._git.refs.as_dict(b"refs/tags")):
1026
refs[tag_name_to_ref(name)] = sha
1028
self.target.repository.send_pack(get_changed_refs,
1029
self.source.repository._git.object_store.generate_pack_data)
1033
class InterGitLocalGitBranch(InterGitBranch):
1034
"""InterBranch that copies from a remote to a local git branch."""
1037
def _get_branch_formats_to_test():
1038
from .remote import RemoteGitBranchFormat
1040
(RemoteGitBranchFormat(), LocalGitBranchFormat()),
1041
(LocalGitBranchFormat(), LocalGitBranchFormat())]
1044
def is_compatible(self, source, target):
1045
return (isinstance(source, GitBranch) and
1046
isinstance(target, LocalGitBranch))
1048
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
1049
interrepo = _mod_repository.InterRepository.get(self.source.repository,
1050
self.target.repository)
1051
if stop_revision is None:
1052
stop_revision = self.source.last_revision()
1053
determine_wants = interrepo.get_determine_wants_revids(
1054
[stop_revision], include_tags=fetch_tags)
1055
interrepo.fetch_objects(determine_wants, limit=limit)
1057
def _basic_push(self, overwrite=False, stop_revision=None):
1058
if overwrite is True:
1059
overwrite = set(["history", "tags"])
1062
result = GitBranchPushResult()
1063
result.source_branch = self.source
1064
result.target_branch = self.target
1065
result.old_revid = self.target.last_revision()
1066
refs, stop_revision = self.update_refs(stop_revision)
1067
self.target.generate_revision_history(stop_revision,
1068
(result.old_revid if ("history" not in overwrite) else None),
1069
other_branch=self.source)
1070
tags_ret = self.source.tags.merge_to(self.target.tags,
1071
source_tag_refs=remote_refs_dict_to_tag_refs(refs),
1072
overwrite=("tags" in overwrite))
1073
if isinstance(tags_ret, tuple):
1074
(result.tag_updates, result.tag_conflicts) = tags_ret
1076
result.tag_conflicts = tags_ret
1077
result.new_revid = self.target.last_revision()
1080
def update_refs(self, stop_revision=None):
1081
interrepo = _mod_repository.InterRepository.get(
1082
self.source.repository, self.target.repository)
1083
c = self.source.get_config_stack()
1084
fetch_tags = c.get('branch.fetch_tags')
1086
if stop_revision is None:
1087
refs = interrepo.fetch(branches=[self.source.ref], include_tags=fetch_tags)
1089
head = refs[self.source.ref]
1091
stop_revision = revision.NULL_REVISION
1093
stop_revision = self.target.lookup_foreign_revision_id(head)
1095
refs = interrepo.fetch(revision_id=stop_revision, include_tags=fetch_tags)
1096
return refs, stop_revision
1098
def pull(self, stop_revision=None, overwrite=False,
1099
possible_transports=None, run_hooks=True, local=False):
1100
# This type of branch can't be bound.
1102
raise errors.LocalRequiresBoundBranch()
1103
if overwrite is True:
1104
overwrite = set(["history", "tags"])
1108
result = GitPullResult()
1109
result.source_branch = self.source
1110
result.target_branch = self.target
1111
with self.target.lock_write(), self.source.lock_read():
1112
result.old_revid = self.target.last_revision()
1113
refs, stop_revision = self.update_refs(stop_revision)
1114
self.target.generate_revision_history(stop_revision,
1115
(result.old_revid if ("history" not in overwrite) else None),
1116
other_branch=self.source)
1117
tags_ret = self.source.tags.merge_to(self.target.tags,
1118
overwrite=("tags" in overwrite),
1119
source_tag_refs=remote_refs_dict_to_tag_refs(refs))
1120
if isinstance(tags_ret, tuple):
1121
(result.tag_updates, result.tag_conflicts) = tags_ret
1123
result.tag_conflicts = tags_ret
1124
result.new_revid = self.target.last_revision()
1125
result.local_branch = None
1126
result.master_branch = result.target_branch
1128
for hook in branch.Branch.hooks['post_pull']:
1133
class InterToGitBranch(branch.GenericInterBranch):
1134
"""InterBranch implementation that pulls from a non-bzr into a Git branch."""
1136
def __init__(self, source, target):
1137
super(InterToGitBranch, self).__init__(source, target)
1138
self.interrepo = _mod_repository.InterRepository.get(source.repository,
1142
def _get_branch_formats_to_test():
1144
default_format = branch.format_registry.get_default()
1145
except AttributeError:
1146
default_format = branch.BranchFormat._default_format
1147
from .remote import RemoteGitBranchFormat
1149
(default_format, LocalGitBranchFormat()),
1150
(default_format, RemoteGitBranchFormat())]
1153
def is_compatible(self, source, target):
1154
return (not isinstance(source, GitBranch) and
1155
isinstance(target, GitBranch))
1157
def _get_new_refs(self, stop_revision=None, fetch_tags=None):
1158
if not self.source.is_locked():
1159
raise errors.ObjectNotLocked(self.source)
1160
if stop_revision is None:
1161
(stop_revno, stop_revision) = self.source.last_revision_info()
1163
stop_revno = self.source.revision_id_to_revno(stop_revision)
1164
if not isinstance(stop_revision, bytes):
1165
raise TypeError(stop_revision)
1166
main_ref = self.target.ref
1167
refs = { main_ref: (None, stop_revision) }
1168
if fetch_tags is None:
1169
c = self.source.get_config_stack()
1170
fetch_tags = c.get('branch.fetch_tags')
1171
for name, revid in viewitems(self.source.tags.get_tag_dict()):
1172
if self.source.repository.has_revision(revid):
1173
ref = tag_name_to_ref(name)
1174
if not check_ref_format(ref):
1175
warning("skipping tag with invalid characters %s (%s)",
1179
# FIXME: Skip tags that are not in the ancestry
1180
refs[ref] = (None, revid)
1181
return refs, main_ref, (stop_revno, stop_revision)
1183
def _update_refs(self, result, old_refs, new_refs, overwrite):
1184
mutter("updating refs. old refs: %r, new refs: %r",
1186
result.tag_updates = {}
1187
result.tag_conflicts = []
1188
ret = dict(old_refs)
1189
def ref_equals(refs, ref, git_sha, revid):
1194
if (value[0] is not None and
1195
git_sha is not None and
1196
value[0] == git_sha):
1198
if (value[1] is not None and
1199
revid is not None and
1202
# FIXME: If one side only has the git sha available and the other only
1203
# has the bzr revid, then this will cause us to show a tag as updated
1204
# that hasn't actually been updated.
1206
# FIXME: Check for diverged branches
1207
for ref, (git_sha, revid) in viewitems(new_refs):
1208
if ref_equals(ret, ref, git_sha, revid):
1209
# Already up to date
1211
git_sha = old_refs[ref][0]
1213
revid = old_refs[ref][1]
1214
ret[ref] = new_refs[ref] = (git_sha, revid)
1215
elif ref not in ret or overwrite:
1217
tag_name = ref_to_tag_name(ref)
1221
result.tag_updates[tag_name] = revid
1222
ret[ref] = (git_sha, revid)
1224
# FIXME: Check diverged
1228
name = ref_to_tag_name(ref)
1232
result.tag_conflicts.append((name, revid, ret[name][1]))
1234
ret[ref] = (git_sha, revid)
1237
def fetch(self, stop_revision=None, fetch_tags=None, lossy=False, limit=None):
1238
if stop_revision is None:
1239
stop_revision = self.source.last_revision()
1242
for k, v in viewitems(self.source.tags.get_tag_dict()):
1243
ret.append((None, v))
1244
ret.append((None, stop_revision))
1246
self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
1247
except NoPushSupport:
1248
raise errors.NoRoundtrippingSupport(self.source, self.target)
1250
def pull(self, overwrite=False, stop_revision=None, local=False,
1251
possible_transports=None, run_hooks=True):
1252
result = GitBranchPullResult()
1253
result.source_branch = self.source
1254
result.target_branch = self.target
1255
with self.source.lock_read(), self.target.lock_write():
1256
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1258
def update_refs(old_refs):
1259
return self._update_refs(result, old_refs, new_refs, overwrite)
1261
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1262
update_refs, lossy=False)
1263
except NoPushSupport:
1264
raise errors.NoRoundtrippingSupport(self.source, self.target)
1265
(old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1266
if result.old_revid is None:
1267
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1268
result.new_revid = new_refs[main_ref][1]
1269
result.local_branch = None
1270
result.master_branch = self.target
1272
for hook in branch.Branch.hooks['post_pull']:
1276
def push(self, overwrite=False, stop_revision=None, lossy=False,
1277
_override_hook_source_branch=None):
1278
result = GitBranchPushResult()
1279
result.source_branch = self.source
1280
result.target_branch = self.target
1281
result.local_branch = None
1282
result.master_branch = result.target_branch
1283
with self.source.lock_read(), self.target.lock_write():
1284
new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
1285
def update_refs(old_refs):
1286
return self._update_refs(result, old_refs, new_refs, overwrite)
1288
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1289
update_refs, lossy=lossy, overwrite=overwrite)
1290
except NoPushSupport:
1291
raise errors.NoRoundtrippingSupport(self.source, self.target)
1292
(old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1293
if result.old_revid is None:
1294
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1295
result.new_revid = new_refs[main_ref][1]
1296
(result.new_original_revno, result.new_original_revid) = stop_revinfo
1297
for hook in branch.Branch.hooks['post_push']:
1302
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
1303
branch.InterBranch.register_optimiser(InterFromGitBranch)
1304
branch.InterBranch.register_optimiser(InterToGitBranch)
1305
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)