/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

Cope with submodules in working trees.

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