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