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, 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(
124
self.repository.lookup_foreign_revision_id(peeled),
125
target_repo.lookup_foreign_revision_id(old_refs[ref_name])))
127
target_repo.controldir.send_pack(
128
get_changed_refs, lambda have, want: [])
129
return updates, conflicts
131
def _merge_to_local_git(self, target_repo, source_tag_refs, overwrite=False):
134
for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
135
if target_repo._git.refs.get(ref_name) == unpeeled:
137
elif overwrite or not ref_name in target_repo._git.refs:
138
target_repo._git.refs[ref_name] = unpeeled or peeled
139
updates[tag_name] = self.repository.lookup_foreign_revision_id(
142
source_revid = self.repository.lookup_foreign_revision_id(
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')),
407
b"nick", nick.encode("utf-8"))
410
self.repository._git._put_named_file('config', f.getvalue())
412
nick = property(_get_nick, _set_nick)
415
return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
418
def generate_revision_history(self, revid, last_rev=None, other_branch=None):
419
if last_rev is not None:
420
graph = self.repository.get_graph()
421
if not graph.is_ancestor(last_rev, revid):
422
# our previous tip is not merged into stop_revision
423
raise errors.DivergedBranches(self, other_branch)
425
self.set_last_revision(revid)
427
def lock_write(self, token=None):
428
if token is not None:
429
raise errors.TokenLockingNotSupported(self)
431
if self._lock_mode == 'r':
432
raise errors.ReadOnlyError(self)
433
self._lock_count += 1
436
self._lock_mode = 'w'
438
self.repository.lock_write()
439
return lock.LogicalLockResult(self.unlock)
441
def leave_lock_in_place(self):
442
raise NotImplementedError(self.leave_lock_in_place)
444
def dont_leave_lock_in_place(self):
445
raise NotImplementedError(self.dont_leave_lock_in_place)
447
def get_stacked_on_url(self):
448
# Git doesn't do stacking (yet...)
449
raise branch.UnstackableBranchFormat(self._format, self.base)
451
def _get_parent_location(self):
452
"""See Branch.get_parent()."""
453
# FIXME: Set "origin" url from .git/config ?
454
cs = self.repository._git.get_config_stack()
456
location = cs.get((b"remote", b'origin'), b"url")
462
ref = cs.get((b"remote", b"origin"), b"merge")
468
params['branch'] = urlutils.escape(ref_to_branch_name(ref))
470
params['ref'] = urlutils.quote_from_bytes(ref)
472
url = git_url_to_bzr_url(location.decode('utf-8'))
473
return urlutils.join_segment_parameters(url, params)
475
def set_parent(self, location):
476
# FIXME: Set "origin" url in .git/config ?
477
cs = self.repository._git.get_config()
478
this_url = urlutils.split_segment_parameters(self.user_url)[0]
479
target_url, target_params = urlutils.split_segment_parameters(location)
480
location = urlutils.relative_url(this_url, target_url)
481
cs.set((b"remote", b"origin"), b"url", location)
482
if 'branch' in target_params:
483
cs.set((b"remote", b"origin"), b"merge",
484
branch_name_to_ref(target_params['branch']))
485
elif 'ref' in target_params:
486
cs.set((b"remote", b"origin"), b"merge",
487
target_params['ref'])
489
# TODO(jelmer): Maybe unset rather than setting to HEAD?
490
cs.set((b"remote", b"origin"), b"merge", 'HEAD')
493
self.repository._git._put_named_file('config', f.getvalue())
495
def break_lock(self):
496
raise NotImplementedError(self.break_lock)
500
if self._lock_mode not in ('r', 'w'):
501
raise ValueError(self._lock_mode)
502
self._lock_count += 1
504
self._lock_mode = 'r'
506
self.repository.lock_read()
507
return lock.LogicalLockResult(self.unlock)
509
def peek_lock_mode(self):
510
return self._lock_mode
513
return (self._lock_mode is not None)
518
def _unlock_ref(self):
522
"""See Branch.unlock()."""
523
if self._lock_count == 0:
524
raise errors.LockNotHeld(self)
526
self._lock_count -= 1
527
if self._lock_count == 0:
528
if self._lock_mode == 'w':
530
self._lock_mode = None
531
self._clear_cached_state()
533
self.repository.unlock()
535
def get_physical_lock_status(self):
538
def last_revision(self):
539
with self.lock_read():
540
# perhaps should escape this ?
541
if self.head is None:
542
return revision.NULL_REVISION
543
return self.lookup_foreign_revision_id(self.head)
545
def _basic_push(self, target, overwrite=False, stop_revision=None):
546
return branch.InterBranch.get(self, target)._basic_push(
547
overwrite, stop_revision)
549
def lookup_foreign_revision_id(self, foreign_revid):
551
return self.repository.lookup_foreign_revision_id(foreign_revid,
555
return self.mapping.revision_id_foreign_to_bzr(foreign_revid)
557
def lookup_bzr_revision_id(self, revid):
558
return self.repository.lookup_bzr_revision_id(
559
revid, mapping=self.mapping)
561
def get_unshelver(self, tree):
562
raise errors.StoringUncommittedNotSupported(self)
564
def _clear_cached_state(self):
565
super(GitBranch, self)._clear_cached_state()
566
self._tag_refs = None
568
def _iter_tag_refs(self, refs):
569
"""Iterate over the tag refs.
571
:param refs: Refs dictionary (name -> git sha1)
572
:return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
574
raise NotImplementedError(self._iter_tag_refs)
576
def get_tag_refs(self):
577
with self.lock_read():
578
if self._tag_refs is None:
579
self._tag_refs = list(self._iter_tag_refs())
580
return self._tag_refs
583
class LocalGitBranch(GitBranch):
584
"""A local Git branch."""
586
def __init__(self, controldir, repository, ref):
587
super(LocalGitBranch, self).__init__(controldir, repository, ref,
588
LocalGitBranchFormat())
590
def create_checkout(self, to_location, revision_id=None, lightweight=False,
591
accelerator_tree=None, hardlink=False):
592
t = transport.get_transport(to_location)
594
format = self._get_checkout_format(lightweight=lightweight)
595
checkout = format.initialize_on_transport(t)
597
from_branch = checkout.set_branch_reference(target_branch=self)
599
policy = checkout.determine_repository_policy()
600
repo = policy.acquire_repository()[0]
602
checkout_branch = checkout.create_branch()
603
checkout_branch.bind(self)
604
checkout_branch.pull(self, stop_revision=revision_id)
606
return checkout.create_workingtree(revision_id,
607
from_branch=from_branch, hardlink=hardlink)
610
self._ref_lock = self.repository._git.refs.lock_ref(self.ref)
612
def _unlock_ref(self):
613
self._ref_lock.unlock()
615
def break_lock(self):
616
self.repository._git.refs.unlock_ref(self.ref)
618
def fetch(self, from_branch, last_revision=None, limit=None):
619
return branch.InterBranch.get(from_branch, self).fetch(
620
stop_revision=last_revision, limit=limit)
622
def _gen_revision_history(self):
623
if self.head is None:
625
last_revid = self.last_revision()
626
graph = self.repository.get_graph()
628
ret = list(graph.iter_lefthand_ancestry(last_revid,
629
(revision.NULL_REVISION, )))
630
except errors.RevisionNotPresent as e:
631
raise errors.GhostRevisionsHaveNoRevno(last_revid, e.revision_id)
637
return self.repository._git.refs[self.ref]
641
def _read_last_revision_info(self):
642
last_revid = self.last_revision()
643
graph = self.repository.get_graph()
644
revno = graph.find_distance_to_null(last_revid,
645
[(revision.NULL_REVISION, 0)])
646
return revno, last_revid
648
def set_last_revision_info(self, revno, revision_id):
649
self.set_last_revision(revision_id)
650
self._last_revision_info_cache = revno, revision_id
652
def set_last_revision(self, revid):
653
if not revid or not isinstance(revid, bytes):
654
raise errors.InvalidRevisionId(revision_id=revid, branch=self)
655
if revid == NULL_REVISION:
658
(newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
659
if self.mapping is None:
661
self._set_head(newhead)
663
def _set_head(self, value):
664
if value == ZERO_SHA:
665
raise ValueError(value)
668
del self.repository._git.refs[self.ref]
670
self.repository._git.refs[self.ref] = self._head
671
self._clear_cached_state()
673
head = property(_get_head, _set_head)
675
def get_push_location(self):
676
"""See Branch.get_push_location."""
677
push_loc = self.get_config_stack().get('push_location')
680
def set_push_location(self, location):
681
"""See Branch.set_push_location."""
682
self.get_config().set_user_option('push_location', location,
683
store=config.STORE_LOCATION)
685
def supports_tags(self):
688
def store_uncommitted(self, creator):
689
raise errors.StoringUncommittedNotSupported(self)
691
def _iter_tag_refs(self):
692
"""Iterate over the tag refs.
694
:param refs: Refs dictionary (name -> git sha1)
695
:return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
697
refs = self.repository._git.refs
698
for ref_name, unpeeled in viewitems(refs.as_dict()):
700
tag_name = ref_to_tag_name(ref_name)
701
except (ValueError, UnicodeDecodeError):
703
peeled = refs.get_peeled(ref_name)
706
if not isinstance(tag_name, text_type):
707
raise TypeError(tag_name)
708
yield (ref_name, tag_name, peeled, unpeeled)
710
def create_memorytree(self):
711
from .memorytree import GitMemoryTree
712
return GitMemoryTree(self, self.repository._git.object_store, self.head)
714
def reference_parent(self, path, file_id=None, possible_transports=None):
715
"""Return the parent branch for a tree-reference file_id
717
:param path: The path of the file_id in the tree
718
:param file_id: Optional file_id of the tree reference
719
:return: A branch associated with the file_id
721
# FIXME should provide multiple branches, based on config
722
url = urlutils.join(self.user_url, path)
723
return branch.Branch.open(
725
possible_transports=possible_transports)
728
def _quick_lookup_revno(local_branch, remote_branch, revid):
729
if not isinstance(revid, bytes):
730
raise TypeError(revid)
731
# Try in source branch first, it'll be faster
732
with local_branch.lock_read():
734
return local_branch.revision_id_to_revno(revid)
735
except errors.NoSuchRevision:
736
graph = local_branch.repository.get_graph()
738
return graph.find_distance_to_null(revid,
739
[(revision.NULL_REVISION, 0)])
740
except errors.GhostRevisionsHaveNoRevno:
741
# FIXME: Check using graph.find_distance_to_null() ?
742
with remote_branch.lock_read():
743
return remote_branch.revision_id_to_revno(revid)
746
class GitBranchPullResult(branch.PullResult):
749
super(GitBranchPullResult, self).__init__()
750
self.new_git_head = None
751
self._old_revno = None
752
self._new_revno = None
754
def report(self, to_file):
756
if self.old_revid == self.new_revid:
757
to_file.write('No revisions to pull.\n')
758
elif self.new_git_head is not None:
759
to_file.write('Now on revision %d (git sha: %s).\n' %
760
(self.new_revno, self.new_git_head))
762
to_file.write('Now on revision %d.\n' % (self.new_revno,))
763
self._show_tag_conficts(to_file)
765
def _lookup_revno(self, revid):
766
return _quick_lookup_revno(self.target_branch, self.source_branch,
769
def _get_old_revno(self):
770
if self._old_revno is not None:
771
return self._old_revno
772
return self._lookup_revno(self.old_revid)
774
def _set_old_revno(self, revno):
775
self._old_revno = revno
777
old_revno = property(_get_old_revno, _set_old_revno)
779
def _get_new_revno(self):
780
if self._new_revno is not None:
781
return self._new_revno
782
return self._lookup_revno(self.new_revid)
784
def _set_new_revno(self, revno):
785
self._new_revno = revno
787
new_revno = property(_get_new_revno, _set_new_revno)
790
class GitBranchPushResult(branch.BranchPushResult):
792
def _lookup_revno(self, revid):
793
return _quick_lookup_revno(self.source_branch, self.target_branch,
798
return self._lookup_revno(self.old_revid)
802
new_original_revno = getattr(self, "new_original_revno", None)
803
if new_original_revno:
804
return new_original_revno
805
if getattr(self, "new_original_revid", None) is not None:
806
return self._lookup_revno(self.new_original_revid)
807
return self._lookup_revno(self.new_revid)
810
class InterFromGitBranch(branch.GenericInterBranch):
811
"""InterBranch implementation that pulls from Git into bzr."""
814
def _get_branch_formats_to_test():
816
default_format = branch.format_registry.get_default()
817
except AttributeError:
818
default_format = branch.BranchFormat._default_format
819
from .remote import RemoteGitBranchFormat
821
(RemoteGitBranchFormat(), default_format),
822
(LocalGitBranchFormat(), default_format)]
825
def _get_interrepo(self, source, target):
826
return _mod_repository.InterRepository.get(source.repository, target.repository)
829
def is_compatible(cls, source, target):
830
if not isinstance(source, GitBranch):
832
if isinstance(target, GitBranch):
833
# InterLocalGitRemoteGitBranch or InterToGitBranch should be used
835
if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
836
# fetch_objects is necessary for this to work
840
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
841
self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
843
def fetch_objects(self, stop_revision, fetch_tags, limit=None):
844
interrepo = self._get_interrepo(self.source, self.target)
845
if fetch_tags is None:
846
c = self.source.get_config_stack()
847
fetch_tags = c.get('branch.fetch_tags')
849
def determine_wants(heads):
850
if stop_revision is None:
852
head = heads[self.source.ref]
854
self._last_revid = revision.NULL_REVISION
856
self._last_revid = self.source.lookup_foreign_revision_id(
859
self._last_revid = stop_revision
860
real = interrepo.get_determine_wants_revids(
861
[self._last_revid], include_tags=fetch_tags)
863
pack_hint, head, refs = interrepo.fetch_objects(
864
determine_wants, self.source.mapping, limit=limit)
865
if (pack_hint is not None and
866
self.target.repository._format.pack_compresses):
867
self.target.repository.pack(hint=pack_hint)
870
def _update_revisions(self, stop_revision=None, overwrite=False):
871
head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
873
prev_last_revid = None
875
prev_last_revid = self.target.last_revision()
876
self.target.generate_revision_history(self._last_revid,
877
last_rev=prev_last_revid, other_branch=self.source)
880
def _basic_pull(self, stop_revision, overwrite, run_hooks,
881
_override_hook_target, _hook_master):
882
if overwrite is True:
883
overwrite = set(["history", "tags"])
886
result = GitBranchPullResult()
887
result.source_branch = self.source
888
if _override_hook_target is None:
889
result.target_branch = self.target
891
result.target_branch = _override_hook_target
892
with self.target.lock_write(), self.source.lock_read():
893
# We assume that during 'pull' the target repository is closer than
895
(result.old_revno, result.old_revid) = \
896
self.target.last_revision_info()
897
result.new_git_head, remote_refs = self._update_revisions(
898
stop_revision, overwrite=("history" in overwrite))
899
tags_ret = self.source.tags.merge_to(
900
self.target.tags, ("tags" in overwrite), ignore_master=True)
901
if isinstance(tags_ret, tuple):
902
result.tag_updates, result.tag_conflicts = tags_ret
904
result.tag_conflicts = tags_ret
905
(result.new_revno, result.new_revid) = \
906
self.target.last_revision_info()
908
result.master_branch = _hook_master
909
result.local_branch = result.target_branch
911
result.master_branch = result.target_branch
912
result.local_branch = None
914
for hook in branch.Branch.hooks['post_pull']:
918
def pull(self, overwrite=False, stop_revision=None,
919
possible_transports=None, _hook_master=None, run_hooks=True,
920
_override_hook_target=None, local=False):
923
:param _hook_master: Private parameter - set the branch to
924
be supplied as the master to pull hooks.
925
:param run_hooks: Private parameter - if false, this branch
926
is being called because it's the master of the primary branch,
927
so it should not run its hooks.
928
:param _override_hook_target: Private parameter - set the branch to be
929
supplied as the target_branch to pull hooks.
931
# This type of branch can't be bound.
932
bound_location = self.target.get_bound_location()
933
if local and not bound_location:
934
raise errors.LocalRequiresBoundBranch()
936
source_is_master = False
937
self.source.lock_read()
939
# bound_location comes from a config file, some care has to be
940
# taken to relate it to source.user_url
941
normalized = urlutils.normalize_url(bound_location)
943
relpath = self.source.user_transport.relpath(normalized)
944
source_is_master = (relpath == '')
945
except (errors.PathNotChild, urlutils.InvalidURL):
946
source_is_master = False
947
if not local and bound_location and not source_is_master:
948
# not pulling from master, so we need to update master.
949
master_branch = self.target.get_master_branch(possible_transports)
950
master_branch.lock_write()
954
# pull from source into master.
955
master_branch.pull(self.source, overwrite, stop_revision,
957
result = self._basic_pull(stop_revision, overwrite, run_hooks,
958
_override_hook_target, _hook_master=master_branch)
963
master_branch.unlock()
966
def _basic_push(self, overwrite, stop_revision):
967
if overwrite is True:
968
overwrite = set(["history", "tags"])
971
result = branch.BranchPushResult()
972
result.source_branch = self.source
973
result.target_branch = self.target
974
result.old_revno, result.old_revid = self.target.last_revision_info()
975
result.new_git_head, remote_refs = self._update_revisions(
976
stop_revision, overwrite=("history" in overwrite))
977
tags_ret = self.source.tags.merge_to(self.target.tags,
978
"tags" in overwrite, ignore_master=True)
979
(result.tag_updates, result.tag_conflicts) = tags_ret
980
result.new_revno, result.new_revid = self.target.last_revision_info()
984
class InterGitBranch(branch.GenericInterBranch):
985
"""InterBranch implementation that pulls between Git branches."""
987
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
988
raise NotImplementedError(self.fetch)
991
class InterLocalGitRemoteGitBranch(InterGitBranch):
992
"""InterBranch that copies from a local to a remote git branch."""
995
def _get_branch_formats_to_test():
996
from .remote import RemoteGitBranchFormat
998
(LocalGitBranchFormat(), RemoteGitBranchFormat())]
1001
def is_compatible(self, source, target):
1002
from .remote import RemoteGitBranch
1003
return (isinstance(source, LocalGitBranch) and
1004
isinstance(target, RemoteGitBranch))
1006
def _basic_push(self, overwrite, stop_revision):
1007
result = GitBranchPushResult()
1008
result.source_branch = self.source
1009
result.target_branch = self.target
1010
if stop_revision is None:
1011
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(
1020
new_ref = self.source.repository.lookup_bzr_revision_id(stop_revision)[
1023
if remote_divergence(old_ref, new_ref, self.source.repository._git.object_store):
1024
raise errors.DivergedBranches(self.source, self.target)
1025
refs = {self.target.ref: new_ref}
1026
result.new_revid = stop_revision
1027
for name, sha in viewitems(self.source.repository._git.refs.as_dict(b"refs/tags")):
1028
refs[tag_name_to_ref(name)] = sha
1030
self.target.repository.send_pack(get_changed_refs,
1031
self.source.repository._git.object_store.generate_pack_data)
1035
class InterGitLocalGitBranch(InterGitBranch):
1036
"""InterBranch that copies from a remote to a local git branch."""
1039
def _get_branch_formats_to_test():
1040
from .remote import RemoteGitBranchFormat
1042
(RemoteGitBranchFormat(), LocalGitBranchFormat()),
1043
(LocalGitBranchFormat(), LocalGitBranchFormat())]
1046
def is_compatible(self, source, target):
1047
return (isinstance(source, GitBranch) and
1048
isinstance(target, LocalGitBranch))
1050
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
1051
interrepo = _mod_repository.InterRepository.get(self.source.repository,
1052
self.target.repository)
1053
if stop_revision is None:
1054
stop_revision = self.source.last_revision()
1055
determine_wants = interrepo.get_determine_wants_revids(
1056
[stop_revision], include_tags=fetch_tags)
1057
interrepo.fetch_objects(determine_wants, limit=limit)
1059
def _basic_push(self, overwrite=False, stop_revision=None):
1060
if overwrite is True:
1061
overwrite = set(["history", "tags"])
1064
result = GitBranchPushResult()
1065
result.source_branch = self.source
1066
result.target_branch = self.target
1067
result.old_revid = self.target.last_revision()
1068
refs, stop_revision = self.update_refs(stop_revision)
1069
self.target.generate_revision_history(stop_revision,
1070
(result.old_revid if (
1071
"history" not in overwrite) else None),
1072
other_branch=self.source)
1073
tags_ret = self.source.tags.merge_to(self.target.tags,
1074
source_tag_refs=remote_refs_dict_to_tag_refs(
1076
overwrite=("tags" in overwrite))
1077
if isinstance(tags_ret, tuple):
1078
(result.tag_updates, result.tag_conflicts) = tags_ret
1080
result.tag_conflicts = tags_ret
1081
result.new_revid = self.target.last_revision()
1084
def update_refs(self, stop_revision=None):
1085
interrepo = _mod_repository.InterRepository.get(
1086
self.source.repository, self.target.repository)
1087
c = self.source.get_config_stack()
1088
fetch_tags = c.get('branch.fetch_tags')
1090
if stop_revision is None:
1091
refs = interrepo.fetch(branches=[b"HEAD"], include_tags=fetch_tags)
1093
head = refs[b"HEAD"]
1095
stop_revision = revision.NULL_REVISION
1097
stop_revision = self.target.lookup_foreign_revision_id(head)
1099
refs = interrepo.fetch(
1100
revision_id=stop_revision, include_tags=fetch_tags)
1101
return refs, stop_revision
1103
def pull(self, stop_revision=None, overwrite=False,
1104
possible_transports=None, run_hooks=True, local=False):
1105
# This type of branch can't be bound.
1107
raise errors.LocalRequiresBoundBranch()
1108
if overwrite is True:
1109
overwrite = set(["history", "tags"])
1113
result = GitPullResult()
1114
result.source_branch = self.source
1115
result.target_branch = self.target
1116
with self.target.lock_write(), self.source.lock_read():
1117
result.old_revid = self.target.last_revision()
1118
refs, stop_revision = self.update_refs(stop_revision)
1119
self.target.generate_revision_history(stop_revision,
1120
(result.old_revid if (
1121
"history" not in overwrite) else None),
1122
other_branch=self.source)
1123
tags_ret = self.source.tags.merge_to(self.target.tags,
1125
"tags" in overwrite),
1126
source_tag_refs=remote_refs_dict_to_tag_refs(refs))
1127
if isinstance(tags_ret, tuple):
1128
(result.tag_updates, result.tag_conflicts) = tags_ret
1130
result.tag_conflicts = tags_ret
1131
result.new_revid = self.target.last_revision()
1132
result.local_branch = None
1133
result.master_branch = result.target_branch
1135
for hook in branch.Branch.hooks['post_pull']:
1140
class InterToGitBranch(branch.GenericInterBranch):
1141
"""InterBranch implementation that pulls from a non-bzr into a Git branch."""
1143
def __init__(self, source, target):
1144
super(InterToGitBranch, self).__init__(source, target)
1145
self.interrepo = _mod_repository.InterRepository.get(source.repository,
1149
def _get_branch_formats_to_test():
1151
default_format = branch.format_registry.get_default()
1152
except AttributeError:
1153
default_format = branch.BranchFormat._default_format
1154
from .remote import RemoteGitBranchFormat
1156
(default_format, LocalGitBranchFormat()),
1157
(default_format, RemoteGitBranchFormat())]
1160
def is_compatible(self, source, target):
1161
return (not isinstance(source, GitBranch) and
1162
isinstance(target, GitBranch))
1164
def _get_new_refs(self, stop_revision=None, fetch_tags=None):
1165
if not self.source.is_locked():
1166
raise errors.ObjectNotLocked(self.source)
1167
if stop_revision is None:
1168
(stop_revno, stop_revision) = self.source.last_revision_info()
1170
stop_revno = self.source.revision_id_to_revno(stop_revision)
1171
if not isinstance(stop_revision, bytes):
1172
raise TypeError(stop_revision)
1173
main_ref = self.target.ref
1174
refs = {main_ref: (None, stop_revision)}
1175
if fetch_tags is None:
1176
c = self.source.get_config_stack()
1177
fetch_tags = c.get('branch.fetch_tags')
1178
for name, revid in viewitems(self.source.tags.get_tag_dict()):
1179
if self.source.repository.has_revision(revid):
1180
ref = tag_name_to_ref(name)
1181
if not check_ref_format(ref):
1182
warning("skipping tag with invalid characters %s (%s)",
1186
# FIXME: Skip tags that are not in the ancestry
1187
refs[ref] = (None, revid)
1188
return refs, main_ref, (stop_revno, stop_revision)
1190
def _update_refs(self, result, old_refs, new_refs, overwrite):
1191
mutter("updating refs. old refs: %r, new refs: %r",
1193
result.tag_updates = {}
1194
result.tag_conflicts = []
1195
ret = dict(old_refs)
1197
def ref_equals(refs, ref, git_sha, revid):
1202
if (value[0] is not None and
1203
git_sha is not None and
1204
value[0] == git_sha):
1206
if (value[1] is not None and
1207
revid is not None and
1210
# FIXME: If one side only has the git sha available and the other only
1211
# has the bzr revid, then this will cause us to show a tag as updated
1212
# that hasn't actually been updated.
1214
# FIXME: Check for diverged branches
1215
for ref, (git_sha, revid) in viewitems(new_refs):
1216
if ref_equals(ret, ref, git_sha, revid):
1217
# Already up to date
1219
git_sha = old_refs[ref][0]
1221
revid = old_refs[ref][1]
1222
ret[ref] = new_refs[ref] = (git_sha, revid)
1223
elif ref not in ret or overwrite:
1225
tag_name = ref_to_tag_name(ref)
1229
result.tag_updates[tag_name] = revid
1230
ret[ref] = (git_sha, revid)
1232
# FIXME: Check diverged
1236
name = ref_to_tag_name(ref)
1240
result.tag_conflicts.append(
1241
(name, revid, ret[name][1]))
1243
ret[ref] = (git_sha, revid)
1246
def fetch(self, stop_revision=None, fetch_tags=None, lossy=False, limit=None):
1247
if stop_revision is None:
1248
stop_revision = self.source.last_revision()
1251
for k, v in viewitems(self.source.tags.get_tag_dict()):
1252
ret.append((None, v))
1253
ret.append((None, stop_revision))
1255
self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
1256
except NoPushSupport:
1257
raise errors.NoRoundtrippingSupport(self.source, self.target)
1259
def pull(self, overwrite=False, stop_revision=None, local=False,
1260
possible_transports=None, run_hooks=True):
1261
result = GitBranchPullResult()
1262
result.source_branch = self.source
1263
result.target_branch = self.target
1264
with self.source.lock_read(), self.target.lock_write():
1265
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1268
def update_refs(old_refs):
1269
return self._update_refs(result, old_refs, new_refs, overwrite)
1271
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1272
update_refs, lossy=False)
1273
except NoPushSupport:
1274
raise errors.NoRoundtrippingSupport(self.source, self.target)
1275
(old_sha1, result.old_revid) = old_refs.get(
1276
main_ref, (ZERO_SHA, NULL_REVISION))
1277
if result.old_revid is None:
1278
result.old_revid = self.target.lookup_foreign_revision_id(
1280
result.new_revid = new_refs[main_ref][1]
1281
result.local_branch = None
1282
result.master_branch = self.target
1284
for hook in branch.Branch.hooks['post_pull']:
1288
def push(self, overwrite=False, stop_revision=None, lossy=False,
1289
_override_hook_source_branch=None):
1290
result = GitBranchPushResult()
1291
result.source_branch = self.source
1292
result.target_branch = self.target
1293
result.local_branch = None
1294
result.master_branch = result.target_branch
1295
with self.source.lock_read(), self.target.lock_write():
1296
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1299
def update_refs(old_refs):
1300
return self._update_refs(result, old_refs, new_refs, overwrite)
1302
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1303
update_refs, lossy=lossy, overwrite=overwrite)
1304
except NoPushSupport:
1305
raise errors.NoRoundtrippingSupport(self.source, self.target)
1306
(old_sha1, result.old_revid) = old_refs.get(
1307
main_ref, (ZERO_SHA, NULL_REVISION))
1308
if result.old_revid is None:
1309
result.old_revid = self.target.lookup_foreign_revision_id(
1311
result.new_revid = new_refs[main_ref][1]
1312
(result.new_original_revno, result.new_original_revid) = stop_revinfo
1313
for hook in branch.Branch.hooks['post_push']:
1318
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
1319
branch.InterBranch.register_optimiser(InterFromGitBranch)
1320
branch.InterBranch.register_optimiser(InterToGitBranch)
1321
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)