/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

Support reading .git files.

Merged from https://code.launchpad.net/~jelmer/brz-git/read-gitfile/+merge/342256

Show diffs side-by-side

added added

removed removed

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