/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.358.2 by Jelmer Vernooij
Refresh copyright headers, add my email.
1
# Copyright (C) 2009-2018 Jelmer Vernooij <jelmer@jelmer.uk>
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
0.358.1 by Jelmer Vernooij
Fix FSF address.
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
16
17
"""Map from Git sha's to Bazaar objects."""
18
0.200.1594 by Jelmer Vernooij
Use absolute_import everywhere.
19
from __future__ import absolute_import
20
0.235.1 by Jelmer Vernooij
Store sha map more efficiently.
21
from dulwich.objects import (
22
    sha_to_hex,
23
    hex_to_sha,
24
    )
0.200.292 by Jelmer Vernooij
Fix formatting.
25
import os
0.200.365 by Jelmer Vernooij
Share sha map cache connections inside threads.
26
import threading
0.200.292 by Jelmer Vernooij
Fix formatting.
27
0.254.44 by Jelmer Vernooij
Add knit-based content cache for trees.
28
from dulwich.objects import (
29
    ShaFile,
30
    )
31
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
32
from .. import (
7336.2.1 by Martin
Split non-ini config methods to bedding
33
    bedding,
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
34
    errors as bzr_errors,
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
35
    osutils,
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
36
    registry,
0.200.528 by Jelmer Vernooij
Fix import.
37
    trace,
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
38
    )
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
39
from ..bzr import (
0.200.1648 by Jelmer Vernooij
Fix compatibility with newer versions of breezy.
40
    btree_index as _mod_btree_index,
41
    index as _mod_index,
0.254.31 by Jelmer Vernooij
Initial work on CHKMap support.
42
    versionedfile,
0.200.528 by Jelmer Vernooij
Fix import.
43
    )
6986.2.3 by Jelmer Vernooij
Merge trunk
44
from ..sixish import (
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
45
    viewitems,
46
    viewkeys,
47
    viewvalues,
48
    )
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
49
from ..transport import (
7336.2.1 by Martin
Split non-ini config methods to bedding
50
    get_transport_from_path,
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
51
    )
0.200.230 by Jelmer Vernooij
Implement sha cache.
52
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
53
0.200.534 by Jelmer Vernooij
Use XDG cache directory if the python xdg module is available.
54
def get_cache_dir():
7336.2.1 by Martin
Split non-ini config methods to bedding
55
    path = os.path.join(bedding.cache_dir(), "git")
56
    if not os.path.isdir(path):
57
        os.mkdir(path)
58
    return path
0.200.534 by Jelmer Vernooij
Use XDG cache directory if the python xdg module is available.
59
60
0.200.1221 by Jelmer Vernooij
Support cache for non-local transport properly.
61
def get_remote_cache_transport(repository):
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
62
    """Retrieve the transport to use when accessing (unwritable) remote
0.200.1027 by Jelmer Vernooij
mark remote git directories as not supporting working trees.
63
    repositories.
64
    """
0.200.1221 by Jelmer Vernooij
Support cache for non-local transport properly.
65
    uuid = getattr(repository, "uuid", None)
66
    if uuid is None:
67
        path = get_cache_dir()
68
    else:
69
        path = os.path.join(get_cache_dir(), uuid)
70
        if not os.path.isdir(path):
71
            os.mkdir(path)
7336.2.1 by Martin
Split non-ini config methods to bedding
72
    return get_transport_from_path(path)
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
73
74
0.200.228 by Jelmer Vernooij
Split out map.
75
def check_pysqlite_version(sqlite3):
76
    """Check that sqlite library is compatible.
77
78
    """
7143.15.2 by Jelmer Vernooij
Run autopep8.
79
    if (sqlite3.sqlite_version_info[0] < 3
80
            or (sqlite3.sqlite_version_info[0] == 3 and
81
                sqlite3.sqlite_version_info[1] < 3)):
0.200.586 by Jelmer Vernooij
Fix issues pointed out by pyflakes.
82
        trace.warning('Needs at least sqlite 3.3.x')
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
83
        raise bzr_errors.BzrError("incompatible sqlite library")
0.200.228 by Jelmer Vernooij
Split out map.
84
7143.15.2 by Jelmer Vernooij
Run autopep8.
85
0.200.228 by Jelmer Vernooij
Split out map.
86
try:
87
    try:
88
        import sqlite3
89
        check_pysqlite_version(sqlite3)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
90
    except (ImportError, bzr_errors.BzrError):
0.200.228 by Jelmer Vernooij
Split out map.
91
        from pysqlite2 import dbapi2 as sqlite3
92
        check_pysqlite_version(sqlite3)
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
93
except BaseException:
0.200.586 by Jelmer Vernooij
Fix issues pointed out by pyflakes.
94
    trace.warning('Needs at least Python2.5 or Python2.4 with the pysqlite2 '
7143.15.2 by Jelmer Vernooij
Run autopep8.
95
                  'module')
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
96
    raise bzr_errors.BzrError("missing sqlite library")
0.200.228 by Jelmer Vernooij
Split out map.
97
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
98
0.200.365 by Jelmer Vernooij
Share sha map cache connections inside threads.
99
_mapdbs = threading.local()
7143.15.2 by Jelmer Vernooij
Run autopep8.
100
101
0.200.365 by Jelmer Vernooij
Share sha map cache connections inside threads.
102
def mapdbs():
103
    """Get a cache for this thread's db connections."""
104
    try:
105
        return _mapdbs.cache
106
    except AttributeError:
107
        _mapdbs.cache = {}
108
        return _mapdbs.cache
109
110
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
111
class GitShaMap(object):
112
    """Git<->Bzr revision id mapping database."""
113
114
    def lookup_git_sha(self, sha):
115
        """Lookup a Git sha in the database.
116
        :param sha: Git object sha
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
117
        :return: list with (type, type_data) tuples with type_data:
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
118
            commit: revid, tree_sha, verifiers
119
            blob: fileid, revid
120
            tree: fileid, revid
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
121
        """
122
        raise NotImplementedError(self.lookup_git_sha)
123
0.200.835 by Jelmer Vernooij
Rename lookup_{tree,blob} -> lookup_{tree,blob}_id.
124
    def lookup_blob_id(self, file_id, revision):
0.200.753 by Jelmer Vernooij
Move lookup_tree/lookup_blob to a separate object.
125
        """Retrieve a Git blob SHA by file id.
126
127
        :param file_id: File id of the file/symlink
0.200.806 by Jelmer Vernooij
Make revision_hint mandatory.
128
        :param revision: revision in which the file was last changed.
0.200.753 by Jelmer Vernooij
Move lookup_tree/lookup_blob to a separate object.
129
        """
0.200.835 by Jelmer Vernooij
Rename lookup_{tree,blob} -> lookup_{tree,blob}_id.
130
        raise NotImplementedError(self.lookup_blob_id)
0.200.753 by Jelmer Vernooij
Move lookup_tree/lookup_blob to a separate object.
131
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
132
    def lookup_tree_id(self, file_id, revision):
0.200.753 by Jelmer Vernooij
Move lookup_tree/lookup_blob to a separate object.
133
        """Retrieve a Git tree SHA by file id.
134
        """
0.200.835 by Jelmer Vernooij
Rename lookup_{tree,blob} -> lookup_{tree,blob}_id.
135
        raise NotImplementedError(self.lookup_tree_id)
0.200.753 by Jelmer Vernooij
Move lookup_tree/lookup_blob to a separate object.
136
0.200.1039 by Jelmer Vernooij
Add stub.
137
    def lookup_commit(self, revid):
138
        """Retrieve a Git commit SHA by Bazaar revision id.
139
        """
140
        raise NotImplementedError(self.lookup_commit)
141
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
142
    def revids(self):
143
        """List the revision ids known."""
144
        raise NotImplementedError(self.revids)
145
0.200.677 by Jelmer Vernooij
Implement TdbCache.missing_revisions().
146
    def missing_revisions(self, revids):
147
        """Return set of all the revisions that are not present."""
148
        present_revids = set(self.revids())
149
        if not isinstance(revids, set):
150
            revids = set(revids)
151
        return revids - present_revids
152
0.200.586 by Jelmer Vernooij
Fix issues pointed out by pyflakes.
153
    def sha1s(self):
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
154
        """List the SHA1s."""
155
        raise NotImplementedError(self.sha1s)
156
0.200.687 by Jelmer Vernooij
Use start_write_group() / commit_write_group() mechanism when creating git SHA maps.
157
    def start_write_group(self):
158
        """Start writing changes."""
159
160
    def commit_write_group(self):
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
161
        """Commit any pending changes."""
162
0.200.687 by Jelmer Vernooij
Use start_write_group() / commit_write_group() mechanism when creating git SHA maps.
163
    def abort_write_group(self):
164
        """Abort any pending changes."""
165
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
166
0.254.44 by Jelmer Vernooij
Add knit-based content cache for trees.
167
class ContentCache(object):
168
    """Object that can cache Git objects."""
169
0.200.952 by Jelmer Vernooij
Write git pack files rather than loose objects.
170
    def add(self, object):
171
        """Add an object."""
172
        raise NotImplementedError(self.add)
173
174
    def add_multi(self, objects):
175
        """Add multiple objects."""
176
        for obj in objects:
177
            self.add(obj)
178
0.254.44 by Jelmer Vernooij
Add knit-based content cache for trees.
179
    def __getitem__(self, sha):
180
        """Retrieve an item, by SHA."""
181
        raise NotImplementedError(self.__getitem__)
182
183
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
184
class BzrGitCacheFormat(object):
0.254.51 by Jelmer Vernooij
Add some docstrings.
185
    """Bazaar-Git Cache Format."""
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
186
187
    def get_format_string(self):
0.200.866 by Jelmer Vernooij
More docstrings, prefer migrating git.db to migrating git.tdb.
188
        """Return a single-line unique format string for this cache format."""
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
189
        raise NotImplementedError(self.get_format_string)
190
191
    def open(self, transport):
0.200.866 by Jelmer Vernooij
More docstrings, prefer migrating git.db to migrating git.tdb.
192
        """Open this format on a transport."""
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
193
        raise NotImplementedError(self.open)
194
195
    def initialize(self, transport):
0.254.51 by Jelmer Vernooij
Add some docstrings.
196
        """Create a new instance of this cache format at transport."""
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
197
        transport.put_bytes('format', self.get_format_string())
198
199
    @classmethod
0.200.866 by Jelmer Vernooij
More docstrings, prefer migrating git.db to migrating git.tdb.
200
    def from_transport(self, transport):
201
        """Open a cache file present on a transport, or initialize one.
202
203
        :param transport: Transport to use
204
        :return: A BzrGitCache instance
205
        """
206
        try:
207
            format_name = transport.get_bytes('format')
208
            format = formats.get(format_name)
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
209
        except bzr_errors.NoSuchFile:
0.200.866 by Jelmer Vernooij
More docstrings, prefer migrating git.db to migrating git.tdb.
210
            format = formats.get('default')
211
            format.initialize(transport)
212
        return format.open(transport)
213
214
    @classmethod
215
    def from_repository(cls, repository):
216
        """Open a cache file for a repository.
217
218
        This will use the repository's transport to store the cache file, or
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
219
        use the users global cache directory if the repository has no
0.200.866 by Jelmer Vernooij
More docstrings, prefer migrating git.db to migrating git.tdb.
220
        transport associated with it.
221
222
        :param repository: Repository to open the cache for
223
        :return: A `BzrGitCache`
224
        """
6986.2.1 by Jelmer Vernooij
Move breezy.plugins.git to breezy.git.
225
        from ..transport.local import LocalTransport
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
226
        repo_transport = getattr(repository, "_transport", None)
7143.15.2 by Jelmer Vernooij
Run autopep8.
227
        if (repo_transport is not None
228
                and isinstance(repo_transport, LocalTransport)):
0.200.1221 by Jelmer Vernooij
Support cache for non-local transport properly.
229
            # Even if we don't write to this repo, we should be able
0.200.865 by Jelmer Vernooij
Support serving without --allow-writes.
230
            # to update its cache.
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
231
            try:
7143.15.2 by Jelmer Vernooij
Run autopep8.
232
                repo_transport = remove_readonly_transport_decorator(
233
                    repo_transport)
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
234
            except bzr_errors.ReadOnlyError:
0.200.1438 by Jelmer Vernooij
Cope with remote branches not being readonly at all better.
235
                transport = None
236
            else:
237
                try:
238
                    repo_transport.mkdir('git')
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
239
                except bzr_errors.FileExists:
0.200.1438 by Jelmer Vernooij
Cope with remote branches not being readonly at all better.
240
                    pass
241
                transport = repo_transport.clone('git')
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
242
        else:
0.200.1438 by Jelmer Vernooij
Cope with remote branches not being readonly at all better.
243
            transport = None
244
        if transport is None:
0.200.1221 by Jelmer Vernooij
Support cache for non-local transport properly.
245
            transport = get_remote_cache_transport(repository)
0.200.866 by Jelmer Vernooij
More docstrings, prefer migrating git.db to migrating git.tdb.
246
        return cls.from_transport(transport)
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
247
248
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
249
class CacheUpdater(object):
0.254.51 by Jelmer Vernooij
Add some docstrings.
250
    """Base class for objects that can update a bzr-git cache."""
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
251
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
252
    def add_object(self, obj, bzr_key_data, path):
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
253
        """Add an object.
254
255
        :param obj: Object type ("commit", "blob" or "tree")
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
256
        :param bzr_key_data: bzr key store data or testament_sha in case
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
257
            of commit
258
        :param path: Path of the object (optional)
259
        """
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
260
        raise NotImplementedError(self.add_object)
261
262
    def finish(self):
263
        raise NotImplementedError(self.finish)
264
265
266
class BzrGitCache(object):
267
    """Caching backend."""
268
0.422.1 by Jelmer Vernooij
Remove content caching, fix index.
269
    def __init__(self, idmap, cache_updater_klass):
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
270
        self.idmap = idmap
271
        self._cache_updater_klass = cache_updater_klass
272
273
    def get_updater(self, rev):
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
274
        """Update an object that implements the CacheUpdater interface for
0.254.51 by Jelmer Vernooij
Add some docstrings.
275
        updating this cache.
276
        """
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
277
        return self._cache_updater_klass(self, rev)
278
279
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
280
def DictBzrGitCache():
281
    return BzrGitCache(DictGitShaMap(), DictCacheUpdater)
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
282
283
284
class DictCacheUpdater(CacheUpdater):
0.254.51 by Jelmer Vernooij
Add some docstrings.
285
    """Cache updater for dict-based caches."""
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
286
287
    def __init__(self, cache, rev):
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
288
        self.cache = cache
289
        self.revid = rev.revision_id
290
        self.parent_revids = rev.parent_ids
291
        self._commit = None
292
        self._entries = []
293
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
294
    def add_object(self, obj, bzr_key_data, path):
0.423.1 by Jelmer Vernooij
Some performance fixes.
295
        if isinstance(obj, tuple):
296
            (type_name, hexsha) = obj
297
        else:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
298
            type_name = obj.type_name.decode('ascii')
0.423.1 by Jelmer Vernooij
Some performance fixes.
299
            hexsha = obj.id
7018.3.1 by Jelmer Vernooij
Fix git cache handling.
300
        if not isinstance(hexsha, bytes):
301
            raise TypeError(hexsha)
0.423.1 by Jelmer Vernooij
Some performance fixes.
302
        if type_name == "commit":
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
303
            self._commit = obj
0.361.1 by Jelmer Vernooij
Don't use assert.
304
            if type(bzr_key_data) is not dict:
305
                raise TypeError(bzr_key_data)
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
306
            key = self.revid
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
307
            type_data = (self.revid, self._commit.tree, bzr_key_data)
0.423.1 by Jelmer Vernooij
Some performance fixes.
308
            self.cache.idmap._by_revid[self.revid] = hexsha
309
        elif type_name in ("blob", "tree"):
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
310
            if bzr_key_data is not None:
0.421.6 by Jelmer Vernooij
Some more simplifications.
311
                key = type_data = bzr_key_data
7143.15.2 by Jelmer Vernooij
Run autopep8.
312
                self.cache.idmap._by_fileid.setdefault(type_data[1], {})[
313
                    type_data[0]] = hexsha
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
314
        else:
315
            raise AssertionError
0.423.1 by Jelmer Vernooij
Some performance fixes.
316
        entry = (type_name, type_data)
317
        self.cache.idmap._by_sha.setdefault(hexsha, {})[key] = entry
0.200.847 by Jelmer Vernooij
Add BzrGitCache object.
318
319
    def finish(self):
320
        if self._commit is None:
321
            raise AssertionError("No commit object added")
322
        return self._commit
323
324
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
325
class DictGitShaMap(GitShaMap):
0.254.51 by Jelmer Vernooij
Add some docstrings.
326
    """Git SHA map that uses a dictionary."""
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
327
328
    def __init__(self):
0.200.753 by Jelmer Vernooij
Move lookup_tree/lookup_blob to a separate object.
329
        self._by_sha = {}
330
        self._by_fileid = {}
0.200.853 by Jelmer Vernooij
Fix lookup of commits in tdb.
331
        self._by_revid = {}
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
332
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
333
    def lookup_blob_id(self, fileid, revision):
334
        return self._by_fileid[revision][fileid]
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
335
336
    def lookup_git_sha(self, sha):
7018.3.1 by Jelmer Vernooij
Fix git cache handling.
337
        if not isinstance(sha, bytes):
338
            raise TypeError(sha)
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
339
        for entry in viewvalues(self._by_sha[sha]):
0.261.2 by Jelmer Vernooij
Fix cache tests.
340
            yield entry
0.230.2 by Jelmer Vernooij
Fix versionedfiles.
341
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
342
    def lookup_tree_id(self, fileid, revision):
0.200.860 by Jelmer Vernooij
Fix bugs in two lookup_tree_id implementations and add a test for it.
343
        return self._by_fileid[revision][fileid]
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
344
0.200.853 by Jelmer Vernooij
Fix lookup of commits in tdb.
345
    def lookup_commit(self, revid):
346
        return self._by_revid[revid]
347
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
348
    def revids(self):
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
349
        for key, entries in viewitems(self._by_sha):
7018.3.1 by Jelmer Vernooij
Fix git cache handling.
350
            for (type, type_data) in viewvalues(entries):
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
351
                if type == "commit":
352
                    yield type_data[0]
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
353
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
354
    def sha1s(self):
6973.13.6 by Jelmer Vernooij
drop tests affected by new HPSS call.
355
        return viewkeys(self._by_sha)
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
356
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
357
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
358
class SqliteCacheUpdater(CacheUpdater):
359
360
    def __init__(self, cache, rev):
361
        self.cache = cache
0.200.850 by Jelmer Vernooij
Fix tests.
362
        self.db = self.cache.idmap.db
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
363
        self.revid = rev.revision_id
364
        self._commit = None
365
        self._trees = []
366
        self._blobs = []
367
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
368
    def add_object(self, obj, bzr_key_data, path):
0.423.1 by Jelmer Vernooij
Some performance fixes.
369
        if isinstance(obj, tuple):
370
            (type_name, hexsha) = obj
371
        else:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
372
            type_name = obj.type_name.decode('ascii')
0.423.1 by Jelmer Vernooij
Some performance fixes.
373
            hexsha = obj.id
7018.3.1 by Jelmer Vernooij
Fix git cache handling.
374
        if not isinstance(hexsha, bytes):
375
            raise TypeError(hexsha)
0.423.1 by Jelmer Vernooij
Some performance fixes.
376
        if type_name == "commit":
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
377
            self._commit = obj
0.361.1 by Jelmer Vernooij
Don't use assert.
378
            if type(bzr_key_data) is not dict:
379
                raise TypeError(bzr_key_data)
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
380
            self._testament3_sha1 = bzr_key_data.get("testament3-sha1")
0.423.1 by Jelmer Vernooij
Some performance fixes.
381
        elif type_name == "tree":
382
            if bzr_key_data is not None:
383
                self._trees.append((hexsha, bzr_key_data[0], bzr_key_data[1]))
384
        elif type_name == "blob":
385
            if bzr_key_data is not None:
386
                self._blobs.append((hexsha, bzr_key_data[0], bzr_key_data[1]))
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
387
        else:
388
            raise AssertionError
389
390
    def finish(self):
391
        if self._commit is None:
392
            raise AssertionError("No commit object added")
0.200.850 by Jelmer Vernooij
Fix tests.
393
        self.db.executemany(
394
            "replace into trees (sha1, fileid, revid) values (?, ?, ?)",
395
            self._trees)
396
        self.db.executemany(
397
            "replace into blobs (sha1, fileid, revid) values (?, ?, ?)",
398
            self._blobs)
399
        self.db.execute(
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
400
            "replace into commits (sha1, revid, tree_sha, testament3_sha1) "
401
            "values (?, ?, ?, ?)",
402
            (self._commit.id, self.revid, self._commit.tree,
403
                self._testament3_sha1))
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
404
        return self._commit
405
406
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
407
def SqliteBzrGitCache(p):
408
    return BzrGitCache(SqliteGitShaMap(p), SqliteCacheUpdater)
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
409
410
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
411
class SqliteGitCacheFormat(BzrGitCacheFormat):
412
413
    def get_format_string(self):
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
414
        return b'bzr-git sha map version 1 using sqlite\n'
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
415
416
    def open(self, transport):
417
        try:
418
            basepath = transport.local_abspath(".")
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
419
        except bzr_errors.NotLocalUrl:
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
420
            basepath = get_cache_dir()
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
421
        return SqliteBzrGitCache(os.path.join(basepath, "idmap.db"))
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
422
423
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
424
class SqliteGitShaMap(GitShaMap):
0.254.51 by Jelmer Vernooij
Add some docstrings.
425
    """Bazaar GIT Sha map that uses a sqlite database for storage."""
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
426
0.200.365 by Jelmer Vernooij
Share sha map cache connections inside threads.
427
    def __init__(self, path=None):
428
        self.path = path
429
        if path is None:
0.200.262 by Jelmer Vernooij
Add tests for GitShaMap.
430
            self.db = sqlite3.connect(":memory:")
431
        else:
6973.5.10 by Jelmer Vernooij
Random bunch of python3 bee-improvements.
432
            if path not in mapdbs():
0.200.365 by Jelmer Vernooij
Share sha map cache connections inside threads.
433
                mapdbs()[path] = sqlite3.connect(path)
0.200.675 by Jelmer Vernooij
Fix formatting.
434
            self.db = mapdbs()[path]
0.200.688 by Jelmer Vernooij
Use str text factory rather than encoding/decoding each time.
435
        self.db.text_factory = str
0.200.230 by Jelmer Vernooij
Implement sha cache.
436
        self.db.executescript("""
0.200.691 by Jelmer Vernooij
Add extra constraints in sqlite tables.
437
        create table if not exists commits(
438
            sha1 text not null check(length(sha1) == 40),
439
            revid text not null,
440
            tree_sha text not null check(length(tree_sha) == 40)
441
        );
0.200.230 by Jelmer Vernooij
Implement sha cache.
442
        create index if not exists commit_sha1 on commits(sha1);
0.200.284 by Jelmer Vernooij
Add extra indexes.
443
        create unique index if not exists commit_revid on commits(revid);
0.200.691 by Jelmer Vernooij
Add extra constraints in sqlite tables.
444
        create table if not exists blobs(
445
            sha1 text not null check(length(sha1) == 40),
446
            fileid text not null,
447
            revid text not null
448
        );
0.200.230 by Jelmer Vernooij
Implement sha cache.
449
        create index if not exists blobs_sha1 on blobs(sha1);
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
450
        create unique index if not exists blobs_fileid_revid on blobs(
451
            fileid, revid);
0.200.691 by Jelmer Vernooij
Add extra constraints in sqlite tables.
452
        create table if not exists trees(
0.255.1 by Jelmer Vernooij
Remove use of lookup_tree.
453
            sha1 text unique not null check(length(sha1) == 40),
0.200.691 by Jelmer Vernooij
Add extra constraints in sqlite tables.
454
            fileid text not null,
455
            revid text not null
456
        );
0.255.1 by Jelmer Vernooij
Remove use of lookup_tree.
457
        create unique index if not exists trees_sha1 on trees(sha1);
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
458
        create unique index if not exists trees_fileid_revid on trees(
459
            fileid, revid);
0.200.230 by Jelmer Vernooij
Implement sha cache.
460
""")
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
461
        try:
462
            self.db.executescript(
463
                "ALTER TABLE commits ADD testament3_sha1 TEXT;")
464
        except sqlite3.OperationalError:
7143.15.2 by Jelmer Vernooij
Run autopep8.
465
            pass  # Column already exists.
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
466
0.254.19 by Jelmer Vernooij
Support upgrading sha maps.
467
    def __repr__(self):
468
        return "%s(%r)" % (self.__class__.__name__, self.path)
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
469
0.200.487 by Jelmer Vernooij
Prevent deep recursion if the shamap is out of date.
470
    def lookup_commit(self, revid):
7143.15.2 by Jelmer Vernooij
Run autopep8.
471
        cursor = self.db.execute("select sha1 from commits where revid = ?",
472
                                 (revid,))
0.254.51 by Jelmer Vernooij
Add some docstrings.
473
        row = cursor.fetchone()
0.200.364 by Jelmer Vernooij
Reimplement dpush, but more efficient and only writing a single pack file rather than one per revision.
474
        if row is not None:
0.200.688 by Jelmer Vernooij
Use str text factory rather than encoding/decoding each time.
475
            return row[0]
0.200.364 by Jelmer Vernooij
Reimplement dpush, but more efficient and only writing a single pack file rather than one per revision.
476
        raise KeyError
0.200.231 by Jelmer Vernooij
Partially fix pull.
477
0.200.687 by Jelmer Vernooij
Use start_write_group() / commit_write_group() mechanism when creating git SHA maps.
478
    def commit_write_group(self):
0.200.232 by Jelmer Vernooij
Fix pull from remote branches.
479
        self.db.commit()
480
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
481
    def lookup_blob_id(self, fileid, revision):
7143.15.2 by Jelmer Vernooij
Run autopep8.
482
        row = self.db.execute(
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
483
            "select sha1 from blobs where fileid = ? and revid = ?",
484
            (fileid, revision)).fetchone()
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
485
        if row is not None:
486
            return row[0]
487
        raise KeyError(fileid)
488
489
    def lookup_tree_id(self, fileid, revision):
7143.15.2 by Jelmer Vernooij
Run autopep8.
490
        row = self.db.execute(
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
491
            "select sha1 from trees where fileid = ? and revid = ?",
492
            (fileid, revision)).fetchone()
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
493
        if row is not None:
494
            return row[0]
495
        raise KeyError(fileid)
0.230.2 by Jelmer Vernooij
Fix versionedfiles.
496
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
497
    def lookup_git_sha(self, sha):
498
        """Lookup a Git sha in the database.
499
500
        :param sha: Git object sha
501
        :return: (type, type_data) with type_data:
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
502
            commit: revid, tree sha, verifiers
503
            tree: fileid, revid
504
            blob: fileid, revid
0.200.226 by Jelmer Vernooij
Merge thin-pack work.
505
        """
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
506
        found = False
7143.15.2 by Jelmer Vernooij
Run autopep8.
507
        cursor = self.db.execute(
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
508
            "select revid, tree_sha, testament3_sha1 from commits where "
509
            "sha1 = ?", (sha,))
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
510
        for row in cursor.fetchall():
511
            found = True
0.200.1179 by Jelmer Vernooij
Avoid using verifiers for natively imported revisions, save a lot of time.
512
            if row[2] is not None:
513
                verifiers = {"testament3-sha1": row[2]}
514
            else:
515
                verifiers = {}
516
            yield ("commit", (row[0], row[1], verifiers))
7143.15.2 by Jelmer Vernooij
Run autopep8.
517
        cursor = self.db.execute(
518
            "select fileid, revid from blobs where sha1 = ?", (sha,))
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
519
        for row in cursor.fetchall():
520
            found = True
521
            yield ("blob", row)
7143.15.2 by Jelmer Vernooij
Run autopep8.
522
        cursor = self.db.execute(
523
            "select fileid, revid from trees where sha1 = ?", (sha,))
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
524
        for row in cursor.fetchall():
525
            found = True
526
            yield ("tree", row)
527
        if not found:
528
            raise KeyError(sha)
0.200.230 by Jelmer Vernooij
Implement sha cache.
529
530
    def revids(self):
0.200.260 by Jelmer Vernooij
Add DictGitShaMap, useful for testing.
531
        """List the revision ids known."""
0.248.7 by Jelmer Vernooij
Avoid fetching all sha1s at once.
532
        return (row for (row,) in self.db.execute("select revid from commits"))
0.200.422 by Jelmer Vernooij
'bzr git-object' without arguments now prints the available git objects.
533
534
    def sha1s(self):
535
        """List the SHA1s."""
536
        for table in ("blobs", "commits", "trees"):
0.254.26 by Jelmer Vernooij
Fix typo, cope with invalid shamaps a bit better.
537
            for (sha,) in self.db.execute("select sha1 from %s" % table):
7018.3.1 by Jelmer Vernooij
Fix git cache handling.
538
                yield sha.encode('ascii')
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
539
540
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
541
class TdbCacheUpdater(CacheUpdater):
0.254.51 by Jelmer Vernooij
Add some docstrings.
542
    """Cache updater for tdb-based caches."""
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
543
544
    def __init__(self, cache, rev):
545
        self.cache = cache
546
        self.db = cache.idmap.db
547
        self.revid = rev.revision_id
548
        self.parent_revids = rev.parent_ids
549
        self._commit = None
550
        self._entries = []
551
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
552
    def add_object(self, obj, bzr_key_data, path):
0.423.1 by Jelmer Vernooij
Some performance fixes.
553
        if isinstance(obj, tuple):
554
            (type_name, hexsha) = obj
555
            sha = hex_to_sha(hexsha)
556
        else:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
557
            type_name = obj.type_name.decode('ascii')
0.423.1 by Jelmer Vernooij
Some performance fixes.
558
            sha = obj.sha().digest()
559
        if type_name == "commit":
6973.14.6 by Jelmer Vernooij
Fix some more tests.
560
            self.db[b"commit\0" + self.revid] = b"\0".join((sha, obj.tree))
0.361.1 by Jelmer Vernooij
Don't use assert.
561
            if type(bzr_key_data) is not dict:
562
                raise TypeError(bzr_key_data)
0.200.1179 by Jelmer Vernooij
Avoid using verifiers for natively imported revisions, save a lot of time.
563
            type_data = (self.revid, obj.tree)
564
            try:
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
565
                type_data += (bzr_key_data["testament3-sha1"],)
0.200.1179 by Jelmer Vernooij
Avoid using verifiers for natively imported revisions, save a lot of time.
566
            except KeyError:
567
                pass
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
568
            self._commit = obj
0.423.1 by Jelmer Vernooij
Some performance fixes.
569
        elif type_name == "blob":
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
570
            if bzr_key_data is None:
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
571
                return
7143.15.2 by Jelmer Vernooij
Run autopep8.
572
            self.db[b"\0".join(
573
                (b"blob", bzr_key_data[0], bzr_key_data[1]))] = sha
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
574
            type_data = bzr_key_data
0.423.1 by Jelmer Vernooij
Some performance fixes.
575
        elif type_name == "tree":
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
576
            if bzr_key_data is None:
0.252.23 by Jelmer Vernooij
More work on roundtripping support.
577
                return
0.421.6 by Jelmer Vernooij
Some more simplifications.
578
            type_data = bzr_key_data
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
579
        else:
580
            raise AssertionError
6973.14.6 by Jelmer Vernooij
Fix some more tests.
581
        entry = b"\0".join((type_name.encode('ascii'), ) + type_data) + b"\n"
582
        key = b"git\0" + sha
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
583
        try:
584
            oldval = self.db[key]
585
        except KeyError:
586
            self.db[key] = entry
587
        else:
6973.11.12 by Jelmer Vernooij
Fix tdb cache tests when tdb is installed.
588
            if not oldval.endswith(b'\n'):
6973.14.6 by Jelmer Vernooij
Fix some more tests.
589
                self.db[key] = b"".join([oldval, b"\n", entry])
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
590
            else:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
591
                self.db[key] = b"".join([oldval, entry])
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
592
593
    def finish(self):
594
        if self._commit is None:
595
            raise AssertionError("No commit object added")
596
        return self._commit
597
598
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
599
def TdbBzrGitCache(p):
600
    return BzrGitCache(TdbGitShaMap(p), TdbCacheUpdater)
0.200.479 by Jelmer Vernooij
Version tdb sha map.
601
0.200.1140 by Jelmer Vernooij
Update now that the control dir formats are no longer in __init__.
602
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
603
class TdbGitCacheFormat(BzrGitCacheFormat):
0.254.51 by Jelmer Vernooij
Add some docstrings.
604
    """Cache format for tdb-based caches."""
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
605
606
    def get_format_string(self):
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
607
        return b'bzr-git sha map version 3 using tdb\n'
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
608
609
    def open(self, transport):
610
        try:
7290.11.2 by Jelmer Vernooij
Fix cache handling.
611
            basepath = transport.local_abspath(".")
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
612
        except bzr_errors.NotLocalUrl:
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
613
            basepath = get_cache_dir()
614
        try:
0.200.850 by Jelmer Vernooij
Fix tests.
615
            return TdbBzrGitCache(os.path.join(basepath, "idmap.tdb"))
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
616
        except ImportError:
617
            raise ImportError(
618
                "Unable to open existing bzr-git cache because 'tdb' is not "
619
                "installed.")
620
621
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
622
class TdbGitShaMap(GitShaMap):
623
    """SHA Map that uses a TDB database.
624
625
    Entries:
626
0.200.476 by Jelmer Vernooij
Fix Tdb backend, use tdb if possible by default.
627
    "git <sha1>" -> "<type> <type-data1> <type-data2>"
628
    "commit revid" -> "<sha1> <tree-id>"
0.200.477 by Jelmer Vernooij
More tests for sha maps, fix cache misses in tdb.
629
    "tree fileid revid" -> "<sha1>"
630
    "blob fileid revid" -> "<sha1>"
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
631
    """
632
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
633
    TDB_MAP_VERSION = 3
634
    TDB_HASH_SIZE = 50000
635
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
636
    def __init__(self, path=None):
637
        import tdb
638
        self.path = path
639
        if path is None:
640
            self.db = {}
641
        else:
6973.5.10 by Jelmer Vernooij
Random bunch of python3 bee-improvements.
642
            if path not in mapdbs():
0.200.849 by Jelmer Vernooij
Allow cache backends to decide when to add entries rather than adding once per commit.
643
                mapdbs()[path] = tdb.Tdb(path, self.TDB_HASH_SIZE, tdb.DEFAULT,
7143.15.2 by Jelmer Vernooij
Run autopep8.
644
                                         os.O_RDWR | os.O_CREAT)
0.200.676 by Jelmer Vernooij
Avoid iterating over all keys in the tdb database.
645
            self.db = mapdbs()[path]
646
        try:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
647
            if int(self.db[b"version"]) not in (2, 3):
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
648
                trace.warning(
649
                    "SHA Map is incompatible (%s -> %d), rebuilding database.",
650
                    self.db[b"version"], self.TDB_MAP_VERSION)
0.235.1 by Jelmer Vernooij
Store sha map more efficiently.
651
                self.db.clear()
0.200.676 by Jelmer Vernooij
Avoid iterating over all keys in the tdb database.
652
        except KeyError:
0.200.751 by Jelmer Vernooij
Unrelated small fixes - import, avoid storing tree info (no longer used).
653
            pass
6973.14.6 by Jelmer Vernooij
Fix some more tests.
654
        self.db[b"version"] = b'%d' % self.TDB_MAP_VERSION
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
655
0.200.809 by Jelmer Vernooij
Use tdb transactions for write groups.
656
    def start_write_group(self):
657
        """Start writing changes."""
0.200.778 by Jelmer Vernooij
Use transactions in tdb.
658
        self.db.transaction_start()
0.200.809 by Jelmer Vernooij
Use tdb transactions for write groups.
659
660
    def commit_write_group(self):
661
        """Commit any pending changes."""
662
        self.db.transaction_commit()
663
664
    def abort_write_group(self):
665
        """Abort any pending changes."""
666
        self.db.transaction_cancel()
0.200.778 by Jelmer Vernooij
Use transactions in tdb.
667
0.200.750 by Jelmer Vernooij
Remove unused tree code, add mechanism for migrating between sha maps.
668
    def __repr__(self):
669
        return "%s(%r)" % (self.__class__.__name__, self.path)
670
0.200.487 by Jelmer Vernooij
Prevent deep recursion if the shamap is out of date.
671
    def lookup_commit(self, revid):
0.200.1264 by Jelmer Vernooij
Fix updating cache for single revision - don't consider it an update of the full cache.
672
        try:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
673
            return sha_to_hex(self.db[b"commit\0" + revid][:20])
0.200.1264 by Jelmer Vernooij
Fix updating cache for single revision - don't consider it an update of the full cache.
674
        except KeyError:
675
            raise KeyError("No cache entry for %r" % revid)
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
676
0.200.841 by Jelmer Vernooij
Eliminate InventorySHAMap.
677
    def lookup_blob_id(self, fileid, revision):
6973.14.6 by Jelmer Vernooij
Fix some more tests.
678
        return sha_to_hex(self.db[b"\0".join((b"blob", fileid, revision))])
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
679
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
680
    def lookup_git_sha(self, sha):
681
        """Lookup a Git sha in the database.
682
683
        :param sha: Git object sha
684
        :return: (type, type_data) with type_data:
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
685
            commit: revid, tree sha
686
            blob: fileid, revid
687
            tree: fileid, revid
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
688
        """
0.200.564 by Jelmer Vernooij
Accept 'binary' shas.
689
        if len(sha) == 40:
690
            sha = hex_to_sha(sha)
6973.14.6 by Jelmer Vernooij
Fix some more tests.
691
        value = self.db[b"git\0" + sha]
0.261.2 by Jelmer Vernooij
Fix cache tests.
692
        for data in value.splitlines():
6973.14.6 by Jelmer Vernooij
Fix some more tests.
693
            data = data.split(b"\0")
694
            type_name = data[0].decode('ascii')
695
            if type_name == "commit":
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
696
                if len(data) == 3:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
697
                    yield (type_name, (data[1], data[2], {}))
0.261.1 by Jelmer Vernooij
Initial work on supporting multiple results for git shas.
698
                else:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
699
                    yield (type_name, (data[1], data[2],
7143.15.5 by Jelmer Vernooij
More PEP8 fixes.
700
                                       {"testament3-sha1": data[3]}))
6973.14.8 by Jelmer Vernooij
Fix tests.
701
            elif type_name in ("tree", "blob"):
702
                yield (type_name, tuple(data[1:]))
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
703
            else:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
704
                raise AssertionError("unknown type %r" % type_name)
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
705
0.200.677 by Jelmer Vernooij
Implement TdbCache.missing_revisions().
706
    def missing_revisions(self, revids):
707
        ret = set()
708
        for revid in revids:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
709
            if self.db.get(b"commit\0" + revid) is None:
0.200.677 by Jelmer Vernooij
Implement TdbCache.missing_revisions().
710
                ret.add(revid)
711
        return ret
712
6973.14.10 by Jelmer Vernooij
Merge python3-l.
713
    def _keys(self):
714
        try:
7018.3.2 by Jelmer Vernooij
Fix some git tests.
715
            return self.db.keys()
716
        except AttributeError:  # python < 3
6973.14.10 by Jelmer Vernooij
Merge python3-l.
717
            return self.db.iterkeys()
718
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
719
    def revids(self):
720
        """List the revision ids known."""
6973.14.10 by Jelmer Vernooij
Merge python3-l.
721
        for key in self._keys():
6973.14.6 by Jelmer Vernooij
Fix some more tests.
722
            if key.startswith(b"commit\0"):
0.235.1 by Jelmer Vernooij
Store sha map more efficiently.
723
                yield key[7:]
0.200.475 by Jelmer Vernooij
Add Tdb database backend.
724
725
    def sha1s(self):
726
        """List the SHA1s."""
6973.14.10 by Jelmer Vernooij
Merge python3-l.
727
        for key in self._keys():
6973.14.6 by Jelmer Vernooij
Fix some more tests.
728
            if key.startswith(b"git\0"):
0.235.1 by Jelmer Vernooij
Store sha map more efficiently.
729
                yield sha_to_hex(key[4:])
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
730
0.200.750 by Jelmer Vernooij
Remove unused tree code, add mechanism for migrating between sha maps.
731
0.254.44 by Jelmer Vernooij
Add knit-based content cache for trees.
732
class VersionedFilesContentCache(ContentCache):
733
734
    def __init__(self, vf):
735
        self._vf = vf
736
737
    def add(self, obj):
738
        self._vf.insert_record_stream(
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
739
            [versionedfile.ChunkedContentFactory(
740
                (obj.id,), [], None, obj.as_legacy_object_chunks())])
0.254.44 by Jelmer Vernooij
Add knit-based content cache for trees.
741
742
    def __getitem__(self, sha):
743
        stream = self._vf.get_record_stream([(sha,)], 'unordered', True)
6973.10.5 by Jelmer Vernooij
Fix use of .next.
744
        entry = next(stream)
0.254.44 by Jelmer Vernooij
Add knit-based content cache for trees.
745
        if entry.storage_kind == 'absent':
746
            raise KeyError(sha)
747
        return ShaFile._parse_legacy_object(entry.get_bytes_as('fulltext'))
748
749
0.254.46 by Jelmer Vernooij
Merge trunk.
750
class IndexCacheUpdater(CacheUpdater):
751
752
    def __init__(self, cache, rev):
753
        self.cache = cache
754
        self.revid = rev.revision_id
755
        self.parent_revids = rev.parent_ids
756
        self._commit = None
757
        self._entries = []
758
0.275.2 by Jelmer Vernooij
Pass tuples around for cache entries, rather than inventory entries.
759
    def add_object(self, obj, bzr_key_data, path):
0.423.1 by Jelmer Vernooij
Some performance fixes.
760
        if isinstance(obj, tuple):
761
            (type_name, hexsha) = obj
762
        else:
6973.14.6 by Jelmer Vernooij
Fix some more tests.
763
            type_name = obj.type_name.decode('ascii')
0.423.1 by Jelmer Vernooij
Some performance fixes.
764
            hexsha = obj.id
765
        if type_name == "commit":
0.254.46 by Jelmer Vernooij
Merge trunk.
766
            self._commit = obj
0.361.1 by Jelmer Vernooij
Don't use assert.
767
            if type(bzr_key_data) is not dict:
768
                raise TypeError(bzr_key_data)
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
769
            self.cache.idmap._add_git_sha(hexsha, b"commit",
7143.15.2 by Jelmer Vernooij
Run autopep8.
770
                                          (self.revid, obj.tree, bzr_key_data))
6973.14.6 by Jelmer Vernooij
Fix some more tests.
771
            self.cache.idmap._add_node((b"commit", self.revid, b"X"),
7143.15.2 by Jelmer Vernooij
Run autopep8.
772
                                       b" ".join((hexsha, obj.tree)))
0.423.1 by Jelmer Vernooij
Some performance fixes.
773
        elif type_name == "blob":
6973.14.6 by Jelmer Vernooij
Fix some more tests.
774
            self.cache.idmap._add_git_sha(hexsha, b"blob", bzr_key_data)
775
            self.cache.idmap._add_node((b"blob", bzr_key_data[0],
7143.15.2 by Jelmer Vernooij
Run autopep8.
776
                                        bzr_key_data[1]), hexsha)
0.423.1 by Jelmer Vernooij
Some performance fixes.
777
        elif type_name == "tree":
6973.14.6 by Jelmer Vernooij
Fix some more tests.
778
            self.cache.idmap._add_git_sha(hexsha, b"tree", bzr_key_data)
0.254.46 by Jelmer Vernooij
Merge trunk.
779
        else:
780
            raise AssertionError
781
782
    def finish(self):
783
        return self._commit
784
785
786
class IndexBzrGitCache(BzrGitCache):
787
788
    def __init__(self, transport=None):
0.254.52 by Jelmer Vernooij
Merge trunk, use git objects to cache tree objects.
789
        shamap = IndexGitShaMap(transport.clone('index'))
0.422.1 by Jelmer Vernooij
Remove content caching, fix index.
790
        super(IndexBzrGitCache, self).__init__(shamap, IndexCacheUpdater)
0.254.46 by Jelmer Vernooij
Merge trunk.
791
792
0.254.43 by Jelmer Vernooij
Merge trunk.
793
class IndexGitCacheFormat(BzrGitCacheFormat):
794
795
    def get_format_string(self):
6964.2.1 by Jelmer Vernooij
Initial work to support brz-git on python3.
796
        return b'bzr-git sha map with git object cache version 1\n'
0.254.43 by Jelmer Vernooij
Merge trunk.
797
798
    def initialize(self, transport):
799
        super(IndexGitCacheFormat, self).initialize(transport)
800
        transport.mkdir('index')
0.254.52 by Jelmer Vernooij
Merge trunk, use git objects to cache tree objects.
801
        transport.mkdir('objects')
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
802
        from .transportgit import TransportObjectStore
0.254.52 by Jelmer Vernooij
Merge trunk, use git objects to cache tree objects.
803
        TransportObjectStore.init(transport.clone('objects'))
0.254.43 by Jelmer Vernooij
Merge trunk.
804
805
    def open(self, transport):
0.254.46 by Jelmer Vernooij
Merge trunk.
806
        return IndexBzrGitCache(transport)
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
807
808
809
class IndexGitShaMap(GitShaMap):
0.254.31 by Jelmer Vernooij
Initial work on CHKMap support.
810
    """SHA Map that uses the Bazaar APIs to store a cache.
811
812
    BTree Index file with the following contents:
813
0.422.1 by Jelmer Vernooij
Remove content caching, fix index.
814
    ("git", <sha1>, "X") -> "<type> <type-data1> <type-data2>"
815
    ("commit", <revid>, "X") -> "<sha1> <tree-id>"
0.254.36 by Jelmer Vernooij
Merge trunk.
816
    ("blob", <fileid>, <revid>) -> <sha1>
817
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
818
    """
819
820
    def __init__(self, transport=None):
6962.1.1 by Jelmer Vernooij
Fix handling cache updates in bzr-based index formats.
821
        self._name = None
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
822
        if transport is None:
0.254.43 by Jelmer Vernooij
Merge trunk.
823
            self._transport = None
0.254.36 by Jelmer Vernooij
Merge trunk.
824
            self._index = _mod_index.InMemoryGraphIndex(0, key_elements=3)
0.254.2 by jelmer
use btree indexes
825
            self._builder = self._index
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
826
        else:
0.254.30 by Jelmer Vernooij
Move index to separate dir.
827
            self._builder = None
0.254.43 by Jelmer Vernooij
Merge trunk.
828
            self._transport = transport
0.254.2 by jelmer
use btree indexes
829
            self._index = _mod_index.CombinedGraphIndex([])
0.254.43 by Jelmer Vernooij
Merge trunk.
830
            for name in self._transport.list_dir("."):
0.254.2 by jelmer
use btree indexes
831
                if not name.endswith(".rix"):
832
                    continue
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
833
                x = _mod_btree_index.BTreeGraphIndex(
834
                    self._transport, name, self._transport.stat(name).st_size)
0.254.2 by jelmer
use btree indexes
835
                self._index.insert_index(0, x)
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
836
837
    @classmethod
838
    def from_repository(cls, repository):
839
        transport = getattr(repository, "_transport", None)
840
        if transport is not None:
0.254.2 by jelmer
use btree indexes
841
            try:
842
                transport.mkdir('git')
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
843
            except bzr_errors.FileExists:
0.254.2 by jelmer
use btree indexes
844
                pass
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
845
            return cls(transport.clone('git'))
7336.2.1 by Martin
Split non-ini config methods to bedding
846
        return cls(get_transport_from_path(get_cache_dir()))
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
847
0.254.19 by Jelmer Vernooij
Support upgrading sha maps.
848
    def __repr__(self):
849
        if self._transport is not None:
850
            return "%s(%r)" % (self.__class__.__name__, self._transport.base)
851
        else:
852
            return "%s()" % (self.__class__.__name__)
853
0.254.3 by John Arbash Meinel
Add repack function.
854
    def repack(self):
0.361.1 by Jelmer Vernooij
Don't use assert.
855
        if self._builder is not None:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
856
            raise bzr_errors.BzrError('builder already open')
0.254.3 by John Arbash Meinel
Add repack function.
857
        self.start_write_group()
0.422.1 by Jelmer Vernooij
Remove content caching, fix index.
858
        self._builder.add_nodes(
859
            ((key, value) for (_, key, value) in
860
                self._index.iter_all_entries()))
0.254.3 by John Arbash Meinel
Add repack function.
861
        to_remove = []
0.254.43 by Jelmer Vernooij
Merge trunk.
862
        for name in self._transport.list_dir('.'):
0.254.3 by John Arbash Meinel
Add repack function.
863
            if name.endswith('.rix'):
864
                to_remove.append(name)
865
        self.commit_write_group()
866
        del self._index.indices[1:]
867
        for name in to_remove:
0.254.43 by Jelmer Vernooij
Merge trunk.
868
            self._transport.rename(name, name + '.old')
0.254.3 by John Arbash Meinel
Add repack function.
869
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
870
    def start_write_group(self):
0.361.1 by Jelmer Vernooij
Don't use assert.
871
        if self._builder is not None:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
872
            raise bzr_errors.BzrError('builder already open')
0.254.36 by Jelmer Vernooij
Merge trunk.
873
        self._builder = _mod_btree_index.BTreeBuilder(0, key_elements=3)
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
874
        self._name = osutils.sha()
875
876
    def commit_write_group(self):
0.361.1 by Jelmer Vernooij
Don't use assert.
877
        if self._builder is None:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
878
            raise bzr_errors.BzrError('builder not open')
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
879
        stream = self._builder.finish()
0.254.2 by jelmer
use btree indexes
880
        name = self._name.hexdigest() + ".rix"
0.254.43 by Jelmer Vernooij
Merge trunk.
881
        size = self._transport.put_file(name, stream)
882
        index = _mod_btree_index.BTreeGraphIndex(self._transport, name, size)
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
883
        self._index.insert_index(0, index)
884
        self._builder = None
885
        self._name = None
886
887
    def abort_write_group(self):
0.361.1 by Jelmer Vernooij
Don't use assert.
888
        if self._builder is None:
7143.15.3 by Jelmer Vernooij
Fix pep8 issues in breezy.git.
889
            raise bzr_errors.BzrError('builder not open')
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
890
        self._builder = None
891
        self._name = None
892
0.254.15 by Jelmer Vernooij
Convenience function for adding index nodes.
893
    def _add_node(self, key, value):
894
        try:
0.425.1 by Jelmer Vernooij
Add really basic check implementation.
895
            self._get_entry(key)
896
        except KeyError:
0.254.15 by Jelmer Vernooij
Convenience function for adding index nodes.
897
            self._builder.add_node(key, value)
0.425.1 by Jelmer Vernooij
Add really basic check implementation.
898
            return False
899
        else:
0.254.26 by Jelmer Vernooij
Fix typo, cope with invalid shamaps a bit better.
900
            return True
0.254.15 by Jelmer Vernooij
Convenience function for adding index nodes.
901
0.254.2 by jelmer
use btree indexes
902
    def _get_entry(self, key):
903
        entries = self._index.iter_entries([key])
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
904
        try:
6973.10.5 by Jelmer Vernooij
Fix use of .next.
905
            return next(entries)[2]
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
906
        except StopIteration:
0.254.2 by jelmer
use btree indexes
907
            if self._builder is None:
908
                raise KeyError
909
            entries = self._builder.iter_entries([key])
910
            try:
6973.10.5 by Jelmer Vernooij
Fix use of .next.
911
                return next(entries)[2]
0.254.2 by jelmer
use btree indexes
912
            except StopIteration:
913
                raise KeyError
914
0.261.2 by Jelmer Vernooij
Fix cache tests.
915
    def _iter_entries_prefix(self, prefix):
0.254.2 by jelmer
use btree indexes
916
        for entry in self._index.iter_entries_prefix([prefix]):
0.261.2 by Jelmer Vernooij
Fix cache tests.
917
            yield (entry[1], entry[2])
0.254.2 by jelmer
use btree indexes
918
        if self._builder is not None:
919
            for entry in self._builder.iter_entries_prefix([prefix]):
0.261.2 by Jelmer Vernooij
Fix cache tests.
920
                yield (entry[1], entry[2])
0.254.2 by jelmer
use btree indexes
921
922
    def lookup_commit(self, revid):
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
923
        return self._get_entry((b"commit", revid, b"X"))[:40]
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
924
0.254.33 by Jelmer Vernooij
Merge trunk.
925
    def _add_git_sha(self, hexsha, type, type_data):
0.254.2 by jelmer
use btree indexes
926
        if hexsha is not None:
927
            self._name.update(hexsha)
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
928
            if type == b"commit":
0.200.1179 by Jelmer Vernooij
Avoid using verifiers for natively imported revisions, save a lot of time.
929
                td = (type_data[0], type_data[1])
930
                try:
931
                    td += (type_data[2]["testament3-sha1"],)
932
                except KeyError:
933
                    pass
0.200.1029 by Jelmer Vernooij
Use dictionary with verifiers rather than requiring testament3-sha1 everywhere.
934
            else:
935
                td = type_data
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
936
            self._add_node((b"git", hexsha, b"X"), b" ".join((type,) + td))
0.254.2 by jelmer
use btree indexes
937
        else:
938
            # This object is not represented in Git - perhaps an empty
939
            # directory?
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
940
            self._name.update(type + b" ".join(type_data))
0.254.33 by Jelmer Vernooij
Merge trunk.
941
0.254.42 by Jelmer Vernooij
Merge trunk.
942
    def lookup_blob_id(self, fileid, revision):
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
943
        return self._get_entry((b"blob", fileid, revision))
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
944
945
    def lookup_git_sha(self, sha):
946
        if len(sha) == 20:
947
            sha = sha_to_hex(sha)
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
948
        value = self._get_entry((b"git", sha, b"X"))
949
        data = value.split(b" ", 3)
950
        if data[0] == b"commit":
0.425.1 by Jelmer Vernooij
Add really basic check implementation.
951
            try:
952
                if data[3]:
953
                    verifiers = {"testament3-sha1": data[3]}
954
                else:
955
                    verifiers = {}
956
            except IndexError:
0.422.1 by Jelmer Vernooij
Remove content caching, fix index.
957
                verifiers = {}
958
            yield ("commit", (data[1], data[2], verifiers))
959
        else:
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
960
            yield (data[0].decode('ascii'), tuple(data[1:]))
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
961
962
    def revids(self):
963
        """List the revision ids known."""
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
964
        for key, value in self._iter_entries_prefix((b"commit", None, None)):
0.254.2 by jelmer
use btree indexes
965
            yield key[1]
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
966
0.254.21 by Jelmer Vernooij
Implement faster missing_revisions.
967
    def missing_revisions(self, revids):
968
        """Return set of all the revisions that are not present."""
969
        missing_revids = set(revids)
970
        for _, key, value in self._index.iter_entries((
7143.15.2 by Jelmer Vernooij
Run autopep8.
971
                (b"commit", revid, b"X") for revid in revids)):
0.254.21 by Jelmer Vernooij
Implement faster missing_revisions.
972
            missing_revids.remove(key[1])
973
        return missing_revids
974
0.254.1 by Jelmer Vernooij
Add trivial index-based sha map.
975
    def sha1s(self):
976
        """List the SHA1s."""
6973.13.7 by Jelmer Vernooij
Fix remaining git cache tests.
977
        for key, value in self._iter_entries_prefix((b"git", None, None)):
0.254.2 by jelmer
use btree indexes
978
            yield key[1]
0.254.19 by Jelmer Vernooij
Support upgrading sha maps.
979
980
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
981
formats = registry.Registry()
982
formats.register(TdbGitCacheFormat().get_format_string(),
7143.15.2 by Jelmer Vernooij
Run autopep8.
983
                 TdbGitCacheFormat())
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
984
formats.register(SqliteGitCacheFormat().get_format_string(),
7143.15.2 by Jelmer Vernooij
Run autopep8.
985
                 SqliteGitCacheFormat())
0.254.43 by Jelmer Vernooij
Merge trunk.
986
formats.register(IndexGitCacheFormat().get_format_string(),
7143.15.2 by Jelmer Vernooij
Run autopep8.
987
                 IndexGitCacheFormat())
0.200.951 by Jelmer Vernooij
merge support for git object store-based caching mechanism.
988
# In the future, this will become the default:
0.425.1 by Jelmer Vernooij
Add really basic check implementation.
989
formats.register('default', IndexGitCacheFormat())
0.200.951 by Jelmer Vernooij
merge support for git object store-based caching mechanism.
990
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
991
992
def migrate_ancient_formats(repo_transport):
0.200.1221 by Jelmer Vernooij
Support cache for non-local transport properly.
993
    # Migrate older cache formats
994
    repo_transport = remove_readonly_transport_decorator(repo_transport)
995
    has_sqlite = repo_transport.has("git.db")
996
    has_tdb = repo_transport.has("git.tdb")
997
    if not has_sqlite or has_tdb:
998
        return
999
    try:
1000
        repo_transport.mkdir("git")
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
1001
    except bzr_errors.FileExists:
0.200.1221 by Jelmer Vernooij
Support cache for non-local transport properly.
1002
        return
7143.15.2 by Jelmer Vernooij
Run autopep8.
1003
    # Prefer migrating git.db over git.tdb, since the latter may not
0.200.866 by Jelmer Vernooij
More docstrings, prefer migrating git.db to migrating git.tdb.
1004
    # be openable on some platforms.
0.200.1221 by Jelmer Vernooij
Support cache for non-local transport properly.
1005
    if has_sqlite:
0.200.866 by Jelmer Vernooij
More docstrings, prefer migrating git.db to migrating git.tdb.
1006
        SqliteGitCacheFormat().initialize(repo_transport.clone("git"))
1007
        repo_transport.rename("git.db", "git/idmap.db")
0.200.1221 by Jelmer Vernooij
Support cache for non-local transport properly.
1008
    elif has_tdb:
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
1009
        TdbGitCacheFormat().initialize(repo_transport.clone("git"))
1010
        repo_transport.rename("git.tdb", "git/idmap.tdb")
1011
1012
0.200.865 by Jelmer Vernooij
Support serving without --allow-writes.
1013
def remove_readonly_transport_decorator(transport):
1014
    if transport.is_readonly():
0.200.1438 by Jelmer Vernooij
Cope with remote branches not being readonly at all better.
1015
        try:
1016
            return transport._decorated
1017
        except AttributeError:
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
1018
            raise bzr_errors.ReadOnlyError(transport)
0.200.865 by Jelmer Vernooij
Support serving without --allow-writes.
1019
    return transport
1020
1021
0.254.19 by Jelmer Vernooij
Support upgrading sha maps.
1022
def from_repository(repository):
0.200.866 by Jelmer Vernooij
More docstrings, prefer migrating git.db to migrating git.tdb.
1023
    """Open a cache file for a repository.
1024
1025
    If the repository is remote and there is no transport available from it
1026
    this will use a local file in the users cache directory
1027
    (typically ~/.cache/bazaar/git/)
1028
1029
    :param repository: A repository object
1030
    """
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
1031
    repo_transport = getattr(repository, "_transport", None)
1032
    if repo_transport is not None:
0.200.1438 by Jelmer Vernooij
Cope with remote branches not being readonly at all better.
1033
        try:
1034
            migrate_ancient_formats(repo_transport)
0.200.1641 by Jelmer Vernooij
Use relative imports where possible.
1035
        except bzr_errors.ReadOnlyError:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1036
            pass  # Not much we can do
0.200.844 by Jelmer Vernooij
Add infrastructure for multiple cache formats.
1037
    return BzrGitCacheFormat.from_repository(repository)