/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-11 04:08:32 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-20181111040832-nsljjynzzwmznf3h
Run autopep8.

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