/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.200.1613 by Jelmer Vernooij
Handle encoding better in working tree iter changes.
1
# Copyright (C) 2007,2012 Canonical Ltd
0.358.2 by Jelmer Vernooij
Refresh copyright headers, add my email.
2
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
3
#
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
0.358.1 by Jelmer Vernooij
Fix FSF address.
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
17
18
"""An adapter between a Git Branch and a Bazaar Branch"""
19
0.200.1594 by Jelmer Vernooij
Use absolute_import everywhere.
20
from __future__ import absolute_import
21
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
22
from io import BytesIO
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
23
from collections import defaultdict
24
7449.1.2 by Jelmer Vernooij
Fix git support.
25
from dulwich.config import (
26
    ConfigFile as GitConfigFile,
27
    parse_submodules,
28
    )
29
0.200.261 by Jelmer Vernooij
More formatting fixes.
30
from dulwich.objects import (
0.200.1717 by Jelmer Vernooij
Ignore tags pointing at non-commit objects.
31
    NotCommitError,
0.200.1153 by Jelmer Vernooij
Import ZERO_SHA from dulwich.objects.
32
    ZERO_SHA,
0.200.261 by Jelmer Vernooij
More formatting fixes.
33
    )
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
34
from dulwich.repo import check_ref_format
0.200.261 by Jelmer Vernooij
More formatting fixes.
35
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
36
from .. import (
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
37
    branch,
7431.1.1 by Jelmer Vernooij
Ignore ghost tags when interacting with remote Git repositories.
38
    cleanup,
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
39
    config,
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
40
    controldir,
0.200.446 by Jelmer Vernooij
Support new 'local' argument.
41
    errors,
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
42
    lock,
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
43
    repository as _mod_repository,
0.200.19 by John Arbash Meinel
More refactoring. Add some direct tests for GitModel.
44
    revision,
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
45
    trace,
0.230.1 by Jelmer Vernooij
Support lightweight checkouts.
46
    transport,
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
47
    urlutils,
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
48
    )
6986.2.3 by Jelmer Vernooij
Merge trunk
49
from ..foreign import ForeignBranch
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
50
from ..revision import (
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
51
    NULL_REVISION,
52
    )
6986.2.3 by Jelmer Vernooij
Merge trunk
53
from ..sixish import (
7018.3.2 by Jelmer Vernooij
Fix some git tests.
54
    text_type,
55
    viewitems,
56
    )
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
57
from ..tag import (
58
    Tags,
59
    InterTags,
60
    )
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
61
from ..trace import (
0.200.342 by Jelmer Vernooij
Report git sha during pull.
62
    is_quiet,
0.200.261 by Jelmer Vernooij
More formatting fixes.
63
    mutter,
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
64
    warning,
0.200.261 by Jelmer Vernooij
More formatting fixes.
65
    )
66
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
67
from .errors import (
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
68
    NoPushSupport,
0.200.278 by Jelmer Vernooij
Update branch head appropriately during dpull.
69
    )
7490.70.1 by Jelmer Vernooij
Add functions for encoding/decoding git paths.
70
from .mapping import (
71
    encode_git_path,
72
    decode_git_path,
73
    )
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
74
from .push import (
75
    remote_divergence,
76
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
77
from .refs import (
0.408.4 by Jelmer Vernooij
Fix some tests.
78
    branch_name_to_ref,
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
79
    is_tag,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
80
    ref_to_branch_name,
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
81
    ref_to_tag_name,
0.346.1 by Jelmer Vernooij
Fix tag caching.
82
    remote_refs_dict_to_tag_refs,
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
83
    tag_name_to_ref,
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
84
    )
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
85
from .unpeel_map import (
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
86
    UnpeelMap,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
87
    )
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
88
from .urls import (
89
    git_url_to_bzr_url,
90
    bzr_url_to_git_url,
91
    )
0.200.261 by Jelmer Vernooij
More formatting fixes.
92
0.200.388 by Jelmer Vernooij
Support bzr 1.14 as well.
93
7339.1.6 by Jelmer Vernooij
Also support revno-less push/pull operations.
94
def _calculate_revnos(branch):
95
    if branch._format.stores_revno():
96
        return True
97
    config = branch.get_config_stack()
98
    return config.get('calculate_revnos')
99
100
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
101
class GitPullResult(branch.PullResult):
0.200.956 by Jelmer Vernooij
Add some more format tests.
102
    """Result of a pull from a Git branch."""
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
103
104
    def _lookup_revno(self, revid):
6973.13.2 by Jelmer Vernooij
Fix some more tests.
105
        if not isinstance(revid, bytes):
0.361.1 by Jelmer Vernooij
Don't use assert.
106
            raise TypeError(revid)
7339.1.6 by Jelmer Vernooij
Also support revno-less push/pull operations.
107
        if not _calculate_revnos(self.target_branch):
108
            return None
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
109
        # Try in source branch first, it'll be faster
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
110
        with self.target_branch.lock_read():
0.200.1362 by Jelmer Vernooij
Add locking.
111
            return self.target_branch.revision_id_to_revno(revid)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
112
113
    @property
114
    def old_revno(self):
115
        return self._lookup_revno(self.old_revid)
116
117
    @property
118
    def new_revno(self):
119
        return self._lookup_revno(self.new_revid)
120
121
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
122
class InterTagsFromGitToRemoteGit(InterTags):
123
124
    @classmethod
125
    def is_compatible(klass, source, target):
126
        if not isinstance(source, GitTags):
127
            return False
128
        if not isinstance(target, GitTags):
129
            return False
130
        if getattr(target.branch.repository, "_git", None) is not None:
131
            return False
132
        return True
133
7489.4.1 by Jelmer Vernooij
Add tag selecting callback.
134
    def merge(self, overwrite=False, ignore_master=False, selector=None):
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
135
        if self.source.branch.repository.has_same_location(self.target.branch.repository):
136
            return {}, []
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
137
        updates = {}
138
        conflicts = []
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
139
        source_tag_refs = self.source.branch.get_tag_refs()
7490.60.1 by Jelmer Vernooij
Add support for new push interface in Dulwich >= 0.20.4.
140
        ref_to_tag_map = {}
7143.15.2 by Jelmer Vernooij
Run autopep8.
141
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
142
        def get_changed_refs(old_refs):
143
            ret = dict(old_refs)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
144
            for ref_name, tag_name, peeled, unpeeled in (
145
                    source_tag_refs.iteritems()):
7489.4.1 by Jelmer Vernooij
Add tag selecting callback.
146
                if selector and not selector(tag_name):
147
                    continue
0.346.1 by Jelmer Vernooij
Fix tag caching.
148
                if old_refs.get(ref_name) == unpeeled:
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
149
                    pass
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
150
                elif overwrite or ref_name not in old_refs:
0.346.1 by Jelmer Vernooij
Fix tag caching.
151
                    ret[ref_name] = unpeeled
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
152
                    updates[tag_name] = self.target.branch.repository.lookup_foreign_revision_id(
7143.15.2 by Jelmer Vernooij
Run autopep8.
153
                        peeled)
7490.60.1 by Jelmer Vernooij
Add support for new push interface in Dulwich >= 0.20.4.
154
                    ref_to_tag_map[ref_name] = tag_name
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
155
                    self.target.branch._tag_refs = None
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
156
                else:
0.346.1 by Jelmer Vernooij
Fix tag caching.
157
                    conflicts.append(
158
                        (tag_name,
7143.15.2 by Jelmer Vernooij
Run autopep8.
159
                         self.repository.lookup_foreign_revision_id(peeled),
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
160
                         self.target.branch.repository.lookup_foreign_revision_id(
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
161
                             old_refs[ref_name])))
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
162
            return ret
7490.60.1 by Jelmer Vernooij
Add support for new push interface in Dulwich >= 0.20.4.
163
        result = self.target.branch.repository.controldir.send_pack(
7143.15.2 by Jelmer Vernooij
Run autopep8.
164
            get_changed_refs, lambda have, want: [])
7490.60.1 by Jelmer Vernooij
Add support for new push interface in Dulwich >= 0.20.4.
165
        if result is not None and not isinstance(result, dict):
166
            for ref, error in result.ref_status.items():
167
                if error:
168
                    warning('unable to update ref %s: %s',
169
                            ref, error)
170
                    del updates[ref_to_tag_map[ref]]
7489.4.4 by Jelmer Vernooij
Add more tests.
171
        return updates, set(conflicts)
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
172
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
173
174
class InterTagsFromGitToLocalGit(InterTags):
175
176
    @classmethod
177
    def is_compatible(klass, source, target):
178
        if not isinstance(source, GitTags):
179
            return False
180
        if not isinstance(target, GitTags):
181
            return False
182
        if getattr(target.branch.repository, "_git", None) is None:
183
            return False
184
        return True
185
7489.4.1 by Jelmer Vernooij
Add tag selecting callback.
186
    def merge(self, overwrite=False, ignore_master=False, selector=None):
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
187
        if self.source.branch.repository.has_same_location(self.target.branch.repository):
188
            return {}, []
189
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
190
        conflicts = []
191
        updates = {}
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
192
        source_tag_refs = self.source.branch.get_tag_refs()
193
194
        target_repo = self.target.branch.repository
195
0.346.1 by Jelmer Vernooij
Fix tag caching.
196
        for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
7489.4.1 by Jelmer Vernooij
Add tag selecting callback.
197
            if selector and not selector(tag_name):
198
                continue
0.346.1 by Jelmer Vernooij
Fix tag caching.
199
            if target_repo._git.refs.get(ref_name) == unpeeled:
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
200
                pass
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
201
            elif overwrite or ref_name not in target_repo._git.refs:
7143.12.3 by Jelmer Vernooij
Ignore ghost tags.
202
                try:
7143.15.8 by Jelmer Vernooij
Merge trunk.
203
                    updates[tag_name] = (
7240.2.1 by Jelmer Vernooij
Don't copy tags that don't point to valid objects.
204
                        target_repo.lookup_foreign_revision_id(peeled))
7143.12.3 by Jelmer Vernooij
Ignore ghost tags.
205
                except KeyError:
206
                    trace.warning('%s does not point to a valid object',
207
                                  tag_name)
7142.3.3 by Jelmer Vernooij
Fix test.
208
                    continue
7405.1.1 by Jelmer Vernooij
Cope with non-commit tags in remote git repositories.
209
                except NotCommitError:
210
                    trace.warning('%s points to a non-commit object',
211
                                  tag_name)
212
                    continue
7240.2.1 by Jelmer Vernooij
Don't copy tags that don't point to valid objects.
213
                target_repo._git.refs[ref_name] = unpeeled or peeled
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
214
                self.target.branch._tag_refs = None
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
215
            else:
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
216
                try:
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
217
                    source_revid = self.source.branch.repository.lookup_foreign_revision_id(
7143.15.8 by Jelmer Vernooij
Merge trunk.
218
                        peeled)
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
219
                    target_revid = target_repo.lookup_foreign_revision_id(
7143.15.2 by Jelmer Vernooij
Run autopep8.
220
                        target_repo._git.refs[ref_name])
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
221
                except KeyError:
222
                    trace.warning('%s does not point to a valid object',
223
                                  ref_name)
224
                    continue
7405.1.1 by Jelmer Vernooij
Cope with non-commit tags in remote git repositories.
225
                except NotCommitError:
226
                    trace.warning('%s points to a non-commit object',
227
                                  tag_name)
228
                    continue
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
229
                conflicts.append((tag_name, source_revid, target_revid))
7489.4.4 by Jelmer Vernooij
Add more tests.
230
        return updates, set(conflicts)
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
231
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
232
233
class InterTagsFromGitToNonGit(InterTags):
234
235
    @classmethod
236
    def is_compatible(klass, source, target):
237
        if not isinstance(source, GitTags):
238
            return False
239
        if isinstance(target, GitTags):
240
            return False
241
        return True
242
7489.4.1 by Jelmer Vernooij
Add tag selecting callback.
243
    def merge(self, overwrite=False, ignore_master=False, selector=None):
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
244
        """See Tags.merge_to."""
245
        source_tag_refs = self.source.branch.get_tag_refs()
246
        if ignore_master:
247
            master = None
248
        else:
249
            master = self.target.branch.get_master_branch()
250
        with cleanup.ExitStack() as es:
251
            if master is not None:
252
                es.enter_context(master.lock_write())
253
            updates, conflicts = self._merge_to(
7489.4.1 by Jelmer Vernooij
Add tag selecting callback.
254
                self.target, source_tag_refs, overwrite=overwrite,
255
                selector=selector)
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
256
            if master is not None:
257
                extra_updates, extra_conflicts = self._merge_to(
258
                    master.tags, overwrite=overwrite,
259
                    source_tag_refs=source_tag_refs,
7489.4.1 by Jelmer Vernooij
Add tag selecting callback.
260
                    ignore_master=ignore_master, selector=selector)
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
261
                updates.update(extra_updates)
7489.4.4 by Jelmer Vernooij
Add more tests.
262
                conflicts.update(extra_conflicts)
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
263
            return updates, conflicts
264
7489.4.1 by Jelmer Vernooij
Add tag selecting callback.
265
    def _merge_to(self, to_tags, source_tag_refs, overwrite=False,
266
                  selector=None):
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
267
        unpeeled_map = defaultdict(set)
268
        conflicts = []
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
269
        updates = {}
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
270
        result = dict(to_tags.get_tag_dict())
0.346.1 by Jelmer Vernooij
Fix tag caching.
271
        for ref_name, tag_name, peeled, unpeeled in source_tag_refs:
7489.4.1 by Jelmer Vernooij
Add tag selecting callback.
272
            if selector and not selector(tag_name):
273
                continue
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
274
            if unpeeled is not None:
275
                unpeeled_map[peeled].add(unpeeled)
0.346.1 by Jelmer Vernooij
Fix tag caching.
276
            try:
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
277
                bzr_revid = self.source.branch.lookup_foreign_revision_id(peeled)
0.346.1 by Jelmer Vernooij
Fix tag caching.
278
            except NotCommitError:
279
                continue
280
            if result.get(tag_name) == bzr_revid:
0.200.1396 by Jelmer Vernooij
Support updating tags in remote branches during pull.
281
                pass
0.346.1 by Jelmer Vernooij
Fix tag caching.
282
            elif tag_name not in result or overwrite:
283
                result[tag_name] = bzr_revid
284
                updates[tag_name] = bzr_revid
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
285
            else:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
286
                conflicts.append((tag_name, bzr_revid, result[tag_name]))
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
287
        to_tags._set_tag_dict(result)
288
        if len(unpeeled_map) > 0:
289
            map_file = UnpeelMap.from_repository(to_tags.branch.repository)
290
            map_file.update(unpeeled_map)
291
            map_file.save_in_repository(to_tags.branch.repository)
7489.4.4 by Jelmer Vernooij
Add more tests.
292
        return updates, set(conflicts)
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
293
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
294
295
InterTags.register_optimiser(InterTagsFromGitToRemoteGit)
296
InterTags.register_optimiser(InterTagsFromGitToLocalGit)
297
InterTags.register_optimiser(InterTagsFromGitToNonGit)
298
299
300
class GitTags(Tags):
301
    """Ref-based tag dictionary."""
302
303
    def __init__(self, branch):
304
        self.branch = branch
305
        self.repository = branch.repository
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
306
307
    def get_tag_dict(self):
308
        ret = {}
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
309
        for (ref_name, tag_name, peeled, unpeeled) in (
310
                self.branch.get_tag_refs()):
0.346.1 by Jelmer Vernooij
Fix tag caching.
311
            try:
312
                bzr_revid = self.branch.lookup_foreign_revision_id(peeled)
313
            except NotCommitError:
314
                continue
315
            else:
316
                ret[tag_name] = bzr_revid
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
317
        return ret
318
7489.3.2 by Jelmer Vernooij
Use InterTags in anger.
319
    def lookup_tag(self, tag_name):
320
        """Return the referent string of a tag"""
321
        # TODO(jelmer): Replace with something more efficient for local tags.
322
        td = self.get_tag_dict()
323
        try:
324
            return td[tag_name]
325
        except KeyError:
326
            raise errors.NoSuchTag(tag_name)
327
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
328
329
class LocalGitTagDict(GitTags):
330
    """Dictionary with tags in a local repository."""
331
332
    def __init__(self, branch):
333
        super(LocalGitTagDict, self).__init__(branch)
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
334
        self.refs = self.repository.controldir._git.refs
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
335
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
336
    def _set_tag_dict(self, to_dict):
0.200.1487 by Jelmer Vernooij
Use peeling.
337
        extra = set(self.refs.allkeys())
6973.13.2 by Jelmer Vernooij
Fix some more tests.
338
        for k, revid in viewitems(to_dict):
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
339
            name = tag_name_to_ref(k)
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
340
            if name in extra:
341
                extra.remove(name)
7455.2.1 by Jelmer Vernooij
Return a FetchResult object from Repository.fetch / Branch.fetch.
342
            try:
343
                self.set_tag(k, revid)
344
            except errors.GhostTagsNotSupported:
345
                pass
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
346
        for name in extra:
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
347
            if is_tag(name):
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
348
                del self.repository._git[name]
0.200.956 by Jelmer Vernooij
Add some more format tests.
349
0.200.86 by Jelmer Vernooij
Clearer error when setting tags.
350
    def set_tag(self, name, revid):
0.200.1369 by Jelmer Vernooij
Clarify that ghost tags are not supported.
351
        try:
352
            git_sha, mapping = self.branch.lookup_bzr_revision_id(revid)
353
        except errors.NoSuchRevision:
354
            raise errors.GhostTagsNotSupported(self)
355
        self.refs[tag_name_to_ref(name)] = git_sha
0.346.1 by Jelmer Vernooij
Fix tag caching.
356
        self.branch._tag_refs = None
357
358
    def delete_tag(self, name):
359
        ref = tag_name_to_ref(name)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
360
        if ref not in self.refs:
0.346.1 by Jelmer Vernooij
Fix tag caching.
361
            raise errors.NoSuchTag(name)
362
        del self.refs[ref]
363
        self.branch._tag_refs = None
0.239.1 by Jelmer Vernooij
Avoid re-connecting to fetch tags we already know.
364
365
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
366
class GitBranchFormat(branch.BranchFormat):
367
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
368
    def network_name(self):
6973.6.2 by Jelmer Vernooij
Fix more tests.
369
        return b"git"
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
370
0.200.82 by Jelmer Vernooij
Support listing tags.
371
    def supports_tags(self):
372
        return True
373
0.200.1105 by Jelmer Vernooij
Don't claim to support leaving locks.
374
    def supports_leaving_lock(self):
375
        return False
376
0.200.1369 by Jelmer Vernooij
Clarify that ghost tags are not supported.
377
    def supports_tags_referencing_ghosts(self):
378
        return False
379
380
    def tags_are_versioned(self):
381
        return False
382
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
383
    def get_foreign_tests_branch_factory(self):
0.200.1644 by Jelmer Vernooij
More relative imports.
384
        from .tests.test_branch import ForeignTestsBranchFactory
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
385
        return ForeignTestsBranchFactory()
386
0.200.246 by Jelmer Vernooij
Cope with API changes in 1.13.
387
    def make_tags(self, branch):
0.200.1487 by Jelmer Vernooij
Use peeling.
388
        try:
389
            return branch.tags
390
        except AttributeError:
391
            pass
0.200.1433 by Jelmer Vernooij
Fix fetching between git repositories.
392
        if getattr(branch.repository, "_git", None) is None:
0.200.1644 by Jelmer Vernooij
More relative imports.
393
            from .remote import RemoteGitTagDict
0.228.3 by Jelmer Vernooij
Fix tags when fetching from remotes.
394
            return RemoteGitTagDict(branch)
0.200.261 by Jelmer Vernooij
More formatting fixes.
395
        else:
396
            return LocalGitTagDict(branch)
0.200.246 by Jelmer Vernooij
Cope with API changes in 1.13.
397
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
398
    def initialize(self, a_controldir, name=None, repository=None,
0.200.1378 by Jelmer Vernooij
Fix branch.
399
                   append_revisions_only=None):
0.295.2 by Jelmer Vernooij
Make RemoteGitBranchFormat uninitializeable.
400
        raise NotImplementedError(self.initialize)
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
401
0.200.1728 by Jelmer Vernooij
Support following branch references.
402
    def get_reference(self, controldir, name=None):
7142.3.1 by Jelmer Vernooij
Support .nick on remote branches and fix get_branch_reference.
403
        return controldir.get_branch_reference(name=name)
0.200.1728 by Jelmer Vernooij
Support following branch references.
404
405
    def set_reference(self, controldir, name, target):
406
        return controldir.set_branch_reference(target, name)
407
7339.1.2 by Jelmer Vernooij
Add stores_revno method to BranchFormat.
408
    def stores_revno(self):
409
        """True if this branch format store revision numbers."""
410
        return False
411
7449.2.4 by Jelmer Vernooij
Set BranchFormat.supports_reference_locations everywhere.
412
    supports_reference_locations = False
413
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
414
0.295.1 by Jelmer Vernooij
Split up branch formats.
415
class LocalGitBranchFormat(GitBranchFormat):
416
417
    def get_format_description(self):
418
        return 'Local Git Branch'
419
420
    @property
421
    def _matchingcontroldir(self):
422
        from .dir import LocalGitControlDirFormat
423
        return LocalGitControlDirFormat()
424
0.295.2 by Jelmer Vernooij
Make RemoteGitBranchFormat uninitializeable.
425
    def initialize(self, a_controldir, name=None, repository=None,
426
                   append_revisions_only=None):
427
        from .dir import LocalGitDir
428
        if not isinstance(a_controldir, LocalGitDir):
429
            raise errors.IncompatibleFormat(self, a_controldir._format)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
430
        return a_controldir.create_branch(
431
            repository=repository, name=name,
432
            append_revisions_only=append_revisions_only)
0.295.2 by Jelmer Vernooij
Make RemoteGitBranchFormat uninitializeable.
433
0.295.1 by Jelmer Vernooij
Split up branch formats.
434
0.200.388 by Jelmer Vernooij
Support bzr 1.14 as well.
435
class GitBranch(ForeignBranch):
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
436
    """An adapter to git repositories for bzr Branch objects."""
437
0.200.1129 by Jelmer Vernooij
Implement GitBranch.control_transport.
438
    @property
439
    def control_transport(self):
0.310.16 by Jelmer Vernooij
Update xfail.
440
        return self._control_transport
0.306.1 by Jelmer Vernooij
Set correct segment parameters on branches.
441
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
442
    @property
443
    def user_transport(self):
444
        return self._user_transport
445
0.295.1 by Jelmer Vernooij
Split up branch formats.
446
    def __init__(self, controldir, repository, ref, format):
0.200.82 by Jelmer Vernooij
Support listing tags.
447
        self.repository = repository
0.295.1 by Jelmer Vernooij
Split up branch formats.
448
        self._format = format
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
449
        self.controldir = controldir
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
450
        self._lock_mode = None
451
        self._lock_count = 0
0.231.1 by Jelmer Vernooij
Check that regenerated objects have the expected sha1.
452
        super(GitBranch, self).__init__(repository.get_mapping())
0.200.770 by Jelmer Vernooij
Proper branch names.
453
        self.ref = ref
0.200.1708 by Jelmer Vernooij
Fix to colocated branch tests.
454
        self._head = None
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
455
        self._user_transport = controldir.user_transport.clone('.')
0.310.16 by Jelmer Vernooij
Update xfail.
456
        self._control_transport = controldir.control_transport.clone('.')
0.346.1 by Jelmer Vernooij
Fix tag caching.
457
        self._tag_refs = None
0.306.1 by Jelmer Vernooij
Set correct segment parameters on branches.
458
        params = {}
0.200.1361 by Jelmer Vernooij
Support branches where the ref can't be mapped back to a branch name.
459
        try:
460
            self.name = ref_to_branch_name(ref)
461
        except ValueError:
462
            self.name = None
0.200.1708 by Jelmer Vernooij
Fix to colocated branch tests.
463
            if self.ref is not None:
0.310.16 by Jelmer Vernooij
Update xfail.
464
                params = {"ref": urlutils.escape(self.ref)}
0.200.1708 by Jelmer Vernooij
Fix to colocated branch tests.
465
        else:
466
            if self.name != "":
0.310.16 by Jelmer Vernooij
Update xfail.
467
                params = {"branch": urlutils.escape(self.name)}
468
        for k, v in params.items():
469
            self._user_transport.set_segment_parameter(k, v)
470
            self._control_transport.set_segment_parameter(k, v)
0.310.14 by Jelmer Vernooij
merge lightweight checkout-in-git support.
471
        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.
472
0.200.1360 by Jelmer Vernooij
Support lighweight argument to _get_checkout_format.
473
    def _get_checkout_format(self, lightweight=False):
0.239.8 by Jelmer Vernooij
Support checkouts.
474
        """Return the most suitable metadir for a checkout of this branch.
475
        Weaves are used if this branch's repository uses weaves.
476
        """
0.311.1 by Jelmer Vernooij
Support git lightweight checkouts.
477
        if lightweight:
478
            return controldir.format_registry.make_controldir("git")
479
        else:
480
            return controldir.format_registry.make_controldir("default")
0.239.8 by Jelmer Vernooij
Support checkouts.
481
0.238.3 by Jelmer Vernooij
Remove svn references, prefer git send format when submitting changes against a git branch.
482
    def get_child_submit_format(self):
483
        """Return the preferred format of submissions to this branch."""
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
484
        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.
485
        if ret is not None:
486
            return ret
487
        return "git"
488
0.200.1397 by Jelmer Vernooij
Fix use of get_config() for RemoteGitBranch.
489
    def get_config(self):
7490.62.3 by Jelmer Vernooij
Move btree and remove references.
490
        from .config import GitBranchConfig
0.200.1397 by Jelmer Vernooij
Fix use of get_config() for RemoteGitBranch.
491
        return GitBranchConfig(self)
492
0.200.1472 by Jelmer Vernooij
Provide basic implementation of Branch.get_config_stack.
493
    def get_config_stack(self):
7490.62.3 by Jelmer Vernooij
Move btree and remove references.
494
        from .config import GitBranchStack
0.200.1472 by Jelmer Vernooij
Provide basic implementation of Branch.get_config_stack.
495
        return GitBranchStack(self)
496
0.200.293 by Jelmer Vernooij
Fix branch nicks.
497
    def _get_nick(self, local=False, possible_master_transports=None):
498
        """Find the nick name for this branch.
499
500
        :return: Branch nick
501
        """
7131.14.1 by Jelmer Vernooij
Fix committing to a bzr branch bound to a git branch.
502
        if getattr(self.repository, '_git', None):
503
            cs = self.repository._git.get_config_stack()
504
            try:
7143.15.12 by Jelmer Vernooij
Merge trunk.
505
                return cs.get((b"branch", self.name.encode('utf-8')),
7490.70.1 by Jelmer Vernooij
Add functions for encoding/decoding git paths.
506
                        b"nick").decode("utf-8")
7131.14.1 by Jelmer Vernooij
Fix committing to a bzr branch bound to a git branch.
507
            except KeyError:
508
                pass
0.200.1694 by Jelmer Vernooij
Fix nick test.
509
        return self.name or u"HEAD"
0.200.293 by Jelmer Vernooij
Fix branch nicks.
510
0.200.331 by Jelmer Vernooij
Add stub for setting nick function.
511
    def _set_nick(self, nick):
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
512
        cf = self.repository._git.get_config()
7143.15.2 by Jelmer Vernooij
Run autopep8.
513
        cf.set((b"branch", self.name.encode('utf-8')),
514
               b"nick", nick.encode("utf-8"))
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
515
        f = BytesIO()
0.200.1547 by Jelmer Vernooij
Support setting branch nicks.
516
        cf.write_to_file(f)
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
517
        self.repository._git._put_named_file('config', f.getvalue())
0.200.331 by Jelmer Vernooij
Add stub for setting nick function.
518
519
    nick = property(_get_nick, _set_nick)
0.200.293 by Jelmer Vernooij
Fix branch nicks.
520
0.200.412 by Jelmer Vernooij
Implement GitBranch.__repr__.
521
    def __repr__(self):
0.200.770 by Jelmer Vernooij
Proper branch names.
522
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
7143.15.2 by Jelmer Vernooij
Run autopep8.
523
                                 self.name)
0.200.412 by Jelmer Vernooij
Implement GitBranch.__repr__.
524
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
525
    def generate_revision_history(self, revid, last_rev=None,
526
                                  other_branch=None):
0.296.2 by Jelmer Vernooij
Handle DivergedBranches.
527
        if last_rev is not None:
528
            graph = self.repository.get_graph()
529
            if not graph.is_ancestor(last_rev, revid):
530
                # our previous tip is not merged into stop_revision
531
                raise errors.DivergedBranches(self, other_branch)
532
0.297.2 by Jelmer Vernooij
Simplify Branch.generate_revision_history.
533
        self.set_last_revision(revid)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
534
0.200.1199 by Jelmer Vernooij
Support 'token' argument to Branch.lock_write.
535
    def lock_write(self, token=None):
536
        if token is not None:
537
            raise errors.TokenLockingNotSupported(self)
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
538
        if self._lock_mode:
0.200.1369 by Jelmer Vernooij
Clarify that ghost tags are not supported.
539
            if self._lock_mode == 'r':
540
                raise errors.ReadOnlyError(self)
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
541
            self._lock_count += 1
542
        else:
0.383.1 by Jelmer Vernooij
Fix a bunch of locking issues.
543
            self._lock_ref()
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
544
            self._lock_mode = 'w'
545
            self._lock_count = 1
546
        self.repository.lock_write()
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
547
        return lock.LogicalLockResult(self.unlock)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
548
0.200.1453 by Jelmer Vernooij
Provide Branch.leave_lock_in_place and Branch.dont_leave_lock_in_place.
549
    def leave_lock_in_place(self):
550
        raise NotImplementedError(self.leave_lock_in_place)
551
552
    def dont_leave_lock_in_place(self):
553
        raise NotImplementedError(self.dont_leave_lock_in_place)
554
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
555
    def get_stacked_on_url(self):
556
        # Git doesn't do stacking (yet...)
0.200.1660 by Jelmer Vernooij
Fix imports.
557
        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.
558
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
559
    def _get_push_origin(self, cs):
7141.8.3 by Jelmer Vernooij
Review comments.
560
        """Get the name for the push origin.
561
562
        The exact behaviour is documented in the git-config(1) manpage.
563
        """
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
564
        try:
7141.8.3 by Jelmer Vernooij
Review comments.
565
            return cs.get((b'branch', self.name.encode('utf-8')), b'pushRemote')
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
566
        except KeyError:
567
            try:
7141.8.3 by Jelmer Vernooij
Review comments.
568
                return cs.get((b'branch', ), b'remote')
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
569
            except KeyError:
570
                try:
7141.8.3 by Jelmer Vernooij
Review comments.
571
                    return cs.get((b'branch', self.name.encode('utf-8')), b'remote')
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
572
                except KeyError:
573
                    return b'origin'
574
575
    def _get_origin(self, cs):
576
        try:
7141.8.3 by Jelmer Vernooij
Review comments.
577
            return cs.get((b'branch', self.name.encode('utf-8')), b'remote')
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
578
        except KeyError:
579
            return b'origin'
580
581
    def _get_related_push_branch(self, cs):
582
        remote = self._get_push_origin(cs)
583
        try:
584
            location = cs.get((b"remote", remote), b"url")
585
        except KeyError:
586
            return None
587
588
        return git_url_to_bzr_url(location.decode('utf-8'), ref=self.ref)
589
590
    def _get_related_merge_branch(self, cs):
591
        remote = self._get_origin(cs)
592
        try:
593
            location = cs.get((b"remote", remote), b"url")
594
        except KeyError:
595
            return None
596
597
        try:
7141.8.3 by Jelmer Vernooij
Review comments.
598
            ref = cs.get((b"branch", remote), b"merge")
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
599
        except KeyError:
600
            ref = self.ref
601
602
        return git_url_to_bzr_url(location.decode('utf-8'), ref=ref)
603
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
604
    def _get_parent_location(self):
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
605
        """See Branch.get_parent()."""
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
606
        cs = self.repository._git.get_config_stack()
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
607
        return self._get_related_merge_branch(cs)
608
609
    def _write_git_config(self, cs):
610
        f = BytesIO()
611
        cs.write_to_file(f)
612
        self.repository._git._put_named_file('config', f.getvalue())
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
613
0.288.3 by Jelmer Vernooij
Fix parent URL handling.
614
    def set_parent(self, location):
615
        cs = self.repository._git.get_config()
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
616
        remote = self._get_origin(cs)
7441.1.1 by Jelmer Vernooij
Add strip_segment_parameters function.
617
        this_url = urlutils.strip_segment_parameters(self.user_url)
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
618
        target_url, branch, ref = bzr_url_to_git_url(location)
0.408.4 by Jelmer Vernooij
Fix some tests.
619
        location = urlutils.relative_url(this_url, target_url)
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
620
        cs.set((b"remote", remote), b"url", location)
621
        if branch:
7141.8.3 by Jelmer Vernooij
Review comments.
622
            cs.set((b"branch", remote), b"merge", branch_name_to_ref(branch))
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
623
        elif ref:
7141.8.3 by Jelmer Vernooij
Review comments.
624
            cs.set((b"branch", remote), b"merge", ref)
0.408.4 by Jelmer Vernooij
Fix some tests.
625
        else:
626
            # TODO(jelmer): Maybe unset rather than setting to HEAD?
7141.8.3 by Jelmer Vernooij
Review comments.
627
            cs.set((b"branch", remote), b"merge", b'HEAD')
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
628
        self._write_git_config(cs)
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
629
0.200.1411 by Jelmer Vernooij
Fix control files.
630
    def break_lock(self):
631
        raise NotImplementedError(self.break_lock)
632
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
633
    def lock_read(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
634
        if self._lock_mode:
0.361.1 by Jelmer Vernooij
Don't use assert.
635
            if self._lock_mode not in ('r', 'w'):
636
                raise ValueError(self._lock_mode)
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
637
            self._lock_count += 1
638
        else:
639
            self._lock_mode = 'r'
640
            self._lock_count = 1
641
        self.repository.lock_read()
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
642
        return lock.LogicalLockResult(self.unlock)
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
643
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
644
    def peek_lock_mode(self):
645
        return self._lock_mode
646
0.200.432 by Jelmer Vernooij
Support Branch.is_locked, required for loggerhead.
647
    def is_locked(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
648
        return (self._lock_mode is not None)
0.200.432 by Jelmer Vernooij
Support Branch.is_locked, required for loggerhead.
649
0.383.1 by Jelmer Vernooij
Fix a bunch of locking issues.
650
    def _lock_ref(self):
651
        pass
652
653
    def _unlock_ref(self):
654
        pass
655
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
656
    def unlock(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
657
        """See Branch.unlock()."""
658
        if self._lock_count == 0:
0.383.1 by Jelmer Vernooij
Fix a bunch of locking issues.
659
            raise errors.LockNotHeld(self)
660
        try:
661
            self._lock_count -= 1
662
            if self._lock_count == 0:
663
                if self._lock_mode == 'w':
664
                    self._unlock_ref()
665
                self._lock_mode = None
666
                self._clear_cached_state()
667
        finally:
668
            self.repository.unlock()
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
669
670
    def get_physical_lock_status(self):
671
        return False
672
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
673
    def last_revision(self):
0.200.1675 by Jelmer Vernooij
Remove uses of decorators.
674
        with self.lock_read():
675
            # perhaps should escape this ?
676
            if self.head is None:
677
                return revision.NULL_REVISION
678
            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.
679
7489.4.4 by Jelmer Vernooij
Add more tests.
680
    def _basic_push(self, target, overwrite=False, stop_revision=None,
681
                    tag_selector=None):
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
682
        return branch.InterBranch.get(self, target)._basic_push(
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
683
            overwrite, stop_revision, tag_selector=tag_selector)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
684
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
685
    def lookup_foreign_revision_id(self, foreign_revid):
0.200.1760 by Jelmer Vernooij
Fall back to simple revision id generation.
686
        try:
687
            return self.repository.lookup_foreign_revision_id(foreign_revid,
7143.15.2 by Jelmer Vernooij
Run autopep8.
688
                                                              self.mapping)
0.200.1760 by Jelmer Vernooij
Fall back to simple revision id generation.
689
        except KeyError:
690
            # Let's try..
691
            return self.mapping.revision_id_foreign_to_bzr(foreign_revid)
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
692
0.200.1030 by Jelmer Vernooij
More work on supporting roundtripping push.
693
    def lookup_bzr_revision_id(self, revid):
694
        return self.repository.lookup_bzr_revision_id(
695
            revid, mapping=self.mapping)
696
0.200.1678 by Jelmer Vernooij
Fix tests.
697
    def get_unshelver(self, tree):
698
        raise errors.StoringUncommittedNotSupported(self)
699
0.346.1 by Jelmer Vernooij
Fix tag caching.
700
    def _clear_cached_state(self):
701
        super(GitBranch, self)._clear_cached_state()
702
        self._tag_refs = None
703
704
    def _iter_tag_refs(self, refs):
705
        """Iterate over the tag refs.
706
707
        :param refs: Refs dictionary (name -> git sha1)
708
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
709
        """
710
        raise NotImplementedError(self._iter_tag_refs)
711
0.375.1 by Jelmer Vernooij
Fix remote tests, warn when fetching git->bzr and bzr->git.
712
    def get_tag_refs(self):
713
        with self.lock_read():
714
            if self._tag_refs is None:
715
                self._tag_refs = list(self._iter_tag_refs())
716
            return self._tag_refs
717
7131.14.1 by Jelmer Vernooij
Fix committing to a bzr branch bound to a git branch.
718
    def import_last_revision_info_and_tags(self, source, revno, revid,
719
                                           lossy=False):
720
        """Set the last revision info, importing from another repo if necessary.
721
722
        This is used by the bound branch code to upload a revision to
723
        the master branch first before updating the tip of the local branch.
724
        Revisions referenced by source's tags are also transferred.
725
726
        :param source: Source branch to optionally fetch from
727
        :param revno: Revision number of the new tip
728
        :param revid: Revision id of the new tip
729
        :param lossy: Whether to discard metadata that can not be
730
            natively represented
731
        :return: Tuple with the new revision number and revision id
732
            (should only be different from the arguments when lossy=True)
733
        """
7131.14.2 by Jelmer Vernooij
Make sure resulting branch is correct too.
734
        push_result = source.push(
735
            self, stop_revision=revid, lossy=lossy, _stop_revno=revno)
736
        return (push_result.new_revno, push_result.new_revid)
7131.14.1 by Jelmer Vernooij
Fix committing to a bzr branch bound to a git branch.
737
7206.6.4 by Jelmer Vernooij
Move reconcile logic to breezy.bzr.reconcile.
738
    def reconcile(self, thorough=True):
739
        """Make sure the data stored in this branch is consistent."""
740
        from ..reconcile import ReconcileResult
741
        # Nothing to do here
742
        return ReconcileResult()
743
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
744
0.200.465 by Jelmer Vernooij
Use dulwich standard functionality for finding missing revisions.
745
class LocalGitBranch(GitBranch):
746
    """A local Git branch."""
747
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
748
    def __init__(self, controldir, repository, ref):
0.295.1 by Jelmer Vernooij
Split up branch formats.
749
        super(LocalGitBranch, self).__init__(controldir, repository, ref,
7143.15.2 by Jelmer Vernooij
Run autopep8.
750
                                             LocalGitBranchFormat())
0.200.763 by Jelmer Vernooij
Provide proper colocated branch support.
751
0.200.261 by Jelmer Vernooij
More formatting fixes.
752
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
7143.15.2 by Jelmer Vernooij
Run autopep8.
753
                        accelerator_tree=None, hardlink=False):
0.200.1774 by Jelmer Vernooij
Simplify checkout creation.
754
        t = transport.get_transport(to_location)
755
        t.ensure_base()
756
        format = self._get_checkout_format(lightweight=lightweight)
757
        checkout = format.initialize_on_transport(t)
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
758
        if lightweight:
0.200.1774 by Jelmer Vernooij
Simplify checkout creation.
759
            from_branch = checkout.set_branch_reference(target_branch=self)
760
        else:
7143.15.14 by Jelmer Vernooij
Fix repo acquisition.
761
            policy = checkout.determine_repository_policy()
762
            policy.acquire_repository()
0.200.1774 by Jelmer Vernooij
Simplify checkout creation.
763
            checkout_branch = checkout.create_branch()
764
            checkout_branch.bind(self)
765
            checkout_branch.pull(self, stop_revision=revision_id)
766
            from_branch = None
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
767
        return checkout.create_workingtree(
768
            revision_id, from_branch=from_branch, hardlink=hardlink)
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
769
0.383.1 by Jelmer Vernooij
Fix a bunch of locking issues.
770
    def _lock_ref(self):
771
        self._ref_lock = self.repository._git.refs.lock_ref(self.ref)
772
773
    def _unlock_ref(self):
774
        self._ref_lock.unlock()
775
0.412.1 by Jelmer Vernooij
Implement Branch.break_lock.
776
    def break_lock(self):
777
        self.repository._git.refs.unlock_ref(self.ref)
778
0.200.57 by Jelmer Vernooij
Fix more tests.
779
    def _gen_revision_history(self):
0.200.58 by Jelmer Vernooij
Fix remaining tests.
780
        if self.head is None:
781
            return []
6968.1.1 by Jelmer Vernooij
Support 'bzr version-info' in horizon branches.
782
        last_revid = self.last_revision()
0.200.1279 by Jelmer Vernooij
Avoid using deprecated Repository.iter_reverse_revision_history.
783
        graph = self.repository.get_graph()
6968.1.1 by Jelmer Vernooij
Support 'bzr version-info' in horizon branches.
784
        try:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
785
            ret = list(graph.iter_lefthand_ancestry(
786
                last_revid, (revision.NULL_REVISION, )))
6968.1.1 by Jelmer Vernooij
Support 'bzr version-info' in horizon branches.
787
        except errors.RevisionNotPresent as e:
788
            raise errors.GhostRevisionsHaveNoRevno(last_revid, e.revision_id)
0.200.59 by Jelmer Vernooij
Add more tests, fix revision history.
789
        ret.reverse()
0.200.57 by Jelmer Vernooij
Fix more tests.
790
        return ret
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
791
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
792
    def _get_head(self):
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
793
        try:
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
794
            return self.repository._git.refs[self.ref]
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
795
        except KeyError:
796
            return None
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
797
0.200.1228 by Jelmer Vernooij
Provide Branch._read_last_revision_info.
798
    def _read_last_revision_info(self):
799
        last_revid = self.last_revision()
800
        graph = self.repository.get_graph()
7143.8.1 by Jelmer Vernooij
Cope with the revno not being known.
801
        try:
7143.15.6 by Jelmer Vernooij
Merge trunk.
802
            revno = graph.find_distance_to_null(
803
                last_revid, [(revision.NULL_REVISION, 0)])
7143.8.1 by Jelmer Vernooij
Cope with the revno not being known.
804
        except errors.GhostRevisionsHaveNoRevno:
805
            revno = None
0.200.1228 by Jelmer Vernooij
Provide Branch._read_last_revision_info.
806
        return revno, last_revid
807
808
    def set_last_revision_info(self, revno, revision_id):
809
        self.set_last_revision(revision_id)
810
        self._last_revision_info_cache = revno, revision_id
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
811
812
    def set_last_revision(self, revid):
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
813
        if not revid or not isinstance(revid, bytes):
0.200.1233 by Jelmer Vernooij
Implement Repository.iter_files_bytes.
814
            raise errors.InvalidRevisionId(revision_id=revid, branch=self)
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
815
        if revid == NULL_REVISION:
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
816
            newhead = None
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
817
        else:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
818
            (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(
819
                revid)
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
820
            if self.mapping is None:
821
                raise AssertionError
822
        self._set_head(newhead)
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
823
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
824
    def _set_head(self, value):
0.361.1 by Jelmer Vernooij
Don't use assert.
825
        if value == ZERO_SHA:
826
            raise ValueError(value)
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
827
        self._head = value
0.336.2 by Jelmer Vernooij
Don't use ZERO_SHA outside of remote communication to indicate empty history.
828
        if value is None:
829
            del self.repository._git.refs[self.ref]
830
        else:
831
            self.repository._git.refs[self.ref] = self._head
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
832
        self._clear_cached_state()
833
834
    head = property(_get_head, _set_head)
835
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
836
    def get_push_location(self):
837
        """See Branch.get_push_location."""
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
838
        push_loc = self.get_config_stack().get('push_location')
7141.8.1 by Jelmer Vernooij
Read parent branch properly from git config.
839
        if push_loc is not None:
840
            return push_loc
841
        cs = self.repository._git.get_config_stack()
842
        return self._get_related_push_branch(cs)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
843
844
    def set_push_location(self, location):
845
        """See Branch.set_push_location."""
0.200.19 by John Arbash Meinel
More refactoring. Add some direct tests for GitModel.
846
        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.
847
                                          store=config.STORE_LOCATION)
0.200.43 by David Allouche
Ultra-experimental support for "bzr pull". No test. No sanity.
848
849
    def supports_tags(self):
0.200.82 by Jelmer Vernooij
Support listing tags.
850
        return True
0.200.956 by Jelmer Vernooij
Add some more format tests.
851
0.200.1681 by Jelmer Vernooij
Provide Branch.store_uncommitted.
852
    def store_uncommitted(self, creator):
853
        raise errors.StoringUncommittedNotSupported(self)
854
0.346.1 by Jelmer Vernooij
Fix tag caching.
855
    def _iter_tag_refs(self):
856
        """Iterate over the tag refs.
857
858
        :param refs: Refs dictionary (name -> git sha1)
859
        :return: iterator over (ref_name, tag_name, peeled_sha1, unpeeled_sha1)
860
        """
7371.2.1 by Jelmer Vernooij
Fix importing from remote git repositories.
861
        refs = self.repository.controldir.get_refs_container()
7018.3.2 by Jelmer Vernooij
Fix some git tests.
862
        for ref_name, unpeeled in viewitems(refs.as_dict()):
0.346.1 by Jelmer Vernooij
Fix tag caching.
863
            try:
864
                tag_name = ref_to_tag_name(ref_name)
865
            except (ValueError, UnicodeDecodeError):
866
                continue
867
            peeled = refs.get_peeled(ref_name)
868
            if peeled is None:
0.382.1 by Jelmer Vernooij
Various fixes for annotated tags and symrefs.
869
                peeled = unpeeled
6973.6.2 by Jelmer Vernooij
Fix more tests.
870
            if not isinstance(tag_name, text_type):
0.361.1 by Jelmer Vernooij
Don't use assert.
871
                raise TypeError(tag_name)
0.346.1 by Jelmer Vernooij
Fix tag caching.
872
            yield (ref_name, tag_name, peeled, unpeeled)
873
0.360.1 by Jelmer Vernooij
Implement GitMemoryTree.
874
    def create_memorytree(self):
875
        from .memorytree import GitMemoryTree
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
876
        return GitMemoryTree(self, self.repository._git.object_store,
877
                             self.head)
0.360.1 by Jelmer Vernooij
Implement GitMemoryTree.
878
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
879
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
880
def _quick_lookup_revno(local_branch, remote_branch, revid):
6973.13.2 by Jelmer Vernooij
Fix some more tests.
881
    if not isinstance(revid, bytes):
0.361.1 by Jelmer Vernooij
Don't use assert.
882
        raise TypeError(revid)
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
883
    # Try in source branch first, it'll be faster
0.200.1788 by Jelmer Vernooij
Use context managers.
884
    with local_branch.lock_read():
7339.1.6 by Jelmer Vernooij
Also support revno-less push/pull operations.
885
        if not _calculate_revnos(local_branch):
886
            return None
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
887
        try:
0.200.1362 by Jelmer Vernooij
Add locking.
888
            return local_branch.revision_id_to_revno(revid)
889
        except errors.NoSuchRevision:
890
            graph = local_branch.repository.get_graph()
891
            try:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
892
                return graph.find_distance_to_null(
893
                    revid, [(revision.NULL_REVISION, 0)])
0.200.1362 by Jelmer Vernooij
Add locking.
894
            except errors.GhostRevisionsHaveNoRevno:
7339.1.6 by Jelmer Vernooij
Also support revno-less push/pull operations.
895
                if not _calculate_revnos(remote_branch):
896
                    return None
0.200.1362 by Jelmer Vernooij
Add locking.
897
                # FIXME: Check using graph.find_distance_to_null() ?
0.200.1788 by Jelmer Vernooij
Use context managers.
898
                with remote_branch.lock_read():
0.200.1362 by Jelmer Vernooij
Add locking.
899
                    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.
900
901
0.200.342 by Jelmer Vernooij
Report git sha during pull.
902
class GitBranchPullResult(branch.PullResult):
903
0.252.36 by Jelmer Vernooij
Fix pull.
904
    def __init__(self):
905
        super(GitBranchPullResult, self).__init__()
906
        self.new_git_head = None
907
        self._old_revno = None
908
        self._new_revno = None
909
0.200.342 by Jelmer Vernooij
Report git sha during pull.
910
    def report(self, to_file):
911
        if not is_quiet():
912
            if self.old_revid == self.new_revid:
913
                to_file.write('No revisions to pull.\n')
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
914
            elif self.new_git_head is not None:
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
915
                to_file.write('Now on revision %d (git sha: %s).\n' %
7143.15.2 by Jelmer Vernooij
Run autopep8.
916
                              (self.new_revno, self.new_git_head))
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
917
            else:
918
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
0.200.342 by Jelmer Vernooij
Report git sha during pull.
919
        self._show_tag_conficts(to_file)
920
0.252.36 by Jelmer Vernooij
Fix pull.
921
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
922
        return _quick_lookup_revno(self.target_branch, self.source_branch,
7143.15.2 by Jelmer Vernooij
Run autopep8.
923
                                   revid)
0.252.36 by Jelmer Vernooij
Fix pull.
924
925
    def _get_old_revno(self):
926
        if self._old_revno is not None:
927
            return self._old_revno
928
        return self._lookup_revno(self.old_revid)
929
930
    def _set_old_revno(self, revno):
931
        self._old_revno = revno
932
933
    old_revno = property(_get_old_revno, _set_old_revno)
934
935
    def _get_new_revno(self):
936
        if self._new_revno is not None:
937
            return self._new_revno
938
        return self._lookup_revno(self.new_revid)
939
940
    def _set_new_revno(self, revno):
941
        self._new_revno = revno
0.200.956 by Jelmer Vernooij
Add some more format tests.
942
0.252.36 by Jelmer Vernooij
Fix pull.
943
    new_revno = property(_get_new_revno, _set_new_revno)
944
0.200.342 by Jelmer Vernooij
Report git sha during pull.
945
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
946
class GitBranchPushResult(branch.BranchPushResult):
947
948
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
949
        return _quick_lookup_revno(self.source_branch, self.target_branch,
7143.15.2 by Jelmer Vernooij
Run autopep8.
950
                                   revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
951
952
    @property
953
    def old_revno(self):
954
        return self._lookup_revno(self.old_revid)
955
956
    @property
957
    def new_revno(self):
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
958
        new_original_revno = getattr(self, "new_original_revno", None)
959
        if new_original_revno:
960
            return new_original_revno
961
        if getattr(self, "new_original_revid", None) is not None:
962
            return self._lookup_revno(self.new_original_revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
963
        return self._lookup_revno(self.new_revid)
964
965
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
966
class InterFromGitBranch(branch.GenericInterBranch):
0.200.261 by Jelmer Vernooij
More formatting fixes.
967
    """InterBranch implementation that pulls from Git into bzr."""
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
968
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
969
    @staticmethod
970
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
971
        try:
972
            default_format = branch.format_registry.get_default()
973
        except AttributeError:
974
            default_format = branch.BranchFormat._default_format
0.295.4 by Jelmer Vernooij
Fix imports.
975
        from .remote import RemoteGitBranchFormat
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
976
        return [
0.295.1 by Jelmer Vernooij
Split up branch formats.
977
            (RemoteGitBranchFormat(), default_format),
978
            (LocalGitBranchFormat(), default_format)]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
979
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
980
    @classmethod
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
981
    def _get_interrepo(self, source, target):
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
982
        return _mod_repository.InterRepository.get(
983
            source.repository, target.repository)
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
984
985
    @classmethod
986
    def is_compatible(cls, source, target):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
987
        if not isinstance(source, GitBranch):
988
            return False
989
        if isinstance(target, GitBranch):
990
            # InterLocalGitRemoteGitBranch or InterToGitBranch should be used
991
            return False
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
992
        if (getattr(cls._get_interrepo(source, target), "fetch_objects", None)
993
                is None):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
994
            # fetch_objects is necessary for this to work
995
            return False
996
        return True
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
997
7455.2.1 by Jelmer Vernooij
Return a FetchResult object from Repository.fetch / Branch.fetch.
998
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None, lossy=False):
999
        self.fetch_objects(
1000
            stop_revision, fetch_tags=fetch_tags, limit=limit, lossy=lossy)
1001
        return _mod_repository.FetchResult()
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
1002
7489.4.4 by Jelmer Vernooij
Add more tests.
1003
    def fetch_objects(self, stop_revision, fetch_tags, limit=None, lossy=False, tag_selector=None):
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
1004
        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.
1005
        if fetch_tags is None:
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
1006
            c = self.source.get_config_stack()
1007
            fetch_tags = c.get('branch.fetch_tags')
7143.15.2 by Jelmer Vernooij
Run autopep8.
1008
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
1009
        def determine_wants(heads):
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
1010
            if stop_revision is None:
0.336.6 by Jelmer Vernooij
Fix pull tests.
1011
                try:
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
1012
                    head = heads[self.source.ref]
0.336.6 by Jelmer Vernooij
Fix pull tests.
1013
                except KeyError:
1014
                    self._last_revid = revision.NULL_REVISION
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
1015
                else:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1016
                    self._last_revid = self.source.lookup_foreign_revision_id(
1017
                        head)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
1018
            else:
1019
                self._last_revid = stop_revision
1020
            real = interrepo.get_determine_wants_revids(
7489.4.4 by Jelmer Vernooij
Add more tests.
1021
                [self._last_revid], include_tags=fetch_tags, tag_selector=tag_selector)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
1022
            return real(heads)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
1023
        pack_hint, head, refs = interrepo.fetch_objects(
7455.2.1 by Jelmer Vernooij
Return a FetchResult object from Repository.fetch / Branch.fetch.
1024
            determine_wants, self.source.mapping, limit=limit,
1025
            lossy=lossy)
0.252.45 by Jelmer Vernooij
Finish fetching roundtripped revisions back into bzr.
1026
        if (pack_hint is not None and
7143.15.2 by Jelmer Vernooij
Run autopep8.
1027
                self.target.repository._format.pack_compresses):
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
1028
            self.target.repository.pack(hint=pack_hint)
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
1029
        return head, refs
1030
7489.4.4 by Jelmer Vernooij
Add more tests.
1031
    def _update_revisions(self, stop_revision=None, overwrite=False, tag_selector=None):
1032
        head, refs = self.fetch_objects(stop_revision, fetch_tags=None, tag_selector=tag_selector)
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
1033
        if overwrite:
0.200.314 by Jelmer Vernooij
Support stop_revision.
1034
            prev_last_revid = None
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
1035
        else:
0.200.314 by Jelmer Vernooij
Support stop_revision.
1036
            prev_last_revid = self.target.last_revision()
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1037
        self.target.generate_revision_history(
1038
            self._last_revid, last_rev=prev_last_revid,
1039
            other_branch=self.source)
0.200.1062 by Jelmer Vernooij
Pass remote refs along in _update_revisions.
1040
        return head, refs
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
1041
7449.1.2 by Jelmer Vernooij
Fix git support.
1042
    def update_references(self, revid=None):
1043
        if revid is None:
1044
            revid = self.target.last_revision()
1045
        tree = self.target.repository.revision_tree(revid)
1046
        try:
1047
            with tree.get_file('.gitmodules') as f:
1048
                for path, url, section in parse_submodules(
1049
                        GitConfigFile.from_file(f)):
1050
                    self.target.set_reference_info(
7490.70.1 by Jelmer Vernooij
Add functions for encoding/decoding git paths.
1051
                        tree.path2id(decode_git_path(path)), url.decode('utf-8'),
1052
                        decode_git_path(path))
7449.1.2 by Jelmer Vernooij
Fix git support.
1053
        except errors.NoSuchFile:
1054
            pass
1055
0.200.1423 by Jelmer Vernooij
Fix space.
1056
    def _basic_pull(self, stop_revision, overwrite, run_hooks,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1057
                    _override_hook_target, _hook_master, tag_selector=None):
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1058
        if overwrite is True:
1059
            overwrite = set(["history", "tags"])
7142.3.2 by Jelmer Vernooij
Fix overwrite for git branches.
1060
        elif not overwrite:
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1061
            overwrite = set()
0.200.342 by Jelmer Vernooij
Report git sha during pull.
1062
        result = GitBranchPullResult()
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
1063
        result.source_branch = self.source
1064
        if _override_hook_target is None:
1065
            result.target_branch = self.target
1066
        else:
1067
            result.target_branch = _override_hook_target
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1068
        with self.target.lock_write(), self.source.lock_read():
1069
            # We assume that during 'pull' the target repository is closer than
1070
            # the source one.
1071
            (result.old_revno, result.old_revid) = \
1072
                self.target.last_revision_info()
1073
            result.new_git_head, remote_refs = self._update_revisions(
7489.4.4 by Jelmer Vernooij
Add more tests.
1074
                stop_revision, overwrite=("history" in overwrite),
1075
                tag_selector=tag_selector)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1076
            tags_ret = self.source.tags.merge_to(
7489.4.4 by Jelmer Vernooij
Add more tests.
1077
                self.target.tags, ("tags" in overwrite), ignore_master=True)
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1078
            if isinstance(tags_ret, tuple):
1079
                result.tag_updates, result.tag_conflicts = tags_ret
1080
            else:
1081
                result.tag_conflicts = tags_ret
1082
            (result.new_revno, result.new_revid) = \
1083
                self.target.last_revision_info()
7449.1.2 by Jelmer Vernooij
Fix git support.
1084
            self.update_references(revid=result.new_revid)
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1085
            if _hook_master:
1086
                result.master_branch = _hook_master
1087
                result.local_branch = result.target_branch
1088
            else:
1089
                result.master_branch = result.target_branch
1090
                result.local_branch = None
1091
            if run_hooks:
1092
                for hook in branch.Branch.hooks['post_pull']:
1093
                    hook(result)
1094
            return result
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
1095
1096
    def pull(self, overwrite=False, stop_revision=None,
1097
             possible_transports=None, _hook_master=None, run_hooks=True,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1098
             _override_hook_target=None, local=False, tag_selector=None):
0.200.1414 by Jelmer Vernooij
Fix pulling into bound branches.
1099
        """See Branch.pull.
1100
1101
        :param _hook_master: Private parameter - set the branch to
1102
            be supplied as the master to pull hooks.
1103
        :param run_hooks: Private parameter - if false, this branch
1104
            is being called because it's the master of the primary branch,
1105
            so it should not run its hooks.
1106
        :param _override_hook_target: Private parameter - set the branch to be
1107
            supplied as the target_branch to pull hooks.
1108
        """
1109
        # This type of branch can't be bound.
1110
        bound_location = self.target.get_bound_location()
1111
        if local and not bound_location:
1112
            raise errors.LocalRequiresBoundBranch()
1113
        source_is_master = False
7431.1.1 by Jelmer Vernooij
Ignore ghost tags when interacting with remote Git repositories.
1114
        with cleanup.ExitStack() as es:
1115
            es.enter_context(self.source.lock_read())
1116
            if bound_location:
1117
                # bound_location comes from a config file, some care has to be
1118
                # taken to relate it to source.user_url
1119
                normalized = urlutils.normalize_url(bound_location)
1120
                try:
1121
                    relpath = self.source.user_transport.relpath(normalized)
1122
                    source_is_master = (relpath == '')
1123
                except (errors.PathNotChild, urlutils.InvalidURL):
1124
                    source_is_master = False
1125
            if not local and bound_location and not source_is_master:
1126
                # not pulling from master, so we need to update master.
1127
                master_branch = self.target.get_master_branch(possible_transports)
1128
                es.enter_context(master_branch.lock_write())
1129
                # pull from source into master.
1130
                master_branch.pull(self.source, overwrite, stop_revision,
7489.4.4 by Jelmer Vernooij
Add more tests.
1131
                                   run_hooks=False)
7431.1.1 by Jelmer Vernooij
Ignore ghost tags when interacting with remote Git repositories.
1132
            else:
1133
                master_branch = None
1134
            return self._basic_pull(stop_revision, overwrite, run_hooks,
1135
                                    _override_hook_target,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1136
                                    _hook_master=master_branch,
1137
                                    tag_selector=tag_selector)
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
1138
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1139
    def _basic_push(self, overwrite, stop_revision, tag_selector=None):
0.331.1 by Jelmer Vernooij
Fix some tags tests.
1140
        if overwrite is True:
1141
            overwrite = set(["history", "tags"])
7142.3.2 by Jelmer Vernooij
Fix overwrite for git branches.
1142
        elif not overwrite:
0.331.1 by Jelmer Vernooij
Fix some tags tests.
1143
            overwrite = set()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1144
        result = branch.BranchPushResult()
1145
        result.source_branch = self.source
1146
        result.target_branch = self.target
1147
        result.old_revno, result.old_revid = self.target.last_revision_info()
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
1148
        result.new_git_head, remote_refs = self._update_revisions(
7489.4.4 by Jelmer Vernooij
Add more tests.
1149
            stop_revision, overwrite=("history" in overwrite),
1150
            tag_selector=tag_selector)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1151
        tags_ret = self.source.tags.merge_to(
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1152
            self.target.tags, "tags" in overwrite, ignore_master=True,
1153
            selector=tag_selector)
0.331.1 by Jelmer Vernooij
Fix some tags tests.
1154
        (result.tag_updates, result.tag_conflicts) = tags_ret
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1155
        result.new_revno, result.new_revid = self.target.last_revision_info()
7449.1.2 by Jelmer Vernooij
Fix git support.
1156
        self.update_references(revid=result.new_revid)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1157
        return result
1158
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
1159
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1160
class InterGitBranch(branch.GenericInterBranch):
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1161
    """InterBranch implementation that pulls between Git branches."""
1162
7455.2.1 by Jelmer Vernooij
Return a FetchResult object from Repository.fetch / Branch.fetch.
1163
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None, lossy=False):
0.200.1493 by Jelmer Vernooij
Test fixes.
1164
        raise NotImplementedError(self.fetch)
1165
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1166
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1167
class InterLocalGitRemoteGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1168
    """InterBranch that copies from a local to a remote git branch."""
1169
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
1170
    @staticmethod
1171
    def _get_branch_formats_to_test():
0.295.4 by Jelmer Vernooij
Fix imports.
1172
        from .remote import RemoteGitBranchFormat
0.295.3 by Jelmer Vernooij
Fix some more tests.
1173
        return [
1174
            (LocalGitBranchFormat(), RemoteGitBranchFormat())]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
1175
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1176
    @classmethod
1177
    def is_compatible(self, source, target):
0.200.1644 by Jelmer Vernooij
More relative imports.
1178
        from .remote import RemoteGitBranch
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1179
        return (isinstance(source, LocalGitBranch) and
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1180
                isinstance(target, RemoteGitBranch))
1181
7489.4.7 by Jelmer Vernooij
Fix test.
1182
    def _basic_push(self, overwrite, stop_revision, tag_selector=None):
7490.91.1 by Jelmer Vernooij
Handle GitLab protected branch errors.
1183
        from .remote import parse_git_error
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1184
        result = GitBranchPushResult()
1185
        result.source_branch = self.source
1186
        result.target_branch = self.target
1187
        if stop_revision is None:
1188
            stop_revision = self.source.last_revision()
7143.15.2 by Jelmer Vernooij
Run autopep8.
1189
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1190
        def get_changed_refs(old_refs):
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
1191
            old_ref = old_refs.get(self.target.ref, None)
1192
            if old_ref is None:
1193
                result.old_revid = revision.NULL_REVISION
1194
            else:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1195
                result.old_revid = self.target.lookup_foreign_revision_id(
1196
                    old_ref)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1197
            new_ref = self.source.repository.lookup_bzr_revision_id(
1198
                stop_revision)[0]
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
1199
            if not overwrite:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1200
                if remote_divergence(
1201
                        old_ref, new_ref,
1202
                        self.source.repository._git.object_store):
0.404.5 by Jelmer Vernooij
Check for diverged branches during push.
1203
                    raise errors.DivergedBranches(self.source, self.target)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1204
            refs = {self.target.ref: new_ref}
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1205
            result.new_revid = stop_revision
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1206
            for name, sha in viewitems(
1207
                    self.source.repository._git.refs.as_dict(b"refs/tags")):
7489.4.7 by Jelmer Vernooij
Fix test.
1208
                if tag_selector and not tag_selector(name):
1209
                    continue
7431.1.1 by Jelmer Vernooij
Ignore ghost tags when interacting with remote Git repositories.
1210
                if sha not in self.source.repository._git:
1211
                    trace.mutter('Ignoring missing SHA: %s', sha)
1212
                    continue
7489.4.4 by Jelmer Vernooij
Add more tests.
1213
                refs[tag_name_to_ref(name)] = sha
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1214
            return refs
7490.60.1 by Jelmer Vernooij
Add support for new push interface in Dulwich >= 0.20.4.
1215
        dw_result = self.target.repository.send_pack(
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1216
            get_changed_refs,
7490.26.2 by Jelmer Vernooij
More shallow work.
1217
            self.source.repository._git.generate_pack_data)
7490.60.1 by Jelmer Vernooij
Add support for new push interface in Dulwich >= 0.20.4.
1218
        if dw_result is not None and not isinstance(dw_result, dict):
1219
            error = dw_result.ref_status.get(self.target.ref)
1220
            if error:
7490.91.2 by Jelmer Vernooij
Fix number of arguments.
1221
                raise parse_git_error(self.target.user_url, error)
7490.60.1 by Jelmer Vernooij
Add support for new push interface in Dulwich >= 0.20.4.
1222
            for ref, error in dw_result.ref_status.items():
1223
                if error:
7490.91.1 by Jelmer Vernooij
Handle GitLab protected branch errors.
1224
                    trace.warning('unable to open ref %s: %s', ref, error)
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1225
        return result
1226
1227
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1228
class InterGitLocalGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
1229
    """InterBranch that copies from a remote to a local git branch."""
1230
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
1231
    @staticmethod
1232
    def _get_branch_formats_to_test():
0.295.4 by Jelmer Vernooij
Fix imports.
1233
        from .remote import RemoteGitBranchFormat
0.295.3 by Jelmer Vernooij
Fix some more tests.
1234
        return [
1235
            (RemoteGitBranchFormat(), LocalGitBranchFormat()),
1236
            (LocalGitBranchFormat(), LocalGitBranchFormat())]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
1237
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1238
    @classmethod
1239
    def is_compatible(self, source, target):
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1240
        return (isinstance(source, GitBranch) and
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1241
                isinstance(target, LocalGitBranch))
1242
7455.2.1 by Jelmer Vernooij
Return a FetchResult object from Repository.fetch / Branch.fetch.
1243
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None, lossy=False):
1244
        interrepo = _mod_repository.InterRepository.get(
1245
            self.source.repository, self.target.repository)
0.200.1534 by Jelmer Vernooij
Implement fetch between git branches, encode nicks.
1246
        if stop_revision is None:
1247
            stop_revision = self.source.last_revision()
7380.1.1 by Jelmer Vernooij
Several more fixes for git merge proposals.
1248
        if fetch_tags is None:
1249
            c = self.source.get_config_stack()
1250
            fetch_tags = c.get('branch.fetch_tags')
0.200.1534 by Jelmer Vernooij
Implement fetch between git branches, encode nicks.
1251
        determine_wants = interrepo.get_determine_wants_revids(
1252
            [stop_revision], include_tags=fetch_tags)
7455.2.1 by Jelmer Vernooij
Return a FetchResult object from Repository.fetch / Branch.fetch.
1253
        interrepo.fetch_objects(determine_wants, limit=limit, lossy=lossy)
1254
        return _mod_repository.FetchResult()
0.200.1534 by Jelmer Vernooij
Implement fetch between git branches, encode nicks.
1255
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1256
    def _basic_push(self, overwrite=False, stop_revision=None, tag_selector=None):
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1257
        if overwrite is True:
1258
            overwrite = set(["history", "tags"])
7142.3.2 by Jelmer Vernooij
Fix overwrite for git branches.
1259
        elif not overwrite:
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1260
            overwrite = set()
0.200.1325 by Jelmer Vernooij
More test fixes.
1261
        result = GitBranchPushResult()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1262
        result.source_branch = self.source
1263
        result.target_branch = self.target
1264
        result.old_revid = self.target.last_revision()
1265
        refs, stop_revision = self.update_refs(stop_revision)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1266
        self.target.generate_revision_history(
1267
            stop_revision,
1268
            (result.old_revid if ("history" not in overwrite) else None),
1269
            other_branch=self.source)
1270
        tags_ret = self.source.tags.merge_to(
1271
            self.target.tags,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1272
            overwrite=("tags" in overwrite),
1273
            selector=tag_selector)
0.200.1402 by Jelmer Vernooij
Cope with tag changes in bzr.
1274
        if isinstance(tags_ret, tuple):
1275
            (result.tag_updates, result.tag_conflicts) = tags_ret
1276
        else:
1277
            result.tag_conflicts = tags_ret
0.200.505 by Jelmer Vernooij
Remove duplicate code.
1278
        result.new_revid = self.target.last_revision()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1279
        return result
1280
1281
    def update_refs(self, stop_revision=None):
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1282
        interrepo = _mod_repository.InterRepository.get(
7143.15.2 by Jelmer Vernooij
Run autopep8.
1283
            self.source.repository, self.target.repository)
0.296.1 by Jelmer Vernooij
Fix tag fetching.
1284
        c = self.source.get_config_stack()
1285
        fetch_tags = c.get('branch.fetch_tags')
1286
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1287
        if stop_revision is None:
7455.2.2 by Jelmer Vernooij
Fix git tests.
1288
            result = interrepo.fetch(branches=[self.source.ref], include_tags=fetch_tags)
0.336.5 by Jelmer Vernooij
Fix some tests.
1289
            try:
7455.2.2 by Jelmer Vernooij
Fix git tests.
1290
                head = result.refs[self.source.ref]
0.336.5 by Jelmer Vernooij
Fix some tests.
1291
            except KeyError:
1292
                stop_revision = revision.NULL_REVISION
1293
            else:
1294
                stop_revision = self.target.lookup_foreign_revision_id(head)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1295
        else:
7455.2.2 by Jelmer Vernooij
Fix git tests.
1296
            result = interrepo.fetch(
7143.15.2 by Jelmer Vernooij
Run autopep8.
1297
                revision_id=stop_revision, include_tags=fetch_tags)
7455.2.2 by Jelmer Vernooij
Fix git tests.
1298
        return result.refs, stop_revision
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
1299
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1300
    def pull(self, stop_revision=None, overwrite=False,
7489.4.6 by Jelmer Vernooij
Fix test.
1301
             possible_transports=None, run_hooks=True, local=False,
1302
             tag_selector=None):
0.200.446 by Jelmer Vernooij
Support new 'local' argument.
1303
        # This type of branch can't be bound.
1304
        if local:
1305
            raise errors.LocalRequiresBoundBranch()
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1306
        if overwrite is True:
1307
            overwrite = set(["history", "tags"])
7142.3.2 by Jelmer Vernooij
Fix overwrite for git branches.
1308
        elif not overwrite:
0.343.1 by Jelmer Vernooij
Support overwrite flag properly, remove DictTagDict.
1309
            overwrite = set()
1310
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1311
        result = GitPullResult()
1312
        result.source_branch = self.source
1313
        result.target_branch = self.target
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1314
        with self.target.lock_write(), self.source.lock_read():
1315
            result.old_revid = self.target.last_revision()
1316
            refs, stop_revision = self.update_refs(stop_revision)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1317
            self.target.generate_revision_history(
1318
                stop_revision,
1319
                (result.old_revid if ("history" not in overwrite) else None),
1320
                other_branch=self.source)
1321
            tags_ret = self.source.tags.merge_to(
7489.4.6 by Jelmer Vernooij
Fix test.
1322
                self.target.tags, overwrite=("tags" in overwrite),
1323
                selector=tag_selector)
0.200.1670 by Jelmer Vernooij
Fix compatibility with newer versions of bzr.
1324
            if isinstance(tags_ret, tuple):
1325
                (result.tag_updates, result.tag_conflicts) = tags_ret
1326
            else:
1327
                result.tag_conflicts = tags_ret
1328
            result.new_revid = self.target.last_revision()
1329
            result.local_branch = None
1330
            result.master_branch = result.target_branch
1331
            if run_hooks:
1332
                for hook in branch.Branch.hooks['post_pull']:
1333
                    hook(result)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1334
        return result
1335
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1336
0.200.960 by Jelmer Vernooij
Use GenericInterBranch.
1337
class InterToGitBranch(branch.GenericInterBranch):
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1338
    """InterBranch implementation that pulls into a Git branch."""
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1339
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
1340
    def __init__(self, source, target):
1341
        super(InterToGitBranch, self).__init__(source, target)
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
1342
        self.interrepo = _mod_repository.InterRepository.get(source.repository,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1343
                                                             target.repository)
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
1344
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
1345
    @staticmethod
1346
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
1347
        try:
1348
            default_format = branch.format_registry.get_default()
1349
        except AttributeError:
1350
            default_format = branch.BranchFormat._default_format
0.295.4 by Jelmer Vernooij
Fix imports.
1351
        from .remote import RemoteGitBranchFormat
0.295.1 by Jelmer Vernooij
Split up branch formats.
1352
        return [
1353
            (default_format, LocalGitBranchFormat()),
1354
            (default_format, RemoteGitBranchFormat())]
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
1355
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1356
    @classmethod
1357
    def is_compatible(self, source, target):
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
1358
        return (not isinstance(source, GitBranch) and
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1359
                isinstance(target, GitBranch))
1360
7131.14.1 by Jelmer Vernooij
Fix committing to a bzr branch bound to a git branch.
1361
    def _get_new_refs(self, stop_revision=None, fetch_tags=None,
7489.4.4 by Jelmer Vernooij
Add more tests.
1362
                      stop_revno=None):
0.361.1 by Jelmer Vernooij
Don't use assert.
1363
        if not self.source.is_locked():
1364
            raise errors.ObjectNotLocked(self.source)
0.252.38 by Jelmer Vernooij
Minor cleanups.
1365
        if stop_revision is None:
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
1366
            (stop_revno, stop_revision) = self.source.last_revision_info()
7131.14.1 by Jelmer Vernooij
Fix committing to a bzr branch bound to a git branch.
1367
        elif stop_revno is None:
7296.4.1 by Jelmer Vernooij
Fix pushing non-mainline revisions from bzr to git.
1368
            try:
1369
                stop_revno = self.source.revision_id_to_revno(stop_revision)
1370
            except errors.NoSuchRevision:
1371
                stop_revno = None
6973.13.2 by Jelmer Vernooij
Fix some more tests.
1372
        if not isinstance(stop_revision, bytes):
0.361.1 by Jelmer Vernooij
Don't use assert.
1373
            raise TypeError(stop_revision)
0.377.1 by Jelmer Vernooij
Fix some remote operations and add more tests.
1374
        main_ref = self.target.ref
7143.15.2 by Jelmer Vernooij
Run autopep8.
1375
        refs = {main_ref: (None, stop_revision)}
0.200.1363 by Jelmer Vernooij
Only fetch tags if requested in config.
1376
        if fetch_tags is None:
0.200.1584 by Jelmer Vernooij
Use config stacks in a few more places.
1377
            c = self.source.get_config_stack()
1378
            fetch_tags = c.get('branch.fetch_tags')
7018.3.2 by Jelmer Vernooij
Fix some git tests.
1379
        for name, revid in viewitems(self.source.tags.get_tag_dict()):
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1380
            if self.source.repository.has_revision(revid):
1381
                ref = tag_name_to_ref(name)
1382
                if not check_ref_format(ref):
1383
                    warning("skipping tag with invalid characters %s (%s)",
7143.15.2 by Jelmer Vernooij
Run autopep8.
1384
                            name, ref)
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1385
                    continue
0.200.1398 by Jelmer Vernooij
Make GitSmartRemoteNotSupported derive from UnsupportedOperation.
1386
                if fetch_tags:
1387
                    # FIXME: Skip tags that are not in the ancestry
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1388
                    refs[ref] = (None, revid)
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
1389
        return refs, main_ref, (stop_revno, stop_revision)
0.252.37 by Jelmer Vernooij
Factor out some common code for finding refs to send.
1390
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1391
    def _update_refs(self, result, old_refs, new_refs, overwrite, tag_selector):
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1392
        mutter("updating refs. old refs: %r, new refs: %r",
1393
               old_refs, new_refs)
1394
        result.tag_updates = {}
1395
        result.tag_conflicts = []
7490.93.1 by Jelmer Vernooij
Only update refs that have actually changed.
1396
        ret = {}
7143.15.2 by Jelmer Vernooij
Run autopep8.
1397
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1398
        def ref_equals(refs, ref, git_sha, revid):
1399
            try:
1400
                value = refs[ref]
1401
            except KeyError:
1402
                return False
1403
            if (value[0] is not None and
1404
                git_sha is not None and
7143.15.2 by Jelmer Vernooij
Run autopep8.
1405
                    value[0] == git_sha):
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1406
                return True
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1407
            if (value[1] is not None and
1408
                revid is not None and
7143.15.2 by Jelmer Vernooij
Run autopep8.
1409
                    value[1] == revid):
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1410
                return True
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1411
            # FIXME: If one side only has the git sha available and the other
1412
            # only has the bzr revid, then this will cause us to show a tag as
1413
            # updated that hasn't actually been updated.
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1414
            return False
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1415
        # FIXME: Check for diverged branches
7018.3.8 by Jelmer Vernooij
Disable some flaky tests on python3, allow running without fastimport.
1416
        for ref, (git_sha, revid) in viewitems(new_refs):
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1417
            if ref_equals(ret, ref, git_sha, revid):
1418
                # Already up to date
1419
                if git_sha is None:
1420
                    git_sha = old_refs[ref][0]
1421
                if revid is None:
1422
                    revid = old_refs[ref][1]
1423
                ret[ref] = new_refs[ref] = (git_sha, revid)
1424
            elif ref not in ret or overwrite:
1425
                try:
1426
                    tag_name = ref_to_tag_name(ref)
1427
                except ValueError:
1428
                    pass
1429
                else:
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1430
                    if tag_selector and not tag_selector(tag_name):
1431
                        continue
0.200.1479 by Jelmer Vernooij
Simplify branch ref handling.
1432
                    result.tag_updates[tag_name] = revid
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1433
                ret[ref] = (git_sha, revid)
1434
            else:
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1435
                # FIXME: Check diverged
1436
                diverged = False
1437
                if diverged:
1438
                    try:
1439
                        name = ref_to_tag_name(ref)
1440
                    except ValueError:
1441
                        pass
1442
                    else:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1443
                        result.tag_conflicts.append(
1444
                            (name, revid, ret[name][1]))
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1445
                else:
0.200.1474 by Jelmer Vernooij
Cope with refs when pushing.
1446
                    ret[ref] = (git_sha, revid)
0.200.1392 by Jelmer Vernooij
Preserve existing refs.
1447
        return ret
1448
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1449
    def fetch(self, stop_revision=None, fetch_tags=None, lossy=False,
1450
              limit=None):
0.200.1493 by Jelmer Vernooij
Test fixes.
1451
        if stop_revision is None:
7455.2.3 by Jelmer Vernooij
Fix remaining tests.
1452
            stop_revision = self.source.last_revision()
0.200.1493 by Jelmer Vernooij
Test fixes.
1453
        ret = []
1454
        if fetch_tags:
7018.3.2 by Jelmer Vernooij
Fix some git tests.
1455
            for k, v in viewitems(self.source.tags.get_tag_dict()):
0.200.1493 by Jelmer Vernooij
Test fixes.
1456
                ret.append((None, v))
1457
        ret.append((None, stop_revision))
0.320.5 by Jelmer Vernooij
Always raise NoRoundtrippingSupport rather than NoPushSupport.
1458
        try:
7455.2.1 by Jelmer Vernooij
Return a FetchResult object from Repository.fetch / Branch.fetch.
1459
            revidmap = self.interrepo.fetch_objects(ret, lossy=lossy, limit=limit)
0.320.5 by Jelmer Vernooij
Always raise NoRoundtrippingSupport rather than NoPushSupport.
1460
        except NoPushSupport:
1461
            raise errors.NoRoundtrippingSupport(self.source, self.target)
7455.2.1 by Jelmer Vernooij
Return a FetchResult object from Repository.fetch / Branch.fetch.
1462
        return _mod_repository.FetchResult(revidmap={
1463
            old_revid: new_revid
1464
            for (old_revid, (new_sha, new_revid)) in revidmap.items()})
0.200.1493 by Jelmer Vernooij
Test fixes.
1465
0.252.36 by Jelmer Vernooij
Fix pull.
1466
    def pull(self, overwrite=False, stop_revision=None, local=False,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1467
             possible_transports=None, run_hooks=True, _stop_revno=None,
1468
             tag_selector=None):
0.252.36 by Jelmer Vernooij
Fix pull.
1469
        result = GitBranchPullResult()
1470
        result.source_branch = self.source
1471
        result.target_branch = self.target
0.200.1788 by Jelmer Vernooij
Use context managers.
1472
        with self.source.lock_read(), self.target.lock_write():
1473
            new_refs, main_ref, stop_revinfo = self._get_new_refs(
7131.14.1 by Jelmer Vernooij
Fix committing to a bzr branch bound to a git branch.
1474
                stop_revision, stop_revno=_stop_revno)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1475
0.200.1788 by Jelmer Vernooij
Use context managers.
1476
            def update_refs(old_refs):
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1477
                return self._update_refs(result, old_refs, new_refs, overwrite, tag_selector)
0.200.1353 by Jelmer Vernooij
Run various hooks.
1478
            try:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1479
                result.revidmap, old_refs, new_refs = (
7489.4.4 by Jelmer Vernooij
Add more tests.
1480
                    self.interrepo.fetch_refs(update_refs, lossy=False))
0.200.1788 by Jelmer Vernooij
Use context managers.
1481
            except NoPushSupport:
1482
                raise errors.NoRoundtrippingSupport(self.source, self.target)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1483
            (old_sha1, result.old_revid) = old_refs.get(
1484
                main_ref, (ZERO_SHA, NULL_REVISION))
0.200.1788 by Jelmer Vernooij
Use context managers.
1485
            if result.old_revid is None:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1486
                result.old_revid = self.target.lookup_foreign_revision_id(
1487
                    old_sha1)
0.200.1788 by Jelmer Vernooij
Use context managers.
1488
            result.new_revid = new_refs[main_ref][1]
1489
            result.local_branch = None
1490
            result.master_branch = self.target
1491
            if run_hooks:
1492
                for hook in branch.Branch.hooks['post_pull']:
1493
                    hook(result)
0.252.36 by Jelmer Vernooij
Fix pull.
1494
        return result
1495
0.200.1260 by Jelmer Vernooij
Cope with new lossy argument.
1496
    def push(self, overwrite=False, stop_revision=None, lossy=False,
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1497
             _override_hook_source_branch=None, _stop_revno=None,
1498
             tag_selector=None):
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
1499
        result = GitBranchPushResult()
1500
        result.source_branch = self.source
1501
        result.target_branch = self.target
0.200.1356 by Jelmer Vernooij
Fix result properties for hook.
1502
        result.local_branch = None
1503
        result.master_branch = result.target_branch
0.331.1 by Jelmer Vernooij
Fix some tags tests.
1504
        with self.source.lock_read(), self.target.lock_write():
7143.15.2 by Jelmer Vernooij
Run autopep8.
1505
            new_refs, main_ref, stop_revinfo = self._get_new_refs(
7489.4.4 by Jelmer Vernooij
Add more tests.
1506
                stop_revision, stop_revno=_stop_revno)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1507
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1508
            def update_refs(old_refs):
7489.4.2 by Jelmer Vernooij
Plumb through tag_selector.
1509
                return self._update_refs(result, old_refs, new_refs, overwrite, tag_selector)
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1510
            try:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1511
                result.revidmap, old_refs, new_refs = (
1512
                    self.interrepo.fetch_refs(
1513
                        update_refs, lossy=lossy, overwrite=overwrite))
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1514
            except NoPushSupport:
1515
                raise errors.NoRoundtrippingSupport(self.source, self.target)
7143.15.2 by Jelmer Vernooij
Run autopep8.
1516
            (old_sha1, result.old_revid) = old_refs.get(
1517
                main_ref, (ZERO_SHA, NULL_REVISION))
7446.1.2 by Jelmer Vernooij
Fix working tree update of incremental lossy push.
1518
            if lossy or result.old_revid is None:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1519
                result.old_revid = self.target.lookup_foreign_revision_id(
1520
                    old_sha1)
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1521
            result.new_revid = new_refs[main_ref][1]
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
1522
            (result.new_original_revno,
1523
                result.new_original_revid) = stop_revinfo
0.200.1391 by Jelmer Vernooij
Warn on (and skip) invalid tags.
1524
            for hook in branch.Branch.hooks['post_push']:
1525
                hook(result)
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
1526
        return result
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
1527
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
1528
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1529
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
1530
branch.InterBranch.register_optimiser(InterFromGitBranch)
1531
branch.InterBranch.register_optimiser(InterToGitBranch)
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
1532
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)