/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 more tests.

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