/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

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2006-04-13 23:16:57 UTC
  • mfrom: (1662.1.1 bzr.mbp.integration)
  • Revision ID: pqm@pqm.ubuntu.com-20060413231657-bce3d67d3e7a4f2b
(mbp/olaf) push/pull/merge --remember improvements

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