/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 git
20
 
import os
21
 
import time
22
 
 
23
 
import bzrlib
24
19
from bzrlib import (
25
20
    deprecated_graph,
26
21
    errors,
30
25
    revision,
31
26
    revisiontree,
32
27
    urlutils,
33
 
    versionedfile,
34
28
    )
35
 
from bzrlib.transport import get_transport
36
29
 
37
30
from bzrlib.plugins.git import (
38
 
    cache,
39
31
    ids,
 
32
    model,
40
33
    )
41
34
 
42
35
 
43
 
cachedbs = {}
44
 
 
45
 
 
46
36
class GitRepository(repository.Repository):
47
37
    """An adapter to git repositories for bzr."""
48
38
 
 
39
    # To make bzrlib happy
49
40
    _serializer = None
50
41
 
51
42
    def __init__(self, gitdir, lockfiles):
52
 
        self.base = gitdir.root_transport.base
53
43
        self.bzrdir = gitdir
54
44
        self.control_files = lockfiles
55
 
        self._git = git.repo.Repo(gitdir.root_transport.local_abspath("."))
 
45
        gitdirectory = gitdir.transport.local_abspath('.')
 
46
        self._git = model.GitModel(gitdirectory)
 
47
        self._revision_cache = {}
56
48
        self._blob_cache = {}
57
 
        self._blob_info_cache = {}
58
 
        cache_dir = cache.create_cache_dir()
59
 
        cachedir_transport = get_transport(cache_dir)
60
 
        cache_file = os.path.join(cache_dir, 'cache-%s' % ids.NAMESPACE)
61
 
        if not cachedbs.has_key(cache_file):
62
 
            cachedbs[cache_file] = cache.sqlite3.connect(cache_file)
63
 
        self.cachedb = cachedbs[cache_file]
64
 
        self._init_cachedb()
65
 
        self.texts = None
66
 
        self.signatures = versionedfile.VirtualSignatureTexts(self)
67
 
        self.revisions = None
68
 
        self._format = GitFormat()
69
 
        self._fallback_repositories = []
 
49
        self._entry_revision_cache = {}
 
50
        self._inventory_cache = {}
70
51
 
71
 
    def _init_cachedb(self):
72
 
        self.cachedb.executescript("""
73
 
        create table if not exists inventory (
74
 
            revid blob);
75
 
        create unique index if not exists inventory_revid
76
 
            on inventory (revid);
77
 
        create table if not exists entry_revision (
78
 
            inventory blob,
79
 
            path blob,
80
 
            gitid blob,
81
 
            executable integer,
82
 
            revision blob);
83
 
        create unique index if not exists entry_revision_revid_path
84
 
            on entry_revision (inventory, path);
85
 
        """)
86
 
        self.cachedb.commit()
 
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
87
60
 
88
61
    def is_shared(self):
89
62
        return True
91
64
    def supports_rich_root(self):
92
65
        return False
93
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
 
94
97
    def get_ancestry(self, revision_id):
95
 
        revision_id = revision.ensure_null(revision_id)
96
 
        ret = []
97
 
        if revision_id != revision.NULL_REVISION:
98
 
            skip = 0
99
 
            max_count = 1000
100
 
            cms = None
101
 
            while cms != []:
102
 
                cms = self._git.commits(ids.convert_revision_id_bzr_to_git(revision_id), max_count=max_count, skip=skip)
103
 
                skip += max_count
104
 
                ret += [ids.convert_revision_id_git_to_bzr(cm.id) for cm in cms]
105
 
        return [None] + ret
 
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]
106
104
 
107
105
    def get_signature_text(self, revision_id):
108
106
        raise errors.NoSuchRevision(self, revision_id)
109
107
 
110
 
    def has_signature_for_revision_id(self, revision_id):
111
 
        return False
112
 
 
113
 
    def get_parent_map(self, revision_ids):
114
 
        ret = {}
115
 
        for revid in revision_ids:
116
 
            commit = self._git.commit(ids.convert_revision_id_bzr_to_git(revid))
117
 
            ret[revid] = tuple([ids.convert_revision_id_git_to_bzr(p.id) for p in commit.parents])
118
 
        return ret
 
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))
119
131
 
120
132
    def get_revision(self, revision_id):
 
133
        if revision_id in self._revision_cache:
 
134
            return self._revision_cache[revision_id]
121
135
        git_commit_id = ids.convert_revision_id_bzr_to_git(revision_id)
122
 
        commit = self._git.commit(git_commit_id)
 
136
        raw = self._git.rev_list([git_commit_id], max_count=1, header=True)
123
137
        # print "fetched revision:", git_commit_id
124
 
        revision = self._parse_rev(commit)
 
138
        revision = self._parse_rev(raw)
 
139
        self._revision_cache[revision_id] = revision
125
140
        return revision
126
141
 
127
142
    def has_revision(self, revision_id):
136
151
        return [self.get_revision(r) for r in revisions]
137
152
 
138
153
    @classmethod
139
 
    def _parse_rev(klass, commit):
140
 
        """Convert a git commit to a bzr revision.
141
 
 
 
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.
142
165
        :return: a `bzrlib.revision.Revision` object.
143
166
        """
144
 
        rev = revision.Revision(ids.convert_revision_id_git_to_bzr(commit.id))
145
 
        rev.parent_ids = tuple([ids.convert_revision_id_git_to_bzr(p.id) for p in commit.parents])
 
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)
146
173
        rev.inventory_sha1 = ""
147
 
        rev.message = commit.message.decode("utf-8", "replace")
148
 
        rev.committer = str(commit.committer)
149
 
        rev.properties['author'] = str(commit.author)
150
 
        rev.timestamp = time.mktime(commit.committed_date)
151
 
        rev.timezone = 0
 
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)
152
212
        return rev
153
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)
 
225
 
154
226
    def revision_trees(self, revids):
155
227
        for revid in revids:
156
228
            yield self.revision_tree(revid)
157
229
 
158
230
    def revision_tree(self, revision_id):
159
 
        revision_id = revision.ensure_null(revision_id)
160
 
 
161
 
        if revision_id == revision.NULL_REVISION:
162
 
            inv = inventory.Inventory(root_id=None)
163
 
            inv.revision_id = revision_id
164
 
            return revisiontree.RevisionTree(self, inv, revision_id)
165
 
 
166
231
        return GitRevisionTree(self, revision_id)
167
232
 
168
 
    def _fetch_blob(self, git_id):
169
 
        lines = self._git.cat_file('blob', git_id)
170
 
        # print "fetched blob:", git_id
171
 
        if self._building_inventory is not None:
172
 
            self._building_inventory.git_file_data[git_id] = lines
173
 
        return lines
174
 
 
175
233
    def _get_blob(self, git_id):
176
234
        try:
177
235
            return self._blob_cache[git_id]
178
236
        except KeyError:
179
 
            return self._fetch_blob(git_id)
180
 
 
181
 
    def _get_blob_caching(self, git_id):
182
 
        try:
183
 
            return self._blob_cache[git_id]
184
 
        except KeyError:
185
 
            lines = self._fetch_blob(git_id)
186
 
            self._blob_cache[git_id] = lines
187
 
            return lines
188
 
 
189
 
    def _get_blob_info(self, git_id):
190
 
        try:
191
 
            return self._blob_info_cache[git_id]
192
 
        except KeyError:
193
 
            lines = self._get_blob(git_id)
194
 
            size = sum(len(line) for line in lines)
195
 
            sha1 = osutils.sha_strings(lines)
196
 
            self._blob_info_cache[git_id] = (size, sha1)
197
 
            return size, sha1
 
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
198
241
 
199
242
    def get_inventory(self, revision_id):
200
 
        assert revision_id != None
201
 
        return self.revision_tree(revision_id).inventory
 
243
        if revision_id is None:
 
244
            revision_id = revision.NULL_REVISION
 
245
        if revision_id == revision.NULL_REVISION:
 
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
202
304
 
203
305
    def _set_entry_text_info(self, inv, entry, git_id):
204
306
        if entry.kind == 'directory':
205
307
            return
206
 
        size, sha1 = self._get_blob_info(git_id)
207
 
        entry.text_size = size
208
 
        entry.text_sha1 = sha1
 
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)
209
311
        if entry.kind == 'symlink':
210
 
            lines = self._get_blob_caching(git_id)
211
312
            entry.symlink_target = ''.join(lines)
 
313
        inv.git_file_data[entry.file_id] = lines
212
314
 
213
315
    def _get_file_revision(self, revision_id, path):
214
316
        lines = self._git.rev_list(
219
321
        # print "fetched file revision", line[:-1], path
220
322
        return result
221
323
 
222
 
    def _get_entry_revision_from_db(self, revid, path, git_id, executable):
223
 
        result = self.cachedb.execute(
224
 
            "select revision from entry_revision where"
225
 
            " inventory=? and path=? and gitid=? and executable=?",
226
 
            (revid, path, git_id, executable)).fetchone()
227
 
        if result is None:
228
 
            return None
229
 
        [revision] = result
230
 
        return revision
231
 
 
232
 
    def _set_entry_revision_in_db(self, revid, path, git_id, executable, revision):
233
 
        self.cachedb.execute(
234
 
            "insert into entry_revision"
235
 
            " (inventory, path, gitid, executable, revision)"
236
 
            " values (?, ?, ?, ?, ?)",
237
 
            (revid, path, git_id, executable, revision))
238
 
 
239
 
    def _all_inventories_in_db(self, revids):
240
 
        for revid in revids:
241
 
            result = self.cachedb.execute(
242
 
                "select count(*) from inventory where revid = ?",
243
 
                (revid,)).fetchone()
244
 
            if result is None:
245
 
                return False
246
 
        return True
247
 
 
248
 
    def _set_entry_revision(self, entry, revid, path, git_id):
 
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
        #
249
457
        # If a revision is in the cache, we assume it contains entries for the
250
458
        # whole inventory. So if all parent revisions are in the cache, but no
251
459
        # parent entry is present, then the entry revision is the current
252
 
        # revision. That amortizes the number of _get_file_revision calls for
253
 
        # large pulls to a "small number".
254
 
        entry_rev = self._get_entry_revision_from_db(
255
 
            revid, path, git_id, entry.executable)
256
 
        if entry_rev is not None:
257
 
            entry.revision = entry_rev
 
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
258
466
            return
259
 
 
260
467
        revision = self.get_revision(revid)
 
468
        all_parents_in_cache = True
261
469
        for parent_id in revision.parent_ids:
262
 
            entry_rev = self._get_entry_revision_from_db(
263
 
                parent_id, path, git_id, entry.executable)
 
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))
264
475
            if entry_rev is not None:
265
476
                break
266
477
        else:
267
 
            if self._all_inventories_in_db(revision.parent_ids):
 
478
            if all_parents_in_cache:
268
479
                entry_rev = revid
269
480
            else:
270
481
                entry_rev = self._get_file_revision(revid, path)
271
 
        self._set_entry_revision_in_db(
272
 
            revid, path, git_id, entry.executable, entry_rev)
273
 
        #self.cachedb.commit()
 
482
        self._entry_revision_cache.setdefault(
 
483
            revid, {})[(path, git_id, entry.executable)] = entry_rev
274
484
        entry.revision = entry_rev
275
485
 
 
486
    _set_entry_revision = _set_entry_revision_optimized5
 
487
    #get_inventory = _get_inventory_caching
 
488
 
276
489
 
277
490
def escape_file_id(file_id):
278
491
    return file_id.replace('_', '__').replace(' ', '_s')
279
492
 
280
 
 
281
493
class GitRevisionTree(revisiontree.RevisionTree):
282
494
 
283
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)
284
499
        self._repository = repository
285
 
        self.revision_id = revision_id
286
 
        git_id = ids.convert_revision_id_bzr_to_git(revision_id)
287
 
        self.tree = repository._git.commit(git_id).tree
288
 
        self._inventory = inventory.Inventory(revision_id=revision_id)
289
 
        self._inventory.root.revision = revision_id
290
 
        self._build_inventory(self.tree, self._inventory.root, "")
 
500
        self._revision_id = revision_id
291
501
 
292
502
    def get_file_lines(self, file_id):
293
503
        entry = self._inventory[file_id]
294
504
        if entry.kind == 'directory': return []
295
 
        git_id = self._inventory.git_ids[file_id]
296
 
        if git_id in self._inventory.git_file_data:
297
 
            return self._inventory.git_file_data[git_id]
298
 
        return self._repository._get_blob(git_id)
299
 
 
300
 
    def _build_inventory(self, tree, ie, path):
301
 
        assert isinstance(path, str)
302
 
        for b in tree.contents:
303
 
            basename = b.name.decode("utf-8")
304
 
            if path == "":
305
 
                child_path = b.name
306
 
            else:
307
 
                child_path = urlutils.join(path, b.name)
308
 
            file_id = escape_file_id(child_path.encode('utf-8'))
309
 
            if b.mode[0] == '0':
310
 
                child_ie = inventory.InventoryDirectory(file_id, basename, ie.file_id)
311
 
            elif b.mode[0] == '1':
312
 
                if b.mode[1] == '0':
313
 
                    child_ie = inventory.InventoryFile(file_id, basename, ie.file_id)
314
 
                    child_ie.text_sha1 = osutils.sha_string(b.data)
315
 
                elif b.mode[1] == '2':
316
 
                    child_ie = inventory.InventoryLink(file_id, basename, ie.file_id)
317
 
                    child_ie.text_sha1 = osutils.sha_string("")
318
 
                else:
319
 
                    raise AssertionError(
320
 
                        "Unknown file kind, perms=%r." % (b.mode,))
321
 
                child_ie.text_size = b.size
322
 
            else:
323
 
                raise AssertionError(
324
 
                    "Unknown blob kind, perms=%r." % (b.mode,))
325
 
            child_ie.executable = bool(int(b.mode[3:], 8) & 0111)
326
 
            child_ie.revision = self.revision_id
327
 
            assert not basename in ie.children
328
 
            ie.children[basename] = child_ie
329
 
            if b.mode[0] == '0':
330
 
                self._build_inventory(b, child_ie, child_path)
331
 
 
332
 
 
333
 
class GitFormat(object):
334
 
 
335
 
    supports_tree_reference = False
336
 
 
337
 
    def get_format_description(self):
338
 
        return "Git Repository"
 
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)