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