/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
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
22
from cStringIO import StringIO
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"))
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
400
        f = StringIO()
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')
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
483
        f = StringIO()
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 []
0.200.1279 by Jelmer Vernooij
Avoid using deprecated Repository.iter_reverse_revision_history.
617
        graph = self.repository.get_graph()
618
        ret = list(graph.iter_lefthand_ancestry(self.last_revision(),
619
            (revision.NULL_REVISION, )))
0.200.59 by Jelmer Vernooij
Add more tests, fix revision history.
620
        ret.reverse()
0.200.57 by Jelmer Vernooij
Fix more tests.
621
        return ret
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
622
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
623
    def _get_head(self):
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
624
        try:
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
625
            return self.repository._git.refs[self.ref]
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
626
        except KeyError:
627
            return None
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
628
0.200.1228 by Jelmer Vernooij
Provide Branch._read_last_revision_info.
629
    def _read_last_revision_info(self):
630
        last_revid = self.last_revision()
631
        graph = self.repository.get_graph()
632
        revno = graph.find_distance_to_null(last_revid,
633
            [(revision.NULL_REVISION, 0)])
634
        return revno, last_revid
635
636
    def set_last_revision_info(self, revno, revision_id):
637
        self.set_last_revision(revision_id)
638
        self._last_revision_info_cache = revno, revision_id
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
639
640
    def set_last_revision(self, revid):
0.200.1233 by Jelmer Vernooij
Implement Repository.iter_files_bytes.
641
        if not revid or not isinstance(revid, basestring):
642
            raise errors.InvalidRevisionId(revision_id=revid, branch=self)
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
643
        if revid == NULL_REVISION:
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
644
            newhead = None
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
645
        else:
646
            (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
647
            if self.mapping is None:
648
                raise AssertionError
649
        self._set_head(newhead)
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
650
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
651
    def _set_head(self, value):
0.361.1 by Jelmer Vernooij
Don't use assert.
652
        if value == ZERO_SHA:
653
            raise ValueError(value)
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
654
        self._head = value
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
655
        if value is None:
656
            del self.repository._git.refs[self.ref]
657
        else:
658
            self.repository._git.refs[self.ref] = self._head
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
659
        self._clear_cached_state()
660
661
    head = property(_get_head, _set_head)
662
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
663
    def get_push_location(self):
664
        """See Branch.get_push_location."""
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
665
        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.
666
        return push_loc
667
668
    def set_push_location(self, location):
669
        """See Branch.set_push_location."""
0.200.19 by John Arbash Meinel
More refactoring. Add some direct tests for GitModel.
670
        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.
671
                                          store=config.STORE_LOCATION)
0.200.43 by David Allouche
Ultra-experimental support for "bzr pull". No test. No sanity.
672
673
    def supports_tags(self):
0.200.82 by Jelmer Vernooij
Support listing tags.
674
        return True
0.200.956 by Jelmer Vernooij
Add some more format tests.
675
0.200.1681 by Jelmer Vernooij
Provide Branch.store_uncommitted.
676
    def store_uncommitted(self, creator):
677
        raise errors.StoringUncommittedNotSupported(self)
678
0.346.1 by Jelmer Vernooij
Fix tag caching.
679
    def _iter_tag_refs(self):
680
        """Iterate over the tag refs.
681
682
        :param refs: Refs dictionary (name -> git sha1)
683
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
684
        """
685
        refs = self.repository._git.refs
686
        for ref_name, unpeeled in refs.as_dict().iteritems():
687
            try:
688
                tag_name = ref_to_tag_name(ref_name)
689
            except (ValueError, UnicodeDecodeError):
690
                continue
691
            peeled = refs.get_peeled(ref_name)
692
            if peeled is None:
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
693
                peeled = unpeeled
0.361.1 by Jelmer Vernooij
Don't use assert.
694
            if type(tag_name) is not unicode:
695
                raise TypeError(tag_name)
0.346.1 by Jelmer Vernooij
Fix tag caching.
696
            yield (ref_name, tag_name, peeled, unpeeled)
697
0.360.1 by Jelmer Vernooij
Implement GitMemoryTree.
698
    def create_memorytree(self):
699
        from .memorytree import GitMemoryTree
700
        return GitMemoryTree(self, self.repository._git.object_store, self.head)
701
0.429.10 by Jelmer Vernooij
use new read_submodule_head from dulwich.
702
    def reference_parent(self, path, file_id=None, possible_transports=None):
703
        """Return the parent branch for a tree-reference file_id
704
705
        :param path: The path of the file_id in the tree
706
        :param file_id: Optional file_id of the tree reference
707
        :return: A branch associated with the file_id
708
        """
709
        # FIXME should provide multiple branches, based on config
0.429.18 by Jelmer Vernooij
Fix reference_parent tets.
710
        url = urlutils.join(self.user_url, path)
711
        return branch.Branch.open(
712
                url,
713
                possible_transports=possible_transports)
714
0.429.10 by Jelmer Vernooij
use new read_submodule_head from dulwich.
715
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
716
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
717
def _quick_lookup_revno(local_branch, remote_branch, revid):
0.361.1 by Jelmer Vernooij
Don't use assert.
718
    if type(revid) is not str:
719
        raise TypeError(revid)
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
720
    # Try in source branch first, it'll be faster
0.200.1788 by Jelmer Vernooij
Use context managers.
721
    with local_branch.lock_read():
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
722
        try:
0.200.1362 by Jelmer Vernooij
Add locking.
723
            return local_branch.revision_id_to_revno(revid)
724
        except errors.NoSuchRevision:
725
            graph = local_branch.repository.get_graph()
726
            try:
727
                return graph.find_distance_to_null(revid,
728
                    [(revision.NULL_REVISION, 0)])
729
            except errors.GhostRevisionsHaveNoRevno:
730
                # FIXME: Check using graph.find_distance_to_null() ?
0.200.1788 by Jelmer Vernooij
Use context managers.
731
                with remote_branch.lock_read():
0.200.1362 by Jelmer Vernooij
Add locking.
732
                    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.
733
734
0.200.342 by Jelmer Vernooij
Report git sha during pull.
735
class GitBranchPullResult(branch.PullResult):
736
0.252.36 by Jelmer Vernooij
Fix pull.
737
    def __init__(self):
738
        super(GitBranchPullResult, self).__init__()
739
        self.new_git_head = None
740
        self._old_revno = None
741
        self._new_revno = None
742
0.200.342 by Jelmer Vernooij
Report git sha during pull.
743
    def report(self, to_file):
744
        if not is_quiet():
745
            if self.old_revid == self.new_revid:
746
                to_file.write('No revisions to pull.\n')
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
747
            elif self.new_git_head is not None:
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
748
                to_file.write('Now on revision %d (git sha: %s).\n' %
0.200.342 by Jelmer Vernooij
Report git sha during pull.
749
                        (self.new_revno, self.new_git_head))
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
750
            else:
751
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
0.200.342 by Jelmer Vernooij
Report git sha during pull.
752
        self._show_tag_conficts(to_file)
753
0.252.36 by Jelmer Vernooij
Fix pull.
754
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
755
        return _quick_lookup_revno(self.target_branch, self.source_branch,
0.200.1513 by Jelmer Vernooij
Cope with zero shas.
756
            revid)
0.252.36 by Jelmer Vernooij
Fix pull.
757
758
    def _get_old_revno(self):
759
        if self._old_revno is not None:
760
            return self._old_revno
761
        return self._lookup_revno(self.old_revid)
762
763
    def _set_old_revno(self, revno):
764
        self._old_revno = revno
765
766
    old_revno = property(_get_old_revno, _set_old_revno)
767
768
    def _get_new_revno(self):
769
        if self._new_revno is not None:
770
            return self._new_revno
771
        return self._lookup_revno(self.new_revid)
772
773
    def _set_new_revno(self, revno):
774
        self._new_revno = revno
0.200.956 by Jelmer Vernooij
Add some more format tests.
775
0.252.36 by Jelmer Vernooij
Fix pull.
776
    new_revno = property(_get_new_revno, _set_new_revno)
777
0.200.342 by Jelmer Vernooij
Report git sha during pull.
778
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
779
class GitBranchPushResult(branch.BranchPushResult):
780
781
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
782
        return _quick_lookup_revno(self.source_branch, self.target_branch,
783
            revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
784
785
    @property
786
    def old_revno(self):
787
        return self._lookup_revno(self.old_revid)
788
789
    @property
790
    def new_revno(self):
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
791
        new_original_revno = getattr(self, "new_original_revno", None)
792
        if new_original_revno:
793
            return new_original_revno
794
        if getattr(self, "new_original_revid", None) is not None:
795
            return self._lookup_revno(self.new_original_revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
796
        return self._lookup_revno(self.new_revid)
797
798
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
799
class InterFromGitBranch(branch.GenericInterBranch):
0.200.261 by Jelmer Vernooij
More formatting fixes.
800
    """InterBranch implementation that pulls from Git into bzr."""
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
801
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
802
    @staticmethod
803
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
804
        try:
805
            default_format = branch.format_registry.get_default()
806
        except AttributeError:
807
            default_format = branch.BranchFormat._default_format
0.295.4 by Jelmer Vernooij
Fix imports.
808
        from .remote import RemoteGitBranchFormat
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
809
        return [
0.295.1 by Jelmer Vernooij
Split up branch formats.
810
            (RemoteGitBranchFormat(), default_format),
811
            (LocalGitBranchFormat(), default_format)]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
812
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
813
    @classmethod
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
814
    def _get_interrepo(self, source, target):
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
815
        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.
816
817
    @classmethod
818
    def is_compatible(cls, source, target):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
819
        if not isinstance(source, GitBranch):
820
            return False
821
        if isinstance(target, GitBranch):
822
            # InterLocalGitRemoteGitBranch or InterToGitBranch should be used
823
            return False
824
        if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
825
            # fetch_objects is necessary for this to work
826
            return False
827
        return True
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
828
0.200.1305 by Jelmer Vernooij
Only actually fetch tags if "branch.fetch_tags" is set to true.
829
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
830
        self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
831
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
832
    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.
833
        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.
834
        if fetch_tags is None:
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
835
            c = self.source.get_config_stack()
836
            fetch_tags = c.get('branch.fetch_tags')
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
837
        def determine_wants(heads):
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
838
            if stop_revision is None:
0.336.6 by Jelmer Vernooij
Fix pull tests.
839
                try:
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
840
                    head = heads[self.source.ref]
0.336.6 by Jelmer Vernooij
Fix pull tests.
841
                except KeyError:
842
                    self._last_revid = revision.NULL_REVISION
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
843
                else:
0.336.6 by Jelmer Vernooij
Fix pull tests.
844
                    self._last_revid = self.source.lookup_foreign_revision_id(head)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
845
            else:
846
                self._last_revid = stop_revision
847
            real = interrepo.get_determine_wants_revids(
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
848
                [self._last_revid], include_tags=fetch_tags)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
849
            return real(heads)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
850
        pack_hint, head, refs = interrepo.fetch_objects(
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
851
            determine_wants, self.source.mapping, limit=limit)
0.252.45 by Jelmer Vernooij
Finish fetching roundtripped revisions back into bzr.
852
        if (pack_hint is not None and
853
            self.target.repository._format.pack_compresses):
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
854
            self.target.repository.pack(hint=pack_hint)
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
855
        return head, refs
856
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
857
    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.
858
        head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
859
        if overwrite:
0.200.314 by Jelmer Vernooij
Support stop_revision.
860
            prev_last_revid = None
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
861
        else:
0.200.314 by Jelmer Vernooij
Support stop_revision.
862
            prev_last_revid = self.target.last_revision()
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
863
        self.target.generate_revision_history(self._last_revid,
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
864
            last_rev=prev_last_revid, other_branch=self.source)
0.200.1062 by Jelmer Vernooij
Pass remote refs along in _update_revisions.
865
        return head, refs
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
866
0.200.1423 by Jelmer Vernooij
Fix space.
867
    def _basic_pull(self, stop_revision, overwrite, run_hooks,
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
868
              _override_hook_target, _hook_master):
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
869
        if overwrite is True:
870
            overwrite = set(["history", "tags"])
871
        else:
872
            overwrite = set()
0.200.342 by Jelmer Vernooij
Report git sha during pull.
873
        result = GitBranchPullResult()
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
874
        result.source_branch = self.source
875
        if _override_hook_target is None:
876
            result.target_branch = self.target
877
        else:
878
            result.target_branch = _override_hook_target
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
879
        with self.target.lock_write(), self.source.lock_read():
880
            # We assume that during 'pull' the target repository is closer than
881
            # the source one.
882
            (result.old_revno, result.old_revid) = \
883
                self.target.last_revision_info()
884
            result.new_git_head, remote_refs = self._update_revisions(
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
885
                stop_revision, overwrite=("history" in overwrite))
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
886
            tags_ret  = self.source.tags.merge_to(
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
887
                    self.target.tags, ("tags" in overwrite), ignore_master=True)
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
888
            if isinstance(tags_ret, tuple):
889
                result.tag_updates, result.tag_conflicts = tags_ret
890
            else:
891
                result.tag_conflicts = tags_ret
892
            (result.new_revno, result.new_revid) = \
893
                self.target.last_revision_info()
894
            if _hook_master:
895
                result.master_branch = _hook_master
896
                result.local_branch = result.target_branch
897
            else:
898
                result.master_branch = result.target_branch
899
                result.local_branch = None
900
            if run_hooks:
901
                for hook in branch.Branch.hooks['post_pull']:
902
                    hook(result)
903
            return result
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
904
905
    def pull(self, overwrite=False, stop_revision=None,
906
             possible_transports=None, _hook_master=None, run_hooks=True,
907
             _override_hook_target=None, local=False):
908
        """See Branch.pull.
909
910
        :param _hook_master: Private parameter - set the branch to
911
            be supplied as the master to pull hooks.
912
        :param run_hooks: Private parameter - if false, this branch
913
            is being called because it's the master of the primary branch,
914
            so it should not run its hooks.
915
        :param _override_hook_target: Private parameter - set the branch to be
916
            supplied as the target_branch to pull hooks.
917
        """
918
        # This type of branch can't be bound.
919
        bound_location = self.target.get_bound_location()
920
        if local and not bound_location:
921
            raise errors.LocalRequiresBoundBranch()
922
        master_branch = None
923
        source_is_master = False
924
        self.source.lock_read()
925
        if bound_location:
926
            # bound_location comes from a config file, some care has to be
927
            # taken to relate it to source.user_url
928
            normalized = urlutils.normalize_url(bound_location)
929
            try:
930
                relpath = self.source.user_transport.relpath(normalized)
931
                source_is_master = (relpath == '')
0.200.1660 by Jelmer Vernooij
Fix imports.
932
            except (errors.PathNotChild, urlutils.InvalidURL):
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
933
                source_is_master = False
934
        if not local and bound_location and not source_is_master:
935
            # not pulling from master, so we need to update master.
936
            master_branch = self.target.get_master_branch(possible_transports)
937
            master_branch.lock_write()
938
        try:
939
            try:
940
                if master_branch:
941
                    # pull from source into master.
942
                    master_branch.pull(self.source, overwrite, stop_revision,
943
                        run_hooks=False)
944
                result = self._basic_pull(stop_revision, overwrite, run_hooks,
945
                    _override_hook_target, _hook_master=master_branch)
946
            finally:
947
                self.source.unlock()
948
        finally:
949
            if master_branch:
950
                master_branch.unlock()
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
951
        return result
952
0.331.1 by Jelmer Vernooij
Fix some tags tests.
953
    def _basic_push(self, overwrite, stop_revision):
954
        if overwrite is True:
955
            overwrite = set(["history", "tags"])
956
        else:
957
            overwrite = set()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
958
        result = branch.BranchPushResult()
959
        result.source_branch = self.source
960
        result.target_branch = self.target
961
        result.old_revno, result.old_revid = self.target.last_revision_info()
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
962
        result.new_git_head, remote_refs = self._update_revisions(
0.331.1 by Jelmer Vernooij
Fix some tags tests.
963
            stop_revision, overwrite=("history" in overwrite))
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
964
        tags_ret = self.source.tags.merge_to(self.target.tags,
0.331.1 by Jelmer Vernooij
Fix some tags tests.
965
            "tags" in overwrite, ignore_master=True)
966
        (result.tag_updates, result.tag_conflicts) = tags_ret
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
967
        result.new_revno, result.new_revid = self.target.last_revision_info()
968
        return result
969
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
970
0.200.512 by Jelmer Vernooij
Support pushing git->git.
971
class InterGitBranch(branch.GenericInterBranch):
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
972
    """InterBranch implementation that pulls between Git branches."""
973
0.200.1493 by Jelmer Vernooij
Test fixes.
974
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
975
        raise NotImplementedError(self.fetch)
976
0.200.512 by Jelmer Vernooij
Support pushing git->git.
977
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
978
class InterLocalGitRemoteGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
979
    """InterBranch that copies from a local to a remote git branch."""
980
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
981
    @staticmethod
982
    def _get_branch_formats_to_test():
0.295.4 by Jelmer Vernooij
Fix imports.
983
        from .remote import RemoteGitBranchFormat
0.295.3 by Jelmer Vernooij
Fix some more tests.
984
        return [
985
            (LocalGitBranchFormat(), RemoteGitBranchFormat())]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
986
0.200.512 by Jelmer Vernooij
Support pushing git->git.
987
    @classmethod
988
    def is_compatible(self, source, target):
0.200.1644 by Jelmer Vernooij
More relative imports.
989
        from .remote import RemoteGitBranch
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
990
        return (isinstance(source, LocalGitBranch) and
0.200.512 by Jelmer Vernooij
Support pushing git->git.
991
                isinstance(target, RemoteGitBranch))
992
0.331.1 by Jelmer Vernooij
Fix some tags tests.
993
    def _basic_push(self, overwrite, stop_revision):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
994
        result = GitBranchPushResult()
995
        result.source_branch = self.source
996
        result.target_branch = self.target
997
        if stop_revision is None:
998
            stop_revision = self.source.last_revision()
999
        def get_changed_refs(old_refs):
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
1000
            old_ref = old_refs.get(self.target.ref, None)
1001
            if old_ref is None:
1002
                result.old_revid = revision.NULL_REVISION
1003
            else:
1004
                result.old_revid = self.target.lookup_foreign_revision_id(old_ref)
1005
            new_ref = self.source.repository.lookup_bzr_revision_id(stop_revision)[0]
1006
            if not overwrite:
1007
                if remote_divergence(old_ref, new_ref, self.source.repository._git.object_store):
1008
                    raise errors.DivergedBranches(self.source, self.target)
1009
            refs = { self.target.ref: new_ref }
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1010
            result.new_revid = stop_revision
1011
            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.
1012
                refs[tag_name_to_ref(name)] = sha
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1013
            return refs
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1014
        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.
1015
            self.source.repository._git.object_store.generate_pack_data)
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1016
        return result
1017
1018
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1019
class InterGitLocalGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1020
    """InterBranch that copies from a remote to a local git branch."""
1021
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
1022
    @staticmethod
1023
    def _get_branch_formats_to_test():
0.295.4 by Jelmer Vernooij
Fix imports.
1024
        from .remote import RemoteGitBranchFormat
0.295.3 by Jelmer Vernooij
Fix some more tests.
1025
        return [
1026
            (RemoteGitBranchFormat(), LocalGitBranchFormat()),
1027
            (LocalGitBranchFormat(), LocalGitBranchFormat())]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
1028
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1029
    @classmethod
1030
    def is_compatible(self, source, target):
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1031
        return (isinstance(source, GitBranch) and
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1032
                isinstance(target, LocalGitBranch))
1033
0.200.1534 by Jelmer Vernooij
Implement fetch between git branches, encode nicks.
1034
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
1035
        interrepo = _mod_repository.InterRepository.get(self.source.repository,
1036
            self.target.repository)
1037
        if stop_revision is None:
1038
            stop_revision = self.source.last_revision()
1039
        determine_wants = interrepo.get_determine_wants_revids(
1040
            [stop_revision], include_tags=fetch_tags)
1041
        interrepo.fetch_objects(determine_wants, limit=limit)
1042
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1043
    def _basic_push(self, overwrite=False, stop_revision=None):
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1044
        if overwrite is True:
1045
            overwrite = set(["history", "tags"])
1046
        else:
1047
            overwrite = set()
0.200.1325 by Jelmer Vernooij
More test fixes.
1048
        result = GitBranchPushResult()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1049
        result.source_branch = self.source
1050
        result.target_branch = self.target
1051
        result.old_revid = self.target.last_revision()
1052
        refs, stop_revision = self.update_refs(stop_revision)
0.296.3 by Jelmer Vernooij
Update xfail.
1053
        self.target.generate_revision_history(stop_revision,
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1054
                (result.old_revid if ("history" not in overwrite) else None),
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
1055
                other_branch=self.source)
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
1056
        tags_ret = self.source.tags.merge_to(self.target.tags,
0.346.1 by Jelmer Vernooij
Fix tag caching.
1057
            source_tag_refs=remote_refs_dict_to_tag_refs(refs),
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1058
            overwrite=("tags" in overwrite))
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
1059
        if isinstance(tags_ret, tuple):
1060
            (result.tag_updates, result.tag_conflicts) = tags_ret
1061
        else:
1062
            result.tag_conflicts = tags_ret
0.200.505 by Jelmer Vernooij
Remove duplicate code.
1063
        result.new_revid = self.target.last_revision()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1064
        return result
1065
1066
    def update_refs(self, stop_revision=None):
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1067
        interrepo = _mod_repository.InterRepository.get(
1068
                self.source.repository, self.target.repository)
1069
        c = self.source.get_config_stack()
1070
        fetch_tags = c.get('branch.fetch_tags')
1071
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1072
        if stop_revision is None:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1073
            refs = interrepo.fetch(branches=["HEAD"], include_tags=fetch_tags)
0.336.5 by Jelmer Vernooij
Fix some tests.
1074
            try:
1075
                head = refs["HEAD"]
1076
            except KeyError:
1077
                stop_revision = revision.NULL_REVISION
1078
            else:
1079
                stop_revision = self.target.lookup_foreign_revision_id(head)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1080
        else:
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1081
            refs = interrepo.fetch(revision_id=stop_revision, include_tags=fetch_tags)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1082
        return refs, stop_revision
1083
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1084
    def pull(self, stop_revision=None, overwrite=False,
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1085
             possible_transports=None, run_hooks=True, local=False):
0.200.446 by Jelmer Vernooij
Support new 'local' argument.
1086
        # This type of branch can't be bound.
1087
        if local:
1088
            raise errors.LocalRequiresBoundBranch()
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1089
        if overwrite is True:
1090
            overwrite = set(["history", "tags"])
1091
        else:
1092
            overwrite = set()
1093
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1094
        result = GitPullResult()
1095
        result.source_branch = self.source
1096
        result.target_branch = self.target
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1097
        with self.target.lock_write(), self.source.lock_read():
1098
            result.old_revid = self.target.last_revision()
1099
            refs, stop_revision = self.update_refs(stop_revision)
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
1100
            self.target.generate_revision_history(stop_revision,
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1101
                    (result.old_revid if ("history" not in overwrite) else None),
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
1102
                    other_branch=self.source)
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1103
            tags_ret = self.source.tags.merge_to(self.target.tags,
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1104
                overwrite=("tags" in overwrite),
0.346.1 by Jelmer Vernooij
Fix tag caching.
1105
                source_tag_refs=remote_refs_dict_to_tag_refs(refs))
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1106
            if isinstance(tags_ret, tuple):
1107
                (result.tag_updates, result.tag_conflicts) = tags_ret
1108
            else:
1109
                result.tag_conflicts = tags_ret
1110
            result.new_revid = self.target.last_revision()
1111
            result.local_branch = None
1112
            result.master_branch = result.target_branch
1113
            if run_hooks:
1114
                for hook in branch.Branch.hooks['post_pull']:
1115
                    hook(result)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1116
        return result
1117
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1118
0.200.960 by Jelmer Vernooij
Use GenericInterBranch.
1119
class InterToGitBranch(branch.GenericInterBranch):
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1120
    """InterBranch implementation that pulls from a non-bzr into a Git branch."""
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1121
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
1122
    def __init__(self, source, target):
1123
        super(InterToGitBranch, self).__init__(source, target)
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
1124
        self.interrepo = _mod_repository.InterRepository.get(source.repository,
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
1125
                                           target.repository)
1126
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
1127
    @staticmethod
1128
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
1129
        try:
1130
            default_format = branch.format_registry.get_default()
1131
        except AttributeError:
1132
            default_format = branch.BranchFormat._default_format
0.295.4 by Jelmer Vernooij
Fix imports.
1133
        from .remote import RemoteGitBranchFormat
0.295.1 by Jelmer Vernooij
Split up branch formats.
1134
        return [
1135
            (default_format, LocalGitBranchFormat()),
1136
            (default_format, RemoteGitBranchFormat())]
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
1137
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1138
    @classmethod
1139
    def is_compatible(self, source, target):
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1140
        return (not isinstance(source, GitBranch) and
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1141
                isinstance(target, GitBranch))
1142
0.200.1363 by Jelmer Vernooij
Only fetch tags if requested in config.
1143
    def _get_new_refs(self, stop_revision=None, fetch_tags=None):
0.361.1 by Jelmer Vernooij
Don't use assert.
1144
        if not self.source.is_locked():
1145
            raise errors.ObjectNotLocked(self.source)
0.252.38 by Jelmer Vernooij
Minor cleanups.
1146
        if stop_revision is None:
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
1147
            (stop_revno, stop_revision) = self.source.last_revision_info()
0.263.1 by Jelmer Vernooij
Fix dpush for certain branches.
1148
        else:
1149
            stop_revno = self.source.revision_id_to_revno(stop_revision)
0.361.1 by Jelmer Vernooij
Don't use assert.
1150
        if type(stop_revision) is not str:
1151
            raise TypeError(stop_revision)
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
1152
        main_ref = self.target.ref
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
1153
        refs = { main_ref: (None, stop_revision) }
0.200.1363 by Jelmer Vernooij
Only fetch tags if requested in config.
1154
        if fetch_tags is None:
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
1155
            c = self.source.get_config_stack()
1156
            fetch_tags = c.get('branch.fetch_tags')
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1157
        for name, revid in self.source.tags.get_tag_dict().iteritems():
1158
            if self.source.repository.has_revision(revid):
1159
                ref = tag_name_to_ref(name)
1160
                if not check_ref_format(ref):
1161
                    warning("skipping tag with invalid characters %s (%s)",
1162
                        name, ref)
1163
                    continue
0.200.1398 by Jelmer Vernooij
Make GitSmartRemoteNotSupported derive from UnsupportedOperation.
1164
                if fetch_tags:
1165
                    # FIXME: Skip tags that are not in the ancestry
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1166
                    refs[ref] = (None, revid)
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
1167
        return refs, main_ref, (stop_revno, stop_revision)
0.252.37 by Jelmer Vernooij
Factor out some common code for finding refs to send.
1168
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1169
    def _update_refs(self, result, old_refs, new_refs, overwrite):
1170
        mutter("updating refs. old refs: %r, new refs: %r",
1171
               old_refs, new_refs)
1172
        result.tag_updates = {}
1173
        result.tag_conflicts = []
1174
        ret = dict(old_refs)
1175
        def ref_equals(refs, ref, git_sha, revid):
1176
            try:
1177
                value = refs[ref]
1178
            except KeyError:
1179
                return False
1180
            if (value[0] is not None and
1181
                git_sha is not None and
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1182
                value[0] == git_sha):
1183
                return True
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1184
            if (value[1] is not None and
1185
                revid is not None and
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1186
                value[1] == revid):
1187
                return True
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1188
            # FIXME: If one side only has the git sha available and the other only
1189
            # has the bzr revid, then this will cause us to show a tag as updated
0.200.1636 by Jelmer Vernooij
Some formatting fixes.
1190
            # that hasn't actually been updated.
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1191
            return False
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1192
        # FIXME: Check for diverged branches
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1193
        for ref, (git_sha, revid) in new_refs.iteritems():
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1194
            if ref_equals(ret, ref, git_sha, revid):
1195
                # Already up to date
1196
                if git_sha is None:
1197
                    git_sha = old_refs[ref][0]
1198
                if revid is None:
1199
                    revid = old_refs[ref][1]
1200
                ret[ref] = new_refs[ref] = (git_sha, revid)
1201
            elif ref not in ret or overwrite:
1202
                try:
1203
                    tag_name = ref_to_tag_name(ref)
1204
                except ValueError:
1205
                    pass
1206
                else:
1207
                    result.tag_updates[tag_name] = revid
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1208
                ret[ref] = (git_sha, revid)
1209
            else:
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1210
                # FIXME: Check diverged
1211
                diverged = False
1212
                if diverged:
1213
                    try:
1214
                        name = ref_to_tag_name(ref)
1215
                    except ValueError:
1216
                        pass
1217
                    else:
1218
                        result.tag_conflicts.append((name, revid, ret[name][1]))
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1219
                else:
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1220
                    ret[ref] = (git_sha, revid)
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1221
        return ret
1222
0.200.1493 by Jelmer Vernooij
Test fixes.
1223
    def fetch(self, stop_revision=None, fetch_tags=None, lossy=False, limit=None):
1224
        if stop_revision is None:
1225
            stop_revision = self.source.last_revision()
1226
        ret = []
1227
        if fetch_tags:
1228
            for k, v in self.source.tags.get_tag_dict().iteritems():
1229
                ret.append((None, v))
1230
        ret.append((None, stop_revision))
0.320.5 by Jelmer Vernooij
Always raise NoRoundtrippingSupport rather than NoPushSupport.
1231
        try:
1232
            self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
1233
        except NoPushSupport:
1234
            raise errors.NoRoundtrippingSupport(self.source, self.target)
0.200.1493 by Jelmer Vernooij
Test fixes.
1235
0.252.36 by Jelmer Vernooij
Fix pull.
1236
    def pull(self, overwrite=False, stop_revision=None, local=False,
0.200.1131 by Jelmer Vernooij
Accept run_hooks argument to InterToGitBranch.pull().
1237
             possible_transports=None, run_hooks=True):
0.252.36 by Jelmer Vernooij
Fix pull.
1238
        result = GitBranchPullResult()
1239
        result.source_branch = self.source
1240
        result.target_branch = self.target
0.200.1788 by Jelmer Vernooij
Use context managers.
1241
        with self.source.lock_read(), self.target.lock_write():
1242
            new_refs, main_ref, stop_revinfo = self._get_new_refs(
1243
                stop_revision)
1244
            def update_refs(old_refs):
1245
                return self._update_refs(result, old_refs, new_refs, overwrite)
0.200.1353 by Jelmer Vernooij
Run various hooks.
1246
            try:
0.200.1788 by Jelmer Vernooij
Use context managers.
1247
                result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
1248
                    update_refs, lossy=False)
1249
            except NoPushSupport:
1250
                raise errors.NoRoundtrippingSupport(self.source, self.target)
1251
            (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1252
            if result.old_revid is None:
1253
                result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1254
            result.new_revid = new_refs[main_ref][1]
1255
            result.local_branch = None
1256
            result.master_branch = self.target
1257
            if run_hooks:
1258
                for hook in branch.Branch.hooks['post_pull']:
1259
                    hook(result)
0.252.36 by Jelmer Vernooij
Fix pull.
1260
        return result
1261
0.200.1260 by Jelmer Vernooij
Cope with new lossy argument.
1262
    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.
1263
             _override_hook_source_branch=None):
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
1264
        result = GitBranchPushResult()
1265
        result.source_branch = self.source
1266
        result.target_branch = self.target
0.200.1356 by Jelmer Vernooij
Fix result properties for hook.
1267
        result.local_branch = None
1268
        result.master_branch = result.target_branch
0.331.1 by Jelmer Vernooij
Fix some tags tests.
1269
        with self.source.lock_read(), self.target.lock_write():
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1270
            new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
1271
            def update_refs(old_refs):
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1272
                return self._update_refs(result, old_refs, new_refs, overwrite)
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1273
            try:
1274
                result.revidmap, old_refs, new_refs = self.interrepo.fetch_refs(
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
1275
                    update_refs, lossy=lossy, overwrite=overwrite)
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1276
            except NoPushSupport:
1277
                raise errors.NoRoundtrippingSupport(self.source, self.target)
1278
            (old_sha1, result.old_revid) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
1279
            if result.old_revid is None:
1280
                result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
1281
            result.new_revid = new_refs[main_ref][1]
1282
            (result.new_original_revno, result.new_original_revid) = stop_revinfo
1283
            for hook in branch.Branch.hooks['post_push']:
1284
                hook(result)
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
1285
        return result
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
1286
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1287
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1288
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1289
branch.InterBranch.register_optimiser(InterFromGitBranch)
1290
branch.InterBranch.register_optimiser(InterToGitBranch)
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1291
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)