/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 two mistakes in 'bzr help git'.

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