/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

  • Committer: Jelmer Vernooij
  • Date: 2018-03-22 23:28:30 UTC
  • mto: (0.200.1883 work)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180322232830-fy9mychr0f8s7hn2
Various fixes for annotated tags and symrefs.

Show diffs side-by-side

added added

removed removed

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