/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 repository.py

Print proper error about not supporting push.

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
"""An adapter between a Git Repository and a Bazaar Branch"""
19
19
 
 
20
import bzrlib
20
21
from bzrlib import (
21
22
    errors,
 
23
    graph,
22
24
    inventory,
 
25
    osutils,
23
26
    repository,
24
27
    revision,
25
28
    revisiontree,
 
29
    ui,
 
30
    urlutils,
26
31
    )
27
32
from bzrlib.foreign import (
28
 
    ForeignRepository,
29
 
    )
 
33
        ForeignRepository,
 
34
        )
 
35
from bzrlib.trace import mutter
 
36
from bzrlib.transport import get_transport
30
37
 
31
 
from bzrlib.plugins.git.commit import (
32
 
    GitCommitBuilder,
 
38
from bzrlib.plugins.git.foreign import (
 
39
    versionedfiles,
33
40
    )
34
41
from bzrlib.plugins.git.mapping import (
35
42
    default_mapping,
36
 
    foreign_git,
 
43
    inventory_to_tree_and_blobs,
37
44
    mapping_registry,
38
 
    )
39
 
from bzrlib.plugins.git.tree import (
40
 
    GitRevisionTree,
41
 
    )
42
 
from bzrlib.plugins.git.versionedfiles import (
43
 
    GitRevisions,
44
 
    GitTexts,
45
 
    )
46
 
 
47
 
 
48
 
from dulwich.objects import (
49
 
    Commit,
50
 
    )
 
45
    revision_to_commit,
 
46
    )
 
47
from bzrlib.plugins.git.versionedfiles import GitTexts
 
48
 
 
49
import dulwich as git
 
50
import os
 
51
import time
 
52
 
 
53
 
 
54
class GitTags(object):
 
55
 
 
56
    def __init__(self, tags):
 
57
        self._tags = tags
 
58
 
 
59
    def __iter__(self):
 
60
        return iter(self._tags)
51
61
 
52
62
 
53
63
class GitRepository(ForeignRepository):
54
64
    """An adapter to git repositories for bzr."""
55
65
 
56
66
    _serializer = None
57
 
    _commit_builder_class = GitCommitBuilder
58
 
    vcs = foreign_git
59
67
 
60
68
    def __init__(self, gitdir, lockfiles):
61
 
        ForeignRepository.__init__(self, GitRepositoryFormat(), gitdir,
 
69
        ForeignRepository.__init__(self, GitRepositoryFormat(), gitdir, 
62
70
            lockfiles)
63
71
        from bzrlib.plugins.git import fetch, push
64
 
        for optimiser in [fetch.InterRemoteGitNonGitRepository,
65
 
                          fetch.InterLocalGitNonGitRepository,
66
 
                          fetch.InterGitGitRepository,
67
 
                          push.InterToLocalGitRepository,
68
 
                          push.InterToRemoteGitRepository]:
 
72
        for optimiser in [fetch.InterGitRepository, 
 
73
                          fetch.InterGitNonGitRepository,
 
74
                          push.InterToGitRepository]:
69
75
            repository.InterRepository.register_optimiser(optimiser)
70
76
 
71
77
    def is_shared(self):
72
 
        return False
 
78
        return True
73
79
 
74
80
    def supports_rich_root(self):
75
81
        return True
76
82
 
77
 
    def _warn_if_deprecated(self, branch=None):
 
83
    def _warn_if_deprecated(self):
78
84
        # This class isn't deprecated
79
85
        pass
80
86
 
82
88
        return default_mapping
83
89
 
84
90
    def make_working_trees(self):
85
 
        return not self._git.bare
86
 
 
87
 
    def revision_graph_can_have_wrong_parents(self):
88
 
        return False
89
 
 
90
 
    def dfetch(self, source, stop_revision):
91
 
        interrepo = repository.InterRepository.get(source, self)
92
 
        return interrepo.dfetch(stop_revision)
 
91
        return True
93
92
 
94
93
 
95
94
class LocalGitRepository(GitRepository):
96
95
    """Git repository on the file system."""
97
96
 
98
97
    def __init__(self, gitdir, lockfiles):
 
98
        # FIXME: This also caches negatives. Need to be more careful 
 
99
        # about this once we start writing to git
 
100
        self._parents_provider = graph.CachingParentsProvider(self)
99
101
        GitRepository.__init__(self, gitdir, lockfiles)
100
102
        self.base = gitdir.root_transport.base
101
103
        self._git = gitdir._git
102
 
        self.signatures = None
103
 
        self.revisions = GitRevisions(self, self._git.object_store)
104
 
        self.inventories = None
 
104
        self.texts = None
 
105
        self.signatures = versionedfiles.VirtualSignatureTexts(self)
 
106
        self.revisions = versionedfiles.VirtualRevisionTexts(self)
 
107
        self.inventories = versionedfiles.VirtualInventoryTexts(self)
105
108
        self.texts = GitTexts(self)
106
 
 
107
 
    def _iter_revision_ids(self):
108
 
        mapping = self.get_mapping()
109
 
        for sha in self._git.object_store:
110
 
            o = self._git.object_store[sha]
111
 
            if not isinstance(o, Commit):
112
 
                continue
113
 
            rev, roundtrip_revid, verifiers = mapping.import_commit(o,
114
 
                self.lookup_foreign_revision_id)
115
 
            yield o.id, rev.revision_id, roundtrip_revid
 
109
        self.tags = GitTags(self._git.get_tags())
116
110
 
117
111
    def all_revision_ids(self):
118
 
        ret = set([])
119
 
        for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
120
 
            ret.add(revid)
121
 
            if roundtrip_revid:
122
 
                ret.add(roundtrip_revid)
 
112
        ret = set([revision.NULL_REVISION])
 
113
        heads = self._git.heads()
 
114
        if heads == {}:
 
115
            return ret
 
116
        bzr_heads = [self.get_mapping().revision_id_foreign_to_bzr(h) for h in heads.itervalues()]
 
117
        ret = set(bzr_heads)
 
118
        graph = self.get_graph()
 
119
        for rev, parents in graph.iter_ancestry(bzr_heads):
 
120
            ret.add(rev)
123
121
        return ret
124
122
 
 
123
    #def get_revision_delta(self, revision_id):
 
124
    #    parent_revid = self.get_revision(revision_id).parent_ids[0]
 
125
    #    diff = self._git.diff(ids.convert_revision_id_bzr_to_git(parent_revid),
 
126
    #                   ids.convert_revision_id_bzr_to_git(revision_id))
 
127
 
 
128
    def _make_parents_provider(self):
 
129
        """See Repository._make_parents_provider()."""
 
130
        return self._parents_provider
 
131
 
125
132
    def get_parent_map(self, revids):
126
133
        parent_map = {}
 
134
        mutter("get_parent_map(%r)", revids)
127
135
        for revision_id in revids:
128
136
            assert isinstance(revision_id, str)
129
137
            if revision_id == revision.NULL_REVISION:
130
138
                parent_map[revision_id] = ()
131
139
                continue
132
 
            hexsha, mapping = self.lookup_bzr_revision_id(revision_id)
133
 
            try:
134
 
                commit = self._git[hexsha]
135
 
            except KeyError:
 
140
            hexsha, mapping = self.lookup_git_revid(revision_id)
 
141
            commit  = self._git.commit(hexsha)
 
142
            if commit is None:
136
143
                continue
137
 
            parent_map[revision_id] = [
138
 
                self.lookup_foreign_revision_id(p, mapping)
139
 
                for p in commit.parents]
 
144
            else:
 
145
                parent_map[revision_id] = [mapping.revision_id_foreign_to_bzr(p) for p in commit.parents]
140
146
        return parent_map
141
147
 
142
148
    def get_ancestry(self, revision_id, topo_sorted=True):
152
158
        ancestry.reverse()
153
159
        return [None] + ancestry
154
160
 
 
161
    def import_revision_gist(self, source, revid, parent_lookup):
 
162
        """Import the gist of a revision into this Git repository.
 
163
 
 
164
        """
 
165
        objects = []
 
166
        rev = source.get_revision(revid)
 
167
        for sha, object, path in inventory_to_tree_and_blobs(source, None, revid):
 
168
            if path == "":
 
169
                tree_sha = sha
 
170
            objects.append((object, path))
 
171
        commit = revision_to_commit(rev, tree_sha, parent_lookup)
 
172
        objects.append((commit, None))
 
173
        self._git.object_store.add_objects(objects)
 
174
        return commit.sha().hexdigest()
 
175
 
 
176
    def dfetch(self, source, stop_revision):
 
177
        """Import the gist of the ancestry of a particular revision."""
 
178
        if stop_revision is None:
 
179
            raise NotImplementedError
 
180
        revidmap = {}
 
181
        gitidmap = {}
 
182
        def parent_lookup(revid):
 
183
            try:
 
184
                return gitidmap[revid]
 
185
            except KeyError:
 
186
                return self.lookup_git_revid(revid)[0]
 
187
        todo = []
 
188
        source.lock_write()
 
189
        try:
 
190
            graph = source.get_graph()
 
191
            ancestry = [x for x in source.get_ancestry(stop_revision) if x is not None]
 
192
            for revid in graph.iter_topo_order(ancestry):
 
193
                if not self.has_revision(revid):
 
194
                    todo.append(revid)
 
195
            pb = ui.ui_factory.nested_progress_bar()
 
196
            try:
 
197
                for i, revid in enumerate(todo):
 
198
                    pb.update("pushing revisions", i, len(todo))
 
199
                    git_commit = self.import_revision_gist(source, revid,
 
200
                        parent_lookup)
 
201
                    gitidmap[revid] = git_commit
 
202
                    git_revid = self.get_mapping().revision_id_foreign_to_bzr(
 
203
                        git_commit)
 
204
                    revidmap[revid] = git_revid
 
205
            finally:
 
206
                pb.finished()
 
207
            source.fetch(self, revision_id=revidmap[stop_revision])
 
208
        finally:
 
209
            source.unlock()
 
210
        return revidmap
 
211
 
155
212
    def get_signature_text(self, revision_id):
156
213
        raise errors.NoSuchRevision(self, revision_id)
157
214
 
158
 
    def pack(self, hint=None, clean_obsolete_packs=False):
159
 
        self._git.object_store.pack_loose_objects()
160
 
 
161
 
    def lookup_foreign_revision_id(self, foreign_revid, mapping=None):
 
215
    def lookup_revision_id(self, revid):
162
216
        """Lookup a revision id.
163
 
 
 
217
        
 
218
        :param revid: Bazaar revision id.
 
219
        :return: Tuple with git revisionid and mapping.
164
220
        """
165
 
        assert type(foreign_revid) is str
166
 
        if mapping is None:
167
 
            mapping = self.get_mapping()
168
 
        from dulwich.protocol import (
169
 
            ZERO_SHA,
170
 
            )
171
 
        if foreign_revid == ZERO_SHA:
172
 
            return revision.NULL_REVISION
173
 
        commit = self._git[foreign_revid]
174
 
        rev, roundtrip_revid, verifiers = mapping.import_commit(commit,
175
 
            lambda x: None)
176
 
        # FIXME: check testament before doing this?
177
 
        if roundtrip_revid:
178
 
            return roundtrip_revid
179
 
        else:
180
 
            return rev.revision_id
 
221
        # Yes, this doesn't really work, but good enough as a stub
 
222
        return osutils.sha(rev_id).hexdigest(), self.get_mapping()
181
223
 
182
224
    def has_signature_for_revision_id(self, revision_id):
183
225
        return False
184
226
 
185
 
    def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
 
227
    def lookup_git_revid(self, bzr_revid):
186
228
        try:
187
229
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
188
230
        except errors.InvalidRevisionId:
189
 
            if mapping is None:
190
 
                mapping = self.get_mapping()
191
 
            try:
192
 
                return (self._git.refs[mapping.revid_as_refname(bzr_revid)],
193
 
                        mapping)
194
 
            except KeyError:
195
 
                # Update refs from Git commit objects
196
 
                # FIXME: Hitting this a lot will be very inefficient...
197
 
                for git_sha, revid, roundtrip_revid in self._iter_revision_ids():
198
 
                    if not roundtrip_revid:
199
 
                        continue
200
 
                    refname = mapping.revid_as_refname(roundtrip_revid)
201
 
                    self._git.refs[refname] = git_sha
202
 
                    if roundtrip_revid == bzr_revid:
203
 
                        return git_sha, mapping
204
 
                raise errors.NoSuchRevision(self, bzr_revid)
 
231
            raise errors.NoSuchRevision(self, bzr_revid)
205
232
 
206
233
    def get_revision(self, revision_id):
207
 
        git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
 
234
        git_commit_id, mapping = self.lookup_git_revid(revision_id)
208
235
        try:
209
 
            commit = self._git[git_commit_id]
 
236
            commit = self._git.commit(git_commit_id)
210
237
        except KeyError:
211
238
            raise errors.NoSuchRevision(self, revision_id)
212
 
        revision, roundtrip_revid, verifiers = mapping.import_commit(
213
 
            commit, self.lookup_foreign_revision_id)
 
239
        # print "fetched revision:", git_commit_id
 
240
        revision = mapping.import_commit(commit)
214
241
        assert revision is not None
215
 
        # FIXME: check verifiers ?
216
 
        if roundtrip_revid:
217
 
            revision.revision_id = roundtrip_revid
218
242
        return revision
219
243
 
220
244
    def has_revision(self, revision_id):
221
245
        try:
222
 
            git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
 
246
            self.get_revision(revision_id)
223
247
        except errors.NoSuchRevision:
224
248
            return False
225
 
        return (git_commit_id in self._git)
226
 
 
227
 
    def has_revisions(self, revision_ids):
228
 
        return set(filter(self.has_revision, revision_ids))
 
249
        else:
 
250
            return True
229
251
 
230
252
    def get_revisions(self, revids):
231
253
        return [self.get_revision(r) for r in revids]
253
275
        progress=None):
254
276
        return self._git.fetch_objects(determine_wants, graph_walker, progress)
255
277
 
256
 
    def _get_versioned_file_checker(self, text_key_references=None,
257
 
                        ancestors=None):
258
 
        return GitVersionedFileChecker(self,
259
 
            text_key_references=text_key_references, ancestors=ancestors)
260
 
 
261
 
 
262
 
class GitVersionedFileChecker(repository._VersionedFileChecker):
263
 
 
264
 
    file_ids = []
265
 
 
266
 
    def _check_file_version_parents(self, texts, progress_bar):
267
 
        return {}, []
 
278
 
 
279
class GitRevisionTree(revisiontree.RevisionTree):
 
280
 
 
281
    def __init__(self, repository, revision_id):
 
282
        self._repository = repository
 
283
        self.revision_id = revision_id
 
284
        assert isinstance(revision_id, str)
 
285
        git_id, self.mapping = repository.lookup_git_revid(revision_id)
 
286
        try:
 
287
            commit = repository._git.commit(git_id)
 
288
        except KeyError, r:
 
289
            raise errors.NoSuchRevision(repository, revision_id)
 
290
        self.tree = commit.tree
 
291
        self._inventory = inventory.Inventory(revision_id=revision_id)
 
292
        self._inventory.root.revision = revision_id
 
293
        self._build_inventory(self.tree, self._inventory.root, "")
 
294
 
 
295
    def get_revision_id(self):
 
296
        return self.revision_id
 
297
 
 
298
    def get_file_text(self, file_id):
 
299
        entry = self._inventory[file_id]
 
300
        if entry.kind == 'directory': return ""
 
301
        return self._repository._git.get_blob(entry.text_id).data
 
302
 
 
303
    def _build_inventory(self, tree_id, ie, path):
 
304
        assert isinstance(path, str)
 
305
        tree = self._repository._git.tree(tree_id)
 
306
        for mode, name, hexsha in tree.entries():
 
307
            basename = name.decode("utf-8")
 
308
            if path == "":
 
309
                child_path = name
 
310
            else:
 
311
                child_path = urlutils.join(path, name)
 
312
            file_id = self.mapping.generate_file_id(child_path)
 
313
            entry_kind = (mode & 0700000) / 0100000
 
314
            if entry_kind == 0:
 
315
                child_ie = inventory.InventoryDirectory(file_id, basename, ie.file_id)
 
316
            elif entry_kind == 1:
 
317
                file_kind = (mode & 070000) / 010000
 
318
                b = self._repository._git.get_blob(hexsha)
 
319
                if file_kind == 0:
 
320
                    child_ie = inventory.InventoryFile(file_id, basename, ie.file_id)
 
321
                    child_ie.text_sha1 = osutils.sha_string(b.data)
 
322
                elif file_kind == 2:
 
323
                    child_ie = inventory.InventoryLink(file_id, basename, ie.file_id)
 
324
                    child_ie.text_sha1 = osutils.sha_string("")
 
325
                else:
 
326
                    raise AssertionError(
 
327
                        "Unknown file kind, perms=%o." % (mode,))
 
328
                child_ie.text_id = b.id
 
329
                child_ie.text_size = len(b.data)
 
330
            else:
 
331
                raise AssertionError(
 
332
                    "Unknown blob kind, perms=%r." % (mode,))
 
333
            fs_mode = mode & 0777
 
334
            child_ie.executable = bool(fs_mode & 0111)
 
335
            child_ie.revision = self.revision_id
 
336
            self._inventory.add(child_ie)
 
337
            if entry_kind == 0:
 
338
                self._build_inventory(hexsha, child_ie, child_path)
268
339
 
269
340
 
270
341
class GitRepositoryFormat(repository.RepositoryFormat):
271
 
    """Git repository format."""
272
342
 
273
343
    supports_tree_reference = False
274
344
    rich_root_data = True
277
347
        return "Git Repository"
278
348
 
279
349
    def initialize(self, url, shared=False, _internal=False):
280
 
        raise errors.UninitializableFormat(self)
 
350
        raise bzr_errors.UninitializableFormat(self)
281
351
 
282
352
    def check_conversion_target(self, target_repo_format):
283
353
        return target_repo_format.rich_root_data
284
 
 
285
 
    def get_foreign_tests_repository_factory(self):
286
 
        from bzrlib.plugins.git.tests.test_repository import (
287
 
            ForeignTestsRepositoryFactory,
288
 
            )
289
 
        return ForeignTestsRepositoryFactory()
290
 
 
291
 
    def network_name(self):
292
 
        return "git"