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