/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: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2018-11-16 11:31:40 UTC
  • mfrom: (7143.12.3 annotated-tags)
  • Revision ID: breezy.the.bot@gmail.com-20181116113140-618u04763u0dyxnh
Fix fetching of revisions that are referenced by annotated tags.

Merged from https://code.launchpad.net/~jelmer/brz/annotated-tags/+merge/358536

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
 
 
83
class GitPullResult(branch.PullResult):
 
84
    """Result of a pull from a Git branch."""
 
85
 
 
86
    def _lookup_revno(self, revid):
 
87
        if not isinstance(revid, bytes):
 
88
            raise TypeError(revid)
 
89
        # Try in source branch first, it'll be faster
 
90
        with self.target_branch.lock_read():
 
91
            return self.target_branch.revision_id_to_revno(revid)
 
92
 
 
93
    @property
 
94
    def old_revno(self):
 
95
        return self._lookup_revno(self.old_revid)
 
96
 
 
97
    @property
 
98
    def new_revno(self):
 
99
        return self._lookup_revno(self.new_revid)
 
100
 
 
101
 
 
102
class GitTags(tag.BasicTags):
 
103
    """Ref-based tag dictionary."""
 
104
 
 
105
    def __init__(self, branch):
 
106
        self.branch = branch
 
107
        self.repository = branch.repository
 
108
 
 
109
    def _merge_to_remote_git(self, target_repo, source_tag_refs, overwrite=False):
 
110
        updates = {}
 
111
        conflicts = []
 
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(peeled)
 
120
                else:
 
121
                    conflicts.append(
 
122
                        (tag_name,
 
123
                        self.repository.lookup_foreign_revision_id(peeled),
 
124
                        target_repo.lookup_foreign_revision_id(old_refs[ref_name])))
 
125
            return ret
 
126
        target_repo.controldir.send_pack(get_changed_refs, lambda have, want: [])
 
127
        return updates, conflicts
 
128
 
 
129
    def _merge_to_local_git(self, target_repo, source_tag_refs, overwrite=False):
 
130
        conflicts = []
 
131
        updates = {}
 
132
        for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
 
133
            if target_repo._git.refs.get(ref_name) == unpeeled:
 
134
                pass
 
135
            elif overwrite or not ref_name in target_repo._git.refs:
 
136
                target_repo._git.refs[ref_name] = unpeeled or peeled
 
137
                try:
 
138
                    updates[tag_name] = self.repository.lookup_foreign_revision_id(peeled)
 
139
                except KeyError:
 
140
                    trace.warning('%s does not point to a valid object',
 
141
                                  tag_name)
 
142
            else:
 
143
                try:
 
144
                    source_revid = self.repository.lookup_foreign_revision_id(peeled)
 
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')), b"nick", nick.encode("utf-8"))
 
407
        f = BytesIO()
 
408
        cf.write_to_file(f)
 
409
        self.repository._git._put_named_file('config', f.getvalue())
 
410
 
 
411
    nick = property(_get_nick, _set_nick)
 
412
 
 
413
    def __repr__(self):
 
414
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
 
415
            self.name)
 
416
 
 
417
    def generate_revision_history(self, revid, last_rev=None, other_branch=None):
 
418
        if last_rev is not None:
 
419
            graph = self.repository.get_graph()
 
420
            if not graph.is_ancestor(last_rev, revid):
 
421
                # our previous tip is not merged into stop_revision
 
422
                raise errors.DivergedBranches(self, other_branch)
 
423
 
 
424
        self.set_last_revision(revid)
 
425
 
 
426
    def lock_write(self, token=None):
 
427
        if token is not None:
 
428
            raise errors.TokenLockingNotSupported(self)
 
429
        if self._lock_mode:
 
430
            if self._lock_mode == 'r':
 
431
                raise errors.ReadOnlyError(self)
 
432
            self._lock_count += 1
 
433
        else:
 
434
            self._lock_ref()
 
435
            self._lock_mode = 'w'
 
436
            self._lock_count = 1
 
437
        self.repository.lock_write()
 
438
        return lock.LogicalLockResult(self.unlock)
 
439
 
 
440
    def leave_lock_in_place(self):
 
441
        raise NotImplementedError(self.leave_lock_in_place)
 
442
 
 
443
    def dont_leave_lock_in_place(self):
 
444
        raise NotImplementedError(self.dont_leave_lock_in_place)
 
445
 
 
446
    def get_stacked_on_url(self):
 
447
        # Git doesn't do stacking (yet...)
 
448
        raise branch.UnstackableBranchFormat(self._format, self.base)
 
449
 
 
450
    def _get_parent_location(self):
 
451
        """See Branch.get_parent()."""
 
452
        # FIXME: Set "origin" url from .git/config ?
 
453
        cs = self.repository._git.get_config_stack()
 
454
        try:
 
455
            location = cs.get((b"remote", b'origin'), b"url")
 
456
        except KeyError:
 
457
            return None
 
458
 
 
459
        params = {}
 
460
        try:
 
461
            ref = cs.get((b"remote", b"origin"), b"merge")
 
462
        except KeyError:
 
463
            pass
 
464
        else:
 
465
            if ref != b'HEAD':
 
466
                try:
 
467
                    params['branch'] = urlutils.escape(ref_to_branch_name(ref))
 
468
                except ValueError:
 
469
                    params['ref'] = urlutils.quote_from_bytes(ref)
 
470
 
 
471
        url = git_url_to_bzr_url(location.decode('utf-8'))
 
472
        return urlutils.join_segment_parameters(url, params)
 
473
 
 
474
    def set_parent(self, location):
 
475
        # FIXME: Set "origin" url in .git/config ?
 
476
        cs = self.repository._git.get_config()
 
477
        this_url = urlutils.split_segment_parameters(self.user_url)[0]
 
478
        target_url, target_params = urlutils.split_segment_parameters(location)
 
479
        location = urlutils.relative_url(this_url, target_url)
 
480
        cs.set((b"remote", b"origin"), b"url", location)
 
481
        if 'branch' in target_params:
 
482
            cs.set((b"remote", b"origin"), b"merge",
 
483
                   branch_name_to_ref(target_params['branch']))
 
484
        elif 'ref' in target_params:
 
485
            cs.set((b"remote", b"origin"), b"merge",
 
486
                   target_params['ref'])
 
487
        else:
 
488
            # TODO(jelmer): Maybe unset rather than setting to HEAD?
 
489
            cs.set((b"remote", b"origin"), b"merge", 'HEAD')
 
490
        f = BytesIO()
 
491
        cs.write_to_file(f)
 
492
        self.repository._git._put_named_file('config', f.getvalue())
 
493
 
 
494
    def break_lock(self):
 
495
        raise NotImplementedError(self.break_lock)
 
496
 
 
497
    def lock_read(self):
 
498
        if self._lock_mode:
 
499
            if self._lock_mode not in ('r', 'w'):
 
500
                raise ValueError(self._lock_mode)
 
501
            self._lock_count += 1
 
502
        else:
 
503
            self._lock_mode = 'r'
 
504
            self._lock_count = 1
 
505
        self.repository.lock_read()
 
506
        return lock.LogicalLockResult(self.unlock)
 
507
 
 
508
    def peek_lock_mode(self):
 
509
        return self._lock_mode
 
510
 
 
511
    def is_locked(self):
 
512
        return (self._lock_mode is not None)
 
513
 
 
514
    def _lock_ref(self):
 
515
        pass
 
516
 
 
517
    def _unlock_ref(self):
 
518
        pass
 
519
 
 
520
    def unlock(self):
 
521
        """See Branch.unlock()."""
 
522
        if self._lock_count == 0:
 
523
            raise errors.LockNotHeld(self)
 
524
        try:
 
525
            self._lock_count -= 1
 
526
            if self._lock_count == 0:
 
527
                if self._lock_mode == 'w':
 
528
                    self._unlock_ref()
 
529
                self._lock_mode = None
 
530
                self._clear_cached_state()
 
531
        finally:
 
532
            self.repository.unlock()
 
533
 
 
534
    def get_physical_lock_status(self):
 
535
        return False
 
536
 
 
537
    def last_revision(self):
 
538
        with self.lock_read():
 
539
            # perhaps should escape this ?
 
540
            if self.head is None:
 
541
                return revision.NULL_REVISION
 
542
            return self.lookup_foreign_revision_id(self.head)
 
543
 
 
544
    def _basic_push(self, target, overwrite=False, stop_revision=None):
 
545
        return branch.InterBranch.get(self, target)._basic_push(
 
546
            overwrite, stop_revision)
 
547
 
 
548
    def lookup_foreign_revision_id(self, foreign_revid):
 
549
        try:
 
550
            return self.repository.lookup_foreign_revision_id(foreign_revid,
 
551
                self.mapping)
 
552
        except KeyError:
 
553
            # Let's try..
 
554
            return self.mapping.revision_id_foreign_to_bzr(foreign_revid)
 
555
 
 
556
    def lookup_bzr_revision_id(self, revid):
 
557
        return self.repository.lookup_bzr_revision_id(
 
558
            revid, mapping=self.mapping)
 
559
 
 
560
    def get_unshelver(self, tree):
 
561
        raise errors.StoringUncommittedNotSupported(self)
 
562
 
 
563
    def _clear_cached_state(self):
 
564
        super(GitBranch, self)._clear_cached_state()
 
565
        self._tag_refs = None
 
566
 
 
567
    def _iter_tag_refs(self, refs):
 
568
        """Iterate over the tag refs.
 
569
 
 
570
        :param refs: Refs dictionary (name -> git sha1)
 
571
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
 
572
        """
 
573
        raise NotImplementedError(self._iter_tag_refs)
 
574
 
 
575
    def get_tag_refs(self):
 
576
        with self.lock_read():
 
577
            if self._tag_refs is None:
 
578
                self._tag_refs = list(self._iter_tag_refs())
 
579
            return self._tag_refs
 
580
 
 
581
 
 
582
class LocalGitBranch(GitBranch):
 
583
    """A local Git branch."""
 
584
 
 
585
    def __init__(self, controldir, repository, ref):
 
586
        super(LocalGitBranch, self).__init__(controldir, repository, ref,
 
587
                LocalGitBranchFormat())
 
588
 
 
589
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
 
590
        accelerator_tree=None, hardlink=False):
 
591
        t = transport.get_transport(to_location)
 
592
        t.ensure_base()
 
593
        format = self._get_checkout_format(lightweight=lightweight)
 
594
        checkout = format.initialize_on_transport(t)
 
595
        if lightweight:
 
596
            from_branch = checkout.set_branch_reference(target_branch=self)
 
597
        else:
 
598
            policy = checkout.determine_repository_policy()
 
599
            repo = policy.acquire_repository()[0]
 
600
 
 
601
            checkout_branch = checkout.create_branch()
 
602
            checkout_branch.bind(self)
 
603
            checkout_branch.pull(self, stop_revision=revision_id)
 
604
            from_branch = None
 
605
        return checkout.create_workingtree(revision_id,
 
606
                from_branch=from_branch, hardlink=hardlink)
 
607
 
 
608
    def _lock_ref(self):
 
609
        self._ref_lock = self.repository._git.refs.lock_ref(self.ref)
 
610
 
 
611
    def _unlock_ref(self):
 
612
        self._ref_lock.unlock()
 
613
 
 
614
    def break_lock(self):
 
615
        self.repository._git.refs.unlock_ref(self.ref)
 
616
 
 
617
    def fetch(self, from_branch, last_revision=None, limit=None):
 
618
        return branch.InterBranch.get(from_branch, self).fetch(
 
619
            stop_revision=last_revision, limit=limit)
 
620
 
 
621
    def _gen_revision_history(self):
 
622
        if self.head is None:
 
623
            return []
 
624
        last_revid = self.last_revision()
 
625
        graph = self.repository.get_graph()
 
626
        try:
 
627
            ret = list(graph.iter_lefthand_ancestry(last_revid,
 
628
                (revision.NULL_REVISION, )))
 
629
        except errors.RevisionNotPresent as e:
 
630
            raise errors.GhostRevisionsHaveNoRevno(last_revid, e.revision_id)
 
631
        ret.reverse()
 
632
        return ret
 
633
 
 
634
    def _get_head(self):
 
635
        try:
 
636
            return self.repository._git.refs[self.ref]
 
637
        except KeyError:
 
638
            return None
 
639
 
 
640
    def _read_last_revision_info(self):
 
641
        last_revid = self.last_revision()
 
642
        graph = self.repository.get_graph()
 
643
        try:
 
644
            revno = graph.find_distance_to_null(last_revid,
 
645
                [(revision.NULL_REVISION, 0)])
 
646
        except errors.GhostRevisionsHaveNoRevno:
 
647
            revno = None
 
648
        return revno, last_revid
 
649
 
 
650
    def set_last_revision_info(self, revno, revision_id):
 
651
        self.set_last_revision(revision_id)
 
652
        self._last_revision_info_cache = revno, revision_id
 
653
 
 
654
    def set_last_revision(self, revid):
 
655
        if not revid or not isinstance(revid, bytes):
 
656
            raise errors.InvalidRevisionId(revision_id=revid, branch=self)
 
657
        if revid == NULL_REVISION:
 
658
            newhead = None
 
659
        else:
 
660
            (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
 
661
            if self.mapping is None:
 
662
                raise AssertionError
 
663
        self._set_head(newhead)
 
664
 
 
665
    def _set_head(self, value):
 
666
        if value == ZERO_SHA:
 
667
            raise ValueError(value)
 
668
        self._head = value
 
669
        if value is None:
 
670
            del self.repository._git.refs[self.ref]
 
671
        else:
 
672
            self.repository._git.refs[self.ref] = self._head
 
673
        self._clear_cached_state()
 
674
 
 
675
    head = property(_get_head, _set_head)
 
676
 
 
677
    def get_push_location(self):
 
678
        """See Branch.get_push_location."""
 
679
        push_loc = self.get_config_stack().get('push_location')
 
680
        return push_loc
 
681
 
 
682
    def set_push_location(self, location):
 
683
        """See Branch.set_push_location."""
 
684
        self.get_config().set_user_option('push_location', location,
 
685
                                          store=config.STORE_LOCATION)
 
686
 
 
687
    def supports_tags(self):
 
688
        return True
 
689
 
 
690
    def store_uncommitted(self, creator):
 
691
        raise errors.StoringUncommittedNotSupported(self)
 
692
 
 
693
    def _iter_tag_refs(self):
 
694
        """Iterate over the tag refs.
 
695
 
 
696
        :param refs: Refs dictionary (name -> git sha1)
 
697
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
 
698
        """
 
699
        refs = self.repository._git.refs
 
700
        for ref_name, unpeeled in viewitems(refs.as_dict()):
 
701
            try:
 
702
                tag_name = ref_to_tag_name(ref_name)
 
703
            except (ValueError, UnicodeDecodeError):
 
704
                continue
 
705
            peeled = refs.get_peeled(ref_name)
 
706
            if peeled is None:
 
707
                peeled = unpeeled
 
708
            if not isinstance(tag_name, text_type):
 
709
                raise TypeError(tag_name)
 
710
            yield (ref_name, tag_name, peeled, unpeeled)
 
711
 
 
712
    def create_memorytree(self):
 
713
        from .memorytree import GitMemoryTree
 
714
        return GitMemoryTree(self, self.repository._git.object_store, self.head)
 
715
 
 
716
    def reference_parent(self, path, file_id=None, possible_transports=None):
 
717
        """Return the parent branch for a tree-reference file_id
 
718
 
 
719
        :param path: The path of the file_id in the tree
 
720
        :param file_id: Optional file_id of the tree reference
 
721
        :return: A branch associated with the file_id
 
722
        """
 
723
        # FIXME should provide multiple branches, based on config
 
724
        url = urlutils.join(self.user_url, path)
 
725
        return branch.Branch.open(
 
726
                url,
 
727
                possible_transports=possible_transports)
 
728
 
 
729
 
 
730
 
 
731
def _quick_lookup_revno(local_branch, remote_branch, revid):
 
732
    if not isinstance(revid, bytes):
 
733
        raise TypeError(revid)
 
734
    # Try in source branch first, it'll be faster
 
735
    with local_branch.lock_read():
 
736
        try:
 
737
            return local_branch.revision_id_to_revno(revid)
 
738
        except errors.NoSuchRevision:
 
739
            graph = local_branch.repository.get_graph()
 
740
            try:
 
741
                return graph.find_distance_to_null(revid,
 
742
                    [(revision.NULL_REVISION, 0)])
 
743
            except errors.GhostRevisionsHaveNoRevno:
 
744
                # FIXME: Check using graph.find_distance_to_null() ?
 
745
                with remote_branch.lock_read():
 
746
                    return remote_branch.revision_id_to_revno(revid)
 
747
 
 
748
 
 
749
class GitBranchPullResult(branch.PullResult):
 
750
 
 
751
    def __init__(self):
 
752
        super(GitBranchPullResult, self).__init__()
 
753
        self.new_git_head = None
 
754
        self._old_revno = None
 
755
        self._new_revno = None
 
756
 
 
757
    def report(self, to_file):
 
758
        if not is_quiet():
 
759
            if self.old_revid == self.new_revid:
 
760
                to_file.write('No revisions to pull.\n')
 
761
            elif self.new_git_head is not None:
 
762
                to_file.write('Now on revision %d (git sha: %s).\n' %
 
763
                        (self.new_revno, self.new_git_head))
 
764
            else:
 
765
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
 
766
        self._show_tag_conficts(to_file)
 
767
 
 
768
    def _lookup_revno(self, revid):
 
769
        return _quick_lookup_revno(self.target_branch, self.source_branch,
 
770
            revid)
 
771
 
 
772
    def _get_old_revno(self):
 
773
        if self._old_revno is not None:
 
774
            return self._old_revno
 
775
        return self._lookup_revno(self.old_revid)
 
776
 
 
777
    def _set_old_revno(self, revno):
 
778
        self._old_revno = revno
 
779
 
 
780
    old_revno = property(_get_old_revno, _set_old_revno)
 
781
 
 
782
    def _get_new_revno(self):
 
783
        if self._new_revno is not None:
 
784
            return self._new_revno
 
785
        return self._lookup_revno(self.new_revid)
 
786
 
 
787
    def _set_new_revno(self, revno):
 
788
        self._new_revno = revno
 
789
 
 
790
    new_revno = property(_get_new_revno, _set_new_revno)
 
791
 
 
792
 
 
793
class GitBranchPushResult(branch.BranchPushResult):
 
794
 
 
795
    def _lookup_revno(self, revid):
 
796
        return _quick_lookup_revno(self.source_branch, self.target_branch,
 
797
            revid)
 
798
 
 
799
    @property
 
800
    def old_revno(self):
 
801
        return self._lookup_revno(self.old_revid)
 
802
 
 
803
    @property
 
804
    def new_revno(self):
 
805
        new_original_revno = getattr(self, "new_original_revno", None)
 
806
        if new_original_revno:
 
807
            return new_original_revno
 
808
        if getattr(self, "new_original_revid", None) is not None:
 
809
            return self._lookup_revno(self.new_original_revid)
 
810
        return self._lookup_revno(self.new_revid)
 
811
 
 
812
 
 
813
class InterFromGitBranch(branch.GenericInterBranch):
 
814
    """InterBranch implementation that pulls from Git into bzr."""
 
815
 
 
816
    @staticmethod
 
817
    def _get_branch_formats_to_test():
 
818
        try:
 
819
            default_format = branch.format_registry.get_default()
 
820
        except AttributeError:
 
821
            default_format = branch.BranchFormat._default_format
 
822
        from .remote import RemoteGitBranchFormat
 
823
        return [
 
824
            (RemoteGitBranchFormat(), default_format),
 
825
            (LocalGitBranchFormat(), default_format)]
 
826
 
 
827
    @classmethod
 
828
    def _get_interrepo(self, source, target):
 
829
        return _mod_repository.InterRepository.get(source.repository, target.repository)
 
830
 
 
831
    @classmethod
 
832
    def is_compatible(cls, source, target):
 
833
        if not isinstance(source, GitBranch):
 
834
            return False
 
835
        if isinstance(target, GitBranch):
 
836
            # InterLocalGitRemoteGitBranch or InterToGitBranch should be used
 
837
            return False
 
838
        if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
 
839
            # fetch_objects is necessary for this to work
 
840
            return False
 
841
        return True
 
842
 
 
843
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
 
844
        self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
 
845
 
 
846
    def fetch_objects(self, stop_revision, fetch_tags, limit=None):
 
847
        interrepo = self._get_interrepo(self.source, self.target)
 
848
        if fetch_tags is None:
 
849
            c = self.source.get_config_stack()
 
850
            fetch_tags = c.get('branch.fetch_tags')
 
851
        def determine_wants(heads):
 
852
            if stop_revision is None:
 
853
                try:
 
854
                    head = heads[self.source.ref]
 
855
                except KeyError:
 
856
                    self._last_revid = revision.NULL_REVISION
 
857
                else:
 
858
                    self._last_revid = self.source.lookup_foreign_revision_id(head)
 
859
            else:
 
860
                self._last_revid = stop_revision
 
861
            real = interrepo.get_determine_wants_revids(
 
862
                [self._last_revid], include_tags=fetch_tags)
 
863
            return real(heads)
 
864
        pack_hint, head, refs = interrepo.fetch_objects(
 
865
            determine_wants, self.source.mapping, limit=limit)
 
866
        if (pack_hint is not None and
 
867
            self.target.repository._format.pack_compresses):
 
868
            self.target.repository.pack(hint=pack_hint)
 
869
        return head, refs
 
870
 
 
871
    def _update_revisions(self, stop_revision=None, overwrite=False):
 
872
        head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
 
873
        if overwrite:
 
874
            prev_last_revid = None
 
875
        else:
 
876
            prev_last_revid = self.target.last_revision()
 
877
        self.target.generate_revision_history(self._last_revid,
 
878
            last_rev=prev_last_revid, other_branch=self.source)
 
879
        return head, refs
 
880
 
 
881
    def _basic_pull(self, stop_revision, overwrite, run_hooks,
 
882
              _override_hook_target, _hook_master):
 
883
        if overwrite is True:
 
884
            overwrite = set(["history", "tags"])
 
885
        else:
 
886
            overwrite = set()
 
887
        result = GitBranchPullResult()
 
888
        result.source_branch = self.source
 
889
        if _override_hook_target is None:
 
890
            result.target_branch = self.target
 
891
        else:
 
892
            result.target_branch = _override_hook_target
 
893
        with self.target.lock_write(), self.source.lock_read():
 
894
            # We assume that during 'pull' the target repository is closer than
 
895
            # the source one.
 
896
            (result.old_revno, result.old_revid) = \
 
897
                self.target.last_revision_info()
 
898
            result.new_git_head, remote_refs = self._update_revisions(
 
899
                stop_revision, overwrite=("history" in overwrite))
 
900
            tags_ret  = self.source.tags.merge_to(
 
901
                    self.target.tags, ("tags" in overwrite), ignore_master=True)
 
902
            if isinstance(tags_ret, tuple):
 
903
                result.tag_updates, result.tag_conflicts = tags_ret
 
904
            else:
 
905
                result.tag_conflicts = tags_ret
 
906
            (result.new_revno, result.new_revid) = \
 
907
                self.target.last_revision_info()
 
908
            if _hook_master:
 
909
                result.master_branch = _hook_master
 
910
                result.local_branch = result.target_branch
 
911
            else:
 
912
                result.master_branch = result.target_branch
 
913
                result.local_branch = None
 
914
            if run_hooks:
 
915
                for hook in branch.Branch.hooks['post_pull']:
 
916
                    hook(result)
 
917
            return result
 
918
 
 
919
    def pull(self, overwrite=False, stop_revision=None,
 
920
             possible_transports=None, _hook_master=None, run_hooks=True,
 
921
             _override_hook_target=None, local=False):
 
922
        """See Branch.pull.
 
923
 
 
924
        :param _hook_master: Private parameter - set the branch to
 
925
            be supplied as the master to pull hooks.
 
926
        :param run_hooks: Private parameter - if false, this branch
 
927
            is being called because it's the master of the primary branch,
 
928
            so it should not run its hooks.
 
929
        :param _override_hook_target: Private parameter - set the branch to be
 
930
            supplied as the target_branch to pull hooks.
 
931
        """
 
932
        # This type of branch can't be bound.
 
933
        bound_location = self.target.get_bound_location()
 
934
        if local and not bound_location:
 
935
            raise errors.LocalRequiresBoundBranch()
 
936
        master_branch = None
 
937
        source_is_master = False
 
938
        self.source.lock_read()
 
939
        if bound_location:
 
940
            # bound_location comes from a config file, some care has to be
 
941
            # taken to relate it to source.user_url
 
942
            normalized = urlutils.normalize_url(bound_location)
 
943
            try:
 
944
                relpath = self.source.user_transport.relpath(normalized)
 
945
                source_is_master = (relpath == '')
 
946
            except (errors.PathNotChild, urlutils.InvalidURL):
 
947
                source_is_master = False
 
948
        if not local and bound_location and not source_is_master:
 
949
            # not pulling from master, so we need to update master.
 
950
            master_branch = self.target.get_master_branch(possible_transports)
 
951
            master_branch.lock_write()
 
952
        try:
 
953
            try:
 
954
                if master_branch:
 
955
                    # pull from source into master.
 
956
                    master_branch.pull(self.source, overwrite, stop_revision,
 
957
                        run_hooks=False)
 
958
                result = self._basic_pull(stop_revision, overwrite, run_hooks,
 
959
                    _override_hook_target, _hook_master=master_branch)
 
960
            finally:
 
961
                self.source.unlock()
 
962
        finally:
 
963
            if master_branch:
 
964
                master_branch.unlock()
 
965
        return result
 
966
 
 
967
    def _basic_push(self, overwrite, stop_revision):
 
968
        if overwrite is True:
 
969
            overwrite = set(["history", "tags"])
 
970
        else:
 
971
            overwrite = set()
 
972
        result = branch.BranchPushResult()
 
973
        result.source_branch = self.source
 
974
        result.target_branch = self.target
 
975
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
976
        result.new_git_head, remote_refs = self._update_revisions(
 
977
            stop_revision, overwrite=("history" in overwrite))
 
978
        tags_ret = self.source.tags.merge_to(self.target.tags,
 
979
            "tags" in overwrite, ignore_master=True)
 
980
        (result.tag_updates, result.tag_conflicts) = tags_ret
 
981
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
982
        return result
 
983
 
 
984
 
 
985
class InterGitBranch(branch.GenericInterBranch):
 
986
    """InterBranch implementation that pulls between Git branches."""
 
987
 
 
988
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
 
989
        raise NotImplementedError(self.fetch)
 
990
 
 
991
 
 
992
class InterLocalGitRemoteGitBranch(InterGitBranch):
 
993
    """InterBranch that copies from a local to a remote git branch."""
 
994
 
 
995
    @staticmethod
 
996
    def _get_branch_formats_to_test():
 
997
        from .remote import RemoteGitBranchFormat
 
998
        return [
 
999
            (LocalGitBranchFormat(), RemoteGitBranchFormat())]
 
1000
 
 
1001
    @classmethod
 
1002
    def is_compatible(self, source, target):
 
1003
        from .remote import RemoteGitBranch
 
1004
        return (isinstance(source, LocalGitBranch) and
 
1005
                isinstance(target, RemoteGitBranch))
 
1006
 
 
1007
    def _basic_push(self, overwrite, stop_revision):
 
1008
        result = GitBranchPushResult()
 
1009
        result.source_branch = self.source
 
1010
        result.target_branch = self.target
 
1011
        if stop_revision is None:
 
1012
            stop_revision = self.source.last_revision()
 
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(old_ref)
 
1019
            new_ref = self.source.repository.lookup_bzr_revision_id(stop_revision)[0]
 
1020
            if not overwrite:
 
1021
                if remote_divergence(old_ref, new_ref, self.source.repository._git.object_store):
 
1022
                    raise errors.DivergedBranches(self.source, self.target)
 
1023
            refs = { self.target.ref: new_ref }
 
1024
            result.new_revid = stop_revision
 
1025
            for name, sha in viewitems(self.source.repository._git.refs.as_dict(b"refs/tags")):
 
1026
                refs[tag_name_to_ref(name)] = sha
 
1027
            return refs
 
1028
        self.target.repository.send_pack(get_changed_refs,
 
1029
            self.source.repository._git.object_store.generate_pack_data)
 
1030
        return result
 
1031
 
 
1032
 
 
1033
class InterGitLocalGitBranch(InterGitBranch):
 
1034
    """InterBranch that copies from a remote to a local git branch."""
 
1035
 
 
1036
    @staticmethod
 
1037
    def _get_branch_formats_to_test():
 
1038
        from .remote import RemoteGitBranchFormat
 
1039
        return [
 
1040
            (RemoteGitBranchFormat(), LocalGitBranchFormat()),
 
1041
            (LocalGitBranchFormat(), LocalGitBranchFormat())]
 
1042
 
 
1043
    @classmethod
 
1044
    def is_compatible(self, source, target):
 
1045
        return (isinstance(source, GitBranch) and
 
1046
                isinstance(target, LocalGitBranch))
 
1047
 
 
1048
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
 
1049
        interrepo = _mod_repository.InterRepository.get(self.source.repository,
 
1050
            self.target.repository)
 
1051
        if stop_revision is None:
 
1052
            stop_revision = self.source.last_revision()
 
1053
        determine_wants = interrepo.get_determine_wants_revids(
 
1054
            [stop_revision], include_tags=fetch_tags)
 
1055
        interrepo.fetch_objects(determine_wants, limit=limit)
 
1056
 
 
1057
    def _basic_push(self, overwrite=False, stop_revision=None):
 
1058
        if overwrite is True:
 
1059
            overwrite = set(["history", "tags"])
 
1060
        else:
 
1061
            overwrite = set()
 
1062
        result = GitBranchPushResult()
 
1063
        result.source_branch = self.source
 
1064
        result.target_branch = self.target
 
1065
        result.old_revid = self.target.last_revision()
 
1066
        refs, stop_revision = self.update_refs(stop_revision)
 
1067
        self.target.generate_revision_history(stop_revision,
 
1068
                (result.old_revid if ("history" not in overwrite) else None),
 
1069
                other_branch=self.source)
 
1070
        tags_ret = self.source.tags.merge_to(self.target.tags,
 
1071
            source_tag_refs=remote_refs_dict_to_tag_refs(refs),
 
1072
            overwrite=("tags" in overwrite))
 
1073
        if isinstance(tags_ret, tuple):
 
1074
            (result.tag_updates, result.tag_conflicts) = tags_ret
 
1075
        else:
 
1076
            result.tag_conflicts = tags_ret
 
1077
        result.new_revid = self.target.last_revision()
 
1078
        return result
 
1079
 
 
1080
    def update_refs(self, stop_revision=None):
 
1081
        interrepo = _mod_repository.InterRepository.get(
 
1082
                self.source.repository, self.target.repository)
 
1083
        c = self.source.get_config_stack()
 
1084
        fetch_tags = c.get('branch.fetch_tags')
 
1085
 
 
1086
        if stop_revision is None:
 
1087
            refs = interrepo.fetch(branches=[self.source.ref], include_tags=fetch_tags)
 
1088
            try:
 
1089
                head = refs[self.source.ref]
 
1090
            except KeyError:
 
1091
                stop_revision = revision.NULL_REVISION
 
1092
            else:
 
1093
                stop_revision = self.target.lookup_foreign_revision_id(head)
 
1094
        else:
 
1095
            refs = interrepo.fetch(revision_id=stop_revision, include_tags=fetch_tags)
 
1096
        return refs, stop_revision
 
1097
 
 
1098
    def pull(self, stop_revision=None, overwrite=False,
 
1099
             possible_transports=None, run_hooks=True, local=False):
 
1100
        # This type of branch can't be bound.
 
1101
        if local:
 
1102
            raise errors.LocalRequiresBoundBranch()
 
1103
        if overwrite is True:
 
1104
            overwrite = set(["history", "tags"])
 
1105
        else:
 
1106
            overwrite = set()
 
1107
 
 
1108
        result = GitPullResult()
 
1109
        result.source_branch = self.source
 
1110
        result.target_branch = self.target
 
1111
        with self.target.lock_write(), self.source.lock_read():
 
1112
            result.old_revid = self.target.last_revision()
 
1113
            refs, stop_revision = self.update_refs(stop_revision)
 
1114
            self.target.generate_revision_history(stop_revision,
 
1115
                    (result.old_revid if ("history" not in overwrite) else None),
 
1116
                    other_branch=self.source)
 
1117
            tags_ret = self.source.tags.merge_to(self.target.tags,
 
1118
                overwrite=("tags" in overwrite),
 
1119
                source_tag_refs=remote_refs_dict_to_tag_refs(refs))
 
1120
            if isinstance(tags_ret, tuple):
 
1121
                (result.tag_updates, result.tag_conflicts) = tags_ret
 
1122
            else:
 
1123
                result.tag_conflicts = tags_ret
 
1124
            result.new_revid = self.target.last_revision()
 
1125
            result.local_branch = None
 
1126
            result.master_branch = result.target_branch
 
1127
            if run_hooks:
 
1128
                for hook in branch.Branch.hooks['post_pull']:
 
1129
                    hook(result)
 
1130
        return result
 
1131
 
 
1132
 
 
1133
class InterToGitBranch(branch.GenericInterBranch):
 
1134
    """InterBranch implementation that pulls from a non-bzr into a Git branch."""
 
1135
 
 
1136
    def __init__(self, source, target):
 
1137
        super(InterToGitBranch, self).__init__(source, target)
 
1138
        self.interrepo = _mod_repository.InterRepository.get(source.repository,
 
1139
                                           target.repository)
 
1140
 
 
1141
    @staticmethod
 
1142
    def _get_branch_formats_to_test():
 
1143
        try:
 
1144
            default_format = branch.format_registry.get_default()
 
1145
        except AttributeError:
 
1146
            default_format = branch.BranchFormat._default_format
 
1147
        from .remote import RemoteGitBranchFormat
 
1148
        return [
 
1149
            (default_format, LocalGitBranchFormat()),
 
1150
            (default_format, RemoteGitBranchFormat())]
 
1151
 
 
1152
    @classmethod
 
1153
    def is_compatible(self, source, target):
 
1154
        return (not isinstance(source, GitBranch) and
 
1155
                isinstance(target, GitBranch))
 
1156
 
 
1157
    def _get_new_refs(self, stop_revision=None, fetch_tags=None):
 
1158
        if not self.source.is_locked():
 
1159
            raise errors.ObjectNotLocked(self.source)
 
1160
        if stop_revision is None:
 
1161
            (stop_revno, stop_revision) = self.source.last_revision_info()
 
1162
        else:
 
1163
            stop_revno = self.source.revision_id_to_revno(stop_revision)
 
1164
        if not isinstance(stop_revision, bytes):
 
1165
            raise TypeError(stop_revision)
 
1166
        main_ref = self.target.ref
 
1167
        refs = { main_ref: (None, stop_revision) }
 
1168
        if fetch_tags is None:
 
1169
            c = self.source.get_config_stack()
 
1170
            fetch_tags = c.get('branch.fetch_tags')
 
1171
        for name, revid in viewitems(self.source.tags.get_tag_dict()):
 
1172
            if self.source.repository.has_revision(revid):
 
1173
                ref = tag_name_to_ref(name)
 
1174
                if not check_ref_format(ref):
 
1175
                    warning("skipping tag with invalid characters %s (%s)",
 
1176
                        name, ref)
 
1177
                    continue
 
1178
                if fetch_tags:
 
1179
                    # FIXME: Skip tags that are not in the ancestry
 
1180
                    refs[ref] = (None, revid)
 
1181
        return refs, main_ref, (stop_revno, stop_revision)
 
1182
 
 
1183
    def _update_refs(self, result, old_refs, new_refs, overwrite):
 
1184
        mutter("updating refs. old refs: %r, new refs: %r",
 
1185
               old_refs, new_refs)
 
1186
        result.tag_updates = {}
 
1187
        result.tag_conflicts = []
 
1188
        ret = dict(old_refs)
 
1189
        def ref_equals(refs, ref, git_sha, revid):
 
1190
            try:
 
1191
                value = refs[ref]
 
1192
            except KeyError:
 
1193
                return False
 
1194
            if (value[0] is not None and
 
1195
                git_sha is not None and
 
1196
                value[0] == git_sha):
 
1197
                return True
 
1198
            if (value[1] is not None and
 
1199
                revid is not None and
 
1200
                value[1] == revid):
 
1201
                return True
 
1202
            # FIXME: If one side only has the git sha available and the other only
 
1203
            # has the bzr revid, then this will cause us to show a tag as updated
 
1204
            # that hasn't actually been updated.
 
1205
            return False
 
1206
        # FIXME: Check for diverged branches
 
1207
        for ref, (git_sha, revid) in viewitems(new_refs):
 
1208
            if ref_equals(ret, ref, git_sha, revid):
 
1209
                # Already up to date
 
1210
                if git_sha is None:
 
1211
                    git_sha = old_refs[ref][0]
 
1212
                if revid is None:
 
1213
                    revid = old_refs[ref][1]
 
1214
                ret[ref] = new_refs[ref] = (git_sha, revid)
 
1215
            elif ref not in ret or overwrite:
 
1216
                try:
 
1217
                    tag_name = ref_to_tag_name(ref)
 
1218
                except ValueError:
 
1219
                    pass
 
1220
                else:
 
1221
                    result.tag_updates[tag_name] = revid
 
1222
                ret[ref] = (git_sha, revid)
 
1223
            else:
 
1224
                # FIXME: Check diverged
 
1225
                diverged = False
 
1226
                if diverged:
 
1227
                    try:
 
1228
                        name = ref_to_tag_name(ref)
 
1229
                    except ValueError:
 
1230
                        pass
 
1231
                    else:
 
1232
                        result.tag_conflicts.append((name, revid, ret[name][1]))
 
1233
                else:
 
1234
                    ret[ref] = (git_sha, revid)
 
1235
        return ret
 
1236
 
 
1237
    def fetch(self, stop_revision=None, fetch_tags=None, lossy=False, limit=None):
 
1238
        if stop_revision is None:
 
1239
            stop_revision = self.source.last_revision()
 
1240
        ret = []
 
1241
        if fetch_tags:
 
1242
            for k, v in viewitems(self.source.tags.get_tag_dict()):
 
1243
                ret.append((None, v))
 
1244
        ret.append((None, stop_revision))
 
1245
        try:
 
1246
            self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
 
1247
        except NoPushSupport:
 
1248
            raise errors.NoRoundtrippingSupport(self.source, self.target)
 
1249
 
 
1250
    def pull(self, overwrite=False, stop_revision=None, local=False,
 
1251
             possible_transports=None, run_hooks=True):
 
1252
        result = GitBranchPullResult()
 
1253
        result.source_branch = self.source
 
1254
        result.target_branch = self.target
 
1255
        with self.source.lock_read(), self.target.lock_write():
 
1256
            new_refs, main_ref, stop_revinfo = self._get_new_refs(
 
1257
                stop_revision)
 
1258
            def update_refs(old_refs):
 
1259
                return self._update_refs(result, old_refs, new_refs, overwrite)
 
1260
            try:
 
1261
                result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
 
1262
                    update_refs, lossy=False)
 
1263
            except NoPushSupport:
 
1264
                raise errors.NoRoundtrippingSupport(self.source, self.target)
 
1265
            (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
 
1266
            if result.old_revid is None:
 
1267
                result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
 
1268
            result.new_revid = new_refs[main_ref][1]
 
1269
            result.local_branch = None
 
1270
            result.master_branch = self.target
 
1271
            if run_hooks:
 
1272
                for hook in branch.Branch.hooks['post_pull']:
 
1273
                    hook(result)
 
1274
        return result
 
1275
 
 
1276
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
1277
             _override_hook_source_branch=None):
 
1278
        result = GitBranchPushResult()
 
1279
        result.source_branch = self.source
 
1280
        result.target_branch = self.target
 
1281
        result.local_branch = None
 
1282
        result.master_branch = result.target_branch
 
1283
        with self.source.lock_read(), self.target.lock_write():
 
1284
            new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
 
1285
            def update_refs(old_refs):
 
1286
                return self._update_refs(result, old_refs, new_refs, overwrite)
 
1287
            try:
 
1288
                result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
 
1289
                    update_refs, lossy=lossy, overwrite=overwrite)
 
1290
            except NoPushSupport:
 
1291
                raise errors.NoRoundtrippingSupport(self.source, self.target)
 
1292
            (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
 
1293
            if result.old_revid is None:
 
1294
                result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
 
1295
            result.new_revid = new_refs[main_ref][1]
 
1296
            (result.new_original_revno, result.new_original_revid) = stop_revinfo
 
1297
            for hook in branch.Branch.hooks['post_push']:
 
1298
                hook(result)
 
1299
        return result
 
1300
 
 
1301
 
 
1302
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
 
1303
branch.InterBranch.register_optimiser(InterFromGitBranch)
 
1304
branch.InterBranch.register_optimiser(InterToGitBranch)
 
1305
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)