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 dulwich.objects import (
35
from bzrlib.decorators import (
38
from bzrlib.revision import (
41
from bzrlib.trace import (
46
from bzrlib.plugins.git.config import (
49
from bzrlib.plugins.git.errors import (
53
from bzrlib.plugins.git.refs import (
59
from bzrlib.foreign import ForeignBranch
62
class GitPullResult(branch.PullResult):
63
"""Result of a pull from a Git branch."""
65
def _lookup_revno(self, revid):
66
assert isinstance(revid, str), "was %r" % revid
67
# Try in source branch first, it'll be faster
68
return self.target_branch.revision_id_to_revno(revid)
72
return self._lookup_revno(self.old_revid)
76
return self._lookup_revno(self.new_revid)
79
class LocalGitTagDict(tag.BasicTags):
80
"""Dictionary with tags in a local repository."""
82
def __init__(self, branch):
84
self.repository = branch.repository
86
def get_tag_dict(self):
88
for k,v in extract_tags(self.repository._git.get_refs()).iteritems():
90
obj = self.repository._git[v]
92
mutter("Tag %s points at unknown object %s, ignoring", v, obj)
94
while isinstance(obj, Tag):
96
obj = self.repository._git[v]
97
if not isinstance(obj, Commit):
98
mutter("Tag %s points at object %r that is not a commit, "
101
ret[k] = self.branch.lookup_foreign_revision_id(v)
104
def _set_tag_dict(self, to_dict):
105
extra = set(self.repository._git.get_refs().keys())
106
for k, revid in to_dict.iteritems():
107
name = tag_name_to_ref(k)
110
self.set_tag(k, revid)
112
if name.startswith("refs/tags/"):
113
del self.repository._git[name]
115
def set_tag(self, name, revid):
116
self.repository._git.refs[tag_name_to_ref(name)], _ = \
117
self.branch.mapping.revision_id_bzr_to_foreign(revid)
120
class DictTagDict(LocalGitTagDict):
122
def __init__(self, branch, tags):
123
super(DictTagDict, self).__init__(branch)
126
def get_tag_dict(self):
130
class GitBranchFormat(branch.BranchFormat):
132
def get_format_description(self):
135
def network_name(self):
138
def supports_tags(self):
141
def get_foreign_tests_branch_factory(self):
142
from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
143
return ForeignTestsBranchFactory()
145
def make_tags(self, branch):
146
if getattr(branch.repository, "get_refs", None) is not None:
147
from bzrlib.plugins.git.remote import RemoteGitTagDict
148
return RemoteGitTagDict(branch)
150
return LocalGitTagDict(branch)
153
class GitReadLock(object):
155
def __init__(self, unlock):
159
class GitWriteLock(object):
161
def __init__(self, unlock):
165
class GitBranch(ForeignBranch):
166
"""An adapter to git repositories for bzr Branch objects."""
168
def __init__(self, bzrdir, repository, ref, lockfiles, tagsdict=None):
169
self.repository = repository
170
self._format = GitBranchFormat()
171
self.control_files = lockfiles
173
super(GitBranch, self).__init__(repository.get_mapping())
174
if tagsdict is not None:
175
self.tags = DictTagDict(self, tagsdict)
177
self.name = ref_to_branch_name(ref)
179
self.base = bzrdir.root_transport.base
181
def _get_checkout_format(self):
182
"""Return the most suitable metadir for a checkout of this branch.
183
Weaves are used if this branch's repository uses weaves.
185
return bzrdir.format_registry.make_bzrdir("default")
187
def get_child_submit_format(self):
188
"""Return the preferred format of submissions to this branch."""
189
ret = self.get_config().get_user_option("child_submit_format")
194
def _get_nick(self, local=False, possible_master_transports=None):
195
"""Find the nick name for this branch.
199
return self.name or "HEAD"
201
def _set_nick(self, nick):
202
raise NotImplementedError
204
nick = property(_get_nick, _set_nick)
207
return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
210
def generate_revision_history(self, revid, old_revid=None):
211
# FIXME: Check that old_revid is in the ancestry of revid
212
newhead, self.mapping = self.mapping.revision_id_bzr_to_foreign(revid)
213
self._set_head(newhead)
215
def lock_write(self):
216
self.control_files.lock_write()
217
return GitWriteLock(self.unlock)
219
def get_stacked_on_url(self):
220
# Git doesn't do stacking (yet...)
221
raise errors.UnstackableBranchFormat(self._format, self.base)
223
def get_parent(self):
224
"""See Branch.get_parent()."""
225
# FIXME: Set "origin" url from .git/config ?
228
def set_parent(self, url):
229
# FIXME: Set "origin" url in .git/config ?
233
self.control_files.lock_read()
234
return GitReadLock(self.unlock)
237
return self.control_files.is_locked()
240
self.control_files.unlock()
242
def get_physical_lock_status(self):
246
def last_revision(self):
247
# perhaps should escape this ?
248
if self.head is None:
249
return revision.NULL_REVISION
250
return self.lookup_foreign_revision_id(self.head)
252
def _basic_push(self, target, overwrite=False, stop_revision=None):
253
return branch.InterBranch.get(self, target)._basic_push(
254
overwrite, stop_revision)
256
def lookup_foreign_revision_id(self, foreign_revid):
257
return self.repository.lookup_foreign_revision_id(foreign_revid,
261
class LocalGitBranch(GitBranch):
262
"""A local Git branch."""
264
def __init__(self, bzrdir, repository, name, lockfiles, tagsdict=None):
265
super(LocalGitBranch, self).__init__(bzrdir, repository, name,
267
refs = repository._git.get_refs()
268
if not (name in refs.keys() or "HEAD" in refs.keys()):
269
raise errors.NotBranchError(self.base)
271
def create_checkout(self, to_location, revision_id=None, lightweight=False,
272
accelerator_tree=None, hardlink=False):
274
t = transport.get_transport(to_location)
276
format = self._get_checkout_format()
277
checkout = format.initialize_on_transport(t)
278
from_branch = branch.BranchReferenceFormat().initialize(checkout,
280
tree = checkout.create_workingtree(revision_id,
281
from_branch=from_branch, hardlink=hardlink)
284
return self._create_heavyweight_checkout(to_location, revision_id,
287
def _create_heavyweight_checkout(self, to_location, revision_id=None,
289
"""Create a new heavyweight checkout of this branch.
291
:param to_location: URL of location to create the new checkout in.
292
:param revision_id: Revision that should be the tip of the checkout.
293
:param hardlink: Whether to hardlink
294
:return: WorkingTree object of checkout.
296
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
297
to_location, force_new_tree=False)
298
checkout = checkout_branch.bzrdir
299
checkout_branch.bind(self)
300
# pull up to the specified revision_id to set the initial
301
# branch tip correctly, and seed it with history.
302
checkout_branch.pull(self, stop_revision=revision_id)
303
return checkout.create_workingtree(revision_id, hardlink=hardlink)
305
def _gen_revision_history(self):
306
if self.head is None:
308
ret = list(self.repository.iter_reverse_revision_history(
309
self.last_revision()))
315
return self.repository._git.ref(self.ref or "HEAD")
319
def set_last_revision_info(self, revno, revid):
320
self.set_last_revision(revid)
322
def set_last_revision(self, revid):
323
(newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
326
def _set_head(self, value):
328
self.repository._git.refs[self.ref or "HEAD"] = self._head
329
self._clear_cached_state()
331
head = property(_get_head, _set_head)
333
def get_config(self):
334
return GitBranchConfig(self)
336
def get_push_location(self):
337
"""See Branch.get_push_location."""
338
push_loc = self.get_config().get_user_option('push_location')
341
def set_push_location(self, location):
342
"""See Branch.set_push_location."""
343
self.get_config().set_user_option('push_location', location,
344
store=config.STORE_LOCATION)
346
def supports_tags(self):
350
class GitBranchPullResult(branch.PullResult):
353
super(GitBranchPullResult, self).__init__()
354
self.new_git_head = None
355
self._old_revno = None
356
self._new_revno = None
358
def report(self, to_file):
360
if self.old_revid == self.new_revid:
361
to_file.write('No revisions to pull.\n')
362
elif self.new_git_head is not None:
363
to_file.write('Now on revision %d (git sha: %s).\n' %
364
(self.new_revno, self.new_git_head))
366
to_file.write('Now on revision %d.\n' % (self.new_revno,))
367
self._show_tag_conficts(to_file)
369
def _lookup_revno(self, revid):
370
assert isinstance(revid, str), "was %r" % revid
371
# Try in source branch first, it'll be faster
373
return self.source_branch.revision_id_to_revno(revid)
374
except errors.NoSuchRevision:
375
# FIXME: Check using graph.find_distance_to_null() ?
376
return self.target_branch.revision_id_to_revno(revid)
378
def _get_old_revno(self):
379
if self._old_revno is not None:
380
return self._old_revno
381
return self._lookup_revno(self.old_revid)
383
def _set_old_revno(self, revno):
384
self._old_revno = revno
386
old_revno = property(_get_old_revno, _set_old_revno)
388
def _get_new_revno(self):
389
if self._new_revno is not None:
390
return self._new_revno
391
return self._lookup_revno(self.new_revid)
393
def _set_new_revno(self, revno):
394
self._new_revno = revno
396
new_revno = property(_get_new_revno, _set_new_revno)
399
class GitBranchPushResult(branch.BranchPushResult):
401
def _lookup_revno(self, revid):
402
assert isinstance(revid, str), "was %r" % revid
403
# Try in source branch first, it'll be faster
405
return self.source_branch.revision_id_to_revno(revid)
406
except errors.NoSuchRevision:
407
# FIXME: Check using graph.find_distance_to_null() ?
408
return self.target_branch.revision_id_to_revno(revid)
412
return self._lookup_revno(self.old_revid)
416
return self._lookup_revno(self.new_revid)
419
class InterFromGitBranch(branch.GenericInterBranch):
420
"""InterBranch implementation that pulls from Git into bzr."""
423
def _get_interrepo(self, source, target):
424
return repository.InterRepository.get(source.repository,
428
def is_compatible(cls, source, target):
429
return (isinstance(source, GitBranch) and
430
not isinstance(target, GitBranch) and
431
(getattr(cls._get_interrepo(source, target), "fetch_objects", None) is not None))
433
def _update_revisions(self, stop_revision=None, overwrite=False,
434
graph=None, limit=None):
435
"""Like InterBranch.update_revisions(), but with additions.
437
Compared to the `update_revisions()` below, this function takes a
438
`limit` argument that limits how many git commits will be converted
439
and returns the new git head.
441
interrepo = self._get_interrepo(self.source, self.target)
442
def determine_wants(heads):
443
if self.source.ref is not None and not self.source.ref in heads:
444
raise NoSuchRef(self.source.ref, heads.keys())
445
if stop_revision is not None:
446
self._last_revid = stop_revision
447
head, mapping = self.source.repository.lookup_bzr_revision_id(
450
if self.source.ref is not None:
451
head = heads[self.source.ref]
454
self._last_revid = self.source.lookup_foreign_revision_id(head)
455
if self.target.repository.has_revision(self._last_revid):
458
pack_hint, head = interrepo.fetch_objects(
459
determine_wants, self.source.mapping, limit=limit)
460
if (pack_hint is not None and
461
self.target.repository._format.pack_compresses):
462
self.target.repository.pack(hint=pack_hint)
464
self._last_revid = self.source.lookup_foreign_revision_id(head)
466
prev_last_revid = None
468
prev_last_revid = self.target.last_revision()
469
self.target.generate_revision_history(self._last_revid,
473
def update_revisions(self, stop_revision=None, overwrite=False,
475
"""See InterBranch.update_revisions()."""
476
self._update_revisions(stop_revision, overwrite, graph)
478
def pull(self, overwrite=False, stop_revision=None,
479
possible_transports=None, _hook_master=None, run_hooks=True,
480
_override_hook_target=None, local=False, limit=None):
483
:param _hook_master: Private parameter - set the branch to
484
be supplied as the master to pull hooks.
485
:param run_hooks: Private parameter - if false, this branch
486
is being called because it's the master of the primary branch,
487
so it should not run its hooks.
488
:param _override_hook_target: Private parameter - set the branch to be
489
supplied as the target_branch to pull hooks.
490
:param limit: Only import this many revisons. `None`, the default,
491
means import all revisions.
493
# This type of branch can't be bound.
495
raise errors.LocalRequiresBoundBranch()
496
result = GitBranchPullResult()
497
result.source_branch = self.source
498
if _override_hook_target is None:
499
result.target_branch = self.target
501
result.target_branch = _override_hook_target
502
self.source.lock_read()
504
# We assume that during 'pull' the target repository is closer than
506
graph = self.target.repository.get_graph(self.source.repository)
507
(result.old_revno, result.old_revid) = \
508
self.target.last_revision_info()
509
result.new_git_head = self._update_revisions(
510
stop_revision, overwrite=overwrite, graph=graph, limit=limit)
511
result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
513
(result.new_revno, result.new_revid) = \
514
self.target.last_revision_info()
516
result.master_branch = _hook_master
517
result.local_branch = result.target_branch
519
result.master_branch = result.target_branch
520
result.local_branch = None
522
for hook in branch.Branch.hooks['post_pull']:
528
def _basic_push(self, overwrite=False, stop_revision=None):
529
result = branch.BranchPushResult()
530
result.source_branch = self.source
531
result.target_branch = self.target
532
graph = self.target.repository.get_graph(self.source.repository)
533
result.old_revno, result.old_revid = self.target.last_revision_info()
534
result.new_git_head = self._update_revisions(
535
stop_revision, overwrite=overwrite, graph=graph)
536
result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
538
result.new_revno, result.new_revid = self.target.last_revision_info()
542
class InterGitBranch(branch.GenericInterBranch):
543
"""InterBranch implementation that pulls between Git branches."""
546
class InterGitLocalRemoteBranch(InterGitBranch):
547
"""InterBranch that copies from a local to a remote git branch."""
550
def is_compatible(self, source, target):
551
from bzrlib.plugins.git.remote import RemoteGitBranch
552
return (isinstance(source, LocalGitBranch) and
553
isinstance(target, RemoteGitBranch))
555
def _basic_push(self, overwrite=False, stop_revision=None):
556
from dulwich.protocol import ZERO_SHA
557
result = GitBranchPushResult()
558
result.source_branch = self.source
559
result.target_branch = self.target
560
if stop_revision is None:
561
stop_revision = self.source.last_revision()
562
# FIXME: Check for diverged branches
563
def get_changed_refs(old_refs):
564
result.old_revid = self.target.lookup_foreign_revision_id(old_refs.get(self.target.ref, ZERO_SHA))
565
refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
566
result.new_revid = stop_revision
567
for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
568
refs[tag_name_to_ref(name)] = sha
570
self.target.repository.send_pack(get_changed_refs,
571
self.source.repository._git.object_store.generate_pack_contents)
575
class InterGitRemoteLocalBranch(InterGitBranch):
576
"""InterBranch that copies from a remote to a local git branch."""
579
def is_compatible(self, source, target):
580
from bzrlib.plugins.git.remote import RemoteGitBranch
581
return (isinstance(source, RemoteGitBranch) and
582
isinstance(target, LocalGitBranch))
584
def _basic_push(self, overwrite=False, stop_revision=None):
585
result = branch.BranchPushResult()
586
result.source_branch = self.source
587
result.target_branch = self.target
588
result.old_revid = self.target.last_revision()
589
refs, stop_revision = self.update_refs(stop_revision)
590
self.target.generate_revision_history(stop_revision, result.old_revid)
591
self.update_tags(refs)
592
result.new_revid = self.target.last_revision()
595
def update_tags(self, refs):
596
for name, v in extract_tags(refs).iteritems():
597
revid = self.target.lookup_foreign_revision_id(v)
598
self.target.tags.set_tag(name, revid)
600
def update_refs(self, stop_revision=None):
601
interrepo = repository.InterRepository.get(self.source.repository,
602
self.target.repository)
603
if stop_revision is None:
604
refs = interrepo.fetch(branches=["HEAD"])
605
stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
607
refs = interrepo.fetch(revision_id=stop_revision)
608
return refs, stop_revision
610
def pull(self, stop_revision=None, overwrite=False,
611
possible_transports=None, run_hooks=True,local=False):
612
# This type of branch can't be bound.
614
raise errors.LocalRequiresBoundBranch()
615
result = GitPullResult()
616
result.source_branch = self.source
617
result.target_branch = self.target
618
result.old_revid = self.target.last_revision()
619
refs, stop_revision = self.update_refs(stop_revision)
620
self.target.generate_revision_history(stop_revision, result.old_revid)
621
self.update_tags(refs)
622
result.new_revid = self.target.last_revision()
626
class InterToGitBranch(branch.GenericInterBranch):
627
"""InterBranch implementation that pulls from Git into bzr."""
629
def __init__(self, source, target):
630
super(InterToGitBranch, self).__init__(source, target)
631
self.interrepo = repository.InterRepository.get(source.repository,
635
def _get_branch_formats_to_test():
639
def is_compatible(self, source, target):
640
return (not isinstance(source, GitBranch) and
641
isinstance(target, GitBranch))
643
def update_revisions(self, *args, **kwargs):
644
raise NoPushSupport()
646
def _get_new_refs(self, stop_revision=None):
647
if stop_revision is None:
648
stop_revision = self.source.last_revision()
649
assert type(stop_revision) is str
650
main_ref = self.target.ref or "refs/heads/master"
651
refs = { main_ref: (None, stop_revision) }
652
for name, revid in self.source.tags.get_tag_dict().iteritems():
653
if self.source.repository.has_revision(revid):
654
refs[tag_name_to_ref(name)] = (None, revid)
655
return refs, main_ref
657
def pull(self, overwrite=False, stop_revision=None, local=False,
658
possible_transports=None):
659
from dulwich.protocol import ZERO_SHA
660
result = GitBranchPullResult()
661
result.source_branch = self.source
662
result.target_branch = self.target
663
new_refs, main_ref = self._get_new_refs(stop_revision)
664
def update_refs(old_refs):
665
refs = dict(old_refs)
666
# FIXME: Check for diverged branches
667
refs.update(new_refs)
669
old_refs, new_refs = self.interrepo.fetch_refs(update_refs)
670
result.old_revid = self.target.lookup_foreign_revision_id(
671
old_refs.get(main_ref, ZERO_SHA))
672
result.new_revid = new_refs[main_ref]
675
def push(self, overwrite=False, stop_revision=None,
676
_override_hook_source_branch=None):
677
from dulwich.protocol import ZERO_SHA
678
result = GitBranchPushResult()
679
result.source_branch = self.source
680
result.target_branch = self.target
681
new_refs, main_ref = self._get_new_refs(stop_revision)
682
def update_refs(old_refs):
683
refs = dict(old_refs)
684
# FIXME: Check for diverged branches
685
refs.update(new_refs)
687
old_refs, new_refs = self.interrepo.fetch_refs(update_refs)
688
result.old_revid = self.target.lookup_foreign_revision_id(
689
old_refs.get(main_ref, ZERO_SHA))
690
result.new_revid = new_refs[main_ref]
693
def lossy_push(self, stop_revision=None):
694
result = GitBranchPushResult()
695
result.source_branch = self.source
696
result.target_branch = self.target
697
new_refs, main_ref = self._get_new_refs(stop_revision)
698
def update_refs(old_refs):
699
refs = dict(old_refs)
700
# FIXME: Check for diverged branches
701
refs.update(new_refs)
703
result.revidmap, old_refs, new_refs = self.interrepo.dfetch_refs(
705
result.old_revid = old_refs.get(self.target.ref, (None, NULL_REVISION))[1]
706
result.new_revid = new_refs[main_ref][1]
710
branch.InterBranch.register_optimiser(InterGitRemoteLocalBranch)
711
branch.InterBranch.register_optimiser(InterFromGitBranch)
712
branch.InterBranch.register_optimiser(InterToGitBranch)
713
branch.InterBranch.register_optimiser(InterGitLocalRemoteBranch)