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