/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.200.1613 by Jelmer Vernooij
Handle encoding better in working tree iter changes.
1
# Copyright (C) 2007,2012 Canonical Ltd
2
# Copyright (C) 2009-2012 Jelmer Vernooij <jelmer@samba.org>
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
18
"""An adapter between a Git Branch and a Bazaar Branch"""
19
0.200.1594 by Jelmer Vernooij
Use absolute_import everywhere.
20
from __future__ import absolute_import
21
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
22
from cStringIO import StringIO
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
23
from collections import defaultdict
24
0.200.261 by Jelmer Vernooij
More formatting fixes.
25
from dulwich.objects import (
0.200.1717 by Jelmer Vernooij
Ignore tags pointing at non-commit objects.
26
    NotCommitError,
0.200.1153 by Jelmer Vernooij
Import ZERO_SHA from dulwich.objects.
27
    ZERO_SHA,
0.200.261 by Jelmer Vernooij
More formatting fixes.
28
    )
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
29
from dulwich.repo import check_ref_format
0.200.261 by Jelmer Vernooij
More formatting fixes.
30
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
31
from ... import (
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
32
    branch,
33
    config,
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
34
    controldir,
0.200.446 by Jelmer Vernooij
Support new 'local' argument.
35
    errors,
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
36
    lock,
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
37
    repository as _mod_repository,
0.200.19 by John Arbash Meinel
More refactoring. Add some direct tests for GitModel.
38
    revision,
0.200.82 by Jelmer Vernooij
Support listing tags.
39
    tag,
0.230.1 by Jelmer Vernooij
Support lightweight checkouts.
40
    transport,
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
41
    urlutils,
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
42
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
43
from ...revision import (
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
44
    NULL_REVISION,
45
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
46
from ...trace import (
0.200.342 by Jelmer Vernooij
Report git sha during pull.
47
    is_quiet,
0.200.261 by Jelmer Vernooij
More formatting fixes.
48
    mutter,
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
49
    warning,
0.200.261 by Jelmer Vernooij
More formatting fixes.
50
    )
51
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
52
from .config import (
0.200.386 by Jelmer Vernooij
Move config to a separate file, support BranchConfig.username().
53
    GitBranchConfig,
0.200.1472 by Jelmer Vernooij
Provide basic implementation of Branch.get_config_stack.
54
    GitBranchStack,
0.200.386 by Jelmer Vernooij
Move config to a separate file, support BranchConfig.username().
55
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
56
from .errors import (
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
57
    NoPushSupport,
0.200.278 by Jelmer Vernooij
Update branch head appropriately during dpull.
58
    NoSuchRef,
59
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
60
from .refs import (
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
61
    is_tag,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
62
    ref_to_branch_name,
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
63
    ref_to_tag_name,
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
64
    tag_name_to_ref,
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
65
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
66
from .unpeel_map import (
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
67
    UnpeelMap,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
68
    )
0.200.261 by Jelmer Vernooij
More formatting fixes.
69
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
70
from ...foreign import ForeignBranch
0.200.388 by Jelmer Vernooij
Support bzr 1.14 as well.
71
0.200.261 by Jelmer Vernooij
More formatting fixes.
72
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
73
class GitPullResult(branch.PullResult):
0.200.956 by Jelmer Vernooij
Add some more format tests.
74
    """Result of a pull from a Git branch."""
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
75
76
    def _lookup_revno(self, revid):
77
        assert isinstance(revid, str), "was %r" % revid
78
        # Try in source branch first, it'll be faster
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
79
        with self.target_branch.lock_read():
0.200.1362 by Jelmer Vernooij
Add locking.
80
            return self.target_branch.revision_id_to_revno(revid)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
81
82
    @property
83
    def old_revno(self):
84
        return self._lookup_revno(self.old_revid)
85
86
    @property
87
    def new_revno(self):
88
        return self._lookup_revno(self.new_revid)
89
90
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
91
class GitTags(tag.BasicTags):
92
    """Ref-based tag dictionary."""
0.200.82 by Jelmer Vernooij
Support listing tags.
93
0.200.89 by Jelmer Vernooij
Support sprouting branches.
94
    def __init__(self, branch):
95
        self.branch = branch
96
        self.repository = branch.repository
0.200.82 by Jelmer Vernooij
Support listing tags.
97
0.200.1487 by Jelmer Vernooij
Use peeling.
98
    def get_refs_container(self):
99
        raise NotImplementedError(self.get_refs_container)
0.200.1066 by Jelmer Vernooij
Add GitTags.get_refs.
100
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
101
    def _iter_tag_refs(self, refs):
0.200.1487 by Jelmer Vernooij
Use peeling.
102
        """Iterate over the tag refs.
103
104
        :param refs: Refs dictionary (name -> git sha1)
105
        :return: iterator over (name, peeled_sha1, unpeeled_sha1, bzr_revid)
106
        """
107
        for k, unpeeled in refs.as_dict().iteritems():
108
            try:
109
                tag_name = ref_to_tag_name(k)
110
            except (ValueError, UnicodeDecodeError):
111
                continue
112
            peeled = refs.get_peeled(k)
113
            if peeled is None:
0.200.1759 by Jelmer Vernooij
Fix handling of tags not present in the repo.
114
                try:
115
                    peeled = self.repository.controldir._git.object_store.peel_sha(unpeeled).id
116
                except KeyError:
117
                    # Let's just hope it's a commit
118
                    peeled = unpeeled
0.200.1580 by Jelmer Vernooij
Add assertion.
119
            assert type(tag_name) is unicode
0.200.1717 by Jelmer Vernooij
Ignore tags pointing at non-commit objects.
120
            try:
121
                foreign_peeled = self.branch.lookup_foreign_revision_id(peeled)
122
            except NotCommitError:
123
                continue
124
            yield (tag_name, peeled, unpeeled, foreign_peeled)
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
125
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
126
    def _merge_to_remote_git(self, target_repo, new_refs, overwrite=False):
127
        updates = {}
128
        conflicts = []
129
        def get_changed_refs(old_refs):
130
            ret = dict(old_refs)
131
            for k, v in new_refs.iteritems():
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
132
                if not is_tag(k):
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
133
                    continue
134
                name = ref_to_tag_name(k)
135
                if old_refs.get(k) == v:
136
                    pass
137
                elif overwrite or not k in old_refs:
138
                    ret[k] = v
139
                    updates[name] = target_repo.lookup_foreign_revision_id(v)
140
                else:
141
                    conflicts.append((name, v, old_refs[k]))
142
            return ret
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
143
        target_repo.controldir.send_pack(get_changed_refs, lambda have, want: [])
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
144
        return updates, conflicts
145
146
    def _merge_to_local_git(self, target_repo, refs, overwrite=False):
147
        conflicts = []
148
        updates = {}
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
149
        for k, unpeeled in refs.as_dict().iteritems():
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
150
            if not is_tag(k):
151
                continue
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
152
            name = ref_to_tag_name(k)
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
153
            peeled = self.repository.controldir.get_peeled(k)
0.200.1489 by Jelmer Vernooij
More fixes to peel handling.
154
            if target_repo._git.refs.get(k) == unpeeled:
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
155
                pass
156
            elif overwrite or not k in target_repo._git.refs:
0.200.1460 by Jelmer Vernooij
Improve pulling into local git branches.
157
                target_repo._git.refs[k] = unpeeled or peeled
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
158
                updates[name] = self.repository.lookup_foreign_revision_id(peeled)
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
159
            else:
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
160
                conflicts.append((name, self.repository.lookup_foreign_revision_id(peeled), target_repo.lookup_foreign_revision_id(target_repo._git.refs[k])))
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
161
        return updates, conflicts
162
163
    def _merge_to_git(self, to_tags, refs, overwrite=False):
164
        target_repo = to_tags.repository
165
        if self.repository.has_same_location(target_repo):
166
            return {}, []
167
        if getattr(target_repo, "_git", None):
168
            return self._merge_to_local_git(target_repo, refs, overwrite)
169
        else:
170
            return self._merge_to_remote_git(target_repo, refs, overwrite)
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
171
172
    def _merge_to_non_git(self, to_tags, refs, overwrite=False):
173
        unpeeled_map = defaultdict(set)
174
        conflicts = []
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
175
        updates = {}
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
176
        result = dict(to_tags.get_tag_dict())
177
        for n, peeled, unpeeled, bzr_revid in self._iter_tag_refs(refs):
178
            if unpeeled is not None:
179
                unpeeled_map[peeled].add(unpeeled)
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
180
            if result.get(n) == bzr_revid:
181
                pass
182
            elif n not in result or overwrite:
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
183
                result[n] = bzr_revid
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
184
                updates[n] = bzr_revid
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
185
            else:
0.200.1707 by Jelmer Vernooij
Fix test.
186
                conflicts.append((n, bzr_revid, result[n]))
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
187
        to_tags._set_tag_dict(result)
188
        if len(unpeeled_map) > 0:
189
            map_file = UnpeelMap.from_repository(to_tags.branch.repository)
190
            map_file.update(unpeeled_map)
191
            map_file.save_in_repository(to_tags.branch.repository)
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
192
        return updates, conflicts
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
193
194
    def merge_to(self, to_tags, overwrite=False, ignore_master=False,
195
                 source_refs=None):
0.200.1113 by Jelmer Vernooij
Fix Tags.merge_to.
196
        """See Tags.merge_to."""
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
197
        if source_refs is None:
0.200.1487 by Jelmer Vernooij
Use peeling.
198
            source_refs = self.get_refs_container()
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
199
        if self == to_tags:
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
200
            return {}, []
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
201
        if isinstance(to_tags, GitTags):
202
            return self._merge_to_git(to_tags, source_refs,
203
                                      overwrite=overwrite)
204
        else:
205
            if ignore_master:
206
                master = None
207
            else:
208
                master = to_tags.branch.get_master_branch()
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
209
            updates, conflicts = self._merge_to_non_git(to_tags, source_refs,
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
210
                                              overwrite=overwrite)
211
            if master is not None:
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
212
                extra_updates, extra_conflicts = self.merge_to(
213
                    master.tags, overwrite=overwrite,
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
214
                                           source_refs=source_refs,
215
                                           ignore_master=ignore_master)
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
216
                updates.update(extra_updates)
217
                conflicts += extra_conflicts
218
            return updates, conflicts
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
219
220
    def get_tag_dict(self):
221
        ret = {}
0.200.1487 by Jelmer Vernooij
Use peeling.
222
        refs = self.get_refs_container()
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
223
        for (name, peeled, unpeeled, bzr_revid) in self._iter_tag_refs(refs):
224
            ret[name] = bzr_revid
225
        return ret
226
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
227
228
class LocalGitTagDict(GitTags):
229
    """Dictionary with tags in a local repository."""
230
231
    def __init__(self, branch):
232
        super(LocalGitTagDict, self).__init__(branch)
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
233
        self.refs = self.repository.controldir._git.refs
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
234
0.200.1487 by Jelmer Vernooij
Use peeling.
235
    def get_refs_container(self):
236
        return self.refs
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
237
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
238
    def _set_tag_dict(self, to_dict):
0.200.1487 by Jelmer Vernooij
Use peeling.
239
        extra = set(self.refs.allkeys())
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
240
        for k, revid in to_dict.iteritems():
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
241
            name = tag_name_to_ref(k)
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
242
            if name in extra:
243
                extra.remove(name)
244
            self.set_tag(k, revid)
245
        for name in extra:
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
246
            if is_tag(name):
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
247
                del self.repository._git[name]
0.200.956 by Jelmer Vernooij
Add some more format tests.
248
0.200.86 by Jelmer Vernooij
Clearer error when setting tags.
249
    def set_tag(self, name, revid):
0.200.1369 by Jelmer Vernooij
Clarify that ghost tags are not supported.
250
        try:
251
            git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
252
        except errors.NoSuchRevision:
253
            raise errors.GhostTagsNotSupported(self)
254
        self.refs[tag_name_to_ref(name)] = git_sha
0.200.86 by Jelmer Vernooij
Clearer error when setting tags.
255
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
256
0.200.1078 by Jelmer Vernooij
Fix git-import from remote repositories.
257
class DictTagDict(tag.BasicTags):
0.239.1 by Jelmer Vernooij
Avoid re-connecting to fetch tags we already know.
258
259
    def __init__(self, branch, tags):
260
        super(DictTagDict, self).__init__(branch)
261
        self._tags = tags
262
263
    def get_tag_dict(self):
264
        return self._tags
265
266
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
267
class GitBranchFormat(branch.BranchFormat):
268
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
269
    def network_name(self):
270
        return "git"
271
0.200.82 by Jelmer Vernooij
Support listing tags.
272
    def supports_tags(self):
273
        return True
274
0.200.1105 by Jelmer Vernooij
Don't claim to support leaving locks.
275
    def supports_leaving_lock(self):
276
        return False
277
0.200.1369 by Jelmer Vernooij
Clarify that ghost tags are not supported.
278
    def supports_tags_referencing_ghosts(self):
279
        return False
280
281
    def tags_are_versioned(self):
282
        return False
283
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
284
    def get_foreign_tests_branch_factory(self):
0.200.1644 by Jelmer Vernooij
More relative imports.
285
        from .tests.test_branch import ForeignTestsBranchFactory
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
286
        return ForeignTestsBranchFactory()
287
0.200.246 by Jelmer Vernooij
Cope with API changes in 1.13.
288
    def make_tags(self, branch):
0.200.1487 by Jelmer Vernooij
Use peeling.
289
        try:
290
            return branch.tags
291
        except AttributeError:
292
            pass
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
293
        if getattr(branch.repository, "_git", None) is None:
0.200.1644 by Jelmer Vernooij
More relative imports.
294
            from .remote import RemoteGitTagDict
0.228.3 by Jelmer Vernooij
Fix tags when fetching from remotes.
295
            return RemoteGitTagDict(branch)
0.200.261 by Jelmer Vernooij
More formatting fixes.
296
        else:
297
            return LocalGitTagDict(branch)
0.200.246 by Jelmer Vernooij
Cope with API changes in 1.13.
298
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
299
    def initialize(self, a_controldir, name=None, repository=None,
0.200.1378 by Jelmer Vernooij
Fix branch.
300
                   append_revisions_only=None):
0.295.2 by Jelmer Vernooij
Make RemoteGitBranchFormat uninitializeable.
301
        raise NotImplementedError(self.initialize)
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
302
0.200.1728 by Jelmer Vernooij
Support following branch references.
303
    def get_reference(self, controldir, name=None):
304
        return controldir.get_branch_reference(name)
305
306
    def set_reference(self, controldir, name, target):
307
        return controldir.set_branch_reference(target, name)
308
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
309
0.295.1 by Jelmer Vernooij
Split up branch formats.
310
class LocalGitBranchFormat(GitBranchFormat):
311
312
    def get_format_description(self):
313
        return 'Local Git Branch'
314
315
    @property
316
    def _matchingcontroldir(self):
317
        from .dir import LocalGitControlDirFormat
318
        return LocalGitControlDirFormat()
319
0.295.2 by Jelmer Vernooij
Make RemoteGitBranchFormat uninitializeable.
320
    def initialize(self, a_controldir, name=None, repository=None,
321
                   append_revisions_only=None):
322
        from .dir import LocalGitDir
323
        if not isinstance(a_controldir, LocalGitDir):
324
            raise errors.IncompatibleFormat(self, a_controldir._format)
325
        return a_controldir.create_branch(repository=repository, name=name,
326
            append_revisions_only=append_revisions_only)
327
0.295.1 by Jelmer Vernooij
Split up branch formats.
328
0.200.388 by Jelmer Vernooij
Support bzr 1.14 as well.
329
class GitBranch(ForeignBranch):
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
330
    """An adapter to git repositories for bzr Branch objects."""
331
0.200.1129 by Jelmer Vernooij
Implement GitBranch.control_transport.
332
    @property
333
    def control_transport(self):
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
334
        return self.controldir.control_transport
0.200.1129 by Jelmer Vernooij
Implement GitBranch.control_transport.
335
0.295.1 by Jelmer Vernooij
Split up branch formats.
336
    def __init__(self, controldir, repository, ref, format):
0.200.82 by Jelmer Vernooij
Support listing tags.
337
        self.repository = repository
0.295.1 by Jelmer Vernooij
Split up branch formats.
338
        self._format = format
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
339
        self.controldir = controldir
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
340
        self._lock_mode = None
341
        self._lock_count = 0
0.231.1 by Jelmer Vernooij
Check that regenerated objects have the expected sha1.
342
        super(GitBranch, self).__init__(repository.get_mapping())
0.200.770 by Jelmer Vernooij
Proper branch names.
343
        self.ref = ref
0.200.1708 by Jelmer Vernooij
Fix to colocated branch tests.
344
        self._head = None
0.200.1361 by Jelmer Vernooij
Support branches where the ref can't be mapped back to a branch name.
345
        try:
346
            self.name = ref_to_branch_name(ref)
347
        except ValueError:
348
            self.name = None
0.200.1708 by Jelmer Vernooij
Fix to colocated branch tests.
349
            if self.ref is not None:
350
                self.user_transport.set_segment_parameter(
351
                    "ref", urlutils.escape(self.ref))
352
        else:
353
            if self.name != "":
354
                self.user_transport.set_segment_parameter(
355
                    "branch", urlutils.escape(self.name))
356
        self.base = self.user_transport.base
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
357
0.200.1360 by Jelmer Vernooij
Support lighweight argument to _get_checkout_format.
358
    def _get_checkout_format(self, lightweight=False):
0.239.8 by Jelmer Vernooij
Support checkouts.
359
        """Return the most suitable metadir for a checkout of this branch.
360
        Weaves are used if this branch's repository uses weaves.
361
        """
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
362
        return controldir.format_registry.make_controldir("default")
0.239.8 by Jelmer Vernooij
Support checkouts.
363
0.238.3 by Jelmer Vernooij
Remove svn references, prefer git send format when submitting changes against a git branch.
364
    def get_child_submit_format(self):
365
        """Return the preferred format of submissions to this branch."""
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
366
        ret = self.get_config_stack().get("child_submit_format")
0.238.3 by Jelmer Vernooij
Remove svn references, prefer git send format when submitting changes against a git branch.
367
        if ret is not None:
368
            return ret
369
        return "git"
370
0.200.1397 by Jelmer Vernooij
Fix use of get_config() for RemoteGitBranch.
371
    def get_config(self):
372
        return GitBranchConfig(self)
373
0.200.1472 by Jelmer Vernooij
Provide basic implementation of Branch.get_config_stack.
374
    def get_config_stack(self):
375
        return GitBranchStack(self)
376
0.200.293 by Jelmer Vernooij
Fix branch nicks.
377
    def _get_nick(self, local=False, possible_master_transports=None):
378
        """Find the nick name for this branch.
379
380
        :return: Branch nick
381
        """
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
382
        cs = self.repository._git.get_config_stack()
383
        try:
0.200.1694 by Jelmer Vernooij
Fix nick test.
384
            return cs.get((b"branch", self.name.encode('utf-8')), b"nick").decode("utf-8")
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
385
        except KeyError:
386
            pass
0.200.1694 by Jelmer Vernooij
Fix nick test.
387
        return self.name or u"HEAD"
0.200.293 by Jelmer Vernooij
Fix branch nicks.
388
0.200.331 by Jelmer Vernooij
Add stub for setting nick function.
389
    def _set_nick(self, nick):
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
390
        cf = self.repository._git.get_config()
0.200.1694 by Jelmer Vernooij
Fix nick test.
391
        cf.set((b"branch", self.name.encode('utf-8')), b"nick", nick.encode("utf-8"))
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
392
        f = StringIO()
393
        cf.write_to_file(f)
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
394
        self.repository._git._put_named_file('config', f.getvalue())
0.200.331 by Jelmer Vernooij
Add stub for setting nick function.
395
396
    nick = property(_get_nick, _set_nick)
0.200.293 by Jelmer Vernooij
Fix branch nicks.
397
0.200.412 by Jelmer Vernooij
Implement GitBranch.__repr__.
398
    def __repr__(self):
0.200.770 by Jelmer Vernooij
Proper branch names.
399
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
400
            self.name)
0.200.412 by Jelmer Vernooij
Implement GitBranch.__repr__.
401
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
402
    def generate_revision_history(self, revid, last_rev=None, other_branch=None):
403
        if last_rev is not None:
404
            graph = self.repository.get_graph()
405
            if not graph.is_ancestor(last_rev, revid):
406
                # our previous tip is not merged into stop_revision
407
                raise errors.DivergedBranches(self, other_branch)
408
0.200.1103 by Jelmer Vernooij
Support generate_revision_history(NULL_REVISION).
409
        if revid == NULL_REVISION:
410
            newhead = ZERO_SHA
411
        else:
412
            # FIXME: Check that old_revid is in the ancestry of revid
0.200.1324 by Jelmer Vernooij
More work on roundtripping support.
413
            newhead, self.mapping = self.repository.lookup_bzr_revision_id(revid)
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
414
            if self.mapping is None:
415
                raise AssertionError
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
416
        self._set_head(newhead)
417
0.200.1199 by Jelmer Vernooij
Support 'token' argument to Branch.lock_write.
418
    def lock_write(self, token=None):
419
        if token is not None:
420
            raise errors.TokenLockingNotSupported(self)
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
421
        if self._lock_mode:
0.200.1369 by Jelmer Vernooij
Clarify that ghost tags are not supported.
422
            if self._lock_mode == 'r':
423
                raise errors.ReadOnlyError(self)
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
424
            self._lock_count += 1
425
        else:
426
            self._lock_mode = 'w'
427
            self._lock_count = 1
428
        self.repository.lock_write()
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
429
        return lock.LogicalLockResult(self.unlock)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
430
0.200.1453 by Jelmer Vernooij
Provide Branch.leave_lock_in_place and Branch.dont_leave_lock_in_place.
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
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
437
    def get_stacked_on_url(self):
438
        # Git doesn't do stacking (yet...)
0.200.1660 by Jelmer Vernooij
Fix imports.
439
        raise branch.UnstackableBranchFormat(self._format, self.base)
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
440
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
441
    def _get_parent_location(self):
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
442
        """See Branch.get_parent()."""
0.200.312 by Jelmer Vernooij
Add notes about parent locations.
443
        # FIXME: Set "origin" url from .git/config ?
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
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
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
449
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
450
    def set_parent(self, location):
0.200.312 by Jelmer Vernooij
Add notes about parent locations.
451
        # FIXME: Set "origin" url in .git/config ?
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
452
        cs = self.repository._git.get_config()
0.292.1 by Jelmer Vernooij
Try to set relative parent in config.
453
        location = urlutils.relative_url(self.base, location)
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
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())
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
458
0.200.1411 by Jelmer Vernooij
Fix control files.
459
    def break_lock(self):
460
        raise NotImplementedError(self.break_lock)
461
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
462
    def lock_read(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
463
        if self._lock_mode:
464
            assert self._lock_mode in ('r', 'w')
465
            self._lock_count += 1
466
        else:
467
            self._lock_mode = 'r'
468
            self._lock_count = 1
469
        self.repository.lock_read()
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
470
        return lock.LogicalLockResult(self.unlock)
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
471
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
472
    def peek_lock_mode(self):
473
        return self._lock_mode
474
0.200.432 by Jelmer Vernooij
Support Branch.is_locked, required for loggerhead.
475
    def is_locked(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
476
        return (self._lock_mode is not None)
0.200.432 by Jelmer Vernooij
Support Branch.is_locked, required for loggerhead.
477
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
478
    def unlock(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
479
        """See Branch.unlock()."""
480
        self._lock_count -= 1
481
        if self._lock_count == 0:
482
            self._lock_mode = None
483
            self._clear_cached_state()
484
        self.repository.unlock()
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
485
486
    def get_physical_lock_status(self):
487
        return False
488
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
489
    def last_revision(self):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
490
        with self.lock_read():
491
            # perhaps should escape this ?
492
            if self.head is None:
493
                return revision.NULL_REVISION
494
            return self.lookup_foreign_revision_id(self.head)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
495
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
496
    def _basic_push(self, target, overwrite=False, stop_revision=None):
497
        return branch.InterBranch.get(self, target)._basic_push(
498
            overwrite, stop_revision)
499
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
500
    def lookup_foreign_revision_id(self, foreign_revid):
0.200.1760 by Jelmer Vernooij
Fall back to simple revision id generation.
501
        try:
502
            return self.repository.lookup_foreign_revision_id(foreign_revid,
503
                self.mapping)
504
        except KeyError:
505
            # Let's try..
506
            return self.mapping.revision_id_foreign_to_bzr(foreign_revid)
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
507
0.200.1030 by Jelmer Vernooij
More work on supporting roundtripping push.
508
    def lookup_bzr_revision_id(self, revid):
509
        return self.repository.lookup_bzr_revision_id(
510
            revid, mapping=self.mapping)
511
0.200.1678 by Jelmer Vernooij
Fix tests.
512
    def get_unshelver(self, tree):
513
        raise errors.StoringUncommittedNotSupported(self)
514
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
515
0.200.465 by Jelmer Vernooij
Use dulwich standard functionality for finding missing revisions.
516
class LocalGitBranch(GitBranch):
517
    """A local Git branch."""
518
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
519
    def __init__(self, controldir, repository, ref):
0.295.1 by Jelmer Vernooij
Split up branch formats.
520
        super(LocalGitBranch, self).__init__(controldir, repository, ref,
521
                LocalGitBranchFormat())
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
522
        refs = controldir.get_refs_container()
0.200.1487 by Jelmer Vernooij
Use peeling.
523
        if not (ref in refs or "HEAD" in refs):
0.200.763 by Jelmer Vernooij
Provide proper colocated branch support.
524
            raise errors.NotBranchError(self.base)
525
0.200.261 by Jelmer Vernooij
More formatting fixes.
526
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
527
        accelerator_tree=None, hardlink=False):
0.200.1774 by Jelmer Vernooij
Simplify checkout creation.
528
        t = transport.get_transport(to_location)
529
        t.ensure_base()
530
        format = self._get_checkout_format(lightweight=lightweight)
531
        checkout = format.initialize_on_transport(t)
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
532
        if lightweight:
0.200.1774 by Jelmer Vernooij
Simplify checkout creation.
533
            from_branch = checkout.set_branch_reference(target_branch=self)
534
        else:
535
            policy = checkout.determine_repository_policy()
536
            repo = policy.acquire_repository()[0]
537
538
            checkout_branch = checkout.create_branch()
539
            checkout_branch.bind(self)
540
            checkout_branch.pull(self, stop_revision=revision_id)
541
            from_branch = None
542
        return checkout.create_workingtree(revision_id,
0.230.1 by Jelmer Vernooij
Support lightweight checkouts.
543
                from_branch=from_branch, hardlink=hardlink)
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
544
0.200.1493 by Jelmer Vernooij
Test fixes.
545
    def fetch(self, from_branch, last_revision=None, limit=None):
546
        return branch.InterBranch.get(from_branch, self).fetch(
547
            stop_revision=last_revision, limit=limit)
548
0.200.57 by Jelmer Vernooij
Fix more tests.
549
    def _gen_revision_history(self):
0.200.58 by Jelmer Vernooij
Fix remaining tests.
550
        if self.head is None:
551
            return []
0.200.1279 by Jelmer Vernooij
Avoid using deprecated Repository.iter_reverse_revision_history.
552
        graph = self.repository.get_graph()
553
        ret = list(graph.iter_lefthand_ancestry(self.last_revision(),
554
            (revision.NULL_REVISION, )))
0.200.59 by Jelmer Vernooij
Add more tests, fix revision history.
555
        ret.reverse()
0.200.57 by Jelmer Vernooij
Fix more tests.
556
        return ret
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
557
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
558
    def _get_head(self):
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
559
        try:
0.280.1 by Martin Pitt
Fix deprecated Repo.ref(), to make testsuite succeed again.
560
            return self.repository._git.refs[self.ref or "HEAD"]
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
561
        except KeyError:
562
            return None
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
563
0.200.1228 by Jelmer Vernooij
Provide Branch._read_last_revision_info.
564
    def _read_last_revision_info(self):
565
        last_revid = self.last_revision()
566
        graph = self.repository.get_graph()
567
        revno = graph.find_distance_to_null(last_revid,
568
            [(revision.NULL_REVISION, 0)])
569
        return revno, last_revid
570
571
    def set_last_revision_info(self, revno, revision_id):
572
        self.set_last_revision(revision_id)
573
        self._last_revision_info_cache = revno, revision_id
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
574
575
    def set_last_revision(self, revid):
0.200.1233 by Jelmer Vernooij
Implement Repository.iter_files_bytes.
576
        if not revid or not isinstance(revid, basestring):
577
            raise errors.InvalidRevisionId(revision_id=revid, branch=self)
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
578
        if revid == NULL_REVISION:
579
            newhead = ZERO_SHA
580
        else:
581
            (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
582
            if self.mapping is None:
583
                raise AssertionError
584
        self._set_head(newhead)
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
585
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
586
    def _set_head(self, value):
587
        self._head = value
0.200.918 by Jelmer Vernooij
Cope with 'self.ref is None' in a couple more places.
588
        self.repository._git.refs[self.ref or "HEAD"] = self._head
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
589
        self._clear_cached_state()
590
591
    head = property(_get_head, _set_head)
592
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
593
    def get_push_location(self):
594
        """See Branch.get_push_location."""
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
595
        push_loc = self.get_config_stack().get('push_location')
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
596
        return push_loc
597
598
    def set_push_location(self, location):
599
        """See Branch.set_push_location."""
0.200.19 by John Arbash Meinel
More refactoring. Add some direct tests for GitModel.
600
        self.get_config().set_user_option('push_location', location,
0.217.54 by John Carr
set_user_option breaks - doesnt have a local option in BranchConfig. Follow the bzr.dev syntax instead.
601
                                          store=config.STORE_LOCATION)
0.200.43 by David Allouche
Ultra-experimental support for "bzr pull". No test. No sanity.
602
603
    def supports_tags(self):
0.200.82 by Jelmer Vernooij
Support listing tags.
604
        return True
0.200.956 by Jelmer Vernooij
Add some more format tests.
605
0.200.1681 by Jelmer Vernooij
Provide Branch.store_uncommitted.
606
    def store_uncommitted(self, creator):
607
        raise errors.StoringUncommittedNotSupported(self)
608
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
609
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
610
def _quick_lookup_revno(local_branch, remote_branch, revid):
611
    assert isinstance(revid, str), "was %r" % revid
612
    # Try in source branch first, it'll be faster
0.200.1788 by Jelmer Vernooij
Use context managers.
613
    with local_branch.lock_read():
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
614
        try:
0.200.1362 by Jelmer Vernooij
Add locking.
615
            return local_branch.revision_id_to_revno(revid)
616
        except errors.NoSuchRevision:
617
            graph = local_branch.repository.get_graph()
618
            try:
619
                return graph.find_distance_to_null(revid,
620
                    [(revision.NULL_REVISION, 0)])
621
            except errors.GhostRevisionsHaveNoRevno:
622
                # FIXME: Check using graph.find_distance_to_null() ?
0.200.1788 by Jelmer Vernooij
Use context managers.
623
                with remote_branch.lock_read():
0.200.1362 by Jelmer Vernooij
Add locking.
624
                    return remote_branch.revision_id_to_revno(revid)
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
625
626
0.200.342 by Jelmer Vernooij
Report git sha during pull.
627
class GitBranchPullResult(branch.PullResult):
628
0.252.36 by Jelmer Vernooij
Fix pull.
629
    def __init__(self):
630
        super(GitBranchPullResult, self).__init__()
631
        self.new_git_head = None
632
        self._old_revno = None
633
        self._new_revno = None
634
0.200.342 by Jelmer Vernooij
Report git sha during pull.
635
    def report(self, to_file):
636
        if not is_quiet():
637
            if self.old_revid == self.new_revid:
638
                to_file.write('No revisions to pull.\n')
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
639
            elif self.new_git_head is not None:
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
640
                to_file.write('Now on revision %d (git sha: %s).\n' %
0.200.342 by Jelmer Vernooij
Report git sha during pull.
641
                        (self.new_revno, self.new_git_head))
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
642
            else:
643
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
0.200.342 by Jelmer Vernooij
Report git sha during pull.
644
        self._show_tag_conficts(to_file)
645
0.252.36 by Jelmer Vernooij
Fix pull.
646
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
647
        return _quick_lookup_revno(self.target_branch, self.source_branch,
0.200.1513 by Jelmer Vernooij
Cope with zero shas.
648
            revid)
0.252.36 by Jelmer Vernooij
Fix pull.
649
650
    def _get_old_revno(self):
651
        if self._old_revno is not None:
652
            return self._old_revno
653
        return self._lookup_revno(self.old_revid)
654
655
    def _set_old_revno(self, revno):
656
        self._old_revno = revno
657
658
    old_revno = property(_get_old_revno, _set_old_revno)
659
660
    def _get_new_revno(self):
661
        if self._new_revno is not None:
662
            return self._new_revno
663
        return self._lookup_revno(self.new_revid)
664
665
    def _set_new_revno(self, revno):
666
        self._new_revno = revno
0.200.956 by Jelmer Vernooij
Add some more format tests.
667
0.252.36 by Jelmer Vernooij
Fix pull.
668
    new_revno = property(_get_new_revno, _set_new_revno)
669
0.200.342 by Jelmer Vernooij
Report git sha during pull.
670
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
671
class GitBranchPushResult(branch.BranchPushResult):
672
673
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
674
        return _quick_lookup_revno(self.source_branch, self.target_branch,
675
            revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
676
677
    @property
678
    def old_revno(self):
679
        return self._lookup_revno(self.old_revid)
680
681
    @property
682
    def new_revno(self):
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
683
        new_original_revno = getattr(self, "new_original_revno", None)
684
        if new_original_revno:
685
            return new_original_revno
686
        if getattr(self, "new_original_revid", None) is not None:
687
            return self._lookup_revno(self.new_original_revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
688
        return self._lookup_revno(self.new_revid)
689
690
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
691
class InterFromGitBranch(branch.GenericInterBranch):
0.200.261 by Jelmer Vernooij
More formatting fixes.
692
    """InterBranch implementation that pulls from Git into bzr."""
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
693
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
694
    @staticmethod
695
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
696
        try:
697
            default_format = branch.format_registry.get_default()
698
        except AttributeError:
699
            default_format = branch.BranchFormat._default_format
0.295.4 by Jelmer Vernooij
Fix imports.
700
        from .remote import RemoteGitBranchFormat
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
701
        return [
0.295.1 by Jelmer Vernooij
Split up branch formats.
702
            (RemoteGitBranchFormat(), default_format),
703
            (LocalGitBranchFormat(), default_format)]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
704
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
705
    @classmethod
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
706
    def _get_interrepo(self, source, target):
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
707
        return _mod_repository.InterRepository.get(source.repository, target.repository)
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
708
709
    @classmethod
710
    def is_compatible(cls, source, target):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
711
        if not isinstance(source, GitBranch):
712
            return False
713
        if isinstance(target, GitBranch):
714
            # InterLocalGitRemoteGitBranch or InterToGitBranch should be used
715
            return False
716
        if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
717
            # fetch_objects is necessary for this to work
718
            return False
719
        return True
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
720
0.200.1305 by Jelmer Vernooij
Only actually fetch tags if "branch.fetch_tags" is set to true.
721
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
722
        self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
723
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
724
    def fetch_objects(self, stop_revision, fetch_tags, limit=None):
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
725
        interrepo = self._get_interrepo(self.source, self.target)
0.200.1305 by Jelmer Vernooij
Only actually fetch tags if "branch.fetch_tags" is set to true.
726
        if fetch_tags is None:
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
727
            c = self.source.get_config_stack()
728
            fetch_tags = c.get('branch.fetch_tags')
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
729
        def determine_wants(heads):
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
730
            if self.source.ref is not None and not self.source.ref in heads:
0.200.1386 by Jelmer Vernooij
Friendlier message if HEAD is not found.
731
                raise NoSuchRef(self.source.ref, self.source.user_url, heads.keys())
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
732
733
            if stop_revision is None:
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
734
                if self.source.ref is not None:
735
                    head = heads[self.source.ref]
736
                else:
737
                    head = heads["HEAD"]
0.252.44 by Jelmer Vernooij
Properly look up Bazaar revision ids for revision parents in case they are round-tripped.
738
                self._last_revid = self.source.lookup_foreign_revision_id(head)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
739
            else:
740
                self._last_revid = stop_revision
741
            real = interrepo.get_determine_wants_revids(
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
742
                [self._last_revid], include_tags=fetch_tags)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
743
            return real(heads)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
744
        pack_hint, head, refs = interrepo.fetch_objects(
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
745
            determine_wants, self.source.mapping, limit=limit)
0.252.45 by Jelmer Vernooij
Finish fetching roundtripped revisions back into bzr.
746
        if (pack_hint is not None and
747
            self.target.repository._format.pack_compresses):
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
748
            self.target.repository.pack(hint=pack_hint)
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
749
        return head, refs
750
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
751
    def _update_revisions(self, stop_revision=None, overwrite=False):
0.200.1305 by Jelmer Vernooij
Only actually fetch tags if "branch.fetch_tags" is set to true.
752
        head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
753
        if overwrite:
0.200.314 by Jelmer Vernooij
Support stop_revision.
754
            prev_last_revid = None
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
755
        else:
0.200.314 by Jelmer Vernooij
Support stop_revision.
756
            prev_last_revid = self.target.last_revision()
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
757
        self.target.generate_revision_history(self._last_revid,
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
758
            last_rev=prev_last_revid, other_branch=self.source)
0.200.1062 by Jelmer Vernooij
Pass remote refs along in _update_revisions.
759
        return head, refs
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
760
0.200.1423 by Jelmer Vernooij
Fix space.
761
    def _basic_pull(self, stop_revision, overwrite, run_hooks,
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
762
              _override_hook_target, _hook_master):
0.200.342 by Jelmer Vernooij
Report git sha during pull.
763
        result = GitBranchPullResult()
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
764
        result.source_branch = self.source
765
        if _override_hook_target is None:
766
            result.target_branch = self.target
767
        else:
768
            result.target_branch = _override_hook_target
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
769
        with self.target.lock_write(), self.source.lock_read():
770
            # We assume that during 'pull' the target repository is closer than
771
            # the source one.
772
            (result.old_revno, result.old_revid) = \
773
                self.target.last_revision_info()
774
            result.new_git_head, remote_refs = self._update_revisions(
775
                stop_revision, overwrite=overwrite)
776
            tags_ret  = self.source.tags.merge_to(
777
                    self.target.tags, overwrite, ignore_master=True)
778
            if isinstance(tags_ret, tuple):
779
                result.tag_updates, result.tag_conflicts = tags_ret
780
            else:
781
                result.tag_conflicts = tags_ret
782
            (result.new_revno, result.new_revid) = \
783
                self.target.last_revision_info()
784
            if _hook_master:
785
                result.master_branch = _hook_master
786
                result.local_branch = result.target_branch
787
            else:
788
                result.master_branch = result.target_branch
789
                result.local_branch = None
790
            if run_hooks:
791
                for hook in branch.Branch.hooks['post_pull']:
792
                    hook(result)
793
            return result
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
794
795
    def pull(self, overwrite=False, stop_revision=None,
796
             possible_transports=None, _hook_master=None, run_hooks=True,
797
             _override_hook_target=None, local=False):
798
        """See Branch.pull.
799
800
        :param _hook_master: Private parameter - set the branch to
801
            be supplied as the master to pull hooks.
802
        :param run_hooks: Private parameter - if false, this branch
803
            is being called because it's the master of the primary branch,
804
            so it should not run its hooks.
805
        :param _override_hook_target: Private parameter - set the branch to be
806
            supplied as the target_branch to pull hooks.
807
        """
808
        # This type of branch can't be bound.
809
        bound_location = self.target.get_bound_location()
810
        if local and not bound_location:
811
            raise errors.LocalRequiresBoundBranch()
812
        master_branch = None
813
        source_is_master = False
814
        self.source.lock_read()
815
        if bound_location:
816
            # bound_location comes from a config file, some care has to be
817
            # taken to relate it to source.user_url
818
            normalized = urlutils.normalize_url(bound_location)
819
            try:
820
                relpath = self.source.user_transport.relpath(normalized)
821
                source_is_master = (relpath == '')
0.200.1660 by Jelmer Vernooij
Fix imports.
822
            except (errors.PathNotChild, urlutils.InvalidURL):
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
823
                source_is_master = False
824
        if not local and bound_location and not source_is_master:
825
            # not pulling from master, so we need to update master.
826
            master_branch = self.target.get_master_branch(possible_transports)
827
            master_branch.lock_write()
828
        try:
829
            try:
830
                if master_branch:
831
                    # pull from source into master.
832
                    master_branch.pull(self.source, overwrite, stop_revision,
833
                        run_hooks=False)
834
                result = self._basic_pull(stop_revision, overwrite, run_hooks,
835
                    _override_hook_target, _hook_master=master_branch)
836
            finally:
837
                self.source.unlock()
838
        finally:
839
            if master_branch:
840
                master_branch.unlock()
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
841
        return result
842
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
843
    def _basic_push(self, overwrite=False, stop_revision=None):
844
        result = branch.BranchPushResult()
845
        result.source_branch = self.source
846
        result.target_branch = self.target
847
        result.old_revno, result.old_revid = self.target.last_revision_info()
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
848
        result.new_git_head, remote_refs = self._update_revisions(
849
            stop_revision, overwrite=overwrite)
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
850
        tags_ret = self.source.tags.merge_to(self.target.tags,
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
851
            overwrite)
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
852
        if isinstance(tags_ret, tuple):
853
            (result.tag_updates, result.tag_conflicts) = tags_ret
854
        else:
855
            result.tag_conflicts = tags_ret
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
856
        result.new_revno, result.new_revid = self.target.last_revision_info()
857
        return result
858
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
859
0.200.512 by Jelmer Vernooij
Support pushing git->git.
860
class InterGitBranch(branch.GenericInterBranch):
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
861
    """InterBranch implementation that pulls between Git branches."""
862
0.200.1493 by Jelmer Vernooij
Test fixes.
863
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
864
        raise NotImplementedError(self.fetch)
865
0.200.512 by Jelmer Vernooij
Support pushing git->git.
866
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
867
class InterLocalGitRemoteGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
868
    """InterBranch that copies from a local to a remote git branch."""
869
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
870
    @staticmethod
871
    def _get_branch_formats_to_test():
0.295.4 by Jelmer Vernooij
Fix imports.
872
        from .remote import RemoteGitBranchFormat
0.295.3 by Jelmer Vernooij
Fix some more tests.
873
        return [
874
            (LocalGitBranchFormat(), RemoteGitBranchFormat())]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
875
0.200.512 by Jelmer Vernooij
Support pushing git->git.
876
    @classmethod
877
    def is_compatible(self, source, target):
0.200.1644 by Jelmer Vernooij
More relative imports.
878
        from .remote import RemoteGitBranch
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
879
        return (isinstance(source, LocalGitBranch) and
0.200.512 by Jelmer Vernooij
Support pushing git->git.
880
                isinstance(target, RemoteGitBranch))
881
882
    def _basic_push(self, overwrite=False, stop_revision=None):
883
        result = GitBranchPushResult()
884
        result.source_branch = self.source
885
        result.target_branch = self.target
886
        if stop_revision is None:
887
            stop_revision = self.source.last_revision()
888
        # FIXME: Check for diverged branches
889
        def get_changed_refs(old_refs):
0.200.1300 by Jelmer Vernooij
Fix formatting.
890
            old_ref = old_refs.get(self.target.ref, ZERO_SHA)
891
            result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
0.200.822 by Jelmer Vernooij
Fix indication of number of revisions pushed in dpush.
892
            refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
0.200.512 by Jelmer Vernooij
Support pushing git->git.
893
            result.new_revid = stop_revision
894
            for name, sha in self.source.repository._git.refs.as_dict("refs/tags").iteritems():
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
895
                refs[tag_name_to_ref(name)] = sha
0.200.512 by Jelmer Vernooij
Support pushing git->git.
896
            return refs
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
897
        self.target.repository.send_pack(get_changed_refs,
0.200.726 by Jelmer Vernooij
Factor out conversion of branch names to refs.
898
            self.source.repository._git.object_store.generate_pack_contents)
0.200.512 by Jelmer Vernooij
Support pushing git->git.
899
        return result
900
901
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
902
class InterGitLocalGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
903
    """InterBranch that copies from a remote to a local git branch."""
904
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
905
    @staticmethod
906
    def _get_branch_formats_to_test():
0.295.4 by Jelmer Vernooij
Fix imports.
907
        from .remote import RemoteGitBranchFormat
0.295.3 by Jelmer Vernooij
Fix some more tests.
908
        return [
909
            (RemoteGitBranchFormat(), LocalGitBranchFormat()),
910
            (LocalGitBranchFormat(), LocalGitBranchFormat())]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
911
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
912
    @classmethod
913
    def is_compatible(self, source, target):
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
914
        return (isinstance(source, GitBranch) and
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
915
                isinstance(target, LocalGitBranch))
916
0.200.1534 by Jelmer Vernooij
Implement fetch between git branches, encode nicks.
917
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
918
        interrepo = _mod_repository.InterRepository.get(self.source.repository,
919
            self.target.repository)
920
        if stop_revision is None:
921
            stop_revision = self.source.last_revision()
922
        determine_wants = interrepo.get_determine_wants_revids(
923
            [stop_revision], include_tags=fetch_tags)
924
        interrepo.fetch_objects(determine_wants, limit=limit)
925
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
926
    def _basic_push(self, overwrite=False, stop_revision=None):
0.200.1325 by Jelmer Vernooij
More test fixes.
927
        result = GitBranchPushResult()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
928
        result.source_branch = self.source
929
        result.target_branch = self.target
930
        result.old_revid = self.target.last_revision()
931
        refs, stop_revision = self.update_refs(stop_revision)
0.296.3 by Jelmer Vernooij
Update xfail.
932
        self.target.generate_revision_history(stop_revision,
933
                (result.old_revid if not overwrite else None),
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
934
                other_branch=self.source)
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
935
        tags_ret = self.source.tags.merge_to(self.target.tags,
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
936
            source_refs=refs, overwrite=overwrite)
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
937
        if isinstance(tags_ret, tuple):
938
            (result.tag_updates, result.tag_conflicts) = tags_ret
939
        else:
940
            result.tag_conflicts = tags_ret
0.200.505 by Jelmer Vernooij
Remove duplicate code.
941
        result.new_revid = self.target.last_revision()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
942
        return result
943
944
    def update_refs(self, stop_revision=None):
0.296.1 by Jelmer Vernooij
Fix tag fetching.
945
        interrepo = _mod_repository.InterRepository.get(
946
                self.source.repository, self.target.repository)
947
        c = self.source.get_config_stack()
948
        fetch_tags = c.get('branch.fetch_tags')
949
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
950
        if stop_revision is None:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
951
            refs = interrepo.fetch(branches=["HEAD"], include_tags=fetch_tags)
0.252.44 by Jelmer Vernooij
Properly look up Bazaar revision ids for revision parents in case they are round-tripped.
952
            stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
953
        else:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
954
            refs = interrepo.fetch(revision_id=stop_revision, include_tags=fetch_tags)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
955
        return refs, stop_revision
956
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
957
    def pull(self, stop_revision=None, overwrite=False,
0.296.1 by Jelmer Vernooij
Fix tag fetching.
958
             possible_transports=None, run_hooks=True, local=False):
0.200.446 by Jelmer Vernooij
Support new 'local' argument.
959
        # This type of branch can't be bound.
960
        if local:
961
            raise errors.LocalRequiresBoundBranch()
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
962
        result = GitPullResult()
963
        result.source_branch = self.source
964
        result.target_branch = self.target
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
965
        with self.target.lock_write(), self.source.lock_read():
966
            result.old_revid = self.target.last_revision()
967
            refs, stop_revision = self.update_refs(stop_revision)
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
968
            self.target.generate_revision_history(stop_revision,
969
                    (result.old_revid if not overwrite else None),
970
                    other_branch=self.source)
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
971
            tags_ret = self.source.tags.merge_to(self.target.tags,
972
                overwrite=overwrite, source_refs=refs)
973
            if isinstance(tags_ret, tuple):
974
                (result.tag_updates, result.tag_conflicts) = tags_ret
975
            else:
976
                result.tag_conflicts = tags_ret
977
            result.new_revid = self.target.last_revision()
978
            result.local_branch = None
979
            result.master_branch = result.target_branch
980
            if run_hooks:
981
                for hook in branch.Branch.hooks['post_pull']:
982
                    hook(result)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
983
        return result
984
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
985
0.200.960 by Jelmer Vernooij
Use GenericInterBranch.
986
class InterToGitBranch(branch.GenericInterBranch):
0.296.1 by Jelmer Vernooij
Fix tag fetching.
987
    """InterBranch implementation that pulls from a non-bzr into a Git branch."""
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
988
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
989
    def __init__(self, source, target):
990
        super(InterToGitBranch, self).__init__(source, target)
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
991
        self.interrepo = _mod_repository.InterRepository.get(source.repository,
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
992
                                           target.repository)
993
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
994
    @staticmethod
995
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
996
        try:
997
            default_format = branch.format_registry.get_default()
998
        except AttributeError:
999
            default_format = branch.BranchFormat._default_format
0.295.4 by Jelmer Vernooij
Fix imports.
1000
        from .remote import RemoteGitBranchFormat
0.295.1 by Jelmer Vernooij
Split up branch formats.
1001
        return [
1002
            (default_format, LocalGitBranchFormat()),
1003
            (default_format, RemoteGitBranchFormat())]
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
1004
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1005
    @classmethod
1006
    def is_compatible(self, source, target):
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1007
        return (not isinstance(source, GitBranch) and
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1008
                isinstance(target, GitBranch))
1009
0.200.1363 by Jelmer Vernooij
Only fetch tags if requested in config.
1010
    def _get_new_refs(self, stop_revision=None, fetch_tags=None):
0.200.1398 by Jelmer Vernooij
Make GitSmartRemoteNotSupported derive from UnsupportedOperation.
1011
        assert self.source.is_locked()
0.252.38 by Jelmer Vernooij
Minor cleanups.
1012
        if stop_revision is None:
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
1013
            (stop_revno, stop_revision) = self.source.last_revision_info()
0.263.1 by Jelmer Vernooij
Fix dpush for certain branches.
1014
        else:
1015
            stop_revno = self.source.revision_id_to_revno(stop_revision)
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
1016
        assert type(stop_revision) is str
0.200.916 by Jelmer Vernooij
Set refs/heads/master if no ref is set yet.
1017
        main_ref = self.target.ref or "refs/heads/master"
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
1018
        refs = { main_ref: (None, stop_revision) }
0.200.1363 by Jelmer Vernooij
Only fetch tags if requested in config.
1019
        if fetch_tags is None:
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
1020
            c = self.source.get_config_stack()
1021
            fetch_tags = c.get('branch.fetch_tags')
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1022
        for name, revid in self.source.tags.get_tag_dict().iteritems():
1023
            if self.source.repository.has_revision(revid):
1024
                ref = tag_name_to_ref(name)
1025
                if not check_ref_format(ref):
1026
                    warning("skipping tag with invalid characters %s (%s)",
1027
                        name, ref)
1028
                    continue
0.200.1398 by Jelmer Vernooij
Make GitSmartRemoteNotSupported derive from UnsupportedOperation.
1029
                if fetch_tags:
1030
                    # FIXME: Skip tags that are not in the ancestry
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1031
                    refs[ref] = (None, revid)
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
1032
        return refs, main_ref, (stop_revno, stop_revision)
0.252.37 by Jelmer Vernooij
Factor out some common code for finding refs to send.
1033
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1034
    def _update_refs(self, result, old_refs, new_refs, overwrite):
1035
        mutter("updating refs. old refs: %r, new refs: %r",
1036
               old_refs, new_refs)
1037
        result.tag_updates = {}
1038
        result.tag_conflicts = []
1039
        ret = dict(old_refs)
1040
        def ref_equals(refs, ref, git_sha, revid):
1041
            try:
1042
                value = refs[ref]
1043
            except KeyError:
1044
                return False
1045
            if (value[0] is not None and
1046
                git_sha is not None and
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1047
                value[0] == git_sha):
1048
                return True
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1049
            if (value[1] is not None and
1050
                revid is not None and
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1051
                value[1] == revid):
1052
                return True
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1053
            # FIXME: If one side only has the git sha available and the other only
1054
            # has the bzr revid, then this will cause us to show a tag as updated
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
1055
            # that hasn't actually been updated.
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1056
            return False
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1057
        # FIXME: Check for diverged branches
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1058
        for ref, (git_sha, revid) in new_refs.iteritems():
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1059
            if ref_equals(ret, ref, git_sha, revid):
1060
                # Already up to date
1061
                if git_sha is None:
1062
                    git_sha = old_refs[ref][0]
1063
                if revid is None:
1064
                    revid = old_refs[ref][1]
1065
                ret[ref] = new_refs[ref] = (git_sha, revid)
1066
            elif ref not in ret or overwrite:
1067
                try:
1068
                    tag_name = ref_to_tag_name(ref)
1069
                except ValueError:
1070
                    pass
1071
                else:
1072
                    result.tag_updates[tag_name] = revid
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1073
                ret[ref] = (git_sha, revid)
1074
            else:
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1075
                # FIXME: Check diverged
1076
                diverged = False
1077
                if diverged:
1078
                    try:
1079
                        name = ref_to_tag_name(ref)
1080
                    except ValueError:
1081
                        pass
1082
                    else:
1083
                        result.tag_conflicts.append((name, revid, ret[name][1]))
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1084
                else:
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1085
                    ret[ref] = (git_sha, revid)
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1086
        return ret
1087
0.200.1493 by Jelmer Vernooij
Test fixes.
1088
    def fetch(self, stop_revision=None, fetch_tags=None, lossy=False, limit=None):
1089
        if stop_revision is None:
1090
            stop_revision = self.source.last_revision()
1091
        ret = []
1092
        if fetch_tags:
1093
            for k, v in self.source.tags.get_tag_dict().iteritems():
1094
                ret.append((None, v))
1095
        ret.append((None, stop_revision))
0.286.6 by Jelmer Vernooij
Pass through limit argument.
1096
        self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
0.200.1493 by Jelmer Vernooij
Test fixes.
1097
0.252.36 by Jelmer Vernooij
Fix pull.
1098
    def pull(self, overwrite=False, stop_revision=None, local=False,
0.200.1131 by Jelmer Vernooij
Accept run_hooks argument to InterToGitBranch.pull().
1099
             possible_transports=None, run_hooks=True):
0.252.36 by Jelmer Vernooij
Fix pull.
1100
        result = GitBranchPullResult()
1101
        result.source_branch = self.source
1102
        result.target_branch = self.target
0.200.1788 by Jelmer Vernooij
Use context managers.
1103
        with self.source.lock_read(), self.target.lock_write():
1104
            new_refs, main_ref, stop_revinfo = self._get_new_refs(
1105
                stop_revision)
1106
            def update_refs(old_refs):
1107
                return self._update_refs(result, old_refs, new_refs, overwrite)
0.200.1353 by Jelmer Vernooij
Run various hooks.
1108
            try:
0.200.1788 by Jelmer Vernooij
Use context managers.
1109
                result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1110
                    update_refs, lossy=False)
1111
            except NoPushSupport:
1112
                raise errors.NoRoundtrippingSupport(self.source, self.target)
1113
            (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1114
            if result.old_revid is None:
1115
                result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1116
            result.new_revid = new_refs[main_ref][1]
1117
            result.local_branch = None
1118
            result.master_branch = self.target
1119
            if run_hooks:
1120
                for hook in branch.Branch.hooks['post_pull']:
1121
                    hook(result)
0.252.36 by Jelmer Vernooij
Fix pull.
1122
        return result
1123
0.200.1260 by Jelmer Vernooij
Cope with new lossy argument.
1124
    def push(self, overwrite=False, stop_revision=None, lossy=False,
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
1125
             _override_hook_source_branch=None):
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
1126
        result = GitBranchPushResult()
1127
        result.source_branch = self.source
1128
        result.target_branch = self.target
0.200.1356 by Jelmer Vernooij
Fix result properties for hook.
1129
        result.local_branch = None
1130
        result.master_branch = result.target_branch
0.200.1788 by Jelmer Vernooij
Use context managers.
1131
        with self.source.lock_read():
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1132
            new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
1133
            def update_refs(old_refs):
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1134
                return self._update_refs(result, old_refs, new_refs, overwrite)
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1135
            try:
1136
                result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1137
                    update_refs, lossy=lossy)
1138
            except NoPushSupport:
1139
                raise errors.NoRoundtrippingSupport(self.source, self.target)
1140
            (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1141
            if result.old_revid is None:
1142
                result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1143
            result.new_revid = new_refs[main_ref][1]
1144
            (result.new_original_revno, result.new_original_revid) = stop_revinfo
1145
            for hook in branch.Branch.hooks['post_push']:
1146
                hook(result)
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
1147
        return result
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
1148
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1149
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1150
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1151
branch.InterBranch.register_optimiser(InterFromGitBranch)
1152
branch.InterBranch.register_optimiser(InterToGitBranch)
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1153
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)