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,
39
from bzrlib.decorators import (
42
from bzrlib.revision import (
45
from bzrlib.trace import (
51
from bzrlib.plugins.git.config import (
54
from bzrlib.plugins.git.errors import (
58
from bzrlib.plugins.git.refs import (
65
from bzrlib.plugins.git.unpeel_map import (
69
from bzrlib.foreign import ForeignBranch
72
class GitPullResult(branch.PullResult):
73
"""Result of a pull from a Git branch."""
75
def _lookup_revno(self, revid):
76
assert isinstance(revid, str), "was %r" % revid
77
# Try in source branch first, it'll be faster
78
self.target_branch.lock_read()
80
return self.target_branch.revision_id_to_revno(revid)
82
self.target_branch.unlock()
86
return self._lookup_revno(self.old_revid)
90
return self._lookup_revno(self.new_revid)
93
class GitTags(tag.BasicTags):
94
"""Ref-based tag dictionary."""
96
def __init__(self, branch):
98
self.repository = branch.repository
101
raise NotImplementedError(self.get_refs)
103
def _iter_tag_refs(self, refs):
104
raise NotImplementedError(self._iter_tag_refs)
106
def _merge_to_remote_git(self, target_repo, new_refs, overwrite=False):
109
def get_changed_refs(old_refs):
111
for k, v in new_refs.iteritems():
114
name = ref_to_tag_name(k)
115
if old_refs.get(k) == v:
117
elif overwrite or not k in old_refs:
119
updates[name] = target_repo.lookup_foreign_revision_id(v)
121
conflicts.append((name, v, old_refs[k]))
123
target_repo.bzrdir.send_pack(get_changed_refs, lambda have, want: [])
124
return updates, conflicts
126
def _merge_to_local_git(self, target_repo, refs, overwrite=False):
129
for k, v in refs.iteritems():
132
name = ref_to_tag_name(k)
133
if target_repo._git.refs.get(k) == v:
135
elif overwrite or not k in target_repo._git.refs:
136
target_repo._git.refs[k] = v
137
updates[name] = target_repo.lookup_foreign_revision_id(v)
139
conflicts.append((name, v, target_repo.refs[k]))
140
return updates, conflicts
142
def _merge_to_git(self, to_tags, refs, overwrite=False):
143
target_repo = to_tags.repository
144
if self.repository.has_same_location(target_repo):
146
if getattr(target_repo, "_git", None):
147
return self._merge_to_local_git(target_repo, refs, overwrite)
149
return self._merge_to_remote_git(target_repo, refs, overwrite)
151
def _merge_to_non_git(self, to_tags, refs, overwrite=False):
152
unpeeled_map = defaultdict(set)
155
result = dict(to_tags.get_tag_dict())
156
for n, peeled, unpeeled, bzr_revid in self._iter_tag_refs(refs):
157
if unpeeled is not None:
158
unpeeled_map[peeled].add(unpeeled)
159
if result.get(n) == bzr_revid:
161
elif n not in result or overwrite:
162
result[n] = bzr_revid
163
updates[n] = bzr_revid
165
conflicts.append((n, result[n], bzr_revid))
166
to_tags._set_tag_dict(result)
167
if len(unpeeled_map) > 0:
168
map_file = UnpeelMap.from_repository(to_tags.branch.repository)
169
map_file.update(unpeeled_map)
170
map_file.save_in_repository(to_tags.branch.repository)
171
return updates, conflicts
173
def merge_to(self, to_tags, overwrite=False, ignore_master=False,
175
"""See Tags.merge_to."""
176
if source_refs is None:
177
source_refs = self.get_refs()
180
if isinstance(to_tags, GitTags):
181
return self._merge_to_git(to_tags, source_refs,
187
master = to_tags.branch.get_master_branch()
188
updates, conflicts = self._merge_to_non_git(to_tags, source_refs,
190
if master is not None:
191
extra_updates, extra_conflicts = self.merge_to(
192
master.tags, overwrite=overwrite,
193
source_refs=source_refs,
194
ignore_master=ignore_master)
195
updates.update(extra_updates)
196
conflicts += extra_conflicts
197
return updates, conflicts
199
def get_tag_dict(self):
201
refs = self.get_refs()
202
for (name, peeled, unpeeled, bzr_revid) in self._iter_tag_refs(refs):
203
ret[name] = bzr_revid
207
class LocalGitTagDict(GitTags):
208
"""Dictionary with tags in a local repository."""
210
def __init__(self, branch):
211
super(LocalGitTagDict, self).__init__(branch)
212
self.refs = self.repository._git.refs
215
return self.repository._git.get_refs()
217
def _iter_tag_refs(self, refs):
218
"""Iterate over the tag refs.
220
:param refs: Refs dictionary (name -> git sha1)
221
:return: iterator over (name, peeled_sha1, unpeeled_sha1, bzr_revid)
223
for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
225
obj = self.repository._git[peeled]
227
mutter("Tag %s points at unknown object %s, ignoring", peeled,
230
# FIXME: this shouldn't really be necessary, the repository
231
# already should have these unpeeled.
232
while isinstance(obj, Tag):
233
peeled = obj.object[1]
234
obj = self.repository._git[peeled]
235
if not isinstance(obj, Commit):
236
mutter("Tag %s points at object %r that is not a commit, "
239
yield (k, peeled, unpeeled,
240
self.branch.lookup_foreign_revision_id(peeled))
242
def _set_tag_dict(self, to_dict):
243
extra = set(self.get_refs().keys())
244
for k, revid in to_dict.iteritems():
245
name = tag_name_to_ref(k)
248
self.set_tag(k, revid)
251
del self.repository._git[name]
253
def set_tag(self, name, revid):
255
git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
256
except errors.NoSuchRevision:
257
raise errors.GhostTagsNotSupported(self)
258
self.refs[tag_name_to_ref(name)] = git_sha
261
class DictTagDict(tag.BasicTags):
263
def __init__(self, branch, tags):
264
super(DictTagDict, self).__init__(branch)
267
def get_tag_dict(self):
271
class GitSymrefBranchFormat(branch.BranchFormat):
273
def get_format_description(self):
274
return 'Git Symbolic Reference Branch'
276
def network_name(self):
279
def get_reference(self, controldir, name=None):
280
return controldir.get_branch_reference(name)
282
def set_reference(self, controldir, name, target):
283
return controldir.set_branch_reference(name, target)
286
class GitBranchFormat(branch.BranchFormat):
288
def get_format_description(self):
291
def network_name(self):
294
def supports_tags(self):
297
def supports_leaving_lock(self):
300
def supports_tags_referencing_ghosts(self):
303
def tags_are_versioned(self):
307
def _matchingbzrdir(self):
308
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
309
return LocalGitControlDirFormat()
311
def get_foreign_tests_branch_factory(self):
312
from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
313
return ForeignTestsBranchFactory()
315
def make_tags(self, branch):
316
if getattr(branch.repository, "get_refs", None) is not None:
317
from bzrlib.plugins.git.remote import RemoteGitTagDict
318
return RemoteGitTagDict(branch)
320
return LocalGitTagDict(branch)
322
def initialize(self, a_bzrdir, name=None, repository=None,
323
append_revisions_only=None):
324
from bzrlib.plugins.git.dir import LocalGitDir
325
if not isinstance(a_bzrdir, LocalGitDir):
326
raise errors.IncompatibleFormat(self, a_bzrdir._format)
327
return a_bzrdir.create_branch(repository=repository, name=name,
328
append_revisions_only=append_revisions_only)
331
class GitReadLock(object):
333
def __init__(self, unlock):
337
class GitWriteLock(object):
339
def __init__(self, unlock):
340
self.branch_token = None
344
class GitBranch(ForeignBranch):
345
"""An adapter to git repositories for bzr Branch objects."""
348
def control_transport(self):
349
return self.bzrdir.control_transport
351
def __init__(self, bzrdir, repository, ref, tagsdict=None):
352
self.base = bzrdir.root_transport.base
353
self.repository = repository
354
self._format = GitBranchFormat()
356
self._lock_mode = None
358
super(GitBranch, self).__init__(repository.get_mapping())
359
if tagsdict is not None:
360
self.tags = DictTagDict(self, tagsdict)
363
self.name = ref_to_branch_name(ref)
368
def _get_checkout_format(self, lightweight=False):
369
"""Return the most suitable metadir for a checkout of this branch.
370
Weaves are used if this branch's repository uses weaves.
372
return bzrdir.format_registry.make_bzrdir("default")
374
def get_child_submit_format(self):
375
"""Return the preferred format of submissions to this branch."""
376
ret = self.get_config().get_user_option("child_submit_format")
381
def get_config(self):
382
return GitBranchConfig(self)
384
def _get_nick(self, local=False, possible_master_transports=None):
385
"""Find the nick name for this branch.
389
return self.name or "HEAD"
391
def _set_nick(self, nick):
392
raise NotImplementedError
394
nick = property(_get_nick, _set_nick)
397
return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
400
def generate_revision_history(self, revid, old_revid=None):
401
if revid == NULL_REVISION:
404
# FIXME: Check that old_revid is in the ancestry of revid
405
newhead, self.mapping = self.repository.lookup_bzr_revision_id(revid)
406
if self.mapping is None:
408
self._set_head(newhead)
410
def lock_write(self, token=None):
411
if token is not None:
412
raise errors.TokenLockingNotSupported(self)
414
if self._lock_mode == 'r':
415
raise errors.ReadOnlyError(self)
416
self._lock_count += 1
418
self._lock_mode = 'w'
420
self.repository.lock_write()
421
return GitWriteLock(self.unlock)
423
def get_stacked_on_url(self):
424
# Git doesn't do stacking (yet...)
425
raise errors.UnstackableBranchFormat(self._format, self.base)
427
def get_parent(self):
428
"""See Branch.get_parent()."""
429
# FIXME: Set "origin" url from .git/config ?
432
def set_parent(self, url):
433
# FIXME: Set "origin" url in .git/config ?
436
def break_lock(self):
437
raise NotImplementedError(self.break_lock)
441
assert self._lock_mode in ('r', 'w')
442
self._lock_count += 1
444
self._lock_mode = 'r'
446
self.repository.lock_read()
447
return GitReadLock(self.unlock)
449
def peek_lock_mode(self):
450
return self._lock_mode
453
return (self._lock_mode is not None)
456
"""See Branch.unlock()."""
457
self._lock_count -= 1
458
if self._lock_count == 0:
459
self._lock_mode = None
460
self._clear_cached_state()
461
self.repository.unlock()
463
def get_physical_lock_status(self):
467
def last_revision(self):
468
# perhaps should escape this ?
469
if self.head is None:
470
return revision.NULL_REVISION
471
return self.lookup_foreign_revision_id(self.head)
473
def _basic_push(self, target, overwrite=False, stop_revision=None):
474
return branch.InterBranch.get(self, target)._basic_push(
475
overwrite, stop_revision)
477
def lookup_foreign_revision_id(self, foreign_revid):
478
return self.repository.lookup_foreign_revision_id(foreign_revid,
481
def lookup_bzr_revision_id(self, revid):
482
return self.repository.lookup_bzr_revision_id(
483
revid, mapping=self.mapping)
486
class LocalGitBranch(GitBranch):
487
"""A local Git branch."""
489
def __init__(self, bzrdir, repository, ref, tagsdict=None):
490
super(LocalGitBranch, self).__init__(bzrdir, repository, ref,
492
refs = repository._git.get_refs()
493
if not (ref in refs.keys() or "HEAD" in refs.keys()):
494
raise errors.NotBranchError(self.base)
496
def create_checkout(self, to_location, revision_id=None, lightweight=False,
497
accelerator_tree=None, hardlink=False):
499
t = transport.get_transport(to_location)
501
format = self._get_checkout_format(lightweight=True)
502
checkout = format.initialize_on_transport(t)
503
from_branch = branch.BranchReferenceFormat().initialize(checkout,
505
tree = checkout.create_workingtree(revision_id,
506
from_branch=from_branch, hardlink=hardlink)
509
return self._create_heavyweight_checkout(to_location, revision_id,
512
def _create_heavyweight_checkout(self, to_location, revision_id=None,
514
"""Create a new heavyweight checkout of this branch.
516
:param to_location: URL of location to create the new checkout in.
517
:param revision_id: Revision that should be the tip of the checkout.
518
:param hardlink: Whether to hardlink
519
:return: WorkingTree object of checkout.
521
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
522
to_location, force_new_tree=False,
523
format=self._get_checkout_format(lightweight=False))
524
checkout = checkout_branch.bzrdir
525
checkout_branch.bind(self)
526
# pull up to the specified revision_id to set the initial
527
# branch tip correctly, and seed it with history.
528
checkout_branch.pull(self, stop_revision=revision_id)
529
return checkout.create_workingtree(revision_id, hardlink=hardlink)
531
def _gen_revision_history(self):
532
if self.head is None:
534
graph = self.repository.get_graph()
535
ret = list(graph.iter_lefthand_ancestry(self.last_revision(),
536
(revision.NULL_REVISION, )))
542
return self.repository._git.ref(self.ref or "HEAD")
546
def _read_last_revision_info(self):
547
last_revid = self.last_revision()
548
graph = self.repository.get_graph()
549
revno = graph.find_distance_to_null(last_revid,
550
[(revision.NULL_REVISION, 0)])
551
return revno, last_revid
553
def set_last_revision_info(self, revno, revision_id):
554
self.set_last_revision(revision_id)
555
self._last_revision_info_cache = revno, revision_id
557
def set_last_revision(self, revid):
558
if not revid or not isinstance(revid, basestring):
559
raise errors.InvalidRevisionId(revision_id=revid, branch=self)
560
if revid == NULL_REVISION:
563
(newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
564
if self.mapping is None:
566
self._set_head(newhead)
568
def _set_head(self, value):
570
self.repository._git.refs[self.ref or "HEAD"] = self._head
571
self._clear_cached_state()
573
head = property(_get_head, _set_head)
575
def get_push_location(self):
576
"""See Branch.get_push_location."""
577
push_loc = self.get_config().get_user_option('push_location')
580
def set_push_location(self, location):
581
"""See Branch.set_push_location."""
582
self.get_config().set_user_option('push_location', location,
583
store=config.STORE_LOCATION)
585
def supports_tags(self):
589
def _quick_lookup_revno(local_branch, remote_branch, revid):
590
assert isinstance(revid, str), "was %r" % revid
591
# Try in source branch first, it'll be faster
592
local_branch.lock_read()
595
return local_branch.revision_id_to_revno(revid)
596
except errors.NoSuchRevision:
597
graph = local_branch.repository.get_graph()
599
return graph.find_distance_to_null(revid,
600
[(revision.NULL_REVISION, 0)])
601
except errors.GhostRevisionsHaveNoRevno:
602
# FIXME: Check using graph.find_distance_to_null() ?
603
remote_branch.lock_read()
605
return remote_branch.revision_id_to_revno(revid)
607
remote_branch.unlock()
609
local_branch.unlock()
612
class GitBranchPullResult(branch.PullResult):
615
super(GitBranchPullResult, self).__init__()
616
self.new_git_head = None
617
self._old_revno = None
618
self._new_revno = None
620
def report(self, to_file):
622
if self.old_revid == self.new_revid:
623
to_file.write('No revisions to pull.\n')
624
elif self.new_git_head is not None:
625
to_file.write('Now on revision %d (git sha: %s).\n' %
626
(self.new_revno, self.new_git_head))
628
to_file.write('Now on revision %d.\n' % (self.new_revno,))
629
self._show_tag_conficts(to_file)
631
def _lookup_revno(self, revid):
632
return _quick_lookup_revno(self.target_branch, self.source_branch,
635
def _get_old_revno(self):
636
if self._old_revno is not None:
637
return self._old_revno
638
return self._lookup_revno(self.old_revid)
640
def _set_old_revno(self, revno):
641
self._old_revno = revno
643
old_revno = property(_get_old_revno, _set_old_revno)
645
def _get_new_revno(self):
646
if self._new_revno is not None:
647
return self._new_revno
648
return self._lookup_revno(self.new_revid)
650
def _set_new_revno(self, revno):
651
self._new_revno = revno
653
new_revno = property(_get_new_revno, _set_new_revno)
656
class GitBranchPushResult(branch.BranchPushResult):
658
def _lookup_revno(self, revid):
659
return _quick_lookup_revno(self.source_branch, self.target_branch,
664
return self._lookup_revno(self.old_revid)
668
new_original_revno = getattr(self, "new_original_revno", None)
669
if new_original_revno:
670
return new_original_revno
671
if getattr(self, "new_original_revid", None) is not None:
672
return self._lookup_revno(self.new_original_revid)
673
return self._lookup_revno(self.new_revid)
676
class InterFromGitBranch(branch.GenericInterBranch):
677
"""InterBranch implementation that pulls from Git into bzr."""
680
def _get_branch_formats_to_test():
682
default_format = branch.format_registry.get_default()
683
except AttributeError:
684
default_format = branch.BranchFormat._default_format
686
(GitBranchFormat(), GitBranchFormat()),
687
(GitBranchFormat(), default_format)]
690
def _get_interrepo(self, source, target):
691
return _mod_repository.InterRepository.get(source.repository, target.repository)
694
def is_compatible(cls, source, target):
695
if not isinstance(source, GitBranch):
697
if isinstance(target, GitBranch):
698
# InterLocalGitRemoteGitBranch or InterToGitBranch should be used
700
if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
701
# fetch_objects is necessary for this to work
705
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
706
self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
708
def fetch_objects(self, stop_revision, fetch_tags, limit=None):
709
interrepo = self._get_interrepo(self.source, self.target)
710
if fetch_tags is None:
711
c = self.source.get_config()
712
fetch_tags = c.get_user_option_as_bool('branch.fetch_tags')
713
def determine_wants(heads):
714
if self.source.ref is not None and not self.source.ref in heads:
715
raise NoSuchRef(self.source.ref, self.source.user_url, heads.keys())
717
if stop_revision is None:
718
if self.source.ref is not None:
719
head = heads[self.source.ref]
722
self._last_revid = self.source.lookup_foreign_revision_id(head)
724
self._last_revid = stop_revision
725
real = interrepo.get_determine_wants_revids(
726
[self._last_revid], include_tags=fetch_tags)
728
pack_hint, head, refs = interrepo.fetch_objects(
729
determine_wants, self.source.mapping, limit=limit)
730
if (pack_hint is not None and
731
self.target.repository._format.pack_compresses):
732
self.target.repository.pack(hint=pack_hint)
735
def _update_revisions(self, stop_revision=None, overwrite=False):
736
head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
738
prev_last_revid = None
740
prev_last_revid = self.target.last_revision()
741
self.target.generate_revision_history(self._last_revid,
742
prev_last_revid, self.source)
745
def pull(self, overwrite=False, stop_revision=None,
746
possible_transports=None, _hook_master=None, run_hooks=True,
747
_override_hook_target=None, local=False):
750
:param _hook_master: Private parameter - set the branch to
751
be supplied as the master to pull hooks.
752
:param run_hooks: Private parameter - if false, this branch
753
is being called because it's the master of the primary branch,
754
so it should not run its hooks.
755
:param _override_hook_target: Private parameter - set the branch to be
756
supplied as the target_branch to pull hooks.
758
# This type of branch can't be bound.
760
raise errors.LocalRequiresBoundBranch()
761
result = GitBranchPullResult()
762
result.source_branch = self.source
763
if _override_hook_target is None:
764
result.target_branch = self.target
766
result.target_branch = _override_hook_target
767
self.source.lock_read()
769
self.target.lock_write()
771
# We assume that during 'pull' the target repository is closer than
773
(result.old_revno, result.old_revid) = \
774
self.target.last_revision_info()
775
result.new_git_head, remote_refs = self._update_revisions(
776
stop_revision, overwrite=overwrite)
777
tags_ret = self.source.tags.merge_to(
778
self.target.tags, overwrite)
779
if isinstance(tags_ret, tuple):
780
result.tag_updates, result.tag_conflicts = tags_ret
782
result.tag_conflicts = tags_ret
783
(result.new_revno, result.new_revid) = \
784
self.target.last_revision_info()
786
result.master_branch = _hook_master
787
result.local_branch = result.target_branch
789
result.master_branch = result.target_branch
790
result.local_branch = None
792
for hook in branch.Branch.hooks['post_pull']:
800
def _basic_push(self, overwrite=False, stop_revision=None):
801
result = branch.BranchPushResult()
802
result.source_branch = self.source
803
result.target_branch = self.target
804
result.old_revno, result.old_revid = self.target.last_revision_info()
805
result.new_git_head, remote_refs = self._update_revisions(
806
stop_revision, overwrite=overwrite)
807
tags_ret = self.source.tags.merge_to(self.target.tags,
809
if isinstance(tags_ret, tuple):
810
(result.tag_updates, result.tag_conflicts) = tags_ret
812
result.tag_conflicts = tags_ret
813
result.new_revno, result.new_revid = self.target.last_revision_info()
817
class InterGitBranch(branch.GenericInterBranch):
818
"""InterBranch implementation that pulls between Git branches."""
821
class InterLocalGitRemoteGitBranch(InterGitBranch):
822
"""InterBranch that copies from a local to a remote git branch."""
825
def _get_branch_formats_to_test():
830
def is_compatible(self, source, target):
831
from bzrlib.plugins.git.remote import RemoteGitBranch
832
return (isinstance(source, LocalGitBranch) and
833
isinstance(target, RemoteGitBranch))
835
def _basic_push(self, overwrite=False, stop_revision=None):
836
result = GitBranchPushResult()
837
result.source_branch = self.source
838
result.target_branch = self.target
839
if stop_revision is None:
840
stop_revision = self.source.last_revision()
841
# FIXME: Check for diverged branches
842
def get_changed_refs(old_refs):
843
old_ref = old_refs.get(self.target.ref, ZERO_SHA)
844
result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
845
refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
846
result.new_revid = stop_revision
847
for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
848
refs[tag_name_to_ref(name)] = sha
850
self.target.repository.send_pack(get_changed_refs,
851
self.source.repository._git.object_store.generate_pack_contents)
855
class InterGitLocalGitBranch(InterGitBranch):
856
"""InterBranch that copies from a remote to a local git branch."""
859
def _get_branch_formats_to_test():
864
def is_compatible(self, source, target):
865
return (isinstance(source, GitBranch) and
866
isinstance(target, LocalGitBranch))
868
def _basic_push(self, overwrite=False, stop_revision=None):
869
result = GitBranchPushResult()
870
result.source_branch = self.source
871
result.target_branch = self.target
872
result.old_revid = self.target.last_revision()
873
refs, stop_revision = self.update_refs(stop_revision)
874
self.target.generate_revision_history(stop_revision, result.old_revid)
875
tags_ret = self.source.tags.merge_to(self.target.tags,
876
source_refs=refs, overwrite=overwrite)
877
if isinstance(tags_ret, tuple):
878
(result.tag_updates, result.tag_conflicts) = tags_ret
880
result.tag_conflicts = tags_ret
881
result.new_revid = self.target.last_revision()
884
def update_refs(self, stop_revision=None):
885
interrepo = _mod_repository.InterRepository.get(self.source.repository,
886
self.target.repository)
887
if stop_revision is None:
888
refs = interrepo.fetch(branches=["HEAD"])
889
stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
891
refs = interrepo.fetch(revision_id=stop_revision)
892
return refs, stop_revision
894
def pull(self, stop_revision=None, overwrite=False,
895
possible_transports=None, run_hooks=True,local=False):
896
# This type of branch can't be bound.
898
raise errors.LocalRequiresBoundBranch()
899
result = GitPullResult()
900
result.source_branch = self.source
901
result.target_branch = self.target
902
self.source.lock_read()
904
self.target.lock_write()
906
result.old_revid = self.target.last_revision()
907
refs, stop_revision = self.update_refs(stop_revision)
908
self.target.generate_revision_history(stop_revision, result.old_revid)
909
tags_ret = self.source.tags.merge_to(self.target.tags,
910
overwrite=overwrite, source_refs=refs)
911
if isinstance(tags_ret, tuple):
912
(result.tag_updates, result.tag_conflicts) = tags_ret
914
result.tag_conflicts = tags_ret
915
result.new_revid = self.target.last_revision()
916
result.local_branch = None
917
result.master_branch = result.target_branch
919
for hook in branch.Branch.hooks['post_pull']:
928
class InterToGitBranch(branch.GenericInterBranch):
929
"""InterBranch implementation that pulls into a Git branch."""
931
def __init__(self, source, target):
932
super(InterToGitBranch, self).__init__(source, target)
933
self.interrepo = _mod_repository.InterRepository.get(source.repository,
937
def _get_branch_formats_to_test():
939
default_format = branch.format_registry.get_default()
940
except AttributeError:
941
default_format = branch.BranchFormat._default_format
942
return [(default_format, GitBranchFormat())]
945
def is_compatible(self, source, target):
946
return (not isinstance(source, GitBranch) and
947
isinstance(target, GitBranch))
949
def _get_new_refs(self, stop_revision=None, fetch_tags=None):
950
assert self.source.is_locked()
951
if stop_revision is None:
952
(stop_revno, stop_revision) = self.source.last_revision_info()
954
stop_revno = self.source.revision_id_to_revno(stop_revision)
955
assert type(stop_revision) is str
956
main_ref = self.target.ref or "refs/heads/master"
957
refs = { main_ref: (None, stop_revision) }
958
if fetch_tags is None:
959
c = self.source.get_config()
960
fetch_tags = c.get_user_option_as_bool('branch.fetch_tags')
961
for name, revid in self.source.tags.get_tag_dict().iteritems():
962
if self.source.repository.has_revision(revid):
963
ref = tag_name_to_ref(name)
964
if not check_ref_format(ref):
965
warning("skipping tag with invalid characters %s (%s)",
969
# FIXME: Skip tags that are not in the ancestry
970
refs[ref] = (None, revid)
971
return refs, main_ref, (stop_revno, stop_revision)
973
def _update_refs(self, result, old_refs, new_refs, overwrite):
974
mutter("updating refs. old refs: %r, new refs: %r",
976
result.tag_updates = {}
977
result.tag_conflicts = []
979
def ref_equals(refs, ref, git_sha, revid):
984
if (value[0] is not None and
985
git_sha is not None and
986
value[0] != git_sha):
988
if (value[1] is not None and
989
revid is not None and
992
# FIXME: If one side only has the git sha available and the other only
993
# has the bzr revid, then this will cause us to show a tag as updated
994
# that hasn't actually been updated.
996
for ref, (git_sha, revid) in new_refs.iteritems():
997
if ref not in ret or overwrite:
998
if not ref_equals(ret, ref, git_sha, revid):
1000
tag_name = ref_to_tag_name(ref)
1004
result.tag_updates[tag_name] = revid
1005
ret[ref] = (git_sha, revid)
1006
elif ref_equals(ret, ref, git_sha, revid):
1010
name = ref_to_tag_name(ref)
1014
result.tag_conflicts.append((name, revid, ret[name][1]))
1015
# FIXME: Check for diverged branches
1016
ret.update(new_refs)
1019
def pull(self, overwrite=False, stop_revision=None, local=False,
1020
possible_transports=None, run_hooks=True):
1021
result = GitBranchPullResult()
1022
result.source_branch = self.source
1023
result.target_branch = self.target
1024
self.source.lock_read()
1026
self.target.lock_write()
1028
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1030
def update_refs(old_refs):
1031
return self._update_refs(result, old_refs, new_refs, overwrite)
1033
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1034
update_refs, lossy=False)
1035
except NoPushSupport:
1036
raise errors.NoRoundtrippingSupport(self.source, self.target)
1037
(result.old_revid, old_sha1) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1038
if result.old_revid is None:
1039
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1040
result.new_revid = new_refs[main_ref][1]
1041
result.local_branch = None
1042
result.master_branch = self.target
1044
for hook in branch.Branch.hooks['post_pull']:
1047
self.target.unlock()
1049
self.source.unlock()
1052
def push(self, overwrite=False, stop_revision=None, lossy=False,
1053
_override_hook_source_branch=None):
1054
result = GitBranchPushResult()
1055
result.source_branch = self.source
1056
result.target_branch = self.target
1057
result.local_branch = None
1058
result.master_branch = result.target_branch
1059
self.source.lock_read()
1061
new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
1062
def update_refs(old_refs):
1063
return self._update_refs(result, old_refs, new_refs, overwrite)
1065
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1066
update_refs, lossy=lossy)
1067
except NoPushSupport:
1068
raise errors.NoRoundtrippingSupport(self.source, self.target)
1069
(old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1070
if result.old_revid is None:
1071
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1072
result.new_revid = new_refs[main_ref][1]
1073
(result.new_original_revno, result.new_original_revid) = stop_revinfo
1074
for hook in branch.Branch.hooks['post_push']:
1077
self.source.unlock()
1080
def lossy_push(self, stop_revision=None):
1081
# For compatibility with bzr < 2.4
1082
return self.push(lossy=True, stop_revision=stop_revision)
1085
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
1086
branch.InterBranch.register_optimiser(InterFromGitBranch)
1087
branch.InterBranch.register_optimiser(InterToGitBranch)
1088
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)