/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
0.358.2 by Jelmer Vernooij
Refresh copyright headers, add my email.
2
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
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
0.358.1 by Jelmer Vernooij
Fix FSF address.
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
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
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
22
from io import BytesIO
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
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
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.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
40
    trace,
0.230.1 by Jelmer Vernooij
Support lightweight checkouts.
41
    transport,
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
42
    urlutils,
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
43
    )
6986.2.3 by Jelmer Vernooij
Merge trunk
44
from ..foreign import ForeignBranch
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
45
from ..revision import (
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
46
    NULL_REVISION,
47
    )
6986.2.3 by Jelmer Vernooij
Merge trunk
48
from ..sixish import (
7018.3.2 by Jelmer Vernooij
Fix some git tests.
49
    text_type,
50
    viewitems,
51
    )
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
52
from ..trace import (
0.200.342 by Jelmer Vernooij
Report git sha during pull.
53
    is_quiet,
0.200.261 by Jelmer Vernooij
More formatting fixes.
54
    mutter,
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
55
    warning,
0.200.261 by Jelmer Vernooij
More formatting fixes.
56
    )
57
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
58
from .config import (
0.200.386 by Jelmer Vernooij
Move config to a separate file, support BranchConfig.username().
59
    GitBranchConfig,
0.200.1472 by Jelmer Vernooij
Provide basic implementation of Branch.get_config_stack.
60
    GitBranchStack,
0.200.386 by Jelmer Vernooij
Move config to a separate file, support BranchConfig.username().
61
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
62
from .errors import (
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
63
    NoPushSupport,
0.200.278 by Jelmer Vernooij
Update branch head appropriately during dpull.
64
    NoSuchRef,
65
    )
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
66
from .push import (
67
    remote_divergence,
68
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
69
from .refs import (
0.408.4 by Jelmer Vernooij
Fix some tests.
70
    branch_name_to_ref,
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
71
    is_tag,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
72
    ref_to_branch_name,
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
73
    ref_to_tag_name,
0.346.1 by Jelmer Vernooij
Fix tag caching.
74
    remote_refs_dict_to_tag_refs,
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
75
    tag_name_to_ref,
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
76
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
77
from .unpeel_map import (
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
78
    UnpeelMap,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
79
    )
0.408.1 by Jelmer Vernooij
Convert Git URLs in stored config to Breezy URLs.
80
from .urls import git_url_to_bzr_url
0.200.261 by Jelmer Vernooij
More formatting fixes.
81
0.200.388 by Jelmer Vernooij
Support bzr 1.14 as well.
82
0.200.261 by Jelmer Vernooij
More formatting fixes.
83
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
84
class GitPullResult(branch.PullResult):
0.200.956 by Jelmer Vernooij
Add some more format tests.
85
    """Result of a pull from a Git branch."""
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
86
87
    def _lookup_revno(self, revid):
6973.13.2 by Jelmer Vernooij
Fix some more tests.
88
        if not isinstance(revid, bytes):
0.361.1 by Jelmer Vernooij
Don't use assert.
89
            raise TypeError(revid)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
90
        # Try in source branch first, it'll be faster
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
91
        with self.target_branch.lock_read():
0.200.1362 by Jelmer Vernooij
Add locking.
92
            return self.target_branch.revision_id_to_revno(revid)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
93
94
    @property
95
    def old_revno(self):
96
        return self._lookup_revno(self.old_revid)
97
98
    @property
99
    def new_revno(self):
100
        return self._lookup_revno(self.new_revid)
101
102
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
103
class GitTags(tag.BasicTags):
104
    """Ref-based tag dictionary."""
0.200.82 by Jelmer Vernooij
Support listing tags.
105
0.200.89 by Jelmer Vernooij
Support sprouting branches.
106
    def __init__(self, branch):
107
        self.branch = branch
108
        self.repository = branch.repository
0.200.82 by Jelmer Vernooij
Support listing tags.
109
0.346.1 by Jelmer Vernooij
Fix tag caching.
110
    def _merge_to_remote_git(self, target_repo, source_tag_refs, overwrite=False):
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
111
        updates = {}
112
        conflicts = []
113
        def get_changed_refs(old_refs):
114
            ret = dict(old_refs)
0.346.1 by Jelmer Vernooij
Fix tag caching.
115
            for ref_name, tag_name, peeled, unpeeled in source_tag_refs.iteritems():
116
                if old_refs.get(ref_name) == unpeeled:
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
117
                    pass
0.346.1 by Jelmer Vernooij
Fix tag caching.
118
                elif overwrite or not ref_name in old_refs:
119
                    ret[ref_name] = unpeeled
120
                    updates[tag_name] = target_repo.lookup_foreign_revision_id(peeled)
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
121
                else:
0.346.1 by Jelmer Vernooij
Fix tag caching.
122
                    conflicts.append(
123
                        (tag_name,
124
                        self.repository.lookup_foreign_revision_id(peeled),
125
                        target_repo.lookup_foreign_revision_id(old_refs[ref_name])))
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
126
            return ret
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
127
        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.
128
        return updates, conflicts
129
0.346.1 by Jelmer Vernooij
Fix tag caching.
130
    def _merge_to_local_git(self, target_repo, source_tag_refs, overwrite=False):
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
131
        conflicts = []
132
        updates = {}
0.346.1 by Jelmer Vernooij
Fix tag caching.
133
        for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
134
            if target_repo._git.refs.get(ref_name) == unpeeled:
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
135
                pass
0.346.1 by Jelmer Vernooij
Fix tag caching.
136
            elif overwrite or not ref_name in target_repo._git.refs:
137
                target_repo._git.refs[ref_name] = unpeeled or peeled
138
                updates[tag_name] = self.repository.lookup_foreign_revision_id(peeled)
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
139
            else:
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
140
                source_revid = self.repository.lookup_foreign_revision_id(peeled)
141
                try:
142
                    target_revid = target_repo.lookup_foreign_revision_id(
143
                            target_repo._git.refs[ref_name])
144
                except KeyError:
145
                    trace.warning('%s does not point to a valid object',
146
                                  ref_name)
147
                    continue
148
                conflicts.append((tag_name, source_revid, target_revid))
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
149
        return updates, conflicts
150
0.346.1 by Jelmer Vernooij
Fix tag caching.
151
    def _merge_to_git(self, to_tags, source_tag_refs, overwrite=False):
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
152
        target_repo = to_tags.repository
153
        if self.repository.has_same_location(target_repo):
154
            return {}, []
0.346.1 by Jelmer Vernooij
Fix tag caching.
155
        try:
156
            if getattr(target_repo, "_git", None):
157
                return self._merge_to_local_git(target_repo, source_tag_refs, overwrite)
158
            else:
159
                return self._merge_to_remote_git(target_repo, source_tag_refs, overwrite)
160
        finally:
161
            to_tags.branch._tag_refs = None
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
162
0.346.1 by Jelmer Vernooij
Fix tag caching.
163
    def _merge_to_non_git(self, to_tags, source_tag_refs, overwrite=False):
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
164
        unpeeled_map = defaultdict(set)
165
        conflicts = []
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
166
        updates = {}
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
167
        result = dict(to_tags.get_tag_dict())
0.346.1 by Jelmer Vernooij
Fix tag caching.
168
        for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
169
            if unpeeled is not None:
170
                unpeeled_map[peeled].add(unpeeled)
0.346.1 by Jelmer Vernooij
Fix tag caching.
171
            try:
172
                bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
173
            except NotCommitError:
174
                continue
175
            if result.get(tag_name) == bzr_revid:
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
176
                pass
0.346.1 by Jelmer Vernooij
Fix tag caching.
177
            elif tag_name not in result or overwrite:
178
                result[tag_name] = bzr_revid
179
                updates[tag_name] = bzr_revid
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
180
            else:
0.346.1 by Jelmer Vernooij
Fix tag caching.
181
                conflicts.append((tag_name, bzr_revid, result[n]))
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
182
        to_tags._set_tag_dict(result)
183
        if len(unpeeled_map) > 0:
184
            map_file = UnpeelMap.from_repository(to_tags.branch.repository)
185
            map_file.update(unpeeled_map)
186
            map_file.save_in_repository(to_tags.branch.repository)
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
187
        return updates, conflicts
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
188
189
    def merge_to(self, to_tags, overwrite=False, ignore_master=False,
0.346.1 by Jelmer Vernooij
Fix tag caching.
190
                 source_tag_refs=None):
0.200.1113 by Jelmer Vernooij
Fix Tags.merge_to.
191
        """See Tags.merge_to."""
0.346.1 by Jelmer Vernooij
Fix tag caching.
192
        if source_tag_refs is None:
193
            source_tag_refs = self.branch.get_tag_refs()
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
194
        if self == to_tags:
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
195
            return {}, []
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
196
        if isinstance(to_tags, GitTags):
0.346.1 by Jelmer Vernooij
Fix tag caching.
197
            return self._merge_to_git(to_tags, source_tag_refs,
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
198
                                      overwrite=overwrite)
199
        else:
200
            if ignore_master:
201
                master = None
202
            else:
203
                master = to_tags.branch.get_master_branch()
204
            if master is not None:
0.331.1 by Jelmer Vernooij
Fix some tags tests.
205
                master.lock_write()
206
            try:
0.346.1 by Jelmer Vernooij
Fix tag caching.
207
                updates, conflicts = self._merge_to_non_git(to_tags, source_tag_refs,
0.331.1 by Jelmer Vernooij
Fix some tags tests.
208
                                                  overwrite=overwrite)
209
                if master is not None:
210
                    extra_updates, extra_conflicts = self.merge_to(
211
                        master.tags, overwrite=overwrite,
0.346.1 by Jelmer Vernooij
Fix tag caching.
212
                                               source_tag_refs=source_tag_refs,
0.331.1 by Jelmer Vernooij
Fix some tags tests.
213
                                               ignore_master=ignore_master)
214
                    updates.update(extra_updates)
215
                    conflicts += extra_conflicts
216
                return updates, conflicts
217
            finally:
218
                if master is not None:
219
                    master.unlock()
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
220
221
    def get_tag_dict(self):
222
        ret = {}
0.346.1 by Jelmer Vernooij
Fix tag caching.
223
        for (ref_name, tag_name, peeled, unpeeled) in self.branch.get_tag_refs():
224
            try:
225
                bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
226
            except NotCommitError:
227
                continue
228
            else:
229
                ret[tag_name] = bzr_revid
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
230
        return ret
231
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
232
233
class LocalGitTagDict(GitTags):
234
    """Dictionary with tags in a local repository."""
235
236
    def __init__(self, branch):
237
        super(LocalGitTagDict, self).__init__(branch)
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
238
        self.refs = self.repository.controldir._git.refs
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
239
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
240
    def _set_tag_dict(self, to_dict):
0.200.1487 by Jelmer Vernooij
Use peeling.
241
        extra = set(self.refs.allkeys())
6973.13.2 by Jelmer Vernooij
Fix some more tests.
242
        for k, revid in viewitems(to_dict):
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
243
            name = tag_name_to_ref(k)
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
244
            if name in extra:
245
                extra.remove(name)
246
            self.set_tag(k, revid)
247
        for name in extra:
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
248
            if is_tag(name):
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
249
                del self.repository._git[name]
0.200.956 by Jelmer Vernooij
Add some more format tests.
250
0.200.86 by Jelmer Vernooij
Clearer error when setting tags.
251
    def set_tag(self, name, revid):
0.200.1369 by Jelmer Vernooij
Clarify that ghost tags are not supported.
252
        try:
253
            git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
254
        except errors.NoSuchRevision:
255
            raise errors.GhostTagsNotSupported(self)
256
        self.refs[tag_name_to_ref(name)] = git_sha
0.346.1 by Jelmer Vernooij
Fix tag caching.
257
        self.branch._tag_refs = None
258
259
    def delete_tag(self, name):
260
        ref = tag_name_to_ref(name)
261
        if not ref in self.refs:
262
            raise errors.NoSuchTag(name)
263
        del self.refs[ref]
264
        self.branch._tag_refs = None
0.239.1 by Jelmer Vernooij
Avoid re-connecting to fetch tags we already know.
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):
6973.6.2 by Jelmer Vernooij
Fix more tests.
270
        return b"git"
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
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.310.16 by Jelmer Vernooij
Update xfail.
334
        return self._control_transport
0.306.1 by Jelmer Vernooij
Set correct segment parameters on branches.
335
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
336
    @property
337
    def user_transport(self):
338
        return self._user_transport
339
0.295.1 by Jelmer Vernooij
Split up branch formats.
340
    def __init__(self, controldir, repository, ref, format):
0.200.82 by Jelmer Vernooij
Support listing tags.
341
        self.repository = repository
0.295.1 by Jelmer Vernooij
Split up branch formats.
342
        self._format = format
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
343
        self.controldir = controldir
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
344
        self._lock_mode = None
345
        self._lock_count = 0
0.231.1 by Jelmer Vernooij
Check that regenerated objects have the expected sha1.
346
        super(GitBranch, self).__init__(repository.get_mapping())
0.200.770 by Jelmer Vernooij
Proper branch names.
347
        self.ref = ref
0.200.1708 by Jelmer Vernooij
Fix to colocated branch tests.
348
        self._head = None
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
349
        self._user_transport = controldir.user_transport.clone('.')
0.310.16 by Jelmer Vernooij
Update xfail.
350
        self._control_transport = controldir.control_transport.clone('.')
0.346.1 by Jelmer Vernooij
Fix tag caching.
351
        self._tag_refs = None
0.306.1 by Jelmer Vernooij
Set correct segment parameters on branches.
352
        params = {}
0.200.1361 by Jelmer Vernooij
Support branches where the ref can't be mapped back to a branch name.
353
        try:
354
            self.name = ref_to_branch_name(ref)
355
        except ValueError:
356
            self.name = None
0.200.1708 by Jelmer Vernooij
Fix to colocated branch tests.
357
            if self.ref is not None:
0.310.16 by Jelmer Vernooij
Update xfail.
358
                params = {"ref": urlutils.escape(self.ref)}
0.200.1708 by Jelmer Vernooij
Fix to colocated branch tests.
359
        else:
360
            if self.name != "":
0.310.16 by Jelmer Vernooij
Update xfail.
361
                params = {"branch": urlutils.escape(self.name)}
362
        for k, v in params.items():
363
            self._user_transport.set_segment_parameter(k, v)
364
            self._control_transport.set_segment_parameter(k, v)
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
365
        self.base = controldir.user_transport.base
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
366
0.200.1360 by Jelmer Vernooij
Support lighweight argument to _get_checkout_format.
367
    def _get_checkout_format(self, lightweight=False):
0.239.8 by Jelmer Vernooij
Support checkouts.
368
        """Return the most suitable metadir for a checkout of this branch.
369
        Weaves are used if this branch's repository uses weaves.
370
        """
0.311.1 by Jelmer Vernooij
Support git lightweight checkouts.
371
        if lightweight:
372
            return controldir.format_registry.make_controldir("git")
373
        else:
374
            return controldir.format_registry.make_controldir("default")
0.239.8 by Jelmer Vernooij
Support checkouts.
375
0.238.3 by Jelmer Vernooij
Remove svn references, prefer git send format when submitting changes against a git branch.
376
    def get_child_submit_format(self):
377
        """Return the preferred format of submissions to this branch."""
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
378
        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.
379
        if ret is not None:
380
            return ret
381
        return "git"
382
0.200.1397 by Jelmer Vernooij
Fix use of get_config() for RemoteGitBranch.
383
    def get_config(self):
384
        return GitBranchConfig(self)
385
0.200.1472 by Jelmer Vernooij
Provide basic implementation of Branch.get_config_stack.
386
    def get_config_stack(self):
387
        return GitBranchStack(self)
388
0.200.293 by Jelmer Vernooij
Fix branch nicks.
389
    def _get_nick(self, local=False, possible_master_transports=None):
390
        """Find the nick name for this branch.
391
392
        :return: Branch nick
393
        """
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
394
        cs = self.repository._git.get_config_stack()
395
        try:
0.200.1694 by Jelmer Vernooij
Fix nick test.
396
            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.
397
        except KeyError:
398
            pass
0.200.1694 by Jelmer Vernooij
Fix nick test.
399
        return self.name or u"HEAD"
0.200.293 by Jelmer Vernooij
Fix branch nicks.
400
0.200.331 by Jelmer Vernooij
Add stub for setting nick function.
401
    def _set_nick(self, nick):
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
402
        cf = self.repository._git.get_config()
0.200.1694 by Jelmer Vernooij
Fix nick test.
403
        cf.set((b"branch", self.name.encode('utf-8')), b"nick", nick.encode("utf-8"))
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
404
        f = BytesIO()
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
405
        cf.write_to_file(f)
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
406
        self.repository._git._put_named_file('config', f.getvalue())
0.200.331 by Jelmer Vernooij
Add stub for setting nick function.
407
408
    nick = property(_get_nick, _set_nick)
0.200.293 by Jelmer Vernooij
Fix branch nicks.
409
0.200.412 by Jelmer Vernooij
Implement GitBranch.__repr__.
410
    def __repr__(self):
0.200.770 by Jelmer Vernooij
Proper branch names.
411
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
0.200.1311 by Jelmer Vernooij
More work on colocated branch support.
412
            self.name)
0.200.412 by Jelmer Vernooij
Implement GitBranch.__repr__.
413
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
414
    def generate_revision_history(self, revid, last_rev=None, other_branch=None):
415
        if last_rev is not None:
416
            graph = self.repository.get_graph()
417
            if not graph.is_ancestor(last_rev, revid):
418
                # our previous tip is not merged into stop_revision
419
                raise errors.DivergedBranches(self, other_branch)
420
0.297.2 by Jelmer Vernooij
Simplify Branch.generate_revision_history.
421
        self.set_last_revision(revid)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
422
0.200.1199 by Jelmer Vernooij
Support 'token' argument to Branch.lock_write.
423
    def lock_write(self, token=None):
424
        if token is not None:
425
            raise errors.TokenLockingNotSupported(self)
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
426
        if self._lock_mode:
0.200.1369 by Jelmer Vernooij
Clarify that ghost tags are not supported.
427
            if self._lock_mode == 'r':
428
                raise errors.ReadOnlyError(self)
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
429
            self._lock_count += 1
430
        else:
0.383.1 by Jelmer Vernooij
Fix a bunch of locking issues.
431
            self._lock_ref()
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
432
            self._lock_mode = 'w'
433
            self._lock_count = 1
434
        self.repository.lock_write()
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
435
        return lock.LogicalLockResult(self.unlock)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
436
0.200.1453 by Jelmer Vernooij
Provide Branch.leave_lock_in_place and Branch.dont_leave_lock_in_place.
437
    def leave_lock_in_place(self):
438
        raise NotImplementedError(self.leave_lock_in_place)
439
440
    def dont_leave_lock_in_place(self):
441
        raise NotImplementedError(self.dont_leave_lock_in_place)
442
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
443
    def get_stacked_on_url(self):
444
        # Git doesn't do stacking (yet...)
0.200.1660 by Jelmer Vernooij
Fix imports.
445
        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.
446
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
447
    def _get_parent_location(self):
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
448
        """See Branch.get_parent()."""
0.200.312 by Jelmer Vernooij
Add notes about parent locations.
449
        # FIXME: Set "origin" url from .git/config ?
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
450
        cs = self.repository._git.get_config_stack()
451
        try:
0.408.1 by Jelmer Vernooij
Convert Git URLs in stored config to Breezy URLs.
452
            location = cs.get((b"remote", b'origin'), b"url")
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
453
        except KeyError:
454
            return None
0.408.4 by Jelmer Vernooij
Fix some tests.
455
456
        params = {}
457
        try:
458
            ref = cs.get((b"remote", b"origin"), b"merge")
459
        except KeyError:
460
            pass
0.408.1 by Jelmer Vernooij
Convert Git URLs in stored config to Breezy URLs.
461
        else:
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
462
            if ref != b'HEAD':
0.408.4 by Jelmer Vernooij
Fix some tests.
463
                try:
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
464
                    params['branch'] = urlutils.escape(ref_to_branch_name(ref))
0.408.4 by Jelmer Vernooij
Fix some tests.
465
                except ValueError:
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
466
                    params['ref'] = urlutils.quote_from_bytes(ref)
0.408.4 by Jelmer Vernooij
Fix some tests.
467
7045.3.1 by Jelmer Vernooij
Fix another ~500 tests.
468
        url = git_url_to_bzr_url(location.decode('utf-8'))
0.408.4 by Jelmer Vernooij
Fix some tests.
469
        return urlutils.join_segment_parameters(url, params)
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
470
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
471
    def set_parent(self, location):
0.200.312 by Jelmer Vernooij
Add notes about parent locations.
472
        # FIXME: Set "origin" url in .git/config ?
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
473
        cs = self.repository._git.get_config()
0.408.4 by Jelmer Vernooij
Fix some tests.
474
        this_url = urlutils.split_segment_parameters(self.user_url)[0]
475
        target_url, target_params = urlutils.split_segment_parameters(location)
476
        location = urlutils.relative_url(this_url, target_url)
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
477
        cs.set((b"remote", b"origin"), b"url", location)
0.408.4 by Jelmer Vernooij
Fix some tests.
478
        if 'branch' in target_params:
479
            cs.set((b"remote", b"origin"), b"merge",
480
                   branch_name_to_ref(target_params['branch']))
481
        elif 'ref' in target_params:
482
            cs.set((b"remote", b"origin"), b"merge",
483
                   target_params['ref'])
484
        else:
485
            # TODO(jelmer): Maybe unset rather than setting to HEAD?
486
            cs.set((b"remote", b"origin"), b"merge", 'HEAD')
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
487
        f = BytesIO()
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
488
        cs.write_to_file(f)
489
        self.repository._git._put_named_file('config', f.getvalue())
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
490
0.200.1411 by Jelmer Vernooij
Fix control files.
491
    def break_lock(self):
492
        raise NotImplementedError(self.break_lock)
493
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
494
    def lock_read(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
495
        if self._lock_mode:
0.361.1 by Jelmer Vernooij
Don't use assert.
496
            if self._lock_mode not in ('r', 'w'):
497
                raise ValueError(self._lock_mode)
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
498
            self._lock_count += 1
499
        else:
500
            self._lock_mode = 'r'
501
            self._lock_count = 1
502
        self.repository.lock_read()
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
503
        return lock.LogicalLockResult(self.unlock)
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
504
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
505
    def peek_lock_mode(self):
506
        return self._lock_mode
507
0.200.432 by Jelmer Vernooij
Support Branch.is_locked, required for loggerhead.
508
    def is_locked(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
509
        return (self._lock_mode is not None)
0.200.432 by Jelmer Vernooij
Support Branch.is_locked, required for loggerhead.
510
0.383.1 by Jelmer Vernooij
Fix a bunch of locking issues.
511
    def _lock_ref(self):
512
        pass
513
514
    def _unlock_ref(self):
515
        pass
516
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
517
    def unlock(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
518
        """See Branch.unlock()."""
519
        if self._lock_count == 0:
0.383.1 by Jelmer Vernooij
Fix a bunch of locking issues.
520
            raise errors.LockNotHeld(self)
521
        try:
522
            self._lock_count -= 1
523
            if self._lock_count == 0:
524
                if self._lock_mode == 'w':
525
                    self._unlock_ref()
526
                self._lock_mode = None
527
                self._clear_cached_state()
528
        finally:
529
            self.repository.unlock()
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
530
531
    def get_physical_lock_status(self):
532
        return False
533
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
534
    def last_revision(self):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
535
        with self.lock_read():
536
            # perhaps should escape this ?
537
            if self.head is None:
538
                return revision.NULL_REVISION
539
            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.
540
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
541
    def _basic_push(self, target, overwrite=False, stop_revision=None):
542
        return branch.InterBranch.get(self, target)._basic_push(
543
            overwrite, stop_revision)
544
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
545
    def lookup_foreign_revision_id(self, foreign_revid):
0.200.1760 by Jelmer Vernooij
Fall back to simple revision id generation.
546
        try:
547
            return self.repository.lookup_foreign_revision_id(foreign_revid,
548
                self.mapping)
549
        except KeyError:
550
            # Let's try..
551
            return self.mapping.revision_id_foreign_to_bzr(foreign_revid)
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
552
0.200.1030 by Jelmer Vernooij
More work on supporting roundtripping push.
553
    def lookup_bzr_revision_id(self, revid):
554
        return self.repository.lookup_bzr_revision_id(
555
            revid, mapping=self.mapping)
556
0.200.1678 by Jelmer Vernooij
Fix tests.
557
    def get_unshelver(self, tree):
558
        raise errors.StoringUncommittedNotSupported(self)
559
0.346.1 by Jelmer Vernooij
Fix tag caching.
560
    def _clear_cached_state(self):
561
        super(GitBranch, self)._clear_cached_state()
562
        self._tag_refs = None
563
564
    def _iter_tag_refs(self, refs):
565
        """Iterate over the tag refs.
566
567
        :param refs: Refs dictionary (name -> git sha1)
568
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
569
        """
570
        raise NotImplementedError(self._iter_tag_refs)
571
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
572
    def get_tag_refs(self):
573
        with self.lock_read():
574
            if self._tag_refs is None:
575
                self._tag_refs = list(self._iter_tag_refs())
576
            return self._tag_refs
577
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
578
0.200.465 by Jelmer Vernooij
Use dulwich standard functionality for finding missing revisions.
579
class LocalGitBranch(GitBranch):
580
    """A local Git branch."""
581
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
582
    def __init__(self, controldir, repository, ref):
0.295.1 by Jelmer Vernooij
Split up branch formats.
583
        super(LocalGitBranch, self).__init__(controldir, repository, ref,
584
                LocalGitBranchFormat())
0.200.763 by Jelmer Vernooij
Provide proper colocated branch support.
585
0.200.261 by Jelmer Vernooij
More formatting fixes.
586
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
587
        accelerator_tree=None, hardlink=False):
0.200.1774 by Jelmer Vernooij
Simplify checkout creation.
588
        t = transport.get_transport(to_location)
589
        t.ensure_base()
590
        format = self._get_checkout_format(lightweight=lightweight)
591
        checkout = format.initialize_on_transport(t)
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
592
        if lightweight:
0.200.1774 by Jelmer Vernooij
Simplify checkout creation.
593
            from_branch = checkout.set_branch_reference(target_branch=self)
594
        else:
595
            policy = checkout.determine_repository_policy()
596
            repo = policy.acquire_repository()[0]
597
598
            checkout_branch = checkout.create_branch()
599
            checkout_branch.bind(self)
600
            checkout_branch.pull(self, stop_revision=revision_id)
601
            from_branch = None
602
        return checkout.create_workingtree(revision_id,
0.230.1 by Jelmer Vernooij
Support lightweight checkouts.
603
                from_branch=from_branch, hardlink=hardlink)
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
604
0.383.1 by Jelmer Vernooij
Fix a bunch of locking issues.
605
    def _lock_ref(self):
606
        self._ref_lock = self.repository._git.refs.lock_ref(self.ref)
607
608
    def _unlock_ref(self):
609
        self._ref_lock.unlock()
610
0.412.1 by Jelmer Vernooij
Implement Branch.break_lock.
611
    def break_lock(self):
612
        self.repository._git.refs.unlock_ref(self.ref)
613
0.200.1493 by Jelmer Vernooij
Test fixes.
614
    def fetch(self, from_branch, last_revision=None, limit=None):
615
        return branch.InterBranch.get(from_branch, self).fetch(
616
            stop_revision=last_revision, limit=limit)
617
0.200.57 by Jelmer Vernooij
Fix more tests.
618
    def _gen_revision_history(self):
0.200.58 by Jelmer Vernooij
Fix remaining tests.
619
        if self.head is None:
620
            return []
6968.1.1 by Jelmer Vernooij
Support 'bzr version-info' in horizon branches.
621
        last_revid = self.last_revision()
0.200.1279 by Jelmer Vernooij
Avoid using deprecated Repository.iter_reverse_revision_history.
622
        graph = self.repository.get_graph()
6968.1.1 by Jelmer Vernooij
Support 'bzr version-info' in horizon branches.
623
        try:
624
            ret = list(graph.iter_lefthand_ancestry(last_revid,
625
                (revision.NULL_REVISION, )))
626
        except errors.RevisionNotPresent as e:
627
            raise errors.GhostRevisionsHaveNoRevno(last_revid, e.revision_id)
0.200.59 by Jelmer Vernooij
Add more tests, fix revision history.
628
        ret.reverse()
0.200.57 by Jelmer Vernooij
Fix more tests.
629
        return ret
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
630
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
631
    def _get_head(self):
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
632
        try:
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
633
            return self.repository._git.refs[self.ref]
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
634
        except KeyError:
635
            return None
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
636
0.200.1228 by Jelmer Vernooij
Provide Branch._read_last_revision_info.
637
    def _read_last_revision_info(self):
638
        last_revid = self.last_revision()
639
        graph = self.repository.get_graph()
7143.8.1 by Jelmer Vernooij
Cope with the revno not being known.
640
        try:
641
            revno = graph.find_distance_to_null(last_revid,
642
                [(revision.NULL_REVISION, 0)])
643
        except errors.GhostRevisionsHaveNoRevno:
644
            revno = None
0.200.1228 by Jelmer Vernooij
Provide Branch._read_last_revision_info.
645
        return revno, last_revid
646
647
    def set_last_revision_info(self, revno, revision_id):
648
        self.set_last_revision(revision_id)
649
        self._last_revision_info_cache = revno, revision_id
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
650
651
    def set_last_revision(self, revid):
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
652
        if not revid or not isinstance(revid, bytes):
0.200.1233 by Jelmer Vernooij
Implement Repository.iter_files_bytes.
653
            raise errors.InvalidRevisionId(revision_id=revid, branch=self)
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
654
        if revid == NULL_REVISION:
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
655
            newhead = None
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
656
        else:
657
            (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
658
            if self.mapping is None:
659
                raise AssertionError
660
        self._set_head(newhead)
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
661
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
662
    def _set_head(self, value):
0.361.1 by Jelmer Vernooij
Don't use assert.
663
        if value == ZERO_SHA:
664
            raise ValueError(value)
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
665
        self._head = value
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
666
        if value is None:
667
            del self.repository._git.refs[self.ref]
668
        else:
669
            self.repository._git.refs[self.ref] = self._head
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
670
        self._clear_cached_state()
671
672
    head = property(_get_head, _set_head)
673
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
674
    def get_push_location(self):
675
        """See Branch.get_push_location."""
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
676
        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.
677
        return push_loc
678
679
    def set_push_location(self, location):
680
        """See Branch.set_push_location."""
0.200.19 by John Arbash Meinel
More refactoring. Add some direct tests for GitModel.
681
        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.
682
                                          store=config.STORE_LOCATION)
0.200.43 by David Allouche
Ultra-experimental support for "bzr pull". No test. No sanity.
683
684
    def supports_tags(self):
0.200.82 by Jelmer Vernooij
Support listing tags.
685
        return True
0.200.956 by Jelmer Vernooij
Add some more format tests.
686
0.200.1681 by Jelmer Vernooij
Provide Branch.store_uncommitted.
687
    def store_uncommitted(self, creator):
688
        raise errors.StoringUncommittedNotSupported(self)
689
0.346.1 by Jelmer Vernooij
Fix tag caching.
690
    def _iter_tag_refs(self):
691
        """Iterate over the tag refs.
692
693
        :param refs: Refs dictionary (name -> git sha1)
694
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
695
        """
696
        refs = self.repository._git.refs
7018.3.2 by Jelmer Vernooij
Fix some git tests.
697
        for ref_name, unpeeled in viewitems(refs.as_dict()):
0.346.1 by Jelmer Vernooij
Fix tag caching.
698
            try:
699
                tag_name = ref_to_tag_name(ref_name)
700
            except (ValueError, UnicodeDecodeError):
701
                continue
702
            peeled = refs.get_peeled(ref_name)
703
            if peeled is None:
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
704
                peeled = unpeeled
6973.6.2 by Jelmer Vernooij
Fix more tests.
705
            if not isinstance(tag_name, text_type):
0.361.1 by Jelmer Vernooij
Don't use assert.
706
                raise TypeError(tag_name)
0.346.1 by Jelmer Vernooij
Fix tag caching.
707
            yield (ref_name, tag_name, peeled, unpeeled)
708
0.360.1 by Jelmer Vernooij
Implement GitMemoryTree.
709
    def create_memorytree(self):
710
        from .memorytree import GitMemoryTree
711
        return GitMemoryTree(self, self.repository._git.object_store, self.head)
712
0.429.10 by Jelmer Vernooij
use new read_submodule_head from dulwich.
713
    def reference_parent(self, path, file_id=None, possible_transports=None):
714
        """Return the parent branch for a tree-reference file_id
715
716
        :param path: The path of the file_id in the tree
717
        :param file_id: Optional file_id of the tree reference
718
        :return: A branch associated with the file_id
719
        """
720
        # FIXME should provide multiple branches, based on config
0.429.18 by Jelmer Vernooij
Fix reference_parent tets.
721
        url = urlutils.join(self.user_url, path)
722
        return branch.Branch.open(
723
                url,
724
                possible_transports=possible_transports)
725
0.429.10 by Jelmer Vernooij
use new read_submodule_head from dulwich.
726
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
727
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
728
def _quick_lookup_revno(local_branch, remote_branch, revid):
6973.13.2 by Jelmer Vernooij
Fix some more tests.
729
    if not isinstance(revid, bytes):
0.361.1 by Jelmer Vernooij
Don't use assert.
730
        raise TypeError(revid)
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
731
    # Try in source branch first, it'll be faster
0.200.1788 by Jelmer Vernooij
Use context managers.
732
    with local_branch.lock_read():
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
733
        try:
0.200.1362 by Jelmer Vernooij
Add locking.
734
            return local_branch.revision_id_to_revno(revid)
735
        except errors.NoSuchRevision:
736
            graph = local_branch.repository.get_graph()
737
            try:
738
                return graph.find_distance_to_null(revid,
739
                    [(revision.NULL_REVISION, 0)])
740
            except errors.GhostRevisionsHaveNoRevno:
741
                # FIXME: Check using graph.find_distance_to_null() ?
0.200.1788 by Jelmer Vernooij
Use context managers.
742
                with remote_branch.lock_read():
0.200.1362 by Jelmer Vernooij
Add locking.
743
                    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.
744
745
0.200.342 by Jelmer Vernooij
Report git sha during pull.
746
class GitBranchPullResult(branch.PullResult):
747
0.252.36 by Jelmer Vernooij
Fix pull.
748
    def __init__(self):
749
        super(GitBranchPullResult, self).__init__()
750
        self.new_git_head = None
751
        self._old_revno = None
752
        self._new_revno = None
753
0.200.342 by Jelmer Vernooij
Report git sha during pull.
754
    def report(self, to_file):
755
        if not is_quiet():
756
            if self.old_revid == self.new_revid:
757
                to_file.write('No revisions to pull.\n')
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
758
            elif self.new_git_head is not None:
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
759
                to_file.write('Now on revision %d (git sha: %s).\n' %
0.200.342 by Jelmer Vernooij
Report git sha during pull.
760
                        (self.new_revno, self.new_git_head))
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
761
            else:
762
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
0.200.342 by Jelmer Vernooij
Report git sha during pull.
763
        self._show_tag_conficts(to_file)
764
0.252.36 by Jelmer Vernooij
Fix pull.
765
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
766
        return _quick_lookup_revno(self.target_branch, self.source_branch,
0.200.1513 by Jelmer Vernooij
Cope with zero shas.
767
            revid)
0.252.36 by Jelmer Vernooij
Fix pull.
768
769
    def _get_old_revno(self):
770
        if self._old_revno is not None:
771
            return self._old_revno
772
        return self._lookup_revno(self.old_revid)
773
774
    def _set_old_revno(self, revno):
775
        self._old_revno = revno
776
777
    old_revno = property(_get_old_revno, _set_old_revno)
778
779
    def _get_new_revno(self):
780
        if self._new_revno is not None:
781
            return self._new_revno
782
        return self._lookup_revno(self.new_revid)
783
784
    def _set_new_revno(self, revno):
785
        self._new_revno = revno
0.200.956 by Jelmer Vernooij
Add some more format tests.
786
0.252.36 by Jelmer Vernooij
Fix pull.
787
    new_revno = property(_get_new_revno, _set_new_revno)
788
0.200.342 by Jelmer Vernooij
Report git sha during pull.
789
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
790
class GitBranchPushResult(branch.BranchPushResult):
791
792
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
793
        return _quick_lookup_revno(self.source_branch, self.target_branch,
794
            revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
795
796
    @property
797
    def old_revno(self):
798
        return self._lookup_revno(self.old_revid)
799
800
    @property
801
    def new_revno(self):
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
802
        new_original_revno = getattr(self, "new_original_revno", None)
803
        if new_original_revno:
804
            return new_original_revno
805
        if getattr(self, "new_original_revid", None) is not None:
806
            return self._lookup_revno(self.new_original_revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
807
        return self._lookup_revno(self.new_revid)
808
809
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
810
class InterFromGitBranch(branch.GenericInterBranch):
0.200.261 by Jelmer Vernooij
More formatting fixes.
811
    """InterBranch implementation that pulls from Git into bzr."""
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
812
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
813
    @staticmethod
814
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
815
        try:
816
            default_format = branch.format_registry.get_default()
817
        except AttributeError:
818
            default_format = branch.BranchFormat._default_format
0.295.4 by Jelmer Vernooij
Fix imports.
819
        from .remote import RemoteGitBranchFormat
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
820
        return [
0.295.1 by Jelmer Vernooij
Split up branch formats.
821
            (RemoteGitBranchFormat(), default_format),
822
            (LocalGitBranchFormat(), default_format)]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
823
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
824
    @classmethod
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
825
    def _get_interrepo(self, source, target):
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
826
        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.
827
828
    @classmethod
829
    def is_compatible(cls, source, target):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
830
        if not isinstance(source, GitBranch):
831
            return False
832
        if isinstance(target, GitBranch):
833
            # InterLocalGitRemoteGitBranch or InterToGitBranch should be used
834
            return False
835
        if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
836
            # fetch_objects is necessary for this to work
837
            return False
838
        return True
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
839
0.200.1305 by Jelmer Vernooij
Only actually fetch tags if "branch.fetch_tags" is set to true.
840
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
841
        self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
842
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
843
    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.
844
        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.
845
        if fetch_tags is None:
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
846
            c = self.source.get_config_stack()
847
            fetch_tags = c.get('branch.fetch_tags')
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
848
        def determine_wants(heads):
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
849
            if stop_revision is None:
0.336.6 by Jelmer Vernooij
Fix pull tests.
850
                try:
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
851
                    head = heads[self.source.ref]
0.336.6 by Jelmer Vernooij
Fix pull tests.
852
                except KeyError:
853
                    self._last_revid = revision.NULL_REVISION
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
854
                else:
0.336.6 by Jelmer Vernooij
Fix pull tests.
855
                    self._last_revid = self.source.lookup_foreign_revision_id(head)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
856
            else:
857
                self._last_revid = stop_revision
858
            real = interrepo.get_determine_wants_revids(
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
859
                [self._last_revid], include_tags=fetch_tags)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
860
            return real(heads)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
861
        pack_hint, head, refs = interrepo.fetch_objects(
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
862
            determine_wants, self.source.mapping, limit=limit)
0.252.45 by Jelmer Vernooij
Finish fetching roundtripped revisions back into bzr.
863
        if (pack_hint is not None and
864
            self.target.repository._format.pack_compresses):
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
865
            self.target.repository.pack(hint=pack_hint)
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
866
        return head, refs
867
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
868
    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.
869
        head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
870
        if overwrite:
0.200.314 by Jelmer Vernooij
Support stop_revision.
871
            prev_last_revid = None
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
872
        else:
0.200.314 by Jelmer Vernooij
Support stop_revision.
873
            prev_last_revid = self.target.last_revision()
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
874
        self.target.generate_revision_history(self._last_revid,
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
875
            last_rev=prev_last_revid, other_branch=self.source)
0.200.1062 by Jelmer Vernooij
Pass remote refs along in _update_revisions.
876
        return head, refs
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
877
0.200.1423 by Jelmer Vernooij
Fix space.
878
    def _basic_pull(self, stop_revision, overwrite, run_hooks,
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
879
              _override_hook_target, _hook_master):
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
880
        if overwrite is True:
881
            overwrite = set(["history", "tags"])
882
        else:
883
            overwrite = set()
0.200.342 by Jelmer Vernooij
Report git sha during pull.
884
        result = GitBranchPullResult()
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
885
        result.source_branch = self.source
886
        if _override_hook_target is None:
887
            result.target_branch = self.target
888
        else:
889
            result.target_branch = _override_hook_target
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
890
        with self.target.lock_write(), self.source.lock_read():
891
            # We assume that during 'pull' the target repository is closer than
892
            # the source one.
893
            (result.old_revno, result.old_revid) = \
894
                self.target.last_revision_info()
895
            result.new_git_head, remote_refs = self._update_revisions(
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
896
                stop_revision, overwrite=("history" in overwrite))
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
897
            tags_ret  = self.source.tags.merge_to(
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
898
                    self.target.tags, ("tags" in overwrite), ignore_master=True)
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
899
            if isinstance(tags_ret, tuple):
900
                result.tag_updates, result.tag_conflicts = tags_ret
901
            else:
902
                result.tag_conflicts = tags_ret
903
            (result.new_revno, result.new_revid) = \
904
                self.target.last_revision_info()
905
            if _hook_master:
906
                result.master_branch = _hook_master
907
                result.local_branch = result.target_branch
908
            else:
909
                result.master_branch = result.target_branch
910
                result.local_branch = None
911
            if run_hooks:
912
                for hook in branch.Branch.hooks['post_pull']:
913
                    hook(result)
914
            return result
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
915
916
    def pull(self, overwrite=False, stop_revision=None,
917
             possible_transports=None, _hook_master=None, run_hooks=True,
918
             _override_hook_target=None, local=False):
919
        """See Branch.pull.
920
921
        :param _hook_master: Private parameter - set the branch to
922
            be supplied as the master to pull hooks.
923
        :param run_hooks: Private parameter - if false, this branch
924
            is being called because it's the master of the primary branch,
925
            so it should not run its hooks.
926
        :param _override_hook_target: Private parameter - set the branch to be
927
            supplied as the target_branch to pull hooks.
928
        """
929
        # This type of branch can't be bound.
930
        bound_location = self.target.get_bound_location()
931
        if local and not bound_location:
932
            raise errors.LocalRequiresBoundBranch()
933
        master_branch = None
934
        source_is_master = False
935
        self.source.lock_read()
936
        if bound_location:
937
            # bound_location comes from a config file, some care has to be
938
            # taken to relate it to source.user_url
939
            normalized = urlutils.normalize_url(bound_location)
940
            try:
941
                relpath = self.source.user_transport.relpath(normalized)
942
                source_is_master = (relpath == '')
0.200.1660 by Jelmer Vernooij
Fix imports.
943
            except (errors.PathNotChild, urlutils.InvalidURL):
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
944
                source_is_master = False
945
        if not local and bound_location and not source_is_master:
946
            # not pulling from master, so we need to update master.
947
            master_branch = self.target.get_master_branch(possible_transports)
948
            master_branch.lock_write()
949
        try:
950
            try:
951
                if master_branch:
952
                    # pull from source into master.
953
                    master_branch.pull(self.source, overwrite, stop_revision,
954
                        run_hooks=False)
955
                result = self._basic_pull(stop_revision, overwrite, run_hooks,
956
                    _override_hook_target, _hook_master=master_branch)
957
            finally:
958
                self.source.unlock()
959
        finally:
960
            if master_branch:
961
                master_branch.unlock()
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
962
        return result
963
0.331.1 by Jelmer Vernooij
Fix some tags tests.
964
    def _basic_push(self, overwrite, stop_revision):
965
        if overwrite is True:
966
            overwrite = set(["history", "tags"])
967
        else:
968
            overwrite = set()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
969
        result = branch.BranchPushResult()
970
        result.source_branch = self.source
971
        result.target_branch = self.target
972
        result.old_revno, result.old_revid = self.target.last_revision_info()
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
973
        result.new_git_head, remote_refs = self._update_revisions(
0.331.1 by Jelmer Vernooij
Fix some tags tests.
974
            stop_revision, overwrite=("history" in overwrite))
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
975
        tags_ret = self.source.tags.merge_to(self.target.tags,
0.331.1 by Jelmer Vernooij
Fix some tags tests.
976
            "tags" in overwrite, ignore_master=True)
977
        (result.tag_updates, result.tag_conflicts) = tags_ret
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
978
        result.new_revno, result.new_revid = self.target.last_revision_info()
979
        return result
980
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
981
0.200.512 by Jelmer Vernooij
Support pushing git->git.
982
class InterGitBranch(branch.GenericInterBranch):
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
983
    """InterBranch implementation that pulls between Git branches."""
984
0.200.1493 by Jelmer Vernooij
Test fixes.
985
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
986
        raise NotImplementedError(self.fetch)
987
0.200.512 by Jelmer Vernooij
Support pushing git->git.
988
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
989
class InterLocalGitRemoteGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
990
    """InterBranch that copies from a local to a remote git branch."""
991
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
992
    @staticmethod
993
    def _get_branch_formats_to_test():
0.295.4 by Jelmer Vernooij
Fix imports.
994
        from .remote import RemoteGitBranchFormat
0.295.3 by Jelmer Vernooij
Fix some more tests.
995
        return [
996
            (LocalGitBranchFormat(), RemoteGitBranchFormat())]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
997
0.200.512 by Jelmer Vernooij
Support pushing git->git.
998
    @classmethod
999
    def is_compatible(self, source, target):
0.200.1644 by Jelmer Vernooij
More relative imports.
1000
        from .remote import RemoteGitBranch
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1001
        return (isinstance(source, LocalGitBranch) and
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1002
                isinstance(target, RemoteGitBranch))
1003
0.331.1 by Jelmer Vernooij
Fix some tags tests.
1004
    def _basic_push(self, overwrite, stop_revision):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1005
        result = GitBranchPushResult()
1006
        result.source_branch = self.source
1007
        result.target_branch = self.target
1008
        if stop_revision is None:
1009
            stop_revision = self.source.last_revision()
1010
        def get_changed_refs(old_refs):
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
1011
            old_ref = old_refs.get(self.target.ref, None)
1012
            if old_ref is None:
1013
                result.old_revid = revision.NULL_REVISION
1014
            else:
1015
                result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
1016
            new_ref = self.source.repository.lookup_bzr_revision_id(stop_revision)[0]
1017
            if not overwrite:
1018
                if remote_divergence(old_ref, new_ref, self.source.repository._git.object_store):
1019
                    raise errors.DivergedBranches(self.source, self.target)
1020
            refs = { self.target.ref: new_ref }
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1021
            result.new_revid = stop_revision
7018.3.8 by Jelmer Vernooij
Disable some flaky tests on python3, allow running without fastimport.
1022
            for name, sha in viewitems(self.source.repository._git.refs.as_dict(b"refs/tags")):
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
1023
                refs[tag_name_to_ref(name)] = sha
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1024
            return refs
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1025
        self.target.repository.send_pack(get_changed_refs,
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
1026
            self.source.repository._git.object_store.generate_pack_data)
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1027
        return result
1028
1029
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1030
class InterGitLocalGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1031
    """InterBranch that copies from a remote to a local git branch."""
1032
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
1033
    @staticmethod
1034
    def _get_branch_formats_to_test():
0.295.4 by Jelmer Vernooij
Fix imports.
1035
        from .remote import RemoteGitBranchFormat
0.295.3 by Jelmer Vernooij
Fix some more tests.
1036
        return [
1037
            (RemoteGitBranchFormat(), LocalGitBranchFormat()),
1038
            (LocalGitBranchFormat(), LocalGitBranchFormat())]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
1039
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1040
    @classmethod
1041
    def is_compatible(self, source, target):
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1042
        return (isinstance(source, GitBranch) and
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1043
                isinstance(target, LocalGitBranch))
1044
0.200.1534 by Jelmer Vernooij
Implement fetch between git branches, encode nicks.
1045
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
1046
        interrepo = _mod_repository.InterRepository.get(self.source.repository,
1047
            self.target.repository)
1048
        if stop_revision is None:
1049
            stop_revision = self.source.last_revision()
1050
        determine_wants = interrepo.get_determine_wants_revids(
1051
            [stop_revision], include_tags=fetch_tags)
1052
        interrepo.fetch_objects(determine_wants, limit=limit)
1053
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1054
    def _basic_push(self, overwrite=False, stop_revision=None):
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1055
        if overwrite is True:
1056
            overwrite = set(["history", "tags"])
1057
        else:
1058
            overwrite = set()
0.200.1325 by Jelmer Vernooij
More test fixes.
1059
        result = GitBranchPushResult()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1060
        result.source_branch = self.source
1061
        result.target_branch = self.target
1062
        result.old_revid = self.target.last_revision()
1063
        refs, stop_revision = self.update_refs(stop_revision)
0.296.3 by Jelmer Vernooij
Update xfail.
1064
        self.target.generate_revision_history(stop_revision,
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1065
                (result.old_revid if ("history" not in overwrite) else None),
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
1066
                other_branch=self.source)
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
1067
        tags_ret = self.source.tags.merge_to(self.target.tags,
0.346.1 by Jelmer Vernooij
Fix tag caching.
1068
            source_tag_refs=remote_refs_dict_to_tag_refs(refs),
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1069
            overwrite=("tags" in overwrite))
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
1070
        if isinstance(tags_ret, tuple):
1071
            (result.tag_updates, result.tag_conflicts) = tags_ret
1072
        else:
1073
            result.tag_conflicts = tags_ret
0.200.505 by Jelmer Vernooij
Remove duplicate code.
1074
        result.new_revid = self.target.last_revision()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1075
        return result
1076
1077
    def update_refs(self, stop_revision=None):
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1078
        interrepo = _mod_repository.InterRepository.get(
1079
                self.source.repository, self.target.repository)
1080
        c = self.source.get_config_stack()
1081
        fetch_tags = c.get('branch.fetch_tags')
1082
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1083
        if stop_revision is None:
7141.5.1 by Jelmer Vernooij
Fix fetching between non-default git branches.
1084
            refs = interrepo.fetch(branches=[self.source.ref], include_tags=fetch_tags)
0.336.5 by Jelmer Vernooij
Fix some tests.
1085
            try:
7141.5.1 by Jelmer Vernooij
Fix fetching between non-default git branches.
1086
                head = refs[self.source.ref]
0.336.5 by Jelmer Vernooij
Fix some tests.
1087
            except KeyError:
1088
                stop_revision = revision.NULL_REVISION
1089
            else:
1090
                stop_revision = self.target.lookup_foreign_revision_id(head)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1091
        else:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1092
            refs = interrepo.fetch(revision_id=stop_revision, include_tags=fetch_tags)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1093
        return refs, stop_revision
1094
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1095
    def pull(self, stop_revision=None, overwrite=False,
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1096
             possible_transports=None, run_hooks=True, local=False):
0.200.446 by Jelmer Vernooij
Support new 'local' argument.
1097
        # This type of branch can't be bound.
1098
        if local:
1099
            raise errors.LocalRequiresBoundBranch()
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1100
        if overwrite is True:
1101
            overwrite = set(["history", "tags"])
1102
        else:
1103
            overwrite = set()
1104
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1105
        result = GitPullResult()
1106
        result.source_branch = self.source
1107
        result.target_branch = self.target
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1108
        with self.target.lock_write(), self.source.lock_read():
1109
            result.old_revid = self.target.last_revision()
1110
            refs, stop_revision = self.update_refs(stop_revision)
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
1111
            self.target.generate_revision_history(stop_revision,
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1112
                    (result.old_revid if ("history" not in overwrite) else None),
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
1113
                    other_branch=self.source)
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1114
            tags_ret = self.source.tags.merge_to(self.target.tags,
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1115
                overwrite=("tags" in overwrite),
0.346.1 by Jelmer Vernooij
Fix tag caching.
1116
                source_tag_refs=remote_refs_dict_to_tag_refs(refs))
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1117
            if isinstance(tags_ret, tuple):
1118
                (result.tag_updates, result.tag_conflicts) = tags_ret
1119
            else:
1120
                result.tag_conflicts = tags_ret
1121
            result.new_revid = self.target.last_revision()
1122
            result.local_branch = None
1123
            result.master_branch = result.target_branch
1124
            if run_hooks:
1125
                for hook in branch.Branch.hooks['post_pull']:
1126
                    hook(result)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1127
        return result
1128
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1129
0.200.960 by Jelmer Vernooij
Use GenericInterBranch.
1130
class InterToGitBranch(branch.GenericInterBranch):
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1131
    """InterBranch implementation that pulls from a non-bzr into a Git branch."""
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1132
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
1133
    def __init__(self, source, target):
1134
        super(InterToGitBranch, self).__init__(source, target)
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
1135
        self.interrepo = _mod_repository.InterRepository.get(source.repository,
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
1136
                                           target.repository)
1137
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
1138
    @staticmethod
1139
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
1140
        try:
1141
            default_format = branch.format_registry.get_default()
1142
        except AttributeError:
1143
            default_format = branch.BranchFormat._default_format
0.295.4 by Jelmer Vernooij
Fix imports.
1144
        from .remote import RemoteGitBranchFormat
0.295.1 by Jelmer Vernooij
Split up branch formats.
1145
        return [
1146
            (default_format, LocalGitBranchFormat()),
1147
            (default_format, RemoteGitBranchFormat())]
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
1148
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1149
    @classmethod
1150
    def is_compatible(self, source, target):
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1151
        return (not isinstance(source, GitBranch) and
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1152
                isinstance(target, GitBranch))
1153
0.200.1363 by Jelmer Vernooij
Only fetch tags if requested in config.
1154
    def _get_new_refs(self, stop_revision=None, fetch_tags=None):
0.361.1 by Jelmer Vernooij
Don't use assert.
1155
        if not self.source.is_locked():
1156
            raise errors.ObjectNotLocked(self.source)
0.252.38 by Jelmer Vernooij
Minor cleanups.
1157
        if stop_revision is None:
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
1158
            (stop_revno, stop_revision) = self.source.last_revision_info()
0.263.1 by Jelmer Vernooij
Fix dpush for certain branches.
1159
        else:
1160
            stop_revno = self.source.revision_id_to_revno(stop_revision)
6973.13.2 by Jelmer Vernooij
Fix some more tests.
1161
        if not isinstance(stop_revision, bytes):
0.361.1 by Jelmer Vernooij
Don't use assert.
1162
            raise TypeError(stop_revision)
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
1163
        main_ref = self.target.ref
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
1164
        refs = { main_ref: (None, stop_revision) }
0.200.1363 by Jelmer Vernooij
Only fetch tags if requested in config.
1165
        if fetch_tags is None:
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
1166
            c = self.source.get_config_stack()
1167
            fetch_tags = c.get('branch.fetch_tags')
7018.3.2 by Jelmer Vernooij
Fix some git tests.
1168
        for name, revid in viewitems(self.source.tags.get_tag_dict()):
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1169
            if self.source.repository.has_revision(revid):
1170
                ref = tag_name_to_ref(name)
1171
                if not check_ref_format(ref):
1172
                    warning("skipping tag with invalid characters %s (%s)",
1173
                        name, ref)
1174
                    continue
0.200.1398 by Jelmer Vernooij
Make GitSmartRemoteNotSupported derive from UnsupportedOperation.
1175
                if fetch_tags:
1176
                    # FIXME: Skip tags that are not in the ancestry
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1177
                    refs[ref] = (None, revid)
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
1178
        return refs, main_ref, (stop_revno, stop_revision)
0.252.37 by Jelmer Vernooij
Factor out some common code for finding refs to send.
1179
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1180
    def _update_refs(self, result, old_refs, new_refs, overwrite):
1181
        mutter("updating refs. old refs: %r, new refs: %r",
1182
               old_refs, new_refs)
1183
        result.tag_updates = {}
1184
        result.tag_conflicts = []
1185
        ret = dict(old_refs)
1186
        def ref_equals(refs, ref, git_sha, revid):
1187
            try:
1188
                value = refs[ref]
1189
            except KeyError:
1190
                return False
1191
            if (value[0] is not None and
1192
                git_sha is not None and
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1193
                value[0] == git_sha):
1194
                return True
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1195
            if (value[1] is not None and
1196
                revid is not None and
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1197
                value[1] == revid):
1198
                return True
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1199
            # FIXME: If one side only has the git sha available and the other only
1200
            # has the bzr revid, then this will cause us to show a tag as updated
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
1201
            # that hasn't actually been updated.
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1202
            return False
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1203
        # FIXME: Check for diverged branches
7018.3.8 by Jelmer Vernooij
Disable some flaky tests on python3, allow running without fastimport.
1204
        for ref, (git_sha, revid) in viewitems(new_refs):
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1205
            if ref_equals(ret, ref, git_sha, revid):
1206
                # Already up to date
1207
                if git_sha is None:
1208
                    git_sha = old_refs[ref][0]
1209
                if revid is None:
1210
                    revid = old_refs[ref][1]
1211
                ret[ref] = new_refs[ref] = (git_sha, revid)
1212
            elif ref not in ret or overwrite:
1213
                try:
1214
                    tag_name = ref_to_tag_name(ref)
1215
                except ValueError:
1216
                    pass
1217
                else:
1218
                    result.tag_updates[tag_name] = revid
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1219
                ret[ref] = (git_sha, revid)
1220
            else:
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1221
                # FIXME: Check diverged
1222
                diverged = False
1223
                if diverged:
1224
                    try:
1225
                        name = ref_to_tag_name(ref)
1226
                    except ValueError:
1227
                        pass
1228
                    else:
1229
                        result.tag_conflicts.append((name, revid, ret[name][1]))
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1230
                else:
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1231
                    ret[ref] = (git_sha, revid)
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1232
        return ret
1233
0.200.1493 by Jelmer Vernooij
Test fixes.
1234
    def fetch(self, stop_revision=None, fetch_tags=None, lossy=False, limit=None):
1235
        if stop_revision is None:
1236
            stop_revision = self.source.last_revision()
1237
        ret = []
1238
        if fetch_tags:
7018.3.2 by Jelmer Vernooij
Fix some git tests.
1239
            for k, v in viewitems(self.source.tags.get_tag_dict()):
0.200.1493 by Jelmer Vernooij
Test fixes.
1240
                ret.append((None, v))
1241
        ret.append((None, stop_revision))
0.320.5 by Jelmer Vernooij
Always raise NoRoundtrippingSupport rather than NoPushSupport.
1242
        try:
1243
            self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
1244
        except NoPushSupport:
1245
            raise errors.NoRoundtrippingSupport(self.source, self.target)
0.200.1493 by Jelmer Vernooij
Test fixes.
1246
0.252.36 by Jelmer Vernooij
Fix pull.
1247
    def pull(self, overwrite=False, stop_revision=None, local=False,
0.200.1131 by Jelmer Vernooij
Accept run_hooks argument to InterToGitBranch.pull().
1248
             possible_transports=None, run_hooks=True):
0.252.36 by Jelmer Vernooij
Fix pull.
1249
        result = GitBranchPullResult()
1250
        result.source_branch = self.source
1251
        result.target_branch = self.target
0.200.1788 by Jelmer Vernooij
Use context managers.
1252
        with self.source.lock_read(), self.target.lock_write():
1253
            new_refs, main_ref, stop_revinfo = self._get_new_refs(
1254
                stop_revision)
1255
            def update_refs(old_refs):
1256
                return self._update_refs(result, old_refs, new_refs, overwrite)
0.200.1353 by Jelmer Vernooij
Run various hooks.
1257
            try:
0.200.1788 by Jelmer Vernooij
Use context managers.
1258
                result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1259
                    update_refs, lossy=False)
1260
            except NoPushSupport:
1261
                raise errors.NoRoundtrippingSupport(self.source, self.target)
1262
            (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1263
            if result.old_revid is None:
1264
                result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1265
            result.new_revid = new_refs[main_ref][1]
1266
            result.local_branch = None
1267
            result.master_branch = self.target
1268
            if run_hooks:
1269
                for hook in branch.Branch.hooks['post_pull']:
1270
                    hook(result)
0.252.36 by Jelmer Vernooij
Fix pull.
1271
        return result
1272
0.200.1260 by Jelmer Vernooij
Cope with new lossy argument.
1273
    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.
1274
             _override_hook_source_branch=None):
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
1275
        result = GitBranchPushResult()
1276
        result.source_branch = self.source
1277
        result.target_branch = self.target
0.200.1356 by Jelmer Vernooij
Fix result properties for hook.
1278
        result.local_branch = None
1279
        result.master_branch = result.target_branch
0.331.1 by Jelmer Vernooij
Fix some tags tests.
1280
        with self.source.lock_read(), self.target.lock_write():
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1281
            new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
1282
            def update_refs(old_refs):
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1283
                return self._update_refs(result, old_refs, new_refs, overwrite)
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1284
            try:
1285
                result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
1286
                    update_refs, lossy=lossy, overwrite=overwrite)
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1287
            except NoPushSupport:
1288
                raise errors.NoRoundtrippingSupport(self.source, self.target)
1289
            (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1290
            if result.old_revid is None:
1291
                result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1292
            result.new_revid = new_refs[main_ref][1]
1293
            (result.new_original_revno, result.new_original_revid) = stop_revinfo
1294
            for hook in branch.Branch.hooks['post_push']:
1295
                hook(result)
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
1296
        return result
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
1297
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1298
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1299
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1300
branch.InterBranch.register_optimiser(InterFromGitBranch)
1301
branch.InterBranch.register_optimiser(InterToGitBranch)
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1302
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)