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