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 (
66
from bzrlib.plugins.git.unpeel_map import (
70
from bzrlib.foreign import ForeignBranch
73
class GitPullResult(branch.PullResult):
74
"""Result of a pull from a Git branch."""
76
def _lookup_revno(self, revid):
77
assert isinstance(revid, str), "was %r" % revid
78
# Try in source branch first, it'll be faster
79
self.target_branch.lock_read()
81
return self.target_branch.revision_id_to_revno(revid)
83
self.target_branch.unlock()
87
return self._lookup_revno(self.old_revid)
91
return self._lookup_revno(self.new_revid)
94
class GitTags(tag.BasicTags):
95
"""Ref-based tag dictionary."""
97
def __init__(self, branch):
99
self.repository = branch.repository
102
raise NotImplementedError(self.get_refs)
104
def _iter_tag_refs(self, refs):
105
raise NotImplementedError(self._iter_tag_refs)
107
def _merge_to_remote_git(self, target_repo, new_refs, overwrite=False):
110
def get_changed_refs(old_refs):
112
for k, v in new_refs.iteritems():
115
name = ref_to_tag_name(k)
116
if old_refs.get(k) == v:
118
elif overwrite or not k in old_refs:
120
updates[name] = target_repo.lookup_foreign_revision_id(v)
122
conflicts.append((name, v, old_refs[k]))
124
target_repo.bzrdir.send_pack(get_changed_refs, lambda have, want: [])
125
return updates, conflicts
127
def _merge_to_local_git(self, target_repo, refs, overwrite=False):
130
for k, v in refs.iteritems():
133
name = ref_to_tag_name(k)
134
if target_repo._git.refs.get(k) == v:
136
elif overwrite or not k in target_repo._git.refs:
137
target_repo._git.refs[k] = v
138
updates[name] = target_repo.lookup_foreign_revision_id(v)
140
conflicts.append((name, v, target_repo.refs[k]))
141
return updates, conflicts
143
def _merge_to_git(self, to_tags, refs, overwrite=False):
144
target_repo = to_tags.repository
145
if self.repository.has_same_location(target_repo):
147
if getattr(target_repo, "_git", None):
148
return self._merge_to_local_git(target_repo, refs, overwrite)
150
return self._merge_to_remote_git(target_repo, refs, overwrite)
152
def _merge_to_non_git(self, to_tags, refs, overwrite=False):
153
unpeeled_map = defaultdict(set)
156
result = dict(to_tags.get_tag_dict())
157
for n, peeled, unpeeled, bzr_revid in self._iter_tag_refs(refs):
158
if unpeeled is not None:
159
unpeeled_map[peeled].add(unpeeled)
160
if result.get(n) == bzr_revid:
162
elif n not in result or overwrite:
163
result[n] = bzr_revid
164
updates[n] = bzr_revid
166
conflicts.append((n, result[n], bzr_revid))
167
to_tags._set_tag_dict(result)
168
if len(unpeeled_map) > 0:
169
map_file = UnpeelMap.from_repository(to_tags.branch.repository)
170
map_file.update(unpeeled_map)
171
map_file.save_in_repository(to_tags.branch.repository)
172
return updates, conflicts
174
def merge_to(self, to_tags, overwrite=False, ignore_master=False,
176
"""See Tags.merge_to."""
177
if source_refs is None:
178
source_refs = self.get_refs()
181
if isinstance(to_tags, GitTags):
182
return self._merge_to_git(to_tags, source_refs,
188
master = to_tags.branch.get_master_branch()
189
updates, conflicts = self._merge_to_non_git(to_tags, source_refs,
191
if master is not None:
192
extra_updates, extra_conflicts = self.merge_to(
193
master.tags, overwrite=overwrite,
194
source_refs=source_refs,
195
ignore_master=ignore_master)
196
updates.update(extra_updates)
197
conflicts += extra_conflicts
198
return updates, conflicts
200
def get_tag_dict(self):
202
refs = self.get_refs()
203
for (name, peeled, unpeeled, bzr_revid) in self._iter_tag_refs(refs):
204
ret[name] = bzr_revid
208
class LocalGitTagDict(GitTags):
209
"""Dictionary with tags in a local repository."""
211
def __init__(self, branch):
212
super(LocalGitTagDict, self).__init__(branch)
213
self.refs = self.repository.bzrdir._git.refs
216
return self.refs.as_dict()
218
def _iter_tag_refs(self, refs):
219
"""Iterate over the tag refs.
221
:param refs: Refs dictionary (name -> git sha1)
222
:return: iterator over (name, peeled_sha1, unpeeled_sha1, bzr_revid)
224
for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
226
obj = self.repository._git[peeled]
228
mutter("Tag %s points at unknown object %s, ignoring", peeled,
231
# FIXME: this shouldn't really be necessary, the repository
232
# already should have these unpeeled.
233
while isinstance(obj, Tag):
234
peeled = obj.object[1]
235
obj = self.repository._git[peeled]
236
if not isinstance(obj, Commit):
237
mutter("Tag %s points at object %r that is not a commit, "
240
yield (k, peeled, unpeeled,
241
self.branch.lookup_foreign_revision_id(peeled))
243
def _set_tag_dict(self, to_dict):
244
extra = set(self.get_refs().keys())
245
for k, revid in to_dict.iteritems():
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
262
class DictTagDict(tag.BasicTags):
264
def __init__(self, branch, tags):
265
super(DictTagDict, self).__init__(branch)
268
def get_tag_dict(self):
272
class GitSymrefBranchFormat(branch.BranchFormat):
274
def get_format_description(self):
275
return 'Git Symbolic Reference Branch'
277
def network_name(self):
280
def get_reference(self, controldir, name=None):
281
return controldir.get_branch_reference(name)
283
def set_reference(self, controldir, name, target):
284
return controldir.set_branch_reference(name, target)
287
class GitBranchFormat(branch.BranchFormat):
289
def get_format_description(self):
292
def network_name(self):
295
def supports_tags(self):
298
def supports_leaving_lock(self):
301
def supports_tags_referencing_ghosts(self):
304
def tags_are_versioned(self):
308
def _matchingbzrdir(self):
309
from bzrlib.plugins.git.dir import LocalGitControlDirFormat
310
return LocalGitControlDirFormat()
312
def get_foreign_tests_branch_factory(self):
313
from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
314
return ForeignTestsBranchFactory()
316
def make_tags(self, branch):
317
if getattr(branch.repository, "_git", None) is None:
318
from bzrlib.plugins.git.remote import RemoteGitTagDict
319
return RemoteGitTagDict(branch)
321
return LocalGitTagDict(branch)
323
def initialize(self, a_bzrdir, name=None, repository=None,
324
append_revisions_only=None):
325
from bzrlib.plugins.git.dir import LocalGitDir
326
if not isinstance(a_bzrdir, LocalGitDir):
327
raise errors.IncompatibleFormat(self, a_bzrdir._format)
328
return a_bzrdir.create_branch(repository=repository, name=name,
329
append_revisions_only=append_revisions_only)
332
class GitReadLock(object):
334
def __init__(self, unlock):
338
class GitWriteLock(object):
340
def __init__(self, unlock):
341
self.branch_token = None
345
class GitBranch(ForeignBranch):
346
"""An adapter to git repositories for bzr Branch objects."""
349
def control_transport(self):
350
return self.bzrdir.control_transport
352
def __init__(self, bzrdir, repository, ref, tagsdict=None):
353
self.base = bzrdir.root_transport.base
354
self.repository = repository
355
self._format = GitBranchFormat()
357
self._lock_mode = None
359
super(GitBranch, self).__init__(repository.get_mapping())
360
if tagsdict is not None:
361
self.tags = DictTagDict(self, tagsdict)
364
self.name = ref_to_branch_name(ref)
369
def _get_checkout_format(self, lightweight=False):
370
"""Return the most suitable metadir for a checkout of this branch.
371
Weaves are used if this branch's repository uses weaves.
373
return bzrdir.format_registry.make_bzrdir("default")
375
def get_child_submit_format(self):
376
"""Return the preferred format of submissions to this branch."""
377
ret = self.get_config().get_user_option("child_submit_format")
382
def get_config(self):
383
return GitBranchConfig(self)
385
def _get_nick(self, local=False, possible_master_transports=None):
386
"""Find the nick name for this branch.
390
return self.name or "HEAD"
392
def _set_nick(self, nick):
393
raise NotImplementedError
395
nick = property(_get_nick, _set_nick)
398
return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
401
def generate_revision_history(self, revid, old_revid=None):
402
if revid == NULL_REVISION:
405
# FIXME: Check that old_revid is in the ancestry of revid
406
newhead, self.mapping = self.repository.lookup_bzr_revision_id(revid)
407
if self.mapping is None:
409
self._set_head(newhead)
411
def lock_write(self, token=None):
412
if token is not None:
413
raise errors.TokenLockingNotSupported(self)
415
if self._lock_mode == 'r':
416
raise errors.ReadOnlyError(self)
417
self._lock_count += 1
419
self._lock_mode = 'w'
421
self.repository.lock_write()
422
return GitWriteLock(self.unlock)
424
def leave_lock_in_place(self):
425
raise NotImplementedError(self.leave_lock_in_place)
427
def dont_leave_lock_in_place(self):
428
raise NotImplementedError(self.dont_leave_lock_in_place)
430
def get_stacked_on_url(self):
431
# Git doesn't do stacking (yet...)
432
raise errors.UnstackableBranchFormat(self._format, self.base)
434
def get_parent(self):
435
"""See Branch.get_parent()."""
436
# FIXME: Set "origin" url from .git/config ?
439
def set_parent(self, url):
440
# FIXME: Set "origin" url in .git/config ?
443
def break_lock(self):
444
raise NotImplementedError(self.break_lock)
448
assert self._lock_mode in ('r', 'w')
449
self._lock_count += 1
451
self._lock_mode = 'r'
453
self.repository.lock_read()
454
return GitReadLock(self.unlock)
456
def peek_lock_mode(self):
457
return self._lock_mode
460
return (self._lock_mode is not None)
463
"""See Branch.unlock()."""
464
self._lock_count -= 1
465
if self._lock_count == 0:
466
self._lock_mode = None
467
self._clear_cached_state()
468
self.repository.unlock()
470
def get_physical_lock_status(self):
474
def last_revision(self):
475
# perhaps should escape this ?
476
if self.head is None:
477
return revision.NULL_REVISION
478
return self.lookup_foreign_revision_id(self.head)
480
def _basic_push(self, target, overwrite=False, stop_revision=None):
481
return branch.InterBranch.get(self, target)._basic_push(
482
overwrite, stop_revision)
484
def lookup_foreign_revision_id(self, foreign_revid):
485
return self.repository.lookup_foreign_revision_id(foreign_revid,
488
def lookup_bzr_revision_id(self, revid):
489
return self.repository.lookup_bzr_revision_id(
490
revid, mapping=self.mapping)
493
class LocalGitBranch(GitBranch):
494
"""A local Git branch."""
496
def __init__(self, bzrdir, repository, ref, tagsdict=None):
497
super(LocalGitBranch, self).__init__(bzrdir, repository, ref,
499
refs = bzrdir.get_refs()
500
if not (ref in refs.keys() or "HEAD" in refs.keys()):
501
raise errors.NotBranchError(self.base)
503
def create_checkout(self, to_location, revision_id=None, lightweight=False,
504
accelerator_tree=None, hardlink=False):
506
t = transport.get_transport(to_location)
508
format = self._get_checkout_format(lightweight=True)
509
checkout = format.initialize_on_transport(t)
510
from_branch = branch.BranchReferenceFormat().initialize(checkout,
512
tree = checkout.create_workingtree(revision_id,
513
from_branch=from_branch, hardlink=hardlink)
516
return self._create_heavyweight_checkout(to_location, revision_id,
519
def _create_heavyweight_checkout(self, to_location, revision_id=None,
521
"""Create a new heavyweight checkout of this branch.
523
:param to_location: URL of location to create the new checkout in.
524
:param revision_id: Revision that should be the tip of the checkout.
525
:param hardlink: Whether to hardlink
526
:return: WorkingTree object of checkout.
528
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
529
to_location, force_new_tree=False,
530
format=self._get_checkout_format(lightweight=False))
531
checkout = checkout_branch.bzrdir
532
checkout_branch.bind(self)
533
# pull up to the specified revision_id to set the initial
534
# branch tip correctly, and seed it with history.
535
checkout_branch.pull(self, stop_revision=revision_id)
536
return checkout.create_workingtree(revision_id, hardlink=hardlink)
538
def _gen_revision_history(self):
539
if self.head is None:
541
graph = self.repository.get_graph()
542
ret = list(graph.iter_lefthand_ancestry(self.last_revision(),
543
(revision.NULL_REVISION, )))
549
return self.repository._git.ref(self.ref or "HEAD")
553
def _read_last_revision_info(self):
554
last_revid = self.last_revision()
555
graph = self.repository.get_graph()
556
revno = graph.find_distance_to_null(last_revid,
557
[(revision.NULL_REVISION, 0)])
558
return revno, last_revid
560
def set_last_revision_info(self, revno, revision_id):
561
self.set_last_revision(revision_id)
562
self._last_revision_info_cache = revno, revision_id
564
def set_last_revision(self, revid):
565
if not revid or not isinstance(revid, basestring):
566
raise errors.InvalidRevisionId(revision_id=revid, branch=self)
567
if revid == NULL_REVISION:
570
(newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
571
if self.mapping is None:
573
self._set_head(newhead)
575
def _set_head(self, value):
577
self.repository._git.refs[self.ref or "HEAD"] = self._head
578
self._clear_cached_state()
580
head = property(_get_head, _set_head)
582
def get_push_location(self):
583
"""See Branch.get_push_location."""
584
push_loc = self.get_config().get_user_option('push_location')
587
def set_push_location(self, location):
588
"""See Branch.set_push_location."""
589
self.get_config().set_user_option('push_location', location,
590
store=config.STORE_LOCATION)
592
def supports_tags(self):
596
def _quick_lookup_revno(local_branch, remote_branch, revid):
597
assert isinstance(revid, str), "was %r" % revid
598
# Try in source branch first, it'll be faster
599
local_branch.lock_read()
602
return local_branch.revision_id_to_revno(revid)
603
except errors.NoSuchRevision:
604
graph = local_branch.repository.get_graph()
606
return graph.find_distance_to_null(revid,
607
[(revision.NULL_REVISION, 0)])
608
except errors.GhostRevisionsHaveNoRevno:
609
# FIXME: Check using graph.find_distance_to_null() ?
610
remote_branch.lock_read()
612
return remote_branch.revision_id_to_revno(revid)
614
remote_branch.unlock()
616
local_branch.unlock()
619
class GitBranchPullResult(branch.PullResult):
622
super(GitBranchPullResult, self).__init__()
623
self.new_git_head = None
624
self._old_revno = None
625
self._new_revno = None
627
def report(self, to_file):
629
if self.old_revid == self.new_revid:
630
to_file.write('No revisions to pull.\n')
631
elif self.new_git_head is not None:
632
to_file.write('Now on revision %d (git sha: %s).\n' %
633
(self.new_revno, self.new_git_head))
635
to_file.write('Now on revision %d.\n' % (self.new_revno,))
636
self._show_tag_conficts(to_file)
638
def _lookup_revno(self, revid):
639
return _quick_lookup_revno(self.target_branch, self.source_branch,
642
def _get_old_revno(self):
643
if self._old_revno is not None:
644
return self._old_revno
645
return self._lookup_revno(self.old_revid)
647
def _set_old_revno(self, revno):
648
self._old_revno = revno
650
old_revno = property(_get_old_revno, _set_old_revno)
652
def _get_new_revno(self):
653
if self._new_revno is not None:
654
return self._new_revno
655
return self._lookup_revno(self.new_revid)
657
def _set_new_revno(self, revno):
658
self._new_revno = revno
660
new_revno = property(_get_new_revno, _set_new_revno)
663
class GitBranchPushResult(branch.BranchPushResult):
665
def _lookup_revno(self, revid):
666
return _quick_lookup_revno(self.source_branch, self.target_branch,
671
return self._lookup_revno(self.old_revid)
675
new_original_revno = getattr(self, "new_original_revno", None)
676
if new_original_revno:
677
return new_original_revno
678
if getattr(self, "new_original_revid", None) is not None:
679
return self._lookup_revno(self.new_original_revid)
680
return self._lookup_revno(self.new_revid)
683
class InterFromGitBranch(branch.GenericInterBranch):
684
"""InterBranch implementation that pulls from Git into bzr."""
687
def _get_branch_formats_to_test():
689
default_format = branch.format_registry.get_default()
690
except AttributeError:
691
default_format = branch.BranchFormat._default_format
693
(GitBranchFormat(), GitBranchFormat()),
694
(GitBranchFormat(), default_format)]
697
def _get_interrepo(self, source, target):
698
return _mod_repository.InterRepository.get(source.repository, target.repository)
701
def is_compatible(cls, source, target):
702
if not isinstance(source, GitBranch):
704
if isinstance(target, GitBranch):
705
# InterLocalGitRemoteGitBranch or InterToGitBranch should be used
707
if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
708
# fetch_objects is necessary for this to work
712
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
713
self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
715
def fetch_objects(self, stop_revision, fetch_tags, limit=None):
716
interrepo = self._get_interrepo(self.source, self.target)
717
if fetch_tags is None:
718
c = self.source.get_config()
719
fetch_tags = c.get_user_option_as_bool('branch.fetch_tags')
720
def determine_wants(heads):
721
if self.source.ref is not None and not self.source.ref in heads:
722
raise NoSuchRef(self.source.ref, self.source.user_url, heads.keys())
724
if stop_revision is None:
725
if self.source.ref is not None:
726
head = heads[self.source.ref]
729
self._last_revid = self.source.lookup_foreign_revision_id(head)
731
self._last_revid = stop_revision
732
real = interrepo.get_determine_wants_revids(
733
[self._last_revid], include_tags=fetch_tags)
735
pack_hint, head, refs = interrepo.fetch_objects(
736
determine_wants, self.source.mapping, limit=limit)
737
if (pack_hint is not None and
738
self.target.repository._format.pack_compresses):
739
self.target.repository.pack(hint=pack_hint)
742
def _update_revisions(self, stop_revision=None, overwrite=False):
743
head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
745
prev_last_revid = None
747
prev_last_revid = self.target.last_revision()
748
self.target.generate_revision_history(self._last_revid,
749
prev_last_revid, self.source)
752
def _basic_pull(self, stop_revision, overwrite, run_hooks,
753
_override_hook_target, _hook_master):
754
result = GitBranchPullResult()
755
result.source_branch = self.source
756
if _override_hook_target is None:
757
result.target_branch = self.target
759
result.target_branch = _override_hook_target
760
self.source.lock_read()
762
self.target.lock_write()
764
# We assume that during 'pull' the target repository is closer than
766
(result.old_revno, result.old_revid) = \
767
self.target.last_revision_info()
768
result.new_git_head, remote_refs = self._update_revisions(
769
stop_revision, overwrite=overwrite)
770
tags_ret = self.source.tags.merge_to(
771
self.target.tags, overwrite)
772
if isinstance(tags_ret, tuple):
773
result.tag_updates, result.tag_conflicts = tags_ret
775
result.tag_conflicts = tags_ret
776
(result.new_revno, result.new_revid) = \
777
self.target.last_revision_info()
779
result.master_branch = _hook_master
780
result.local_branch = result.target_branch
782
result.master_branch = result.target_branch
783
result.local_branch = None
785
for hook in branch.Branch.hooks['post_pull']:
793
def pull(self, overwrite=False, stop_revision=None,
794
possible_transports=None, _hook_master=None, run_hooks=True,
795
_override_hook_target=None, local=False):
798
:param _hook_master: Private parameter - set the branch to
799
be supplied as the master to pull hooks.
800
:param run_hooks: Private parameter - if false, this branch
801
is being called because it's the master of the primary branch,
802
so it should not run its hooks.
803
:param _override_hook_target: Private parameter - set the branch to be
804
supplied as the target_branch to pull hooks.
806
# This type of branch can't be bound.
807
bound_location = self.target.get_bound_location()
808
if local and not bound_location:
809
raise errors.LocalRequiresBoundBranch()
811
source_is_master = False
812
self.source.lock_read()
814
# bound_location comes from a config file, some care has to be
815
# taken to relate it to source.user_url
816
normalized = urlutils.normalize_url(bound_location)
818
relpath = self.source.user_transport.relpath(normalized)
819
source_is_master = (relpath == '')
820
except (errors.PathNotChild, errors.InvalidURL):
821
source_is_master = False
822
if not local and bound_location and not source_is_master:
823
# not pulling from master, so we need to update master.
824
master_branch = self.target.get_master_branch(possible_transports)
825
master_branch.lock_write()
829
# pull from source into master.
830
master_branch.pull(self.source, overwrite, stop_revision,
832
result = self._basic_pull(stop_revision, overwrite, run_hooks,
833
_override_hook_target, _hook_master=master_branch)
838
master_branch.unlock()
841
def _basic_push(self, overwrite=False, stop_revision=None):
842
result = branch.BranchPushResult()
843
result.source_branch = self.source
844
result.target_branch = self.target
845
result.old_revno, result.old_revid = self.target.last_revision_info()
846
result.new_git_head, remote_refs = self._update_revisions(
847
stop_revision, overwrite=overwrite)
848
tags_ret = self.source.tags.merge_to(self.target.tags,
850
if isinstance(tags_ret, tuple):
851
(result.tag_updates, result.tag_conflicts) = tags_ret
853
result.tag_conflicts = tags_ret
854
result.new_revno, result.new_revid = self.target.last_revision_info()
858
class InterGitBranch(branch.GenericInterBranch):
859
"""InterBranch implementation that pulls between Git branches."""
862
class InterLocalGitRemoteGitBranch(InterGitBranch):
863
"""InterBranch that copies from a local to a remote git branch."""
866
def _get_branch_formats_to_test():
871
def is_compatible(self, source, target):
872
from bzrlib.plugins.git.remote import RemoteGitBranch
873
return (isinstance(source, LocalGitBranch) and
874
isinstance(target, RemoteGitBranch))
876
def _basic_push(self, overwrite=False, stop_revision=None):
877
result = GitBranchPushResult()
878
result.source_branch = self.source
879
result.target_branch = self.target
880
if stop_revision is None:
881
stop_revision = self.source.last_revision()
882
# FIXME: Check for diverged branches
883
def get_changed_refs(old_refs):
884
old_ref = old_refs.get(self.target.ref, ZERO_SHA)
885
result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
886
refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
887
result.new_revid = stop_revision
888
for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
889
refs[tag_name_to_ref(name)] = sha
891
self.target.repository.send_pack(get_changed_refs,
892
self.source.repository._git.object_store.generate_pack_contents)
896
class InterGitLocalGitBranch(InterGitBranch):
897
"""InterBranch that copies from a remote to a local git branch."""
900
def _get_branch_formats_to_test():
905
def is_compatible(self, source, target):
906
return (isinstance(source, GitBranch) and
907
isinstance(target, LocalGitBranch))
909
def _basic_push(self, overwrite=False, stop_revision=None):
910
result = GitBranchPushResult()
911
result.source_branch = self.source
912
result.target_branch = self.target
913
result.old_revid = self.target.last_revision()
914
refs, stop_revision = self.update_refs(stop_revision)
915
self.target.generate_revision_history(stop_revision, result.old_revid)
916
tags_ret = self.source.tags.merge_to(self.target.tags,
917
source_refs=refs, overwrite=overwrite)
918
if isinstance(tags_ret, tuple):
919
(result.tag_updates, result.tag_conflicts) = tags_ret
921
result.tag_conflicts = tags_ret
922
result.new_revid = self.target.last_revision()
925
def update_refs(self, stop_revision=None):
926
interrepo = _mod_repository.InterRepository.get(self.source.repository,
927
self.target.repository)
928
if stop_revision is None:
929
refs = interrepo.fetch(branches=["HEAD"])
930
stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
932
refs = interrepo.fetch(revision_id=stop_revision)
933
return refs, stop_revision
935
def pull(self, stop_revision=None, overwrite=False,
936
possible_transports=None, run_hooks=True,local=False):
937
# This type of branch can't be bound.
939
raise errors.LocalRequiresBoundBranch()
940
result = GitPullResult()
941
result.source_branch = self.source
942
result.target_branch = self.target
943
self.source.lock_read()
945
self.target.lock_write()
947
result.old_revid = self.target.last_revision()
948
refs, stop_revision = self.update_refs(stop_revision)
949
self.target.generate_revision_history(stop_revision, result.old_revid)
950
tags_ret = self.source.tags.merge_to(self.target.tags,
951
overwrite=overwrite, source_refs=refs)
952
if isinstance(tags_ret, tuple):
953
(result.tag_updates, result.tag_conflicts) = tags_ret
955
result.tag_conflicts = tags_ret
956
result.new_revid = self.target.last_revision()
957
result.local_branch = None
958
result.master_branch = result.target_branch
960
for hook in branch.Branch.hooks['post_pull']:
969
class InterToGitBranch(branch.GenericInterBranch):
970
"""InterBranch implementation that pulls into a Git branch."""
972
def __init__(self, source, target):
973
super(InterToGitBranch, self).__init__(source, target)
974
self.interrepo = _mod_repository.InterRepository.get(source.repository,
978
def _get_branch_formats_to_test():
980
default_format = branch.format_registry.get_default()
981
except AttributeError:
982
default_format = branch.BranchFormat._default_format
983
return [(default_format, GitBranchFormat())]
986
def is_compatible(self, source, target):
987
return (not isinstance(source, GitBranch) and
988
isinstance(target, GitBranch))
990
def _get_new_refs(self, stop_revision=None, fetch_tags=None):
991
assert self.source.is_locked()
992
if stop_revision is None:
993
(stop_revno, stop_revision) = self.source.last_revision_info()
995
stop_revno = self.source.revision_id_to_revno(stop_revision)
996
assert type(stop_revision) is str
997
main_ref = self.target.ref or "refs/heads/master"
998
refs = { main_ref: (None, stop_revision) }
999
if fetch_tags is None:
1000
c = self.source.get_config()
1001
fetch_tags = c.get_user_option_as_bool('branch.fetch_tags')
1002
for name, revid in self.source.tags.get_tag_dict().iteritems():
1003
if self.source.repository.has_revision(revid):
1004
ref = tag_name_to_ref(name)
1005
if not check_ref_format(ref):
1006
warning("skipping tag with invalid characters %s (%s)",
1010
# FIXME: Skip tags that are not in the ancestry
1011
refs[ref] = (None, revid)
1012
return refs, main_ref, (stop_revno, stop_revision)
1014
def _update_refs(self, result, old_refs, new_refs, overwrite):
1015
mutter("updating refs. old refs: %r, new refs: %r",
1017
result.tag_updates = {}
1018
result.tag_conflicts = []
1019
ret = dict(old_refs)
1020
def ref_equals(refs, ref, git_sha, revid):
1025
if (value[0] is not None and
1026
git_sha is not None and
1027
value[0] != git_sha):
1029
if (value[1] is not None and
1030
revid is not None and
1033
# FIXME: If one side only has the git sha available and the other only
1034
# has the bzr revid, then this will cause us to show a tag as updated
1035
# that hasn't actually been updated.
1037
for ref, (git_sha, revid) in new_refs.iteritems():
1038
if ref not in ret or overwrite:
1039
if not ref_equals(ret, ref, git_sha, revid):
1041
tag_name = ref_to_tag_name(ref)
1045
result.tag_updates[tag_name] = revid
1046
ret[ref] = (git_sha, revid)
1047
elif ref_equals(ret, ref, git_sha, revid):
1051
name = ref_to_tag_name(ref)
1055
result.tag_conflicts.append((name, revid, ret[name][1]))
1056
# FIXME: Check for diverged branches
1057
ret.update(new_refs)
1060
def pull(self, overwrite=False, stop_revision=None, local=False,
1061
possible_transports=None, run_hooks=True):
1062
result = GitBranchPullResult()
1063
result.source_branch = self.source
1064
result.target_branch = self.target
1065
self.source.lock_read()
1067
self.target.lock_write()
1069
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1071
def update_refs(old_refs):
1072
return self._update_refs(result, old_refs, new_refs, overwrite)
1074
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1075
update_refs, lossy=False)
1076
except NoPushSupport:
1077
raise errors.NoRoundtrippingSupport(self.source, self.target)
1078
(result.old_revid, old_sha1) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1079
if result.old_revid is None:
1080
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1081
result.new_revid = new_refs[main_ref][1]
1082
result.local_branch = None
1083
result.master_branch = self.target
1085
for hook in branch.Branch.hooks['post_pull']:
1088
self.target.unlock()
1090
self.source.unlock()
1093
def push(self, overwrite=False, stop_revision=None, lossy=False,
1094
_override_hook_source_branch=None):
1095
result = GitBranchPushResult()
1096
result.source_branch = self.source
1097
result.target_branch = self.target
1098
result.local_branch = None
1099
result.master_branch = result.target_branch
1100
self.source.lock_read()
1102
new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
1103
def update_refs(old_refs):
1104
return self._update_refs(result, old_refs, new_refs, overwrite)
1106
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1107
update_refs, lossy=lossy)
1108
except NoPushSupport:
1109
raise errors.NoRoundtrippingSupport(self.source, self.target)
1110
(old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1111
if result.old_revid is None:
1112
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1113
result.new_revid = new_refs[main_ref][1]
1114
(result.new_original_revno, result.new_original_revid) = stop_revinfo
1115
for hook in branch.Branch.hooks['post_push']:
1118
self.source.unlock()
1121
def lossy_push(self, stop_revision=None):
1122
# For compatibility with bzr < 2.4
1123
return self.push(lossy=True, stop_revision=stop_revision)
1126
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
1127
branch.InterBranch.register_optimiser(InterFromGitBranch)
1128
branch.InterBranch.register_optimiser(InterToGitBranch)
1129
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)