/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 breezy/git/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2020-02-07 02:14:30 UTC
  • mto: This revision was merged to the branch mainline in revision 7492.
  • Revision ID: jelmer@jelmer.uk-20200207021430-m49iq3x4x8xlib6x
Drop python2 support.

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>
 
1
# Copyright (C) 2007,2012 Canonical Ltd
 
2
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
5
5
# it under the terms of the GNU General Public License as published by
13
13
#
14
14
# You should have received a copy of the GNU General Public License
15
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
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
 
18
18
"""An adapter between a Git Branch and a Bazaar Branch"""
19
19
 
 
20
from __future__ import absolute_import
 
21
 
 
22
import contextlib
 
23
from io import BytesIO
 
24
from collections import defaultdict
 
25
 
 
26
from dulwich.config import (
 
27
    ConfigFile as GitConfigFile,
 
28
    parse_submodules,
 
29
    )
 
30
 
20
31
from dulwich.objects import (
21
 
    Commit,
22
 
    Tag,
 
32
    NotCommitError,
 
33
    ZERO_SHA,
23
34
    )
 
35
from dulwich.repo import check_ref_format
24
36
 
25
 
from bzrlib import (
 
37
from .. import (
26
38
    branch,
27
 
    bzrdir,
28
39
    config,
 
40
    controldir,
29
41
    errors,
30
 
    repository,
 
42
    lock,
 
43
    repository as _mod_repository,
31
44
    revision,
32
45
    tag,
 
46
    trace,
33
47
    transport,
34
 
    )
35
 
from bzrlib.decorators import (
36
 
    needs_read_lock,
37
 
    )
38
 
from bzrlib.revision import (
 
48
    urlutils,
 
49
    )
 
50
from ..foreign import ForeignBranch
 
51
from ..revision import (
39
52
    NULL_REVISION,
40
53
    )
41
 
from bzrlib.trace import (
 
54
from ..trace import (
42
55
    is_quiet,
43
56
    mutter,
 
57
    warning,
44
58
    )
45
59
 
46
 
from bzrlib.plugins.git.config import (
 
60
from .config import (
47
61
    GitBranchConfig,
 
62
    GitBranchStack,
48
63
    )
49
 
from bzrlib.plugins.git.errors import (
 
64
from .errors import (
50
65
    NoPushSupport,
51
 
    NoSuchRef,
52
 
    )
53
 
from bzrlib.plugins.git.refs import (
 
66
    )
 
67
from .push import (
 
68
    remote_divergence,
 
69
    )
 
70
from .refs import (
 
71
    branch_name_to_ref,
 
72
    is_tag,
54
73
    ref_to_branch_name,
55
 
    extract_tags,
 
74
    ref_to_tag_name,
 
75
    remote_refs_dict_to_tag_refs,
56
76
    tag_name_to_ref,
57
77
    )
58
 
 
59
 
from bzrlib.foreign import ForeignBranch
 
78
from .unpeel_map import (
 
79
    UnpeelMap,
 
80
    )
 
81
from .urls import (
 
82
    git_url_to_bzr_url,
 
83
    bzr_url_to_git_url,
 
84
    )
 
85
 
 
86
 
 
87
def _calculate_revnos(branch):
 
88
    if branch._format.stores_revno():
 
89
        return True
 
90
    config = branch.get_config_stack()
 
91
    return config.get('calculate_revnos')
60
92
 
61
93
 
62
94
class GitPullResult(branch.PullResult):
63
95
    """Result of a pull from a Git branch."""
64
96
 
65
97
    def _lookup_revno(self, revid):
66
 
        assert isinstance(revid, str), "was %r" % revid
 
98
        if not isinstance(revid, bytes):
 
99
            raise TypeError(revid)
 
100
        if not _calculate_revnos(self.target_branch):
 
101
            return None
67
102
        # Try in source branch first, it'll be faster
68
 
        return self.target_branch.revision_id_to_revno(revid)
 
103
        with self.target_branch.lock_read():
 
104
            return self.target_branch.revision_id_to_revno(revid)
69
105
 
70
106
    @property
71
107
    def old_revno(self):
76
112
        return self._lookup_revno(self.new_revid)
77
113
 
78
114
 
79
 
class LocalGitTagDict(tag.BasicTags):
80
 
    """Dictionary with tags in a local repository."""
 
115
class GitTags(tag.BasicTags):
 
116
    """Ref-based tag dictionary."""
81
117
 
82
118
    def __init__(self, branch):
83
119
        self.branch = branch
84
120
        self.repository = branch.repository
85
121
 
 
122
    def _merge_to_remote_git(self, target_repo, source_tag_refs,
 
123
                             overwrite=False):
 
124
        updates = {}
 
125
        conflicts = []
 
126
 
 
127
        def get_changed_refs(old_refs):
 
128
            ret = dict(old_refs)
 
129
            for ref_name, tag_name, peeled, unpeeled in (
 
130
                    source_tag_refs.iteritems()):
 
131
                if old_refs.get(ref_name) == unpeeled:
 
132
                    pass
 
133
                elif overwrite or ref_name not in old_refs:
 
134
                    ret[ref_name] = unpeeled
 
135
                    updates[tag_name] = target_repo.lookup_foreign_revision_id(
 
136
                        peeled)
 
137
                else:
 
138
                    conflicts.append(
 
139
                        (tag_name,
 
140
                         self.repository.lookup_foreign_revision_id(peeled),
 
141
                         target_repo.lookup_foreign_revision_id(
 
142
                             old_refs[ref_name])))
 
143
            return ret
 
144
        target_repo.controldir.send_pack(
 
145
            get_changed_refs, lambda have, want: [])
 
146
        return updates, conflicts
 
147
 
 
148
    def _merge_to_local_git(self, target_repo, source_tag_refs,
 
149
                            overwrite=False):
 
150
        conflicts = []
 
151
        updates = {}
 
152
        for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
 
153
            if target_repo._git.refs.get(ref_name) == unpeeled:
 
154
                pass
 
155
            elif overwrite or ref_name not in target_repo._git.refs:
 
156
                try:
 
157
                    updates[tag_name] = (
 
158
                        target_repo.lookup_foreign_revision_id(peeled))
 
159
                except KeyError:
 
160
                    trace.warning('%s does not point to a valid object',
 
161
                                  tag_name)
 
162
                    continue
 
163
                except NotCommitError:
 
164
                    trace.warning('%s points to a non-commit object',
 
165
                                  tag_name)
 
166
                    continue
 
167
                target_repo._git.refs[ref_name] = unpeeled or peeled
 
168
            else:
 
169
                try:
 
170
                    source_revid = self.repository.lookup_foreign_revision_id(
 
171
                        peeled)
 
172
                    target_revid = target_repo.lookup_foreign_revision_id(
 
173
                        target_repo._git.refs[ref_name])
 
174
                except KeyError:
 
175
                    trace.warning('%s does not point to a valid object',
 
176
                                  ref_name)
 
177
                    continue
 
178
                except NotCommitError:
 
179
                    trace.warning('%s points to a non-commit object',
 
180
                                  tag_name)
 
181
                    continue
 
182
                conflicts.append((tag_name, source_revid, target_revid))
 
183
        return updates, conflicts
 
184
 
 
185
    def _merge_to_git(self, to_tags, source_tag_refs, overwrite=False):
 
186
        target_repo = to_tags.repository
 
187
        if self.repository.has_same_location(target_repo):
 
188
            return {}, []
 
189
        try:
 
190
            if getattr(target_repo, "_git", None):
 
191
                return self._merge_to_local_git(
 
192
                    target_repo, source_tag_refs, overwrite)
 
193
            else:
 
194
                return self._merge_to_remote_git(
 
195
                    target_repo, source_tag_refs, overwrite)
 
196
        finally:
 
197
            to_tags.branch._tag_refs = None
 
198
 
 
199
    def _merge_to_non_git(self, to_tags, source_tag_refs, overwrite=False):
 
200
        unpeeled_map = defaultdict(set)
 
201
        conflicts = []
 
202
        updates = {}
 
203
        result = dict(to_tags.get_tag_dict())
 
204
        for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
 
205
            if unpeeled is not None:
 
206
                unpeeled_map[peeled].add(unpeeled)
 
207
            try:
 
208
                bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
 
209
            except NotCommitError:
 
210
                continue
 
211
            if result.get(tag_name) == bzr_revid:
 
212
                pass
 
213
            elif tag_name not in result or overwrite:
 
214
                result[tag_name] = bzr_revid
 
215
                updates[tag_name] = bzr_revid
 
216
            else:
 
217
                conflicts.append((tag_name, bzr_revid, result[tag_name]))
 
218
        to_tags._set_tag_dict(result)
 
219
        if len(unpeeled_map) > 0:
 
220
            map_file = UnpeelMap.from_repository(to_tags.branch.repository)
 
221
            map_file.update(unpeeled_map)
 
222
            map_file.save_in_repository(to_tags.branch.repository)
 
223
        return updates, conflicts
 
224
 
 
225
    def merge_to(self, to_tags, overwrite=False, ignore_master=False,
 
226
                 source_tag_refs=None):
 
227
        """See Tags.merge_to."""
 
228
        if source_tag_refs is None:
 
229
            source_tag_refs = self.branch.get_tag_refs()
 
230
        if self == to_tags:
 
231
            return {}, []
 
232
        if isinstance(to_tags, GitTags):
 
233
            return self._merge_to_git(to_tags, source_tag_refs,
 
234
                                      overwrite=overwrite)
 
235
        else:
 
236
            if ignore_master:
 
237
                master = None
 
238
            else:
 
239
                master = to_tags.branch.get_master_branch()
 
240
            with contextlib.ExitStack() as es:
 
241
                if master is not None:
 
242
                    es.enter_context(master.lock_write())
 
243
                updates, conflicts = self._merge_to_non_git(
 
244
                    to_tags, source_tag_refs, overwrite=overwrite)
 
245
                if master is not None:
 
246
                    extra_updates, extra_conflicts = self.merge_to(
 
247
                        master.tags, overwrite=overwrite,
 
248
                        source_tag_refs=source_tag_refs,
 
249
                        ignore_master=ignore_master)
 
250
                    updates.update(extra_updates)
 
251
                    conflicts += extra_conflicts
 
252
                return updates, conflicts
 
253
 
86
254
    def get_tag_dict(self):
87
255
        ret = {}
88
 
        for k,v in extract_tags(self.repository._git.get_refs()).iteritems():
 
256
        for (ref_name, tag_name, peeled, unpeeled) in (
 
257
                self.branch.get_tag_refs()):
89
258
            try:
90
 
                obj = self.repository._git[v]
91
 
            except KeyError:
92
 
                mutter("Tag %s points at unknown object %s, ignoring", v, obj)
93
 
                continue
94
 
            while isinstance(obj, Tag):
95
 
                v = obj.object[1]
96
 
                obj = self.repository._git[v]
97
 
            if not isinstance(obj, Commit):
98
 
                mutter("Tag %s points at object %r that is not a commit, "
99
 
                       "ignoring", k, obj)
100
 
                continue
101
 
            ret[k] = self.branch.lookup_foreign_revision_id(v)
 
259
                bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
 
260
            except NotCommitError:
 
261
                continue
 
262
            else:
 
263
                ret[tag_name] = bzr_revid
102
264
        return ret
103
265
 
 
266
 
 
267
class LocalGitTagDict(GitTags):
 
268
    """Dictionary with tags in a local repository."""
 
269
 
 
270
    def __init__(self, branch):
 
271
        super(LocalGitTagDict, self).__init__(branch)
 
272
        self.refs = self.repository.controldir._git.refs
 
273
 
104
274
    def _set_tag_dict(self, to_dict):
105
 
        extra = set(self.repository._git.get_refs().keys())
106
 
        for k, revid in to_dict.iteritems():
 
275
        extra = set(self.refs.allkeys())
 
276
        for k, revid in to_dict.items():
107
277
            name = tag_name_to_ref(k)
108
278
            if name in extra:
109
279
                extra.remove(name)
110
 
            self.set_tag(k, revid)
 
280
            try:
 
281
                self.set_tag(k, revid)
 
282
            except errors.GhostTagsNotSupported:
 
283
                pass
111
284
        for name in extra:
112
 
            if name.startswith("refs/tags/"):
 
285
            if is_tag(name):
113
286
                del self.repository._git[name]
114
287
 
115
288
    def set_tag(self, name, revid):
116
 
        self.repository._git.refs[tag_name_to_ref(name)], _ = \
117
 
            self.branch.lookup_bzr_revision_id(revid)
118
 
 
119
 
 
120
 
class DictTagDict(LocalGitTagDict):
121
 
 
122
 
    def __init__(self, branch, tags):
123
 
        super(DictTagDict, self).__init__(branch)
124
 
        self._tags = tags
125
 
 
126
 
    def get_tag_dict(self):
127
 
        return self._tags
 
289
        try:
 
290
            git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
 
291
        except errors.NoSuchRevision:
 
292
            raise errors.GhostTagsNotSupported(self)
 
293
        self.refs[tag_name_to_ref(name)] = git_sha
 
294
        self.branch._tag_refs = None
 
295
 
 
296
    def delete_tag(self, name):
 
297
        ref = tag_name_to_ref(name)
 
298
        if ref not in self.refs:
 
299
            raise errors.NoSuchTag(name)
 
300
        del self.refs[ref]
 
301
        self.branch._tag_refs = None
128
302
 
129
303
 
130
304
class GitBranchFormat(branch.BranchFormat):
131
305
 
132
 
    def get_format_description(self):
133
 
        return 'Git Branch'
134
 
 
135
306
    def network_name(self):
136
 
        return "git"
 
307
        return b"git"
137
308
 
138
309
    def supports_tags(self):
139
310
        return True
140
311
 
 
312
    def supports_leaving_lock(self):
 
313
        return False
 
314
 
 
315
    def supports_tags_referencing_ghosts(self):
 
316
        return False
 
317
 
 
318
    def tags_are_versioned(self):
 
319
        return False
 
320
 
141
321
    def get_foreign_tests_branch_factory(self):
142
 
        from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
 
322
        from .tests.test_branch import ForeignTestsBranchFactory
143
323
        return ForeignTestsBranchFactory()
144
324
 
145
325
    def make_tags(self, branch):
146
 
        if getattr(branch.repository, "get_refs", None) is not None:
147
 
            from bzrlib.plugins.git.remote import RemoteGitTagDict
 
326
        try:
 
327
            return branch.tags
 
328
        except AttributeError:
 
329
            pass
 
330
        if getattr(branch.repository, "_git", None) is None:
 
331
            from .remote import RemoteGitTagDict
148
332
            return RemoteGitTagDict(branch)
149
333
        else:
150
334
            return LocalGitTagDict(branch)
151
335
 
152
 
 
153
 
class GitReadLock(object):
154
 
 
155
 
    def __init__(self, unlock):
156
 
        self.unlock = unlock
157
 
 
158
 
 
159
 
class GitWriteLock(object):
160
 
 
161
 
    def __init__(self, unlock):
162
 
        self.unlock = unlock
 
336
    def initialize(self, a_controldir, name=None, repository=None,
 
337
                   append_revisions_only=None):
 
338
        raise NotImplementedError(self.initialize)
 
339
 
 
340
    def get_reference(self, controldir, name=None):
 
341
        return controldir.get_branch_reference(name=name)
 
342
 
 
343
    def set_reference(self, controldir, name, target):
 
344
        return controldir.set_branch_reference(target, name)
 
345
 
 
346
    def stores_revno(self):
 
347
        """True if this branch format store revision numbers."""
 
348
        return False
 
349
 
 
350
    supports_reference_locations = False
 
351
 
 
352
 
 
353
class LocalGitBranchFormat(GitBranchFormat):
 
354
 
 
355
    def get_format_description(self):
 
356
        return 'Local Git Branch'
 
357
 
 
358
    @property
 
359
    def _matchingcontroldir(self):
 
360
        from .dir import LocalGitControlDirFormat
 
361
        return LocalGitControlDirFormat()
 
362
 
 
363
    def initialize(self, a_controldir, name=None, repository=None,
 
364
                   append_revisions_only=None):
 
365
        from .dir import LocalGitDir
 
366
        if not isinstance(a_controldir, LocalGitDir):
 
367
            raise errors.IncompatibleFormat(self, a_controldir._format)
 
368
        return a_controldir.create_branch(
 
369
            repository=repository, name=name,
 
370
            append_revisions_only=append_revisions_only)
163
371
 
164
372
 
165
373
class GitBranch(ForeignBranch):
166
374
    """An adapter to git repositories for bzr Branch objects."""
167
375
 
168
 
    def __init__(self, bzrdir, repository, ref, lockfiles, tagsdict=None):
 
376
    @property
 
377
    def control_transport(self):
 
378
        return self._control_transport
 
379
 
 
380
    @property
 
381
    def user_transport(self):
 
382
        return self._user_transport
 
383
 
 
384
    def __init__(self, controldir, repository, ref, format):
169
385
        self.repository = repository
170
 
        self._format = GitBranchFormat()
171
 
        self.control_files = lockfiles
172
 
        self.bzrdir = bzrdir
 
386
        self._format = format
 
387
        self.controldir = controldir
 
388
        self._lock_mode = None
 
389
        self._lock_count = 0
173
390
        super(GitBranch, self).__init__(repository.get_mapping())
174
 
        if tagsdict is not None:
175
 
            self.tags = DictTagDict(self, tagsdict)
176
391
        self.ref = ref
177
 
        self.name = ref_to_branch_name(ref)
178
392
        self._head = None
179
 
        self.base = bzrdir.root_transport.base
 
393
        self._user_transport = controldir.user_transport.clone('.')
 
394
        self._control_transport = controldir.control_transport.clone('.')
 
395
        self._tag_refs = None
 
396
        params = {}
 
397
        try:
 
398
            self.name = ref_to_branch_name(ref)
 
399
        except ValueError:
 
400
            self.name = None
 
401
            if self.ref is not None:
 
402
                params = {"ref": urlutils.escape(self.ref)}
 
403
        else:
 
404
            if self.name != "":
 
405
                params = {"branch": urlutils.escape(self.name)}
 
406
        for k, v in params.items():
 
407
            self._user_transport.set_segment_parameter(k, v)
 
408
            self._control_transport.set_segment_parameter(k, v)
 
409
        self.base = controldir.user_transport.base
180
410
 
181
 
    def _get_checkout_format(self):
 
411
    def _get_checkout_format(self, lightweight=False):
182
412
        """Return the most suitable metadir for a checkout of this branch.
183
413
        Weaves are used if this branch's repository uses weaves.
184
414
        """
185
 
        return bzrdir.format_registry.make_bzrdir("default")
 
415
        if lightweight:
 
416
            return controldir.format_registry.make_controldir("git")
 
417
        else:
 
418
            return controldir.format_registry.make_controldir("default")
186
419
 
187
420
    def get_child_submit_format(self):
188
421
        """Return the preferred format of submissions to this branch."""
189
 
        ret = self.get_config().get_user_option("child_submit_format")
 
422
        ret = self.get_config_stack().get("child_submit_format")
190
423
        if ret is not None:
191
424
            return ret
192
425
        return "git"
193
426
 
 
427
    def get_config(self):
 
428
        return GitBranchConfig(self)
 
429
 
 
430
    def get_config_stack(self):
 
431
        return GitBranchStack(self)
 
432
 
194
433
    def _get_nick(self, local=False, possible_master_transports=None):
195
434
        """Find the nick name for this branch.
196
435
 
197
436
        :return: Branch nick
198
437
        """
199
 
        return self.name or "HEAD"
 
438
        if getattr(self.repository, '_git', None):
 
439
            cs = self.repository._git.get_config_stack()
 
440
            try:
 
441
                return cs.get((b"branch", self.name.encode('utf-8')),
 
442
                              b"nick").decode("utf-8")
 
443
            except KeyError:
 
444
                pass
 
445
        return self.name or u"HEAD"
200
446
 
201
447
    def _set_nick(self, nick):
202
 
        raise NotImplementedError
 
448
        cf = self.repository._git.get_config()
 
449
        cf.set((b"branch", self.name.encode('utf-8')),
 
450
               b"nick", nick.encode("utf-8"))
 
451
        f = BytesIO()
 
452
        cf.write_to_file(f)
 
453
        self.repository._git._put_named_file('config', f.getvalue())
203
454
 
204
455
    nick = property(_get_nick, _set_nick)
205
456
 
206
457
    def __repr__(self):
207
458
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
208
 
            self.ref or "HEAD")
209
 
 
210
 
    def generate_revision_history(self, revid, old_revid=None):
211
 
        # FIXME: Check that old_revid is in the ancestry of revid
212
 
        newhead, self.mapping = self.mapping.revision_id_bzr_to_foreign(revid)
213
 
        self._set_head(newhead)
214
 
 
215
 
    def lock_write(self):
216
 
        self.control_files.lock_write()
217
 
        return GitWriteLock(self.unlock)
 
459
                                 self.name)
 
460
 
 
461
    def generate_revision_history(self, revid, last_rev=None,
 
462
                                  other_branch=None):
 
463
        if last_rev is not None:
 
464
            graph = self.repository.get_graph()
 
465
            if not graph.is_ancestor(last_rev, revid):
 
466
                # our previous tip is not merged into stop_revision
 
467
                raise errors.DivergedBranches(self, other_branch)
 
468
 
 
469
        self.set_last_revision(revid)
 
470
 
 
471
    def lock_write(self, token=None):
 
472
        if token is not None:
 
473
            raise errors.TokenLockingNotSupported(self)
 
474
        if self._lock_mode:
 
475
            if self._lock_mode == 'r':
 
476
                raise errors.ReadOnlyError(self)
 
477
            self._lock_count += 1
 
478
        else:
 
479
            self._lock_ref()
 
480
            self._lock_mode = 'w'
 
481
            self._lock_count = 1
 
482
        self.repository.lock_write()
 
483
        return lock.LogicalLockResult(self.unlock)
 
484
 
 
485
    def leave_lock_in_place(self):
 
486
        raise NotImplementedError(self.leave_lock_in_place)
 
487
 
 
488
    def dont_leave_lock_in_place(self):
 
489
        raise NotImplementedError(self.dont_leave_lock_in_place)
218
490
 
219
491
    def get_stacked_on_url(self):
220
492
        # Git doesn't do stacking (yet...)
221
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
222
 
 
223
 
    def get_parent(self):
 
493
        raise branch.UnstackableBranchFormat(self._format, self.base)
 
494
 
 
495
    def _get_push_origin(self, cs):
 
496
        """Get the name for the push origin.
 
497
 
 
498
        The exact behaviour is documented in the git-config(1) manpage.
 
499
        """
 
500
        try:
 
501
            return cs.get((b'branch', self.name.encode('utf-8')), b'pushRemote')
 
502
        except KeyError:
 
503
            try:
 
504
                return cs.get((b'branch', ), b'remote')
 
505
            except KeyError:
 
506
                try:
 
507
                    return cs.get((b'branch', self.name.encode('utf-8')), b'remote')
 
508
                except KeyError:
 
509
                    return b'origin'
 
510
 
 
511
    def _get_origin(self, cs):
 
512
        try:
 
513
            return cs.get((b'branch', self.name.encode('utf-8')), b'remote')
 
514
        except KeyError:
 
515
            return b'origin'
 
516
 
 
517
    def _get_related_push_branch(self, cs):
 
518
        remote = self._get_push_origin(cs)
 
519
        try:
 
520
            location = cs.get((b"remote", remote), b"url")
 
521
        except KeyError:
 
522
            return None
 
523
 
 
524
        return git_url_to_bzr_url(location.decode('utf-8'), ref=self.ref)
 
525
 
 
526
    def _get_related_merge_branch(self, cs):
 
527
        remote = self._get_origin(cs)
 
528
        try:
 
529
            location = cs.get((b"remote", remote), b"url")
 
530
        except KeyError:
 
531
            return None
 
532
 
 
533
        try:
 
534
            ref = cs.get((b"branch", remote), b"merge")
 
535
        except KeyError:
 
536
            ref = self.ref
 
537
 
 
538
        return git_url_to_bzr_url(location.decode('utf-8'), ref=ref)
 
539
 
 
540
    def _get_parent_location(self):
224
541
        """See Branch.get_parent()."""
225
 
        # FIXME: Set "origin" url from .git/config ?
226
 
        return None
227
 
 
228
 
    def set_parent(self, url):
229
 
        # FIXME: Set "origin" url in .git/config ?
230
 
        pass
 
542
        cs = self.repository._git.get_config_stack()
 
543
        return self._get_related_merge_branch(cs)
 
544
 
 
545
    def _write_git_config(self, cs):
 
546
        f = BytesIO()
 
547
        cs.write_to_file(f)
 
548
        self.repository._git._put_named_file('config', f.getvalue())
 
549
 
 
550
    def set_parent(self, location):
 
551
        cs = self.repository._git.get_config()
 
552
        remote = self._get_origin(cs)
 
553
        this_url = urlutils.strip_segment_parameters(self.user_url)
 
554
        target_url, branch, ref = bzr_url_to_git_url(location)
 
555
        location = urlutils.relative_url(this_url, target_url)
 
556
        cs.set((b"remote", remote), b"url", location)
 
557
        if branch:
 
558
            cs.set((b"branch", remote), b"merge", branch_name_to_ref(branch))
 
559
        elif ref:
 
560
            cs.set((b"branch", remote), b"merge", ref)
 
561
        else:
 
562
            # TODO(jelmer): Maybe unset rather than setting to HEAD?
 
563
            cs.set((b"branch", remote), b"merge", b'HEAD')
 
564
        self._write_git_config(cs)
 
565
 
 
566
    def break_lock(self):
 
567
        raise NotImplementedError(self.break_lock)
231
568
 
232
569
    def lock_read(self):
233
 
        self.control_files.lock_read()
234
 
        return GitReadLock(self.unlock)
 
570
        if self._lock_mode:
 
571
            if self._lock_mode not in ('r', 'w'):
 
572
                raise ValueError(self._lock_mode)
 
573
            self._lock_count += 1
 
574
        else:
 
575
            self._lock_mode = 'r'
 
576
            self._lock_count = 1
 
577
        self.repository.lock_read()
 
578
        return lock.LogicalLockResult(self.unlock)
 
579
 
 
580
    def peek_lock_mode(self):
 
581
        return self._lock_mode
235
582
 
236
583
    def is_locked(self):
237
 
        return self.control_files.is_locked()
 
584
        return (self._lock_mode is not None)
 
585
 
 
586
    def _lock_ref(self):
 
587
        pass
 
588
 
 
589
    def _unlock_ref(self):
 
590
        pass
238
591
 
239
592
    def unlock(self):
240
 
        self.control_files.unlock()
 
593
        """See Branch.unlock()."""
 
594
        if self._lock_count == 0:
 
595
            raise errors.LockNotHeld(self)
 
596
        try:
 
597
            self._lock_count -= 1
 
598
            if self._lock_count == 0:
 
599
                if self._lock_mode == 'w':
 
600
                    self._unlock_ref()
 
601
                self._lock_mode = None
 
602
                self._clear_cached_state()
 
603
        finally:
 
604
            self.repository.unlock()
241
605
 
242
606
    def get_physical_lock_status(self):
243
607
        return False
244
608
 
245
 
    @needs_read_lock
246
609
    def last_revision(self):
247
 
        # perhaps should escape this ?
248
 
        if self.head is None:
249
 
            return revision.NULL_REVISION
250
 
        return self.lookup_foreign_revision_id(self.head)
 
610
        with self.lock_read():
 
611
            # perhaps should escape this ?
 
612
            if self.head is None:
 
613
                return revision.NULL_REVISION
 
614
            return self.lookup_foreign_revision_id(self.head)
251
615
 
252
616
    def _basic_push(self, target, overwrite=False, stop_revision=None):
253
617
        return branch.InterBranch.get(self, target)._basic_push(
254
618
            overwrite, stop_revision)
255
619
 
256
620
    def lookup_foreign_revision_id(self, foreign_revid):
257
 
        return self.repository.lookup_foreign_revision_id(foreign_revid,
258
 
            self.mapping)
 
621
        try:
 
622
            return self.repository.lookup_foreign_revision_id(foreign_revid,
 
623
                                                              self.mapping)
 
624
        except KeyError:
 
625
            # Let's try..
 
626
            return self.mapping.revision_id_foreign_to_bzr(foreign_revid)
259
627
 
260
628
    def lookup_bzr_revision_id(self, revid):
261
629
        return self.repository.lookup_bzr_revision_id(
262
630
            revid, mapping=self.mapping)
263
631
 
 
632
    def get_unshelver(self, tree):
 
633
        raise errors.StoringUncommittedNotSupported(self)
 
634
 
 
635
    def _clear_cached_state(self):
 
636
        super(GitBranch, self)._clear_cached_state()
 
637
        self._tag_refs = None
 
638
 
 
639
    def _iter_tag_refs(self, refs):
 
640
        """Iterate over the tag refs.
 
641
 
 
642
        :param refs: Refs dictionary (name -> git sha1)
 
643
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
 
644
        """
 
645
        raise NotImplementedError(self._iter_tag_refs)
 
646
 
 
647
    def get_tag_refs(self):
 
648
        with self.lock_read():
 
649
            if self._tag_refs is None:
 
650
                self._tag_refs = list(self._iter_tag_refs())
 
651
            return self._tag_refs
 
652
 
 
653
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
654
                                           lossy=False):
 
655
        """Set the last revision info, importing from another repo if necessary.
 
656
 
 
657
        This is used by the bound branch code to upload a revision to
 
658
        the master branch first before updating the tip of the local branch.
 
659
        Revisions referenced by source's tags are also transferred.
 
660
 
 
661
        :param source: Source branch to optionally fetch from
 
662
        :param revno: Revision number of the new tip
 
663
        :param revid: Revision id of the new tip
 
664
        :param lossy: Whether to discard metadata that can not be
 
665
            natively represented
 
666
        :return: Tuple with the new revision number and revision id
 
667
            (should only be different from the arguments when lossy=True)
 
668
        """
 
669
        push_result = source.push(
 
670
            self, stop_revision=revid, lossy=lossy, _stop_revno=revno)
 
671
        return (push_result.new_revno, push_result.new_revid)
 
672
 
 
673
    def reconcile(self, thorough=True):
 
674
        """Make sure the data stored in this branch is consistent."""
 
675
        from ..reconcile import ReconcileResult
 
676
        # Nothing to do here
 
677
        return ReconcileResult()
 
678
 
264
679
 
265
680
class LocalGitBranch(GitBranch):
266
681
    """A local Git branch."""
267
682
 
268
 
    def __init__(self, bzrdir, repository, name, lockfiles, tagsdict=None):
269
 
        super(LocalGitBranch, self).__init__(bzrdir, repository, name,
270
 
              lockfiles, tagsdict)
271
 
        refs = repository._git.get_refs()
272
 
        if not (name in refs.keys() or "HEAD" in refs.keys()):
273
 
            raise errors.NotBranchError(self.base)
 
683
    def __init__(self, controldir, repository, ref):
 
684
        super(LocalGitBranch, self).__init__(controldir, repository, ref,
 
685
                                             LocalGitBranchFormat())
274
686
 
275
687
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
276
 
        accelerator_tree=None, hardlink=False):
 
688
                        accelerator_tree=None, hardlink=False):
 
689
        t = transport.get_transport(to_location)
 
690
        t.ensure_base()
 
691
        format = self._get_checkout_format(lightweight=lightweight)
 
692
        checkout = format.initialize_on_transport(t)
277
693
        if lightweight:
278
 
            t = transport.get_transport(to_location)
279
 
            t.ensure_base()
280
 
            format = self._get_checkout_format()
281
 
            checkout = format.initialize_on_transport(t)
282
 
            from_branch = branch.BranchReferenceFormat().initialize(checkout,
283
 
                self)
284
 
            tree = checkout.create_workingtree(revision_id,
285
 
                from_branch=from_branch, hardlink=hardlink)
286
 
            return tree
 
694
            from_branch = checkout.set_branch_reference(target_branch=self)
287
695
        else:
288
 
            return self._create_heavyweight_checkout(to_location, revision_id,
289
 
                hardlink)
290
 
 
291
 
    def _create_heavyweight_checkout(self, to_location, revision_id=None,
292
 
                                     hardlink=False):
293
 
        """Create a new heavyweight checkout of this branch.
294
 
 
295
 
        :param to_location: URL of location to create the new checkout in.
296
 
        :param revision_id: Revision that should be the tip of the checkout.
297
 
        :param hardlink: Whether to hardlink
298
 
        :return: WorkingTree object of checkout.
299
 
        """
300
 
        checkout_branch = bzrdir.BzrDir.create_branch_convenience(
301
 
            to_location, force_new_tree=False)
302
 
        checkout = checkout_branch.bzrdir
303
 
        checkout_branch.bind(self)
304
 
        # pull up to the specified revision_id to set the initial
305
 
        # branch tip correctly, and seed it with history.
306
 
        checkout_branch.pull(self, stop_revision=revision_id)
307
 
        return checkout.create_workingtree(revision_id, hardlink=hardlink)
 
696
            policy = checkout.determine_repository_policy()
 
697
            policy.acquire_repository()
 
698
            checkout_branch = checkout.create_branch()
 
699
            checkout_branch.bind(self)
 
700
            checkout_branch.pull(self, stop_revision=revision_id)
 
701
            from_branch = None
 
702
        return checkout.create_workingtree(
 
703
            revision_id, from_branch=from_branch, hardlink=hardlink)
 
704
 
 
705
    def _lock_ref(self):
 
706
        self._ref_lock = self.repository._git.refs.lock_ref(self.ref)
 
707
 
 
708
    def _unlock_ref(self):
 
709
        self._ref_lock.unlock()
 
710
 
 
711
    def break_lock(self):
 
712
        self.repository._git.refs.unlock_ref(self.ref)
308
713
 
309
714
    def _gen_revision_history(self):
310
715
        if self.head is None:
311
716
            return []
312
 
        ret = list(self.repository.iter_reverse_revision_history(
313
 
            self.last_revision()))
 
717
        last_revid = self.last_revision()
 
718
        graph = self.repository.get_graph()
 
719
        try:
 
720
            ret = list(graph.iter_lefthand_ancestry(
 
721
                last_revid, (revision.NULL_REVISION, )))
 
722
        except errors.RevisionNotPresent as e:
 
723
            raise errors.GhostRevisionsHaveNoRevno(last_revid, e.revision_id)
314
724
        ret.reverse()
315
725
        return ret
316
726
 
317
727
    def _get_head(self):
318
728
        try:
319
 
            return self.repository._git.ref(self.ref or "HEAD")
 
729
            return self.repository._git.refs[self.ref]
320
730
        except KeyError:
321
731
            return None
322
732
 
323
 
    def set_last_revision_info(self, revno, revid):
324
 
        self.set_last_revision(revid)
 
733
    def _read_last_revision_info(self):
 
734
        last_revid = self.last_revision()
 
735
        graph = self.repository.get_graph()
 
736
        try:
 
737
            revno = graph.find_distance_to_null(
 
738
                last_revid, [(revision.NULL_REVISION, 0)])
 
739
        except errors.GhostRevisionsHaveNoRevno:
 
740
            revno = None
 
741
        return revno, last_revid
 
742
 
 
743
    def set_last_revision_info(self, revno, revision_id):
 
744
        self.set_last_revision(revision_id)
 
745
        self._last_revision_info_cache = revno, revision_id
325
746
 
326
747
    def set_last_revision(self, revid):
327
 
        (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
328
 
        self.head = newhead
 
748
        if not revid or not isinstance(revid, bytes):
 
749
            raise errors.InvalidRevisionId(revision_id=revid, branch=self)
 
750
        if revid == NULL_REVISION:
 
751
            newhead = None
 
752
        else:
 
753
            (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(
 
754
                revid)
 
755
            if self.mapping is None:
 
756
                raise AssertionError
 
757
        self._set_head(newhead)
329
758
 
330
759
    def _set_head(self, value):
 
760
        if value == ZERO_SHA:
 
761
            raise ValueError(value)
331
762
        self._head = value
332
 
        self.repository._git.refs[self.ref or "HEAD"] = self._head
 
763
        if value is None:
 
764
            del self.repository._git.refs[self.ref]
 
765
        else:
 
766
            self.repository._git.refs[self.ref] = self._head
333
767
        self._clear_cached_state()
334
768
 
335
769
    head = property(_get_head, _set_head)
336
770
 
337
 
    def get_config(self):
338
 
        return GitBranchConfig(self)
339
 
 
340
771
    def get_push_location(self):
341
772
        """See Branch.get_push_location."""
342
 
        push_loc = self.get_config().get_user_option('push_location')
343
 
        return push_loc
 
773
        push_loc = self.get_config_stack().get('push_location')
 
774
        if push_loc is not None:
 
775
            return push_loc
 
776
        cs = self.repository._git.get_config_stack()
 
777
        return self._get_related_push_branch(cs)
344
778
 
345
779
    def set_push_location(self, location):
346
780
        """See Branch.set_push_location."""
350
784
    def supports_tags(self):
351
785
        return True
352
786
 
 
787
    def store_uncommitted(self, creator):
 
788
        raise errors.StoringUncommittedNotSupported(self)
 
789
 
 
790
    def _iter_tag_refs(self):
 
791
        """Iterate over the tag refs.
 
792
 
 
793
        :param refs: Refs dictionary (name -> git sha1)
 
794
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
 
795
        """
 
796
        refs = self.repository.controldir.get_refs_container()
 
797
        for ref_name, unpeeled in refs.as_dict().items():
 
798
            try:
 
799
                tag_name = ref_to_tag_name(ref_name)
 
800
            except (ValueError, UnicodeDecodeError):
 
801
                continue
 
802
            peeled = refs.get_peeled(ref_name)
 
803
            if peeled is None:
 
804
                peeled = unpeeled
 
805
            if not isinstance(tag_name, str):
 
806
                raise TypeError(tag_name)
 
807
            yield (ref_name, tag_name, peeled, unpeeled)
 
808
 
 
809
    def create_memorytree(self):
 
810
        from .memorytree import GitMemoryTree
 
811
        return GitMemoryTree(self, self.repository._git.object_store,
 
812
                             self.head)
 
813
 
 
814
 
 
815
def _quick_lookup_revno(local_branch, remote_branch, revid):
 
816
    if not isinstance(revid, bytes):
 
817
        raise TypeError(revid)
 
818
    # Try in source branch first, it'll be faster
 
819
    with local_branch.lock_read():
 
820
        if not _calculate_revnos(local_branch):
 
821
            return None
 
822
        try:
 
823
            return local_branch.revision_id_to_revno(revid)
 
824
        except errors.NoSuchRevision:
 
825
            graph = local_branch.repository.get_graph()
 
826
            try:
 
827
                return graph.find_distance_to_null(
 
828
                    revid, [(revision.NULL_REVISION, 0)])
 
829
            except errors.GhostRevisionsHaveNoRevno:
 
830
                if not _calculate_revnos(remote_branch):
 
831
                    return None
 
832
                # FIXME: Check using graph.find_distance_to_null() ?
 
833
                with remote_branch.lock_read():
 
834
                    return remote_branch.revision_id_to_revno(revid)
 
835
 
353
836
 
354
837
class GitBranchPullResult(branch.PullResult):
355
838
 
365
848
                to_file.write('No revisions to pull.\n')
366
849
            elif self.new_git_head is not None:
367
850
                to_file.write('Now on revision %d (git sha: %s).\n' %
368
 
                        (self.new_revno, self.new_git_head))
 
851
                              (self.new_revno, self.new_git_head))
369
852
            else:
370
853
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
371
854
        self._show_tag_conficts(to_file)
372
855
 
373
856
    def _lookup_revno(self, revid):
374
 
        assert isinstance(revid, str), "was %r" % revid
375
 
        # Try in source branch first, it'll be faster
376
 
        try:
377
 
            return self.source_branch.revision_id_to_revno(revid)
378
 
        except errors.NoSuchRevision:
379
 
            # FIXME: Check using graph.find_distance_to_null() ?
380
 
            return self.target_branch.revision_id_to_revno(revid)
 
857
        return _quick_lookup_revno(self.target_branch, self.source_branch,
 
858
                                   revid)
381
859
 
382
860
    def _get_old_revno(self):
383
861
        if self._old_revno is not None:
403
881
class GitBranchPushResult(branch.BranchPushResult):
404
882
 
405
883
    def _lookup_revno(self, revid):
406
 
        assert isinstance(revid, str), "was %r" % revid
407
 
        # Try in source branch first, it'll be faster
408
 
        try:
409
 
            return self.source_branch.revision_id_to_revno(revid)
410
 
        except errors.NoSuchRevision:
411
 
            # FIXME: Check using graph.find_distance_to_null() ?
412
 
            return self.target_branch.revision_id_to_revno(revid)
 
884
        return _quick_lookup_revno(self.source_branch, self.target_branch,
 
885
                                   revid)
413
886
 
414
887
    @property
415
888
    def old_revno(self):
417
890
 
418
891
    @property
419
892
    def new_revno(self):
 
893
        new_original_revno = getattr(self, "new_original_revno", None)
 
894
        if new_original_revno:
 
895
            return new_original_revno
 
896
        if getattr(self, "new_original_revid", None) is not None:
 
897
            return self._lookup_revno(self.new_original_revid)
420
898
        return self._lookup_revno(self.new_revid)
421
899
 
422
900
 
425
903
 
426
904
    @staticmethod
427
905
    def _get_branch_formats_to_test():
428
 
        return []
 
906
        try:
 
907
            default_format = branch.format_registry.get_default()
 
908
        except AttributeError:
 
909
            default_format = branch.BranchFormat._default_format
 
910
        from .remote import RemoteGitBranchFormat
 
911
        return [
 
912
            (RemoteGitBranchFormat(), default_format),
 
913
            (LocalGitBranchFormat(), default_format)]
429
914
 
430
915
    @classmethod
431
916
    def _get_interrepo(self, source, target):
432
 
        return repository.InterRepository.get(source.repository,
433
 
            target.repository)
 
917
        return _mod_repository.InterRepository.get(
 
918
            source.repository, target.repository)
434
919
 
435
920
    @classmethod
436
921
    def is_compatible(cls, source, target):
437
 
        return (isinstance(source, GitBranch) and
438
 
                not isinstance(target, GitBranch) and
439
 
                (getattr(cls._get_interrepo(source, target), "fetch_objects", None) is not None))
440
 
 
441
 
    def _update_revisions(self, stop_revision=None, overwrite=False,
442
 
        graph=None, limit=None):
443
 
        """Like InterBranch.update_revisions(), but with additions.
444
 
 
445
 
        Compared to the `update_revisions()` below, this function takes a
446
 
        `limit` argument that limits how many git commits will be converted
447
 
        and returns the new git head.
448
 
        """
 
922
        if not isinstance(source, GitBranch):
 
923
            return False
 
924
        if isinstance(target, GitBranch):
 
925
            # InterLocalGitRemoteGitBranch or InterToGitBranch should be used
 
926
            return False
 
927
        if (getattr(cls._get_interrepo(source, target), "fetch_objects", None)
 
928
                is None):
 
929
            # fetch_objects is necessary for this to work
 
930
            return False
 
931
        return True
 
932
 
 
933
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None, lossy=False):
 
934
        self.fetch_objects(
 
935
            stop_revision, fetch_tags=fetch_tags, limit=limit, lossy=lossy)
 
936
        return _mod_repository.FetchResult()
 
937
 
 
938
    def fetch_objects(self, stop_revision, fetch_tags, limit=None, lossy=False):
449
939
        interrepo = self._get_interrepo(self.source, self.target)
 
940
        if fetch_tags is None:
 
941
            c = self.source.get_config_stack()
 
942
            fetch_tags = c.get('branch.fetch_tags')
 
943
 
450
944
        def determine_wants(heads):
451
 
            if self.source.ref is not None and not self.source.ref in heads:
452
 
                raise NoSuchRef(self.source.ref, heads.keys())
453
 
            if stop_revision is not None:
 
945
            if stop_revision is None:
 
946
                try:
 
947
                    head = heads[self.source.ref]
 
948
                except KeyError:
 
949
                    self._last_revid = revision.NULL_REVISION
 
950
                else:
 
951
                    self._last_revid = self.source.lookup_foreign_revision_id(
 
952
                        head)
 
953
            else:
454
954
                self._last_revid = stop_revision
455
 
                head, mapping = self.source.repository.lookup_bzr_revision_id(
456
 
                    stop_revision)
457
 
            else:
458
 
                if self.source.ref is not None:
459
 
                    head = heads[self.source.ref]
460
 
                else:
461
 
                    head = heads["HEAD"]
462
 
                self._last_revid = self.source.lookup_foreign_revision_id(head)
463
 
            if self.target.repository.has_revision(self._last_revid):
464
 
                return []
465
 
            return [head]
 
955
            real = interrepo.get_determine_wants_revids(
 
956
                [self._last_revid], include_tags=fetch_tags)
 
957
            return real(heads)
466
958
        pack_hint, head, refs = interrepo.fetch_objects(
467
 
            determine_wants, self.source.mapping, limit=limit)
 
959
            determine_wants, self.source.mapping, limit=limit,
 
960
            lossy=lossy)
468
961
        if (pack_hint is not None and
469
 
            self.target.repository._format.pack_compresses):
 
962
                self.target.repository._format.pack_compresses):
470
963
            self.target.repository.pack(hint=pack_hint)
471
 
        if head is not None:
472
 
            self._last_revid = self.source.lookup_foreign_revision_id(head)
 
964
        return head, refs
 
965
 
 
966
    def _update_revisions(self, stop_revision=None, overwrite=False):
 
967
        head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
473
968
        if overwrite:
474
969
            prev_last_revid = None
475
970
        else:
476
971
            prev_last_revid = self.target.last_revision()
477
 
        self.target.generate_revision_history(self._last_revid,
478
 
            prev_last_revid)
479
 
        return head
480
 
 
481
 
    def update_revisions(self, stop_revision=None, overwrite=False,
482
 
                         graph=None):
483
 
        """See InterBranch.update_revisions()."""
484
 
        self._update_revisions(stop_revision, overwrite, graph)
485
 
 
486
 
    def pull(self, overwrite=False, stop_revision=None,
487
 
             possible_transports=None, _hook_master=None, run_hooks=True,
488
 
             _override_hook_target=None, local=False, limit=None):
489
 
        """See Branch.pull.
490
 
 
491
 
        :param _hook_master: Private parameter - set the branch to
492
 
            be supplied as the master to pull hooks.
493
 
        :param run_hooks: Private parameter - if false, this branch
494
 
            is being called because it's the master of the primary branch,
495
 
            so it should not run its hooks.
496
 
        :param _override_hook_target: Private parameter - set the branch to be
497
 
            supplied as the target_branch to pull hooks.
498
 
        :param limit: Only import this many revisons.  `None`, the default,
499
 
            means import all revisions.
500
 
        """
501
 
        # This type of branch can't be bound.
502
 
        if local:
503
 
            raise errors.LocalRequiresBoundBranch()
 
972
        self.target.generate_revision_history(
 
973
            self._last_revid, last_rev=prev_last_revid,
 
974
            other_branch=self.source)
 
975
        return head, refs
 
976
 
 
977
    def update_references(self, revid=None):
 
978
        if revid is None:
 
979
            revid = self.target.last_revision()
 
980
        tree = self.target.repository.revision_tree(revid)
 
981
        try:
 
982
            with tree.get_file('.gitmodules') as f:
 
983
                for path, url, section in parse_submodules(
 
984
                        GitConfigFile.from_file(f)):
 
985
                    self.target.set_reference_info(
 
986
                        tree.path2id(path.decode('utf-8')), url.decode('utf-8'),
 
987
                        path.decode('utf-8'))
 
988
        except errors.NoSuchFile:
 
989
            pass
 
990
 
 
991
    def _basic_pull(self, stop_revision, overwrite, run_hooks,
 
992
                    _override_hook_target, _hook_master):
 
993
        if overwrite is True:
 
994
            overwrite = set(["history", "tags"])
 
995
        elif not overwrite:
 
996
            overwrite = set()
504
997
        result = GitBranchPullResult()
505
998
        result.source_branch = self.source
506
999
        if _override_hook_target is None:
507
1000
            result.target_branch = self.target
508
1001
        else:
509
1002
            result.target_branch = _override_hook_target
510
 
        self.source.lock_read()
511
 
        try:
 
1003
        with self.target.lock_write(), self.source.lock_read():
512
1004
            # We assume that during 'pull' the target repository is closer than
513
1005
            # the source one.
514
 
            graph = self.target.repository.get_graph(self.source.repository)
515
1006
            (result.old_revno, result.old_revid) = \
516
1007
                self.target.last_revision_info()
517
 
            result.new_git_head = self._update_revisions(
518
 
                stop_revision, overwrite=overwrite, graph=graph, limit=limit)
519
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
520
 
                overwrite)
 
1008
            result.new_git_head, remote_refs = self._update_revisions(
 
1009
                stop_revision, overwrite=("history" in overwrite))
 
1010
            tags_ret = self.source.tags.merge_to(
 
1011
                self.target.tags, ("tags" in overwrite), ignore_master=True)
 
1012
            if isinstance(tags_ret, tuple):
 
1013
                result.tag_updates, result.tag_conflicts = tags_ret
 
1014
            else:
 
1015
                result.tag_conflicts = tags_ret
521
1016
            (result.new_revno, result.new_revid) = \
522
1017
                self.target.last_revision_info()
 
1018
            self.update_references(revid=result.new_revid)
523
1019
            if _hook_master:
524
1020
                result.master_branch = _hook_master
525
1021
                result.local_branch = result.target_branch
529
1025
            if run_hooks:
530
1026
                for hook in branch.Branch.hooks['post_pull']:
531
1027
                    hook(result)
532
 
        finally:
533
 
            self.source.unlock()
534
 
        return result
535
 
 
536
 
    def _basic_push(self, overwrite=False, stop_revision=None):
 
1028
            return result
 
1029
 
 
1030
    def pull(self, overwrite=False, stop_revision=None,
 
1031
             possible_transports=None, _hook_master=None, run_hooks=True,
 
1032
             _override_hook_target=None, local=False):
 
1033
        """See Branch.pull.
 
1034
 
 
1035
        :param _hook_master: Private parameter - set the branch to
 
1036
            be supplied as the master to pull hooks.
 
1037
        :param run_hooks: Private parameter - if false, this branch
 
1038
            is being called because it's the master of the primary branch,
 
1039
            so it should not run its hooks.
 
1040
        :param _override_hook_target: Private parameter - set the branch to be
 
1041
            supplied as the target_branch to pull hooks.
 
1042
        """
 
1043
        # This type of branch can't be bound.
 
1044
        bound_location = self.target.get_bound_location()
 
1045
        if local and not bound_location:
 
1046
            raise errors.LocalRequiresBoundBranch()
 
1047
        source_is_master = False
 
1048
        with contextlib.ExitStack() as es:
 
1049
            es.enter_context(self.source.lock_read())
 
1050
            if bound_location:
 
1051
                # bound_location comes from a config file, some care has to be
 
1052
                # taken to relate it to source.user_url
 
1053
                normalized = urlutils.normalize_url(bound_location)
 
1054
                try:
 
1055
                    relpath = self.source.user_transport.relpath(normalized)
 
1056
                    source_is_master = (relpath == '')
 
1057
                except (errors.PathNotChild, urlutils.InvalidURL):
 
1058
                    source_is_master = False
 
1059
            if not local and bound_location and not source_is_master:
 
1060
                # not pulling from master, so we need to update master.
 
1061
                master_branch = self.target.get_master_branch(possible_transports)
 
1062
                es.enter_context(master_branch.lock_write())
 
1063
                # pull from source into master.
 
1064
                master_branch.pull(self.source, overwrite, stop_revision,
 
1065
                                   run_hooks=False)
 
1066
            else:
 
1067
                master_branch = None
 
1068
            return self._basic_pull(stop_revision, overwrite, run_hooks,
 
1069
                                    _override_hook_target,
 
1070
                                    _hook_master=master_branch)
 
1071
 
 
1072
    def _basic_push(self, overwrite, stop_revision):
 
1073
        if overwrite is True:
 
1074
            overwrite = set(["history", "tags"])
 
1075
        elif not overwrite:
 
1076
            overwrite = set()
537
1077
        result = branch.BranchPushResult()
538
1078
        result.source_branch = self.source
539
1079
        result.target_branch = self.target
540
 
        graph = self.target.repository.get_graph(self.source.repository)
541
1080
        result.old_revno, result.old_revid = self.target.last_revision_info()
542
 
        result.new_git_head = self._update_revisions(
543
 
            stop_revision, overwrite=overwrite, graph=graph)
544
 
        result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
545
 
            overwrite)
 
1081
        result.new_git_head, remote_refs = self._update_revisions(
 
1082
            stop_revision, overwrite=("history" in overwrite))
 
1083
        tags_ret = self.source.tags.merge_to(
 
1084
            self.target.tags, "tags" in overwrite, ignore_master=True)
 
1085
        (result.tag_updates, result.tag_conflicts) = tags_ret
546
1086
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
1087
        self.update_references(revid=result.new_revid)
547
1088
        return result
548
1089
 
549
1090
 
550
1091
class InterGitBranch(branch.GenericInterBranch):
551
1092
    """InterBranch implementation that pulls between Git branches."""
552
1093
 
553
 
 
554
 
class InterGitLocalRemoteBranch(InterGitBranch):
 
1094
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None, lossy=False):
 
1095
        raise NotImplementedError(self.fetch)
 
1096
 
 
1097
 
 
1098
class InterLocalGitRemoteGitBranch(InterGitBranch):
555
1099
    """InterBranch that copies from a local to a remote git branch."""
556
1100
 
557
1101
    @staticmethod
558
1102
    def _get_branch_formats_to_test():
559
 
        return []
 
1103
        from .remote import RemoteGitBranchFormat
 
1104
        return [
 
1105
            (LocalGitBranchFormat(), RemoteGitBranchFormat())]
560
1106
 
561
1107
    @classmethod
562
1108
    def is_compatible(self, source, target):
563
 
        from bzrlib.plugins.git.remote import RemoteGitBranch
 
1109
        from .remote import RemoteGitBranch
564
1110
        return (isinstance(source, LocalGitBranch) and
565
1111
                isinstance(target, RemoteGitBranch))
566
1112
 
567
 
    def _basic_push(self, overwrite=False, stop_revision=None):
568
 
        from dulwich.protocol import ZERO_SHA
 
1113
    def _basic_push(self, overwrite, stop_revision):
569
1114
        result = GitBranchPushResult()
570
1115
        result.source_branch = self.source
571
1116
        result.target_branch = self.target
572
1117
        if stop_revision is None:
573
1118
            stop_revision = self.source.last_revision()
574
 
        # FIXME: Check for diverged branches
 
1119
 
575
1120
        def get_changed_refs(old_refs):
576
 
            result.old_revid = self.target.lookup_foreign_revision_id(old_refs.get(self.target.ref, ZERO_SHA))
577
 
            refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
 
1121
            old_ref = old_refs.get(self.target.ref, None)
 
1122
            if old_ref is None:
 
1123
                result.old_revid = revision.NULL_REVISION
 
1124
            else:
 
1125
                result.old_revid = self.target.lookup_foreign_revision_id(
 
1126
                    old_ref)
 
1127
            new_ref = self.source.repository.lookup_bzr_revision_id(
 
1128
                stop_revision)[0]
 
1129
            if not overwrite:
 
1130
                if remote_divergence(
 
1131
                        old_ref, new_ref,
 
1132
                        self.source.repository._git.object_store):
 
1133
                    raise errors.DivergedBranches(self.source, self.target)
 
1134
            refs = {self.target.ref: new_ref}
578
1135
            result.new_revid = stop_revision
579
 
            for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
 
1136
            for name, sha in (
 
1137
                    self.source.repository._git.refs.as_dict(b"refs/tags").items()):
 
1138
                if sha not in self.source.repository._git:
 
1139
                    trace.mutter('Ignoring missing SHA: %s', sha)
 
1140
                    continue
580
1141
                refs[tag_name_to_ref(name)] = sha
581
1142
            return refs
582
 
        self.target.repository.send_pack(get_changed_refs,
583
 
            self.source.repository._git.object_store.generate_pack_contents)
 
1143
        self.target.repository.send_pack(
 
1144
            get_changed_refs,
 
1145
            self.source.repository._git.object_store.generate_pack_data)
584
1146
        return result
585
1147
 
586
1148
 
587
 
class InterGitRemoteLocalBranch(InterGitBranch):
 
1149
class InterGitLocalGitBranch(InterGitBranch):
588
1150
    """InterBranch that copies from a remote to a local git branch."""
589
1151
 
590
1152
    @staticmethod
591
1153
    def _get_branch_formats_to_test():
592
 
        return []
 
1154
        from .remote import RemoteGitBranchFormat
 
1155
        return [
 
1156
            (RemoteGitBranchFormat(), LocalGitBranchFormat()),
 
1157
            (LocalGitBranchFormat(), LocalGitBranchFormat())]
593
1158
 
594
1159
    @classmethod
595
1160
    def is_compatible(self, source, target):
596
 
        from bzrlib.plugins.git.remote import RemoteGitBranch
597
 
        return (isinstance(source, RemoteGitBranch) and
 
1161
        return (isinstance(source, GitBranch) and
598
1162
                isinstance(target, LocalGitBranch))
599
1163
 
 
1164
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None, lossy=False):
 
1165
        interrepo = _mod_repository.InterRepository.get(
 
1166
            self.source.repository, self.target.repository)
 
1167
        if stop_revision is None:
 
1168
            stop_revision = self.source.last_revision()
 
1169
        if fetch_tags is None:
 
1170
            c = self.source.get_config_stack()
 
1171
            fetch_tags = c.get('branch.fetch_tags')
 
1172
        determine_wants = interrepo.get_determine_wants_revids(
 
1173
            [stop_revision], include_tags=fetch_tags)
 
1174
        interrepo.fetch_objects(determine_wants, limit=limit, lossy=lossy)
 
1175
        return _mod_repository.FetchResult()
 
1176
 
600
1177
    def _basic_push(self, overwrite=False, stop_revision=None):
601
 
        result = branch.BranchPushResult()
 
1178
        if overwrite is True:
 
1179
            overwrite = set(["history", "tags"])
 
1180
        elif not overwrite:
 
1181
            overwrite = set()
 
1182
        result = GitBranchPushResult()
602
1183
        result.source_branch = self.source
603
1184
        result.target_branch = self.target
604
1185
        result.old_revid = self.target.last_revision()
605
1186
        refs, stop_revision = self.update_refs(stop_revision)
606
 
        self.target.generate_revision_history(stop_revision, result.old_revid)
607
 
        self.update_tags(refs)
 
1187
        self.target.generate_revision_history(
 
1188
            stop_revision,
 
1189
            (result.old_revid if ("history" not in overwrite) else None),
 
1190
            other_branch=self.source)
 
1191
        tags_ret = self.source.tags.merge_to(
 
1192
            self.target.tags,
 
1193
            source_tag_refs=remote_refs_dict_to_tag_refs(refs),
 
1194
            overwrite=("tags" in overwrite))
 
1195
        if isinstance(tags_ret, tuple):
 
1196
            (result.tag_updates, result.tag_conflicts) = tags_ret
 
1197
        else:
 
1198
            result.tag_conflicts = tags_ret
608
1199
        result.new_revid = self.target.last_revision()
609
1200
        return result
610
1201
 
611
 
    def update_tags(self, refs):
612
 
        for name, v in extract_tags(refs).iteritems():
613
 
            revid = self.target.lookup_foreign_revision_id(v)
614
 
            self.target.tags.set_tag(name, revid)
615
 
 
616
1202
    def update_refs(self, stop_revision=None):
617
 
        interrepo = repository.InterRepository.get(self.source.repository,
618
 
            self.target.repository)
 
1203
        interrepo = _mod_repository.InterRepository.get(
 
1204
            self.source.repository, self.target.repository)
 
1205
        c = self.source.get_config_stack()
 
1206
        fetch_tags = c.get('branch.fetch_tags')
 
1207
 
619
1208
        if stop_revision is None:
620
 
            refs = interrepo.fetch(branches=["HEAD"])
621
 
            stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
 
1209
            result = interrepo.fetch(branches=[self.source.ref], include_tags=fetch_tags)
 
1210
            try:
 
1211
                head = result.refs[self.source.ref]
 
1212
            except KeyError:
 
1213
                stop_revision = revision.NULL_REVISION
 
1214
            else:
 
1215
                stop_revision = self.target.lookup_foreign_revision_id(head)
622
1216
        else:
623
 
            refs = interrepo.fetch(revision_id=stop_revision)
624
 
        return refs, stop_revision
 
1217
            result = interrepo.fetch(
 
1218
                revision_id=stop_revision, include_tags=fetch_tags)
 
1219
        return result.refs, stop_revision
625
1220
 
626
1221
    def pull(self, stop_revision=None, overwrite=False,
627
 
        possible_transports=None, run_hooks=True,local=False):
 
1222
             possible_transports=None, run_hooks=True, local=False):
628
1223
        # This type of branch can't be bound.
629
1224
        if local:
630
1225
            raise errors.LocalRequiresBoundBranch()
 
1226
        if overwrite is True:
 
1227
            overwrite = set(["history", "tags"])
 
1228
        elif not overwrite:
 
1229
            overwrite = set()
 
1230
 
631
1231
        result = GitPullResult()
632
1232
        result.source_branch = self.source
633
1233
        result.target_branch = self.target
634
 
        result.old_revid = self.target.last_revision()
635
 
        refs, stop_revision = self.update_refs(stop_revision)
636
 
        self.target.generate_revision_history(stop_revision, result.old_revid)
637
 
        self.update_tags(refs)
638
 
        result.new_revid = self.target.last_revision()
 
1234
        with self.target.lock_write(), self.source.lock_read():
 
1235
            result.old_revid = self.target.last_revision()
 
1236
            refs, stop_revision = self.update_refs(stop_revision)
 
1237
            self.target.generate_revision_history(
 
1238
                stop_revision,
 
1239
                (result.old_revid if ("history" not in overwrite) else None),
 
1240
                other_branch=self.source)
 
1241
            tags_ret = self.source.tags.merge_to(
 
1242
                self.target.tags, overwrite=("tags" in overwrite),
 
1243
                source_tag_refs=remote_refs_dict_to_tag_refs(refs))
 
1244
            if isinstance(tags_ret, tuple):
 
1245
                (result.tag_updates, result.tag_conflicts) = tags_ret
 
1246
            else:
 
1247
                result.tag_conflicts = tags_ret
 
1248
            result.new_revid = self.target.last_revision()
 
1249
            result.local_branch = None
 
1250
            result.master_branch = result.target_branch
 
1251
            if run_hooks:
 
1252
                for hook in branch.Branch.hooks['post_pull']:
 
1253
                    hook(result)
639
1254
        return result
640
1255
 
641
1256
 
642
1257
class InterToGitBranch(branch.GenericInterBranch):
643
 
    """InterBranch implementation that pulls from Git into bzr."""
 
1258
    """InterBranch implementation that pulls into a Git branch."""
644
1259
 
645
1260
    def __init__(self, source, target):
646
1261
        super(InterToGitBranch, self).__init__(source, target)
647
 
        self.interrepo = repository.InterRepository.get(source.repository,
648
 
                                           target.repository)
 
1262
        self.interrepo = _mod_repository.InterRepository.get(source.repository,
 
1263
                                                             target.repository)
649
1264
 
650
1265
    @staticmethod
651
1266
    def _get_branch_formats_to_test():
652
 
        return []
 
1267
        try:
 
1268
            default_format = branch.format_registry.get_default()
 
1269
        except AttributeError:
 
1270
            default_format = branch.BranchFormat._default_format
 
1271
        from .remote import RemoteGitBranchFormat
 
1272
        return [
 
1273
            (default_format, LocalGitBranchFormat()),
 
1274
            (default_format, RemoteGitBranchFormat())]
653
1275
 
654
1276
    @classmethod
655
1277
    def is_compatible(self, source, target):
656
1278
        return (not isinstance(source, GitBranch) and
657
1279
                isinstance(target, GitBranch))
658
1280
 
659
 
    def update_revisions(self, *args, **kwargs):
660
 
        raise NoPushSupport()
661
 
 
662
 
    def _get_new_refs(self, stop_revision=None):
 
1281
    def _get_new_refs(self, stop_revision=None, fetch_tags=None,
 
1282
                      stop_revno=None):
 
1283
        if not self.source.is_locked():
 
1284
            raise errors.ObjectNotLocked(self.source)
663
1285
        if stop_revision is None:
664
 
            stop_revision = self.source.last_revision()
665
 
        assert type(stop_revision) is str
666
 
        main_ref = self.target.ref or "refs/heads/master"
667
 
        refs = { main_ref: (None, stop_revision) }
668
 
        for name, revid in self.source.tags.get_tag_dict().iteritems():
 
1286
            (stop_revno, stop_revision) = self.source.last_revision_info()
 
1287
        elif stop_revno is None:
 
1288
            try:
 
1289
                stop_revno = self.source.revision_id_to_revno(stop_revision)
 
1290
            except errors.NoSuchRevision:
 
1291
                stop_revno = None
 
1292
        if not isinstance(stop_revision, bytes):
 
1293
            raise TypeError(stop_revision)
 
1294
        main_ref = self.target.ref
 
1295
        refs = {main_ref: (None, stop_revision)}
 
1296
        if fetch_tags is None:
 
1297
            c = self.source.get_config_stack()
 
1298
            fetch_tags = c.get('branch.fetch_tags')
 
1299
        for name, revid in self.source.tags.get_tag_dict().items():
669
1300
            if self.source.repository.has_revision(revid):
670
 
                refs[tag_name_to_ref(name)] = (None, revid)
671
 
        return refs, main_ref
 
1301
                ref = tag_name_to_ref(name)
 
1302
                if not check_ref_format(ref):
 
1303
                    warning("skipping tag with invalid characters %s (%s)",
 
1304
                            name, ref)
 
1305
                    continue
 
1306
                if fetch_tags:
 
1307
                    # FIXME: Skip tags that are not in the ancestry
 
1308
                    refs[ref] = (None, revid)
 
1309
        return refs, main_ref, (stop_revno, stop_revision)
 
1310
 
 
1311
    def _update_refs(self, result, old_refs, new_refs, overwrite):
 
1312
        mutter("updating refs. old refs: %r, new refs: %r",
 
1313
               old_refs, new_refs)
 
1314
        result.tag_updates = {}
 
1315
        result.tag_conflicts = []
 
1316
        ret = dict(old_refs)
 
1317
 
 
1318
        def ref_equals(refs, ref, git_sha, revid):
 
1319
            try:
 
1320
                value = refs[ref]
 
1321
            except KeyError:
 
1322
                return False
 
1323
            if (value[0] is not None and
 
1324
                git_sha is not None and
 
1325
                    value[0] == git_sha):
 
1326
                return True
 
1327
            if (value[1] is not None and
 
1328
                revid is not None and
 
1329
                    value[1] == revid):
 
1330
                return True
 
1331
            # FIXME: If one side only has the git sha available and the other
 
1332
            # only has the bzr revid, then this will cause us to show a tag as
 
1333
            # updated that hasn't actually been updated.
 
1334
            return False
 
1335
        # FIXME: Check for diverged branches
 
1336
        for ref, (git_sha, revid) in new_refs.items():
 
1337
            if ref_equals(ret, ref, git_sha, revid):
 
1338
                # Already up to date
 
1339
                if git_sha is None:
 
1340
                    git_sha = old_refs[ref][0]
 
1341
                if revid is None:
 
1342
                    revid = old_refs[ref][1]
 
1343
                ret[ref] = new_refs[ref] = (git_sha, revid)
 
1344
            elif ref not in ret or overwrite:
 
1345
                try:
 
1346
                    tag_name = ref_to_tag_name(ref)
 
1347
                except ValueError:
 
1348
                    pass
 
1349
                else:
 
1350
                    result.tag_updates[tag_name] = revid
 
1351
                ret[ref] = (git_sha, revid)
 
1352
            else:
 
1353
                # FIXME: Check diverged
 
1354
                diverged = False
 
1355
                if diverged:
 
1356
                    try:
 
1357
                        name = ref_to_tag_name(ref)
 
1358
                    except ValueError:
 
1359
                        pass
 
1360
                    else:
 
1361
                        result.tag_conflicts.append(
 
1362
                            (name, revid, ret[name][1]))
 
1363
                else:
 
1364
                    ret[ref] = (git_sha, revid)
 
1365
        return ret
 
1366
 
 
1367
    def fetch(self, stop_revision=None, fetch_tags=None, lossy=False,
 
1368
              limit=None):
 
1369
        if stop_revision is None:
 
1370
            stop_revision = self.source.last_revision()
 
1371
        ret = []
 
1372
        if fetch_tags:
 
1373
            for k, v in self.source.tags.get_tag_dict().items():
 
1374
                ret.append((None, v))
 
1375
        ret.append((None, stop_revision))
 
1376
        try:
 
1377
            revidmap = self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
 
1378
        except NoPushSupport:
 
1379
            raise errors.NoRoundtrippingSupport(self.source, self.target)
 
1380
        return _mod_repository.FetchResult(revidmap={
 
1381
            old_revid: new_revid
 
1382
            for (old_revid, (new_sha, new_revid)) in revidmap.items()})
672
1383
 
673
1384
    def pull(self, overwrite=False, stop_revision=None, local=False,
674
 
             possible_transports=None):
675
 
        from dulwich.protocol import ZERO_SHA
 
1385
             possible_transports=None, run_hooks=True, _stop_revno=None):
676
1386
        result = GitBranchPullResult()
677
1387
        result.source_branch = self.source
678
1388
        result.target_branch = self.target
679
 
        new_refs, main_ref = self._get_new_refs(stop_revision)
680
 
        def update_refs(old_refs):
681
 
            refs = dict(old_refs)
682
 
            # FIXME: Check for diverged branches
683
 
            refs.update(new_refs)
684
 
            return refs
685
 
        old_refs, new_refs = self.interrepo.fetch_refs(update_refs)
686
 
        result.old_revid = self.target.lookup_foreign_revision_id(
687
 
            old_refs.get(main_ref, ZERO_SHA))
688
 
        result.new_revid = new_refs[main_ref]
689
 
        return result
690
 
 
691
 
    def push(self, overwrite=False, stop_revision=None,
692
 
             _override_hook_source_branch=None):
693
 
        from dulwich.protocol import ZERO_SHA
694
 
        result = GitBranchPushResult()
695
 
        result.source_branch = self.source
696
 
        result.target_branch = self.target
697
 
        new_refs, main_ref = self._get_new_refs(stop_revision)
698
 
        def update_refs(old_refs):
699
 
            refs = dict(old_refs)
700
 
            # FIXME: Check for diverged branches
701
 
            refs.update(new_refs)
702
 
            return refs
703
 
        old_refs, new_refs = self.interrepo.fetch_refs(update_refs)
704
 
        (result.old_revid, old_sha1) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
705
 
        if result.old_revid is None:
706
 
            result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
707
 
        result.new_revid = new_refs[main_ref]
708
 
        return result
709
 
 
710
 
    def lossy_push(self, stop_revision=None):
711
 
        result = GitBranchPushResult()
712
 
        result.source_branch = self.source
713
 
        result.target_branch = self.target
714
 
        new_refs, main_ref = self._get_new_refs(stop_revision)
715
 
        def update_refs(old_refs):
716
 
            refs = dict(old_refs)
717
 
            # FIXME: Check for diverged branches
718
 
            refs.update(new_refs)
719
 
            return refs
720
 
        result.revidmap, old_refs, new_refs = self.interrepo.dfetch_refs(
721
 
            update_refs)
722
 
        result.old_revid = old_refs.get(self.target.ref, (None, NULL_REVISION))[1]
723
 
        result.new_revid = new_refs[main_ref][1]
724
 
        return result
725
 
 
726
 
 
727
 
branch.InterBranch.register_optimiser(InterGitRemoteLocalBranch)
 
1389
        with self.source.lock_read(), self.target.lock_write():
 
1390
            new_refs, main_ref, stop_revinfo = self._get_new_refs(
 
1391
                stop_revision, stop_revno=_stop_revno)
 
1392
 
 
1393
            def update_refs(old_refs):
 
1394
                return self._update_refs(result, old_refs, new_refs, overwrite)
 
1395
            try:
 
1396
                result.revidmap, old_refs, new_refs = (
 
1397
                    self.interrepo.fetch_refs(update_refs, lossy=False))
 
1398
            except NoPushSupport:
 
1399
                raise errors.NoRoundtrippingSupport(self.source, self.target)
 
1400
            (old_sha1, result.old_revid) = old_refs.get(
 
1401
                main_ref, (ZERO_SHA, NULL_REVISION))
 
1402
            if result.old_revid is None:
 
1403
                result.old_revid = self.target.lookup_foreign_revision_id(
 
1404
                    old_sha1)
 
1405
            result.new_revid = new_refs[main_ref][1]
 
1406
            result.local_branch = None
 
1407
            result.master_branch = self.target
 
1408
            if run_hooks:
 
1409
                for hook in branch.Branch.hooks['post_pull']:
 
1410
                    hook(result)
 
1411
        return result
 
1412
 
 
1413
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
1414
             _override_hook_source_branch=None, _stop_revno=None):
 
1415
        result = GitBranchPushResult()
 
1416
        result.source_branch = self.source
 
1417
        result.target_branch = self.target
 
1418
        result.local_branch = None
 
1419
        result.master_branch = result.target_branch
 
1420
        with self.source.lock_read(), self.target.lock_write():
 
1421
            new_refs, main_ref, stop_revinfo = self._get_new_refs(
 
1422
                stop_revision, stop_revno=_stop_revno)
 
1423
 
 
1424
            def update_refs(old_refs):
 
1425
                return self._update_refs(result, old_refs, new_refs, overwrite)
 
1426
            try:
 
1427
                result.revidmap, old_refs, new_refs = (
 
1428
                    self.interrepo.fetch_refs(
 
1429
                        update_refs, lossy=lossy, overwrite=overwrite))
 
1430
            except NoPushSupport:
 
1431
                raise errors.NoRoundtrippingSupport(self.source, self.target)
 
1432
            (old_sha1, result.old_revid) = old_refs.get(
 
1433
                main_ref, (ZERO_SHA, NULL_REVISION))
 
1434
            if lossy or result.old_revid is None:
 
1435
                result.old_revid = self.target.lookup_foreign_revision_id(
 
1436
                    old_sha1)
 
1437
            result.new_revid = new_refs[main_ref][1]
 
1438
            (result.new_original_revno,
 
1439
                result.new_original_revid) = stop_revinfo
 
1440
            for hook in branch.Branch.hooks['post_push']:
 
1441
                hook(result)
 
1442
        return result
 
1443
 
 
1444
 
 
1445
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
728
1446
branch.InterBranch.register_optimiser(InterFromGitBranch)
729
1447
branch.InterBranch.register_optimiser(InterToGitBranch)
730
 
branch.InterBranch.register_optimiser(InterGitLocalRemoteBranch)
 
1448
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)