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