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

Black-box text for "bzr log" in a git tree. Further simplification of GitRevisionTree.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# Copyright (C) 2007 Canonical Ltd
2
 
# Copyright (C) 2008-2009 Jelmer Vernooij <jelmer@samba.org>
3
2
#
4
3
# This program is free software; you can redistribute it and/or modify
5
4
# it under the terms of the GNU General Public License as published by
18
17
"""An adapter between a Git Repository and a Bazaar Branch"""
19
18
 
20
19
from bzrlib import (
21
 
    errors,
 
20
    deprecated_graph,
22
21
    inventory,
23
22
    repository,
24
23
    revision,
25
24
    revisiontree,
26
 
    )
27
 
from bzrlib.foreign import (
28
 
    ForeignRepository,
29
 
    )
30
 
 
31
 
from bzrlib.plugins.git.commit import (
32
 
    GitCommitBuilder,
33
 
    )
34
 
from bzrlib.plugins.git.mapping import (
35
 
    default_mapping,
36
 
    foreign_git,
37
 
    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
 
    )
51
 
 
52
 
 
53
 
class GitRepository(ForeignRepository):
 
25
    urlutils,
 
26
    )
 
27
 
 
28
from bzrlib.plugins.git import (
 
29
    ids,
 
30
    model,
 
31
    )
 
32
 
 
33
 
 
34
class GitRepository(repository.Repository):
54
35
    """An adapter to git repositories for bzr."""
55
36
 
56
 
    _serializer = None
57
 
    _commit_builder_class = GitCommitBuilder
58
 
    vcs = foreign_git
59
 
 
60
37
    def __init__(self, gitdir, lockfiles):
61
 
        ForeignRepository.__init__(self, GitRepositoryFormat(), gitdir,
62
 
            lockfiles)
63
 
        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]:
69
 
            repository.InterRepository.register_optimiser(optimiser)
 
38
        self.bzrdir = gitdir
 
39
        self.control_files = lockfiles
 
40
        gitdirectory = gitdir.transport.local_abspath('.')
 
41
        self._git = model.GitModel(gitdirectory)
 
42
        self._revision_cache = {}
 
43
 
 
44
    def _ancestor_revisions(self, revision_ids):
 
45
        if revision_ids is not None:
 
46
            git_revisions = [gitrevid_from_bzr(r) for r in revision_ids]
 
47
        else:
 
48
            git_revisions = None
 
49
        for lines in self._git.ancestor_lines(git_revisions):
 
50
            yield self._parse_rev(lines)
70
51
 
71
52
    def is_shared(self):
72
 
        return False
73
 
 
74
 
    def supports_rich_root(self):
75
53
        return True
76
54
 
77
 
    def _warn_if_deprecated(self, branch=None):
78
 
        # This class isn't deprecated
79
 
        pass
80
 
 
81
 
    def get_mapping(self):
82
 
        return default_mapping
83
 
 
84
 
    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)
93
 
 
94
 
 
95
 
class LocalGitRepository(GitRepository):
96
 
    """Git repository on the file system."""
97
 
 
98
 
    def __init__(self, gitdir, lockfiles):
99
 
        GitRepository.__init__(self, gitdir, lockfiles)
100
 
        self.base = gitdir.root_transport.base
101
 
        self._git = gitdir._git
102
 
        self.signatures = None
103
 
        self.revisions = GitRevisions(self, self._git.object_store)
104
 
        self.inventories = None
105
 
        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
116
 
 
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)
123
 
        return ret
124
 
 
125
 
    def get_parent_map(self, revids):
126
 
        parent_map = {}
127
 
        for revision_id in revids:
128
 
            assert isinstance(revision_id, str)
129
 
            if revision_id == revision.NULL_REVISION:
130
 
                parent_map[revision_id] = ()
131
 
                continue
132
 
            hexsha, mapping = self.lookup_bzr_revision_id(revision_id)
133
 
            try:
134
 
                commit = self._git[hexsha]
135
 
            except KeyError:
136
 
                continue
137
 
            parent_map[revision_id] = [
138
 
                self.lookup_foreign_revision_id(p, mapping)
139
 
                for p in commit.parents]
140
 
        return parent_map
141
 
 
142
 
    def get_ancestry(self, revision_id, topo_sorted=True):
143
 
        """See Repository.get_ancestry().
144
 
        """
145
 
        if revision_id is None:
146
 
            return [None, revision.NULL_REVISION] + self._all_revision_ids()
147
 
        assert isinstance(revision_id, str)
148
 
        ancestry = []
149
 
        graph = self.get_graph()
150
 
        for rev, parents in graph.iter_ancestry([revision_id]):
151
 
            ancestry.append(rev)
152
 
        ancestry.reverse()
153
 
        return [None] + ancestry
154
 
 
155
 
    def get_signature_text(self, revision_id):
156
 
        raise errors.NoSuchRevision(self, revision_id)
157
 
 
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):
162
 
        """Lookup a revision id.
163
 
 
164
 
        """
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
 
55
    def get_revision_graph(self, revision_id=None):
 
56
        result = {}
 
57
        if revision_id is not None:
 
58
            param = [ids.convert_revision_id_bzr_to_git(revision_id)]
179
59
        else:
180
 
            return rev.revision_id
181
 
 
182
 
    def has_signature_for_revision_id(self, revision_id):
183
 
        return False
184
 
 
185
 
    def lookup_bzr_revision_id(self, bzr_revid, mapping=None):
186
 
        try:
187
 
            return mapping_registry.revision_id_bzr_to_foreign(bzr_revid)
188
 
        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)
 
60
            param = None
 
61
        for node, parents in self._git.ancestry(param).iteritems():
 
62
            bzr_node = ids.convert_revision_id_git_to_bzr(node)
 
63
            bzr_parents = [ids.convert_revision_id_git_to_bzr(n)
 
64
                           for n in parents]
 
65
            result[bzr_node] = bzr_parents
 
66
        return result
 
67
 
 
68
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
69
        graph = deprecated_graph.Graph()
 
70
        if revision_ids is not None:
 
71
            revision_ids = [ids.convert_revision_id_bzr_to_git(r)
 
72
                            for r in revision_ids]
 
73
        for node, parents in self._git.ancestry(revision_ids).iteritems():
 
74
            bzr_node = ids.convert_revision_id_git_to_bzr(node)
 
75
            bzr_parents = [ids.convert_revision_id_git_to_bzr(n)
 
76
                           for n in parents]
 
77
 
 
78
            graph.add_node(bzr_node, bzr_parents)
 
79
        return graph
205
80
 
206
81
    def get_revision(self, revision_id):
207
 
        git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
208
 
        try:
209
 
            commit = self._git[git_commit_id]
210
 
        except KeyError:
211
 
            raise errors.NoSuchRevision(self, revision_id)
212
 
        revision, roundtrip_revid, verifiers = mapping.import_commit(
213
 
            commit, self.lookup_foreign_revision_id)
214
 
        assert revision is not None
215
 
        # FIXME: check verifiers ?
216
 
        if roundtrip_revid:
217
 
            revision.revision_id = roundtrip_revid
218
 
        return revision
 
82
        if revision_id in self._revision_cache:
 
83
            return self._revision_cache[revision_id]
 
84
        raw = self._git.rev_list(
 
85
            [ids.convert_revision_id_bzr_to_git(revision_id)],
 
86
            max_count=1, header=True)
 
87
        return self._parse_rev(raw)
219
88
 
220
89
    def has_revision(self, revision_id):
221
90
        try:
222
 
            git_commit_id, mapping = self.lookup_bzr_revision_id(revision_id)
223
 
        except errors.NoSuchRevision:
 
91
            self.get_revision(revision_id)
 
92
        except NoSuchRevision:
224
93
            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))
229
 
 
230
 
    def get_revisions(self, revids):
231
 
        return [self.get_revision(r) for r in revids]
 
94
        else:
 
95
            return True
 
96
 
 
97
    def get_revisions(self, revisions):
 
98
        return [self.get_revision(r) for r in revisions]
 
99
 
 
100
    @classmethod
 
101
    def _parse_rev(klass, raw):
 
102
        """Parse a single git revision.
 
103
 
 
104
        * The first line is the git commit id.
 
105
        * Following lines conform to the 'name value' structure, until the
 
106
          first blank line.
 
107
        * All lines after the first blank line and until the NULL line have 4
 
108
          leading spaces and constitute the commit message.
 
109
 
 
110
        :param raw: sequence of newline-terminated strings, its last item is a
 
111
            single NULL character.
 
112
        :return: a `bzrlib.revision.Revision` object.
 
113
        """
 
114
        parents = []
 
115
        message_lines = []
 
116
        in_message = False
 
117
        committer_was_set = False
 
118
        revision_id = ids.convert_revision_id_git_to_bzr(raw[0][:-1])
 
119
        rev = revision.Revision(revision_id)
 
120
        rev.inventory_sha1 = ""
 
121
        assert raw[-1] == '\x00', (
 
122
            "Last item of raw was not a single NULL character.")
 
123
        for line in raw[1:-1]:
 
124
            if in_message:
 
125
                assert line[:4] == '    ', (
 
126
                    "Unexpected line format in commit message: %r" % line)
 
127
                message_lines.append(line[4:])
 
128
                continue
 
129
            if line == '\n':
 
130
                in_message = True
 
131
                continue
 
132
            name, value = line[:-1].split(' ', 1)
 
133
            if name == 'parent':
 
134
                rev.parent_ids.append(
 
135
                    ids.convert_revision_id_git_to_bzr(value))
 
136
                continue
 
137
            if name == 'author':
 
138
                author, timestamp, timezone = value.rsplit(' ', 2)
 
139
                rev.properties['author'] = author
 
140
                rev.properties['git-author-timestamp'] = timestamp
 
141
                rev.properties['git-author-timezone'] = timezone
 
142
                if not committer_was_set:
 
143
                    rev.committer = author
 
144
                    rev.timestamp = float(timestamp)
 
145
                    rev.timezone = klass._parse_tz(timezone)
 
146
                continue
 
147
            if name == 'committer':
 
148
                committer_was_set = True
 
149
                committer, timestamp, timezone = value.rsplit(' ', 2)
 
150
                rev.committer = committer
 
151
                rev.timestamp = float(timestamp)
 
152
                rev.timezone = klass._parse_tz(timezone)
 
153
                continue
 
154
            if name == 'tree':
 
155
                rev.properties['git-tree-id'] = value
 
156
                continue
 
157
 
 
158
        rev.message = ''.join(message_lines)
 
159
        return rev
 
160
 
 
161
    @classmethod
 
162
    def _parse_tz(klass, tz):
 
163
        """Parse a timezone specification in the [+|-]HHMM format.
 
164
 
 
165
        :return: the timezone offset in seconds.
 
166
        """
 
167
        assert len(tz) == 5
 
168
        sign = {'+': +1, '-': -1}[tz[0]]
 
169
        hours = int(tz[1:3])
 
170
        minutes = int(tz[3:])
 
171
        return float(sign * 60 * (60 * hours + minutes))
232
172
 
233
173
    def revision_trees(self, revids):
234
174
        for revid in revids:
235
175
            yield self.revision_tree(revid)
236
176
 
237
177
    def revision_tree(self, revision_id):
238
 
        revision_id = revision.ensure_null(revision_id)
239
 
        if revision_id == revision.NULL_REVISION:
240
 
            inv = inventory.Inventory(root_id=None)
241
 
            inv.revision_id = revision_id
242
 
            return revisiontree.RevisionTree(self, inv, revision_id)
243
178
        return GitRevisionTree(self, revision_id)
244
179
 
245
180
    def get_inventory(self, revision_id):
246
 
        assert revision_id != None
247
 
        return self.revision_tree(revision_id).inventory
248
 
 
249
 
    def set_make_working_trees(self, trees):
250
 
        pass
251
 
 
252
 
    def fetch_objects(self, determine_wants, graph_walker, resolve_ext_ref,
253
 
        progress=None):
254
 
        return self._git.fetch_objects(determine_wants, graph_walker, progress)
255
 
 
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 {}, []
268
 
 
269
 
 
270
 
class GitRepositoryFormat(repository.RepositoryFormat):
271
 
    """Git repository format."""
272
 
 
273
 
    supports_tree_reference = False
274
 
    rich_root_data = True
275
 
 
276
 
    def get_format_description(self):
277
 
        return "Git Repository"
278
 
 
279
 
    def initialize(self, url, shared=False, _internal=False):
280
 
        raise errors.UninitializableFormat(self)
281
 
 
282
 
    def check_conversion_target(self, target_repo_format):
283
 
        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"
 
181
        if revision_id is None:
 
182
            revision_id = revision.NULL_REVISION
 
183
        if revision_id == revision.NULL_REVISION:
 
184
            return inventory.Inventory(
 
185
                revision_id=revision_id, root_id=None)
 
186
        git_commit = ids.convert_revision_id_bzr_to_git(revision_id)
 
187
        git_inventory = self._git.get_inventory(git_commit)
 
188
        return self._parse_inventory(revision_id, git_inventory)
 
189
 
 
190
    @classmethod
 
191
    def _parse_inventory(klass, revid, git_inv):
 
192
        # For now, git inventory do not have root ids. It is not clear that we
 
193
        # can reliably support root ids. -- David Allouche 2007-12-28
 
194
        inv = inventory.Inventory(revision_id=revid)
 
195
        for perms, git_kind, git_id, path in git_inv:
 
196
            text_sha1 = None
 
197
            executable = False
 
198
            if git_kind == 'blob':
 
199
                text_sha1 = git_id
 
200
                if perms[1] == '0':
 
201
                    kind = 'file'
 
202
                    executable = bool(int(perms[-3:], 8) & 0111)
 
203
                elif perms[1] == '2':
 
204
                    kind = 'symlink'
 
205
                else:
 
206
                    raise AssertionError(
 
207
                        "Unknown blob kind, perms=%r." % (perms,))
 
208
            elif git_kind == 'tree':
 
209
                kind = 'directory'
 
210
            else:
 
211
                raise AssertionError(
 
212
                    "Unknown git entry kind: %r" % (git_kind,))
 
213
            # XXX: Maybe the file id should be prefixed by file kind, so when
 
214
            # the kind of path changes, the id changes too.
 
215
            # -- David Allouche 2007-12-28.
 
216
            entry = inv.add_path(path, kind, file_id=path.encode('utf-8'))
 
217
            entry.text_sha1 = text_sha1
 
218
            entry.executable = executable
 
219
        return inv
 
220
 
 
221
 
 
222
class GitRevisionTree(revisiontree.RevisionTree):
 
223
 
 
224
    def __init__(self, repository, revision_id):
 
225
        if revision_id is None:
 
226
            revision_id = revision.NULL_REVISION
 
227
        self._inventory = repository.get_inventory(revision_id)
 
228
        self._repository = repository
 
229
        self._revision_id = revision_id
 
230
 
 
231
    def get_file_lines(self, file_id):
 
232
        obj_id = self._inventory[file_id].text_sha1
 
233
        return self._repository._git.cat_file('blob', obj_id)