/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-04-02 14:59:43 UTC
  • mto: (0.200.1913 work)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@jelmer.uk-20180402145943-s5jmpbvvf1x42pao
Just don't touch the URL if it's already a valid URL.

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