/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

Tags: bzr-git-0.6.5
ReleaseĀ 0.6.6.

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