/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 HEAD.

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