/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 branch.py

  • Committer: Jelmer Vernooij
  • Date: 2018-03-31 19:47:40 UTC
  • mto: (0.200.1910 work)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180331194740-q1lhux2ao2etsblk
Use same logic for interpreting progress reports everywhere.

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