/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

Avoid using deprecated Inventory.__contains.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2007 Canonical Ltd
 
2
# Copyright (C) 2009-2010 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 collections import defaultdict
 
21
 
 
22
from dulwich.objects import (
 
23
    Commit,
 
24
    Tag,
 
25
    ZERO_SHA,
 
26
    )
 
27
 
 
28
from bzrlib import (
 
29
    branch,
 
30
    bzrdir,
 
31
    config,
 
32
    errors,
 
33
    repository as _mod_repository,
 
34
    revision,
 
35
    tag,
 
36
    transport,
 
37
    )
 
38
from bzrlib.decorators import (
 
39
    needs_read_lock,
 
40
    )
 
41
from bzrlib.revision import (
 
42
    NULL_REVISION,
 
43
    )
 
44
from bzrlib.trace import (
 
45
    is_quiet,
 
46
    mutter,
 
47
    )
 
48
 
 
49
from bzrlib.plugins.git.config import (
 
50
    GitBranchConfig,
 
51
    )
 
52
from bzrlib.plugins.git.errors import (
 
53
    NoPushSupport,
 
54
    NoSuchRef,
 
55
    )
 
56
from bzrlib.plugins.git.refs import (
 
57
    branch_name_to_ref,
 
58
    extract_tags,
 
59
    is_tag,
 
60
    ref_to_branch_name,
 
61
    ref_to_tag_name,
 
62
    tag_name_to_ref,
 
63
    )
 
64
from bzrlib.plugins.git.unpeel_map import (
 
65
    UnpeelMap,
 
66
    )
 
67
 
 
68
from bzrlib.foreign import ForeignBranch
 
69
 
 
70
 
 
71
class GitPullResult(branch.PullResult):
 
72
    """Result of a pull from a Git branch."""
 
73
 
 
74
    def _lookup_revno(self, revid):
 
75
        assert isinstance(revid, str), "was %r" % revid
 
76
        # Try in source branch first, it'll be faster
 
77
        self.target_branch.lock_read()
 
78
        try:
 
79
            return self.target_branch.revision_id_to_revno(revid)
 
80
        finally:
 
81
            self.target_branch.unlock()
 
82
 
 
83
    @property
 
84
    def old_revno(self):
 
85
        return self._lookup_revno(self.old_revid)
 
86
 
 
87
    @property
 
88
    def new_revno(self):
 
89
        return self._lookup_revno(self.new_revid)
 
90
 
 
91
 
 
92
class GitTags(tag.BasicTags):
 
93
    """Ref-based tag dictionary."""
 
94
 
 
95
    def __init__(self, branch):
 
96
        self.branch = branch
 
97
        self.repository = branch.repository
 
98
 
 
99
    def get_refs(self):
 
100
        raise NotImplementedError(self.get_refs)
 
101
 
 
102
    def _iter_tag_refs(self, refs):
 
103
        raise NotImplementedError(self._iter_tag_refs)
 
104
 
 
105
    def _merge_to_git(self, to_tags, refs, overwrite=False):
 
106
        target_repo = to_tags.repository
 
107
        conflicts = []
 
108
        for k, v in refs.iteritems():
 
109
            if not is_tag(k):
 
110
                continue
 
111
            if overwrite or not k in target_repo._git.refs:
 
112
                target_repo._git.refs[k] = v
 
113
            elif target_repo._git.refs[k] == v:
 
114
                pass
 
115
            else:
 
116
                conflicts.append((ref_to_tag_name(k), v, target_repo.refs[k]))
 
117
        return conflicts
 
118
 
 
119
    def _merge_to_non_git(self, to_tags, refs, overwrite=False):
 
120
        unpeeled_map = defaultdict(set)
 
121
        conflicts = []
 
122
        result = dict(to_tags.get_tag_dict())
 
123
        for n, peeled, unpeeled, bzr_revid in self._iter_tag_refs(refs):
 
124
            if unpeeled is not None:
 
125
                unpeeled_map[peeled].add(unpeeled)
 
126
            if n not in result or overwrite:
 
127
                result[n] = bzr_revid
 
128
            elif result[n] == bzr_revid:
 
129
                pass
 
130
            else:
 
131
                conflicts.append((n, result[n], bzr_revid))
 
132
        to_tags._set_tag_dict(result)
 
133
        if len(unpeeled_map) > 0:
 
134
            map_file = UnpeelMap.from_repository(to_tags.branch.repository)
 
135
            map_file.update(unpeeled_map)
 
136
            map_file.save_in_repository(to_tags.branch.repository)
 
137
        return conflicts
 
138
 
 
139
    def merge_to(self, to_tags, overwrite=False, ignore_master=False,
 
140
                 source_refs=None):
 
141
        """See Tags.merge_to."""
 
142
        if source_refs is None:
 
143
            source_refs = self.get_refs()
 
144
        if self == to_tags:
 
145
            return
 
146
        if isinstance(to_tags, GitTags):
 
147
            return self._merge_to_git(to_tags, source_refs,
 
148
                                      overwrite=overwrite)
 
149
        else:
 
150
            if ignore_master:
 
151
                master = None
 
152
            else:
 
153
                master = to_tags.branch.get_master_branch()
 
154
            conflicts = self._merge_to_non_git(to_tags, source_refs,
 
155
                                              overwrite=overwrite)
 
156
            if master is not None:
 
157
                conflicts += self.merge_to(master.tags, overwrite=overwrite,
 
158
                                           source_refs=source_refs,
 
159
                                           ignore_master=ignore_master)
 
160
            return conflicts
 
161
 
 
162
    def get_tag_dict(self):
 
163
        ret = {}
 
164
        refs = self.get_refs()
 
165
        for (name, peeled, unpeeled, bzr_revid) in self._iter_tag_refs(refs):
 
166
            ret[name] = bzr_revid
 
167
        return ret
 
168
 
 
169
 
 
170
class LocalGitTagDict(GitTags):
 
171
    """Dictionary with tags in a local repository."""
 
172
 
 
173
    def __init__(self, branch):
 
174
        super(LocalGitTagDict, self).__init__(branch)
 
175
        self.refs = self.repository._git.refs
 
176
 
 
177
    def get_refs(self):
 
178
        return self.repository._git.get_refs()
 
179
 
 
180
    def _iter_tag_refs(self, refs):
 
181
        """Iterate over the tag refs.
 
182
 
 
183
        :param refs: Refs dictionary (name -> git sha1)
 
184
        :return: iterator over (name, peeled_sha1, unpeeled_sha1, bzr_revid)
 
185
        """
 
186
        for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
 
187
            try:
 
188
                obj = self.repository._git[peeled]
 
189
            except KeyError:
 
190
                mutter("Tag %s points at unknown object %s, ignoring", peeled,
 
191
                       peeled)
 
192
                continue
 
193
            # FIXME: this shouldn't really be necessary, the repository
 
194
            # already should have these unpeeled.
 
195
            while isinstance(obj, Tag):
 
196
                peeled = obj.object[1]
 
197
                obj = self.repository._git[peeled]
 
198
            if not isinstance(obj, Commit):
 
199
                mutter("Tag %s points at object %r that is not a commit, "
 
200
                       "ignoring", k, obj)
 
201
                continue
 
202
            yield (k, peeled, unpeeled,
 
203
                   self.branch.lookup_foreign_revision_id(peeled))
 
204
 
 
205
    def _set_tag_dict(self, to_dict):
 
206
        extra = set(self.get_refs().keys())
 
207
        for k, revid in to_dict.iteritems():
 
208
            name = tag_name_to_ref(k)
 
209
            if name in extra:
 
210
                extra.remove(name)
 
211
            self.set_tag(k, revid)
 
212
        for name in extra:
 
213
            if is_tag(name):
 
214
                del self.repository._git[name]
 
215
 
 
216
    def set_tag(self, name, revid):
 
217
        try:
 
218
            git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
 
219
        except errors.NoSuchRevision:
 
220
            raise errors.GhostTagsNotSupported(self)
 
221
        self.refs[tag_name_to_ref(name)] = git_sha
 
222
 
 
223
 
 
224
class DictTagDict(tag.BasicTags):
 
225
 
 
226
    def __init__(self, branch, tags):
 
227
        super(DictTagDict, self).__init__(branch)
 
228
        self._tags = tags
 
229
 
 
230
    def get_tag_dict(self):
 
231
        return self._tags
 
232
 
 
233
 
 
234
class GitSymrefBranchFormat(branch.BranchFormat):
 
235
 
 
236
    def get_format_description(self):
 
237
        return 'Git Symbolic Reference Branch'
 
238
 
 
239
    def network_name(self):
 
240
        return "git"
 
241
 
 
242
    def get_reference(self, controldir, name=None):
 
243
        return controldir.get_branch_reference(name)
 
244
 
 
245
    def set_reference(self, controldir, name, target):
 
246
        return controldir.set_branch_reference(name, target)
 
247
 
 
248
 
 
249
class GitBranchFormat(branch.BranchFormat):
 
250
 
 
251
    def get_format_description(self):
 
252
        return 'Git Branch'
 
253
 
 
254
    def network_name(self):
 
255
        return "git"
 
256
 
 
257
    def supports_tags(self):
 
258
        return True
 
259
 
 
260
    def supports_leaving_lock(self):
 
261
        return False
 
262
 
 
263
    def supports_tags_referencing_ghosts(self):
 
264
        return False
 
265
 
 
266
    def tags_are_versioned(self):
 
267
        return False
 
268
 
 
269
    @property
 
270
    def _matchingbzrdir(self):
 
271
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
 
272
        return LocalGitControlDirFormat()
 
273
 
 
274
    def get_foreign_tests_branch_factory(self):
 
275
        from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
 
276
        return ForeignTestsBranchFactory()
 
277
 
 
278
    def make_tags(self, branch):
 
279
        if getattr(branch.repository, "get_refs", None) is not None:
 
280
            from bzrlib.plugins.git.remote import RemoteGitTagDict
 
281
            return RemoteGitTagDict(branch)
 
282
        else:
 
283
            return LocalGitTagDict(branch)
 
284
 
 
285
    def initialize(self, a_bzrdir, name=None, repository=None):
 
286
        from bzrlib.plugins.git.dir import LocalGitDir
 
287
        if not isinstance(a_bzrdir, LocalGitDir):
 
288
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
 
289
        if repository is None:
 
290
            repository = a_bzrdir.open_repository()
 
291
        ref = branch_name_to_ref(name, "HEAD")
 
292
        repository._git[ref] = ZERO_SHA
 
293
        return LocalGitBranch(a_bzrdir, repository, ref, a_bzrdir._lockfiles)
 
294
 
 
295
 
 
296
class GitReadLock(object):
 
297
 
 
298
    def __init__(self, unlock):
 
299
        self.unlock = unlock
 
300
 
 
301
 
 
302
class GitWriteLock(object):
 
303
 
 
304
    def __init__(self, unlock):
 
305
        self.branch_token = None
 
306
        self.unlock = unlock
 
307
 
 
308
 
 
309
class GitBranch(ForeignBranch):
 
310
    """An adapter to git repositories for bzr Branch objects."""
 
311
 
 
312
    @property
 
313
    def control_transport(self):
 
314
        return self.bzrdir.control_transport
 
315
 
 
316
    def __init__(self, bzrdir, repository, ref, lockfiles, tagsdict=None):
 
317
        self.base = bzrdir.root_transport.base
 
318
        self.repository = repository
 
319
        self._format = GitBranchFormat()
 
320
        self.control_files = lockfiles
 
321
        self.bzrdir = bzrdir
 
322
        self._lock_mode = None
 
323
        self._lock_count = 0
 
324
        super(GitBranch, self).__init__(repository.get_mapping())
 
325
        if tagsdict is not None:
 
326
            self.tags = DictTagDict(self, tagsdict)
 
327
        self.ref = ref
 
328
        try:
 
329
            self.name = ref_to_branch_name(ref)
 
330
        except ValueError:
 
331
            self.name = None
 
332
        self._head = None
 
333
 
 
334
    def _get_checkout_format(self, lightweight=False):
 
335
        """Return the most suitable metadir for a checkout of this branch.
 
336
        Weaves are used if this branch's repository uses weaves.
 
337
        """
 
338
        return bzrdir.format_registry.make_bzrdir("default")
 
339
 
 
340
    def get_child_submit_format(self):
 
341
        """Return the preferred format of submissions to this branch."""
 
342
        ret = self.get_config().get_user_option("child_submit_format")
 
343
        if ret is not None:
 
344
            return ret
 
345
        return "git"
 
346
 
 
347
    def _get_nick(self, local=False, possible_master_transports=None):
 
348
        """Find the nick name for this branch.
 
349
 
 
350
        :return: Branch nick
 
351
        """
 
352
        return self.name or "HEAD"
 
353
 
 
354
    def _set_nick(self, nick):
 
355
        raise NotImplementedError
 
356
 
 
357
    nick = property(_get_nick, _set_nick)
 
358
 
 
359
    def __repr__(self):
 
360
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
 
361
            self.name)
 
362
 
 
363
    def generate_revision_history(self, revid, old_revid=None):
 
364
        if revid == NULL_REVISION:
 
365
            newhead = ZERO_SHA
 
366
        else:
 
367
            # FIXME: Check that old_revid is in the ancestry of revid
 
368
            newhead, self.mapping = self.repository.lookup_bzr_revision_id(revid)
 
369
            if self.mapping is None:
 
370
                raise AssertionError
 
371
        self._set_head(newhead)
 
372
 
 
373
    def lock_write(self, token=None):
 
374
        if token is not None:
 
375
            raise errors.TokenLockingNotSupported(self)
 
376
        if self._lock_mode:
 
377
            if self._lock_mode == 'r':
 
378
                raise errors.ReadOnlyError(self)
 
379
            self._lock_count += 1
 
380
        else:
 
381
            self._lock_mode = 'w'
 
382
            self._lock_count = 1
 
383
        self.repository.lock_write()
 
384
        return GitWriteLock(self.unlock)
 
385
 
 
386
    def get_stacked_on_url(self):
 
387
        # Git doesn't do stacking (yet...)
 
388
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
389
 
 
390
    def get_parent(self):
 
391
        """See Branch.get_parent()."""
 
392
        # FIXME: Set "origin" url from .git/config ?
 
393
        return None
 
394
 
 
395
    def set_parent(self, url):
 
396
        # FIXME: Set "origin" url in .git/config ?
 
397
        pass
 
398
 
 
399
    def lock_read(self):
 
400
        if self._lock_mode:
 
401
            assert self._lock_mode in ('r', 'w')
 
402
            self._lock_count += 1
 
403
        else:
 
404
            self._lock_mode = 'r'
 
405
            self._lock_count = 1
 
406
        self.repository.lock_read()
 
407
        return GitReadLock(self.unlock)
 
408
 
 
409
    def peek_lock_mode(self):
 
410
        return self._lock_mode
 
411
 
 
412
    def is_locked(self):
 
413
        return (self._lock_mode is not None)
 
414
 
 
415
    def unlock(self):
 
416
        """See Branch.unlock()."""
 
417
        self._lock_count -= 1
 
418
        if self._lock_count == 0:
 
419
            self._lock_mode = None
 
420
            self._clear_cached_state()
 
421
        self.repository.unlock()
 
422
 
 
423
    def get_physical_lock_status(self):
 
424
        return False
 
425
 
 
426
    @needs_read_lock
 
427
    def last_revision(self):
 
428
        # perhaps should escape this ?
 
429
        if self.head is None:
 
430
            return revision.NULL_REVISION
 
431
        return self.lookup_foreign_revision_id(self.head)
 
432
 
 
433
    def _basic_push(self, target, overwrite=False, stop_revision=None):
 
434
        return branch.InterBranch.get(self, target)._basic_push(
 
435
            overwrite, stop_revision)
 
436
 
 
437
    def lookup_foreign_revision_id(self, foreign_revid):
 
438
        return self.repository.lookup_foreign_revision_id(foreign_revid,
 
439
            self.mapping)
 
440
 
 
441
    def lookup_bzr_revision_id(self, revid):
 
442
        return self.repository.lookup_bzr_revision_id(
 
443
            revid, mapping=self.mapping)
 
444
 
 
445
 
 
446
class LocalGitBranch(GitBranch):
 
447
    """A local Git branch."""
 
448
 
 
449
    def __init__(self, bzrdir, repository, ref, lockfiles, tagsdict=None):
 
450
        super(LocalGitBranch, self).__init__(bzrdir, repository, ref,
 
451
              lockfiles, tagsdict)
 
452
        refs = repository._git.get_refs()
 
453
        if not (ref in refs.keys() or "HEAD" in refs.keys()):
 
454
            raise errors.NotBranchError(self.base)
 
455
 
 
456
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
 
457
        accelerator_tree=None, hardlink=False):
 
458
        if lightweight:
 
459
            t = transport.get_transport(to_location)
 
460
            t.ensure_base()
 
461
            format = self._get_checkout_format(lightweight=True)
 
462
            checkout = format.initialize_on_transport(t)
 
463
            from_branch = branch.BranchReferenceFormat().initialize(checkout,
 
464
                self)
 
465
            tree = checkout.create_workingtree(revision_id,
 
466
                from_branch=from_branch, hardlink=hardlink)
 
467
            return tree
 
468
        else:
 
469
            return self._create_heavyweight_checkout(to_location, revision_id,
 
470
                hardlink)
 
471
 
 
472
    def _create_heavyweight_checkout(self, to_location, revision_id=None,
 
473
                                     hardlink=False):
 
474
        """Create a new heavyweight checkout of this branch.
 
475
 
 
476
        :param to_location: URL of location to create the new checkout in.
 
477
        :param revision_id: Revision that should be the tip of the checkout.
 
478
        :param hardlink: Whether to hardlink
 
479
        :return: WorkingTree object of checkout.
 
480
        """
 
481
        checkout_branch = bzrdir.BzrDir.create_branch_convenience(
 
482
            to_location, force_new_tree=False,
 
483
            format=self._get_checkout_format(lightweight=False))
 
484
        checkout = checkout_branch.bzrdir
 
485
        checkout_branch.bind(self)
 
486
        # pull up to the specified revision_id to set the initial
 
487
        # branch tip correctly, and seed it with history.
 
488
        checkout_branch.pull(self, stop_revision=revision_id)
 
489
        return checkout.create_workingtree(revision_id, hardlink=hardlink)
 
490
 
 
491
    def _gen_revision_history(self):
 
492
        if self.head is None:
 
493
            return []
 
494
        graph = self.repository.get_graph()
 
495
        ret = list(graph.iter_lefthand_ancestry(self.last_revision(),
 
496
            (revision.NULL_REVISION, )))
 
497
        ret.reverse()
 
498
        return ret
 
499
 
 
500
    def _get_head(self):
 
501
        try:
 
502
            return self.repository._git.ref(self.ref or "HEAD")
 
503
        except KeyError:
 
504
            return None
 
505
 
 
506
    def _read_last_revision_info(self):
 
507
        last_revid = self.last_revision()
 
508
        graph = self.repository.get_graph()
 
509
        revno = graph.find_distance_to_null(last_revid,
 
510
            [(revision.NULL_REVISION, 0)])
 
511
        return revno, last_revid
 
512
 
 
513
    def set_last_revision_info(self, revno, revision_id):
 
514
        self.set_last_revision(revision_id)
 
515
        self._last_revision_info_cache = revno, revision_id
 
516
 
 
517
    def set_last_revision(self, revid):
 
518
        if not revid or not isinstance(revid, basestring):
 
519
            raise errors.InvalidRevisionId(revision_id=revid, branch=self)
 
520
        if revid == NULL_REVISION:
 
521
            newhead = ZERO_SHA
 
522
        else:
 
523
            (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
 
524
            if self.mapping is None:
 
525
                raise AssertionError
 
526
        self._set_head(newhead)
 
527
 
 
528
    def _set_head(self, value):
 
529
        self._head = value
 
530
        self.repository._git.refs[self.ref or "HEAD"] = self._head
 
531
        self._clear_cached_state()
 
532
 
 
533
    head = property(_get_head, _set_head)
 
534
 
 
535
    def get_config(self):
 
536
        return GitBranchConfig(self)
 
537
 
 
538
    def get_push_location(self):
 
539
        """See Branch.get_push_location."""
 
540
        push_loc = self.get_config().get_user_option('push_location')
 
541
        return push_loc
 
542
 
 
543
    def set_push_location(self, location):
 
544
        """See Branch.set_push_location."""
 
545
        self.get_config().set_user_option('push_location', location,
 
546
                                          store=config.STORE_LOCATION)
 
547
 
 
548
    def supports_tags(self):
 
549
        return True
 
550
 
 
551
 
 
552
def _quick_lookup_revno(local_branch, remote_branch, revid):
 
553
    assert isinstance(revid, str), "was %r" % revid
 
554
    # Try in source branch first, it'll be faster
 
555
    local_branch.lock_read()
 
556
    try:
 
557
        try:
 
558
            return local_branch.revision_id_to_revno(revid)
 
559
        except errors.NoSuchRevision:
 
560
            graph = local_branch.repository.get_graph()
 
561
            try:
 
562
                return graph.find_distance_to_null(revid,
 
563
                    [(revision.NULL_REVISION, 0)])
 
564
            except errors.GhostRevisionsHaveNoRevno:
 
565
                # FIXME: Check using graph.find_distance_to_null() ?
 
566
                remote_branch.lock_read()
 
567
                try:
 
568
                    return remote_branch.revision_id_to_revno(revid)
 
569
                finally:
 
570
                    remote_branch.unlock()
 
571
    finally:
 
572
        local_branch.unlock()
 
573
 
 
574
 
 
575
class GitBranchPullResult(branch.PullResult):
 
576
 
 
577
    def __init__(self):
 
578
        super(GitBranchPullResult, self).__init__()
 
579
        self.new_git_head = None
 
580
        self._old_revno = None
 
581
        self._new_revno = None
 
582
 
 
583
    def report(self, to_file):
 
584
        if not is_quiet():
 
585
            if self.old_revid == self.new_revid:
 
586
                to_file.write('No revisions to pull.\n')
 
587
            elif self.new_git_head is not None:
 
588
                to_file.write('Now on revision %d (git sha: %s).\n' %
 
589
                        (self.new_revno, self.new_git_head))
 
590
            else:
 
591
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
 
592
        self._show_tag_conficts(to_file)
 
593
 
 
594
    def _lookup_revno(self, revid):
 
595
        return _quick_lookup_revno(self.target_branch, self.source_branch,
 
596
                revid)
 
597
 
 
598
    def _get_old_revno(self):
 
599
        if self._old_revno is not None:
 
600
            return self._old_revno
 
601
        return self._lookup_revno(self.old_revid)
 
602
 
 
603
    def _set_old_revno(self, revno):
 
604
        self._old_revno = revno
 
605
 
 
606
    old_revno = property(_get_old_revno, _set_old_revno)
 
607
 
 
608
    def _get_new_revno(self):
 
609
        if self._new_revno is not None:
 
610
            return self._new_revno
 
611
        return self._lookup_revno(self.new_revid)
 
612
 
 
613
    def _set_new_revno(self, revno):
 
614
        self._new_revno = revno
 
615
 
 
616
    new_revno = property(_get_new_revno, _set_new_revno)
 
617
 
 
618
 
 
619
class GitBranchPushResult(branch.BranchPushResult):
 
620
 
 
621
    def _lookup_revno(self, revid):
 
622
        return _quick_lookup_revno(self.source_branch, self.target_branch,
 
623
            revid)
 
624
 
 
625
    @property
 
626
    def old_revno(self):
 
627
        return self._lookup_revno(self.old_revid)
 
628
 
 
629
    @property
 
630
    def new_revno(self):
 
631
        new_original_revno = getattr(self, "new_original_revno", None)
 
632
        if new_original_revno:
 
633
            return new_original_revno
 
634
        if getattr(self, "new_original_revid", None) is not None:
 
635
            return self._lookup_revno(self.new_original_revid)
 
636
        return self._lookup_revno(self.new_revid)
 
637
 
 
638
 
 
639
class InterFromGitBranch(branch.GenericInterBranch):
 
640
    """InterBranch implementation that pulls from Git into bzr."""
 
641
 
 
642
    @staticmethod
 
643
    def _get_branch_formats_to_test():
 
644
        try:
 
645
            default_format = branch.format_registry.get_default()
 
646
        except AttributeError:
 
647
            default_format = branch.BranchFormat._default_format
 
648
        return [
 
649
            (GitBranchFormat(), GitBranchFormat()),
 
650
            (GitBranchFormat(), default_format)]
 
651
 
 
652
    @classmethod
 
653
    def _get_interrepo(self, source, target):
 
654
        return _mod_repository.InterRepository.get(source.repository, target.repository)
 
655
 
 
656
    @classmethod
 
657
    def is_compatible(cls, source, target):
 
658
        if not isinstance(source, GitBranch):
 
659
            return False
 
660
        if isinstance(target, GitBranch):
 
661
            # InterLocalGitRemoteGitBranch or InterToGitBranch should be used
 
662
            return False
 
663
        if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
 
664
            # fetch_objects is necessary for this to work
 
665
            return False
 
666
        return True
 
667
 
 
668
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
 
669
        self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
 
670
 
 
671
    def fetch_objects(self, stop_revision, fetch_tags, limit=None):
 
672
        interrepo = self._get_interrepo(self.source, self.target)
 
673
        if fetch_tags is None:
 
674
            c = self.source.get_config()
 
675
            fetch_tags = c.get_user_option_as_bool('branch.fetch_tags')
 
676
        def determine_wants(heads):
 
677
            if self.source.ref is not None and not self.source.ref in heads:
 
678
                raise NoSuchRef(self.source.ref, heads.keys())
 
679
 
 
680
            if stop_revision is None:
 
681
                if self.source.ref is not None:
 
682
                    head = heads[self.source.ref]
 
683
                else:
 
684
                    head = heads["HEAD"]
 
685
                self._last_revid = self.source.lookup_foreign_revision_id(head)
 
686
            else:
 
687
                self._last_revid = stop_revision
 
688
            real = interrepo.get_determine_wants_revids(
 
689
                [self._last_revid], include_tags=fetch_tags)
 
690
            return real(heads)
 
691
        pack_hint, head, refs = interrepo.fetch_objects(
 
692
            determine_wants, self.source.mapping, limit=limit)
 
693
        if (pack_hint is not None and
 
694
            self.target.repository._format.pack_compresses):
 
695
            self.target.repository.pack(hint=pack_hint)
 
696
        return head, refs
 
697
 
 
698
    def _update_revisions(self, stop_revision=None, overwrite=False):
 
699
        head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
 
700
        if overwrite:
 
701
            prev_last_revid = None
 
702
        else:
 
703
            prev_last_revid = self.target.last_revision()
 
704
        self.target.generate_revision_history(self._last_revid,
 
705
            prev_last_revid, self.source)
 
706
        return head, refs
 
707
 
 
708
    def pull(self, overwrite=False, stop_revision=None,
 
709
             possible_transports=None, _hook_master=None, run_hooks=True,
 
710
             _override_hook_target=None, local=False):
 
711
        """See Branch.pull.
 
712
 
 
713
        :param _hook_master: Private parameter - set the branch to
 
714
            be supplied as the master to pull hooks.
 
715
        :param run_hooks: Private parameter - if false, this branch
 
716
            is being called because it's the master of the primary branch,
 
717
            so it should not run its hooks.
 
718
        :param _override_hook_target: Private parameter - set the branch to be
 
719
            supplied as the target_branch to pull hooks.
 
720
        """
 
721
        # This type of branch can't be bound.
 
722
        if local:
 
723
            raise errors.LocalRequiresBoundBranch()
 
724
        result = GitBranchPullResult()
 
725
        result.source_branch = self.source
 
726
        if _override_hook_target is None:
 
727
            result.target_branch = self.target
 
728
        else:
 
729
            result.target_branch = _override_hook_target
 
730
        self.source.lock_read()
 
731
        try:
 
732
            self.target.lock_write()
 
733
            try:
 
734
                # We assume that during 'pull' the target repository is closer than
 
735
                # the source one.
 
736
                (result.old_revno, result.old_revid) = \
 
737
                    self.target.last_revision_info()
 
738
                result.new_git_head, remote_refs = self._update_revisions(
 
739
                    stop_revision, overwrite=overwrite)
 
740
                result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
741
                    overwrite)
 
742
                (result.new_revno, result.new_revid) = \
 
743
                    self.target.last_revision_info()
 
744
                if _hook_master:
 
745
                    result.master_branch = _hook_master
 
746
                    result.local_branch = result.target_branch
 
747
                else:
 
748
                    result.master_branch = result.target_branch
 
749
                    result.local_branch = None
 
750
                if run_hooks:
 
751
                    for hook in branch.Branch.hooks['post_pull']:
 
752
                        hook(result)
 
753
            finally:
 
754
                self.target.unlock()
 
755
        finally:
 
756
            self.source.unlock()
 
757
        return result
 
758
 
 
759
    def _basic_push(self, overwrite=False, stop_revision=None):
 
760
        result = branch.BranchPushResult()
 
761
        result.source_branch = self.source
 
762
        result.target_branch = self.target
 
763
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
764
        result.new_git_head, remote_refs = self._update_revisions(
 
765
            stop_revision, overwrite=overwrite)
 
766
        result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
767
            overwrite)
 
768
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
769
        return result
 
770
 
 
771
 
 
772
class InterGitBranch(branch.GenericInterBranch):
 
773
    """InterBranch implementation that pulls between Git branches."""
 
774
 
 
775
 
 
776
class InterLocalGitRemoteGitBranch(InterGitBranch):
 
777
    """InterBranch that copies from a local to a remote git branch."""
 
778
 
 
779
    @staticmethod
 
780
    def _get_branch_formats_to_test():
 
781
        # FIXME
 
782
        return []
 
783
 
 
784
    @classmethod
 
785
    def is_compatible(self, source, target):
 
786
        from bzrlib.plugins.git.remote import RemoteGitBranch
 
787
        return (isinstance(source, LocalGitBranch) and
 
788
                isinstance(target, RemoteGitBranch))
 
789
 
 
790
    def _basic_push(self, overwrite=False, stop_revision=None):
 
791
        result = GitBranchPushResult()
 
792
        result.source_branch = self.source
 
793
        result.target_branch = self.target
 
794
        if stop_revision is None:
 
795
            stop_revision = self.source.last_revision()
 
796
        # FIXME: Check for diverged branches
 
797
        def get_changed_refs(old_refs):
 
798
            old_ref = old_refs.get(self.target.ref, ZERO_SHA)
 
799
            result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
 
800
            refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
 
801
            result.new_revid = stop_revision
 
802
            for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
 
803
                refs[tag_name_to_ref(name)] = sha
 
804
            return refs
 
805
        self.target.repository.send_pack(get_changed_refs,
 
806
            self.source.repository._git.object_store.generate_pack_contents)
 
807
        return result
 
808
 
 
809
 
 
810
class InterGitLocalGitBranch(InterGitBranch):
 
811
    """InterBranch that copies from a remote to a local git branch."""
 
812
 
 
813
    @staticmethod
 
814
    def _get_branch_formats_to_test():
 
815
        # FIXME
 
816
        return []
 
817
 
 
818
    @classmethod
 
819
    def is_compatible(self, source, target):
 
820
        return (isinstance(source, GitBranch) and
 
821
                isinstance(target, LocalGitBranch))
 
822
 
 
823
    def _basic_push(self, overwrite=False, stop_revision=None):
 
824
        result = GitBranchPushResult()
 
825
        result.source_branch = self.source
 
826
        result.target_branch = self.target
 
827
        result.old_revid = self.target.last_revision()
 
828
        refs, stop_revision = self.update_refs(stop_revision)
 
829
        self.target.generate_revision_history(stop_revision, result.old_revid)
 
830
        result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
831
            source_refs=refs, overwrite=overwrite)
 
832
        result.new_revid = self.target.last_revision()
 
833
        return result
 
834
 
 
835
    def update_refs(self, stop_revision=None):
 
836
        interrepo = _mod_repository.InterRepository.get(self.source.repository,
 
837
            self.target.repository)
 
838
        if stop_revision is None:
 
839
            refs = interrepo.fetch(branches=["HEAD"])
 
840
            stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
 
841
        else:
 
842
            refs = interrepo.fetch(revision_id=stop_revision)
 
843
        return refs, stop_revision
 
844
 
 
845
    def pull(self, stop_revision=None, overwrite=False,
 
846
        possible_transports=None, run_hooks=True,local=False):
 
847
        # This type of branch can't be bound.
 
848
        if local:
 
849
            raise errors.LocalRequiresBoundBranch()
 
850
        result = GitPullResult()
 
851
        result.source_branch = self.source
 
852
        result.target_branch = self.target
 
853
        self.source.lock_read()
 
854
        try:
 
855
            self.target.lock_write()
 
856
            try:
 
857
                result.old_revid = self.target.last_revision()
 
858
                refs, stop_revision = self.update_refs(stop_revision)
 
859
                self.target.generate_revision_history(stop_revision, result.old_revid)
 
860
                result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
861
                    overwrite=overwrite, source_refs=refs)
 
862
                result.new_revid = self.target.last_revision()
 
863
                result.local_branch = None
 
864
                result.master_branch = result.target_branch
 
865
                if run_hooks:
 
866
                    for hook in branch.Branch.hooks['post_pull']:
 
867
                        hook(result)
 
868
            finally:
 
869
                self.target.unlock()
 
870
        finally:
 
871
            self.source.unlock()
 
872
        return result
 
873
 
 
874
 
 
875
class InterToGitBranch(branch.GenericInterBranch):
 
876
    """InterBranch implementation that pulls into a Git branch."""
 
877
 
 
878
    def __init__(self, source, target):
 
879
        super(InterToGitBranch, self).__init__(source, target)
 
880
        self.interrepo = _mod_repository.InterRepository.get(source.repository,
 
881
                                           target.repository)
 
882
 
 
883
    @staticmethod
 
884
    def _get_branch_formats_to_test():
 
885
        try:
 
886
            default_format = branch.format_registry.get_default()
 
887
        except AttributeError:
 
888
            default_format = branch.BranchFormat._default_format
 
889
        return [(default_format, GitBranchFormat())]
 
890
 
 
891
    @classmethod
 
892
    def is_compatible(self, source, target):
 
893
        return (not isinstance(source, GitBranch) and
 
894
                isinstance(target, GitBranch))
 
895
 
 
896
    def _get_new_refs(self, stop_revision=None, fetch_tags=None):
 
897
        if stop_revision is None:
 
898
            (stop_revno, stop_revision) = self.source.last_revision_info()
 
899
        else:
 
900
            stop_revno = self.source.revision_id_to_revno(stop_revision)
 
901
        assert type(stop_revision) is str
 
902
        main_ref = self.target.ref or "refs/heads/master"
 
903
        refs = { main_ref: (None, stop_revision) }
 
904
        if fetch_tags is None:
 
905
            c = self.source.get_config()
 
906
            fetch_tags = c.get_user_option_as_bool('branch.fetch_tags')
 
907
        if fetch_tags:
 
908
            for name, revid in self.source.tags.get_tag_dict().iteritems():
 
909
                if self.source.repository.has_revision(revid):
 
910
                    refs[tag_name_to_ref(name)] = (None, revid)
 
911
        return refs, main_ref, (stop_revno, stop_revision)
 
912
 
 
913
    def pull(self, overwrite=False, stop_revision=None, local=False,
 
914
             possible_transports=None, run_hooks=True):
 
915
        result = GitBranchPullResult()
 
916
        result.source_branch = self.source
 
917
        result.target_branch = self.target
 
918
        self.source.lock_read()
 
919
        try:
 
920
            self.target.lock_write()
 
921
            try:
 
922
                new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
 
923
                def update_refs(old_refs):
 
924
                    # FIXME: Check for diverged branches
 
925
                    return new_refs
 
926
                try:
 
927
                    result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
 
928
                        update_refs, lossy=False)
 
929
                except NoPushSupport:
 
930
                    raise errors.NoRoundtrippingSupport(self.source, self.target)
 
931
                (result.old_revid, old_sha1) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
 
932
                if result.old_revid is None:
 
933
                    result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
 
934
                result.new_revid = new_refs[main_ref][1]
 
935
                result.local_branch = None
 
936
                result.master_branch = self.target
 
937
                if run_hooks:
 
938
                    for hook in branch.Branch.hooks['post_pull']:
 
939
                        hook(result)
 
940
            finally:
 
941
                self.target.unlock()
 
942
        finally:
 
943
            self.source.unlock()
 
944
        return result
 
945
 
 
946
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
947
             _override_hook_source_branch=None):
 
948
        result = GitBranchPushResult()
 
949
        result.source_branch = self.source
 
950
        result.target_branch = self.target
 
951
        result.local_branch = None
 
952
        result.master_branch = result.target_branch
 
953
        new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
 
954
        def update_refs(old_refs):
 
955
            # FIXME: Check for diverged branches
 
956
            return new_refs
 
957
        try:
 
958
            result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
 
959
                update_refs, lossy=lossy)
 
960
        except NoPushSupport:
 
961
            raise errors.NoRoundtrippingSupport(self.source, self.target)
 
962
        (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
 
963
        if result.old_revid is None:
 
964
            result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
 
965
        result.new_revid = new_refs[main_ref][1]
 
966
        (result.new_original_revno, result.new_original_revid) = stop_revinfo
 
967
        for hook in branch.Branch.hooks['post_push']:
 
968
            hook(result)
 
969
        return result
 
970
 
 
971
    def lossy_push(self, stop_revision=None):
 
972
        # For compatibility with bzr < 2.4
 
973
        return self.push(lossy=True, stop_revision=stop_revision)
 
974
 
 
975
 
 
976
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
 
977
branch.InterBranch.register_optimiser(InterFromGitBranch)
 
978
branch.InterBranch.register_optimiser(InterToGitBranch)
 
979
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)