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