/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

  • Committer: Jelmer Vernooij
  • Date: 2009-03-28 22:27:07 UTC
  • mto: (0.200.305 trunk)
  • mto: This revision was merged to the branch mainline in revision 6960.
  • Revision ID: jelmer@samba.org-20090328222707-n0y980ntev40xqd2
Fix blob lookup.

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