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