/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
1
# Copyright (C) 2007 Canonical Ltd
0.200.910 by Jelmer Vernooij
update copyright years
2
# Copyright (C) 2009-2010 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.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
20
from collections import defaultdict
21
0.200.261 by Jelmer Vernooij
More formatting fixes.
22
from dulwich.objects import (
23
    Commit,
24
    Tag,
0.200.1153 by Jelmer Vernooij
Import ZERO_SHA from dulwich.objects.
25
    ZERO_SHA,
0.200.261 by Jelmer Vernooij
More formatting fixes.
26
    )
27
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
28
from bzrlib import (
29
    branch,
0.200.513 by Jelmer Vernooij
Fix imports.
30
    bzrdir,
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
31
    config,
0.200.446 by Jelmer Vernooij
Support new 'local' argument.
32
    errors,
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
33
    repository as _mod_repository,
0.200.19 by John Arbash Meinel
More refactoring. Add some direct tests for GitModel.
34
    revision,
0.200.82 by Jelmer Vernooij
Support listing tags.
35
    tag,
0.230.1 by Jelmer Vernooij
Support lightweight checkouts.
36
    transport,
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
37
    )
0.200.261 by Jelmer Vernooij
More formatting fixes.
38
from bzrlib.decorators import (
39
    needs_read_lock,
40
    )
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
41
from bzrlib.revision import (
42
    NULL_REVISION,
43
    )
0.200.261 by Jelmer Vernooij
More formatting fixes.
44
from bzrlib.trace import (
0.200.342 by Jelmer Vernooij
Report git sha during pull.
45
    is_quiet,
0.200.261 by Jelmer Vernooij
More formatting fixes.
46
    mutter,
47
    )
48
0.200.386 by Jelmer Vernooij
Move config to a separate file, support BranchConfig.username().
49
from bzrlib.plugins.git.config import (
50
    GitBranchConfig,
51
    )
0.200.278 by Jelmer Vernooij
Update branch head appropriately during dpull.
52
from bzrlib.plugins.git.errors import (
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
53
    NoPushSupport,
0.200.278 by Jelmer Vernooij
Update branch head appropriately during dpull.
54
    NoSuchRef,
55
    )
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
56
from bzrlib.plugins.git.refs import (
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
57
    branch_name_to_ref,
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
58
    extract_tags,
59
    is_tag,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
60
    ref_to_branch_name,
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
61
    ref_to_tag_name,
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
62
    tag_name_to_ref,
0.200.1292 by Jelmer Vernooij
Fix repeeling objects when determining what to send.
63
    )
64
from bzrlib.plugins.git.unpeel_map import (
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
65
    UnpeelMap,
0.200.872 by Jelmer Vernooij
Move refs code to separate module.
66
    )
0.200.261 by Jelmer Vernooij
More formatting fixes.
67
0.238.5 by Jelmer Vernooij
Remove old backwards compatibility code.
68
from bzrlib.foreign import ForeignBranch
0.200.388 by Jelmer Vernooij
Support bzr 1.14 as well.
69
0.200.261 by Jelmer Vernooij
More formatting fixes.
70
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
71
class GitPullResult(branch.PullResult):
0.200.956 by Jelmer Vernooij
Add some more format tests.
72
    """Result of a pull from a Git branch."""
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
73
74
    def _lookup_revno(self, revid):
75
        assert isinstance(revid, str), "was %r" % revid
76
        # Try in source branch first, it'll be faster
77
        return self.target_branch.revision_id_to_revno(revid)
78
79
    @property
80
    def old_revno(self):
81
        return self._lookup_revno(self.old_revid)
82
83
    @property
84
    def new_revno(self):
85
        return self._lookup_revno(self.new_revid)
86
87
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
88
class GitTags(tag.BasicTags):
89
    """Ref-based tag dictionary."""
0.200.82 by Jelmer Vernooij
Support listing tags.
90
0.200.89 by Jelmer Vernooij
Support sprouting branches.
91
    def __init__(self, branch):
92
        self.branch = branch
93
        self.repository = branch.repository
0.200.82 by Jelmer Vernooij
Support listing tags.
94
0.200.1066 by Jelmer Vernooij
Add GitTags.get_refs.
95
    def get_refs(self):
96
        raise NotImplementedError(self.get_refs)
97
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
98
    def _iter_tag_refs(self, refs):
99
        raise NotImplementedError(self._iter_tag_refs)
100
101
    def _merge_to_git(self, to_tags, refs, overwrite=False):
102
        target_repo = to_tags.repository
103
        conflicts = []
104
        for k, v in refs.iteritems():
105
            if not is_tag(k):
106
                continue
0.200.1128 by Jelmer Vernooij
remove duplicate definition of _matchingbzrdir.
107
            if overwrite or not k in target_repo._git.refs:
108
                target_repo._git.refs[k] = v
109
            elif target_repo._git.refs[k] == v:
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
110
                pass
111
            else:
112
                conflicts.append((ref_to_tag_name(k), v, target_repo.refs[k]))
113
        return conflicts
114
115
    def _merge_to_non_git(self, to_tags, refs, overwrite=False):
116
        unpeeled_map = defaultdict(set)
117
        conflicts = []
118
        result = dict(to_tags.get_tag_dict())
119
        for n, peeled, unpeeled, bzr_revid in self._iter_tag_refs(refs):
120
            if unpeeled is not None:
121
                unpeeled_map[peeled].add(unpeeled)
122
            if n not in result or overwrite:
123
                result[n] = bzr_revid
124
            elif result[n] == bzr_revid:
125
                pass
126
            else:
127
                conflicts.append((n, result[n], bzr_revid))
128
        to_tags._set_tag_dict(result)
129
        if len(unpeeled_map) > 0:
130
            map_file = UnpeelMap.from_repository(to_tags.branch.repository)
131
            map_file.update(unpeeled_map)
132
            map_file.save_in_repository(to_tags.branch.repository)
133
        return conflicts
134
135
    def merge_to(self, to_tags, overwrite=False, ignore_master=False,
136
                 source_refs=None):
0.200.1113 by Jelmer Vernooij
Fix Tags.merge_to.
137
        """See Tags.merge_to."""
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
138
        if source_refs is None:
0.200.1066 by Jelmer Vernooij
Add GitTags.get_refs.
139
            source_refs = self.get_refs()
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
140
        if self == to_tags:
141
            return
142
        if isinstance(to_tags, GitTags):
143
            return self._merge_to_git(to_tags, source_refs,
144
                                      overwrite=overwrite)
145
        else:
146
            if ignore_master:
147
                master = None
148
            else:
149
                master = to_tags.branch.get_master_branch()
150
            conflicts = self._merge_to_non_git(to_tags, source_refs,
151
                                              overwrite=overwrite)
152
            if master is not None:
0.200.1113 by Jelmer Vernooij
Fix Tags.merge_to.
153
                conflicts += self.merge_to(master.tags, overwrite=overwrite,
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
154
                                           source_refs=source_refs,
155
                                           ignore_master=ignore_master)
156
            return conflicts
157
158
    def get_tag_dict(self):
159
        ret = {}
0.200.1066 by Jelmer Vernooij
Add GitTags.get_refs.
160
        refs = self.get_refs()
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
161
        for (name, peeled, unpeeled, bzr_revid) in self._iter_tag_refs(refs):
162
            ret[name] = bzr_revid
163
        return ret
164
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
165
166
class LocalGitTagDict(GitTags):
167
    """Dictionary with tags in a local repository."""
168
169
    def __init__(self, branch):
170
        super(LocalGitTagDict, self).__init__(branch)
171
        self.refs = self.repository._git.refs
172
0.200.1066 by Jelmer Vernooij
Add GitTags.get_refs.
173
    def get_refs(self):
174
        return self.repository._git.get_refs()
175
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
176
    def _iter_tag_refs(self, refs):
177
        """Iterate over the tag refs.
178
179
        :param refs: Refs dictionary (name -> git sha1)
180
        :return: iterator over (name, peeled_sha1, unpeeled_sha1, bzr_revid)
181
        """
0.200.1060 by Jelmer Vernooij
Return unpeeled tags in extract_tags.
182
        for k, (peeled, unpeeled) in extract_tags(refs).iteritems():
0.200.609 by Jelmer Vernooij
Cope with tags pointing at nonexisting objects.
183
            try:
0.200.1060 by Jelmer Vernooij
Return unpeeled tags in extract_tags.
184
                obj = self.repository._git[peeled]
0.200.609 by Jelmer Vernooij
Cope with tags pointing at nonexisting objects.
185
            except KeyError:
0.200.1060 by Jelmer Vernooij
Return unpeeled tags in extract_tags.
186
                mutter("Tag %s points at unknown object %s, ignoring", peeled,
187
                       obj)
0.200.609 by Jelmer Vernooij
Cope with tags pointing at nonexisting objects.
188
                continue
0.200.1060 by Jelmer Vernooij
Return unpeeled tags in extract_tags.
189
            # FIXME: this shouldn't really be necessary, the repository
190
            # already should have these unpeeled.
0.200.194 by Jelmer Vernooij
Look for commit object in heavyweight tags.
191
            while isinstance(obj, Tag):
0.200.1060 by Jelmer Vernooij
Return unpeeled tags in extract_tags.
192
                peeled = obj.object[1]
193
                obj = self.repository._git[peeled]
0.200.194 by Jelmer Vernooij
Look for commit object in heavyweight tags.
194
            if not isinstance(obj, Commit):
0.200.261 by Jelmer Vernooij
More formatting fixes.
195
                mutter("Tag %s points at object %r that is not a commit, "
196
                       "ignoring", k, obj)
0.200.194 by Jelmer Vernooij
Look for commit object in heavyweight tags.
197
                continue
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
198
            yield (k, peeled, unpeeled,
199
                   self.branch.lookup_foreign_revision_id(peeled))
200
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
201
    def _set_tag_dict(self, to_dict):
0.200.1066 by Jelmer Vernooij
Add GitTags.get_refs.
202
        extra = set(self.get_refs().keys())
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
203
        for k, revid in to_dict.iteritems():
0.200.875 by Jelmer Vernooij
Use new tag_name_to_ref function.
204
            name = tag_name_to_ref(k)
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
205
            if name in extra:
206
                extra.remove(name)
207
            self.set_tag(k, revid)
208
        for name in extra:
0.200.1061 by Jelmer Vernooij
Add support for using unpeel map.
209
            if is_tag(name):
0.200.711 by Jelmer Vernooij
Support merging tags to a local Git repository.
210
                del self.repository._git[name]
0.200.956 by Jelmer Vernooij
Add some more format tests.
211
0.200.86 by Jelmer Vernooij
Clearer error when setting tags.
212
    def set_tag(self, name, revid):
0.200.1064 by Jelmer Vernooij
Use common base class for tags.
213
        self.refs[tag_name_to_ref(name)], _ = \
0.200.1030 by Jelmer Vernooij
More work on supporting roundtripping push.
214
            self.branch.lookup_bzr_revision_id(revid)
0.200.86 by Jelmer Vernooij
Clearer error when setting tags.
215
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
216
0.200.1078 by Jelmer Vernooij
Fix git-import from remote repositories.
217
class DictTagDict(tag.BasicTags):
0.239.1 by Jelmer Vernooij
Avoid re-connecting to fetch tags we already know.
218
219
    def __init__(self, branch, tags):
220
        super(DictTagDict, self).__init__(branch)
221
        self._tags = tags
222
223
    def get_tag_dict(self):
224
        return self._tags
225
226
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
227
class GitBranchFormat(branch.BranchFormat):
228
0.200.70 by Jelmer Vernooij
Implement GitBranchFormat.get_format_description.
229
    def get_format_description(self):
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
230
        return 'Git Branch'
231
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
232
    def network_name(self):
233
        return "git"
234
0.200.82 by Jelmer Vernooij
Support listing tags.
235
    def supports_tags(self):
236
        return True
237
0.200.1105 by Jelmer Vernooij
Don't claim to support leaving locks.
238
    def supports_leaving_lock(self):
239
        return False
240
0.200.1091 by Jelmer Vernooij
Provide _matchingbzrdir for testing.
241
    @property
242
    def _matchingbzrdir(self):
0.200.1140 by Jelmer Vernooij
Update now that the control dir formats are no longer in __init__.
243
        from bzrlib.plugins.git.dir import LocalGitControlDirFormat
0.200.1091 by Jelmer Vernooij
Provide _matchingbzrdir for testing.
244
        return LocalGitControlDirFormat()
245
0.243.1 by Jelmer Vernooij
Use foreign branch testing infrastructure.
246
    def get_foreign_tests_branch_factory(self):
247
        from bzrlib.plugins.git.tests.test_branch import ForeignTestsBranchFactory
248
        return ForeignTestsBranchFactory()
249
0.200.246 by Jelmer Vernooij
Cope with API changes in 1.13.
250
    def make_tags(self, branch):
0.228.3 by Jelmer Vernooij
Fix tags when fetching from remotes.
251
        if getattr(branch.repository, "get_refs", None) is not None:
252
            from bzrlib.plugins.git.remote import RemoteGitTagDict
253
            return RemoteGitTagDict(branch)
0.200.261 by Jelmer Vernooij
More formatting fixes.
254
        else:
255
            return LocalGitTagDict(branch)
0.200.246 by Jelmer Vernooij
Cope with API changes in 1.13.
256
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
257
    def initialize(self, a_bzrdir, name=None, repository=None):
258
        from bzrlib.plugins.git.dir import LocalGitDir
259
        if not isinstance(a_bzrdir, LocalGitDir):
260
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
261
        if repository is None:
262
            repository = a_bzrdir.open_repository()
0.200.1102 by Jelmer Vernooij
Fix creating of colocated branches in git repositories.
263
        ref = branch_name_to_ref(name, "HEAD")
264
        repository._git[ref] = ZERO_SHA
265
        return LocalGitBranch(a_bzrdir, repository, ref, a_bzrdir._lockfiles)
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
266
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
267
0.200.911 by Jelmer Vernooij
Cope with locking changes in bzr.dev.
268
class GitReadLock(object):
269
270
    def __init__(self, unlock):
271
        self.unlock = unlock
272
273
274
class GitWriteLock(object):
275
276
    def __init__(self, unlock):
0.200.1175 by Jelmer Vernooij
Provide GitWriteLock.branch_token.
277
        self.branch_token = None
0.200.911 by Jelmer Vernooij
Cope with locking changes in bzr.dev.
278
        self.unlock = unlock
279
280
0.200.388 by Jelmer Vernooij
Support bzr 1.14 as well.
281
class GitBranch(ForeignBranch):
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
282
    """An adapter to git repositories for bzr Branch objects."""
283
0.200.1129 by Jelmer Vernooij
Implement GitBranch.control_transport.
284
    @property
285
    def control_transport(self):
286
        return self.bzrdir.control_transport
287
0.200.770 by Jelmer Vernooij
Proper branch names.
288
    def __init__(self, bzrdir, repository, ref, lockfiles, tagsdict=None):
0.200.1287 by Jelmer Vernooij
Set Branch.base before invoking branch open hooks.
289
        self.base = bzrdir.root_transport.base
0.200.82 by Jelmer Vernooij
Support listing tags.
290
        self.repository = repository
0.200.246 by Jelmer Vernooij
Cope with API changes in 1.13.
291
        self._format = GitBranchFormat()
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
292
        self.control_files = lockfiles
0.200.59 by Jelmer Vernooij
Add more tests, fix revision history.
293
        self.bzrdir = bzrdir
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
294
        self._lock_mode = None
295
        self._lock_count = 0
0.231.1 by Jelmer Vernooij
Check that regenerated objects have the expected sha1.
296
        super(GitBranch, self).__init__(repository.get_mapping())
0.239.1 by Jelmer Vernooij
Avoid re-connecting to fetch tags we already know.
297
        if tagsdict is not None:
298
            self.tags = DictTagDict(self, tagsdict)
0.200.770 by Jelmer Vernooij
Proper branch names.
299
        self.ref = ref
300
        self.name = ref_to_branch_name(ref)
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
301
        self._head = None
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
302
0.239.8 by Jelmer Vernooij
Support checkouts.
303
    def _get_checkout_format(self):
304
        """Return the most suitable metadir for a checkout of this branch.
305
        Weaves are used if this branch's repository uses weaves.
306
        """
0.200.927 by Jelmer Vernooij
Remove explicit use of rich root formats.
307
        return bzrdir.format_registry.make_bzrdir("default")
0.239.8 by Jelmer Vernooij
Support checkouts.
308
0.238.3 by Jelmer Vernooij
Remove svn references, prefer git send format when submitting changes against a git branch.
309
    def get_child_submit_format(self):
310
        """Return the preferred format of submissions to this branch."""
311
        ret = self.get_config().get_user_option("child_submit_format")
312
        if ret is not None:
313
            return ret
314
        return "git"
315
0.200.293 by Jelmer Vernooij
Fix branch nicks.
316
    def _get_nick(self, local=False, possible_master_transports=None):
317
        """Find the nick name for this branch.
318
319
        :return: Branch nick
320
        """
0.200.920 by Jelmer Vernooij
Fix some more tests.
321
        return self.name or "HEAD"
0.200.293 by Jelmer Vernooij
Fix branch nicks.
322
0.200.331 by Jelmer Vernooij
Add stub for setting nick function.
323
    def _set_nick(self, nick):
324
        raise NotImplementedError
325
326
    nick = property(_get_nick, _set_nick)
0.200.293 by Jelmer Vernooij
Fix branch nicks.
327
0.200.412 by Jelmer Vernooij
Implement GitBranch.__repr__.
328
    def __repr__(self):
0.200.770 by Jelmer Vernooij
Proper branch names.
329
        return "<%s(%r, %r)>" % (self.__class__.__name__, self.repository.base,
0.200.920 by Jelmer Vernooij
Fix some more tests.
330
            self.ref or "HEAD")
0.200.412 by Jelmer Vernooij
Implement GitBranch.__repr__.
331
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
332
    def generate_revision_history(self, revid, old_revid=None):
0.200.1103 by Jelmer Vernooij
Support generate_revision_history(NULL_REVISION).
333
        if revid == NULL_REVISION:
334
            newhead = ZERO_SHA
335
        else:
336
            # FIXME: Check that old_revid is in the ancestry of revid
337
            newhead, self.mapping = self.mapping.revision_id_bzr_to_foreign(revid)
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
338
            if self.mapping is None:
339
                raise AssertionError
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
340
        self._set_head(newhead)
341
0.200.1199 by Jelmer Vernooij
Support 'token' argument to Branch.lock_write.
342
    def lock_write(self, token=None):
343
        if token is not None:
344
            raise errors.TokenLockingNotSupported(self)
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
345
        if self._lock_mode:
346
            assert self._lock_mode == 'w'
347
            self._lock_count += 1
348
        else:
349
            self._lock_mode = 'w'
350
            self._lock_count = 1
351
        self.repository.lock_write()
0.200.911 by Jelmer Vernooij
Cope with locking changes in bzr.dev.
352
        return GitWriteLock(self.unlock)
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
353
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
354
    def get_stacked_on_url(self):
355
        # Git doesn't do stacking (yet...)
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
356
        raise errors.UnstackableBranchFormat(self._format, self.base)
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
357
358
    def get_parent(self):
359
        """See Branch.get_parent()."""
0.200.312 by Jelmer Vernooij
Add notes about parent locations.
360
        # FIXME: Set "origin" url from .git/config ?
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
361
        return None
362
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
363
    def set_parent(self, url):
0.200.312 by Jelmer Vernooij
Add notes about parent locations.
364
        # FIXME: Set "origin" url in .git/config ?
0.200.175 by Jelmer Vernooij
Add optimized handling when fetching from git to git.
365
        pass
366
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
367
    def lock_read(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
368
        if self._lock_mode:
369
            assert self._lock_mode in ('r', 'w')
370
            self._lock_count += 1
371
        else:
372
            self._lock_mode = 'r'
373
            self._lock_count = 1
374
        self.repository.lock_read()
0.200.911 by Jelmer Vernooij
Cope with locking changes in bzr.dev.
375
        return GitReadLock(self.unlock)
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
376
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
377
    def peek_lock_mode(self):
378
        return self._lock_mode
379
0.200.432 by Jelmer Vernooij
Support Branch.is_locked, required for loggerhead.
380
    def is_locked(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
381
        return (self._lock_mode is not None)
0.200.432 by Jelmer Vernooij
Support Branch.is_locked, required for loggerhead.
382
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
383
    def unlock(self):
0.200.1250 by Jelmer Vernooij
Simplify lock handling.
384
        """See Branch.unlock()."""
385
        self._lock_count -= 1
386
        if self._lock_count == 0:
387
            self._lock_mode = None
388
            self._clear_cached_state()
389
        self.repository.unlock()
0.200.139 by Jelmer Vernooij
Share more code between local and remote classes, support opening remote branches.
390
391
    def get_physical_lock_status(self):
392
        return False
393
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
394
    @needs_read_lock
395
    def last_revision(self):
396
        # perhaps should escape this ?
0.200.57 by Jelmer Vernooij
Fix more tests.
397
        if self.head is None:
0.200.19 by John Arbash Meinel
More refactoring. Add some direct tests for GitModel.
398
            return revision.NULL_REVISION
0.252.44 by Jelmer Vernooij
Properly look up Bazaar revision ids for revision parents in case they are round-tripped.
399
        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.
400
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
401
    def _basic_push(self, target, overwrite=False, stop_revision=None):
402
        return branch.InterBranch.get(self, target)._basic_push(
403
            overwrite, stop_revision)
404
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
405
    def lookup_foreign_revision_id(self, foreign_revid):
0.200.956 by Jelmer Vernooij
Add some more format tests.
406
        return self.repository.lookup_foreign_revision_id(foreign_revid,
0.252.49 by Jelmer Vernooij
Avoid trying to set HEAD for remote branches.
407
            self.mapping)
408
0.200.1030 by Jelmer Vernooij
More work on supporting roundtripping push.
409
    def lookup_bzr_revision_id(self, revid):
410
        return self.repository.lookup_bzr_revision_id(
411
            revid, mapping=self.mapping)
412
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
413
0.200.465 by Jelmer Vernooij
Use dulwich standard functionality for finding missing revisions.
414
class LocalGitBranch(GitBranch):
415
    """A local Git branch."""
416
0.200.1102 by Jelmer Vernooij
Fix creating of colocated branches in git repositories.
417
    def __init__(self, bzrdir, repository, ref, lockfiles, tagsdict=None):
418
        super(LocalGitBranch, self).__init__(bzrdir, repository, ref,
0.200.763 by Jelmer Vernooij
Provide proper colocated branch support.
419
              lockfiles, tagsdict)
0.200.918 by Jelmer Vernooij
Cope with 'self.ref is None' in a couple more places.
420
        refs = repository._git.get_refs()
0.200.1102 by Jelmer Vernooij
Fix creating of colocated branches in git repositories.
421
        if not (ref in refs.keys() or "HEAD" in refs.keys()):
0.200.763 by Jelmer Vernooij
Provide proper colocated branch support.
422
            raise errors.NotBranchError(self.base)
423
0.200.261 by Jelmer Vernooij
More formatting fixes.
424
    def create_checkout(self, to_location, revision_id=None, lightweight=False,
425
        accelerator_tree=None, hardlink=False):
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
426
        if lightweight:
0.230.1 by Jelmer Vernooij
Support lightweight checkouts.
427
            t = transport.get_transport(to_location)
428
            t.ensure_base()
429
            format = self._get_checkout_format()
430
            checkout = format.initialize_on_transport(t)
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
431
            from_branch = branch.BranchReferenceFormat().initialize(checkout,
0.230.1 by Jelmer Vernooij
Support lightweight checkouts.
432
                self)
433
            tree = checkout.create_workingtree(revision_id,
434
                from_branch=from_branch, hardlink=hardlink)
435
            return tree
436
        else:
437
            return self._create_heavyweight_checkout(to_location, revision_id,
0.257.1 by Jelmer Vernooij
use transport repo objects even for local access.
438
                hardlink)
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
439
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
440
    def _create_heavyweight_checkout(self, to_location, revision_id=None,
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
441
                                     hardlink=False):
442
        """Create a new heavyweight checkout of this branch.
443
444
        :param to_location: URL of location to create the new checkout in.
445
        :param revision_id: Revision that should be the tip of the checkout.
446
        :param hardlink: Whether to hardlink
447
        :return: WorkingTree object of checkout.
448
        """
0.200.513 by Jelmer Vernooij
Fix imports.
449
        checkout_branch = bzrdir.BzrDir.create_branch_convenience(
0.200.927 by Jelmer Vernooij
Remove explicit use of rich root formats.
450
            to_location, force_new_tree=False)
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
451
        checkout = checkout_branch.bzrdir
452
        checkout_branch.bind(self)
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
453
        # pull up to the specified revision_id to set the initial
0.200.210 by Jelmer Vernooij
properly error out about not support lightweight checkouts.
454
        # branch tip correctly, and seed it with history.
455
        checkout_branch.pull(self, stop_revision=revision_id)
456
        return checkout.create_workingtree(revision_id, hardlink=hardlink)
457
0.200.57 by Jelmer Vernooij
Fix more tests.
458
    def _gen_revision_history(self):
0.200.58 by Jelmer Vernooij
Fix remaining tests.
459
        if self.head is None:
460
            return []
0.200.1279 by Jelmer Vernooij
Avoid using deprecated Repository.iter_reverse_revision_history.
461
        graph = self.repository.get_graph()
462
        ret = list(graph.iter_lefthand_ancestry(self.last_revision(),
463
            (revision.NULL_REVISION, )))
0.200.59 by Jelmer Vernooij
Add more tests, fix revision history.
464
        ret.reverse()
0.200.57 by Jelmer Vernooij
Fix more tests.
465
        return ret
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
466
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
467
    def _get_head(self):
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
468
        try:
0.200.918 by Jelmer Vernooij
Cope with 'self.ref is None' in a couple more places.
469
            return self.repository._git.ref(self.ref or "HEAD")
0.200.480 by Jelmer Vernooij
Cope with API changes in Dulwich.
470
        except KeyError:
471
            return None
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
472
0.200.1228 by Jelmer Vernooij
Provide Branch._read_last_revision_info.
473
    def _read_last_revision_info(self):
474
        last_revid = self.last_revision()
475
        graph = self.repository.get_graph()
476
        revno = graph.find_distance_to_null(last_revid,
477
            [(revision.NULL_REVISION, 0)])
478
        return revno, last_revid
479
480
    def set_last_revision_info(self, revno, revision_id):
481
        self.set_last_revision(revision_id)
482
        self._last_revision_info_cache = revno, revision_id
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
483
484
    def set_last_revision(self, revid):
0.200.1233 by Jelmer Vernooij
Implement Repository.iter_files_bytes.
485
        if not revid or not isinstance(revid, basestring):
486
            raise errors.InvalidRevisionId(revision_id=revid, branch=self)
0.200.1218 by Jelmer Vernooij
Support set_last_revision('null:').
487
        if revid == NULL_REVISION:
488
            newhead = ZERO_SHA
489
        else:
490
            (newhead, self.mapping) = self.repository.lookup_bzr_revision_id(revid)
491
            if self.mapping is None:
492
                raise AssertionError
493
        self._set_head(newhead)
0.200.507 by Jelmer Vernooij
Implement set_last_revision{_info,}.
494
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
495
    def _set_head(self, value):
496
        self._head = value
0.200.918 by Jelmer Vernooij
Cope with 'self.ref is None' in a couple more places.
497
        self.repository._git.refs[self.ref or "HEAD"] = self._head
0.200.461 by Jelmer Vernooij
Reduce number of round trips when fetching from Git.
498
        self._clear_cached_state()
499
500
    head = property(_get_head, _set_head)
501
0.200.18 by John Arbash Meinel
Start splitting up the Git{Branch,Dir,Repository} into separate modules, etc.
502
    def get_config(self):
503
        return GitBranchConfig(self)
504
505
    def get_push_location(self):
506
        """See Branch.get_push_location."""
507
        push_loc = self.get_config().get_user_option('push_location')
508
        return push_loc
509
510
    def set_push_location(self, location):
511
        """See Branch.set_push_location."""
0.200.19 by John Arbash Meinel
More refactoring. Add some direct tests for GitModel.
512
        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.
513
                                          store=config.STORE_LOCATION)
0.200.43 by David Allouche
Ultra-experimental support for "bzr pull". No test. No sanity.
514
515
    def supports_tags(self):
0.200.82 by Jelmer Vernooij
Support listing tags.
516
        return True
0.200.956 by Jelmer Vernooij
Add some more format tests.
517
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
518
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
519
def _quick_lookup_revno(local_branch, remote_branch, revid):
520
    assert isinstance(revid, str), "was %r" % revid
521
    # Try in source branch first, it'll be faster
522
    try:
523
        return local_branch.revision_id_to_revno(revid)
524
    except errors.NoSuchRevision:
525
        graph = local_branch.repository.get_graph()
526
        try:
527
            return graph.find_distance_to_null(revid)
528
        except errors.GhostRevisionsHaveNoRevno:
529
            # FIXME: Check using graph.find_distance_to_null() ?
530
            return remote_branch.revision_id_to_revno(revid)
531
532
0.200.342 by Jelmer Vernooij
Report git sha during pull.
533
class GitBranchPullResult(branch.PullResult):
534
0.252.36 by Jelmer Vernooij
Fix pull.
535
    def __init__(self):
536
        super(GitBranchPullResult, self).__init__()
537
        self.new_git_head = None
538
        self._old_revno = None
539
        self._new_revno = None
540
0.200.342 by Jelmer Vernooij
Report git sha during pull.
541
    def report(self, to_file):
542
        if not is_quiet():
543
            if self.old_revid == self.new_revid:
544
                to_file.write('No revisions to pull.\n')
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
545
            elif self.new_git_head is not None:
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
546
                to_file.write('Now on revision %d (git sha: %s).\n' %
0.200.342 by Jelmer Vernooij
Report git sha during pull.
547
                        (self.new_revno, self.new_git_head))
0.200.728 by Jelmer Vernooij
Fix pulling when all revisions are already in the repo.
548
            else:
549
                to_file.write('Now on revision %d.\n' % (self.new_revno,))
0.200.342 by Jelmer Vernooij
Report git sha during pull.
550
        self._show_tag_conficts(to_file)
551
0.252.36 by Jelmer Vernooij
Fix pull.
552
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
553
        return _quick_lookup_revno(self.target_branch, self.source_branch,
554
                revid)
0.252.36 by Jelmer Vernooij
Fix pull.
555
556
    def _get_old_revno(self):
557
        if self._old_revno is not None:
558
            return self._old_revno
559
        return self._lookup_revno(self.old_revid)
560
561
    def _set_old_revno(self, revno):
562
        self._old_revno = revno
563
564
    old_revno = property(_get_old_revno, _set_old_revno)
565
566
    def _get_new_revno(self):
567
        if self._new_revno is not None:
568
            return self._new_revno
569
        return self._lookup_revno(self.new_revid)
570
571
    def _set_new_revno(self, revno):
572
        self._new_revno = revno
0.200.956 by Jelmer Vernooij
Add some more format tests.
573
0.252.36 by Jelmer Vernooij
Fix pull.
574
    new_revno = property(_get_new_revno, _set_new_revno)
575
0.200.342 by Jelmer Vernooij
Report git sha during pull.
576
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
577
class GitBranchPushResult(branch.BranchPushResult):
578
579
    def _lookup_revno(self, revid):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
580
        return _quick_lookup_revno(self.source_branch, self.target_branch,
581
            revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
582
583
    @property
584
    def old_revno(self):
585
        return self._lookup_revno(self.old_revid)
586
587
    @property
588
    def new_revno(self):
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
589
        new_original_revno = getattr(self, "new_original_revno", None)
590
        if new_original_revno:
591
            return new_original_revno
592
        if getattr(self, "new_original_revid", None) is not None:
593
            return self._lookup_revno(self.new_original_revid)
0.200.504 by Jelmer Vernooij
Lazily find revno's for git branches.
594
        return self._lookup_revno(self.new_revid)
595
596
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
597
class InterFromGitBranch(branch.GenericInterBranch):
0.200.261 by Jelmer Vernooij
More formatting fixes.
598
    """InterBranch implementation that pulls from Git into bzr."""
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
599
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
600
    @staticmethod
601
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
602
        try:
603
            default_format = branch.format_registry.get_default()
604
        except AttributeError:
605
            default_format = branch.BranchFormat._default_format
606
        return [
607
            (GitBranchFormat(), GitBranchFormat()),
608
            (GitBranchFormat(), default_format)]
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
609
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
610
    @classmethod
0.200.692 by Jelmer Vernooij
Refuse pulling into non-rich-root branches rather than erroring out with an AttributeError.
611
    def _get_interrepo(self, source, target):
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
612
        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.
613
614
    @classmethod
615
    def is_compatible(cls, source, target):
0.200.1222 by Jelmer Vernooij
Better checks in is_compatible methods.
616
        if not isinstance(source, GitBranch):
617
            return False
618
        if isinstance(target, GitBranch):
619
            # InterLocalGitRemoteGitBranch or InterToGitBranch should be used
620
            return False
621
        if getattr(cls._get_interrepo(source, target), "fetch_objects", None) is None:
622
            # fetch_objects is necessary for this to work
623
            return False
624
        return True
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
625
0.200.1305 by Jelmer Vernooij
Only actually fetch tags if "branch.fetch_tags" is set to true.
626
    def fetch(self, stop_revision=None, fetch_tags=None, limit=None):
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
627
        self.fetch_objects(stop_revision, fetch_tags=fetch_tags, limit=limit)
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
628
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
629
    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.
630
        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.
631
        if fetch_tags is None:
632
            c = self.source.get_config()
0.200.1306 by Jelmer Vernooij
Fix bzr 2.3 compatibility.
633
            fetch_tags = c.get_user_option_as_bool('branch.fetch_tags')
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
634
        def determine_wants(heads):
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
635
            if self.source.ref is not None and not self.source.ref in heads:
0.200.777 by Jelmer Vernooij
Fix colocated remote branches.
636
                raise NoSuchRef(self.source.ref, heads.keys())
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
637
638
            if stop_revision is None:
0.200.917 by Jelmer Vernooij
Cope with implicit branches during pull.
639
                if self.source.ref is not None:
640
                    head = heads[self.source.ref]
641
                else:
642
                    head = heads["HEAD"]
0.252.44 by Jelmer Vernooij
Properly look up Bazaar revision ids for revision parents in case they are round-tripped.
643
                self._last_revid = self.source.lookup_foreign_revision_id(head)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
644
            else:
645
                self._last_revid = stop_revision
646
            real = interrepo.get_determine_wants_revids(
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
647
                [self._last_revid], include_tags=fetch_tags)
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
648
            return real(heads)
0.200.1002 by Jelmer Vernooij
Fix regression in git-import.
649
        pack_hint, head, refs = interrepo.fetch_objects(
0.200.1265 by Jelmer Vernooij
Support limit option to Branch.fetch.
650
            determine_wants, self.source.mapping, limit=limit)
0.252.45 by Jelmer Vernooij
Finish fetching roundtripped revisions back into bzr.
651
        if (pack_hint is not None and
652
            self.target.repository._format.pack_compresses):
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
653
            self.target.repository.pack(hint=pack_hint)
0.260.1 by Jelmer Vernooij
Fix fetch from remote during merge.
654
        return head, refs
655
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
656
    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.
657
        head, refs = self.fetch_objects(stop_revision, fetch_tags=None)
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
658
        if overwrite:
0.200.314 by Jelmer Vernooij
Support stop_revision.
659
            prev_last_revid = None
0.200.313 by Jelmer Vernooij
Support overwrite parameter.
660
        else:
0.200.314 by Jelmer Vernooij
Support stop_revision.
661
            prev_last_revid = self.target.last_revision()
0.248.5 by Jelmer Vernooij
Reformatting, fix dpush.
662
        self.target.generate_revision_history(self._last_revid,
0.259.6 by Jelmer Vernooij
Fetch tags during pull.
663
            prev_last_revid, self.source)
0.200.1062 by Jelmer Vernooij
Pass remote refs along in _update_revisions.
664
        return head, refs
0.200.225 by Jelmer Vernooij
Implement custom InterBranch to support fetching from remote git branches.
665
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
666
    def pull(self, overwrite=False, stop_revision=None,
667
             possible_transports=None, _hook_master=None, run_hooks=True,
0.200.1150 by Jelmer Vernooij
merge compatibility fixes for bzr 2.4, support for fetching tags.
668
             _override_hook_target=None, local=False):
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
669
        """See Branch.pull.
670
671
        :param _hook_master: Private parameter - set the branch to
672
            be supplied as the master to pull hooks.
673
        :param run_hooks: Private parameter - if false, this branch
674
            is being called because it's the master of the primary branch,
675
            so it should not run its hooks.
676
        :param _override_hook_target: Private parameter - set the branch to be
677
            supplied as the target_branch to pull hooks.
678
        """
0.200.446 by Jelmer Vernooij
Support new 'local' argument.
679
        # This type of branch can't be bound.
680
        if local:
681
            raise errors.LocalRequiresBoundBranch()
0.200.342 by Jelmer Vernooij
Report git sha during pull.
682
        result = GitBranchPullResult()
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
683
        result.source_branch = self.source
684
        if _override_hook_target is None:
685
            result.target_branch = self.target
686
        else:
687
            result.target_branch = _override_hook_target
688
        self.source.lock_read()
689
        try:
690
            # We assume that during 'pull' the target repository is closer than
691
            # the source one.
0.200.726 by Jelmer Vernooij
Factor out conversion of branch names to refs.
692
            (result.old_revno, result.old_revid) = \
693
                self.target.last_revision_info()
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
694
            result.new_git_head, remote_refs = self._update_revisions(
695
                stop_revision, overwrite=overwrite)
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
696
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
697
                overwrite)
0.200.726 by Jelmer Vernooij
Factor out conversion of branch names to refs.
698
            (result.new_revno, result.new_revid) = \
699
                self.target.last_revision_info()
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
700
            if _hook_master:
701
                result.master_branch = _hook_master
702
                result.local_branch = result.target_branch
703
            else:
704
                result.master_branch = result.target_branch
705
                result.local_branch = None
706
            if run_hooks:
707
                for hook in branch.Branch.hooks['post_pull']:
708
                    hook(result)
709
        finally:
710
            self.source.unlock()
711
        return result
712
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
713
    def _basic_push(self, overwrite=False, stop_revision=None):
714
        result = branch.BranchPushResult()
715
        result.source_branch = self.source
716
        result.target_branch = self.target
717
        result.old_revno, result.old_revid = self.target.last_revision_info()
0.200.1219 by Jelmer Vernooij
Remove InterBranch.update_revisions.
718
        result.new_git_head, remote_refs = self._update_revisions(
719
            stop_revision, overwrite=overwrite)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
720
        result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
721
            overwrite)
722
        result.new_revno, result.new_revid = self.target.last_revision_info()
723
        return result
724
0.200.338 by Jelmer Vernooij
Fix dpushing without changes necessary.
725
0.200.512 by Jelmer Vernooij
Support pushing git->git.
726
class InterGitBranch(branch.GenericInterBranch):
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
727
    """InterBranch implementation that pulls between Git branches."""
728
0.200.512 by Jelmer Vernooij
Support pushing git->git.
729
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
730
class InterLocalGitRemoteGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
731
    """InterBranch that copies from a local to a remote git branch."""
732
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
733
    @staticmethod
734
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
735
        # FIXME
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
736
        return []
737
0.200.512 by Jelmer Vernooij
Support pushing git->git.
738
    @classmethod
739
    def is_compatible(self, source, target):
740
        from bzrlib.plugins.git.remote import RemoteGitBranch
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
741
        return (isinstance(source, LocalGitBranch) and
0.200.512 by Jelmer Vernooij
Support pushing git->git.
742
                isinstance(target, RemoteGitBranch))
743
744
    def _basic_push(self, overwrite=False, stop_revision=None):
745
        result = GitBranchPushResult()
746
        result.source_branch = self.source
747
        result.target_branch = self.target
748
        if stop_revision is None:
749
            stop_revision = self.source.last_revision()
750
        # FIXME: Check for diverged branches
751
        def get_changed_refs(old_refs):
0.200.1300 by Jelmer Vernooij
Fix formatting.
752
            old_ref = old_refs.get(self.target.ref, ZERO_SHA)
753
            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.
754
            refs = { self.target.ref: self.source.repository.lookup_bzr_revision_id(stop_revision)[0] }
0.200.512 by Jelmer Vernooij
Support pushing git->git.
755
            result.new_revid = stop_revision
756
            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.
757
                refs[tag_name_to_ref(name)] = sha
0.200.512 by Jelmer Vernooij
Support pushing git->git.
758
            return refs
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
759
        self.target.repository.send_pack(get_changed_refs,
0.200.726 by Jelmer Vernooij
Factor out conversion of branch names to refs.
760
            self.source.repository._git.object_store.generate_pack_contents)
0.200.512 by Jelmer Vernooij
Support pushing git->git.
761
        return result
762
763
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
764
class InterGitLocalGitBranch(InterGitBranch):
0.200.512 by Jelmer Vernooij
Support pushing git->git.
765
    """InterBranch that copies from a remote to a local git branch."""
766
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
767
    @staticmethod
768
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
769
        # FIXME
0.200.996 by Jelmer Vernooij
Fix test run of InterBranches.
770
        return []
771
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
772
    @classmethod
773
    def is_compatible(self, source, target):
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
774
        return (isinstance(source, GitBranch) and
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
775
                isinstance(target, LocalGitBranch))
776
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
777
    def _basic_push(self, overwrite=False, stop_revision=None):
778
        result = branch.BranchPushResult()
779
        result.source_branch = self.source
780
        result.target_branch = self.target
781
        result.old_revid = self.target.last_revision()
782
        refs, stop_revision = self.update_refs(stop_revision)
783
        self.target.generate_revision_history(stop_revision, result.old_revid)
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
784
        result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
785
            source_refs=refs, overwrite=overwrite)
0.200.505 by Jelmer Vernooij
Remove duplicate code.
786
        result.new_revid = self.target.last_revision()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
787
        return result
788
789
    def update_refs(self, stop_revision=None):
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
790
        interrepo = _mod_repository.InterRepository.get(self.source.repository,
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
791
            self.target.repository)
792
        if stop_revision is None:
0.200.940 by Jelmer Vernooij
Avoid confusion between different fetch functions with different semantics.
793
            refs = interrepo.fetch(branches=["HEAD"])
0.252.44 by Jelmer Vernooij
Properly look up Bazaar revision ids for revision parents in case they are round-tripped.
794
            stop_revision = self.target.lookup_foreign_revision_id(refs["HEAD"])
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
795
        else:
0.200.940 by Jelmer Vernooij
Avoid confusion between different fetch functions with different semantics.
796
            refs = interrepo.fetch(revision_id=stop_revision)
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
797
        return refs, stop_revision
798
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
799
    def pull(self, stop_revision=None, overwrite=False,
0.200.732 by Jelmer Vernooij
Support run_hooks argument to InterGitRemoteLocalBranch.pull().
800
        possible_transports=None, run_hooks=True,local=False):
0.200.446 by Jelmer Vernooij
Support new 'local' argument.
801
        # This type of branch can't be bound.
802
        if local:
803
            raise errors.LocalRequiresBoundBranch()
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
804
        result = GitPullResult()
805
        result.source_branch = self.source
806
        result.target_branch = self.target
807
        result.old_revid = self.target.last_revision()
0.200.501 by Jelmer Vernooij
Support push from git into bzr.
808
        refs, stop_revision = self.update_refs(stop_revision)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
809
        self.target.generate_revision_history(stop_revision, result.old_revid)
0.200.1065 by Jelmer Vernooij
Don't peel tags automatically when pushing back.
810
        result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
811
            overwrite=overwrite, source_refs=refs)
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
812
        result.new_revid = self.target.last_revision()
813
        return result
814
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
815
0.200.960 by Jelmer Vernooij
Use GenericInterBranch.
816
class InterToGitBranch(branch.GenericInterBranch):
0.200.1185 by Jelmer Vernooij
Some formatting fixes.
817
    """InterBranch implementation that pulls into a Git branch."""
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
818
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
819
    def __init__(self, source, target):
820
        super(InterToGitBranch, self).__init__(source, target)
0.200.1097 by Jelmer Vernooij
Implement GitBranchFormat.initialize.
821
        self.interrepo = _mod_repository.InterRepository.get(source.repository,
0.200.939 by Jelmer Vernooij
Use InterRepo directly.
822
                                           target.repository)
823
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
824
    @staticmethod
825
    def _get_branch_formats_to_test():
0.200.1100 by Jelmer Vernooij
Provide test combinations for InterBranch implementations.
826
        try:
827
            default_format = branch.format_registry.get_default()
828
        except AttributeError:
829
            default_format = branch.BranchFormat._default_format
830
        return [(default_format, GitBranchFormat())]
0.200.631 by Jelmer Vernooij
Raise proper exception in Branch.get_stacked_on_url().
831
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
832
    @classmethod
833
    def is_compatible(self, source, target):
0.200.695 by Jelmer Vernooij
Clean up trailing whitespace.
834
        return (not isinstance(source, GitBranch) and
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
835
                isinstance(target, GitBranch))
836
0.252.38 by Jelmer Vernooij
Minor cleanups.
837
    def _get_new_refs(self, stop_revision=None):
838
        if stop_revision is None:
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
839
            (stop_revno, stop_revision) = self.source.last_revision_info()
0.263.1 by Jelmer Vernooij
Fix dpush for certain branches.
840
        else:
841
            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.
842
        assert type(stop_revision) is str
0.200.916 by Jelmer Vernooij
Set refs/heads/master if no ref is set yet.
843
        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.
844
        refs = { main_ref: (None, stop_revision) }
0.252.37 by Jelmer Vernooij
Factor out some common code for finding refs to send.
845
        for name, revid in self.source.tags.get_tag_dict().iteritems():
846
            if self.source.repository.has_revision(revid):
0.200.969 by Jelmer Vernooij
Use tuples with bzr revid and git sha to avoid lookups.
847
                refs[tag_name_to_ref(name)] = (None, revid)
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
848
        return refs, main_ref, (stop_revno, stop_revision)
0.252.37 by Jelmer Vernooij
Factor out some common code for finding refs to send.
849
0.252.36 by Jelmer Vernooij
Fix pull.
850
    def pull(self, overwrite=False, stop_revision=None, local=False,
0.200.1131 by Jelmer Vernooij
Accept run_hooks argument to InterToGitBranch.pull().
851
             possible_transports=None, run_hooks=True):
0.252.36 by Jelmer Vernooij
Fix pull.
852
        result = GitBranchPullResult()
853
        result.source_branch = self.source
854
        result.target_branch = self.target
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
855
        new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
0.200.941 by Jelmer Vernooij
Pass update_refs argument to fetch_refs.
856
        def update_refs(old_refs):
857
            refs = dict(old_refs)
0.200.945 by Jelmer Vernooij
Move fixmes
858
            # FIXME: Check for diverged branches
0.200.941 by Jelmer Vernooij
Pass update_refs argument to fetch_refs.
859
            refs.update(new_refs)
860
            return refs
0.200.1156 by Jelmer Vernooij
Disable push.
861
        try:
862
            old_refs, new_refs = self.interrepo.fetch_refs(update_refs)
863
        except NoPushSupport:
0.200.1161 by Jelmer Vernooij
Fix exception type.
864
            raise errors.NoRoundtrippingSupport(self.source, self.target)
0.200.1042 by Jelmer Vernooij
Fix pull into git branches.
865
        (result.old_revid, old_sha1) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
866
        if result.old_revid is None:
867
            result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
868
        result.new_revid = new_refs[main_ref][1]
0.252.36 by Jelmer Vernooij
Fix pull.
869
        return result
870
0.200.1260 by Jelmer Vernooij
Cope with new lossy argument.
871
    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.
872
             _override_hook_source_branch=None):
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
873
        result = GitBranchPushResult()
874
        result.source_branch = self.source
875
        result.target_branch = self.target
0.200.1048 by Jelmer Vernooij
Make lookup of revno's after push/pull as efficient as possible.
876
        new_refs, main_ref, stop_revinfo = self._get_new_refs(stop_revision)
0.200.941 by Jelmer Vernooij
Pass update_refs argument to fetch_refs.
877
        def update_refs(old_refs):
878
            refs = dict(old_refs)
0.200.945 by Jelmer Vernooij
Move fixmes
879
            # FIXME: Check for diverged branches
0.200.941 by Jelmer Vernooij
Pass update_refs argument to fetch_refs.
880
            refs.update(new_refs)
881
            return refs
0.200.1260 by Jelmer Vernooij
Cope with new lossy argument.
882
        if lossy:
883
            result.revidmap, old_refs, new_refs = self.interrepo.dfetch_refs(
884
                update_refs)
885
        else:
886
            try:
887
                old_refs, new_refs = self.interrepo.fetch_refs(update_refs)
888
            except NoPushSupport:
889
                raise errors.NoRoundtrippingSupport(self.source, self.target)
0.200.1035 by Jelmer Vernooij
Cope with tuples in refs dictionary.
890
        (result.old_revid, old_sha1) = old_refs.get(main_ref, (ZERO_SHA, NULL_REVISION))
891
        if result.old_revid is None:
892
            result.old_revid = self.target.lookup_foreign_revision_id(old_sha1)
0.200.1042 by Jelmer Vernooij
Fix pull into git branches.
893
        result.new_revid = new_refs[main_ref][1]
0.200.1260 by Jelmer Vernooij
Cope with new lossy argument.
894
        (result.new_original_revno, result.new_original_revid) = stop_revinfo
0.252.5 by Jelmer Vernooij
enable 'bzr push'.
895
        return result
0.200.472 by Jelmer Vernooij
Fix printing error when user attempts to push into git.
896
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
897
    def lossy_push(self, stop_revision=None):
0.200.1261 by Jelmer Vernooij
add note about compatibility
898
        # For compatibility with bzr < 2.4
0.200.1260 by Jelmer Vernooij
Cope with new lossy argument.
899
        return self.push(lossy=True, stop_revision=stop_revision)
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
900
0.200.334 by Jelmer Vernooij
Support pulling from git to git.
901
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
902
branch.InterBranch.register_optimiser(InterGitLocalGitBranch)
0.200.468 by Jelmer Vernooij
Move dpush logic onto InterBranch.
903
branch.InterBranch.register_optimiser(InterFromGitBranch)
904
branch.InterBranch.register_optimiser(InterToGitBranch)
0.200.1176 by Jelmer Vernooij
Fix fetch return value for inter git fetching.
905
branch.InterBranch.register_optimiser(InterLocalGitRemoteGitBranch)