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