/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: 2018-11-16 11:42:27 UTC
  • mto: (7143.16.20 even-more-cleanups)
  • mto: This revision was merged to the branch mainline in revision 7175.
  • Revision ID: jelmer@jelmer.uk-20181116114227-lwabsodakoymo3ew
Remove flake8 issues now fixed.

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