/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-09 01:27:02 UTC
  • mto: This revision was merged to the branch mainline in revision 7487.
  • Revision ID: jelmer@jelmer.uk-20200209012702-m08y7dqif1p99r97
Return iterators from iter_bytes_as.

Show diffs side-by-side

added added

removed removed

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