~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/weaverepo.py

  • Committer: Martin Pool
  • Date: 2007-10-12 08:00:07 UTC
  • mto: This revision was merged to the branch mainline in revision 2913.
  • Revision ID: mbp@sourcefrog.net-20071012080007-vf80woayyom8s8e1
Rename update_to_one_parent_via_delta to more wieldy update_basis_by_delta

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
20
20
ghosts.
21
21
"""
22
22
 
23
 
import os
24
 
from cStringIO import StringIO
25
 
import urllib
 
23
from StringIO import StringIO
26
24
 
27
25
from bzrlib import (
28
26
    bzrdir,
32
30
    lockdir,
33
31
    osutils,
34
32
    revision as _mod_revision,
35
 
    versionedfile,
36
33
    weave,
37
34
    weavefile,
38
35
    xml5,
40
37
from bzrlib.decorators import needs_read_lock, needs_write_lock
41
38
from bzrlib.repository import (
42
39
    CommitBuilder,
43
 
    MetaDirVersionedFileRepository,
 
40
    MetaDirRepository,
44
41
    MetaDirRepositoryFormat,
45
42
    Repository,
46
43
    RepositoryFormat,
47
44
    )
48
45
from bzrlib.store.text import TextStore
49
46
from bzrlib.trace import mutter
50
 
from bzrlib.tuned_gzip import GzipFile, bytes_to_gzip
51
 
from bzrlib.versionedfile import (
52
 
    AbsentContentFactory,
53
 
    FulltextContentFactory,
54
 
    VersionedFiles,
55
 
    )
56
47
 
57
48
 
58
49
class AllInOneRepository(Repository):
60
51
 
61
52
    _serializer = xml5.serializer_v5
62
53
 
63
 
    def __init__(self, _format, a_bzrdir):
 
54
    def __init__(self, _format, a_bzrdir, _revision_store, control_store, text_store):
64
55
        # we reuse one control files instance.
65
 
        dir_mode = a_bzrdir._get_dir_mode()
66
 
        file_mode = a_bzrdir._get_file_mode()
 
56
        dir_mode = a_bzrdir._control_files._dir_mode
 
57
        file_mode = a_bzrdir._control_files._file_mode
67
58
 
68
59
        def get_store(name, compressed=True, prefixed=False):
69
60
            # FIXME: This approach of assuming stores are all entirely compressed
71
62
            # some existing branches where there's a mixture; we probably 
72
63
            # still want the option to look for both.
73
64
            relpath = a_bzrdir._control_files._escape(name)
74
 
            store = TextStore(a_bzrdir.transport.clone(relpath),
 
65
            store = TextStore(a_bzrdir._control_files._transport.clone(relpath),
75
66
                              prefixed=prefixed, compressed=compressed,
76
67
                              dir_mode=dir_mode,
77
68
                              file_mode=file_mode)
78
69
            return store
79
70
 
80
71
        # not broken out yet because the controlweaves|inventory_store
81
 
        # and texts bits are still different.
 
72
        # and text_store | weave_store bits are still different.
82
73
        if isinstance(_format, RepositoryFormat4):
83
74
            # cannot remove these - there is still no consistent api 
84
75
            # which allows access to this old info.
85
76
            self.inventory_store = get_store('inventory-store')
86
 
            self._text_store = get_store('text-store')
87
 
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files)
88
 
        self._fetch_order = 'topological'
89
 
        self._fetch_reconcile = True
 
77
            text_store = get_store('text-store')
 
78
        super(AllInOneRepository, self).__init__(_format, a_bzrdir, a_bzrdir._control_files, _revision_store, control_store, text_store)
90
79
 
91
80
    @needs_read_lock
92
81
    def _all_possible_ids(self):
93
82
        """Return all the possible revisions that we could find."""
94
83
        if 'evil' in debug.debug_flags:
95
84
            mutter_callsite(3, "_all_possible_ids scales with size of history.")
96
 
        return [key[-1] for key in self.inventories.keys()]
 
85
        return self.get_inventory_weave().versions()
97
86
 
98
87
    @needs_read_lock
99
88
    def _all_revision_ids(self):
103
92
        present: for weaves ghosts may lead to a lack of correctness until
104
93
        the reweave updates the parents list.
105
94
        """
106
 
        return [key[-1] for key in self.revisions.keys()]
107
 
 
108
 
    def _activate_new_inventory(self):
109
 
        """Put a replacement inventory.new into use as inventories."""
110
 
        # Copy the content across
111
 
        t = self.bzrdir._control_files._transport
112
 
        t.copy('inventory.new.weave', 'inventory.weave')
113
 
        # delete the temp inventory
114
 
        t.delete('inventory.new.weave')
115
 
        # Check we can parse the new weave properly as a sanity check
116
 
        self.inventories.keys()
117
 
 
118
 
    def _backup_inventory(self):
119
 
        t = self.bzrdir._control_files._transport
120
 
        t.copy('inventory.weave', 'inventory.backup.weave')
121
 
 
122
 
    def _temp_inventories(self):
123
 
        t = self.bzrdir._control_files._transport
124
 
        return self._format._get_inventories(t, self, 'inventory.new')
 
95
        if self._revision_store.text_store.listable():
 
96
            return self._revision_store.all_revision_ids(self.get_transaction())
 
97
        result = self._all_possible_ids()
 
98
        # TODO: jam 20070210 Ensure that _all_possible_ids returns non-unicode
 
99
        #       ids. (It should, since _revision_store's API should change to
 
100
        #       return utf8 revision_ids)
 
101
        return self._eliminate_revisions_not_present(result)
 
102
 
 
103
    def _check_revision_parents(self, revision, inventory):
 
104
        """Private to Repository and Fetch.
 
105
        
 
106
        This checks the parentage of revision in an inventory weave for 
 
107
        consistency and is only applicable to inventory-weave-for-ancestry
 
108
        using repository formats & fetchers.
 
109
        """
 
110
        weave_parents = inventory.get_parents(revision.revision_id)
 
111
        weave_names = inventory.versions()
 
112
        for parent_id in revision.parent_ids:
 
113
            if parent_id in weave_names:
 
114
                # this parent must not be a ghost.
 
115
                if not parent_id in weave_parents:
 
116
                    # but it is a ghost
 
117
                    raise errors.CorruptRepository(self)
125
118
 
126
119
    def get_commit_builder(self, branch, parents, config, timestamp=None,
127
120
                           timezone=None, committer=None, revprops=None,
128
121
                           revision_id=None):
129
122
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
130
 
        result = CommitBuilder(self, parents, config, timestamp, timezone,
 
123
        result = WeaveCommitBuilder(self, parents, config, timestamp, timezone,
131
124
                              committer, revprops, revision_id)
132
125
        self.start_write_group()
133
126
        return result
135
128
    @needs_read_lock
136
129
    def get_revisions(self, revision_ids):
137
130
        revs = self._get_revisions(revision_ids)
 
131
        # weave corruption can lead to absent revision markers that should be
 
132
        # present.
 
133
        # the following test is reasonably cheap (it needs a single weave read)
 
134
        # and the weave is cached in read transactions. In write transactions
 
135
        # it is not cached but typically we only read a small number of
 
136
        # revisions. For knits when they are introduced we will probably want
 
137
        # to ensure that caching write transactions are in use.
 
138
        inv = self.get_inventory_weave()
 
139
        for rev in revs:
 
140
            self._check_revision_parents(rev, inv)
138
141
        return revs
139
142
 
140
 
    def _inventory_add_lines(self, revision_id, parents, lines,
141
 
        check_content=True):
142
 
        """Store lines in inv_vf and return the sha1 of the inventory."""
143
 
        present_parents = self.get_graph().get_parent_map(parents)
144
 
        final_parents = []
145
 
        for parent in parents:
146
 
            if parent in present_parents:
147
 
                final_parents.append((parent,))
148
 
        return self.inventories.add_lines((revision_id,), final_parents, lines,
149
 
            check_content=check_content)[0]
 
143
    @needs_read_lock
 
144
    def get_revision_graph(self, revision_id=None):
 
145
        """Return a dictionary containing the revision graph.
 
146
        
 
147
        :param revision_id: The revision_id to get a graph from. If None, then
 
148
        the entire revision graph is returned. This is a deprecated mode of
 
149
        operation and will be removed in the future.
 
150
        :return: a dictionary of revision_id->revision_parents_list.
 
151
        """
 
152
        if 'evil' in debug.debug_flags:
 
153
            mutter_callsite(2,
 
154
                "get_revision_graph scales with size of history.")
 
155
        # special case NULL_REVISION
 
156
        if revision_id == _mod_revision.NULL_REVISION:
 
157
            return {}
 
158
        a_weave = self.get_inventory_weave()
 
159
        all_revisions = self._eliminate_revisions_not_present(
 
160
                                a_weave.versions())
 
161
        entire_graph = dict([(node, tuple(a_weave.get_parents(node))) for 
 
162
                             node in all_revisions])
 
163
        if revision_id is None:
 
164
            return entire_graph
 
165
        elif revision_id not in entire_graph:
 
166
            raise errors.NoSuchRevision(self, revision_id)
 
167
        else:
 
168
            # add what can be reached from revision_id
 
169
            result = {}
 
170
            pending = set([revision_id])
 
171
            while len(pending) > 0:
 
172
                node = pending.pop()
 
173
                result[node] = entire_graph[node]
 
174
                for revision_id in result[node]:
 
175
                    if revision_id not in result:
 
176
                        pending.add(revision_id)
 
177
            return result
150
178
 
 
179
    @needs_read_lock
151
180
    def is_shared(self):
152
181
        """AllInOne repositories cannot be shared."""
153
182
        return False
162
191
        :param new_value: True to restore the default, False to disable making
163
192
                          working trees.
164
193
        """
165
 
        raise errors.RepositoryUpgradeRequired(self.bzrdir.root_transport.base)
166
 
 
 
194
        raise NotImplementedError(self.set_make_working_trees)
 
195
    
167
196
    def make_working_trees(self):
168
197
        """Returns the policy for making working trees on new branches."""
169
198
        return True
170
199
 
171
 
    def revision_graph_can_have_wrong_parents(self):
172
 
        # XXX: This is an old format that we don't support full checking on, so
173
 
        # just claim that checking for this inconsistency is not required.
174
 
        return False
175
 
 
176
 
 
177
 
class WeaveMetaDirRepository(MetaDirVersionedFileRepository):
 
200
 
 
201
class WeaveMetaDirRepository(MetaDirRepository):
178
202
    """A subclass of MetaDirRepository to set weave specific policy."""
179
203
 
180
204
    _serializer = xml5.serializer_v5
181
205
 
182
 
    def __init__(self, _format, a_bzrdir, control_files):
183
 
        super(WeaveMetaDirRepository, self).__init__(_format, a_bzrdir, control_files)
184
 
        self._fetch_order = 'topological'
185
 
        self._fetch_reconcile = True
186
 
 
187
206
    @needs_read_lock
188
207
    def _all_possible_ids(self):
189
208
        """Return all the possible revisions that we could find."""
190
209
        if 'evil' in debug.debug_flags:
191
210
            mutter_callsite(3, "_all_possible_ids scales with size of history.")
192
 
        return [key[-1] for key in self.inventories.keys()]
 
211
        return self.get_inventory_weave().versions()
193
212
 
194
213
    @needs_read_lock
195
214
    def _all_revision_ids(self):
199
218
        present: for weaves ghosts may lead to a lack of correctness until
200
219
        the reweave updates the parents list.
201
220
        """
202
 
        return [key[-1] for key in self.revisions.keys()]
203
 
 
204
 
    def _activate_new_inventory(self):
205
 
        """Put a replacement inventory.new into use as inventories."""
206
 
        # Copy the content across
207
 
        t = self._transport
208
 
        t.copy('inventory.new.weave', 'inventory.weave')
209
 
        # delete the temp inventory
210
 
        t.delete('inventory.new.weave')
211
 
        # Check we can parse the new weave properly as a sanity check
212
 
        self.inventories.keys()
213
 
 
214
 
    def _backup_inventory(self):
215
 
        t = self._transport
216
 
        t.copy('inventory.weave', 'inventory.backup.weave')
217
 
 
218
 
    def _temp_inventories(self):
219
 
        t = self._transport
220
 
        return self._format._get_inventories(t, self, 'inventory.new')
 
221
        if self._revision_store.text_store.listable():
 
222
            return self._revision_store.all_revision_ids(self.get_transaction())
 
223
        result = self._all_possible_ids()
 
224
        # TODO: jam 20070210 Ensure that _all_possible_ids returns non-unicode
 
225
        #       ids. (It should, since _revision_store's API should change to
 
226
        #       return utf8 revision_ids)
 
227
        return self._eliminate_revisions_not_present(result)
 
228
 
 
229
    def _check_revision_parents(self, revision, inventory):
 
230
        """Private to Repository and Fetch.
 
231
        
 
232
        This checks the parentage of revision in an inventory weave for 
 
233
        consistency and is only applicable to inventory-weave-for-ancestry
 
234
        using repository formats & fetchers.
 
235
        """
 
236
        weave_parents = inventory.get_parents(revision.revision_id)
 
237
        weave_names = inventory.versions()
 
238
        for parent_id in revision.parent_ids:
 
239
            if parent_id in weave_names:
 
240
                # this parent must not be a ghost.
 
241
                if not parent_id in weave_parents:
 
242
                    # but it is a ghost
 
243
                    raise errors.CorruptRepository(self)
221
244
 
222
245
    def get_commit_builder(self, branch, parents, config, timestamp=None,
223
246
                           timezone=None, committer=None, revprops=None,
224
247
                           revision_id=None):
225
248
        self._check_ascii_revisionid(revision_id, self.get_commit_builder)
226
 
        result = CommitBuilder(self, parents, config, timestamp, timezone,
 
249
        result = WeaveCommitBuilder(self, parents, config, timestamp, timezone,
227
250
                              committer, revprops, revision_id)
228
251
        self.start_write_group()
229
252
        return result
231
254
    @needs_read_lock
232
255
    def get_revision(self, revision_id):
233
256
        """Return the Revision object for a named revision"""
 
257
        # TODO: jam 20070210 get_revision_reconcile should do this for us
234
258
        r = self.get_revision_reconcile(revision_id)
 
259
        # weave corruption can lead to absent revision markers that should be
 
260
        # present.
 
261
        # the following test is reasonably cheap (it needs a single weave read)
 
262
        # and the weave is cached in read transactions. In write transactions
 
263
        # it is not cached but typically we only read a small number of
 
264
        # revisions. For knits when they are introduced we will probably want
 
265
        # to ensure that caching write transactions are in use.
 
266
        inv = self.get_inventory_weave()
 
267
        self._check_revision_parents(r, inv)
235
268
        return r
236
269
 
237
 
    def _inventory_add_lines(self, revision_id, parents, lines,
238
 
        check_content=True):
239
 
        """Store lines in inv_vf and return the sha1 of the inventory."""
240
 
        present_parents = self.get_graph().get_parent_map(parents)
241
 
        final_parents = []
242
 
        for parent in parents:
243
 
            if parent in present_parents:
244
 
                final_parents.append((parent,))
245
 
        return self.inventories.add_lines((revision_id,), final_parents, lines,
246
 
            check_content=check_content)[0]
247
 
 
248
 
    def revision_graph_can_have_wrong_parents(self):
249
 
        return False
 
270
    @needs_read_lock
 
271
    def get_revision_graph(self, revision_id=None):
 
272
        """Return a dictionary containing the revision graph.
 
273
        
 
274
        :param revision_id: The revision_id to get a graph from. If None, then
 
275
        the entire revision graph is returned. This is a deprecated mode of
 
276
        operation and will be removed in the future.
 
277
        :return: a dictionary of revision_id->revision_parents_list.
 
278
        """
 
279
        if 'evil' in debug.debug_flags:
 
280
            mutter_callsite(3,
 
281
                "get_revision_graph scales with size of history.")
 
282
        # special case NULL_REVISION
 
283
        if revision_id == _mod_revision.NULL_REVISION:
 
284
            return {}
 
285
        a_weave = self.get_inventory_weave()
 
286
        all_revisions = self._eliminate_revisions_not_present(
 
287
                                a_weave.versions())
 
288
        entire_graph = dict([(node, tuple(a_weave.get_parents(node))) for 
 
289
                             node in all_revisions])
 
290
        if revision_id is None:
 
291
            return entire_graph
 
292
        elif revision_id not in entire_graph:
 
293
            raise errors.NoSuchRevision(self, revision_id)
 
294
        else:
 
295
            # add what can be reached from revision_id
 
296
            result = {}
 
297
            pending = set([revision_id])
 
298
            while len(pending) > 0:
 
299
                node = pending.pop()
 
300
                result[node] = entire_graph[node]
 
301
                for revision_id in result[node]:
 
302
                    if revision_id not in result:
 
303
                        pending.add(revision_id)
 
304
            return result
250
305
 
251
306
 
252
307
class PreSplitOutRepositoryFormat(RepositoryFormat):
254
309
 
255
310
    rich_root_data = False
256
311
    supports_tree_reference = False
257
 
    supports_ghosts = False
258
 
    supports_external_lookups = False
259
312
 
260
313
    def initialize(self, a_bzrdir, shared=False, _internal=False):
261
 
        """Create a weave repository."""
 
314
        """Create a weave repository.
 
315
        
 
316
        TODO: when creating split out bzr branch formats, move this to a common
 
317
        base for Format5, Format6. or something like that.
 
318
        """
262
319
        if shared:
263
320
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
264
321
 
272
329
        empty_weave = sio.getvalue()
273
330
 
274
331
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
332
        dirs = ['revision-store', 'weaves']
 
333
        files = [('inventory.weave', StringIO(empty_weave)),
 
334
                 ]
275
335
        
276
336
        # FIXME: RBC 20060125 don't peek under the covers
277
337
        # NB: no need to escape relative paths that are url safe.
278
338
        control_files = lockable_files.LockableFiles(a_bzrdir.transport,
279
 
            'branch-lock', lockable_files.TransportLock)
 
339
                                'branch-lock', lockable_files.TransportLock)
280
340
        control_files.create_lock()
281
341
        control_files.lock_write()
282
 
        transport = a_bzrdir.transport
 
342
        control_files._transport.mkdir_multi(dirs,
 
343
                mode=control_files._dir_mode)
283
344
        try:
284
 
            transport.mkdir_multi(['revision-store', 'weaves'],
285
 
                mode=a_bzrdir._get_dir_mode())
286
 
            transport.put_bytes_non_atomic('inventory.weave', empty_weave)
 
345
            for file, content in files:
 
346
                control_files.put(file, content)
287
347
        finally:
288
348
            control_files.unlock()
289
349
        return self.open(a_bzrdir, _found=True)
290
350
 
 
351
    def _get_control_store(self, repo_transport, control_files):
 
352
        """Return the control store for this repository."""
 
353
        return self._get_versioned_file_store('',
 
354
                                              repo_transport,
 
355
                                              control_files,
 
356
                                              prefixed=False)
 
357
 
 
358
    def _get_text_store(self, transport, control_files):
 
359
        """Get a store for file texts for this format."""
 
360
        raise NotImplementedError(self._get_text_store)
 
361
 
291
362
    def open(self, a_bzrdir, _found=False):
292
363
        """See RepositoryFormat.open()."""
293
364
        if not _found:
296
367
 
297
368
        repo_transport = a_bzrdir.get_repository_transport(None)
298
369
        control_files = a_bzrdir._control_files
299
 
        result = AllInOneRepository(_format=self, a_bzrdir=a_bzrdir)
300
 
        result.revisions = self._get_revisions(repo_transport, result)
301
 
        result.signatures = self._get_signatures(repo_transport, result)
302
 
        result.inventories = self._get_inventories(repo_transport, result)
303
 
        result.texts = self._get_texts(repo_transport, result)
304
 
        return result
 
370
        text_store = self._get_text_store(repo_transport, control_files)
 
371
        control_store = self._get_control_store(repo_transport, control_files)
 
372
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
373
        return AllInOneRepository(_format=self,
 
374
                                  a_bzrdir=a_bzrdir,
 
375
                                  _revision_store=_revision_store,
 
376
                                  control_store=control_store,
 
377
                                  text_store=text_store)
305
378
 
306
379
    def check_conversion_target(self, target_format):
307
380
        pass
323
396
 
324
397
    def __init__(self):
325
398
        super(RepositoryFormat4, self).__init__()
326
 
        self._fetch_order = 'topological'
327
 
        self._fetch_reconcile = True
328
399
 
329
400
    def get_format_description(self):
330
401
        """See RepositoryFormat.get_format_description()."""
343
414
        """
344
415
        return False
345
416
 
346
 
    def _get_inventories(self, repo_transport, repo, name='inventory'):
347
 
        # No inventories store written so far.
 
417
    def _get_control_store(self, repo_transport, control_files):
 
418
        """Format 4 repositories have no formal control store at this point.
 
419
        
 
420
        This will cause any control-file-needing apis to fail - this is desired.
 
421
        """
348
422
        return None
349
 
 
350
 
    def _get_revisions(self, repo_transport, repo):
 
423
    
 
424
    def _get_revision_store(self, repo_transport, control_files):
 
425
        """See RepositoryFormat._get_revision_store()."""
351
426
        from bzrlib.xml4 import serializer_v4
352
 
        return RevisionTextStore(repo_transport.clone('revision-store'),
353
 
            serializer_v4, True, versionedfile.PrefixMapper(),
354
 
            repo.is_locked, repo.is_write_locked)
355
 
 
356
 
    def _get_signatures(self, repo_transport, repo):
357
 
        return SignatureTextStore(repo_transport.clone('revision-store'),
358
 
            False, versionedfile.PrefixMapper(),
359
 
            repo.is_locked, repo.is_write_locked)
360
 
 
361
 
    def _get_texts(self, repo_transport, repo):
362
 
        return None
 
427
        return self._get_text_rev_store(repo_transport,
 
428
                                        control_files,
 
429
                                        'revision-store',
 
430
                                        serializer=serializer_v4)
 
431
 
 
432
    def _get_text_store(self, transport, control_files):
 
433
        """See RepositoryFormat._get_text_store()."""
363
434
 
364
435
 
365
436
class RepositoryFormat5(PreSplitOutRepositoryFormat):
376
447
 
377
448
    def __init__(self):
378
449
        super(RepositoryFormat5, self).__init__()
379
 
        self._fetch_order = 'topological'
380
 
        self._fetch_reconcile = True
381
450
 
382
451
    def get_format_description(self):
383
452
        """See RepositoryFormat.get_format_description()."""
384
453
        return "Weave repository format 5"
385
454
 
386
 
    def _get_inventories(self, repo_transport, repo, name='inventory'):
387
 
        mapper = versionedfile.ConstantMapper(name)
388
 
        return versionedfile.ThunkedVersionedFiles(repo_transport,
389
 
            weave.WeaveFile, mapper, repo.is_locked)
390
 
 
391
 
    def _get_revisions(self, repo_transport, repo):
392
 
        from bzrlib.xml5 import serializer_v5
393
 
        return RevisionTextStore(repo_transport.clone('revision-store'),
394
 
            serializer_v5, False, versionedfile.PrefixMapper(),
395
 
            repo.is_locked, repo.is_write_locked)
396
 
 
397
 
    def _get_signatures(self, repo_transport, repo):
398
 
        return SignatureTextStore(repo_transport.clone('revision-store'),
399
 
            False, versionedfile.PrefixMapper(),
400
 
            repo.is_locked, repo.is_write_locked)
401
 
 
402
 
    def _get_texts(self, repo_transport, repo):
403
 
        mapper = versionedfile.PrefixMapper()
404
 
        base_transport = repo_transport.clone('weaves')
405
 
        return versionedfile.ThunkedVersionedFiles(base_transport,
406
 
            weave.WeaveFile, mapper, repo.is_locked)
 
455
    def _get_revision_store(self, repo_transport, control_files):
 
456
        """See RepositoryFormat._get_revision_store()."""
 
457
        """Return the revision store object for this a_bzrdir."""
 
458
        return self._get_text_rev_store(repo_transport,
 
459
                                        control_files,
 
460
                                        'revision-store',
 
461
                                        compressed=False)
 
462
 
 
463
    def _get_text_store(self, transport, control_files):
 
464
        """See RepositoryFormat._get_text_store()."""
 
465
        return self._get_versioned_file_store('weaves', transport, control_files, prefixed=False)
407
466
 
408
467
 
409
468
class RepositoryFormat6(PreSplitOutRepositoryFormat):
420
479
 
421
480
    def __init__(self):
422
481
        super(RepositoryFormat6, self).__init__()
423
 
        self._fetch_order = 'topological'
424
 
        self._fetch_reconcile = True
425
482
 
426
483
    def get_format_description(self):
427
484
        """See RepositoryFormat.get_format_description()."""
428
485
        return "Weave repository format 6"
429
486
 
430
 
    def _get_inventories(self, repo_transport, repo, name='inventory'):
431
 
        mapper = versionedfile.ConstantMapper(name)
432
 
        return versionedfile.ThunkedVersionedFiles(repo_transport,
433
 
            weave.WeaveFile, mapper, repo.is_locked)
434
 
 
435
 
    def _get_revisions(self, repo_transport, repo):
436
 
        from bzrlib.xml5 import serializer_v5
437
 
        return RevisionTextStore(repo_transport.clone('revision-store'),
438
 
            serializer_v5, False, versionedfile.HashPrefixMapper(),
439
 
            repo.is_locked, repo.is_write_locked)
440
 
 
441
 
    def _get_signatures(self, repo_transport, repo):
442
 
        return SignatureTextStore(repo_transport.clone('revision-store'),
443
 
            False, versionedfile.HashPrefixMapper(),
444
 
            repo.is_locked, repo.is_write_locked)
445
 
 
446
 
    def _get_texts(self, repo_transport, repo):
447
 
        mapper = versionedfile.HashPrefixMapper()
448
 
        base_transport = repo_transport.clone('weaves')
449
 
        return versionedfile.ThunkedVersionedFiles(base_transport,
450
 
            weave.WeaveFile, mapper, repo.is_locked)
 
487
    def _get_revision_store(self, repo_transport, control_files):
 
488
        """See RepositoryFormat._get_revision_store()."""
 
489
        return self._get_text_rev_store(repo_transport,
 
490
                                        control_files,
 
491
                                        'revision-store',
 
492
                                        compressed=False,
 
493
                                        prefixed=True)
 
494
 
 
495
    def _get_text_store(self, transport, control_files):
 
496
        """See RepositoryFormat._get_text_store()."""
 
497
        return self._get_versioned_file_store('weaves', transport, control_files)
451
498
 
452
499
 
453
500
class RepositoryFormat7(MetaDirRepositoryFormat):
463
510
    """
464
511
 
465
512
    _versionedfile_class = weave.WeaveFile
466
 
    supports_ghosts = False
 
513
 
 
514
    def _get_control_store(self, repo_transport, control_files):
 
515
        """Return the control store for this repository."""
 
516
        return self._get_versioned_file_store('',
 
517
                                              repo_transport,
 
518
                                              control_files,
 
519
                                              prefixed=False)
467
520
 
468
521
    def get_format_string(self):
469
522
        """See RepositoryFormat.get_format_string()."""
476
529
    def check_conversion_target(self, target_format):
477
530
        pass
478
531
 
479
 
    def _get_inventories(self, repo_transport, repo, name='inventory'):
480
 
        mapper = versionedfile.ConstantMapper(name)
481
 
        return versionedfile.ThunkedVersionedFiles(repo_transport,
482
 
            weave.WeaveFile, mapper, repo.is_locked)
483
 
 
484
 
    def _get_revisions(self, repo_transport, repo):
485
 
        from bzrlib.xml5 import serializer_v5
486
 
        return RevisionTextStore(repo_transport.clone('revision-store'),
487
 
            serializer_v5, True, versionedfile.HashPrefixMapper(),
488
 
            repo.is_locked, repo.is_write_locked)
489
 
 
490
 
    def _get_signatures(self, repo_transport, repo):
491
 
        return SignatureTextStore(repo_transport.clone('revision-store'),
492
 
            True, versionedfile.HashPrefixMapper(),
493
 
            repo.is_locked, repo.is_write_locked)
494
 
 
495
 
    def _get_texts(self, repo_transport, repo):
496
 
        mapper = versionedfile.HashPrefixMapper()
497
 
        base_transport = repo_transport.clone('weaves')
498
 
        return versionedfile.ThunkedVersionedFiles(base_transport,
499
 
            weave.WeaveFile, mapper, repo.is_locked)
 
532
    def _get_revision_store(self, repo_transport, control_files):
 
533
        """See RepositoryFormat._get_revision_store()."""
 
534
        return self._get_text_rev_store(repo_transport,
 
535
                                        control_files,
 
536
                                        'revision-store',
 
537
                                        compressed=False,
 
538
                                        prefixed=True,
 
539
                                        )
 
540
 
 
541
    def _get_text_store(self, transport, control_files):
 
542
        """See RepositoryFormat._get_text_store()."""
 
543
        return self._get_versioned_file_store('weaves',
 
544
                                              transport,
 
545
                                              control_files)
500
546
 
501
547
    def initialize(self, a_bzrdir, shared=False):
502
548
        """Create a weave repository.
527
573
        """
528
574
        if not _found:
529
575
            format = RepositoryFormat.find_format(a_bzrdir)
 
576
            assert format.__class__ ==  self.__class__
530
577
        if _override_transport is not None:
531
578
            repo_transport = _override_transport
532
579
        else:
533
580
            repo_transport = a_bzrdir.get_repository_transport(None)
534
581
        control_files = lockable_files.LockableFiles(repo_transport,
535
582
                                'lock', lockdir.LockDir)
536
 
        result = WeaveMetaDirRepository(_format=self, a_bzrdir=a_bzrdir,
537
 
            control_files=control_files)
538
 
        result.revisions = self._get_revisions(repo_transport, result)
539
 
        result.signatures = self._get_signatures(repo_transport, result)
540
 
        result.inventories = self._get_inventories(repo_transport, result)
541
 
        result.texts = self._get_texts(repo_transport, result)
542
 
        result._transport = repo_transport
543
 
        return result
544
 
 
545
 
 
546
 
class TextVersionedFiles(VersionedFiles):
547
 
    """Just-a-bunch-of-files based VersionedFile stores."""
548
 
 
549
 
    def __init__(self, transport, compressed, mapper, is_locked, can_write):
550
 
        self._compressed = compressed
551
 
        self._transport = transport
552
 
        self._mapper = mapper
553
 
        if self._compressed:
554
 
            self._ext = '.gz'
555
 
        else:
556
 
            self._ext = ''
557
 
        self._is_locked = is_locked
558
 
        self._can_write = can_write
559
 
 
560
 
    def add_lines(self, key, parents, lines):
561
 
        """Add a revision to the store."""
562
 
        if not self._is_locked():
563
 
            raise errors.ObjectNotLocked(self)
564
 
        if not self._can_write():
565
 
            raise errors.ReadOnlyError(self)
566
 
        if '/' in key[-1]:
567
 
            raise ValueError('bad idea to put / in %r' % (key,))
568
 
        text = ''.join(lines)
569
 
        if self._compressed:
570
 
            text = bytes_to_gzip(text)
571
 
        path = self._map(key)
572
 
        self._transport.put_bytes_non_atomic(path, text, create_parent_dir=True)
573
 
 
574
 
    def insert_record_stream(self, stream):
575
 
        adapters = {}
576
 
        for record in stream:
577
 
            # Raise an error when a record is missing.
578
 
            if record.storage_kind == 'absent':
579
 
                raise errors.RevisionNotPresent([record.key[0]], self)
580
 
            # adapt to non-tuple interface
581
 
            if record.storage_kind == 'fulltext':
582
 
                self.add_lines(record.key, None,
583
 
                    osutils.split_lines(record.get_bytes_as('fulltext')))
584
 
            else:
585
 
                adapter_key = record.storage_kind, 'fulltext'
586
 
                try:
587
 
                    adapter = adapters[adapter_key]
588
 
                except KeyError:
589
 
                    adapter_factory = adapter_registry.get(adapter_key)
590
 
                    adapter = adapter_factory(self)
591
 
                    adapters[adapter_key] = adapter
592
 
                lines = osutils.split_lines(adapter.get_bytes(
593
 
                    record, record.get_bytes_as(record.storage_kind)))
594
 
                try:
595
 
                    self.add_lines(record.key, None, lines)
596
 
                except RevisionAlreadyPresent:
597
 
                    pass
598
 
 
599
 
    def _load_text(self, key):
600
 
        if not self._is_locked():
601
 
            raise errors.ObjectNotLocked(self)
602
 
        path = self._map(key)
603
 
        try:
604
 
            text = self._transport.get_bytes(path)
605
 
            compressed = self._compressed
606
 
        except errors.NoSuchFile:
607
 
            if self._compressed:
608
 
                # try without the .gz
609
 
                path = path[:-3]
610
 
                try:
611
 
                    text = self._transport.get_bytes(path)
612
 
                    compressed = False
613
 
                except errors.NoSuchFile:
614
 
                    return None
615
 
            else:
616
 
                return None
617
 
        if compressed:
618
 
            text = GzipFile(mode='rb', fileobj=StringIO(text)).read()
619
 
        return text
620
 
 
621
 
    def _map(self, key):
622
 
        return self._mapper.map(key) + self._ext
623
 
 
624
 
 
625
 
class RevisionTextStore(TextVersionedFiles):
626
 
    """Legacy thunk for format 4 repositories."""
627
 
 
628
 
    def __init__(self, transport, serializer, compressed, mapper, is_locked,
629
 
        can_write):
630
 
        """Create a RevisionTextStore at transport with serializer."""
631
 
        TextVersionedFiles.__init__(self, transport, compressed, mapper,
632
 
            is_locked, can_write)
633
 
        self._serializer = serializer
634
 
 
635
 
    def _load_text_parents(self, key):
636
 
        text = self._load_text(key)
637
 
        if text is None:
638
 
            return None, None
639
 
        parents = self._serializer.read_revision_from_string(text).parent_ids
640
 
        return text, tuple((parent,) for parent in parents)
641
 
 
642
 
    def get_parent_map(self, keys):
643
 
        result = {}
644
 
        for key in keys:
645
 
            parents = self._load_text_parents(key)[1]
646
 
            if parents is None:
647
 
                continue
648
 
            result[key] = parents
649
 
        return result
650
 
    
651
 
    def get_record_stream(self, keys, sort_order, include_delta_closure):
652
 
        for key in keys:
653
 
            text, parents = self._load_text_parents(key)
654
 
            if text is None:
655
 
                yield AbsentContentFactory(key)
656
 
            else:
657
 
                yield FulltextContentFactory(key, parents, None, text)
658
 
 
659
 
    def keys(self):
660
 
        if not self._is_locked():
661
 
            raise errors.ObjectNotLocked(self)
662
 
        relpaths = set()
663
 
        for quoted_relpath in self._transport.iter_files_recursive():
664
 
            relpath = urllib.unquote(quoted_relpath)
665
 
            path, ext = os.path.splitext(relpath)
666
 
            if ext == '.gz':
667
 
                relpath = path
668
 
            if '.sig' not in relpath:
669
 
                relpaths.add(relpath)
670
 
        paths = list(relpaths)
671
 
        return set([self._mapper.unmap(path) for path in paths])
672
 
 
673
 
 
674
 
class SignatureTextStore(TextVersionedFiles):
675
 
    """Legacy thunk for format 4-7 repositories."""
676
 
 
677
 
    def __init__(self, transport, compressed, mapper, is_locked, can_write):
678
 
        TextVersionedFiles.__init__(self, transport, compressed, mapper,
679
 
            is_locked, can_write)
680
 
        self._ext = '.sig' + self._ext
681
 
 
682
 
    def get_parent_map(self, keys):
683
 
        result = {}
684
 
        for key in keys:
685
 
            text = self._load_text(key)
686
 
            if text is None:
687
 
                continue
688
 
            result[key] = None
689
 
        return result
690
 
    
691
 
    def get_record_stream(self, keys, sort_order, include_delta_closure):
692
 
        for key in keys:
693
 
            text = self._load_text(key)
694
 
            if text is None:
695
 
                yield AbsentContentFactory(key)
696
 
            else:
697
 
                yield FulltextContentFactory(key, None, None, text)
698
 
 
699
 
    def keys(self):
700
 
        if not self._is_locked():
701
 
            raise errors.ObjectNotLocked(self)
702
 
        relpaths = set()
703
 
        for quoted_relpath in self._transport.iter_files_recursive():
704
 
            relpath = urllib.unquote(quoted_relpath)
705
 
            path, ext = os.path.splitext(relpath)
706
 
            if ext == '.gz':
707
 
                relpath = path
708
 
            if not relpath.endswith('.sig'):
709
 
                continue
710
 
            relpaths.add(relpath[:-4])
711
 
        paths = list(relpaths)
712
 
        return set([self._mapper.unmap(path) for path in paths])
 
583
        text_store = self._get_text_store(repo_transport, control_files)
 
584
        control_store = self._get_control_store(repo_transport, control_files)
 
585
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
586
        return WeaveMetaDirRepository(_format=self,
 
587
            a_bzrdir=a_bzrdir,
 
588
            control_files=control_files,
 
589
            _revision_store=_revision_store,
 
590
            control_store=control_store,
 
591
            text_store=text_store)
 
592
 
 
593
 
 
594
class WeaveCommitBuilder(CommitBuilder):
 
595
    """A builder for weave based repos that don't support ghosts."""
 
596
 
 
597
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
 
598
        versionedfile = self.repository.weave_store.get_weave_or_empty(
 
599
            file_id, self.repository.get_transaction())
 
600
        result = versionedfile.add_lines(
 
601
            self._new_revision_id, parents, new_lines,
 
602
            nostore_sha=nostore_sha)[0:2]
 
603
        versionedfile.clear_cache()
 
604
        return result
 
605
 
713
606
 
714
607
_legacy_formats = [RepositoryFormat4(),
715
608
                   RepositoryFormat5(),