/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-07-18 23:14:00 UTC
  • mfrom: (7490.40.62 work)
  • mto: This revision was merged to the branch mainline in revision 7519.
  • Revision ID: jelmer@jelmer.uk-20200718231400-jaes9qltn8oi8xss
Merge lp:brz/3.1.

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