1
# Copyright (C) 2007,2012 Canonical Ltd
2
# Copyright (C) 2009-2012 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 __future__ import absolute_import
22
from cStringIO import StringIO
23
from collections import defaultdict
25
from dulwich.objects import (
28
from dulwich.repo import check_ref_format
35
repository as _mod_repository,
41
from ...decorators import (
44
from ...revision import (
47
from ...trace import (
67
from .unpeel_map import (
71
from ...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
102
def get_refs_container(self):
103
raise NotImplementedError(self.get_refs_container)
105
def _iter_tag_refs(self, refs):
106
"""Iterate over the tag refs.
108
:param refs: Refs dictionary (name -> git sha1)
109
:return: iterator over (name, peeled_sha1, unpeeled_sha1, bzr_revid)
111
for k, unpeeled in refs.as_dict().iteritems():
113
tag_name = ref_to_tag_name(k)
114
except (ValueError, UnicodeDecodeError):
116
peeled = refs.get_peeled(k)
118
peeled = self.repository.controldir._git.object_store.peel_sha(unpeeled).id
119
assert type(tag_name) is unicode
120
yield (tag_name, peeled, unpeeled,
121
self.branch.lookup_foreign_revision_id(peeled))
123
def _merge_to_remote_git(self, target_repo, new_refs, overwrite=False):
126
def get_changed_refs(old_refs):
128
for k, v in new_refs.iteritems():
131
name = ref_to_tag_name(k)
132
if old_refs.get(k) == v:
134
elif overwrite or not k in old_refs:
136
updates[name] = target_repo.lookup_foreign_revision_id(v)
138
conflicts.append((name, v, old_refs[k]))
140
target_repo.controldir.send_pack(get_changed_refs, lambda have, want: [])
141
return updates, conflicts
143
def _merge_to_local_git(self, target_repo, refs, overwrite=False):
146
for k, unpeeled in refs.as_dict().iteritems():
149
name = ref_to_tag_name(k)
150
peeled = self.repository.controldir.get_peeled(k)
151
if target_repo._git.refs.get(k) == unpeeled:
153
elif overwrite or not k in target_repo._git.refs:
154
target_repo._git.refs[k] = unpeeled or peeled
155
updates[name] = target_repo.lookup_foreign_revision_id(peeled)
157
conflicts.append((name, peeled, target_repo._git.refs[k]))
158
return updates, conflicts
160
def _merge_to_git(self, to_tags, refs, overwrite=False):
161
target_repo = to_tags.repository
162
if self.repository.has_same_location(target_repo):
164
if getattr(target_repo, "_git", None):
165
return self._merge_to_local_git(target_repo, refs, overwrite)
167
return self._merge_to_remote_git(target_repo, refs, overwrite)
169
def _merge_to_non_git(self, to_tags, refs, overwrite=False):
170
unpeeled_map = defaultdict(set)
173
result = dict(to_tags.get_tag_dict())
174
for n, peeled, unpeeled, bzr_revid in self._iter_tag_refs(refs):
175
if unpeeled is not None:
176
unpeeled_map[peeled].add(unpeeled)
177
if result.get(n) == bzr_revid:
179
elif n not in result or overwrite:
180
result[n] = bzr_revid
181
updates[n] = bzr_revid
183
conflicts.append((n, result[n], bzr_revid))
184
to_tags._set_tag_dict(result)
185
if len(unpeeled_map) > 0:
186
map_file = UnpeelMap.from_repository(to_tags.branch.repository)
187
map_file.update(unpeeled_map)
188
map_file.save_in_repository(to_tags.branch.repository)
189
return updates, conflicts
191
def merge_to(self, to_tags, overwrite=False, ignore_master=False,
193
"""See Tags.merge_to."""
194
if source_refs is None:
195
source_refs = self.get_refs_container()
198
if isinstance(to_tags, GitTags):
199
return self._merge_to_git(to_tags, source_refs,
205
master = to_tags.branch.get_master_branch()
206
updates, conflicts = self._merge_to_non_git(to_tags, source_refs,
208
if master is not None:
209
extra_updates, extra_conflicts = self.merge_to(
210
master.tags, overwrite=overwrite,
211
source_refs=source_refs,
212
ignore_master=ignore_master)
213
updates.update(extra_updates)
214
conflicts += extra_conflicts
215
return updates, conflicts
217
def get_tag_dict(self):
219
refs = self.get_refs_container()
220
for (name, peeled, unpeeled, bzr_revid) in self._iter_tag_refs(refs):
221
ret[name] = bzr_revid
225
class LocalGitTagDict(GitTags):
226
"""Dictionary with tags in a local repository."""
228
def __init__(self, branch):
229
super(LocalGitTagDict, self).__init__(branch)
230
self.refs = self.repository.controldir._git.refs
232
def get_refs_container(self):
235
def _set_tag_dict(self, to_dict):
236
extra = set(self.refs.allkeys())
237
for k, revid in to_dict.iteritems():
238
name = tag_name_to_ref(k)
241
self.set_tag(k, revid)
244
del self.repository._git[name]
246
def set_tag(self, name, revid):
248
git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
249
except errors.NoSuchRevision:
250
raise errors.GhostTagsNotSupported(self)
251
self.refs[tag_name_to_ref(name)] = git_sha
254
class DictTagDict(tag.BasicTags):
256
def __init__(self, branch, tags):
257
super(DictTagDict, self).__init__(branch)
260
def get_tag_dict(self):
264
class GitSymrefBranchFormat(branch.BranchFormat):
266
def get_format_description(self):
267
return 'Git Symbolic Reference Branch'
269
def network_name(self):
272
def get_reference(self, controldir, name=None):
273
return controldir.get_branch_reference(name)
275
def set_reference(self, controldir, name, target):
276
return controldir.set_branch_reference(target, name)
279
class GitBranchFormat(branch.BranchFormat):
281
def get_format_description(self):
284
def network_name(self):
287
def supports_tags(self):
290
def supports_leaving_lock(self):
293
def supports_tags_referencing_ghosts(self):
296
def tags_are_versioned(self):
300
def _matchingbzrdir(self):
301
from .dir import LocalGitControlDirFormat
302
return LocalGitControlDirFormat()
304
def get_foreign_tests_branch_factory(self):
305
from .tests.test_branch import ForeignTestsBranchFactory
306
return ForeignTestsBranchFactory()
308
def make_tags(self, branch):
311
except AttributeError:
313
if getattr(branch.repository, "_git", None) is None:
314
from .remote import RemoteGitTagDict
315
return RemoteGitTagDict(branch)
317
return LocalGitTagDict(branch)
319
def initialize(self, a_controldir, name=None, repository=None,
320
append_revisions_only=None):
321
from .dir import LocalGitDir
322
if not isinstance(a_controldir, LocalGitDir):
323
raise errors.IncompatibleFormat(self, a_controldir._format)
324
return a_controldir.create_branch(repository=repository, name=name,
325
append_revisions_only=append_revisions_only)
328
class GitReadLock(object):
330
def __init__(self, unlock):
334
class GitWriteLock(object):
336
def __init__(self, unlock):
337
self.branch_token = None
341
class GitBranch(ForeignBranch):
342
"""An adapter to git repositories for bzr Branch objects."""
345
def control_transport(self):
346
return self.controldir.control_transport
348
def __init__(self, controldir, repository, ref):
349
self.base = controldir.root_transport.base
350
self.repository = repository
351
self._format = GitBranchFormat()
352
self.controldir = controldir
353
self._lock_mode = None
355
super(GitBranch, self).__init__(repository.get_mapping())
358
self.name = ref_to_branch_name(ref)
363
def _get_checkout_format(self, lightweight=False):
364
"""Return the most suitable metadir for a checkout of this branch.
365
Weaves are used if this branch's repository uses weaves.
367
return controldir.format_registry.make_controldir("default")
369
def get_child_submit_format(self):
370
"""Return the preferred format of submissions to this branch."""
371
ret = self.get_config_stack().get("child_submit_format")
376
def get_config(self):
377
return GitBranchConfig(self)
379
def get_config_stack(self):
380
return GitBranchStack(self)
382
def _get_nick(self, local=False, possible_master_transports=None):
383
"""Find the nick name for this branch.
387
cs = self.repository._git.get_config_stack()
389
return cs.get(("branch", self.name), "nick")
392
return self.name.encode('utf-8') or "HEAD"
394
def _set_nick(self, nick):
395
cf = self.repository._git.get_config()
396
cf.set(("branch", self.name), "nick", nick)
399
self.controldir.control_transport.put_bytes('config', f.getvalue())
401
nick = property(_get_nick, _set_nick)
404
return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
407
def generate_revision_history(self, revid, old_revid=None):
408
if revid == NULL_REVISION:
411
# FIXME: Check that old_revid is in the ancestry of revid
412
newhead, self.mapping = self.repository.lookup_bzr_revision_id(revid)
413
if self.mapping is None:
415
self._set_head(newhead)
417
def lock_write(self, token=None):
418
if token is not None:
419
raise errors.TokenLockingNotSupported(self)
421
if self._lock_mode == 'r':
422
raise errors.ReadOnlyError(self)
423
self._lock_count += 1
425
self._lock_mode = 'w'
427
self.repository.lock_write()
428
return GitWriteLock(self.unlock)
430
def leave_lock_in_place(self):
431
raise NotImplementedError(self.leave_lock_in_place)
433
def dont_leave_lock_in_place(self):
434
raise NotImplementedError(self.dont_leave_lock_in_place)
436
def get_stacked_on_url(self):
437
# Git doesn't do stacking (yet...)
438
raise branch.UnstackableBranchFormat(self._format, self.base)
440
def get_parent(self):
441
"""See Branch.get_parent()."""
442
# FIXME: Set "origin" url from .git/config ?
445
def set_parent(self, url):
446
# FIXME: Set "origin" url in .git/config ?
449
def break_lock(self):
450
raise NotImplementedError(self.break_lock)
454
assert self._lock_mode in ('r', 'w')
455
self._lock_count += 1
457
self._lock_mode = 'r'
459
self.repository.lock_read()
460
return GitReadLock(self.unlock)
462
def peek_lock_mode(self):
463
return self._lock_mode
466
return (self._lock_mode is not None)
469
"""See Branch.unlock()."""
470
self._lock_count -= 1
471
if self._lock_count == 0:
472
self._lock_mode = None
473
self._clear_cached_state()
474
self.repository.unlock()
476
def get_physical_lock_status(self):
480
def last_revision(self):
481
# perhaps should escape this ?
482
if self.head is None:
483
return revision.NULL_REVISION
484
return self.lookup_foreign_revision_id(self.head)
486
def _basic_push(self, target, overwrite=False, stop_revision=None):
487
return branch.InterBranch.get(self, target)._basic_push(
488
overwrite, stop_revision)
490
def lookup_foreign_revision_id(self, foreign_revid):
491
return self.repository.lookup_foreign_revision_id(foreign_revid,
494
def lookup_bzr_revision_id(self, revid):
495
return self.repository.lookup_bzr_revision_id(
496
revid, mapping=self.mapping)
499
class LocalGitBranch(GitBranch):
500
"""A local Git branch."""
502
def __init__(self, controldir, repository, ref):
503
super(LocalGitBranch, self).__init__(controldir, repository, ref)
504
refs = controldir.get_refs_container()
505
if not (ref in refs or "HEAD" in refs):
506
raise errors.NotBranchError(self.base)
508
def create_checkout(self, to_location, revision_id=None, lightweight=False,
509
accelerator_tree=None, hardlink=False):
511
t = transport.get_transport(to_location)
513
format = self._get_checkout_format(lightweight=True)
514
checkout = format.initialize_on_transport(t)
515
from breezy.bzr.branch import BranchReferenceFormat
516
from_branch = BranchReferenceFormat().initialize(checkout, self)
517
tree = checkout.create_workingtree(revision_id,
518
from_branch=from_branch, hardlink=hardlink)
521
return self._create_heavyweight_checkout(to_location, revision_id,
524
def _create_heavyweight_checkout(self, to_location, revision_id=None,
526
"""Create a new heavyweight checkout of this branch.
528
:param to_location: URL of location to create the new checkout in.
529
:param revision_id: Revision that should be the tip of the checkout.
530
:param hardlink: Whether to hardlink
531
:return: WorkingTree object of checkout.
533
checkout_branch = controldir.ControlDir.create_branch_convenience(
534
to_location, force_new_tree=False,
535
format=self._get_checkout_format(lightweight=False))
536
checkout = checkout_branch.controldir
537
checkout_branch.bind(self)
538
# pull up to the specified revision_id to set the initial
539
# branch tip correctly, and seed it with history.
540
checkout_branch.pull(self, stop_revision=revision_id)
541
return checkout.create_workingtree(revision_id, hardlink=hardlink)
543
def fetch(self, from_branch, last_revision=None, limit=None):
544
return branch.InterBranch.get(from_branch, self).fetch(
545
stop_revision=last_revision, limit=limit)
547
def _gen_revision_history(self):
548
if self.head is None:
550
graph = self.repository.get_graph()
551
ret = list(graph.iter_lefthand_ancestry(self.last_revision(),
552
(revision.NULL_REVISION, )))
558
return self.repository._git.refs[self.ref or "HEAD"]
562
def _read_last_revision_info(self):
563
last_revid = self.last_revision()
564
graph = self.repository.get_graph()
565
revno = graph.find_distance_to_null(last_revid,
566
[(revision.NULL_REVISION, 0)])
567
return revno, last_revid
569
def set_last_revision_info(self, revno, revision_id):
570
self.set_last_revision(revision_id)
571
self._last_revision_info_cache = revno, revision_id
573
def set_last_revision(self, revid):
574
if not revid or not isinstance(revid, basestring):
575
raise errors.InvalidRevisionId(revision_id=revid, branch=self)
576
if revid == NULL_REVISION:
579
(newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
580
if self.mapping is None:
582
self._set_head(newhead)
584
def _set_head(self, value):
586
self.repository._git.refs[self.ref or "HEAD"] = self._head
587
self._clear_cached_state()
589
head = property(_get_head, _set_head)
591
def get_push_location(self):
592
"""See Branch.get_push_location."""
593
push_loc = self.get_config_stack().get('push_location')
596
def set_push_location(self, location):
597
"""See Branch.set_push_location."""
598
self.get_config().set_user_option('push_location', location,
599
store=config.STORE_LOCATION)
601
def supports_tags(self):
605
def _quick_lookup_revno(local_branch, remote_branch, revid):
606
assert isinstance(revid, str), "was %r" % revid
607
# Try in source branch first, it'll be faster
608
local_branch.lock_read()
611
return local_branch.revision_id_to_revno(revid)
612
except errors.NoSuchRevision:
613
graph = local_branch.repository.get_graph()
615
return graph.find_distance_to_null(revid,
616
[(revision.NULL_REVISION, 0)])
617
except errors.GhostRevisionsHaveNoRevno:
618
# FIXME: Check using graph.find_distance_to_null() ?
619
remote_branch.lock_read()
621
return remote_branch.revision_id_to_revno(revid)
623
remote_branch.unlock()
625
local_branch.unlock()
628
class GitBranchPullResult(branch.PullResult):
631
super(GitBranchPullResult, self).__init__()
632
self.new_git_head = None
633
self._old_revno = None
634
self._new_revno = None
636
def report(self, to_file):
638
if self.old_revid == self.new_revid:
639
to_file.write('No revisions to pull.\n')
640
elif self.new_git_head is not None:
641
to_file.write('Now on revision %d (git sha: %s).\n' %
642
(self.new_revno, self.new_git_head))
644
to_file.write('Now on revision %d.\n' % (self.new_revno,))
645
self._show_tag_conficts(to_file)
647
def _lookup_revno(self, revid):
648
return _quick_lookup_revno(self.target_branch, self.source_branch,
651
def _get_old_revno(self):
652
if self._old_revno is not None:
653
return self._old_revno
654
return self._lookup_revno(self.old_revid)
656
def _set_old_revno(self, revno):
657
self._old_revno = revno
659
old_revno = property(_get_old_revno, _set_old_revno)
661
def _get_new_revno(self):
662
if self._new_revno is not None:
663
return self._new_revno
664
return self._lookup_revno(self.new_revid)
666
def _set_new_revno(self, revno):
667
self._new_revno = revno
669
new_revno = property(_get_new_revno, _set_new_revno)
672
class GitBranchPushResult(branch.BranchPushResult):
674
def _lookup_revno(self, revid):
675
return _quick_lookup_revno(self.source_branch, self.target_branch,
680
return self._lookup_revno(self.old_revid)
684
new_original_revno = getattr(self, "new_original_revno", None)
685
if new_original_revno:
686
return new_original_revno
687
if getattr(self, "new_original_revid", None) is not None:
688
return self._lookup_revno(self.new_original_revid)
689
return self._lookup_revno(self.new_revid)
692
class InterFromGitBranch(branch.GenericInterBranch):
693
"""InterBranch implementation that pulls from Git into bzr."""
696
def _get_branch_formats_to_test():
698
default_format = branch.format_registry.get_default()
699
except AttributeError:
700
default_format = branch.BranchFormat._default_format
702
(GitBranchFormat(), GitBranchFormat()),
703
(GitBranchFormat(), default_format)]
706
def _get_interrepo(self, source, target):
707
return _mod_repository.InterRepository.get(source.repository, target.repository)
710
def is_compatible(cls, source, target):
711
if not isinstance(source, GitBranch):
713
if isinstance(target, GitBranch):
714
# InterLocalGitRemoteGitBranch or InterToGitBranch should be used
716
if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
717
# fetch_objects is necessary for this to work
721
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
722
self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
724
def fetch_objects(self, stop_revision, fetch_tags, limit=None):
725
interrepo = self._get_interrepo(self.source, self.target)
726
if fetch_tags is None:
727
c = self.source.get_config_stack()
728
fetch_tags = c.get('branch.fetch_tags')
729
def determine_wants(heads):
730
if self.source.ref is not None and not self.source.ref in heads:
731
raise NoSuchRef(self.source.ref, self.source.user_url, heads.keys())
733
if stop_revision is None:
734
if self.source.ref is not None:
735
head = heads[self.source.ref]
738
self._last_revid = self.source.lookup_foreign_revision_id(head)
740
self._last_revid = stop_revision
741
real = interrepo.get_determine_wants_revids(
742
[self._last_revid], include_tags=fetch_tags)
744
pack_hint, head, refs = interrepo.fetch_objects(
745
determine_wants, self.source.mapping, limit=limit)
746
if (pack_hint is not None and
747
self.target.repository._format.pack_compresses):
748
self.target.repository.pack(hint=pack_hint)
751
def _update_revisions(self, stop_revision=None, overwrite=False):
752
head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
754
prev_last_revid = None
756
prev_last_revid = self.target.last_revision()
757
self.target.generate_revision_history(self._last_revid,
758
prev_last_revid, self.source)
761
def _basic_pull(self, stop_revision, overwrite, run_hooks,
762
_override_hook_target, _hook_master):
763
result = GitBranchPullResult()
764
result.source_branch = self.source
765
if _override_hook_target is None:
766
result.target_branch = self.target
768
result.target_branch = _override_hook_target
769
self.source.lock_read()
771
self.target.lock_write()
773
# We assume that during 'pull' the target repository is closer than
775
(result.old_revno, result.old_revid) = \
776
self.target.last_revision_info()
777
result.new_git_head, remote_refs = self._update_revisions(
778
stop_revision, overwrite=overwrite)
779
tags_ret = self.source.tags.merge_to(
780
self.target.tags, overwrite, ignore_master=True)
781
if isinstance(tags_ret, tuple):
782
result.tag_updates, result.tag_conflicts = tags_ret
784
result.tag_conflicts = tags_ret
785
(result.new_revno, result.new_revid) = \
786
self.target.last_revision_info()
788
result.master_branch = _hook_master
789
result.local_branch = result.target_branch
791
result.master_branch = result.target_branch
792
result.local_branch = None
794
for hook in branch.Branch.hooks['post_pull']:
802
def pull(self, overwrite=False, stop_revision=None,
803
possible_transports=None, _hook_master=None, run_hooks=True,
804
_override_hook_target=None, local=False):
807
:param _hook_master: Private parameter - set the branch to
808
be supplied as the master to pull hooks.
809
:param run_hooks: Private parameter - if false, this branch
810
is being called because it's the master of the primary branch,
811
so it should not run its hooks.
812
:param _override_hook_target: Private parameter - set the branch to be
813
supplied as the target_branch to pull hooks.
815
# This type of branch can't be bound.
816
bound_location = self.target.get_bound_location()
817
if local and not bound_location:
818
raise errors.LocalRequiresBoundBranch()
820
source_is_master = False
821
self.source.lock_read()
823
# bound_location comes from a config file, some care has to be
824
# taken to relate it to source.user_url
825
normalized = urlutils.normalize_url(bound_location)
827
relpath = self.source.user_transport.relpath(normalized)
828
source_is_master = (relpath == '')
829
except (errors.PathNotChild, urlutils.InvalidURL):
830
source_is_master = False
831
if not local and bound_location and not source_is_master:
832
# not pulling from master, so we need to update master.
833
master_branch = self.target.get_master_branch(possible_transports)
834
master_branch.lock_write()
838
# pull from source into master.
839
master_branch.pull(self.source, overwrite, stop_revision,
841
result = self._basic_pull(stop_revision, overwrite, run_hooks,
842
_override_hook_target, _hook_master=master_branch)
847
master_branch.unlock()
850
def _basic_push(self, overwrite=False, stop_revision=None):
851
result = branch.BranchPushResult()
852
result.source_branch = self.source
853
result.target_branch = self.target
854
result.old_revno, result.old_revid = self.target.last_revision_info()
855
result.new_git_head, remote_refs = self._update_revisions(
856
stop_revision, overwrite=overwrite)
857
tags_ret = self.source.tags.merge_to(self.target.tags,
859
if isinstance(tags_ret, tuple):
860
(result.tag_updates, result.tag_conflicts) = tags_ret
862
result.tag_conflicts = tags_ret
863
result.new_revno, result.new_revid = self.target.last_revision_info()
867
class InterGitBranch(branch.GenericInterBranch):
868
"""InterBranch implementation that pulls between Git branches."""
870
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
871
raise NotImplementedError(self.fetch)
874
class InterLocalGitRemoteGitBranch(InterGitBranch):
875
"""InterBranch that copies from a local to a remote git branch."""
878
def _get_branch_formats_to_test():
883
def is_compatible(self, source, target):
884
from .remote import RemoteGitBranch
885
return (isinstance(source, LocalGitBranch) and
886
isinstance(target, RemoteGitBranch))
888
def _basic_push(self, overwrite=False, stop_revision=None):
889
result = GitBranchPushResult()
890
result.source_branch = self.source
891
result.target_branch = self.target
892
if stop_revision is None:
893
stop_revision = self.source.last_revision()
894
# FIXME: Check for diverged branches
895
def get_changed_refs(old_refs):
896
old_ref = old_refs.get(self.target.ref, ZERO_SHA)
897
result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
898
refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
899
result.new_revid = stop_revision
900
for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
901
refs[tag_name_to_ref(name)] = sha
903
self.target.repository.send_pack(get_changed_refs,
904
self.source.repository._git.object_store.generate_pack_contents)
908
class InterGitLocalGitBranch(InterGitBranch):
909
"""InterBranch that copies from a remote to a local git branch."""
912
def _get_branch_formats_to_test():
917
def is_compatible(self, source, target):
918
return (isinstance(source, GitBranch) and
919
isinstance(target, LocalGitBranch))
921
def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
922
interrepo = _mod_repository.InterRepository.get(self.source.repository,
923
self.target.repository)
924
if stop_revision is None:
925
stop_revision = self.source.last_revision()
926
determine_wants = interrepo.get_determine_wants_revids(
927
[stop_revision], include_tags=fetch_tags)
928
interrepo.fetch_objects(determine_wants, limit=limit)
930
def _basic_push(self, overwrite=False, stop_revision=None):
931
result = GitBranchPushResult()
932
result.source_branch = self.source
933
result.target_branch = self.target
934
result.old_revid = self.target.last_revision()
935
refs, stop_revision = self.update_refs(stop_revision)
936
self.target.generate_revision_history(stop_revision, result.old_revid)
937
tags_ret = self.source.tags.merge_to(self.target.tags,
938
source_refs=refs, overwrite=overwrite)
939
if isinstance(tags_ret, tuple):
940
(result.tag_updates, result.tag_conflicts) = tags_ret
942
result.tag_conflicts = tags_ret
943
result.new_revid = self.target.last_revision()
946
def update_refs(self, stop_revision=None):
947
interrepo = _mod_repository.InterRepository.get(self.source.repository,
948
self.target.repository)
949
if stop_revision is None:
950
refs = interrepo.fetch(branches=["HEAD"])
951
stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
953
refs = interrepo.fetch(revision_id=stop_revision)
954
return refs, stop_revision
956
def pull(self, stop_revision=None, overwrite=False,
957
possible_transports=None, run_hooks=True,local=False):
958
# This type of branch can't be bound.
960
raise errors.LocalRequiresBoundBranch()
961
result = GitPullResult()
962
result.source_branch = self.source
963
result.target_branch = self.target
964
self.source.lock_read()
966
self.target.lock_write()
968
result.old_revid = self.target.last_revision()
969
refs, stop_revision = self.update_refs(stop_revision)
970
self.target.generate_revision_history(stop_revision, result.old_revid)
971
tags_ret = self.source.tags.merge_to(self.target.tags,
972
overwrite=overwrite, source_refs=refs)
973
if isinstance(tags_ret, tuple):
974
(result.tag_updates, result.tag_conflicts) = tags_ret
976
result.tag_conflicts = tags_ret
977
result.new_revid = self.target.last_revision()
978
result.local_branch = None
979
result.master_branch = result.target_branch
981
for hook in branch.Branch.hooks['post_pull']:
990
class InterToGitBranch(branch.GenericInterBranch):
991
"""InterBranch implementation that pulls into a Git branch."""
993
def __init__(self, source, target):
994
super(InterToGitBranch, self).__init__(source, target)
995
self.interrepo = _mod_repository.InterRepository.get(source.repository,
999
def _get_branch_formats_to_test():
1001
default_format = branch.format_registry.get_default()
1002
except AttributeError:
1003
default_format = branch.BranchFormat._default_format
1004
return [(default_format, GitBranchFormat())]
1007
def is_compatible(self, source, target):
1008
return (not isinstance(source, GitBranch) and
1009
isinstance(target, GitBranch))
1011
def _get_new_refs(self, stop_revision=None, fetch_tags=None):
1012
assert self.source.is_locked()
1013
if stop_revision is None:
1014
(stop_revno, stop_revision) = self.source.last_revision_info()
1016
stop_revno = self.source.revision_id_to_revno(stop_revision)
1017
assert type(stop_revision) is str
1018
main_ref = self.target.ref or "refs/heads/master"
1019
refs = { main_ref: (None, stop_revision) }
1020
if fetch_tags is None:
1021
c = self.source.get_config_stack()
1022
fetch_tags = c.get('branch.fetch_tags')
1023
for name, revid in self.source.tags.get_tag_dict().iteritems():
1024
if self.source.repository.has_revision(revid):
1025
ref = tag_name_to_ref(name)
1026
if not check_ref_format(ref):
1027
warning("skipping tag with invalid characters %s (%s)",
1031
# FIXME: Skip tags that are not in the ancestry
1032
refs[ref] = (None, revid)
1033
return refs, main_ref, (stop_revno, stop_revision)
1035
def _update_refs(self, result, old_refs, new_refs, overwrite):
1036
mutter("updating refs. old refs: %r, new refs: %r",
1038
result.tag_updates = {}
1039
result.tag_conflicts = []
1040
ret = dict(old_refs)
1041
def ref_equals(refs, ref, git_sha, revid):
1046
if (value[0] is not None and
1047
git_sha is not None and
1048
value[0] == git_sha):
1050
if (value[1] is not None and
1051
revid is not None and
1054
# FIXME: If one side only has the git sha available and the other only
1055
# has the bzr revid, then this will cause us to show a tag as updated
1056
# that hasn't actually been updated.
1058
# FIXME: Check for diverged branches
1059
for ref, (git_sha, revid) in new_refs.iteritems():
1060
if ref_equals(ret, ref, git_sha, revid):
1061
# Already up to date
1063
git_sha = old_refs[ref][0]
1065
revid = old_refs[ref][1]
1066
ret[ref] = new_refs[ref] = (git_sha, revid)
1067
elif ref not in ret or overwrite:
1069
tag_name = ref_to_tag_name(ref)
1073
result.tag_updates[tag_name] = revid
1074
ret[ref] = (git_sha, revid)
1076
# FIXME: Check diverged
1080
name = ref_to_tag_name(ref)
1084
result.tag_conflicts.append((name, revid, ret[name][1]))
1086
ret[ref] = (git_sha, revid)
1089
def fetch(self, stop_revision=None, fetch_tags=None, lossy=False, limit=None):
1090
assert limit is None
1091
if stop_revision is None:
1092
stop_revision = self.source.last_revision()
1095
for k, v in self.source.tags.get_tag_dict().iteritems():
1096
ret.append((None, v))
1097
ret.append((None, stop_revision))
1098
self.interrepo.fetch_objects(ret, lossy=lossy)
1100
def pull(self, overwrite=False, stop_revision=None, local=False,
1101
possible_transports=None, run_hooks=True):
1102
result = GitBranchPullResult()
1103
result.source_branch = self.source
1104
result.target_branch = self.target
1105
self.source.lock_read()
1107
self.target.lock_write()
1109
new_refs, main_ref, stop_revinfo = self._get_new_refs(
1111
def update_refs(old_refs):
1112
return self._update_refs(result, old_refs, new_refs, overwrite)
1114
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1115
update_refs, lossy=False)
1116
except NoPushSupport:
1117
raise errors.NoRoundtrippingSupport(self.source, self.target)
1118
(old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1119
if result.old_revid is None:
1120
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1121
result.new_revid = new_refs[main_ref][1]
1122
result.local_branch = None
1123
result.master_branch = self.target
1125
for hook in branch.Branch.hooks['post_pull']:
1128
self.target.unlock()
1130
self.source.unlock()
1133
def push(self, overwrite=False, stop_revision=None, lossy=False,
1134
_override_hook_source_branch=None):
1135
result = GitBranchPushResult()
1136
result.source_branch = self.source
1137
result.target_branch = self.target
1138
result.local_branch = None
1139
result.master_branch = result.target_branch
1140
self.source.lock_read()
1142
new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
1143
def update_refs(old_refs):
1144
return self._update_refs(result, old_refs, new_refs, overwrite)
1146
result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1147
update_refs, lossy=lossy)
1148
except NoPushSupport:
1149
raise errors.NoRoundtrippingSupport(self.source, self.target)
1150
(old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1151
if result.old_revid is None:
1152
result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1153
result.new_revid = new_refs[main_ref][1]
1154
(result.new_original_revno, result.new_original_revid) = stop_revinfo
1155
for hook in branch.Branch.hooks['post_push']:
1158
self.source.unlock()
1162
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
1163
branch.InterBranch.register_optimiser(InterFromGitBranch)
1164
branch.InterBranch.register_optimiser(InterToGitBranch)
1165
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)