/brz/remove-bazaar

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