/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-01-19 15:14:16 UTC
  • mto: This revision was merged to the branch mainline in revision 7455.
  • Revision ID: jelmer@jelmer.uk-20200119151416-f2x9y9rtvwxndr2l
Don't show submodules that are not checked out as deltas.

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