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