/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to branch.py

Update notes for git-serve.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007 Canonical Ltd
 
2
# Copyright (C) 2009 Jelmer Vernooij <jelmer@samba.org>
 
3
#
 
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.
 
8
#
 
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.
 
13
#
 
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
 
17
 
 
18
"""An adapter between a Git Branch and a Bazaar Branch"""
 
19
 
 
20
from dulwich.objects import (
 
21
    Commit,
 
22
    Tag,
 
23
    )
 
24
 
 
25
from bzrlib import (
 
26
    branch,
 
27
    bzrdir,
 
28
    config,
 
29
    errors,
 
30
    repository,
 
31
    revision,
 
32
    tag,
 
33
    transport,
 
34
    )
 
35
from bzrlib.decorators import (
 
36
    needs_read_lock,
 
37
    )
 
38
from bzrlib.trace import (
 
39
    is_quiet,
 
40
    mutter,
 
41
    )
 
42
 
 
43
from bzrlib.plugins.git import (
 
44
    get_rich_root_format,
 
45
    )
 
46
from bzrlib.plugins.git.config import (
 
47
    GitBranchConfig,
 
48
    )
 
49
from bzrlib.plugins.git.errors import (
 
50
    NoPushSupport,
 
51
    NoSuchRef,
 
52
    )
 
53
 
 
54
from bzrlib.foreign import ForeignBranch
 
55
 
 
56
 
 
57
def extract_tags(refs):
 
58
    """Extract the tags from a refs dictionary.
 
59
 
 
60
    :param refs: Refs to extract the tags from.
 
61
    :return: Dictionary mapping tag names to SHA1s.
 
62
    """
 
63
    ret = {}
 
64
    for k,v in refs.iteritems():
 
65
        if k.startswith("refs/tags/") and not k.endswith("^{}"):
 
66
            v = refs.get(k+"^{}", v)
 
67
            ret[k[len("refs/tags/"):]] = v
 
68
    return ret
 
69
 
 
70
 
 
71
def branch_name_to_ref(name, default=None):
 
72
    """Map a branch name to a ref.
 
73
 
 
74
    :param name: Branch name
 
75
    :return: ref string
 
76
    """
 
77
    if name is None:
 
78
        return default
 
79
    if name == "HEAD":
 
80
        return "HEAD"
 
81
    if not name.startswith("refs/"):
 
82
        return "refs/heads/%s" % name
 
83
    else:
 
84
        return name
 
85
 
 
86
 
 
87
def ref_to_branch_name(ref):
 
88
    """Map a ref to a branch name
 
89
 
 
90
    :param ref: Ref
 
91
    :return: A branch name
 
92
    """
 
93
    if ref == "HEAD":
 
94
        return "HEAD"
 
95
    if ref.startswith("refs/heads/"):
 
96
        return ref[len("refs/heads/"):]
 
97
    raise ValueError("unable to map ref %s back to branch name")
 
98
 
 
99
 
 
100
class GitPullResult(branch.PullResult):
 
101
 
 
102
    def _lookup_revno(self, revid):
 
103
        assert isinstance(revid, str), "was %r" % revid
 
104
        # Try in source branch first, it'll be faster
 
105
        return self.target_branch.revision_id_to_revno(revid)
 
106
 
 
107
    @property
 
108
    def old_revno(self):
 
109
        return self._lookup_revno(self.old_revid)
 
110
 
 
111
    @property
 
112
    def new_revno(self):
 
113
        return self._lookup_revno(self.new_revid)
 
114
 
 
115
 
 
116
class LocalGitTagDict(tag.BasicTags):
 
117
    """Dictionary with tags in a local repository."""
 
118
 
 
119
    def __init__(self, branch):
 
120
        self.branch = branch
 
121
        self.repository = branch.repository
 
122
 
 
123
    def get_tag_dict(self):
 
124
        ret = {}
 
125
        for k,v in extract_tags(self.repository._git.get_refs()).iteritems():
 
126
            try:
 
127
                obj = self.repository._git[v]
 
128
            except KeyError:
 
129
                mutter("Tag %s points at unknown object %s, ignoring", v, obj)
 
130
                continue
 
131
            while isinstance(obj, Tag):
 
132
                v = obj.object[1]
 
133
                obj = self.repository._git[v]
 
134
            if not isinstance(obj, Commit):
 
135
                mutter("Tag %s points at object %r that is not a commit, "
 
136
                       "ignoring", k, obj)
 
137
                continue
 
138
            ret[k] = self.branch.mapping.revision_id_foreign_to_bzr(v)
 
139
        return ret
 
140
 
 
141
    def _set_tag_dict(self, to_dict):
 
142
        extra = set(self.repository._git.get_refs().keys())
 
143
        for k, revid in to_dict.iteritems():
 
144
            name = "refs/tags/%s" % k
 
145
            if name in extra:
 
146
                extra.remove(name)
 
147
            self.set_tag(k, revid)
 
148
        for name in extra:
 
149
            if name.startswith("refs/tags/"):
 
150
                del self.repository._git[name]
 
151
        
 
152
    def set_tag(self, name, revid):
 
153
        self.repository._git.refs["refs/tags/%s" % name], _ = \
 
154
            self.branch.mapping.revision_id_bzr_to_foreign(revid)
 
155
 
 
156
 
 
157
class DictTagDict(LocalGitTagDict):
 
158
 
 
159
    def __init__(self, branch, tags):
 
160
        super(DictTagDict, self).__init__(branch)
 
161
        self._tags = tags
 
162
 
 
163
    def get_tag_dict(self):
 
164
        return self._tags
 
165
 
 
166
 
 
167
class GitBranchFormat(branch.BranchFormat):
 
168
 
 
169
    def get_format_description(self):
 
170
        return 'Git Branch'
 
171
 
 
172
    def network_name(self):
 
173
        return "git"
 
174
 
 
175
    def supports_tags(self):
 
176
        return True
 
177
 
 
178
    def get_foreign_tests_branch_factory(self):
 
179
        from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
 
180
        return ForeignTestsBranchFactory()
 
181
 
 
182
    def make_tags(self, branch):
 
183
        if getattr(branch.repository, "get_refs", None) is not None:
 
184
            from bzrlib.plugins.git.remote import RemoteGitTagDict
 
185
            return RemoteGitTagDict(branch)
 
186
        else:
 
187
            return LocalGitTagDict(branch)
 
188
 
 
189
 
 
190
class GitBranch(ForeignBranch):
 
191
    """An adapter to git repositories for bzr Branch objects."""
 
192
 
 
193
    def __init__(self, bzrdir, repository, ref, lockfiles, tagsdict=None):
 
194
        self.repository = repository
 
195
        self._format = GitBranchFormat()
 
196
        self.control_files = lockfiles
 
197
        self.bzrdir = bzrdir
 
198
        super(GitBranch, self).__init__(repository.get_mapping())
 
199
        if tagsdict is not None:
 
200
            self.tags = DictTagDict(self, tagsdict)
 
201
        self.ref = ref
 
202
        self.name = ref_to_branch_name(ref)
 
203
        self._head = None
 
204
        self.base = bzrdir.root_transport.base
 
205
 
 
206
    def _get_checkout_format(self):
 
207
        """Return the most suitable metadir for a checkout of this branch.
 
208
        Weaves are used if this branch's repository uses weaves.
 
209
        """
 
210
        return get_rich_root_format()
 
211
 
 
212
    def get_child_submit_format(self):
 
213
        """Return the preferred format of submissions to this branch."""
 
214
        ret = self.get_config().get_user_option("child_submit_format")
 
215
        if ret is not None:
 
216
            return ret
 
217
        return "git"
 
218
 
 
219
    def _get_nick(self, local=False, possible_master_transports=None):
 
220
        """Find the nick name for this branch.
 
221
 
 
222
        :return: Branch nick
 
223
        """
 
224
        return self.name
 
225
 
 
226
    def _set_nick(self, nick):
 
227
        raise NotImplementedError
 
228
 
 
229
    nick = property(_get_nick, _set_nick)
 
230
 
 
231
    def __repr__(self):
 
232
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
 
233
            self.ref)
 
234
 
 
235
    def generate_revision_history(self, revid, old_revid=None):
 
236
        # FIXME: Check that old_revid is in the ancestry of revid
 
237
        newhead, self.mapping = self.mapping.revision_id_bzr_to_foreign(revid)
 
238
        self._set_head(newhead)
 
239
 
 
240
    def lock_write(self):
 
241
        self.control_files.lock_write()
 
242
 
 
243
    def get_stacked_on_url(self):
 
244
        # Git doesn't do stacking (yet...)
 
245
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
246
 
 
247
    def get_parent(self):
 
248
        """See Branch.get_parent()."""
 
249
        # FIXME: Set "origin" url from .git/config ?
 
250
        return None
 
251
 
 
252
    def set_parent(self, url):
 
253
        # FIXME: Set "origin" url in .git/config ?
 
254
        pass
 
255
 
 
256
    def lock_read(self):
 
257
        self.control_files.lock_read()
 
258
 
 
259
    def is_locked(self):
 
260
        return self.control_files.is_locked()
 
261
 
 
262
    def unlock(self):
 
263
        self.control_files.unlock()
 
264
 
 
265
    def get_physical_lock_status(self):
 
266
        return False
 
267
 
 
268
    @needs_read_lock
 
269
    def last_revision(self):
 
270
        # perhaps should escape this ?
 
271
        if self.head is None:
 
272
            return revision.NULL_REVISION
 
273
        return self.mapping.revision_id_foreign_to_bzr(self.head)
 
274
 
 
275
    def _basic_push(self, target, overwrite=False, stop_revision=None):
 
276
        return branch.InterBranch.get(self, target)._basic_push(
 
277
            overwrite, stop_revision)
 
278
 
 
279
 
 
280
class LocalGitBranch(GitBranch):
 
281
    """A local Git branch."""
 
282
 
 
283
    def __init__(self, bzrdir, repository, name, lockfiles, tagsdict=None):
 
284
        super(LocalGitBranch, self).__init__(bzrdir, repository, name, 
 
285
              lockfiles, tagsdict)
 
286
        if not name in repository._git.get_refs().keys():
 
287
            raise errors.NotBranchError(self.base)
 
288
 
 
289
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
 
290
        accelerator_tree=None, hardlink=False):
 
291
        if lightweight:
 
292
            t = transport.get_transport(to_location)
 
293
            t.ensure_base()
 
294
            format = self._get_checkout_format()
 
295
            checkout = format.initialize_on_transport(t)
 
296
            from_branch = branch.BranchReferenceFormat().initialize(checkout,
 
297
                self)
 
298
            tree = checkout.create_workingtree(revision_id,
 
299
                from_branch=from_branch, hardlink=hardlink)
 
300
            return tree
 
301
        else:
 
302
            return self._create_heavyweight_checkout(to_location, revision_id,
 
303
            hardlink)
 
304
 
 
305
    def _create_heavyweight_checkout(self, to_location, revision_id=None,
 
306
                                     hardlink=False):
 
307
        """Create a new heavyweight checkout of this branch.
 
308
 
 
309
        :param to_location: URL of location to create the new checkout in.
 
310
        :param revision_id: Revision that should be the tip of the checkout.
 
311
        :param hardlink: Whether to hardlink
 
312
        :return: WorkingTree object of checkout.
 
313
        """
 
314
        checkout_branch = bzrdir.BzrDir.create_branch_convenience(
 
315
            to_location, force_new_tree=False, format=get_rich_root_format())
 
316
        checkout = checkout_branch.bzrdir
 
317
        checkout_branch.bind(self)
 
318
        # pull up to the specified revision_id to set the initial
 
319
        # branch tip correctly, and seed it with history.
 
320
        checkout_branch.pull(self, stop_revision=revision_id)
 
321
        return checkout.create_workingtree(revision_id, hardlink=hardlink)
 
322
 
 
323
    def _gen_revision_history(self):
 
324
        if self.head is None:
 
325
            return []
 
326
        ret = list(self.repository.iter_reverse_revision_history(
 
327
            self.last_revision()))
 
328
        ret.reverse()
 
329
        return ret
 
330
 
 
331
    def _get_head(self):
 
332
        try:
 
333
            return self.repository._git.ref(self.ref)
 
334
        except KeyError:
 
335
            return None
 
336
 
 
337
    def set_last_revision_info(self, revno, revid):
 
338
        self.set_last_revision(revid)
 
339
 
 
340
    def set_last_revision(self, revid):
 
341
        (newhead, self.mapping) = self.mapping.revision_id_bzr_to_foreign(
 
342
                revid)
 
343
        self.head = newhead
 
344
 
 
345
    def _set_head(self, value):
 
346
        self._head = value
 
347
        self.repository._git.refs[self.ref] = self._head
 
348
        self._clear_cached_state()
 
349
 
 
350
    head = property(_get_head, _set_head)
 
351
 
 
352
    def get_config(self):
 
353
        return GitBranchConfig(self)
 
354
 
 
355
    def get_push_location(self):
 
356
        """See Branch.get_push_location."""
 
357
        push_loc = self.get_config().get_user_option('push_location')
 
358
        return push_loc
 
359
 
 
360
    def set_push_location(self, location):
 
361
        """See Branch.set_push_location."""
 
362
        self.get_config().set_user_option('push_location', location,
 
363
                                          store=config.STORE_LOCATION)
 
364
 
 
365
    def supports_tags(self):
 
366
        return True
 
367
 
 
368
 
 
369
class GitBranchPullResult(branch.PullResult):
 
370
 
 
371
    def report(self, to_file):
 
372
        if not is_quiet():
 
373
            if self.old_revid == self.new_revid:
 
374
                to_file.write('No revisions to pull.\n')
 
375
            elif self.new_git_head is not None:
 
376
                to_file.write('Now on revision %d (git sha: %s).\n' %
 
377
                        (self.new_revno, self.new_git_head))
 
378
            else:
 
379
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
 
380
        self._show_tag_conficts(to_file)
 
381
 
 
382
 
 
383
class GitBranchPushResult(branch.BranchPushResult):
 
384
 
 
385
    def _lookup_revno(self, revid):
 
386
        assert isinstance(revid, str), "was %r" % revid
 
387
        # Try in source branch first, it'll be faster
 
388
        try:
 
389
            return self.source_branch.revision_id_to_revno(revid)
 
390
        except errors.NoSuchRevision:
 
391
            # FIXME: Check using graph.find_distance_to_null() ?
 
392
            return self.target_branch.revision_id_to_revno(revid)
 
393
 
 
394
    @property
 
395
    def old_revno(self):
 
396
        return self._lookup_revno(self.old_revid)
 
397
 
 
398
    @property
 
399
    def new_revno(self):
 
400
        return self._lookup_revno(self.new_revid)
 
401
 
 
402
 
 
403
class InterFromGitBranch(branch.GenericInterBranch):
 
404
    """InterBranch implementation that pulls from Git into bzr."""
 
405
 
 
406
    @classmethod
 
407
    def _get_interrepo(self, source, target):
 
408
        return repository.InterRepository.get(source.repository,
 
409
            target.repository)
 
410
 
 
411
    @classmethod
 
412
    def is_compatible(cls, source, target):
 
413
        return (isinstance(source, GitBranch) and
 
414
                not isinstance(target, GitBranch) and
 
415
                (getattr(cls._get_interrepo(source, target), "fetch_objects", None) is not None))
 
416
 
 
417
    def _update_revisions(self, stop_revision=None, overwrite=False,
 
418
        graph=None, limit=None):
 
419
        """Like InterBranch.update_revisions(), but with additions.
 
420
 
 
421
        Compared to the `update_revisions()` below, this function takes a
 
422
        `limit` argument that limits how many git commits will be converted
 
423
        and returns the new git head.
 
424
        """
 
425
        interrepo = self._get_interrepo(self.source, self.target)
 
426
        def determine_wants(heads):
 
427
            if not self.source.ref in heads:
 
428
                raise NoSuchRef(self.source.ref, heads.keys())
 
429
            if stop_revision is not None:
 
430
                self._last_revid = stop_revision
 
431
                head, mapping = self.source.repository.lookup_bzr_revision_id(
 
432
                    stop_revision)
 
433
            else:
 
434
                head = heads[self.source.ref]
 
435
                self._last_revid = self.source.mapping.revision_id_foreign_to_bzr(
 
436
                    head)
 
437
            if self.target.repository.has_revision(self._last_revid):
 
438
                return []
 
439
            return [head]
 
440
        pack_hint, head = interrepo.fetch_objects(
 
441
            determine_wants, self.source.mapping, limit=limit)
 
442
        if pack_hint is not None and self.target.repository._format.pack_compresses:
 
443
            self.target.repository.pack(hint=pack_hint)
 
444
        if head is not None:
 
445
            self._last_revid = self.source.mapping.revision_id_foreign_to_bzr(head)
 
446
        if overwrite:
 
447
            prev_last_revid = None
 
448
        else:
 
449
            prev_last_revid = self.target.last_revision()
 
450
        self.target.generate_revision_history(self._last_revid,
 
451
            prev_last_revid)
 
452
        return head
 
453
 
 
454
    def update_revisions(self, stop_revision=None, overwrite=False,
 
455
                         graph=None):
 
456
        """See InterBranch.update_revisions()."""
 
457
        self._update_revisions(stop_revision, overwrite, graph)
 
458
 
 
459
    def pull(self, overwrite=False, stop_revision=None,
 
460
             possible_transports=None, _hook_master=None, run_hooks=True,
 
461
             _override_hook_target=None, local=False, limit=None):
 
462
        """See Branch.pull.
 
463
 
 
464
        :param _hook_master: Private parameter - set the branch to
 
465
            be supplied as the master to pull hooks.
 
466
        :param run_hooks: Private parameter - if false, this branch
 
467
            is being called because it's the master of the primary branch,
 
468
            so it should not run its hooks.
 
469
        :param _override_hook_target: Private parameter - set the branch to be
 
470
            supplied as the target_branch to pull hooks.
 
471
        :param limit: Only import this many revisons.  `None`, the default,
 
472
            means import all revisions.
 
473
        """
 
474
        # This type of branch can't be bound.
 
475
        if local:
 
476
            raise errors.LocalRequiresBoundBranch()
 
477
        result = GitBranchPullResult()
 
478
        result.source_branch = self.source
 
479
        if _override_hook_target is None:
 
480
            result.target_branch = self.target
 
481
        else:
 
482
            result.target_branch = _override_hook_target
 
483
        self.source.lock_read()
 
484
        try:
 
485
            # We assume that during 'pull' the target repository is closer than
 
486
            # the source one.
 
487
            graph = self.target.repository.get_graph(self.source.repository)
 
488
            (result.old_revno, result.old_revid) = \
 
489
                self.target.last_revision_info()
 
490
            result.new_git_head = self._update_revisions(
 
491
                stop_revision, overwrite=overwrite, graph=graph, limit=limit)
 
492
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
493
                overwrite)
 
494
            (result.new_revno, result.new_revid) = \
 
495
                self.target.last_revision_info()
 
496
            if _hook_master:
 
497
                result.master_branch = _hook_master
 
498
                result.local_branch = result.target_branch
 
499
            else:
 
500
                result.master_branch = result.target_branch
 
501
                result.local_branch = None
 
502
            if run_hooks:
 
503
                for hook in branch.Branch.hooks['post_pull']:
 
504
                    hook(result)
 
505
        finally:
 
506
            self.source.unlock()
 
507
        return result
 
508
 
 
509
    def _basic_push(self, overwrite=False, stop_revision=None):
 
510
        result = branch.BranchPushResult()
 
511
        result.source_branch = self.source
 
512
        result.target_branch = self.target
 
513
        graph = self.target.repository.get_graph(self.source.repository)
 
514
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
515
        result.new_git_head = self._update_revisions(
 
516
            stop_revision, overwrite=overwrite, graph=graph)
 
517
        result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
518
            overwrite)
 
519
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
520
        return result
 
521
 
 
522
 
 
523
class InterGitBranch(branch.GenericInterBranch):
 
524
    """InterBranch implementation that pulls between Git branches."""
 
525
 
 
526
 
 
527
class InterGitLocalRemoteBranch(InterGitBranch):
 
528
    """InterBranch that copies from a local to a remote git branch."""
 
529
 
 
530
    @classmethod
 
531
    def is_compatible(self, source, target):
 
532
        from bzrlib.plugins.git.remote import RemoteGitBranch
 
533
        return (isinstance(source, LocalGitBranch) and
 
534
                isinstance(target, RemoteGitBranch))
 
535
 
 
536
    def _basic_push(self, overwrite=False, stop_revision=None):
 
537
        result = GitBranchPushResult()
 
538
        result.source_branch = self.source
 
539
        result.target_branch = self.target
 
540
        if stop_revision is None:
 
541
            stop_revision = self.source.last_revision()
 
542
        # FIXME: Check for diverged branches
 
543
        def get_changed_refs(old_refs):
 
544
            result.old_revid = self.target.mapping.revision_id_foreign_to_bzr(old_refs.get(self.target.ref, "0" * 40))
 
545
            refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
 
546
            result.new_revid = stop_revision
 
547
            for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
 
548
                refs["refs/tags/%s" % name] = sha
 
549
            return refs
 
550
        self.target.repository.send_pack(get_changed_refs,
 
551
            self.source.repository._git.object_store.generate_pack_contents)
 
552
        return result
 
553
 
 
554
 
 
555
class InterGitRemoteLocalBranch(InterGitBranch):
 
556
    """InterBranch that copies from a remote to a local git branch."""
 
557
 
 
558
    @classmethod
 
559
    def is_compatible(self, source, target):
 
560
        from bzrlib.plugins.git.remote import RemoteGitBranch
 
561
        return (isinstance(source, RemoteGitBranch) and
 
562
                isinstance(target, LocalGitBranch))
 
563
 
 
564
    def _basic_push(self, overwrite=False, stop_revision=None):
 
565
        result = branch.BranchPushResult()
 
566
        result.source_branch = self.source
 
567
        result.target_branch = self.target
 
568
        result.old_revid = self.target.last_revision()
 
569
        refs, stop_revision = self.update_refs(stop_revision)
 
570
        self.target.generate_revision_history(stop_revision, result.old_revid)
 
571
        self.update_tags(refs)
 
572
        result.new_revid = self.target.last_revision()
 
573
        return result
 
574
 
 
575
    def update_tags(self, refs):
 
576
        for name, v in extract_tags(refs).iteritems():
 
577
            revid = self.target.mapping.revision_id_foreign_to_bzr(v)
 
578
            self.target.tags.set_tag(name, revid)
 
579
 
 
580
    def update_refs(self, stop_revision=None):
 
581
        interrepo = repository.InterRepository.get(self.source.repository,
 
582
            self.target.repository)
 
583
        if stop_revision is None:
 
584
            refs = interrepo.fetch_refs(branches=["HEAD"])
 
585
            stop_revision = self.target.mapping.revision_id_foreign_to_bzr(refs["HEAD"])
 
586
        else:
 
587
            refs = interrepo.fetch_refs(revision_id=stop_revision)
 
588
        return refs, stop_revision
 
589
 
 
590
    def pull(self, stop_revision=None, overwrite=False,
 
591
        possible_transports=None, run_hooks=True,local=False):
 
592
        # This type of branch can't be bound.
 
593
        if local:
 
594
            raise errors.LocalRequiresBoundBranch()
 
595
        result = GitPullResult()
 
596
        result.source_branch = self.source
 
597
        result.target_branch = self.target
 
598
        result.old_revid = self.target.last_revision()
 
599
        refs, stop_revision = self.update_refs(stop_revision)
 
600
        self.target.generate_revision_history(stop_revision, result.old_revid)
 
601
        self.update_tags(refs)
 
602
        result.new_revid = self.target.last_revision()
 
603
        return result
 
604
 
 
605
 
 
606
class InterToGitBranch(branch.InterBranch):
 
607
    """InterBranch implementation that pulls from Git into bzr."""
 
608
 
 
609
    @staticmethod
 
610
    def _get_branch_formats_to_test():
 
611
        return None, None
 
612
 
 
613
    @classmethod
 
614
    def is_compatible(self, source, target):
 
615
        return (not isinstance(source, GitBranch) and
 
616
                isinstance(target, GitBranch))
 
617
 
 
618
    def update_revisions(self, *args, **kwargs):
 
619
        raise NoPushSupport()
 
620
 
 
621
    def push(self, overwrite=True, stop_revision=None,
 
622
             _override_hook_source_branch=None):
 
623
        raise NoPushSupport()
 
624
 
 
625
    def lossy_push(self, stop_revision=None):
 
626
        result = GitBranchPushResult()
 
627
        result.source_branch = self.source
 
628
        result.target_branch = self.target
 
629
        if stop_revision is None:
 
630
            stop_revision = self.source.last_revision()
 
631
        # FIXME: Check for diverged branches
 
632
        refs = { self.target.ref: stop_revision }
 
633
        for name, revid in self.source.tags.get_tag_dict().iteritems():
 
634
            if self.source.repository.has_revision(revid):
 
635
                refs["refs/tags/%s" % name] = revid
 
636
        revidmap, old_refs, new_refs = self.target.repository.dfetch_refs(
 
637
            self.source.repository, refs)
 
638
        result.old_revid = self.target.mapping.revision_id_foreign_to_bzr(
 
639
            old_refs.get(self.target.ref, "0" * 40))
 
640
        result.new_revid = self.target.mapping.revision_id_foreign_to_bzr(
 
641
            new_refs[self.target.ref])
 
642
        result.revidmap = revidmap
 
643
        return result
 
644
 
 
645
 
 
646
branch.InterBranch.register_optimiser(InterGitRemoteLocalBranch)
 
647
branch.InterBranch.register_optimiser(InterFromGitBranch)
 
648
branch.InterBranch.register_optimiser(InterToGitBranch)
 
649
branch.InterBranch.register_optimiser(InterGitLocalRemoteBranch)