1
# Copyright (C) 2007 Canonical Ltd
 
 
2
# Copyright (C) 2009 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 (
 
 
34
from bzrlib.decorators import (
 
 
37
from bzrlib.trace import (
 
 
42
from bzrlib.plugins.git.config import (
 
 
45
from bzrlib.plugins.git.errors import (
 
 
50
    from bzrlib.foreign import ForeignBranch
 
 
52
    class ForeignBranch(branch.Branch):
 
 
53
        def __init__(self, mapping):
 
 
54
            self.mapping = mapping
 
 
55
            super(ForeignBranch, self).__init__()
 
 
58
class GitPullResult(branch.PullResult):
 
 
60
    def _lookup_revno(self, revid):
 
 
61
        assert isinstance(revid, str), "was %r" % revid
 
 
62
        # Try in source branch first, it'll be faster
 
 
63
        return self.target_branch.revision_id_to_revno(revid)
 
 
67
        return self._lookup_revno(self.old_revid)
 
 
71
        return self._lookup_revno(self.new_revid)
 
 
74
class LocalGitTagDict(tag.BasicTags):
 
 
75
    """Dictionary with tags in a local repository."""
 
 
77
    def __init__(self, branch):
 
 
79
        self.repository = branch.repository
 
 
81
    def get_tag_dict(self):
 
 
83
        for k,v in self.repository._git.tags.iteritems():
 
 
84
            obj = self.repository._git.get_object(v)
 
 
85
            while isinstance(obj, Tag):
 
 
87
                obj = self.repository._git.get_object(v)
 
 
88
            if not isinstance(obj, Commit):
 
 
89
                mutter("Tag %s points at object %r that is not a commit, "
 
 
92
            ret[k] = self.branch.mapping.revision_id_foreign_to_bzr(v)
 
 
95
    def set_tag(self, name, revid):
 
 
96
        self.repository._git.tags[name] = revid
 
 
99
class GitBranchFormat(branch.BranchFormat):
 
 
101
    def get_format_description(self):
 
 
104
    def supports_tags(self):
 
 
107
    def make_tags(self, branch):
 
 
108
        if getattr(branch.repository, "get_refs", None) is not None:
 
 
109
            from bzrlib.plugins.git.remote import RemoteGitTagDict
 
 
110
            return RemoteGitTagDict(branch)
 
 
112
            return LocalGitTagDict(branch)
 
 
115
class GitBranch(ForeignBranch):
 
 
116
    """An adapter to git repositories for bzr Branch objects."""
 
 
118
    def __init__(self, bzrdir, repository, name, head, lockfiles):
 
 
119
        self.repository = repository
 
 
120
        self._format = GitBranchFormat()
 
 
121
        self.control_files = lockfiles
 
 
123
        super(GitBranch, self).__init__(repository.get_mapping())
 
 
126
        self.base = bzrdir.transport.base
 
 
128
    def _get_nick(self, local=False, possible_master_transports=None):
 
 
129
        """Find the nick name for this branch.
 
 
135
    def _set_nick(self, nick):
 
 
136
        raise NotImplementedError
 
 
138
    nick = property(_get_nick, _set_nick)
 
 
141
        return "%s(%r, %r)" % (self.__class__.__name__, self.repository.base, self.name)
 
 
143
    def dpull(self, source, stop_revision=None):
 
 
144
        if stop_revision is None:
 
 
145
            stop_revision = source.last_revision()
 
 
146
        # FIXME: Check for diverged branches
 
 
147
        revidmap = self.repository.dfetch(source.repository, stop_revision)
 
 
149
            self.generate_revision_history(revidmap[stop_revision])
 
 
152
    def generate_revision_history(self, revid, old_revid=None):
 
 
153
        # FIXME: Check that old_revid is in the ancestry of revid
 
 
154
        newhead, self.mapping = self.mapping.revision_id_bzr_to_foreign(revid)
 
 
155
        self._set_head(newhead)
 
 
157
    def _set_head(self, head):
 
 
159
        self.repository._git.set_ref(self.name, self.head)
 
 
161
    def lock_write(self):
 
 
162
        self.control_files.lock_write()
 
 
164
    def get_stacked_on_url(self):
 
 
165
        # Git doesn't do stacking (yet...)
 
 
168
    def get_parent(self):
 
 
169
        """See Branch.get_parent()."""
 
 
170
        # FIXME: Set "origin" url from .git/config ?
 
 
173
    def set_parent(self, url):
 
 
174
        # FIXME: Set "origin" url in .git/config ?
 
 
178
        self.control_files.lock_read()
 
 
181
        self.control_files.unlock()
 
 
183
    def get_physical_lock_status(self):
 
 
187
class LocalGitBranch(GitBranch):
 
 
188
    """A local Git branch."""
 
 
191
    def last_revision(self):
 
 
192
        # perhaps should escape this ?
 
 
193
        if self.head is None:
 
 
194
            return revision.NULL_REVISION
 
 
195
        return self.mapping.revision_id_foreign_to_bzr(self.head)
 
 
197
    def _get_checkout_format(self):
 
 
198
        """Return the most suitable metadir for a checkout of this branch.
 
 
199
        Weaves are used if this branch's repository uses weaves.
 
 
201
        format = self.repository.bzrdir.checkout_metadir()
 
 
202
        format.set_branch_format(self._format)
 
 
205
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
 
 
206
        accelerator_tree=None, hardlink=False):
 
 
208
            t = transport.get_transport(to_location)
 
 
210
            format = self._get_checkout_format()
 
 
211
            checkout = format.initialize_on_transport(t)
 
 
212
            from_branch = branch.BranchReferenceFormat().initialize(checkout, 
 
 
214
            tree = checkout.create_workingtree(revision_id,
 
 
215
                from_branch=from_branch, hardlink=hardlink)
 
 
218
            return self._create_heavyweight_checkout(to_location, revision_id,
 
 
221
    def _create_heavyweight_checkout(self, to_location, revision_id=None, 
 
 
223
        """Create a new heavyweight checkout of this branch.
 
 
225
        :param to_location: URL of location to create the new checkout in.
 
 
226
        :param revision_id: Revision that should be the tip of the checkout.
 
 
227
        :param hardlink: Whether to hardlink
 
 
228
        :return: WorkingTree object of checkout.
 
 
230
        checkout_branch = BzrDir.create_branch_convenience(
 
 
231
            to_location, force_new_tree=False, format=get_rich_root_format())
 
 
232
        checkout = checkout_branch.bzrdir
 
 
233
        checkout_branch.bind(self)
 
 
234
        # pull up to the specified revision_id to set the initial 
 
 
235
        # branch tip correctly, and seed it with history.
 
 
236
        checkout_branch.pull(self, stop_revision=revision_id)
 
 
237
        return checkout.create_workingtree(revision_id, hardlink=hardlink)
 
 
239
    def _gen_revision_history(self):
 
 
240
        if self.head is None:
 
 
242
        ret = list(self.repository.iter_reverse_revision_history(
 
 
243
            self.last_revision()))
 
 
247
    def get_config(self):
 
 
248
        return GitBranchConfig(self)
 
 
250
    def get_push_location(self):
 
 
251
        """See Branch.get_push_location."""
 
 
252
        push_loc = self.get_config().get_user_option('push_location')
 
 
255
    def set_push_location(self, location):
 
 
256
        """See Branch.set_push_location."""
 
 
257
        self.get_config().set_user_option('push_location', location,
 
 
258
                                          store=config.STORE_LOCATION)
 
 
260
    def supports_tags(self):
 
 
264
class GitBranchPullResult(branch.PullResult):
 
 
266
    def report(self, to_file):
 
 
268
            if self.old_revid == self.new_revid:
 
 
269
                to_file.write('No revisions to pull.\n')
 
 
271
                to_file.write('Now on revision %d (git sha: %s).\n' % 
 
 
272
                        (self.new_revno, self.new_git_head))
 
 
273
        self._show_tag_conficts(to_file)
 
 
276
class InterGitGenericBranch(branch.InterBranch):
 
 
277
    """InterBranch implementation that pulls from Git into bzr."""
 
 
280
    def is_compatible(self, source, target):
 
 
281
        return (isinstance(source, GitBranch) and 
 
 
282
                not isinstance(target, GitBranch))
 
 
284
    def update_revisions(self, stop_revision=None, overwrite=False,
 
 
286
        """See InterBranch.update_revisions()."""
 
 
287
        interrepo = repository.InterRepository.get(self.source.repository, 
 
 
288
            self.target.repository)
 
 
290
        self._last_revid = None
 
 
291
        def determine_wants(heads):
 
 
292
            if not self.source.name in heads:
 
 
293
                raise NoSuchRef(self.source.name, heads.keys())
 
 
294
            if stop_revision is not None:
 
 
295
                self._last_revid = stop_revision
 
 
296
                self._head, mapping = self.source.repository.lookup_git_revid(
 
 
299
                self._head = heads[self.source.name]
 
 
301
                    self.source.mapping.revision_id_foreign_to_bzr(self._head)
 
 
302
            if self.target.repository.has_revision(self._last_revid):
 
 
305
        interrepo.fetch_objects(determine_wants, self.source.mapping)
 
 
307
            prev_last_revid = None
 
 
309
            prev_last_revid = self.target.last_revision()
 
 
310
        self.target.generate_revision_history(self._last_revid, prev_last_revid)
 
 
312
    def pull(self, overwrite=False, stop_revision=None,
 
 
313
             possible_transports=None, _hook_master=None, run_hooks=True,
 
 
314
             _override_hook_target=None):
 
 
317
        :param _hook_master: Private parameter - set the branch to
 
 
318
            be supplied as the master to pull hooks.
 
 
319
        :param run_hooks: Private parameter - if false, this branch
 
 
320
            is being called because it's the master of the primary branch,
 
 
321
            so it should not run its hooks.
 
 
322
        :param _override_hook_target: Private parameter - set the branch to be
 
 
323
            supplied as the target_branch to pull hooks.
 
 
325
        result = GitBranchPullResult()
 
 
326
        result.source_branch = self.source
 
 
327
        if _override_hook_target is None:
 
 
328
            result.target_branch = self.target
 
 
330
            result.target_branch = _override_hook_target
 
 
331
        self.source.lock_read()
 
 
333
            # We assume that during 'pull' the target repository is closer than
 
 
335
            graph = self.target.repository.get_graph(self.source.repository)
 
 
336
            result.old_revno, result.old_revid = \
 
 
337
                self.target.last_revision_info()
 
 
338
            self.update_revisions(stop_revision, overwrite=overwrite, 
 
 
340
            result.new_git_head = self._head
 
 
341
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
 
343
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
 
345
                result.master_branch = _hook_master
 
 
346
                result.local_branch = result.target_branch
 
 
348
                result.master_branch = result.target_branch
 
 
349
                result.local_branch = None
 
 
351
                for hook in branch.Branch.hooks['post_pull']:
 
 
360
branch.InterBranch.register_optimiser(InterGitGenericBranch)
 
 
363
class InterGitRemoteLocalBranch(branch.InterBranch):
 
 
364
    """InterBranch implementation that pulls between Git branches."""
 
 
367
    def is_compatible(self, source, target):
 
 
368
        from bzrlib.plugins.git.remote import RemoteGitBranch
 
 
369
        return (isinstance(source, RemoteGitBranch) and 
 
 
370
                isinstance(target, LocalGitBranch))
 
 
372
    def pull(self, stop_revision=None, overwrite=False, 
 
 
373
        possible_transports=None):
 
 
374
        result = GitPullResult()
 
 
375
        result.source_branch = self.source
 
 
376
        result.target_branch = self.target
 
 
377
        interrepo = repository.InterRepository.get(self.source.repository, 
 
 
378
            self.target.repository)
 
 
379
        result.old_revid = self.target.last_revision()
 
 
380
        if stop_revision is None:
 
 
381
            stop_revision = self.source.last_revision()
 
 
382
        interrepo.fetch(revision_id=stop_revision)
 
 
383
        self.target.generate_revision_history(stop_revision, result.old_revid)
 
 
384
        result.new_revid = self.target.last_revision()
 
 
388
branch.InterBranch.register_optimiser(InterGitRemoteLocalBranch)