/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

Ultra-experimental support for "bzr pull". No test. No sanity.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""An adapter between a Git Repository and a Bazaar Branch"""
18
18
 
19
 
import os
20
 
import time
21
 
 
22
 
import bzrlib
23
19
from bzrlib import (
24
20
    deprecated_graph,
25
21
    errors,
26
 
    graph,
27
22
    inventory,
28
23
    osutils,
29
24
    repository,
30
25
    revision,
31
26
    revisiontree,
32
27
    urlutils,
33
 
    versionedfile,
34
 
    )
35
 
from bzrlib.foreign import (
36
 
        ForeignRepository,
37
 
        )
38
 
from bzrlib.trace import mutter
39
 
from bzrlib.transport import get_transport
40
 
 
41
 
from bzrlib.plugins.git.foreign import (
42
 
    versionedfiles,
43
 
    )
44
 
from bzrlib.plugins.git.mapping import default_mapping
45
 
 
46
 
from bzrlib.plugins.git import git
47
 
 
48
 
 
49
 
class GitTags(object):
50
 
 
51
 
    def __init__(self, tags):
52
 
        self._tags = tags
53
 
 
54
 
    def __iter__(self):
55
 
        return iter(self._tags)
56
 
 
57
 
 
58
 
class GitRepository(ForeignRepository):
 
28
    )
 
29
 
 
30
from bzrlib.plugins.git import (
 
31
    ids,
 
32
    model,
 
33
    )
 
34
 
 
35
 
 
36
class GitRepository(repository.Repository):
59
37
    """An adapter to git repositories for bzr."""
60
38
 
 
39
    # To make bzrlib happy
61
40
    _serializer = None
62
41
 
63
42
    def __init__(self, gitdir, lockfiles):
64
 
        ForeignRepository.__init__(self, GitFormat(), gitdir, lockfiles)
65
 
        from bzrlib.plugins.git import fetch
66
 
        repository.InterRepository.register_optimiser(fetch.InterGitRepository)
67
 
        repository.InterRepository.register_optimiser(fetch.InterGitNonGitRepository)
 
43
        self.bzrdir = gitdir
 
44
        self.control_files = lockfiles
 
45
        gitdirectory = gitdir.transport.local_abspath('.')
 
46
        self._git = model.GitModel(gitdirectory)
 
47
        self._revision_cache = {}
 
48
        self._blob_cache = {}
 
49
        self._entry_revision_cache = {}
 
50
        self._inventory_cache = {}
 
51
 
 
52
    def _ancestor_revisions(self, revision_ids):
 
53
        if revision_ids is not None:
 
54
            git_revisions = [gitrevid_from_bzr(r) for r in revision_ids]
 
55
        else:
 
56
            git_revisions = None
 
57
        for lines in self._git.ancestor_lines(git_revisions):
 
58
            yield self._parse_rev(lines)
 
59
        # print "fetched ancestors:", git_revisions
68
60
 
69
61
    def is_shared(self):
70
62
        return True
71
63
 
72
64
    def supports_rich_root(self):
73
 
        return True
74
 
 
75
 
    def _warn_if_deprecated(self):
76
 
        # This class isn't deprecated
77
 
        pass
78
 
 
79
 
    def get_mapping(self):
80
 
        return default_mapping
81
 
 
82
 
    def make_working_trees(self):
83
 
        return True
84
 
 
85
 
 
86
 
class LocalGitRepository(GitRepository):
87
 
 
88
 
    def __init__(self, gitdir, lockfiles):
89
 
        # FIXME: This also caches negatives. Need to be more careful 
90
 
        # about this once we start writing to git
91
 
        self._parents_provider = graph.CachingParentsProvider(self)
92
 
        GitRepository.__init__(self, gitdir, lockfiles)
93
 
        self.base = gitdir.root_transport.base
94
 
        self._git = gitdir._git
95
 
        self.texts = None
96
 
        self.signatures = versionedfiles.VirtualSignatureTexts(self)
97
 
        self.revisions = versionedfiles.VirtualRevisionTexts(self)
98
 
        self.tags = GitTags(self._git.get_tags())
99
 
 
100
 
    def all_revision_ids(self):
101
 
        ret = set([revision.NULL_REVISION])
102
 
        if self._git.heads() == []:
103
 
            return ret
104
 
        bzr_heads = [self.get_mapping().revision_id_foreign_to_bzr(h) for h in self._git.heads()]
105
 
        ret = set(bzr_heads)
106
 
        graph = self.get_graph()
107
 
        for rev, parents in graph.iter_ancestry(bzr_heads):
108
 
            ret.add(rev)
109
 
        return ret
110
 
 
111
 
    #def get_revision_delta(self, revision_id):
112
 
    #    parent_revid = self.get_revision(revision_id).parent_ids[0]
113
 
    #    diff = self._git.diff(ids.convert_revision_id_bzr_to_git(parent_revid),
114
 
    #                   ids.convert_revision_id_bzr_to_git(revision_id))
115
 
 
116
 
    def _make_parents_provider(self):
117
 
        """See Repository._make_parents_provider()."""
118
 
        return self._parents_provider
119
 
 
120
 
    def get_parent_map(self, revids):
121
 
        parent_map = {}
122
 
        mutter("get_parent_map(%r)", revids)
123
 
        for revision_id in revids:
124
 
            assert isinstance(revision_id, str)
125
 
            if revision_id == revision.NULL_REVISION:
126
 
                parent_map[revision_id] = ()
127
 
                continue
128
 
            hexsha = self.lookup_git_revid(revision_id, self.get_mapping())
129
 
            commit  = self._git.commit(hexsha)
130
 
            if commit is None:
131
 
                continue
132
 
            else:
133
 
                parent_map[revision_id] = [self.get_mapping().revision_id_foreign_to_bzr(p) for p in commit.parents]
134
 
        return parent_map
135
 
 
136
 
    def get_ancestry(self, revision_id, topo_sorted=True):
137
 
        """See Repository.get_ancestry().
138
 
        """
139
 
        if revision_id is None:
140
 
            return self._all_revision_ids()
141
 
        assert isinstance(revision_id, str)
142
 
        ancestry = []
143
 
        graph = self.get_graph()
144
 
        for rev, parents in graph.iter_ancestry([revision_id]):
145
 
            if rev == revision.NULL_REVISION:
146
 
                rev = None
147
 
            ancestry.append(rev)
148
 
        ancestry.reverse()
149
 
        return ancestry
 
65
        return False
 
66
 
 
67
    def get_revision_graph(self, revision_id=None):
 
68
        result = {}
 
69
        if revision_id is not None:
 
70
            param = [ids.convert_revision_id_bzr_to_git(revision_id)]
 
71
        else:
 
72
            param = None
 
73
        git_graph = self._git.get_revision_graph(param)
 
74
        # print "fetched revision graph:", param
 
75
        for node, parents in git_graph.iteritems():
 
76
            bzr_node = ids.convert_revision_id_git_to_bzr(node)
 
77
            bzr_parents = [ids.convert_revision_id_git_to_bzr(n)
 
78
                           for n in parents]
 
79
            result[bzr_node] = bzr_parents
 
80
        return result
 
81
 
 
82
    def get_revision_graph_with_ghosts(self, revision_ids=None):
 
83
        graph = deprecated_graph.Graph()
 
84
        if revision_ids is not None:
 
85
            revision_ids = [ids.convert_revision_id_bzr_to_git(r)
 
86
                            for r in revision_ids]
 
87
        git_graph = self._git.get_revision_graph(revision_ids)
 
88
        # print "fetched revision graph (ghosts):", revision_ids
 
89
        for node, parents in git_graph.iteritems():
 
90
            bzr_node = ids.convert_revision_id_git_to_bzr(node)
 
91
            bzr_parents = [ids.convert_revision_id_git_to_bzr(n)
 
92
                           for n in parents]
 
93
 
 
94
            graph.add_node(bzr_node, bzr_parents)
 
95
        return graph
 
96
 
 
97
    def get_ancestry(self, revision_id):
 
98
        param = [ids.convert_revision_id_bzr_to_git(revision_id)]
 
99
        git_ancestry = self._git.get_ancestry(param)
 
100
        # print "fetched ancestry:", param
 
101
        return [None] + [
 
102
            ids.convert_revision_id_git_to_bzr(git_id)
 
103
            for git_id in git_ancestry]
150
104
 
151
105
    def get_signature_text(self, revision_id):
152
106
        raise errors.NoSuchRevision(self, revision_id)
153
107
 
154
 
    def lookup_revision_id(self, revid):
155
 
        """Lookup a revision id.
156
 
        
157
 
        :param revid: Bazaar revision id.
158
 
        :return: Tuple with git revisionid and mapping.
159
 
        """
160
 
        # Yes, this doesn't really work, but good enough as a stub
161
 
        return osutils.sha(rev_id).hexdigest(), self.get_mapping()
162
 
 
163
 
    def has_signature_for_revision_id(self, revision_id):
164
 
        return False
165
 
 
166
 
    def lookup_git_revid(self, bzr_revid, mapping):
167
 
        try:
168
 
            return mapping.revision_id_bzr_to_foreign(bzr_revid)
169
 
        except errors.InvalidRevisionId:
170
 
            raise errors.NoSuchRevision(self, bzr_revid)
 
108
    def get_inventory_xml(self, revision_id):
 
109
        """See Repository.get_inventory_xml()."""
 
110
        return bzrlib.xml5.serializer_v5.write_inventory_to_string(
 
111
            self.get_inventory(revision_id))
 
112
 
 
113
    def get_inventory_sha1(self, revision_id):
 
114
        """Get the sha1 for the XML representation of an inventory.
 
115
 
 
116
        :param revision_id: Revision id of the inventory for which to return 
 
117
         the SHA1.
 
118
        :return: XML string
 
119
        """
 
120
 
 
121
        return osutils.sha_string(self.get_inventory_xml(revision_id))
 
122
 
 
123
    def get_revision_xml(self, revision_id):
 
124
        """Return the XML representation of a revision.
 
125
 
 
126
        :param revision_id: Revision for which to return the XML.
 
127
        :return: XML string
 
128
        """
 
129
        return bzrlib.xml5.serializer_v5.write_revision_to_string(
 
130
            self.get_revision(revision_id))
171
131
 
172
132
    def get_revision(self, revision_id):
173
 
        git_commit_id = self.lookup_git_revid(revision_id, self.get_mapping())
174
 
        try:
175
 
            commit = self._git.commit(git_commit_id)
176
 
        except KeyError:
177
 
            raise errors.NoSuchRevision(self, revision_id)
 
133
        if revision_id in self._revision_cache:
 
134
            return self._revision_cache[revision_id]
 
135
        git_commit_id = ids.convert_revision_id_bzr_to_git(revision_id)
 
136
        raw = self._git.rev_list([git_commit_id], max_count=1, header=True)
178
137
        # print "fetched revision:", git_commit_id
179
 
        revision = self.get_mapping().import_commit(commit)
180
 
        assert revision is not None
 
138
        revision = self._parse_rev(raw)
 
139
        self._revision_cache[revision_id] = revision
181
140
        return revision
182
141
 
183
142
    def has_revision(self, revision_id):
184
143
        try:
185
144
            self.get_revision(revision_id)
186
 
        except errors.NoSuchRevision:
 
145
        except NoSuchRevision:
187
146
            return False
188
147
        else:
189
148
            return True
190
149
 
191
 
    def get_revisions(self, revids):
192
 
        return [self.get_revision(r) for r in revids]
 
150
    def get_revisions(self, revisions):
 
151
        return [self.get_revision(r) for r in revisions]
 
152
 
 
153
    @classmethod
 
154
    def _parse_rev(klass, raw):
 
155
        """Parse a single git revision.
 
156
 
 
157
        * The first line is the git commit id.
 
158
        * Following lines conform to the 'name value' structure, until the
 
159
          first blank line.
 
160
        * All lines after the first blank line and until the NULL line have 4
 
161
          leading spaces and constitute the commit message.
 
162
 
 
163
        :param raw: sequence of newline-terminated strings, its last item is a
 
164
            single NULL character.
 
165
        :return: a `bzrlib.revision.Revision` object.
 
166
        """
 
167
        parents = []
 
168
        message_lines = []
 
169
        in_message = False
 
170
        committer_was_set = False
 
171
        revision_id = ids.convert_revision_id_git_to_bzr(raw[0][:-1])
 
172
        rev = revision.Revision(revision_id)
 
173
        rev.inventory_sha1 = ""
 
174
        assert raw[-1] == '\x00', (
 
175
            "Last item of raw was not a single NULL character.")
 
176
        for line in raw[1:-1]:
 
177
            if in_message:
 
178
                assert line[:4] == '    ', (
 
179
                    "Unexpected line format in commit message: %r" % line)
 
180
                message_lines.append(line[4:])
 
181
                continue
 
182
            if line == '\n':
 
183
                in_message = True
 
184
                continue
 
185
            name, value = line[:-1].split(' ', 1)
 
186
            if name == 'parent':
 
187
                rev.parent_ids.append(
 
188
                    ids.convert_revision_id_git_to_bzr(value))
 
189
                continue
 
190
            if name == 'author':
 
191
                author, timestamp, timezone = value.rsplit(' ', 2)
 
192
                rev.properties['author'] = author
 
193
                rev.properties['git-author-timestamp'] = timestamp
 
194
                rev.properties['git-author-timezone'] = timezone
 
195
                if not committer_was_set:
 
196
                    rev.committer = author
 
197
                    rev.timestamp = float(timestamp)
 
198
                    rev.timezone = klass._parse_tz(timezone)
 
199
                continue
 
200
            if name == 'committer':
 
201
                committer_was_set = True
 
202
                committer, timestamp, timezone = value.rsplit(' ', 2)
 
203
                rev.committer = committer
 
204
                rev.timestamp = float(timestamp)
 
205
                rev.timezone = klass._parse_tz(timezone)
 
206
                continue
 
207
            if name == 'tree':
 
208
                rev.properties['git-tree-id'] = value
 
209
                continue
 
210
 
 
211
        rev.message = ''.join(message_lines)
 
212
        return rev
 
213
 
 
214
    @classmethod
 
215
    def _parse_tz(klass, tz):
 
216
        """Parse a timezone specification in the [+|-]HHMM format.
 
217
 
 
218
        :return: the timezone offset in seconds.
 
219
        """
 
220
        assert len(tz) == 5
 
221
        sign = {'+': +1, '-': -1}[tz[0]]
 
222
        hours = int(tz[1:3])
 
223
        minutes = int(tz[3:])
 
224
        return sign * 60 * (60 * hours + minutes)
193
225
 
194
226
    def revision_trees(self, revids):
195
227
        for revid in revids:
196
228
            yield self.revision_tree(revid)
197
229
 
198
230
    def revision_tree(self, revision_id):
199
 
        revision_id = revision.ensure_null(revision_id)
200
 
 
 
231
        return GitRevisionTree(self, revision_id)
 
232
 
 
233
    def _get_blob(self, git_id):
 
234
        try:
 
235
            return self._blob_cache[git_id]
 
236
        except KeyError:
 
237
            blob = self._git.cat_file('blob', git_id)
 
238
            # print "fetched blob:", git_id
 
239
            self._blob_cache[git_id] = blob
 
240
            return blob
 
241
 
 
242
    def get_inventory(self, revision_id):
 
243
        if revision_id is None:
 
244
            revision_id = revision.NULL_REVISION
201
245
        if revision_id == revision.NULL_REVISION:
202
 
            inv = inventory.Inventory(root_id=None)
203
 
            inv.revision_id = revision_id
204
 
            return revisiontree.RevisionTree(self, inv, revision_id)
205
 
 
206
 
        return GitRevisionTree(self, self.get_mapping(), revision_id)
207
 
 
208
 
    def get_inventory(self, revision_id):
209
 
        assert revision_id != None
210
 
        return self.revision_tree(revision_id).inventory
211
 
 
212
 
    def set_make_working_trees(self, trees):
213
 
        pass
214
 
 
215
 
    def fetch_objects(self, determine_wants, graph_walker, progress=None):
216
 
        return self._git.fetch_objects(determine_wants, graph_walker, progress)
217
 
 
 
246
            return inventory.Inventory(
 
247
                revision_id=revision_id, root_id=None)
 
248
 
 
249
        # First pass at building the inventory. We need this one to get the
 
250
        # git ids, so we do not have to cache the entire tree text. Ideally,
 
251
        # this should be all we need to do.
 
252
        git_commit = ids.convert_revision_id_bzr_to_git(revision_id)
 
253
        git_inventory = self._git.get_inventory(git_commit)
 
254
        # print "fetched inventory:", git_commit
 
255
        inv = self._parse_inventory(revision_id, git_inventory)
 
256
 
 
257
        # Second pass at building the inventory. There we retrieve additional
 
258
        # data that bzrlib requires: text sizes, sha1s, symlink targets and
 
259
        # revisions that introduced inventory entries
 
260
        inv.git_file_data = {}
 
261
        for file_id in sorted(inv.git_ids.iterkeys()):
 
262
            git_id = inv.git_ids[file_id]
 
263
            entry = inv[file_id]
 
264
            self._set_entry_text_info(inv, entry, git_id)
 
265
        for file_id in sorted(inv.git_ids.iterkeys()):
 
266
            git_id = inv.git_ids[file_id]
 
267
            entry = inv[file_id]
 
268
            path = inv.id2path(file_id)
 
269
            self._set_entry_revision(entry, revision_id, path, git_id)
 
270
        return inv
 
271
 
 
272
    @classmethod
 
273
    def _parse_inventory(klass, revid, git_inv):
 
274
        # For now, git inventory do not have root ids. It is not clear that we
 
275
        # can reliably support root ids. -- David Allouche 2007-12-28
 
276
        inv = inventory.Inventory(revision_id=revid)
 
277
        inv.git_ids = {}
 
278
        for perms, git_kind, git_id, path in git_inv:
 
279
            text_sha1 = None
 
280
            executable = False
 
281
            if git_kind == 'blob':
 
282
                if perms[1] == '0':
 
283
                    kind = 'file'
 
284
                    executable = bool(int(perms[-3:], 8) & 0111)
 
285
                elif perms[1] == '2':
 
286
                    kind = 'symlink'
 
287
                else:
 
288
                    raise AssertionError(
 
289
                        "Unknown blob kind, perms=%r." % (perms,))
 
290
            elif git_kind == 'tree':
 
291
                kind = 'directory'
 
292
            else:
 
293
                raise AssertionError(
 
294
                    "Unknown git entry kind: %r" % (git_kind,))
 
295
            # XXX: Maybe the file id should be prefixed by file kind, so when
 
296
            # the kind of path changes, the id changes too.
 
297
            # -- David Allouche 2007-12-28.
 
298
            file_id = escape_file_id(path.encode('utf-8'))
 
299
            entry = inv.add_path(path, kind, file_id=file_id)
 
300
            entry.executable = executable
 
301
            inv.git_ids[file_id] = git_id
 
302
        inv.root.revision = revid
 
303
        return inv
 
304
 
 
305
    def _set_entry_text_info(self, inv, entry, git_id):
 
306
        if entry.kind == 'directory':
 
307
            return
 
308
        lines = self._get_blob(git_id)
 
309
        entry.text_size = sum(len(line) for line in lines)
 
310
        entry.text_sha1 = osutils.sha_strings(lines)
 
311
        if entry.kind == 'symlink':
 
312
            entry.symlink_target = ''.join(lines)
 
313
        inv.git_file_data[entry.file_id] = lines
 
314
 
 
315
    def _get_file_revision(self, revision_id, path):
 
316
        lines = self._git.rev_list(
 
317
            [ids.convert_revision_id_bzr_to_git(revision_id)],
 
318
            max_count=1, topo_order=True, paths=[path])
 
319
        [line] = lines
 
320
        result = ids.convert_revision_id_git_to_bzr(line[:-1])
 
321
        # print "fetched file revision", line[:-1], path
 
322
        return result
 
323
 
 
324
    # The various version of _get_entry_revision can be tested by pulling from
 
325
    # the git repo of git itself. First pull up to r700, then r702 to
 
326
    # reproduce the RevisionNotPresent errors.
 
327
 
 
328
    def _set_entry_revision_unoptimized(self, entry, revid, path, git_id):
 
329
        # This is unusably slow and will lead to recording a few unnecessary
 
330
        # duplicated file texts. But it seems to be consistent enough to let
 
331
        # pulls resume without causing RevisionNotPresent errors.
 
332
        entry.revision = self._get_file_revision(revid, path)
 
333
 
 
334
    def _set_entry_revision_optimized1(self, entry, revid, path, git_id):
 
335
        # This is much faster, produces fewer unique file texts, but will
 
336
        # cause RevisionNotPresent errors when resuming pull.
 
337
        #
 
338
        # Oops, this does not account for changes in executable bit. That is
 
339
        # probably why it produces fewer unique texts.
 
340
        cached = self._entry_revision_cache.get((revid, path, git_id))
 
341
        if cached is not None:
 
342
            entry.revision = cached
 
343
            return
 
344
        revision = self.get_revision(revid)
 
345
        for parent_id in revision.parent_ids:
 
346
            entry_rev = self._entry_revision_cache.get((parent_id, path, git_id))
 
347
            if entry_rev is not None:
 
348
                break
 
349
        else:
 
350
            entry_rev = self._get_file_revision(revid, path)
 
351
        self._entry_revision_cache[(revid, path, git_id)] = entry_rev
 
352
        entry.revision = entry_rev
 
353
 
 
354
    def _set_entry_revision_optimized2(self, entry, revid, path, git_id):
 
355
        # This is slower than the previous one, and does not appear to have a
 
356
        # subtantially different effect. Same number of unique texts, same
 
357
        # RevisionNotPresent error.
 
358
        #
 
359
        # Oops, this does not account for changes in executable bit. That is
 
360
        # probably why it produces fewer unique texts.
 
361
        cached = self._entry_revision_cache.get((revid, path, git_id))
 
362
        if cached is not None:
 
363
            entry.revision = cached
 
364
            return
 
365
        revision = self.get_revision(revid)
 
366
        parent_hits = []
 
367
        for parent_id in revision.parent_ids:
 
368
            entry_rev = self._entry_revision_cache.get((parent_id, path, git_id))
 
369
            if entry_rev is not None:
 
370
                parent_hits.append(entry_rev)
 
371
        if len(parent_hits) == len(revision.parent_ids) and len(set(parent_hits)) == 1:
 
372
            entry_rev = parent_hits[0]
 
373
        else:
 
374
            entry_rev = self._get_file_revision(revid, path)
 
375
        self._entry_revision_cache[(revid, path, git_id)] = entry_rev
 
376
        entry.revision = entry_rev
 
377
 
 
378
    _original_get_inventory = get_inventory
 
379
    def _get_inventory_caching(self, revid):
 
380
        if revid in self._inventory_cache:
 
381
            return self._inventory_cache[revid]
 
382
        inv = self._original_get_inventory(revid)
 
383
        self._inventory_cache[revid] = inv
 
384
        return inv
 
385
 
 
386
    def _set_entry_revision_optimized3(self, entry, revid, path, git_id):
 
387
        # Depends on _get_inventory_caching.
 
388
 
 
389
        # Set the revision of directories to the current revision. It's not
 
390
        # accurate, but we cannot compare directory contents from here.
 
391
        if entry.kind == 'directory':
 
392
            entry.revision = revid
 
393
            return
 
394
        # Build ancestral inventories by walking parents depth first. Ideally
 
395
        # this should be done in an inter-repository, where already imported
 
396
        # data can be used as reference.
 
397
        current_revid = revid
 
398
        revision = self.get_revision(revid)
 
399
        pending_revids = list(reversed(revision.parent_ids))
 
400
        while pending_revids:
 
401
            revid = pending_revids.pop()
 
402
            if revid in self._inventory_cache:
 
403
                continue
 
404
            # Not in cache, ensure parents are in cache first.
 
405
            pending_revids.append(revid)
 
406
            revision = self.get_revision(revid)
 
407
            for parent_id in reversed(revision.parent_ids):
 
408
                if parent_id not in self._inventory_cache:
 
409
                    pending_revids.extend(reversed(revision.parent_ids))
 
410
                    break
 
411
            else:
 
412
                # All parents are in cache, we can now build this inventory.
 
413
                revid = pending_revids.pop()
 
414
                self.get_inventory(revid) # populate cache
 
415
        # We now have all ancestral inventories in the cache. Get entries by
 
416
        # the same file_id in parent inventories, and use the revision of the
 
417
        # first one that has the same text_sha1 and executable bit.
 
418
        revision = self.get_revision(current_revid)
 
419
        for revid in revision.parent_ids:
 
420
            inventory = self.get_inventory(revid)
 
421
            if entry.file_id in inventory:
 
422
                parent_entry = inventory[entry.file_id]
 
423
                if (parent_entry.text_sha1 == entry.text_sha1
 
424
                        and parent_entry.executable == entry.executable):
 
425
                    entry.revision = parent_entry.revision
 
426
                    return
 
427
        # If we get here, that means we found no matching parent entry, use
 
428
        # the current revision.
 
429
        entry.revision = current_revid
 
430
 
 
431
    def _set_entry_revision_optimized4(self, entry, revid, path, git_id):
 
432
        # Same as optimized1, but uses the executable bit in the cache index.
 
433
        # That appears to have the same behaviour as the unoptimized version.
 
434
        cached = self._entry_revision_cache.get(
 
435
            (revid, path, git_id, entry.executable))
 
436
        if cached is not None:
 
437
            entry.revision = cached
 
438
            return
 
439
        revision = self.get_revision(revid)
 
440
        for parent_id in revision.parent_ids:
 
441
            entry_rev = self._entry_revision_cache.get(
 
442
                (parent_id, path, git_id, entry.executable))
 
443
            if entry_rev is not None:
 
444
                break
 
445
        else:
 
446
            entry_rev = self._get_file_revision(revid, path)
 
447
        self._entry_revision_cache[
 
448
            (revid, path, git_id, entry.executable)] = entry_rev
 
449
        entry.revision = entry_rev
 
450
 
 
451
    def _set_entry_revision_optimized5(self, entry, revid, path, git_id):
 
452
        # Same as optimized4, but makes get_inventory non-reentrant, and uses
 
453
        # a more structured cache.
 
454
        #
 
455
        # cache[revision][path, git_id, executable] -> revision
 
456
        #
 
457
        # If a revision is in the cache, we assume it contains entries for the
 
458
        # whole inventory. So if all parent revisions are in the cache, but no
 
459
        # parent entry is present, then the entry revision is the current
 
460
        # revision. That amortizes the number of git calls for large pulls to
 
461
        # zero.
 
462
        cached = self._entry_revision_cache.get(revid, {}).get(
 
463
            (path, git_id, entry.executable))
 
464
        if cached is not None:
 
465
            entry.revision = cached
 
466
            return
 
467
        revision = self.get_revision(revid)
 
468
        all_parents_in_cache = True
 
469
        for parent_id in revision.parent_ids:
 
470
            if parent_id not in self._entry_revision_cache:
 
471
                all_parents_in_cache = False
 
472
                continue
 
473
            entry_rev = self._entry_revision_cache[parent_id].get(
 
474
                (path, git_id, entry.executable))
 
475
            if entry_rev is not None:
 
476
                break
 
477
        else:
 
478
            if all_parents_in_cache:
 
479
                entry_rev = revid
 
480
            else:
 
481
                entry_rev = self._get_file_revision(revid, path)
 
482
        self._entry_revision_cache.setdefault(
 
483
            revid, {})[(path, git_id, entry.executable)] = entry_rev
 
484
        entry.revision = entry_rev
 
485
 
 
486
    _set_entry_revision = _set_entry_revision_optimized5
 
487
    #get_inventory = _get_inventory_caching
 
488
 
 
489
 
 
490
def escape_file_id(file_id):
 
491
    return file_id.replace('_', '__').replace(' ', '_s')
218
492
 
219
493
class GitRevisionTree(revisiontree.RevisionTree):
220
494
 
221
 
    def __init__(self, repository, mapping, revision_id):
 
495
    def __init__(self, repository, revision_id):
 
496
        if revision_id is None:
 
497
            revision_id = revision.NULL_REVISION
 
498
        self._inventory = repository.get_inventory(revision_id)
222
499
        self._repository = repository
223
 
        self.revision_id = revision_id
224
 
        assert isinstance(revision_id, str)
225
 
        self.mapping = mapping
226
 
        git_id = repository.lookup_git_revid(revision_id, self.mapping)
227
 
        try:
228
 
            commit = repository._git.commit(git_id)
229
 
        except KeyError, r:
230
 
            raise errors.NoSuchRevision(repository, revision_id)
231
 
        self.tree = commit.tree
232
 
        self._inventory = inventory.Inventory(revision_id=revision_id)
233
 
        self._inventory.root.revision = revision_id
234
 
        self._build_inventory(self.tree, self._inventory.root, "")
235
 
 
236
 
    def get_revision_id(self):
237
 
        return self.revision_id
238
 
 
239
 
    def get_file_text(self, file_id):
 
500
        self._revision_id = revision_id
 
501
 
 
502
    def get_file_lines(self, file_id):
240
503
        entry = self._inventory[file_id]
241
 
        if entry.kind == 'directory': return ""
242
 
        return self._repository._git.get_blob(entry.text_id).data
243
 
 
244
 
    def _build_inventory(self, tree_id, ie, path):
245
 
        assert isinstance(path, str)
246
 
        tree = self._repository._git.tree(tree_id)
247
 
        for mode, name, hexsha in tree.entries():
248
 
            basename = name.decode("utf-8")
249
 
            if path == "":
250
 
                child_path = name
251
 
            else:
252
 
                child_path = urlutils.join(path, name)
253
 
            file_id = self.mapping.generate_file_id(child_path)
254
 
            entry_kind = (mode & 0700000) / 0100000
255
 
            if entry_kind == 0:
256
 
                child_ie = inventory.InventoryDirectory(file_id, basename, ie.file_id)
257
 
            elif entry_kind == 1:
258
 
                file_kind = (mode & 070000) / 010000
259
 
                b = self._repository._git.get_blob(hexsha)
260
 
                if file_kind == 0:
261
 
                    child_ie = inventory.InventoryFile(file_id, basename, ie.file_id)
262
 
                    child_ie.text_sha1 = osutils.sha_string(b.data)
263
 
                elif file_kind == 2:
264
 
                    child_ie = inventory.InventoryLink(file_id, basename, ie.file_id)
265
 
                    child_ie.text_sha1 = osutils.sha_string("")
266
 
                else:
267
 
                    raise AssertionError(
268
 
                        "Unknown file kind, perms=%o." % (mode,))
269
 
                child_ie.text_id = b.id
270
 
                child_ie.text_size = len(b.data)
271
 
            else:
272
 
                raise AssertionError(
273
 
                    "Unknown blob kind, perms=%r." % (mode,))
274
 
            fs_mode = mode & 0777
275
 
            child_ie.executable = bool(fs_mode & 0111)
276
 
            child_ie.revision = self.revision_id
277
 
            self._inventory.add(child_ie)
278
 
            if entry_kind == 0:
279
 
                self._build_inventory(hexsha, child_ie, child_path)
280
 
 
281
 
 
282
 
class GitFormat(object):
283
 
 
284
 
    supports_tree_reference = False
285
 
    rich_root_data = True
286
 
 
287
 
    def get_format_description(self):
288
 
        return "Git Repository"
289
 
 
290
 
    def initialize(self, url, shared=False, _internal=False):
291
 
        raise bzr_errors.UninitializableFormat(self)
292
 
 
293
 
    def check_conversion_target(self, target_repo_format):
294
 
        return target_repo_format.rich_root_data
 
504
        if entry.kind == 'directory': return []
 
505
        return self._inventory.git_file_data[file_id]
 
506
        
 
507
        obj_id = self._inventory.git_ids[file_id]
 
508
        assert obj_id is not None, (
 
509
            "git_id must not be None: %r" % (self._inventory[file_id],))
 
510
        return self._repository._git.cat_file('blob', obj_id)