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