/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to push.py

TranslateĀ moreĀ strings.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2009-2010 Jelmer Vernooij <jelmer@samba.org>
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
"""Push implementation that simply prints message saying push is not supported."""
 
18
 
 
19
from dulwich.objects import ZERO_SHA
 
20
from dulwich.walk import Walker
 
21
 
 
22
from bzrlib import (
 
23
    errors,
 
24
    ui,
 
25
    )
 
26
from bzrlib.repository import (
 
27
    InterRepository,
 
28
    )
 
29
from bzrlib.revision import (
 
30
    NULL_REVISION,
 
31
    )
 
32
 
 
33
from bzrlib.plugins.git.errors import (
 
34
    NoPushSupport,
 
35
    )
 
36
from bzrlib.plugins.git.object_store import (
 
37
    get_object_store,
 
38
    )
 
39
from bzrlib.plugins.git.repository import (
 
40
    GitRepository,
 
41
    LocalGitRepository,
 
42
    GitRepositoryFormat,
 
43
    )
 
44
from bzrlib.plugins.git.remote import (
 
45
    RemoteGitRepository,
 
46
    )
 
47
from bzrlib.plugins.git.unpeel_map import (
 
48
    UnpeelMap,
 
49
    )
 
50
 
 
51
 
 
52
class MissingObjectsIterator(object):
 
53
    """Iterate over git objects that are missing from a target repository.
 
54
 
 
55
    """
 
56
 
 
57
    def __init__(self, store, source, pb=None):
 
58
        """Create a new missing objects iterator.
 
59
 
 
60
        """
 
61
        self.source = source
 
62
        self._object_store = store
 
63
        self._pending = []
 
64
        self.pb = pb
 
65
 
 
66
    def import_revisions(self, revids, roundtrip):
 
67
        """Import a set of revisions into this git repository.
 
68
 
 
69
        :param revids: Revision ids of revisions to import
 
70
        :param roundtrip: Whether to roundtrip bzr metadata
 
71
        """
 
72
        for i, revid in enumerate(revids):
 
73
            if self.pb:
 
74
                self.pb.update("pushing revisions", i, len(revids))
 
75
            git_commit = self.import_revision(revid, roundtrip)
 
76
            yield (revid, git_commit)
 
77
 
 
78
    def import_revision(self, revid, roundtrip):
 
79
        """Import a revision into this Git repository.
 
80
 
 
81
        :param revid: Revision id of the revision
 
82
        :param roundtrip: Whether to roundtrip bzr metadata
 
83
        """
 
84
        tree = self._object_store.tree_cache.revision_tree(revid)
 
85
        rev = self.source.get_revision(revid)
 
86
        commit = None
 
87
        for path, obj, ie in self._object_store._revision_to_objects(rev, tree,
 
88
            roundtrip):
 
89
            if obj.type_name == "commit":
 
90
                commit = obj
 
91
            self._pending.append((obj, path))
 
92
        if commit is None:
 
93
            raise AssertionError("no commit object generated for revision %s" %
 
94
                revid)
 
95
        return commit.id
 
96
 
 
97
    def __len__(self):
 
98
        return len(self._pending)
 
99
 
 
100
    def __iter__(self):
 
101
        return iter(self._pending)
 
102
 
 
103
 
 
104
class InterToGitRepository(InterRepository):
 
105
    """InterRepository that copies into a Git repository."""
 
106
 
 
107
    _matching_repo_format = GitRepositoryFormat()
 
108
 
 
109
    def __init__(self, source, target):
 
110
        super(InterToGitRepository, self).__init__(source, target)
 
111
        self.mapping = self.target.get_mapping()
 
112
        self.source_store = get_object_store(self.source, self.mapping)
 
113
 
 
114
    @staticmethod
 
115
    def _get_repo_format_to_test():
 
116
        return None
 
117
 
 
118
    def copy_content(self, revision_id=None, pb=None):
 
119
        """See InterRepository.copy_content."""
 
120
        self.fetch(revision_id, pb, find_ghosts=False)
 
121
 
 
122
    def fetch_refs(self, update_refs, lossy):
 
123
        """Fetch possibly roundtripped revisions into the target repository
 
124
        and update refs.
 
125
 
 
126
        :param update_refs: Generate refs to fetch. Receives dictionary
 
127
            with old refs (git shas), returns dictionary of new names to
 
128
            git shas.
 
129
        :param lossy: Whether to roundtrip
 
130
        :return: old refs, new refs
 
131
        """
 
132
        raise NotImplementedError(self.fetch_refs)
 
133
 
 
134
    def search_missing_revision_ids(self,
 
135
            find_ghosts=True, revision_ids=None, if_present_ids=None,
 
136
            limit=None):
 
137
        git_shas = []
 
138
        todo = []
 
139
        if revision_ids:
 
140
            todo.extend(revision_ids)
 
141
        if if_present_ids:
 
142
            todo.extend(revision_ids)
 
143
        self.source_store.lock_read()
 
144
        try:
 
145
            for revid in revision_ids:
 
146
                if revid == NULL_REVISION:
 
147
                    continue
 
148
                git_sha = self.source_store._lookup_revision_sha1(revid)
 
149
                git_shas.append(git_sha)
 
150
            walker = Walker(self.source_store,
 
151
                include=git_shas, exclude=[sha for sha in self.target.bzrdir.get_refs().values() if sha != ZERO_SHA])
 
152
            missing_revids = set()
 
153
            for entry in walker:
 
154
                for (kind, type_data) in self.source_store.lookup_git_sha(entry.commit.id):
 
155
                    if kind == "commit":
 
156
                        missing_revids.add(type_data[0])
 
157
        finally:
 
158
            self.source_store.unlock()
 
159
        return self.source.revision_ids_to_search_result(missing_revids)
 
160
 
 
161
 
 
162
class InterToLocalGitRepository(InterToGitRepository):
 
163
    """InterBranch implementation between a Bazaar and a Git repository."""
 
164
 
 
165
    def __init__(self, source, target):
 
166
        super(InterToLocalGitRepository, self).__init__(source, target)
 
167
        self.target_store = self.target.bzrdir._git.object_store
 
168
        self.target_refs = self.target.bzrdir._git.refs
 
169
 
 
170
    def _commit_needs_fetching(self, sha_id):
 
171
        try:
 
172
            return (sha_id not in self.target_store)
 
173
        except errors.NoSuchRevision:
 
174
            # Ghost, can't push
 
175
            return False
 
176
 
 
177
    def _revision_needs_fetching(self, sha_id, revid):
 
178
        if revid == NULL_REVISION:
 
179
            return False
 
180
        if sha_id is None:
 
181
            try:
 
182
                sha_id = self.source_store._lookup_revision_sha1(revid)
 
183
            except KeyError:
 
184
                return False
 
185
        return self._commit_needs_fetching(sha_id)
 
186
 
 
187
    def missing_revisions(self, stop_revisions):
 
188
        """Find the revisions that are missing from the target repository.
 
189
 
 
190
        :param stop_revisions: Revisions to check for (tuples with
 
191
            Git SHA1, bzr revid)
 
192
        :return: sequence of missing revisions, in topological order
 
193
        :raise: NoSuchRevision if the stop_revisions are not present in
 
194
            the source
 
195
        """
 
196
        revid_sha_map = {}
 
197
        stop_revids = []
 
198
        for (sha1, revid) in stop_revisions:
 
199
            if sha1 is not None and revid is not None:
 
200
                revid_sha_map[revid] = sha1
 
201
                stop_revids.append(revid)
 
202
            elif sha1 is not None:
 
203
                if self._commit_needs_fetching(sha1):
 
204
                    for (kind, (revid, tree_sha, verifiers)) in self.source_store.lookup_git_sha(sha1):
 
205
                        revid_sha_map[revid] = sha1
 
206
                        stop_revids.append(revid)
 
207
            else:
 
208
                assert revid is not None
 
209
                stop_revids.append(revid)
 
210
        missing = set()
 
211
        graph = self.source.get_graph()
 
212
        pb = ui.ui_factory.nested_progress_bar()
 
213
        try:
 
214
            while stop_revids:
 
215
                new_stop_revids = []
 
216
                for revid in stop_revids:
 
217
                    sha1 = revid_sha_map.get(revid)
 
218
                    if (not revid in missing and
 
219
                        self._revision_needs_fetching(sha1, revid)):
 
220
                        missing.add(revid)
 
221
                        new_stop_revids.append(revid)
 
222
                stop_revids = set()
 
223
                parent_map = graph.get_parent_map(new_stop_revids)
 
224
                for parent_revids in parent_map.itervalues():
 
225
                    stop_revids.update(parent_revids)
 
226
                pb.update("determining revisions to fetch", len(missing))
 
227
        finally:
 
228
            pb.finished()
 
229
        return graph.iter_topo_order(missing)
 
230
 
 
231
    def _get_target_bzr_refs(self):
 
232
        """Return a dictionary with references.
 
233
 
 
234
        :return: Dictionary with reference names as keys and tuples
 
235
            with Git SHA, Bazaar revid as values.
 
236
        """
 
237
        bzr_refs = {}
 
238
        refs = {}
 
239
        for k in self.target._git.refs.allkeys():
 
240
            v = self.target._git.refs.read_ref(k)
 
241
            try:
 
242
                for (kind, type_data) in self.source_store.lookup_git_sha(v):
 
243
                    if kind == "commit" and self.source.has_revision(type_data[0]):
 
244
                        revid = type_data[0]
 
245
                        break
 
246
                else:
 
247
                    revid = None
 
248
            except KeyError:
 
249
                revid = None
 
250
            bzr_refs[k] = (v, revid)
 
251
        return bzr_refs
 
252
 
 
253
    def fetch_refs(self, update_refs, lossy):
 
254
        self.source_store.lock_read()
 
255
        try:
 
256
            old_refs = self._get_target_bzr_refs()
 
257
            new_refs = update_refs(old_refs)
 
258
            revidmap = self.fetch_objects(
 
259
                [(git_sha, bzr_revid) for (git_sha, bzr_revid) in new_refs.values() if git_sha is None or not git_sha.startswith('ref:')], roundtrip=not lossy)
 
260
            for name, (gitid, revid) in new_refs.iteritems():
 
261
                if gitid is None:
 
262
                    try:
 
263
                        gitid = revidmap[revid][0]
 
264
                    except KeyError:
 
265
                        gitid = self.source_store._lookup_revision_sha1(revid)
 
266
                assert len(gitid) == 40 or gitid.startswith('ref: ')
 
267
                self.target_refs[name] = gitid
 
268
        finally:
 
269
            self.source_store.unlock()
 
270
        return revidmap, old_refs, new_refs
 
271
 
 
272
    def fetch_objects(self, revs, roundtrip):
 
273
        todo = list(self.missing_revisions(revs))
 
274
        revidmap = {}
 
275
        pb = ui.ui_factory.nested_progress_bar()
 
276
        try:
 
277
            object_generator = MissingObjectsIterator(
 
278
                self.source_store, self.source, pb)
 
279
            for (old_revid, git_sha) in object_generator.import_revisions(
 
280
                todo, roundtrip=roundtrip):
 
281
                try:
 
282
                    self.mapping.revision_id_bzr_to_foreign(old_revid)
 
283
                except errors.InvalidRevisionId:
 
284
                    self.target_refs[self.mapping.revid_as_refname(old_revid)] = git_sha
 
285
                if not roundtrip:
 
286
                    new_revid = self.mapping.revision_id_foreign_to_bzr(git_sha)
 
287
                else:
 
288
                    new_revid = old_revid
 
289
                revidmap[old_revid] = (git_sha, new_revid)
 
290
            self.target_store.add_objects(object_generator)
 
291
            return revidmap
 
292
        finally:
 
293
            pb.finished()
 
294
 
 
295
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
296
            fetch_spec=None, mapped_refs=None):
 
297
        if not self.mapping.roundtripping:
 
298
            raise NoPushSupport()
 
299
        self.source_store.lock_read()
 
300
        try:
 
301
            if mapped_refs is not None:
 
302
                stop_revisions = mapped_refs
 
303
            elif revision_id is not None:
 
304
                stop_revisions = [(None, revision_id)]
 
305
            elif fetch_spec is not None:
 
306
                recipe = fetch_spec.get_recipe()
 
307
                if recipe[0] in ("search", "proxy-search"):
 
308
                    stop_revisions = [(None, revid) for revid in recipe[1]]
 
309
                else:
 
310
                    raise AssertionError("Unsupported search result type %s" % recipe[0])
 
311
            else:
 
312
                stop_revisions = [(None, revid) for revid in self.source.all_revision_ids()]
 
313
            self.fetch_objects(stop_revisions, roundtrip=True)
 
314
        finally:
 
315
            self.source_store.unlock()
 
316
 
 
317
    @staticmethod
 
318
    def is_compatible(source, target):
 
319
        """Be compatible with GitRepository."""
 
320
        return (not isinstance(source, GitRepository) and
 
321
                isinstance(target, LocalGitRepository))
 
322
 
 
323
 
 
324
class InterToRemoteGitRepository(InterToGitRepository):
 
325
 
 
326
    def fetch_refs(self, update_refs, lossy):
 
327
        """Import the gist of the ancestry of a particular revision."""
 
328
        if not lossy:
 
329
            raise NoPushSupport()
 
330
        unpeel_map = UnpeelMap.from_repository(self.source)
 
331
        revidmap = {}
 
332
        def determine_wants(old_refs):
 
333
            ret = {}
 
334
            self.old_refs = dict([(k, (v, None)) for (k, v) in old_refs.iteritems()])
 
335
            self.new_refs = update_refs(self.old_refs)
 
336
            for name, (gitid, revid) in self.new_refs.iteritems():
 
337
                if gitid is None:
 
338
                    git_sha = self.source_store._lookup_revision_sha1(revid)
 
339
                    ret[name] = unpeel_map.re_unpeel_tag(git_sha, old_refs.get(name))
 
340
                else:
 
341
                    ret[name] = gitid
 
342
            return ret
 
343
        self.source_store.lock_read()
 
344
        try:
 
345
            new_refs = self.target.send_pack(determine_wants,
 
346
                    self.source_store.generate_lossy_pack_contents)
 
347
        finally:
 
348
            self.source_store.unlock()
 
349
        # FIXME: revidmap?
 
350
        return revidmap, self.old_refs, self.new_refs
 
351
 
 
352
    @staticmethod
 
353
    def is_compatible(source, target):
 
354
        """Be compatible with GitRepository."""
 
355
        return (not isinstance(source, GitRepository) and
 
356
                isinstance(target, RemoteGitRepository))