1
# Copyright (C) 2007 Canonical Ltd
2
# Copyright (C) 2009-2010 Jelmer Vernooij <jelmer@samba.org>
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
"""An adapter between a Git Branch and a Bazaar Branch"""
20
from collections import defaultdict
22
from dulwich.objects import (
27
from dulwich.repo import check_ref_format
34
repository as _mod_repository,
40
from bzrlib.decorators import (
43
from bzrlib.revision import (
46
from bzrlib.trace import (
52
from bzrlib.plugins.git.config import (
55
from bzrlib.plugins.git.errors import (
59
from bzrlib.plugins.git.refs import (
67
from bzrlib.plugins.git.unpeel_map import (
71
from bzrlib.foreign import ForeignBranch
74
class GitPullResult(branch.PullResult):
75
"""Result of a pull from a Git branch."""
77
def _lookup_revno(self, revid):
78
assert isinstance(revid, str), "was %r" % revid
79
# Try in source branch first, it'll be faster
80
self.target_branch.lock_read()
82
return self.target_branch.revision_id_to_revno(revid)
84
self.target_branch.unlock()
88
return self._lookup_revno(self.old_revid)
92
return self._lookup_revno(self.new_revid)
95
class GitTags(tag.BasicTags):
96
"""Ref-based tag dictionary."""
98
def __init__(self, branch):
100
self.repository = branch.repository
103
raise NotImplementedError(self.get_refs)
105
def _iter_tag_refs(self, refs):
106
raise NotImplementedError(self._iter_tag_refs)
108
def _merge_to_remote_git(self, target_repo, new_refs, overwrite=False):
111
def get_changed_refs(old_refs):
113
for k, v in new_refs.iteritems():
116
name = ref_to_tag_name(k)
117
if old_refs.get(k) == v:
119
elif overwrite or not k in old_refs:
121
updates[name] = target_repo.lookup_foreign_revision_id(v)
123
conflicts.append((name, v, old_refs[k]))
125
target_repo.bzrdir.send_pack(get_changed_refs, lambda have, want: [])
126
return updates, conflicts
128
def _merge_to_local_git(self, target_repo, refs, overwrite=False):
131
for k, (peeled, unpeeled) in gather_peeled(refs).iteritems():
134
name = ref_to_tag_name(k)
135
if target_repo._git.refs.get(k) in (peeled, unpeeled):
137
elif overwrite or not k in target_repo._git.refs:
138
target_repo._git.refs[k] = unpeeled or peeled
139
updates[name] = target_repo.lookup_foreign_revision_id(peeled)
141
conflicts.append((name, peeled, target_repo.refs[k]))
142
return updates, conflicts
144
def _merge_to_git(self, to_tags, refs, overwrite=False):
145
target_repo = to_tags.repository
146
if self.repository.has_same_location(target_repo):
148
if getattr(target_repo, "_git", None):
149
return self._merge_to_local_git(target_repo, refs, overwrite)
151
return self._merge_to_remote_git(target_repo, refs, overwrite)
153
def _merge_to_non_git(self, to_tags, refs, overwrite=False):
154
unpeeled_map = defaultdict(set)
157
result = dict(to_tags.get_tag_dict())
158
for n, peeled, unpeeled, bzr_revid in self._iter_tag_refs(refs):
159
if unpeeled is not None:
160
unpeeled_map[peeled].add(unpeeled)
161
if result.get(n) == bzr_revid:
163
elif n not in result or overwrite:
164
result[n] = bzr_revid
165
updates[n] = bzr_revid
167
conflicts.append((n, result[n], bzr_revid))
168
to_tags._set_tag_dict(result)
169
if len(unpeeled_map) > 0:
170
map_file = UnpeelMap.from_repository(to_tags.branch.repository)
171
map_file.update(unpeeled_map)
172
map_file.save_in_repository(to_tags.branch.repository)
173
return updates, conflicts
175
def merge_to(self, to_tags, overwrite=False, ignore_master=False,
177
"""See Tags.merge_to."""
178
if source_refs is None:
179
source_refs = self.get_refs()
182
if isinstance(to_tags, GitTags):
183
return self._merge_to_git(to_tags, source_refs,
189
master = to_tags.branch.get_master_branch()
190
updates, conflicts = self._merge_to_non_git(to_tags, source_refs,
192
if master is not None:
193
extra_updates, extra_conflicts = self.merge_to(
194
master.tags, overwrite=overwrite,
195
source_refs=source_refs,
196
ignore_master=ignore_master)
197
updates.update(extra_updates)
198
conflicts += extra_conflicts
199
return updates, conflicts
201
def get_tag_dict(self):
203
refs = self.get_refs()
204
for (name, peeled, unpeeled, bzr_revid) in self._iter_tag_refs(refs):
205
ret[name] = bzr_revid
209
class LocalGitTagDict(GitTags):
210
"""Dictionary with tags in a local repository."""
212
def __init__(self, branch):
213
super(LocalGitTagDict, self).__init__(branch)
214
self.refs = self.repository.bzrdir._git.refs
217
return self.refs.as_dict()
219
def _iter_tag_refs(self, refs):
220
"""Iterate over the tag refs.
222
:param refs: Refs dictionary (name -> git sha1)
223
:return: iterator over (name, peeled_sha1, unpeeled_sha1, bzr_revid)
225
for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
227
obj = self.repository._git[peeled]
229
mutter("Tag %s points at unknown object %s, ignoring", peeled,
232
# FIXME: this shouldn't really be necessary, the repository
233
# already should have these unpeeled.
234
while isinstance(obj, Tag):
235
peeled = obj.object[1]
236
obj = self.repository._git[peeled]
237
if not isinstance(obj, Commit):
238
mutter("Tag %s points at object %r that is not a commit, "
241
yield (k, peeled, unpeeled,
242
self.branch.lookup_foreign_revision_id(peeled))
244
def _set_tag_dict(self, to_dict):
245
extra = set(self.get_refs().keys())
246
for k, revid in to_dict.iteritems():
247
name = tag_name_to_ref(k)
250
self.set_tag(k, revid)
253
del self.repository._git[name]
255
def set_tag(self, name, revid):
257
git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
258
except errors.NoSuchRevision:
259
raise errors.GhostTagsNotSupported(self)
260
self.refs[tag_name_to_ref(name)] = git_sha
263
class DictTagDict(tag.BasicTags):
265
def __init__(self, branch, tags):
266
super(DictTagDict, self).__init__(branch)
269
def get_tag_dict(self):
273
class GitSymrefBranchFormat(branch.BranchFormat):
275
def get_format_description(self):
276
return 'Git Symbolic Reference Branch'
278
def network_name(self):
281
def get_reference(self, controldir, name=None):
282
return controldir.get_branch_reference(name)
284
def set_reference(self, controldir, name, target):
285
return controldir.set_branch_reference(name, target)
288
class GitBranchFormat(branch.BranchFormat):
290
def get_format_description(self):
293
def network_name(self):
296
def supports_tags(self):
299
def supports_leaving_lock(self):
302
def supports_tags_referencing_ghosts(self):
305
def tags_are_versioned(self):
309
def _matchingbzrdir(self):
310
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
311
return LocalGitControlDirFormat()
313
def get_foreign_tests_branch_factory(self):
314
from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
315
return ForeignTestsBranchFactory()
317
def make_tags(self, branch):
318
if getattr(branch.repository, "_git", None) is None:
319
from bzrlib.plugins.git.remote import RemoteGitTagDict
320
return RemoteGitTagDict(branch)
322
return LocalGitTagDict(branch)
324
def initialize(self, a_bzrdir, name=None, repository=None,
325
append_revisions_only=None):
326
from bzrlib.plugins.git.dir import LocalGitDir
327
if not isinstance(a_bzrdir, LocalGitDir):
328
raise errors.IncompatibleFormat(self, a_bzrdir._format)
329
return a_bzrdir.create_branch(repository=repository, name=name,
330
append_revisions_only=append_revisions_only)
333
class GitReadLock(object):
335
def __init__(self, unlock):
339
class GitWriteLock(object):
341
def __init__(self, unlock):
342
self.branch_token = None
346
class GitBranch(ForeignBranch):
347
"""An adapter to git repositories for bzr Branch objects."""
350
def control_transport(self):
351
return self.bzrdir.control_transport
353
def __init__(self, bzrdir, repository, ref, tagsdict=None):
354
self.base = bzrdir.root_transport.base
355
self.repository = repository
356
self._format = GitBranchFormat()
358
self._lock_mode = None
360
super(GitBranch, self).__init__(repository.get_mapping())
361
if tagsdict is not None:
362
self.tags = DictTagDict(self, tagsdict)
365
self.name = ref_to_branch_name(ref)
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.
374
return bzrdir.format_registry.make_bzrdir("default")
376
def get_child_submit_format(self):
377
"""Return the preferred format of submissions to this branch."""
378
ret = self.get_config().get_user_option("child_submit_format")
383
def get_config(self):
384
return GitBranchConfig(self)
386
def _get_nick(self, local=False, possible_master_transports=None):
387
"""Find the nick name for this branch.
391
return self.name or "HEAD"
393
def _set_nick(self, nick):
394
raise NotImplementedError
396
nick = property(_get_nick, _set_nick)
399
return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
402
def generate_revision_history(self, revid, old_revid=None):
403
if revid == NULL_REVISION:
406
# FIXME: Check that old_revid is in the ancestry of revid
407
newhead, self.mapping = self.repository.lookup_bzr_revision_id(revid)
408
if self.mapping is None:
410
self._set_head(newhead)
412
def lock_write(self, token=None):
413
if token is not None:
414
raise errors.TokenLockingNotSupported(self)
416
if self._lock_mode == 'r':
417
raise errors.ReadOnlyError(self)
418
self._lock_count += 1
420
self._lock_mode = 'w'
422
self.repository.lock_write()
423
return GitWriteLock(self.unlock)
425
def leave_lock_in_place(self):
426
raise NotImplementedError(self.leave_lock_in_place)
428
def dont_leave_lock_in_place(self):
429
raise NotImplementedError(self.dont_leave_lock_in_place)
431
def get_stacked_on_url(self):
432
# Git doesn't do stacking (yet...)
433
raise errors.UnstackableBranchFormat(self._format, self.base)
435
def get_parent(self):
436
"""See Branch.get_parent()."""
437
# FIXME: Set "origin" url from .git/config ?
440
def set_parent(self, url):
441
# FIXME: Set "origin" url in .git/config ?
444
def break_lock(self):
445
raise NotImplementedError(self.break_lock)
449
assert self._lock_mode in ('r', 'w')
450
self._lock_count += 1
452
self._lock_mode = 'r'
454
self.repository.lock_read()
455
return GitReadLock(self.unlock)
457
def peek_lock_mode(self):
458
return self._lock_mode
461
return (self._lock_mode is not None)
464
"""See Branch.unlock()."""
465
self._lock_count -= 1
466
if self._lock_count == 0:
467
self._lock_mode = None
468
self._clear_cached_state()
469
self.repository.unlock()
471
def get_physical_lock_status(self):
475
def last_revision(self):
476
# perhaps should escape this ?
477
if self.head is None:
478
return revision.NULL_REVISION
479
return self.lookup_foreign_revision_id(self.head)
481
def _basic_push(self, target, overwrite=False, stop_revision=None):
482
return branch.InterBranch.get(self, target)._basic_push(
483
overwrite, stop_revision)
485
def lookup_foreign_revision_id(self, foreign_revid):
486
return self.repository.lookup_foreign_revision_id(foreign_revid,
489
def lookup_bzr_revision_id(self, revid):
490
return self.repository.lookup_bzr_revision_id(
491
revid, mapping=self.mapping)
494
class LocalGitBranch(GitBranch):
495
"""A local Git branch."""
497
def __init__(self, bzrdir, repository, ref, tagsdict=None):
498
super(LocalGitBranch, self).__init__(bzrdir, repository, ref,
500
refs = bzrdir.get_refs()
501
if not (ref in refs.keys() or "HEAD" in refs.keys()):
502
raise errors.NotBranchError(self.base)
504
def create_checkout(self, to_location, revision_id=None, lightweight=False,
505
accelerator_tree=None, hardlink=False):
507
t = transport.get_transport(to_location)
509
format = self._get_checkout_format(lightweight=True)
510
checkout = format.initialize_on_transport(t)
511
from_branch = branch.BranchReferenceFormat().initialize(checkout,
513
tree = checkout.create_workingtree(revision_id,
514
from_branch=from_branch, hardlink=hardlink)
517
return self._create_heavyweight_checkout(to_location, revision_id,
520
def _create_heavyweight_checkout(self, to_location, revision_id=None,
522
"""Create a new heavyweight checkout of this branch.
524
:param to_location: URL of location to create the new checkout in.
525
:param revision_id: Revision that should be the tip of the checkout.
526
:param hardlink: Whether to hardlink
527
:return: WorkingTree object of checkout.
529
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
530
to_location, force_new_tree=False,
531
format=self._get_checkout_format(lightweight=False))
532
checkout = checkout_branch.bzrdir
533
checkout_branch.bind(self)
534
# pull up to the specified revision_id to set the initial
535
# branch tip correctly, and seed it with history.
536
checkout_branch.pull(self, stop_revision=revision_id)
537
return checkout.create_workingtree(revision_id, hardlink=hardlink)
539
def _gen_revision_history(self):
540
if self.head is None:
542
graph = self.repository.get_graph()
543
ret = list(graph.iter_lefthand_ancestry(self.last_revision(),
544
(revision.NULL_REVISION, )))
550
return self.repository._git.ref(self.ref or "HEAD")
554
def _read_last_revision_info(self):
555
last_revid = self.last_revision()
556
graph = self.repository.get_graph()
557
revno = graph.find_distance_to_null(last_revid,
558
[(revision.NULL_REVISION, 0)])
559
return revno, last_revid
561
def set_last_revision_info(self, revno, revision_id):
562
self.set_last_revision(revision_id)
563
self._last_revision_info_cache = revno, revision_id
565
def set_last_revision(self, revid):
566
if not revid or not isinstance(revid, basestring):
567
raise errors.InvalidRevisionId(revision_id=revid, branch=self)
568
if revid == NULL_REVISION:
571
(newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
572
if self.mapping is None:
574
self._set_head(newhead)
576
def _set_head(self, value):
578
self.repository._git.refs[self.ref or "HEAD"] = self._head
579
self._clear_cached_state()
581
head = property(_get_head, _set_head)
583
def get_push_location(self):
584
"""See Branch.get_push_location."""
585
push_loc = self.get_config().get_user_option('push_location')
588
def set_push_location(self, location):
589
"""See Branch.set_push_location."""
590
self.get_config().set_user_option('push_location', location,
591
store=config.STORE_LOCATION)
593
def supports_tags(self):
597
def _quick_lookup_revno(local_branch, remote_branch, revid):
598
assert isinstance(revid, str), "was %r" % revid
599
# Try in source branch first, it'll be faster
600
local_branch.lock_read()
603
return local_branch.revision_id_to_revno(revid)
604
except errors.NoSuchRevision:
605
graph = local_branch.repository.get_graph()
607
return graph.find_distance_to_null(revid,
608
[(revision.NULL_REVISION, 0)])
609
except errors.GhostRevisionsHaveNoRevno:
610
# FIXME: Check using graph.find_distance_to_null() ?
611
remote_branch.lock_read()
613
return remote_branch.revision_id_to_revno(revid)
615
remote_branch.unlock()
617
local_branch.unlock()
620
class GitBranchPullResult(branch.PullResult):
623
super(GitBranchPullResult, self).__init__()
624
self.new_git_head = None
625
self._old_revno = None
626
self._new_revno = None
628
def report(self, to_file):
630
if self.old_revid == self.new_revid:
631
to_file.write('No revisions to pull.\n')
632
elif self.new_git_head is not None:
633
to_file.write('Now on revision %d (git sha: %s).\n' %
634
(self.new_revno, self.new_git_head))
636
to_file.write('Now on revision %d.\n' % (self.new_revno,))
637
self._show_tag_conficts(to_file)
639
def _lookup_revno(self, revid):
640
return _quick_lookup_revno(self.target_branch, self.source_branch,
643
def _get_old_revno(self):
644
if self._old_revno is not None:
645
return self._old_revno
646
return self._lookup_revno(self.old_revid)
648
def _set_old_revno(self, revno):
649
self._old_revno = revno
651
old_revno = property(_get_old_revno, _set_old_revno)
653
def _get_new_revno(self):
654
if self._new_revno is not None:
655
return self._new_revno
656
return self._lookup_revno(self.new_revid)
658
def _set_new_revno(self, revno):
659
self._new_revno = revno
661
new_revno = property(_get_new_revno, _set_new_revno)
664
class GitBranchPushResult(branch.BranchPushResult):
666
def _lookup_revno(self, revid):
667
return _quick_lookup_revno(self.source_branch, self.target_branch,
672
return self._lookup_revno(self.old_revid)
676
new_original_revno = getattr(self, "new_original_revno", None)
677
if new_original_revno:
678
return new_original_revno
679
if getattr(self, "new_original_revid", None) is not None:
680
return self._lookup_revno(self.new_original_revid)
681
return self._lookup_revno(self.new_revid)
684
class InterFromGitBranch(branch.GenericInterBranch):
685
"""InterBranch implementation that pulls from Git into bzr."""
688
def _get_branch_formats_to_test():
690
default_format = branch.format_registry.get_default()
691
except AttributeError:
692
default_format = branch.BranchFormat._default_format
694
(GitBranchFormat(), GitBranchFormat()),
695
(GitBranchFormat(), default_format)]
698
def _get_interrepo(self, source, target):
699
return _mod_repository.InterRepository.get(source.repository, target.repository)
702
def is_compatible(cls, source, target):
703
if not isinstance(source, GitBranch):
705
if isinstance(target, GitBranch):
706
# InterLocalGitRemoteGitBranch or InterToGitBranch should be used
708
if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
709
# fetch_objects is necessary for this to work
713
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
714
self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
716
def fetch_objects(self, stop_revision, fetch_tags, limit=None):
717
interrepo = self._get_interrepo(self.source, self.target)
718
if fetch_tags is None:
719
c = self.source.get_config()
720
fetch_tags = c.get_user_option_as_bool('branch.fetch_tags')
721
def determine_wants(heads):
722
if self.source.ref is not None and not self.source.ref in heads:
723
raise NoSuchRef(self.source.ref, self.source.user_url, heads.keys())
725
if stop_revision is None:
726
if self.source.ref is not None:
727
head = heads[self.source.ref]
730
self._last_revid = self.source.lookup_foreign_revision_id(head)
732
self._last_revid = stop_revision
733
real = interrepo.get_determine_wants_revids(
734
[self._last_revid], include_tags=fetch_tags)
736
pack_hint, head, refs = interrepo.fetch_objects(
737
determine_wants, self.source.mapping, limit=limit)
738
if (pack_hint is not None and
739
self.target.repository._format.pack_compresses):
740
self.target.repository.pack(hint=pack_hint)
743
def _update_revisions(self, stop_revision=None, overwrite=False):
744
head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
746
prev_last_revid = None
748
prev_last_revid = self.target.last_revision()
749
self.target.generate_revision_history(self._last_revid,
750
prev_last_revid, self.source)
753
def _basic_pull(self, stop_revision, overwrite, run_hooks,
754
_override_hook_target, _hook_master):
755
result = GitBranchPullResult()
756
result.source_branch = self.source
757
if _override_hook_target is None:
758
result.target_branch = self.target
760
result.target_branch = _override_hook_target
761
self.source.lock_read()
763
self.target.lock_write()
765
# We assume that during 'pull' the target repository is closer than
767
(result.old_revno, result.old_revid) = \
768
self.target.last_revision_info()
769
result.new_git_head, remote_refs = self._update_revisions(
770
stop_revision, overwrite=overwrite)
771
tags_ret = self.source.tags.merge_to(
772
self.target.tags, overwrite)
773
if isinstance(tags_ret, tuple):
774
result.tag_updates, result.tag_conflicts = tags_ret
776
result.tag_conflicts = tags_ret
777
(result.new_revno, result.new_revid) = \
778
self.target.last_revision_info()
780
result.master_branch = _hook_master
781
result.local_branch = result.target_branch
783
result.master_branch = result.target_branch
784
result.local_branch = None
786
for hook in branch.Branch.hooks['post_pull']:
794
def pull(self, overwrite=False, stop_revision=None,
795
possible_transports=None, _hook_master=None, run_hooks=True,
796
_override_hook_target=None, local=False):
799
:param _hook_master: Private parameter - set the branch to
800
be supplied as the master to pull hooks.
801
:param run_hooks: Private parameter - if false, this branch
802
is being called because it's the master of the primary branch,
803
so it should not run its hooks.
804
:param _override_hook_target: Private parameter - set the branch to be
805
supplied as the target_branch to pull hooks.
807
# This type of branch can't be bound.
808
bound_location = self.target.get_bound_location()
809
if local and not bound_location:
810
raise errors.LocalRequiresBoundBranch()
812
source_is_master = False
813
self.source.lock_read()
815
# bound_location comes from a config file, some care has to be
816
# taken to relate it to source.user_url
817
normalized = urlutils.normalize_url(bound_location)
819
relpath = self.source.user_transport.relpath(normalized)
820
source_is_master = (relpath == '')
821
except (errors.PathNotChild, errors.InvalidURL):
822
source_is_master = False
823
if not local and bound_location and not source_is_master:
824
# not pulling from master, so we need to update master.
825
master_branch = self.target.get_master_branch(possible_transports)
826
master_branch.lock_write()
830
# pull from source into master.
831
master_branch.pull(self.source, overwrite, stop_revision,
833
result = self._basic_pull(stop_revision, overwrite, run_hooks,
834
_override_hook_target, _hook_master=master_branch)
839
master_branch.unlock()
842
def _basic_push(self, overwrite=False, stop_revision=None):
843
result = branch.BranchPushResult()
844
result.source_branch = self.source
845
result.target_branch = self.target
846
result.old_revno, result.old_revid = self.target.last_revision_info()
847
result.new_git_head, remote_refs = self._update_revisions(
848
stop_revision, overwrite=overwrite)
849
tags_ret = self.source.tags.merge_to(self.target.tags,
851
if isinstance(tags_ret, tuple):
852
(result.tag_updates, result.tag_conflicts) = tags_ret
854
result.tag_conflicts = tags_ret
855
result.new_revno, result.new_revid = self.target.last_revision_info()
859
class InterGitBranch(branch.GenericInterBranch):
860
"""InterBranch implementation that pulls between Git branches."""
863
class InterLocalGitRemoteGitBranch(InterGitBranch):
864
"""InterBranch that copies from a local to a remote git branch."""
867
def _get_branch_formats_to_test():
872
def is_compatible(self, source, target):
873
from bzrlib.plugins.git.remote import RemoteGitBranch
874
return (isinstance(source, LocalGitBranch) and
875
isinstance(target, RemoteGitBranch))
877
def _basic_push(self, overwrite=False, stop_revision=None):
878
result = GitBranchPushResult()
879
result.source_branch = self.source
880
result.target_branch = self.target
881
if stop_revision is None:
882
stop_revision = self.source.last_revision()
883
# FIXME: Check for diverged branches
884
def get_changed_refs(old_refs):
885
old_ref = old_refs.get(self.target.ref, ZERO_SHA)
886
result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
887
refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
888
result.new_revid = stop_revision
889
for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
890
refs[tag_name_to_ref(name)] = sha
892
self.target.repository.send_pack(get_changed_refs,
893
self.source.repository._git.object_store.generate_pack_contents)
897
class InterGitLocalGitBranch(InterGitBranch):
898
"""InterBranch that copies from a remote to a local git branch."""
901
def _get_branch_formats_to_test():
906
def is_compatible(self, source, target):
907
return (isinstance(source, GitBranch) and
908
isinstance(target, LocalGitBranch))
910
def _basic_push(self, overwrite=False, stop_revision=None):
911
result = GitBranchPushResult()
912
result.source_branch = self.source
913
result.target_branch = self.target
914
result.old_revid = self.target.last_revision()
915
refs, stop_revision = self.update_refs(stop_revision)
916
self.target.generate_revision_history(stop_revision, result.old_revid)
917
tags_ret = self.source.tags.merge_to(self.target.tags,
918
source_refs=refs, overwrite=overwrite)
919
if isinstance(tags_ret, tuple):
920
(result.tag_updates, result.tag_conflicts) = tags_ret
922
result.tag_conflicts = tags_ret
923
result.new_revid = self.target.last_revision()
926
def update_refs(self, stop_revision=None):
927
interrepo = _mod_repository.InterRepository.get(self.source.repository,
928
self.target.repository)
929
if stop_revision is None:
930
refs = interrepo.fetch(branches=["HEAD"])
931
stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
933
refs = interrepo.fetch(revision_id=stop_revision)
934
return refs, stop_revision
936
def pull(self, stop_revision=None, overwrite=False,
937
possible_transports=None, run_hooks=True,local=False):
938
# This type of branch can't be bound.
940
raise errors.LocalRequiresBoundBranch()
941
result = GitPullResult()
942
result.source_branch = self.source
943
result.target_branch = self.target
944
self.source.lock_read()
946
self.target.lock_write()
948
result.old_revid = self.target.last_revision()
949
refs, stop_revision = self.update_refs(stop_revision)
950
self.target.generate_revision_history(stop_revision, result.old_revid)
951
tags_ret = self.source.tags.merge_to(self.target.tags,
952
overwrite=overwrite, source_refs=refs)
953
if isinstance(tags_ret, tuple):
954
(result.tag_updates, result.tag_conflicts) = tags_ret
956
result.tag_conflicts = tags_ret
957
result.new_revid = self.target.last_revision()
958
result.local_branch = None
959
result.master_branch = result.target_branch
961
for hook in branch.Branch.hooks['post_pull']:
970
class InterToGitBranch(branch.GenericInterBranch):
971
"""InterBranch implementation that pulls into a Git branch."""
973
def __init__(self, source, target):
974
super(InterToGitBranch, self).__init__(source, target)
975
self.interrepo = _mod_repository.InterRepository.get(source.repository,
979
def _get_branch_formats_to_test():
981
default_format = branch.format_registry.get_default()
982
except AttributeError:
983
default_format = branch.BranchFormat._default_format
984
return [(default_format, GitBranchFormat())]
987
def is_compatible(self, source, target):
988
return (not isinstance(source, GitBranch) and
989
isinstance(target, GitBranch))
991
def _get_new_refs(self, stop_revision=None, fetch_tags=None):
992
assert self.source.is_locked()
993
if stop_revision is None:
994
(stop_revno, stop_revision) = self.source.last_revision_info()
996
stop_revno = self.source.revision_id_to_revno(stop_revision)
997
assert type(stop_revision) is str
998
main_ref = self.target.ref or "refs/heads/master"
999
refs = { main_ref: (None, stop_revision) }
1000
if fetch_tags is None:
1001
c = self.source.get_config()
1002
fetch_tags = c.get_user_option_as_bool('branch.fetch_tags')
1003
for name, revid in self.source.tags.get_tag_dict().iteritems():
1004
if self.source.repository.has_revision(revid):
1005
ref = tag_name_to_ref(name)
1006
if not check_ref_format(ref):
1007
warning("skipping tag with invalid characters %s (%s)",
1011
# FIXME: Skip tags that are not in the ancestry
1012
refs[ref] = (None, revid)
1013
return refs, main_ref, (stop_revno, stop_revision)
1015
def _update_refs(self, result, old_refs, new_refs, overwrite):
1016
mutter("updating refs. old refs: %r, new refs: %r",
1018
result.tag_updates = {}
1019
result.tag_conflicts = []
1020
ret = dict(old_refs)
1021
def ref_equals(refs, ref, git_sha, revid):
1026
if (value[0] is not None and
1027
git_sha is not None and
1028
value[0] != git_sha):
1030
if (value[1] is not None and
1031
revid is not None and
1034
# FIXME: If one side only has the git sha available and the other only
1035
# has the bzr revid, then this will cause us to show a tag as updated
1036
# that hasn't actually been updated.
1038
for ref, (git_sha, revid) in new_refs.iteritems():
1039
if ref not in ret or overwrite:
1040
if not ref_equals(ret, ref, git_sha, revid):
1042
tag_name = ref_to_tag_name(ref)
1046
result.tag_updates[tag_name] = revid
1047
ret[ref] = (git_sha, revid)
1048
elif ref_equals(ret, ref, git_sha, revid):
1052
name = ref_to_tag_name(ref)
1056
result.tag_conflicts.append((name, revid, ret[name][1]))
1057
# FIXME: Check for diverged branches
1058
ret.update(new_refs)
1061
def pull(self, overwrite=False, stop_revision=None, local=False,
1062
possible_transports=None, run_hooks=True):
1063
result = GitBranchPullResult()
1064
result.source_branch = self.source
1065
result.target_branch = self.target
1066
self.source.lock_read()
1068
self.target.lock_write()
1070
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1072
def update_refs(old_refs):
1073
return self._update_refs(result, old_refs, new_refs, overwrite)
1075
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1076
update_refs, lossy=False)
1077
except NoPushSupport:
1078
raise errors.NoRoundtrippingSupport(self.source, self.target)
1079
(result.old_revid, old_sha1) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1080
if result.old_revid is None:
1081
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1082
result.new_revid = new_refs[main_ref][1]
1083
result.local_branch = None
1084
result.master_branch = self.target
1086
for hook in branch.Branch.hooks['post_pull']:
1089
self.target.unlock()
1091
self.source.unlock()
1094
def push(self, overwrite=False, stop_revision=None, lossy=False,
1095
_override_hook_source_branch=None):
1096
result = GitBranchPushResult()
1097
result.source_branch = self.source
1098
result.target_branch = self.target
1099
result.local_branch = None
1100
result.master_branch = result.target_branch
1101
self.source.lock_read()
1103
new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
1104
def update_refs(old_refs):
1105
return self._update_refs(result, old_refs, new_refs, overwrite)
1107
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1108
update_refs, lossy=lossy)
1109
except NoPushSupport:
1110
raise errors.NoRoundtrippingSupport(self.source, self.target)
1111
(old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1112
if result.old_revid is None:
1113
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1114
result.new_revid = new_refs[main_ref][1]
1115
(result.new_original_revno, result.new_original_revid) = stop_revinfo
1116
for hook in branch.Branch.hooks['post_push']:
1119
self.source.unlock()
1122
def lossy_push(self, stop_revision=None):
1123
# For compatibility with bzr < 2.4
1124
return self.push(lossy=True, stop_revision=stop_revision)
1127
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
1128
branch.InterBranch.register_optimiser(InterFromGitBranch)
1129
branch.InterBranch.register_optimiser(InterToGitBranch)
1130
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)