/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

Fix .destroy_branch.

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