/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: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

Show diffs side-by-side

added added

removed removed

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