/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5590.1.5 by John Arbash Meinel
Don't use tuned_gzip.GzipFile in knit.py
1
# Copyright (C) 2006-2011 Canonical Ltd
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
16
17
"""Knit versionedfile implementation.
18
19
A knit is a versioned file implementation that supports efficient append only
20
updates.
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
21
22
Knit file layout:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
23
lifeless: the data file is made up of "delta records".  each delta record has a delta header
24
that contains; (1) a version id, (2) the size of the delta (in lines), and (3)  the digest of
25
the -expanded data- (ie, the delta applied to the parent).  the delta also ends with a
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
26
end-marker; simply "end VERSION"
27
28
delta can be line or full contents.a
29
... the 8's there are the index number of the annotation.
30
version robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad 7 c7d23b2a5bd6ca00e8e266cec0ec228158ee9f9e
31
59,59,3
32
8
33
8         if ie.executable:
34
8             e.set('executable', 'yes')
35
130,130,2
36
8         if elt.get('executable') == 'yes':
37
8             ie.executable = True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
38
end robertc@robertcollins.net-20051003014215-ee2990904cc4c7ad
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
39
40
41
whats in an index:
42
09:33 < jrydberg> lifeless: each index is made up of a tuple of; version id, options, position, size, parents
43
09:33 < jrydberg> lifeless: the parents are currently dictionary compressed
44
09:33 < jrydberg> lifeless: (meaning it currently does not support ghosts)
45
09:33 < lifeless> right
46
09:33 < jrydberg> lifeless: the position and size is the range in the data file
47
48
49
so the index sequence is the dictionary compressed sequence number used
50
in the deltas to provide line annotation
51
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
52
"""
53
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
54
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
55
from cStringIO import StringIO
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
56
from itertools import izip
1756.2.17 by Aaron Bentley
Fixes suggested by John Meinel
57
import operator
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
58
import os
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
59
import sys
1594.2.19 by Robert Collins
More coalescing tweaks, and knit feedback.
60
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
61
from bzrlib.lazy_import import lazy_import
62
lazy_import(globals(), """
5671.1.2 by Jelmer Vernooij
Lazy load gzip (we don't use it when doing 2a), remove some unused imports.
63
import gzip
64
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
65
from bzrlib import (
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
66
    debug,
67
    diff,
3224.1.10 by John Arbash Meinel
Introduce the heads_provider for reannotate.
68
    graph as _mod_graph,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
69
    index as _mod_index,
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
70
    pack,
5279.1.1 by Andrew Bennetts
lazy_import most things in merge.py; add a few representative modules to the import tariff tests; tweak a couple of other modules so that patiencediff is not necessarily imported; remove a bunch of unused imports from test_knit.py.
71
    patiencediff,
4789.28.3 by John Arbash Meinel
Add a static_tuple.as_tuples() helper.
72
    static_tuple,
2745.1.2 by Robert Collins
Ensure mutter_callsite is not directly called on a lazy_load object, to make the stacklevel parameter work correctly.
73
    trace,
3224.5.1 by Andrew Bennetts
Lots of assorted hackery to reduce the number of imports for common operations. Improves 'rocks', 'st' and 'help' times by ~50ms on my laptop.
74
    tsort,
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
75
    tuned_gzip,
4961.2.13 by Martin Pool
Further progress bar string-pulling
76
    ui,
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
77
    )
78
""")
1911.2.3 by John Arbash Meinel
Moving everything into a new location so that we can cache more than just revision ids
79
from bzrlib import (
5753.2.2 by Jelmer Vernooij
Remove some unnecessary imports, clean up lazy imports.
80
    annotate,
1911.2.3 by John Arbash Meinel
Moving everything into a new location so that we can cache more than just revision ids
81
    errors,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
82
    osutils,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
83
    )
84
from bzrlib.errors import (
85
    NoSuchFile,
86
    InvalidRevisionId,
87
    KnitCorrupt,
88
    KnitHeaderError,
89
    RevisionNotPresent,
3787.1.1 by Robert Collins
Embed the failed text in sha1 knit errors.
90
    SHA1KnitCorrupt,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
91
    )
92
from bzrlib.osutils import (
93
    contains_whitespace,
2850.1.1 by Robert Collins
* ``KnitVersionedFile.add*`` will no longer cache added records even when
94
    sha_string,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
95
    sha_strings,
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
96
    split_lines,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
97
    )
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
98
from bzrlib.versionedfile import (
3350.3.12 by Robert Collins
Generate streams with absent records.
99
    AbsentContentFactory,
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
100
    adapter_registry,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
101
    ConstantMapper,
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
102
    ContentFactory,
4111.1.1 by Robert Collins
Add a groupcompress sort order.
103
    sort_groupcompress,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
104
    VersionedFiles,
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
105
    )
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
106
107
108
# TODO: Split out code specific to this format into an associated object.
109
110
# TODO: Can we put in some kind of value to check that the index and data
111
# files belong together?
112
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
113
# TODO: accommodate binaries, perhaps by storing a byte count
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
114
115
# TODO: function to check whole file
116
117
# TODO: atomically append data, then measure backwards from the cursor
118
# position after writing to work out where it was located.  we may need to
119
# bypass python file buffering.
120
121
DATA_SUFFIX = '.knit'
122
INDEX_SUFFIX = '.kndx'
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
123
_STREAM_MIN_BUFFER_SIZE = 5*1024*1024
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
124
125
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
126
class KnitAdapter(object):
127
    """Base class for knit record adaption."""
128
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
129
    def __init__(self, basis_vf):
130
        """Create an adapter which accesses full texts from basis_vf.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
131
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
132
        :param basis_vf: A versioned file to access basis texts of deltas from.
133
            May be None for adapters that do not need to access basis texts.
134
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
135
        self._data = KnitVersionedFiles(None, None)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
136
        self._annotate_factory = KnitAnnotateFactory()
137
        self._plain_factory = KnitPlainFactory()
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
138
        self._basis_vf = basis_vf
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
139
140
141
class FTAnnotatedToUnannotated(KnitAdapter):
142
    """An adapter from FT annotated knits to unannotated ones."""
143
4005.3.1 by Robert Collins
Change the signature on VersionedFiles adapters to allow less typing and more flexability inside adapters.
144
    def get_bytes(self, factory):
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
145
        annotated_compressed_bytes = factory._raw_record
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
146
        rec, contents = \
147
            self._data._parse_record_unchecked(annotated_compressed_bytes)
148
        content = self._annotate_factory.parse_fulltext(contents, rec[1])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
149
        size, bytes = self._data._record_to_data((rec[1],), rec[3], content.text())
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
150
        return bytes
151
152
153
class DeltaAnnotatedToUnannotated(KnitAdapter):
154
    """An adapter for deltas from annotated to unannotated."""
155
4005.3.1 by Robert Collins
Change the signature on VersionedFiles adapters to allow less typing and more flexability inside adapters.
156
    def get_bytes(self, factory):
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
157
        annotated_compressed_bytes = factory._raw_record
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
158
        rec, contents = \
159
            self._data._parse_record_unchecked(annotated_compressed_bytes)
160
        delta = self._annotate_factory.parse_line_delta(contents, rec[1],
161
            plain=True)
162
        contents = self._plain_factory.lower_line_delta(delta)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
163
        size, bytes = self._data._record_to_data((rec[1],), rec[3], contents)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
164
        return bytes
165
166
167
class FTAnnotatedToFullText(KnitAdapter):
168
    """An adapter from FT annotated knits to unannotated ones."""
169
4005.3.1 by Robert Collins
Change the signature on VersionedFiles adapters to allow less typing and more flexability inside adapters.
170
    def get_bytes(self, factory):
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
171
        annotated_compressed_bytes = factory._raw_record
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
172
        rec, contents = \
173
            self._data._parse_record_unchecked(annotated_compressed_bytes)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
174
        content, delta = self._annotate_factory.parse_record(factory.key[-1],
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
175
            contents, factory._build_details, None)
176
        return ''.join(content.text())
177
178
179
class DeltaAnnotatedToFullText(KnitAdapter):
180
    """An adapter for deltas from annotated to unannotated."""
181
4005.3.1 by Robert Collins
Change the signature on VersionedFiles adapters to allow less typing and more flexability inside adapters.
182
    def get_bytes(self, factory):
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
183
        annotated_compressed_bytes = factory._raw_record
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
184
        rec, contents = \
185
            self._data._parse_record_unchecked(annotated_compressed_bytes)
186
        delta = self._annotate_factory.parse_line_delta(contents, rec[1],
187
            plain=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
188
        compression_parent = factory.parents[0]
189
        basis_entry = self._basis_vf.get_record_stream(
190
            [compression_parent], 'unordered', True).next()
191
        if basis_entry.storage_kind == 'absent':
192
            raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
193
        basis_chunks = basis_entry.get_bytes_as('chunked')
194
        basis_lines = osutils.chunks_to_lines(basis_chunks)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
195
        # Manually apply the delta because we have one annotated content and
196
        # one plain.
197
        basis_content = PlainKnitContent(basis_lines, compression_parent)
198
        basis_content.apply_delta(delta, rec[1])
199
        basis_content._should_strip_eol = factory._build_details[1]
200
        return ''.join(basis_content.text())
201
202
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
203
class FTPlainToFullText(KnitAdapter):
204
    """An adapter from FT plain knits to unannotated ones."""
205
4005.3.1 by Robert Collins
Change the signature on VersionedFiles adapters to allow less typing and more flexability inside adapters.
206
    def get_bytes(self, factory):
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
207
        compressed_bytes = factory._raw_record
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
208
        rec, contents = \
209
            self._data._parse_record_unchecked(compressed_bytes)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
210
        content, delta = self._plain_factory.parse_record(factory.key[-1],
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
211
            contents, factory._build_details, None)
212
        return ''.join(content.text())
213
214
215
class DeltaPlainToFullText(KnitAdapter):
216
    """An adapter for deltas from annotated to unannotated."""
217
4005.3.1 by Robert Collins
Change the signature on VersionedFiles adapters to allow less typing and more flexability inside adapters.
218
    def get_bytes(self, factory):
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
219
        compressed_bytes = factory._raw_record
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
220
        rec, contents = \
221
            self._data._parse_record_unchecked(compressed_bytes)
222
        delta = self._plain_factory.parse_line_delta(contents, rec[1])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
223
        compression_parent = factory.parents[0]
224
        # XXX: string splitting overhead.
225
        basis_entry = self._basis_vf.get_record_stream(
226
            [compression_parent], 'unordered', True).next()
227
        if basis_entry.storage_kind == 'absent':
228
            raise errors.RevisionNotPresent(compression_parent, self._basis_vf)
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
229
        basis_chunks = basis_entry.get_bytes_as('chunked')
230
        basis_lines = osutils.chunks_to_lines(basis_chunks)
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
231
        basis_content = PlainKnitContent(basis_lines, compression_parent)
232
        # Manually apply the delta because we have one annotated content and
233
        # one plain.
234
        content, _ = self._plain_factory.parse_record(rec[1], contents,
235
            factory._build_details, basis_content)
236
        return ''.join(content.text())
237
238
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
239
class KnitContentFactory(ContentFactory):
240
    """Content factory for streaming from knits.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
241
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
242
    :seealso ContentFactory:
243
    """
244
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
245
    def __init__(self, key, parents, build_details, sha1, raw_record,
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
246
        annotated, knit=None, network_bytes=None):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
247
        """Create a KnitContentFactory for key.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
248
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
249
        :param key: The key.
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
250
        :param parents: The parents.
251
        :param build_details: The build details as returned from
252
            get_build_details.
253
        :param sha1: The sha1 expected from the full text of this object.
254
        :param raw_record: The bytes of the knit data from disk.
255
        :param annotated: True if the raw data is annotated.
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
256
        :param network_bytes: None to calculate the network bytes on demand,
257
            not-none if they are already known.
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
258
        """
259
        ContentFactory.__init__(self)
260
        self.sha1 = sha1
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
261
        self.key = key
262
        self.parents = parents
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
263
        if build_details[0] == 'line-delta':
264
            kind = 'delta'
265
        else:
266
            kind = 'ft'
267
        if annotated:
268
            annotated_kind = 'annotated-'
269
        else:
270
            annotated_kind = ''
271
        self.storage_kind = 'knit-%s%s-gz' % (annotated_kind, kind)
272
        self._raw_record = raw_record
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
273
        self._network_bytes = network_bytes
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
274
        self._build_details = build_details
275
        self._knit = knit
276
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
277
    def _create_network_bytes(self):
278
        """Create a fully serialised network version for transmission."""
279
        # storage_kind, key, parents, Noeol, raw_record
280
        key_bytes = '\x00'.join(self.key)
281
        if self.parents is None:
282
            parent_bytes = 'None:'
283
        else:
284
            parent_bytes = '\t'.join('\x00'.join(key) for key in self.parents)
285
        if self._build_details[1]:
286
            noeol = 'N'
287
        else:
288
            noeol = ' '
289
        network_bytes = "%s\n%s\n%s\n%s%s" % (self.storage_kind, key_bytes,
290
            parent_bytes, noeol, self._raw_record)
291
        self._network_bytes = network_bytes
292
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
293
    def get_bytes_as(self, storage_kind):
294
        if storage_kind == self.storage_kind:
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
295
            if self._network_bytes is None:
296
                self._create_network_bytes()
297
            return self._network_bytes
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
298
        if ('-ft-' in self.storage_kind and
299
            storage_kind in ('chunked', 'fulltext')):
300
            adapter_key = (self.storage_kind, 'fulltext')
301
            adapter_factory = adapter_registry.get(adapter_key)
302
            adapter = adapter_factory(None)
303
            bytes = adapter.get_bytes(self)
304
            if storage_kind == 'chunked':
305
                return [bytes]
306
            else:
307
                return bytes
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
308
        if self._knit is not None:
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
309
            # Not redundant with direct conversion above - that only handles
310
            # fulltext cases.
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
311
            if storage_kind == 'chunked':
312
                return self._knit.get_lines(self.key[0])
313
            elif storage_kind == 'fulltext':
314
                return self._knit.get_text(self.key[0])
315
        raise errors.UnavailableRepresentation(self.key, storage_kind,
316
            self.storage_kind)
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
317
318
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
319
class LazyKnitContentFactory(ContentFactory):
320
    """A ContentFactory which can either generate full text or a wire form.
321
322
    :seealso ContentFactory:
323
    """
324
325
    def __init__(self, key, parents, generator, first):
326
        """Create a LazyKnitContentFactory.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
327
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
328
        :param key: The key of the record.
329
        :param parents: The parents of the record.
330
        :param generator: A _ContentMapGenerator containing the record for this
331
            key.
332
        :param first: Is this the first content object returned from generator?
333
            if it is, its storage kind is knit-delta-closure, otherwise it is
334
            knit-delta-closure-ref
335
        """
336
        self.key = key
337
        self.parents = parents
338
        self.sha1 = None
339
        self._generator = generator
340
        self.storage_kind = "knit-delta-closure"
341
        if not first:
342
            self.storage_kind = self.storage_kind + "-ref"
343
        self._first = first
344
345
    def get_bytes_as(self, storage_kind):
346
        if storage_kind == self.storage_kind:
347
            if self._first:
348
                return self._generator._wire_bytes()
349
            else:
350
                # all the keys etc are contained in the bytes returned in the
351
                # first record.
352
                return ''
353
        if storage_kind in ('chunked', 'fulltext'):
354
            chunks = self._generator._get_one_work(self.key).text()
355
            if storage_kind == 'chunked':
356
                return chunks
357
            else:
358
                return ''.join(chunks)
359
        raise errors.UnavailableRepresentation(self.key, storage_kind,
360
            self.storage_kind)
361
362
363
def knit_delta_closure_to_records(storage_kind, bytes, line_end):
364
    """Convert a network record to a iterator over stream records.
365
366
    :param storage_kind: The storage kind of the record.
367
        Must be 'knit-delta-closure'.
368
    :param bytes: The bytes of the record on the network.
369
    """
370
    generator = _NetworkContentMapGenerator(bytes, line_end)
371
    return generator.get_record_stream()
372
373
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
374
def knit_network_to_record(storage_kind, bytes, line_end):
375
    """Convert a network record to a record object.
376
377
    :param storage_kind: The storage kind of the record.
378
    :param bytes: The bytes of the record on the network.
379
    """
380
    start = line_end
381
    line_end = bytes.find('\n', start)
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
382
    key = tuple(bytes[start:line_end].split('\x00'))
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
383
    start = line_end + 1
384
    line_end = bytes.find('\n', start)
385
    parent_line = bytes[start:line_end]
386
    if parent_line == 'None:':
387
        parents = None
388
    else:
389
        parents = tuple(
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
390
            [tuple(segment.split('\x00')) for segment in parent_line.split('\t')
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
391
             if segment])
392
    start = line_end + 1
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
393
    noeol = bytes[start] == 'N'
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
394
    if 'ft' in storage_kind:
395
        method = 'fulltext'
396
    else:
397
        method = 'line-delta'
398
    build_details = (method, noeol)
399
    start = start + 1
400
    raw_record = bytes[start:]
401
    annotated = 'annotated' in storage_kind
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
402
    return [KnitContentFactory(key, parents, build_details, None, raw_record,
403
        annotated, network_bytes=bytes)]
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
404
405
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
406
class KnitContent(object):
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
407
    """Content of a knit version to which deltas can be applied.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
408
3468.2.5 by Martin Pool
Correct comment and remove overbroad except block
409
    This is always stored in memory as a list of lines with \n at the end,
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
410
    plus a flag saying if the final ending is really there or not, because that
3468.2.5 by Martin Pool
Correct comment and remove overbroad except block
411
    corresponds to the on-disk knit representation.
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
412
    """
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
413
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
414
    def __init__(self):
415
        self._should_strip_eol = False
416
2921.2.1 by Robert Collins
* Knit text reconstruction now avoids making copies of the lines list for
417
    def apply_delta(self, delta, new_version_id):
2921.2.2 by Robert Collins
Review feedback.
418
        """Apply delta to this object to become new_version_id."""
2921.2.1 by Robert Collins
* Knit text reconstruction now avoids making copies of the lines list for
419
        raise NotImplementedError(self.apply_delta)
420
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
421
    def line_delta_iter(self, new_lines):
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
422
        """Generate line-based delta from this content to new_lines."""
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
423
        new_texts = new_lines.text()
424
        old_texts = self.text()
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
425
        s = patiencediff.PatienceSequenceMatcher(None, old_texts, new_texts)
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
426
        for tag, i1, i2, j1, j2 in s.get_opcodes():
427
            if tag == 'equal':
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
428
                continue
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
429
            # ofrom, oto, length, data
430
            yield i1, i2, j2 - j1, new_lines._lines[j1:j2]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
431
432
    def line_delta(self, new_lines):
433
        return list(self.line_delta_iter(new_lines))
434
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
435
    @staticmethod
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
436
    def get_line_delta_blocks(knit_delta, source, target):
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
437
        """Extract SequenceMatcher.get_matching_blocks() from a knit delta"""
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
438
        target_len = len(target)
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
439
        s_pos = 0
440
        t_pos = 0
441
        for s_begin, s_end, t_len, new_text in knit_delta:
2520.4.47 by Aaron Bentley
Fix get_line_delta_blocks with eol
442
            true_n = s_begin - s_pos
443
            n = true_n
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
444
            if n > 0:
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
445
                # knit deltas do not provide reliable info about whether the
446
                # last line of a file matches, due to eol handling.
447
                if source[s_pos + n -1] != target[t_pos + n -1]:
2520.4.47 by Aaron Bentley
Fix get_line_delta_blocks with eol
448
                    n-=1
449
                if n > 0:
450
                    yield s_pos, t_pos, n
451
            t_pos += t_len + true_n
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
452
            s_pos = s_end
2520.4.48 by Aaron Bentley
Support getting blocks from knit deltas with no final EOL
453
        n = target_len - t_pos
454
        if n > 0:
455
            if source[s_pos + n -1] != target[t_pos + n -1]:
456
                n-=1
457
            if n > 0:
458
                yield s_pos, t_pos, n
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
459
        yield s_pos + (target_len - t_pos), target_len, 0
460
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
461
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
462
class AnnotatedKnitContent(KnitContent):
463
    """Annotated content."""
464
465
    def __init__(self, lines):
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
466
        KnitContent.__init__(self)
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
467
        self._lines = lines
468
3316.2.13 by Robert Collins
* ``VersionedFile.annotate_iter`` is deprecated. While in principal this
469
    def annotate(self):
470
        """Return a list of (origin, text) for each content line."""
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
471
        lines = self._lines[:]
472
        if self._should_strip_eol:
473
            origin, last_line = lines[-1]
474
            lines[-1] = (origin, last_line.rstrip('\n'))
475
        return lines
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
476
2921.2.1 by Robert Collins
* Knit text reconstruction now avoids making copies of the lines list for
477
    def apply_delta(self, delta, new_version_id):
2921.2.2 by Robert Collins
Review feedback.
478
        """Apply delta to this object to become new_version_id."""
2921.2.1 by Robert Collins
* Knit text reconstruction now avoids making copies of the lines list for
479
        offset = 0
480
        lines = self._lines
481
        for start, end, count, delta_lines in delta:
482
            lines[offset+start:offset+end] = delta_lines
483
            offset = offset + (start - end) + count
484
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
485
    def text(self):
2911.1.1 by Martin Pool
Better messages when problems are detected inside a knit
486
        try:
3224.1.22 by John Arbash Meinel
Cleanup the extra debugging info, and some >80 char lines.
487
            lines = [text for origin, text in self._lines]
2911.1.1 by Martin Pool
Better messages when problems are detected inside a knit
488
        except ValueError, e:
489
            # most commonly (only?) caused by the internal form of the knit
490
            # missing annotation information because of a bug - see thread
491
            # around 20071015
492
            raise KnitCorrupt(self,
493
                "line in annotated knit missing annotation information: %s"
494
                % (e,))
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
495
        if self._should_strip_eol:
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
496
            lines[-1] = lines[-1].rstrip('\n')
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
497
        return lines
498
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
499
    def copy(self):
500
        return AnnotatedKnitContent(self._lines[:])
501
502
503
class PlainKnitContent(KnitContent):
2794.1.3 by Robert Collins
Review feedback.
504
    """Unannotated content.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
505
2794.1.3 by Robert Collins
Review feedback.
506
    When annotate[_iter] is called on this content, the same version is reported
507
    for all lines. Generally, annotate[_iter] is not useful on PlainKnitContent
508
    objects.
509
    """
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
510
511
    def __init__(self, lines, version_id):
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
512
        KnitContent.__init__(self)
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
513
        self._lines = lines
514
        self._version_id = version_id
515
3316.2.13 by Robert Collins
* ``VersionedFile.annotate_iter`` is deprecated. While in principal this
516
    def annotate(self):
517
        """Return a list of (origin, text) for each content line."""
518
        return [(self._version_id, line) for line in self._lines]
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
519
2921.2.1 by Robert Collins
* Knit text reconstruction now avoids making copies of the lines list for
520
    def apply_delta(self, delta, new_version_id):
2921.2.2 by Robert Collins
Review feedback.
521
        """Apply delta to this object to become new_version_id."""
2921.2.1 by Robert Collins
* Knit text reconstruction now avoids making copies of the lines list for
522
        offset = 0
523
        lines = self._lines
524
        for start, end, count, delta_lines in delta:
525
            lines[offset+start:offset+end] = delta_lines
526
            offset = offset + (start - end) + count
527
        self._version_id = new_version_id
528
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
529
    def copy(self):
530
        return PlainKnitContent(self._lines[:], self._version_id)
531
532
    def text(self):
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
533
        lines = self._lines
534
        if self._should_strip_eol:
535
            lines = lines[:]
536
            lines[-1] = lines[-1].rstrip('\n')
537
        return lines
538
539
540
class _KnitFactory(object):
541
    """Base class for common Factory functions."""
542
543
    def parse_record(self, version_id, record, record_details,
544
                     base_content, copy_base_content=True):
545
        """Parse a record into a full content object.
546
547
        :param version_id: The official version id for this content
548
        :param record: The data returned by read_records_iter()
549
        :param record_details: Details about the record returned by
550
            get_build_details
551
        :param base_content: If get_build_details returns a compression_parent,
552
            you must return a base_content here, else use None
553
        :param copy_base_content: When building from the base_content, decide
554
            you can either copy it and return a new object, or modify it in
555
            place.
556
        :return: (content, delta) A Content object and possibly a line-delta,
557
            delta may be None
558
        """
559
        method, noeol = record_details
560
        if method == 'line-delta':
561
            if copy_base_content:
562
                content = base_content.copy()
563
            else:
564
                content = base_content
565
            delta = self.parse_line_delta(record, version_id)
566
            content.apply_delta(delta, version_id)
567
        else:
568
            content = self.parse_fulltext(record, version_id)
569
            delta = None
570
        content._should_strip_eol = noeol
571
        return (content, delta)
572
573
574
class KnitAnnotateFactory(_KnitFactory):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
575
    """Factory for creating annotated Content objects."""
576
577
    annotated = True
578
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
579
    def make(self, lines, version_id):
580
        num_lines = len(lines)
581
        return AnnotatedKnitContent(zip([version_id] * num_lines, lines))
582
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
583
    def parse_fulltext(self, content, version_id):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
584
        """Convert fulltext to internal representation
585
586
        fulltext content is of the format
587
        revid(utf8) plaintext\n
588
        internal representation is of the format:
589
        (revid, plaintext)
590
        """
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
591
        # TODO: jam 20070209 The tests expect this to be returned as tuples,
592
        #       but the code itself doesn't really depend on that.
593
        #       Figure out a way to not require the overhead of turning the
594
        #       list back into tuples.
595
        lines = [tuple(line.split(' ', 1)) for line in content]
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
596
        return AnnotatedKnitContent(lines)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
597
598
    def parse_line_delta_iter(self, lines):
2163.1.2 by John Arbash Meinel
Don't modify the list during parse_line_delta
599
        return iter(self.parse_line_delta(lines))
1628.1.2 by Robert Collins
More knit micro-optimisations.
600
2851.4.2 by Ian Clatworthy
use factory methods in annotated-to-plain conversion instead of duplicating format knowledge
601
    def parse_line_delta(self, lines, version_id, plain=False):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
602
        """Convert a line based delta into internal representation.
603
604
        line delta is in the form of:
605
        intstart intend intcount
606
        1..count lines:
607
        revid(utf8) newline\n
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
608
        internal representation is
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
609
        (start, end, count, [1..count tuples (revid, newline)])
2851.4.2 by Ian Clatworthy
use factory methods in annotated-to-plain conversion instead of duplicating format knowledge
610
611
        :param plain: If True, the lines are returned as a plain
2911.1.1 by Martin Pool
Better messages when problems are detected inside a knit
612
            list without annotations, not as a list of (origin, content) tuples, i.e.
2851.4.2 by Ian Clatworthy
use factory methods in annotated-to-plain conversion instead of duplicating format knowledge
613
            (start, end, count, [1..count newline])
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
614
        """
1628.1.2 by Robert Collins
More knit micro-optimisations.
615
        result = []
616
        lines = iter(lines)
617
        next = lines.next
2249.5.1 by John Arbash Meinel
Leave revision-ids in utf-8 when reading.
618
2249.5.15 by John Arbash Meinel
remove get_cached_utf8 checks which were slowing things down.
619
        cache = {}
620
        def cache_and_return(line):
621
            origin, text = line.split(' ', 1)
622
            return cache.setdefault(origin, origin), text
623
1628.1.2 by Robert Collins
More knit micro-optimisations.
624
        # walk through the lines parsing.
2851.4.2 by Ian Clatworthy
use factory methods in annotated-to-plain conversion instead of duplicating format knowledge
625
        # Note that the plain test is explicitly pulled out of the
626
        # loop to minimise any performance impact
627
        if plain:
628
            for header in lines:
629
                start, end, count = [int(n) for n in header.split(',')]
630
                contents = [next().split(' ', 1)[1] for i in xrange(count)]
631
                result.append((start, end, count, contents))
632
        else:
633
            for header in lines:
634
                start, end, count = [int(n) for n in header.split(',')]
635
                contents = [tuple(next().split(' ', 1)) for i in xrange(count)]
636
                result.append((start, end, count, contents))
1628.1.2 by Robert Collins
More knit micro-optimisations.
637
        return result
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
638
2163.2.2 by John Arbash Meinel
Don't deal with annotations when we don't care about them. Saves another 300+ms
639
    def get_fulltext_content(self, lines):
640
        """Extract just the content lines from a fulltext."""
641
        return (line.split(' ', 1)[1] for line in lines)
642
643
    def get_linedelta_content(self, lines):
644
        """Extract just the content from a line delta.
645
646
        This doesn't return all of the extra information stored in a delta.
647
        Only the actual content lines.
648
        """
649
        lines = iter(lines)
650
        next = lines.next
651
        for header in lines:
652
            header = header.split(',')
653
            count = int(header[2])
654
            for i in xrange(count):
655
                origin, text = next().split(' ', 1)
656
                yield text
657
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
658
    def lower_fulltext(self, content):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
659
        """convert a fulltext content record into a serializable form.
660
661
        see parse_fulltext which this inverts.
662
        """
2249.5.15 by John Arbash Meinel
remove get_cached_utf8 checks which were slowing things down.
663
        return ['%s %s' % (o, t) for o, t in content._lines]
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
664
665
    def lower_line_delta(self, delta):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
666
        """convert a delta into a serializable form.
667
1628.1.2 by Robert Collins
More knit micro-optimisations.
668
        See parse_line_delta which this inverts.
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
669
        """
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
670
        # TODO: jam 20070209 We only do the caching thing to make sure that
671
        #       the origin is a valid utf-8 line, eventually we could remove it
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
672
        out = []
673
        for start, end, c, lines in delta:
674
            out.append('%d,%d,%d\n' % (start, end, c))
2249.5.15 by John Arbash Meinel
remove get_cached_utf8 checks which were slowing things down.
675
            out.extend(origin + ' ' + text
1911.2.1 by John Arbash Meinel
Cache encode/decode operations, saves memory and time. Especially when committing a new kernel tree with 7.7M new lines to annotate
676
                       for origin, text in lines)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
677
        return out
678
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
679
    def annotate(self, knit, key):
680
        content = knit._get_content(key)
681
        # adjust for the fact that serialised annotations are only key suffixes
682
        # for this factory.
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
683
        if type(key) is tuple:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
684
            prefix = key[:-1]
685
            origins = content.annotate()
686
            result = []
687
            for origin, line in origins:
688
                result.append((prefix + (origin,), line))
689
            return result
690
        else:
3350.6.10 by Martin Pool
VersionedFiles review cleanups
691
            # XXX: This smells a bit.  Why would key ever be a non-tuple here?
692
            # Aren't keys defined to be tuples?  -- spiv 20080618
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
693
            return content.annotate()
2770.1.1 by Aaron Bentley
Initial implmentation of plain knit annotation
694
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
695
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
696
class KnitPlainFactory(_KnitFactory):
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
697
    """Factory for creating plain Content objects."""
698
699
    annotated = False
700
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
701
    def make(self, lines, version_id):
702
        return PlainKnitContent(lines, version_id)
703
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
704
    def parse_fulltext(self, content, version_id):
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
705
        """This parses an unannotated fulltext.
706
707
        Note that this is not a noop - the internal representation
708
        has (versionid, line) - its just a constant versionid.
709
        """
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
710
        return self.make(content, version_id)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
711
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
712
    def parse_line_delta_iter(self, lines, version_id):
2163.1.2 by John Arbash Meinel
Don't modify the list during parse_line_delta
713
        cur = 0
714
        num_lines = len(lines)
715
        while cur < num_lines:
716
            header = lines[cur]
717
            cur += 1
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
718
            start, end, c = [int(n) for n in header.split(',')]
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
719
            yield start, end, c, lines[cur:cur+c]
2163.1.2 by John Arbash Meinel
Don't modify the list during parse_line_delta
720
            cur += c
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
721
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
722
    def parse_line_delta(self, lines, version_id):
723
        return list(self.parse_line_delta_iter(lines, version_id))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
724
2163.2.2 by John Arbash Meinel
Don't deal with annotations when we don't care about them. Saves another 300+ms
725
    def get_fulltext_content(self, lines):
726
        """Extract just the content lines from a fulltext."""
727
        return iter(lines)
728
729
    def get_linedelta_content(self, lines):
730
        """Extract just the content from a line delta.
731
732
        This doesn't return all of the extra information stored in a delta.
733
        Only the actual content lines.
734
        """
735
        lines = iter(lines)
736
        next = lines.next
737
        for header in lines:
738
            header = header.split(',')
739
            count = int(header[2])
740
            for i in xrange(count):
741
                yield next()
742
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
743
    def lower_fulltext(self, content):
744
        return content.text()
745
746
    def lower_line_delta(self, delta):
747
        out = []
748
        for start, end, c, lines in delta:
749
            out.append('%d,%d,%d\n' % (start, end, c))
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
750
            out.extend(lines)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
751
        return out
752
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
753
    def annotate(self, knit, key):
3224.1.7 by John Arbash Meinel
_StreamIndex also needs to return the proper values for get_build_details.
754
        annotator = _KnitAnnotator(knit)
4454.3.26 by John Arbash Meinel
The new _KnitAnnotator based on Annotator seems to pass the test suite.
755
        return annotator.annotate_flat(key)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
756
757
758
759
def make_file_factory(annotated, mapper):
760
    """Create a factory for creating a file based KnitVersionedFiles.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
761
762
    This is only functional enough to run interface tests, it doesn't try to
763
    provide a full pack environment.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
764
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
765
    :param annotated: knit annotations are wanted.
766
    :param mapper: The mapper from keys to paths.
767
    """
768
    def factory(transport):
769
        index = _KndxIndex(transport, mapper, lambda:None, lambda:True, lambda:True)
770
        access = _KnitKeyAccess(transport, mapper)
771
        return KnitVersionedFiles(index, access, annotated=annotated)
772
    return factory
773
774
775
def make_pack_factory(graph, delta, keylength):
776
    """Create a factory for creating a pack based VersionedFiles.
777
778
    This is only functional enough to run interface tests, it doesn't try to
779
    provide a full pack environment.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
780
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
781
    :param graph: Store a graph.
782
    :param delta: Delta compress contents.
783
    :param keylength: How long should keys be.
784
    """
785
    def factory(transport):
786
        parents = graph or delta
787
        ref_length = 0
788
        if graph:
789
            ref_length += 1
790
        if delta:
791
            ref_length += 1
792
            max_delta_chain = 200
793
        else:
794
            max_delta_chain = 0
795
        graph_index = _mod_index.InMemoryGraphIndex(reference_lists=ref_length,
796
            key_elements=keylength)
797
        stream = transport.open_write_stream('newpack')
798
        writer = pack.ContainerWriter(stream.write)
799
        writer.begin()
800
        index = _KnitGraphIndex(graph_index, lambda:True, parents=parents,
801
            deltas=delta, add_callback=graph_index.add_nodes)
5757.1.3 by Jelmer Vernooij
Revert noknit branch for the moment.
802
        access = _DirectPackAccess({})
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
803
        access.set_writer(writer, graph_index, (transport, 'newpack'))
804
        result = KnitVersionedFiles(index, access,
805
            max_delta_chain=max_delta_chain)
806
        result.stream = stream
807
        result.writer = writer
808
        return result
809
    return factory
810
811
812
def cleanup_pack_knit(versioned_files):
813
    versioned_files.stream.close()
814
    versioned_files.writer.end()
815
816
4039.3.5 by John Arbash Meinel
Add direct tests for _get_total_build_size.
817
def _get_total_build_size(self, keys, positions):
4039.3.4 by John Arbash Meinel
Properly determine the total number of bytes needed for a given key.
818
    """Determine the total bytes to build these keys.
819
820
    (helper function because _KnitGraphIndex and _KndxIndex work the same, but
821
    don't inherit from a common base.)
822
823
    :param keys: Keys that we want to build
824
    :param positions: dict of {key, (info, index_memo, comp_parent)} (such
825
        as returned by _get_components_positions)
826
    :return: Number of bytes to build those keys
827
    """
828
    all_build_index_memos = {}
829
    build_keys = keys
830
    while build_keys:
831
        next_keys = set()
832
        for key in build_keys:
833
            # This is mostly for the 'stacked' case
834
            # Where we will be getting the data from a fallback
835
            if key not in positions:
836
                continue
837
            _, index_memo, compression_parent = positions[key]
838
            all_build_index_memos[key] = index_memo
839
            if compression_parent not in all_build_index_memos:
840
                next_keys.add(compression_parent)
841
        build_keys = next_keys
842
    return sum([index_memo[2] for index_memo
843
                in all_build_index_memos.itervalues()])
844
845
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
846
class KnitVersionedFiles(VersionedFiles):
847
    """Storage for many versioned files using knit compression.
848
849
    Backend storage is managed by indices and data objects.
3582.1.14 by Martin Pool
Clearer comments about KnitVersionedFile stacking
850
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
851
    :ivar _index: A _KnitGraphIndex or similar that can describe the
852
        parents, graph, compression and data location of entries in this
853
        KnitVersionedFiles.  Note that this is only the index for
3582.1.16 by Martin Pool
Review feedback and news entry
854
        *this* vfs; if there are fallbacks they must be queried separately.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
855
    """
856
857
    def __init__(self, index, data_access, max_delta_chain=200,
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
858
                 annotated=False, reload_func=None):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
859
        """Create a KnitVersionedFiles with index and data_access.
860
861
        :param index: The index for the knit data.
862
        :param data_access: The access object to store and retrieve knit
863
            records.
864
        :param max_delta_chain: The maximum number of deltas to permit during
865
            insertion. Set to 0 to prohibit the use of deltas.
866
        :param annotated: Set to True to cause annotations to be calculated and
867
            stored during insertion.
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
868
        :param reload_func: An function that can be called if we think we need
869
            to reload the pack listing and try again. See
870
            'bzrlib.repofmt.pack_repo.AggregateIndex' for the signature.
1563.2.25 by Robert Collins
Merge in upstream.
871
        """
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
872
        self._index = index
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
873
        self._access = data_access
874
        self._max_delta_chain = max_delta_chain
875
        if annotated:
876
            self._factory = KnitAnnotateFactory()
877
        else:
878
            self._factory = KnitPlainFactory()
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
879
        self._immediate_fallback_vfs = []
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
880
        self._reload_func = reload_func
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
881
3702.1.1 by Martin Pool
Add repr for KnitVersionedFiles
882
    def __repr__(self):
883
        return "%s(%r, %r)" % (
884
            self.__class__.__name__,
885
            self._index,
886
            self._access)
887
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
888
    def add_fallback_versioned_files(self, a_versioned_files):
889
        """Add a source of texts for texts not present in this knit.
890
891
        :param a_versioned_files: A VersionedFiles object.
892
        """
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
893
        self._immediate_fallback_vfs.append(a_versioned_files)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
894
895
    def add_lines(self, key, parents, lines, parent_texts=None,
896
        left_matching_blocks=None, nostore_sha=None, random_id=False,
897
        check_content=True):
898
        """See VersionedFiles.add_lines()."""
899
        self._index._check_write_ok()
900
        self._check_add(key, lines, random_id, check_content)
901
        if parents is None:
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
902
            # The caller might pass None if there is no graph data, but kndx
903
            # indexes can't directly store that, so we give them
904
            # an empty tuple instead.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
905
            parents = ()
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
906
        line_bytes = ''.join(lines)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
907
        return self._add(key, lines, parents,
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
908
            parent_texts, left_matching_blocks, nostore_sha, random_id,
909
            line_bytes=line_bytes)
910
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
911
    def _add_text(self, key, parents, text, nostore_sha=None, random_id=False):
4398.9.1 by Matt Nordhoff
Update _add_text docstrings that still referred to add_text.
912
        """See VersionedFiles._add_text()."""
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
913
        self._index._check_write_ok()
914
        self._check_add(key, None, random_id, check_content=False)
915
        if text.__class__ is not str:
4398.8.5 by John Arbash Meinel
Fix a few more cases where we were adding a list rather than an empty string.
916
            raise errors.BzrBadParameterUnicode("text")
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
917
        if parents is None:
918
            # The caller might pass None if there is no graph data, but kndx
919
            # indexes can't directly store that, so we give them
920
            # an empty tuple instead.
921
            parents = ()
922
        return self._add(key, None, parents,
4398.8.6 by John Arbash Meinel
Switch the api from VF.add_text to VF._add_text and trim some extra 'features'.
923
            None, None, nostore_sha, random_id,
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
924
            line_bytes=text)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
925
926
    def _add(self, key, lines, parents, parent_texts,
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
927
        left_matching_blocks, nostore_sha, random_id,
928
        line_bytes):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
929
        """Add a set of lines on top of version specified by parents.
930
931
        Any versions not present will be converted into ghosts.
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
932
933
        :param lines: A list of strings where each one is a single line (has a
934
            single newline at the end of the string) This is now optional
935
            (callers can pass None). It is left in its location for backwards
936
            compatibility. It should ''.join(lines) must == line_bytes
937
        :param line_bytes: A single string containing the content
938
939
        We pass both lines and line_bytes because different routes bring the
940
        values to this function. And for memory efficiency, we don't want to
941
        have to split/join on-demand.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
942
        """
943
        # first thing, if the content is something we don't need to store, find
944
        # that out.
945
        digest = sha_string(line_bytes)
946
        if nostore_sha == digest:
947
            raise errors.ExistingContent
948
949
        present_parents = []
950
        if parent_texts is None:
951
            parent_texts = {}
3830.3.9 by Martin Pool
Simplify kvf insert_record_stream; add has_key shorthand methods; update stacking effort tests
952
        # Do a single query to ascertain parent presence; we only compress
953
        # against parents in the same kvf.
954
        present_parent_map = self._index.get_parent_map(parents)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
955
        for parent in parents:
956
            if parent in present_parent_map:
957
                present_parents.append(parent)
958
959
        # Currently we can only compress against the left most present parent.
960
        if (len(present_parents) == 0 or
961
            present_parents[0] != parents[0]):
962
            delta = False
963
        else:
964
            # To speed the extract of texts the delta chain is limited
965
            # to a fixed number of deltas.  This should minimize both
966
            # I/O and the time spend applying deltas.
967
            delta = self._check_should_delta(present_parents[0])
968
969
        text_length = len(line_bytes)
970
        options = []
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
971
        no_eol = False
972
        # Note: line_bytes is not modified to add a newline, that is tracked
973
        #       via the no_eol flag. 'lines' *is* modified, because that is the
974
        #       general values needed by the Content code.
975
        if line_bytes and line_bytes[-1] != '\n':
976
            options.append('no-eol')
977
            no_eol = True
978
            # Copy the existing list, or create a new one
979
            if lines is None:
980
                lines = osutils.split_lines(line_bytes)
981
            else:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
982
                lines = lines[:]
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
983
            # Replace the last line with one that ends in a final newline
984
            lines[-1] = lines[-1] + '\n'
985
        if lines is None:
986
            lines = osutils.split_lines(line_bytes)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
987
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
988
        for element in key[:-1]:
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
989
            if type(element) is not str:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
990
                raise TypeError("key contains non-strings: %r" % (key,))
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
991
        if key[-1] is None:
992
            key = key[:-1] + ('sha1:' + digest,)
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
993
        elif type(key[-1]) is not str:
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
994
                raise TypeError("key contains non-strings: %r" % (key,))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
995
        # Knit hunks are still last-element only
996
        version_id = key[-1]
997
        content = self._factory.make(lines, version_id)
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
998
        if no_eol:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
999
            # Hint to the content object that its text() call should strip the
1000
            # EOL.
1001
            content._should_strip_eol = True
1002
        if delta or (self._factory.annotated and len(present_parents) > 0):
1003
            # Merge annotations from parent texts if needed.
1004
            delta_hunks = self._merge_annotations(content, present_parents,
1005
                parent_texts, delta, self._factory.annotated,
1006
                left_matching_blocks)
1007
1008
        if delta:
1009
            options.append('line-delta')
1010
            store_lines = self._factory.lower_line_delta(delta_hunks)
1011
            size, bytes = self._record_to_data(key, digest,
1012
                store_lines)
1013
        else:
1014
            options.append('fulltext')
1015
            # isinstance is slower and we have no hierarchy.
4088.3.1 by Benjamin Peterson
compare types with 'is' not ==
1016
            if self._factory.__class__ is KnitPlainFactory:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1017
                # Use the already joined bytes saving iteration time in
1018
                # _record_to_data.
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
1019
                dense_lines = [line_bytes]
1020
                if no_eol:
1021
                    dense_lines.append('\n')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1022
                size, bytes = self._record_to_data(key, digest,
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
1023
                    lines, dense_lines)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1024
            else:
1025
                # get mixed annotation + content and feed it into the
1026
                # serialiser.
1027
                store_lines = self._factory.lower_fulltext(content)
1028
                size, bytes = self._record_to_data(key, digest,
1029
                    store_lines)
1030
1031
        access_memo = self._access.add_raw_records([(key, size)], bytes)[0]
1032
        self._index.add_records(
1033
            ((key, options, access_memo, parents),),
1034
            random_id=random_id)
1035
        return digest, text_length, content
1036
1037
    def annotate(self, key):
1038
        """See VersionedFiles.annotate."""
1039
        return self._factory.annotate(self, key)
1040
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
1041
    def get_annotator(self):
1042
        return _KnitAnnotator(self)
1043
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1044
    def check(self, progress_bar=None, keys=None):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1045
        """See VersionedFiles.check()."""
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1046
        if keys is None:
1047
            return self._logical_check()
1048
        else:
1049
            # At the moment, check does not extra work over get_record_stream
1050
            return self.get_record_stream(keys, 'unordered', True)
1051
1052
    def _logical_check(self):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1053
        # This doesn't actually test extraction of everything, but that will
1054
        # impact 'bzr check' substantially, and needs to be integrated with
1055
        # care. However, it does check for the obvious problem of a delta with
1056
        # no basis.
3517.4.14 by Martin Pool
KnitVersionedFiles.check should just check its own keys then recurse into fallbacks
1057
        keys = self._index.keys()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1058
        parent_map = self.get_parent_map(keys)
1059
        for key in keys:
1060
            if self._index.get_method(key) != 'fulltext':
1061
                compression_parent = parent_map[key][0]
1062
                if compression_parent not in parent_map:
1063
                    raise errors.KnitCorrupt(self,
1064
                        "Missing basis parent %s for %s" % (
1065
                        compression_parent, key))
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1066
        for fallback_vfs in self._immediate_fallback_vfs:
3517.4.14 by Martin Pool
KnitVersionedFiles.check should just check its own keys then recurse into fallbacks
1067
            fallback_vfs.check()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1068
1069
    def _check_add(self, key, lines, random_id, check_content):
1070
        """check that version_id and lines are safe to add."""
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1071
        version_id = key[-1]
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
1072
        if version_id is not None:
1073
            if contains_whitespace(version_id):
1074
                raise InvalidRevisionId(version_id, self)
1075
            self.check_not_reserved_id(version_id)
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
1076
        # TODO: If random_id==False and the key is already present, we should
1077
        # probably check that the existing content is identical to what is
1078
        # being inserted, and otherwise raise an exception.  This would make
1079
        # the bundle code simpler.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1080
        if check_content:
1081
            self._check_lines_not_unicode(lines)
1082
            self._check_lines_are_lines(lines)
1083
1084
    def _check_header(self, key, line):
1085
        rec = self._split_header(line)
1086
        self._check_header_version(rec, key[-1])
1087
        return rec
1088
1089
    def _check_header_version(self, rec, version_id):
1090
        """Checks the header version on original format knit records.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1091
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1092
        These have the last component of the key embedded in the record.
1093
        """
1094
        if rec[1] != version_id:
1095
            raise KnitCorrupt(self,
1096
                'unexpected version, wanted %r, got %r' % (version_id, rec[1]))
1097
1098
    def _check_should_delta(self, parent):
2147.1.1 by John Arbash Meinel
Factor the common knit delta selection into a helper func, and allow the fulltext to be chosen based on cumulative delta size
1099
        """Iterate back through the parent listing, looking for a fulltext.
1100
1101
        This is used when we want to decide whether to add a delta or a new
1102
        fulltext. It searches for _max_delta_chain parents. When it finds a
1103
        fulltext parent, it sees if the total size of the deltas leading up to
1104
        it is large enough to indicate that we want a new full text anyway.
1105
1106
        Return True if we should create a new delta, False if we should use a
1107
        full text.
1108
        """
1109
        delta_size = 0
1110
        fulltext_size = None
2147.1.2 by John Arbash Meinel
Simplify the knit max-chain detection code.
1111
        for count in xrange(self._max_delta_chain):
3350.8.9 by Robert Collins
define behaviour for add_lines with stacked storage.
1112
            try:
3582.1.14 by Martin Pool
Clearer comments about KnitVersionedFile stacking
1113
                # Note that this only looks in the index of this particular
1114
                # KnitVersionedFiles, not in the fallbacks.  This ensures that
1115
                # we won't store a delta spanning physical repository
1116
                # boundaries.
3915.3.1 by John Arbash Meinel
As part of _check_should_delta, use the get_build_details api.
1117
                build_details = self._index.get_build_details([parent])
1118
                parent_details = build_details[parent]
3973.1.1 by John Arbash Meinel
Trivially fix a bug in _check_should_delta when a parent is not present.
1119
            except (RevisionNotPresent, KeyError), e:
3915.3.1 by John Arbash Meinel
As part of _check_should_delta, use the get_build_details api.
1120
                # Some basis is not locally present: always fulltext
3350.8.9 by Robert Collins
define behaviour for add_lines with stacked storage.
1121
                return False
3915.3.1 by John Arbash Meinel
As part of _check_should_delta, use the get_build_details api.
1122
            index_memo, compression_parent, _, _ = parent_details
1123
            _, _, size = index_memo
1124
            if compression_parent is None:
2147.1.1 by John Arbash Meinel
Factor the common knit delta selection into a helper func, and allow the fulltext to be chosen based on cumulative delta size
1125
                fulltext_size = size
1126
                break
1127
            delta_size += size
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
1128
            # We don't explicitly check for presence because this is in an
1129
            # inner loop, and if it's missing it'll fail anyhow.
3915.3.1 by John Arbash Meinel
As part of _check_should_delta, use the get_build_details api.
1130
            parent = compression_parent
2147.1.2 by John Arbash Meinel
Simplify the knit max-chain detection code.
1131
        else:
1132
            # We couldn't find a fulltext, so we must create a new one
2147.1.1 by John Arbash Meinel
Factor the common knit delta selection into a helper func, and allow the fulltext to be chosen based on cumulative delta size
1133
            return False
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1134
        # Simple heuristic - if the total I/O wold be greater as a delta than
1135
        # the originally installed fulltext, we create a new fulltext.
2147.1.2 by John Arbash Meinel
Simplify the knit max-chain detection code.
1136
        return fulltext_size > delta_size
2147.1.1 by John Arbash Meinel
Factor the common knit delta selection into a helper func, and allow the fulltext to be chosen based on cumulative delta size
1137
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1138
    def _build_details_to_components(self, build_details):
1139
        """Convert a build_details tuple to a position tuple."""
1140
        # record_details, access_memo, compression_parent
1141
        return build_details[3], build_details[0], build_details[1]
1142
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1143
    def _get_components_positions(self, keys, allow_missing=False):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1144
        """Produce a map of position data for the components of keys.
1145
1146
        This data is intended to be used for retrieving the knit records.
1147
1148
        A dict of key to (record_details, index_memo, next, parents) is
1149
        returned.
1150
        method is the way referenced data should be applied.
1151
        index_memo is the handle to pass to the data access to actually get the
1152
            data
1153
        next is the build-parent of the version, or None for fulltexts.
1154
        parents is the version_ids of the parents of this version
1155
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1156
        :param allow_missing: If True do not raise an error on a missing component,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1157
            just ignore it.
1158
        """
1159
        component_data = {}
1160
        pending_components = keys
1161
        while pending_components:
1162
            build_details = self._index.get_build_details(pending_components)
1163
            current_components = set(pending_components)
1164
            pending_components = set()
1165
            for key, details in build_details.iteritems():
1166
                (index_memo, compression_parent, parents,
1167
                 record_details) = details
1168
                method = record_details[0]
1169
                if compression_parent is not None:
1170
                    pending_components.add(compression_parent)
1171
                component_data[key] = self._build_details_to_components(details)
1172
            missing = current_components.difference(build_details)
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1173
            if missing and not allow_missing:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1174
                raise errors.RevisionNotPresent(missing.pop(), self)
1175
        return component_data
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1176
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1177
    def _get_content(self, key, parent_texts={}):
1178
        """Returns a content object that makes up the specified
1179
        version."""
1180
        cached_version = parent_texts.get(key, None)
1181
        if cached_version is not None:
1182
            # Ensure the cache dict is valid.
1183
            if not self.get_parent_map([key]):
1184
                raise RevisionNotPresent(key, self)
1185
            return cached_version
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1186
        generator = _VFContentMapGenerator(self, [key])
1187
        return generator._get_content(key)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1188
4593.5.20 by John Arbash Meinel
Expose KnownGraph off of VersionedFiles
1189
    def get_known_graph_ancestry(self, keys):
1190
        """Get a KnownGraph instance with the ancestry of keys."""
4593.5.36 by John Arbash Meinel
a few more implementations of the interface.
1191
        parent_map, missing_keys = self._index.find_ancestry(keys)
5050.70.2 by Martin Pool
Search all fallbacks for get_known_graph_ancestry
1192
        for fallback in self._transitive_fallbacks():
4634.11.2 by John Arbash Meinel
Teach VF.get_known_graph_ancestry to go to fallbacks (bug #419241)
1193
            if not missing_keys:
1194
                break
1195
            (f_parent_map, f_missing_keys) = fallback._index.find_ancestry(
1196
                                                missing_keys)
1197
            parent_map.update(f_parent_map)
1198
            missing_keys = f_missing_keys
4593.5.20 by John Arbash Meinel
Expose KnownGraph off of VersionedFiles
1199
        kg = _mod_graph.KnownGraph(parent_map)
1200
        return kg
1201
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1202
    def get_parent_map(self, keys):
3517.4.17 by Martin Pool
Redo base Repository.get_parent_map to use .revisions graph
1203
        """Get a map of the graph parents of keys.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1204
1205
        :param keys: The keys to look up parents for.
1206
        :return: A mapping from keys to parents. Absent keys are absent from
1207
            the mapping.
1208
        """
3350.8.14 by Robert Collins
Review feedback.
1209
        return self._get_parent_map_with_sources(keys)[0]
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1210
3350.8.14 by Robert Collins
Review feedback.
1211
    def _get_parent_map_with_sources(self, keys):
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1212
        """Get a map of the parents of keys.
1213
1214
        :param keys: The keys to look up parents for.
1215
        :return: A tuple. The first element is a mapping from keys to parents.
1216
            Absent keys are absent from the mapping. The second element is a
1217
            list with the locations each key was found in. The first element
1218
            is the in-this-knit parents, the second the first fallback source,
1219
            and so on.
1220
        """
3350.8.2 by Robert Collins
stacked get_parent_map.
1221
        result = {}
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1222
        sources = [self._index] + self._immediate_fallback_vfs
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1223
        source_results = []
3350.8.2 by Robert Collins
stacked get_parent_map.
1224
        missing = set(keys)
1225
        for source in sources:
1226
            if not missing:
1227
                break
1228
            new_result = source.get_parent_map(missing)
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1229
            source_results.append(new_result)
3350.8.2 by Robert Collins
stacked get_parent_map.
1230
            result.update(new_result)
1231
            missing.difference_update(set(new_result))
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1232
        return result, source_results
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1233
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1234
    def _get_record_map(self, keys, allow_missing=False):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1235
        """Produce a dictionary of knit records.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1236
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1237
        :return: {key:(record, record_details, digest, next)}
1238
            record
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1239
                data returned from read_records (a KnitContentobject)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1240
            record_details
1241
                opaque information to pass to parse_record
1242
            digest
1243
                SHA1 digest of the full text after all steps are done
1244
            next
1245
                build-parent of the version, i.e. the leftmost ancestor.
1246
                Will be None if the record is not a delta.
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1247
        :param keys: The keys to build a map for
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1248
        :param allow_missing: If some records are missing, rather than
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1249
            error, just return the data that could be generated.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1250
        """
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1251
        raw_map = self._get_record_map_unparsed(keys,
1252
            allow_missing=allow_missing)
1253
        return self._raw_map_to_record_map(raw_map)
1254
1255
    def _raw_map_to_record_map(self, raw_map):
1256
        """Parse the contents of _get_record_map_unparsed.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
1257
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1258
        :return: see _get_record_map.
1259
        """
1260
        result = {}
1261
        for key in raw_map:
1262
            data, record_details, next = raw_map[key]
1263
            content, digest = self._parse_record(key[-1], data)
1264
            result[key] = content, record_details, digest, next
1265
        return result
1266
1267
    def _get_record_map_unparsed(self, keys, allow_missing=False):
1268
        """Get the raw data for reconstructing keys without parsing it.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
1269
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1270
        :return: A dict suitable for parsing via _raw_map_to_record_map.
1271
            key-> raw_bytes, (method, noeol), compression_parent
1272
        """
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
1273
        # This retries the whole request if anything fails. Potentially we
1274
        # could be a bit more selective. We could track the keys whose records
1275
        # we have successfully found, and then only request the new records
1276
        # from there. However, _get_components_positions grabs the whole build
1277
        # chain, which means we'll likely try to grab the same records again
4005.3.7 by Robert Collins
Review feedback.
1278
        # anyway. Also, can the build chains change as part of a pack
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
1279
        # operation? We wouldn't want to end up with a broken chain.
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
1280
        while True:
1281
            try:
1282
                position_map = self._get_components_positions(keys,
1283
                    allow_missing=allow_missing)
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
1284
                # key = component_id, r = record_details, i_m = index_memo,
1285
                # n = next
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
1286
                records = [(key, i_m) for key, (r, i_m, n)
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
1287
                                       in position_map.iteritems()]
4039.3.1 by John Arbash Meinel
Group records to read by pack file and sort by offset.
1288
                # Sort by the index memo, so that we request records from the
1289
                # same pack file together, and in forward-sorted order
1290
                records.sort(key=operator.itemgetter(1))
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1291
                raw_record_map = {}
1292
                for key, data in self._read_records_iter_unchecked(records):
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
1293
                    (record_details, index_memo, next) = position_map[key]
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1294
                    raw_record_map[key] = data, record_details, next
1295
                return raw_record_map
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
1296
            except errors.RetryWithNewPacks, e:
1297
                self._access.reload_or_raise(e)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1298
4039.3.6 by John Arbash Meinel
Turn _split_by_prefix into a classmethod, and add direct tests.
1299
    @classmethod
1300
    def _split_by_prefix(cls, keys):
3763.4.1 by John Arbash Meinel
Possible fix for bug #269456.
1301
        """For the given keys, split them up based on their prefix.
1302
1303
        To keep memory pressure somewhat under control, split the
1304
        requests back into per-file-id requests, otherwise "bzr co"
1305
        extracts the full tree into memory before writing it to disk.
1306
        This should be revisited if _get_content_maps() can ever cross
1307
        file-id boundaries.
1308
4039.3.6 by John Arbash Meinel
Turn _split_by_prefix into a classmethod, and add direct tests.
1309
        The keys for a given file_id are kept in the same relative order.
1310
        Ordering between file_ids is not, though prefix_order will return the
1311
        order that the key was first seen.
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1312
3763.4.1 by John Arbash Meinel
Possible fix for bug #269456.
1313
        :param keys: An iterable of key tuples
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1314
        :return: (split_map, prefix_order)
1315
            split_map       A dictionary mapping prefix => keys
1316
            prefix_order    The order that we saw the various prefixes
3763.4.1 by John Arbash Meinel
Possible fix for bug #269456.
1317
        """
1318
        split_by_prefix = {}
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1319
        prefix_order = []
3763.4.1 by John Arbash Meinel
Possible fix for bug #269456.
1320
        for key in keys:
1321
            if len(key) == 1:
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1322
                prefix = ''
1323
            else:
1324
                prefix = key[0]
1325
1326
            if prefix in split_by_prefix:
1327
                split_by_prefix[prefix].append(key)
1328
            else:
1329
                split_by_prefix[prefix] = [key]
1330
                prefix_order.append(prefix)
1331
        return split_by_prefix, prefix_order
1332
4039.3.7 by John Arbash Meinel
Some direct tests for _group_keys_for_io
1333
    def _group_keys_for_io(self, keys, non_local_keys, positions,
1334
                           _min_buffer_size=_STREAM_MIN_BUFFER_SIZE):
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1335
        """For the given keys, group them into 'best-sized' requests.
1336
1337
        The idea is to avoid making 1 request per file, but to never try to
1338
        unpack an entire 1.5GB source tree in a single pass. Also when
1339
        possible, we should try to group requests to the same pack file
1340
        together.
1341
4039.3.7 by John Arbash Meinel
Some direct tests for _group_keys_for_io
1342
        :return: list of (keys, non_local) tuples that indicate what keys
1343
            should be fetched next.
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1344
        """
1345
        # TODO: Ideally we would group on 2 factors. We want to extract texts
1346
        #       from the same pack file together, and we want to extract all
1347
        #       the texts for a given build-chain together. Ultimately it
1348
        #       probably needs a better global view.
4039.3.3 by John Arbash Meinel
Add some debugging code.
1349
        total_keys = len(keys)
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1350
        prefix_split_keys, prefix_order = self._split_by_prefix(keys)
1351
        prefix_split_non_local_keys, _ = self._split_by_prefix(non_local_keys)
1352
        cur_keys = []
1353
        cur_non_local = set()
1354
        cur_size = 0
4039.3.3 by John Arbash Meinel
Add some debugging code.
1355
        result = []
1356
        sizes = []
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1357
        for prefix in prefix_order:
1358
            keys = prefix_split_keys[prefix]
1359
            non_local = prefix_split_non_local_keys.get(prefix, [])
4039.3.4 by John Arbash Meinel
Properly determine the total number of bytes needed for a given key.
1360
1361
            this_size = self._index._get_total_build_size(keys, positions)
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1362
            cur_size += this_size
1363
            cur_keys.extend(keys)
1364
            cur_non_local.update(non_local)
4039.3.7 by John Arbash Meinel
Some direct tests for _group_keys_for_io
1365
            if cur_size > _min_buffer_size:
4039.3.3 by John Arbash Meinel
Add some debugging code.
1366
                result.append((cur_keys, cur_non_local))
1367
                sizes.append(cur_size)
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1368
                cur_keys = []
4039.3.4 by John Arbash Meinel
Properly determine the total number of bytes needed for a given key.
1369
                cur_non_local = set()
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1370
                cur_size = 0
1371
        if cur_keys:
4039.3.3 by John Arbash Meinel
Add some debugging code.
1372
            result.append((cur_keys, cur_non_local))
1373
            sizes.append(cur_size)
1374
        return result
3763.4.1 by John Arbash Meinel
Possible fix for bug #269456.
1375
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1376
    def get_record_stream(self, keys, ordering, include_delta_closure):
1377
        """Get a stream of records for keys.
1378
1379
        :param keys: The keys to include.
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
1380
        :param ordering: Either 'unordered' or 'topological'. A topologically
1381
            sorted stream has compression parents strictly before their
1382
            children.
1383
        :param include_delta_closure: If True then the closure across any
1384
            compression parents will be included (in the opaque data).
1385
        :return: An iterator of ContentFactory objects, each of which is only
1386
            valid until the iterator is advanced.
1387
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1388
        # keys might be a generator
1389
        keys = set(keys)
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1390
        if not keys:
1391
            return
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1392
        if not self._index.has_graph:
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1393
            # Cannot sort when no graph has been stored.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1394
            ordering = 'unordered'
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
1395
1396
        remaining_keys = keys
1397
        while True:
1398
            try:
1399
                keys = set(remaining_keys)
1400
                for content_factory in self._get_remaining_record_stream(keys,
1401
                                            ordering, include_delta_closure):
1402
                    remaining_keys.discard(content_factory.key)
1403
                    yield content_factory
1404
                return
1405
            except errors.RetryWithNewPacks, e:
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
1406
                self._access.reload_or_raise(e)
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
1407
1408
    def _get_remaining_record_stream(self, keys, ordering,
1409
                                     include_delta_closure):
3789.2.4 by John Arbash Meinel
Add a multiple-record test, though it isn't quite what we want for the readv tests.
1410
        """This function is the 'retry' portion for get_record_stream."""
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
1411
        if include_delta_closure:
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1412
            positions = self._get_components_positions(keys, allow_missing=True)
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
1413
        else:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1414
            build_details = self._index.get_build_details(keys)
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
1415
            # map from key to
1416
            # (record_details, access_memo, compression_parent_key)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1417
            positions = dict((key, self._build_details_to_components(details))
1418
                for key, details in build_details.iteritems())
1419
        absent_keys = keys.difference(set(positions))
1420
        # There may be more absent keys : if we're missing the basis component
1421
        # and are trying to include the delta closure.
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1422
        # XXX: We should not ever need to examine remote sources because we do
1423
        # not permit deltas across versioned files boundaries.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1424
        if include_delta_closure:
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1425
            needed_from_fallback = set()
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
1426
            # Build up reconstructable_keys dict.  key:True in this dict means
1427
            # the key can be reconstructed.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1428
            reconstructable_keys = {}
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1429
            for key in keys:
1430
                # the delta chain
1431
                try:
1432
                    chain = [key, positions[key][2]]
1433
                except KeyError:
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1434
                    needed_from_fallback.add(key)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1435
                    continue
1436
                result = True
1437
                while chain[-1] is not None:
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1438
                    if chain[-1] in reconstructable_keys:
1439
                        result = reconstructable_keys[chain[-1]]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1440
                        break
1441
                    else:
1442
                        try:
1443
                            chain.append(positions[chain[-1]][2])
1444
                        except KeyError:
1445
                            # missing basis component
3350.8.10 by Robert Collins
Stacked insert_record_stream.
1446
                            needed_from_fallback.add(chain[-1])
1447
                            result = True
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1448
                            break
1449
                for chain_key in chain[:-1]:
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1450
                    reconstructable_keys[chain_key] = result
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1451
                if not result:
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1452
                    needed_from_fallback.add(key)
1453
        # Double index lookups here : need a unified api ?
3350.8.14 by Robert Collins
Review feedback.
1454
        global_map, parent_maps = self._get_parent_map_with_sources(keys)
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1455
        if ordering in ('topological', 'groupcompress'):
1456
            if ordering == 'topological':
1457
                # Global topological sort
1458
                present_keys = tsort.topo_sort(global_map)
1459
            else:
1460
                present_keys = sort_groupcompress(global_map)
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1461
            # Now group by source:
1462
            source_keys = []
1463
            current_source = None
1464
            for key in present_keys:
1465
                for parent_map in parent_maps:
1466
                    if key in parent_map:
1467
                        key_source = parent_map
1468
                        break
1469
                if current_source is not key_source:
1470
                    source_keys.append((key_source, []))
1471
                    current_source = key_source
1472
                source_keys[-1][1].append(key)
1473
        else:
3606.7.7 by John Arbash Meinel
Add tests for the fetching behavior.
1474
            if ordering != 'unordered':
1475
                raise AssertionError('valid values for ordering are:'
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1476
                    ' "unordered", "groupcompress" or "topological" not: %r'
3606.7.7 by John Arbash Meinel
Add tests for the fetching behavior.
1477
                    % (ordering,))
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1478
            # Just group by source; remote sources first.
1479
            present_keys = []
1480
            source_keys = []
1481
            for parent_map in reversed(parent_maps):
1482
                source_keys.append((parent_map, []))
1483
                for key in parent_map:
1484
                    present_keys.append(key)
1485
                    source_keys[-1][1].append(key)
3878.1.1 by John Arbash Meinel
KVF.get_record_stream('unordered') now returns the records based on I/O ordering.
1486
            # We have been requested to return these records in an order that
3878.1.2 by John Arbash Meinel
Move the sorting into each index, and customize it for Kndx access.
1487
            # suits us. So we ask the index to give us an optimally sorted
1488
            # order.
3878.1.1 by John Arbash Meinel
KVF.get_record_stream('unordered') now returns the records based on I/O ordering.
1489
            for source, sub_keys in source_keys:
1490
                if source is parent_maps[0]:
3878.1.2 by John Arbash Meinel
Move the sorting into each index, and customize it for Kndx access.
1491
                    # Only sort the keys for this VF
1492
                    self._index._sort_keys_by_io(sub_keys, positions)
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1493
        absent_keys = keys - set(global_map)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1494
        for key in absent_keys:
1495
            yield AbsentContentFactory(key)
1496
        # restrict our view to the keys we can answer.
1497
        # XXX: Memory: TODO: batch data here to cap buffered data at (say) 1MB.
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1498
        # XXX: At that point we need to consider the impact of double reads by
1499
        # utilising components multiple times.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1500
        if include_delta_closure:
1501
            # XXX: get_content_maps performs its own index queries; allow state
1502
            # to be passed in.
3763.4.1 by John Arbash Meinel
Possible fix for bug #269456.
1503
            non_local_keys = needed_from_fallback - absent_keys
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
1504
            for keys, non_local_keys in self._group_keys_for_io(present_keys,
1505
                                                                non_local_keys,
1506
                                                                positions):
1507
                generator = _VFContentMapGenerator(self, keys, non_local_keys,
4537.3.1 by John Arbash Meinel
Start working on tests that get_record_stream gives reasonable results w/ stacking.
1508
                                                   global_map,
1509
                                                   ordering=ordering)
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1510
                for record in generator.get_record_stream():
1511
                    yield record
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1512
        else:
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1513
            for source, keys in source_keys:
1514
                if source is parent_maps[0]:
1515
                    # this KnitVersionedFiles
1516
                    records = [(key, positions[key][1]) for key in keys]
4082.1.1 by Andrew Bennetts
Use _read_records_iter_unchecked in _get_remaining_record_stream.
1517
                    for key, raw_data in self._read_records_iter_unchecked(records):
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1518
                        (record_details, index_memo, _) = positions[key]
1519
                        yield KnitContentFactory(key, global_map[key],
4082.1.1 by Andrew Bennetts
Use _read_records_iter_unchecked in _get_remaining_record_stream.
1520
                            record_details, None, raw_data, self._factory.annotated, None)
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1521
                else:
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1522
                    vf = self._immediate_fallback_vfs[parent_maps.index(source) - 1]
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1523
                    for record in vf.get_record_stream(keys, ordering,
1524
                        include_delta_closure):
1525
                        yield record
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1526
1527
    def get_sha1s(self, keys):
1528
        """See VersionedFiles.get_sha1s()."""
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1529
        missing = set(keys)
1530
        record_map = self._get_record_map(missing, allow_missing=True)
1531
        result = {}
1532
        for key, details in record_map.iteritems():
1533
            if key not in missing:
1534
                continue
1535
            # record entry 2 is the 'digest'.
1536
            result[key] = details[2]
1537
        missing.difference_update(set(result))
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1538
        for source in self._immediate_fallback_vfs:
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1539
            if not missing:
1540
                break
1541
            new_result = source.get_sha1s(missing)
1542
            result.update(new_result)
1543
            missing.difference_update(set(new_result))
1544
        return result
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1545
5195.3.27 by Parth Malwankar
code cleanup and comments.
1546
    def insert_record_stream(self, stream):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1547
        """Insert a record stream into this container.
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1548
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1549
        :param stream: A stream of records to insert.
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1550
        :return: None
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1551
        :seealso VersionedFiles.get_record_stream:
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1552
        """
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1553
        def get_adapter(adapter_key):
1554
            try:
1555
                return adapters[adapter_key]
1556
            except KeyError:
1557
                adapter_factory = adapter_registry.get(adapter_key)
1558
                adapter = adapter_factory(self)
1559
                adapters[adapter_key] = adapter
1560
                return adapter
3871.4.3 by John Arbash Meinel
We should only care if the compression parent is not available, not if all parents are available.
1561
        delta_types = set()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1562
        if self._factory.annotated:
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
1563
            # self is annotated, we need annotated knits to use directly.
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1564
            annotated = "annotated-"
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
1565
            convertibles = []
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1566
        else:
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
1567
            # self is not annotated, but we can strip annotations cheaply.
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1568
            annotated = ""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1569
            convertibles = set(["knit-annotated-ft-gz"])
1570
            if self._max_delta_chain:
3871.4.3 by John Arbash Meinel
We should only care if the compression parent is not available, not if all parents are available.
1571
                delta_types.add("knit-annotated-delta-gz")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1572
                convertibles.add("knit-annotated-delta-gz")
3350.3.22 by Robert Collins
Review feedback.
1573
        # The set of types we can cheaply adapt without needing basis texts.
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1574
        native_types = set()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1575
        if self._max_delta_chain:
1576
            native_types.add("knit-%sdelta-gz" % annotated)
3871.4.3 by John Arbash Meinel
We should only care if the compression parent is not available, not if all parents are available.
1577
            delta_types.add("knit-%sdelta-gz" % annotated)
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1578
        native_types.add("knit-%sft-gz" % annotated)
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
1579
        knit_types = native_types.union(convertibles)
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1580
        adapters = {}
3350.3.22 by Robert Collins
Review feedback.
1581
        # Buffer all index entries that we can't add immediately because their
3350.3.17 by Robert Collins
Prevent corrupt knits being created when a stream is interrupted with basis parents not present.
1582
        # basis parent is missing. We don't buffer all because generating
1583
        # annotations may require access to some of the new records. However we
1584
        # can't generate annotations from new deltas until their basis parent
1585
        # is present anyway, so we get away with not needing an index that
3350.3.22 by Robert Collins
Review feedback.
1586
        # includes the new keys.
3830.3.15 by Martin Pool
Check against all parents when deciding whether to store a fulltext in a stacked repository
1587
        #
1588
        # See <http://launchpad.net/bugs/300177> about ordering of compression
1589
        # parents in the records - to be conservative, we insist that all
1590
        # parents must be present to avoid expanding to a fulltext.
1591
        #
3350.3.17 by Robert Collins
Prevent corrupt knits being created when a stream is interrupted with basis parents not present.
1592
        # key = basis_parent, value = index entry to add
4009.3.7 by Andrew Bennetts
Most tests passing.
1593
        buffered_index_entries = {}
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1594
        for record in stream:
4082.1.3 by Andrew Bennetts
Add knit header paranoia to insert_record_stream to replace the paranoia removed from get_record_stream.
1595
            kind = record.storage_kind
1596
            if kind.startswith('knit-') and kind.endswith('-gz'):
1597
                # Check that the ID in the header of the raw knit bytes matches
1598
                # the record metadata.
1599
                raw_data = record._raw_record
1600
                df, rec = self._parse_record_header(record.key, raw_data)
1601
                df.close()
4052.1.2 by Robert Collins
Review feedback - fix flushing buffered records in knit's insert_record_stream.
1602
            buffered = False
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1603
            parents = record.parents
3871.4.3 by John Arbash Meinel
We should only care if the compression parent is not available, not if all parents are available.
1604
            if record.storage_kind in delta_types:
1605
                # TODO: eventually the record itself should track
1606
                #       compression_parent
1607
                compression_parent = parents[0]
1608
            else:
1609
                compression_parent = None
3350.3.15 by Robert Collins
Update the insert_record_stream contract to error if an absent record is provided.
1610
            # Raise an error when a record is missing.
1611
            if record.storage_kind == 'absent':
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1612
                raise RevisionNotPresent([record.key], self)
3830.3.15 by Martin Pool
Check against all parents when deciding whether to store a fulltext in a stacked repository
1613
            elif ((record.storage_kind in knit_types)
3871.4.3 by John Arbash Meinel
We should only care if the compression parent is not available, not if all parents are available.
1614
                  and (compression_parent is None
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1615
                       or not self._immediate_fallback_vfs
3871.4.3 by John Arbash Meinel
We should only care if the compression parent is not available, not if all parents are available.
1616
                       or self._index.has_key(compression_parent)
1617
                       or not self.has_key(compression_parent))):
3830.3.9 by Martin Pool
Simplify kvf insert_record_stream; add has_key shorthand methods; update stacking effort tests
1618
                # we can insert the knit record literally if either it has no
1619
                # compression parent OR we already have its basis in this kvf
1620
                # OR the basis is not present even in the fallbacks.  In the
1621
                # last case it will either turn up later in the stream and all
1622
                # will be well, or it won't turn up at all and we'll raise an
1623
                # error at the end.
3830.3.13 by Martin Pool
review cleanups to insert_record_stream
1624
                #
1625
                # TODO: self.has_key is somewhat redundant with
1626
                # self._index.has_key; we really want something that directly
1627
                # asks if it's only present in the fallbacks. -- mbp 20081119
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1628
                if record.storage_kind not in native_types:
1629
                    try:
1630
                        adapter_key = (record.storage_kind, "knit-delta-gz")
1631
                        adapter = get_adapter(adapter_key)
1632
                    except KeyError:
1633
                        adapter_key = (record.storage_kind, "knit-ft-gz")
1634
                        adapter = get_adapter(adapter_key)
4005.3.1 by Robert Collins
Change the signature on VersionedFiles adapters to allow less typing and more flexability inside adapters.
1635
                    bytes = adapter.get_bytes(record)
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1636
                else:
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
1637
                    # It's a knit record, it has a _raw_record field (even if
1638
                    # it was reconstituted from a network stream).
1639
                    bytes = record._raw_record
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1640
                options = [record._build_details[0]]
1641
                if record._build_details[1]:
1642
                    options.append('no-eol')
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
1643
                # Just blat it across.
1644
                # Note: This does end up adding data on duplicate keys. As
1645
                # modern repositories use atomic insertions this should not
1646
                # lead to excessive growth in the event of interrupted fetches.
1647
                # 'knit' repositories may suffer excessive growth, but as a
1648
                # deprecated format this is tolerable. It can be fixed if
1649
                # needed by in the kndx index support raising on a duplicate
1650
                # add with identical parents and options.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1651
                access_memo = self._access.add_raw_records(
1652
                    [(record.key, len(bytes))], bytes)[0]
1653
                index_entry = (record.key, options, access_memo, parents)
3350.3.17 by Robert Collins
Prevent corrupt knits being created when a stream is interrupted with basis parents not present.
1654
                if 'fulltext' not in options:
3830.3.24 by John Arbash Meinel
We don't require all parents to be present, just the compression parent.
1655
                    # Not a fulltext, so we need to make sure the compression
1656
                    # parent will also be present.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1657
                    # Note that pack backed knits don't need to buffer here
1658
                    # because they buffer all writes to the transaction level,
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1659
                    # but we don't expose that difference at the index level. If
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1660
                    # the query here has sufficient cost to show up in
1661
                    # profiling we should do that.
3830.3.24 by John Arbash Meinel
We don't require all parents to be present, just the compression parent.
1662
                    #
3830.3.7 by Martin Pool
KnitVersionedFiles.insert_record_stream checks that compression parents are in the same kvf, not in a fallback
1663
                    # They're required to be physically in this
1664
                    # KnitVersionedFiles, not in a fallback.
3871.4.3 by John Arbash Meinel
We should only care if the compression parent is not available, not if all parents are available.
1665
                    if not self._index.has_key(compression_parent):
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
1666
                        pending = buffered_index_entries.setdefault(
1667
                            compression_parent, [])
1668
                        pending.append(index_entry)
4009.3.9 by Andrew Bennetts
Remove some XXXs.
1669
                        buffered = True
1670
                if not buffered:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1671
                    self._index.add_records([index_entry])
3890.2.9 by John Arbash Meinel
Start using osutils.chunks_as_lines rather than osutils.split_lines.
1672
            elif record.storage_kind == 'chunked':
1673
                self.add_lines(record.key, parents,
1674
                    osutils.chunks_to_lines(record.get_bytes_as('chunked')))
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1675
            else:
4005.3.8 by Robert Collins
Handle record streams where a fulltext is obtainable from a record but not the storage_kind.
1676
                # Not suitable for direct insertion as a
3849.3.2 by Andrew Bennetts
Expand a comment inside insert_record_stream slightly.
1677
                # delta, either because it's not the right format, or this
1678
                # KnitVersionedFiles doesn't permit deltas (_max_delta_chain ==
1679
                # 0) or because it depends on a base only present in the
1680
                # fallback kvfs.
4187.3.6 by Andrew Bennetts
Move the flush in KnitVersionedFiles.insert_record_stream so that it covers the add_lines call of the fallback case, not just the adapter.get_bytes.
1681
                self._access.flush()
4005.3.8 by Robert Collins
Handle record streams where a fulltext is obtainable from a record but not the storage_kind.
1682
                try:
1683
                    # Try getting a fulltext directly from the record.
1684
                    bytes = record.get_bytes_as('fulltext')
1685
                except errors.UnavailableRepresentation:
1686
                    adapter_key = record.storage_kind, 'fulltext'
1687
                    adapter = get_adapter(adapter_key)
1688
                    bytes = adapter.get_bytes(record)
1689
                lines = split_lines(bytes)
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
1690
                try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1691
                    self.add_lines(record.key, parents, lines)
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
1692
                except errors.RevisionAlreadyPresent:
1693
                    pass
3350.3.17 by Robert Collins
Prevent corrupt knits being created when a stream is interrupted with basis parents not present.
1694
            # Add any records whose basis parent is now available.
4052.1.2 by Robert Collins
Review feedback - fix flushing buffered records in knit's insert_record_stream.
1695
            if not buffered:
1696
                added_keys = [record.key]
1697
                while added_keys:
1698
                    key = added_keys.pop(0)
1699
                    if key in buffered_index_entries:
1700
                        index_entries = buffered_index_entries[key]
1701
                        self._index.add_records(index_entries)
1702
                        added_keys.extend(
1703
                            [index_entry[0] for index_entry in index_entries])
1704
                        del buffered_index_entries[key]
4009.3.8 by Andrew Bennetts
Fix test failure.
1705
        if buffered_index_entries:
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
1706
            # There were index entries buffered at the end of the stream,
1707
            # So these need to be added (if the index supports holding such
1708
            # entries for later insertion)
4634.84.1 by Andrew Bennetts
Pass all buffered_index_entries together so that records that are buffered because their parent is buffered are not mistaken as having a missing parent.
1709
            all_entries = []
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
1710
            for key in buffered_index_entries:
1711
                index_entries = buffered_index_entries[key]
4634.84.1 by Andrew Bennetts
Pass all buffered_index_entries together so that records that are buffered because their parent is buffered are not mistaken as having a missing parent.
1712
                all_entries.extend(index_entries)
4634.84.2 by Andrew Bennetts
Add test.
1713
            self._index.add_records(
1714
                all_entries, missing_compression_parents=True)
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
1715
1716
    def get_missing_compression_parent_keys(self):
4009.3.3 by Andrew Bennetts
Add docstrings.
1717
        """Return an iterable of keys of missing compression parents.
1718
1719
        Check this after calling insert_record_stream to find out if there are
1720
        any missing compression parents.  If there are, the records that
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
1721
        depend on them are not able to be inserted safely. For atomic
1722
        KnitVersionedFiles built on packs, the transaction should be aborted or
1723
        suspended - commit will fail at this point. Nonatomic knits will error
1724
        earlier because they have no staging area to put pending entries into.
4009.3.3 by Andrew Bennetts
Add docstrings.
1725
        """
4009.3.7 by Andrew Bennetts
Most tests passing.
1726
        return self._index.get_missing_compression_parents()
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1727
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1728
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1729
        """Iterate over the lines in the versioned files from keys.
1730
1731
        This may return lines from other keys. Each item the returned
1732
        iterator yields is a tuple of a line and a text version that that line
1733
        is present in (not introduced in).
1734
1735
        Ordering of results is in whatever order is most suitable for the
1736
        underlying storage format.
1737
1738
        If a progress bar is supplied, it may be used to indicate progress.
1739
        The caller is responsible for cleaning up progress bars (because this
1740
        is an iterator).
1741
1742
        NOTES:
3830.3.17 by Martin Pool
Don't assume versions being unmentioned by iter_lines_added_or_changed implies the versions aren't present
1743
         * Lines are normalised by the underlying store: they will all have \\n
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1744
           terminators.
1745
         * Lines are returned in arbitrary order.
3830.3.17 by Martin Pool
Don't assume versions being unmentioned by iter_lines_added_or_changed implies the versions aren't present
1746
         * If a requested key did not change any lines (or didn't have any
1747
           lines), it may not be mentioned at all in the result.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1748
4110.2.10 by Martin Pool
Tweak iter_lines progress messages
1749
        :param pb: Progress bar supplied by caller.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1750
        :return: An iterator over (line, key).
1751
        """
1752
        if pb is None:
4961.2.2 by Martin Pool
Change some dummy progress bars to be real tasks
1753
            pb = ui.ui_factory.nested_progress_bar()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1754
        keys = set(keys)
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
1755
        total = len(keys)
3789.2.12 by John Arbash Meinel
iter_lines_added_or_present now retries.
1756
        done = False
1757
        while not done:
1758
            try:
1759
                # we don't care about inclusions, the caller cares.
1760
                # but we need to setup a list of records to visit.
1761
                # we need key, position, length
1762
                key_records = []
1763
                build_details = self._index.get_build_details(keys)
1764
                for key, details in build_details.iteritems():
1765
                    if key in keys:
1766
                        key_records.append((key, details[0]))
1767
                records_iter = enumerate(self._read_records_iter(key_records))
1768
                for (key_idx, (key, data, sha_value)) in records_iter:
4103.3.2 by Martin Pool
Remove trailing punctuation from progress messages
1769
                    pb.update('Walking content', key_idx, total)
3789.2.12 by John Arbash Meinel
iter_lines_added_or_present now retries.
1770
                    compression_parent = build_details[key][1]
1771
                    if compression_parent is None:
1772
                        # fulltext
1773
                        line_iterator = self._factory.get_fulltext_content(data)
1774
                    else:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1775
                        # Delta
3789.2.12 by John Arbash Meinel
iter_lines_added_or_present now retries.
1776
                        line_iterator = self._factory.get_linedelta_content(data)
1777
                    # Now that we are yielding the data for this key, remove it
1778
                    # from the list
1779
                    keys.remove(key)
1780
                    # XXX: It might be more efficient to yield (key,
1781
                    # line_iterator) in the future. However for now, this is a
1782
                    # simpler change to integrate into the rest of the
1783
                    # codebase. RBC 20071110
1784
                    for line in line_iterator:
1785
                        yield line, key
1786
                done = True
1787
            except errors.RetryWithNewPacks, e:
1788
                self._access.reload_or_raise(e)
3830.3.17 by Martin Pool
Don't assume versions being unmentioned by iter_lines_added_or_changed implies the versions aren't present
1789
        # If there are still keys we've not yet found, we look in the fallback
1790
        # vfs, and hope to find them there.  Note that if the keys are found
1791
        # but had no changes or no content, the fallback may not return
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1792
        # anything.
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1793
        if keys and not self._immediate_fallback_vfs:
3830.3.17 by Martin Pool
Don't assume versions being unmentioned by iter_lines_added_or_changed implies the versions aren't present
1794
            # XXX: strictly the second parameter is meant to be the file id
1795
            # but it's not easily accessible here.
1796
            raise RevisionNotPresent(keys, repr(self))
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
1797
        for source in self._immediate_fallback_vfs:
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
1798
            if not keys:
1799
                break
1800
            source_keys = set()
1801
            for line, key in source.iter_lines_added_or_present_in_keys(keys):
1802
                source_keys.add(key)
1803
                yield line, key
1804
            keys.difference_update(source_keys)
4103.3.2 by Martin Pool
Remove trailing punctuation from progress messages
1805
        pb.update('Walking content', total, total)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1806
1807
    def _make_line_delta(self, delta_seq, new_content):
1808
        """Generate a line delta from delta_seq and new_content."""
1809
        diff_hunks = []
1810
        for op in delta_seq.get_opcodes():
1811
            if op[0] == 'equal':
1812
                continue
1813
            diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
1814
        return diff_hunks
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1815
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
1816
    def _merge_annotations(self, content, parents, parent_texts={},
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
1817
                           delta=None, annotated=None,
1818
                           left_matching_blocks=None):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1819
        """Merge annotations for content and generate deltas.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1820
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1821
        This is done by comparing the annotations based on changes to the text
1822
        and generating a delta on the resulting full texts. If annotations are
1823
        not being created then a simple delta is created.
1596.2.27 by Robert Collins
Note potential improvements in knit adds.
1824
        """
2520.4.146 by Aaron Bentley
Avoid get_matching_blocks for un-annotated text
1825
        if left_matching_blocks is not None:
1826
            delta_seq = diff._PrematchedMatcher(left_matching_blocks)
1827
        else:
1828
            delta_seq = None
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
1829
        if annotated:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1830
            for parent_key in parents:
1831
                merge_content = self._get_content(parent_key, parent_texts)
1832
                if (parent_key == parents[0] and delta_seq is not None):
2520.4.146 by Aaron Bentley
Avoid get_matching_blocks for un-annotated text
1833
                    seq = delta_seq
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
1834
                else:
1835
                    seq = patiencediff.PatienceSequenceMatcher(
1836
                        None, merge_content.text(), content.text())
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
1837
                for i, j, n in seq.get_matching_blocks():
1838
                    if n == 0:
1839
                        continue
3460.2.1 by Robert Collins
* Inserting a bundle which changes the contents of a file with no trailing
1840
                    # this copies (origin, text) pairs across to the new
1841
                    # content for any line that matches the last-checked
2520.4.146 by Aaron Bentley
Avoid get_matching_blocks for un-annotated text
1842
                    # parent.
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
1843
                    content._lines[j:j+n] = merge_content._lines[i:i+n]
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1844
            # XXX: Robert says the following block is a workaround for a
1845
            # now-fixed bug and it can probably be deleted. -- mbp 20080618
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1846
            if content._lines and content._lines[-1][1][-1] != '\n':
1847
                # The copied annotation was from a line without a trailing EOL,
1848
                # reinstate one for the content object, to ensure correct
1849
                # serialization.
1850
                line = content._lines[-1][1] + '\n'
1851
                content._lines[-1] = (content._lines[-1][0], line)
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
1852
        if delta:
2520.4.146 by Aaron Bentley
Avoid get_matching_blocks for un-annotated text
1853
            if delta_seq is None:
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
1854
                reference_content = self._get_content(parents[0], parent_texts)
1855
                new_texts = content.text()
1856
                old_texts = reference_content.text()
2104.4.2 by John Arbash Meinel
Small cleanup and NEWS entry about fixing bug #65714
1857
                delta_seq = patiencediff.PatienceSequenceMatcher(
2100.2.1 by wang
Replace python's difflib by patiencediff because the worst case
1858
                                                 None, old_texts, new_texts)
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
1859
            return self._make_line_delta(delta_seq, content)
1860
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1861
    def _parse_record(self, version_id, data):
1862
        """Parse an original format knit record.
1863
1864
        These have the last element of the key only present in the stored data.
1865
        """
1866
        rec, record_contents = self._parse_record_unchecked(data)
1867
        self._check_header_version(rec, version_id)
1868
        return record_contents, rec[3]
1869
1870
    def _parse_record_header(self, key, raw_data):
1871
        """Parse a record header for consistency.
1872
1873
        :return: the header and the decompressor stream.
1874
                 as (stream, header_record)
1875
        """
5590.1.5 by John Arbash Meinel
Don't use tuned_gzip.GzipFile in knit.py
1876
        df = gzip.GzipFile(mode='rb', fileobj=StringIO(raw_data))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1877
        try:
1878
            # Current serialise
1879
            rec = self._check_header(key, df.readline())
1880
        except Exception, e:
1881
            raise KnitCorrupt(self,
1882
                              "While reading {%s} got %s(%s)"
1883
                              % (key, e.__class__.__name__, str(e)))
1884
        return df, rec
1885
1886
    def _parse_record_unchecked(self, data):
1887
        # profiling notes:
1888
        # 4168 calls in 2880 217 internal
1889
        # 4168 calls to _parse_record_header in 2121
1890
        # 4168 calls to readlines in 330
5590.1.5 by John Arbash Meinel
Don't use tuned_gzip.GzipFile in knit.py
1891
        df = gzip.GzipFile(mode='rb', fileobj=StringIO(data))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1892
        try:
1893
            record_contents = df.readlines()
1894
        except Exception, e:
1895
            raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
1896
                (data, e.__class__.__name__, str(e)))
1897
        header = record_contents.pop(0)
1898
        rec = self._split_header(header)
1899
        last_line = record_contents.pop()
1900
        if len(record_contents) != int(rec[2]):
1901
            raise KnitCorrupt(self,
1902
                              'incorrect number of lines %s != %s'
1903
                              ' for version {%s} %s'
1904
                              % (len(record_contents), int(rec[2]),
1905
                                 rec[1], record_contents))
1906
        if last_line != 'end %s\n' % rec[1]:
1907
            raise KnitCorrupt(self,
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1908
                              'unexpected version end line %r, wanted %r'
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1909
                              % (last_line, rec[1]))
1910
        df.close()
1911
        return rec, record_contents
1912
1913
    def _read_records_iter(self, records):
1914
        """Read text records from data file and yield result.
1915
1916
        The result will be returned in whatever is the fastest to read.
1917
        Not by the order requested. Also, multiple requests for the same
1918
        record will only yield 1 response.
1919
        :param records: A list of (key, access_memo) entries
1920
        :return: Yields (key, contents, digest) in the order
1921
                 read, not the order requested
1922
        """
1923
        if not records:
1924
            return
1925
1926
        # XXX: This smells wrong, IO may not be getting ordered right.
1927
        needed_records = sorted(set(records), key=operator.itemgetter(1))
1928
        if not needed_records:
1929
            return
1930
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1931
        # The transport optimizes the fetching as well
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1932
        # (ie, reads continuous ranges.)
1933
        raw_data = self._access.get_raw_records(
1934
            [index_memo for key, index_memo in needed_records])
1935
1936
        for (key, index_memo), data in \
1937
                izip(iter(needed_records), raw_data):
1938
            content, digest = self._parse_record(key[-1], data)
1939
            yield key, content, digest
1940
1941
    def _read_records_iter_raw(self, records):
1942
        """Read text records from data file and yield raw data.
1943
1944
        This unpacks enough of the text record to validate the id is
1945
        as expected but thats all.
1946
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1947
        Each item the iterator yields is (key, bytes,
1948
            expected_sha1_of_full_text).
1949
        """
1950
        for key, data in self._read_records_iter_unchecked(records):
1951
            # validate the header (note that we can only use the suffix in
1952
            # current knit records).
1953
            df, rec = self._parse_record_header(key, data)
1954
            df.close()
1955
            yield key, data, rec[3]
1956
1957
    def _read_records_iter_unchecked(self, records):
1958
        """Read text records from data file and yield raw data.
1959
1960
        No validation is done.
1961
1962
        Yields tuples of (key, data).
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1963
        """
1964
        # setup an iterator of the external records:
1965
        # uses readv so nice and fast we hope.
1966
        if len(records):
1967
            # grab the disk data needed.
1968
            needed_offsets = [index_memo for key, index_memo
1969
                                           in records]
1970
            raw_records = self._access.get_raw_records(needed_offsets)
1971
1972
        for key, index_memo in records:
1973
            data = raw_records.next()
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1974
            yield key, data
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1975
1976
    def _record_to_data(self, key, digest, lines, dense_lines=None):
1977
        """Convert key, digest, lines into a raw data block.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1978
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1979
        :param key: The key of the record. Currently keys are always serialised
1980
            using just the trailing component.
1981
        :param dense_lines: The bytes of lines but in a denser form. For
1982
            instance, if lines is a list of 1000 bytestrings each ending in \n,
1983
            dense_lines may be a list with one line in it, containing all the
1984
            1000's lines and their \n's. Using dense_lines if it is already
1985
            known is a win because the string join to create bytes in this
1986
            function spends less time resizing the final string.
1987
        :return: (len, a StringIO instance with the raw data ready to read.)
1988
        """
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
1989
        chunks = ["version %s %d %s\n" % (key[-1], len(lines), digest)]
1990
        chunks.extend(dense_lines or lines)
1991
        chunks.append("end %s\n" % key[-1])
1992
        for chunk in chunks:
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
1993
            if type(chunk) is not str:
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
1994
                raise AssertionError(
1995
                    'data must be plain bytes was %s' % type(chunk))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1996
        if lines and lines[-1][-1] != '\n':
1997
            raise ValueError('corrupt lines value %r' % lines)
4398.8.3 by John Arbash Meinel
Rewrite some of the internals of KnitVersionedFiles._add()
1998
        compressed_bytes = tuned_gzip.chunks_to_gzip(chunks)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1999
        return len(compressed_bytes), compressed_bytes
2000
2001
    def _split_header(self, line):
2002
        rec = line.split()
2003
        if len(rec) != 4:
2004
            raise KnitCorrupt(self,
2005
                              'unexpected number of elements in record header')
2006
        return rec
2007
2008
    def keys(self):
2009
        """See VersionedFiles.keys."""
2010
        if 'evil' in debug.debug_flags:
2011
            trace.mutter_callsite(2, "keys scales with size of history")
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
2012
        sources = [self._index] + self._immediate_fallback_vfs
3350.8.4 by Robert Collins
Vf.keys() stacking support.
2013
        result = set()
2014
        for source in sources:
2015
            result.update(source.keys())
2016
        return result
2017
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2018
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2019
class _ContentMapGenerator(object):
2020
    """Generate texts or expose raw deltas for a set of texts."""
2021
4537.3.1 by John Arbash Meinel
Start working on tests that get_record_stream gives reasonable results w/ stacking.
2022
    def __init__(self, ordering='unordered'):
2023
        self._ordering = ordering
2024
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2025
    def _get_content(self, key):
2026
        """Get the content object for key."""
4005.3.7 by Robert Collins
Review feedback.
2027
        # Note that _get_content is only called when the _ContentMapGenerator
2028
        # has been constructed with just one key requested for reconstruction.
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2029
        if key in self.nonlocal_keys:
2030
            record = self.get_record_stream().next()
2031
            # Create a content object on the fly
2032
            lines = osutils.chunks_to_lines(record.get_bytes_as('chunked'))
2033
            return PlainKnitContent(lines, record.key)
2034
        else:
2035
            # local keys we can ask for directly
2036
            return self._get_one_work(key)
2037
2038
    def get_record_stream(self):
2039
        """Get a record stream for the keys requested during __init__."""
2040
        for record in self._work():
2041
            yield record
2042
2043
    def _work(self):
2044
        """Produce maps of text and KnitContents as dicts.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2045
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2046
        :return: (text_map, content_map) where text_map contains the texts for
2047
            the requested versions and content_map contains the KnitContents.
2048
        """
2049
        # NB: By definition we never need to read remote sources unless texts
2050
        # are requested from them: we don't delta across stores - and we
2051
        # explicitly do not want to to prevent data loss situations.
2052
        if self.global_map is None:
2053
            self.global_map = self.vf.get_parent_map(self.keys)
2054
        nonlocal_keys = self.nonlocal_keys
2055
2056
        missing_keys = set(nonlocal_keys)
2057
        # Read from remote versioned file instances and provide to our caller.
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
2058
        for source in self.vf._immediate_fallback_vfs:
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2059
            if not missing_keys:
2060
                break
2061
            # Loop over fallback repositories asking them for texts - ignore
2062
            # any missing from a particular fallback.
2063
            for record in source.get_record_stream(missing_keys,
4537.3.1 by John Arbash Meinel
Start working on tests that get_record_stream gives reasonable results w/ stacking.
2064
                self._ordering, True):
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2065
                if record.storage_kind == 'absent':
2066
                    # Not in thie particular stream, may be in one of the
2067
                    # other fallback vfs objects.
2068
                    continue
2069
                missing_keys.remove(record.key)
2070
                yield record
2071
4454.2.1 by John Arbash Meinel
Don't populate self._raw_record_map in _work, it was done in __init__
2072
        if self._raw_record_map is None:
2073
            raise AssertionError('_raw_record_map should have been filled')
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2074
        first = True
2075
        for key in self.keys:
2076
            if key in self.nonlocal_keys:
2077
                continue
2078
            yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2079
            first = False
2080
2081
    def _get_one_work(self, requested_key):
2082
        # Now, if we have calculated everything already, just return the
2083
        # desired text.
2084
        if requested_key in self._contents_map:
2085
            return self._contents_map[requested_key]
4005.3.7 by Robert Collins
Review feedback.
2086
        # To simplify things, parse everything at once - code that wants one text
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2087
        # probably wants them all.
2088
        # FUTURE: This function could be improved for the 'extract many' case
2089
        # by tracking each component and only doing the copy when the number of
2090
        # children than need to apply delta's to it is > 1 or it is part of the
2091
        # final output.
2092
        multiple_versions = len(self.keys) != 1
2093
        if self._record_map is None:
2094
            self._record_map = self.vf._raw_map_to_record_map(
2095
                self._raw_record_map)
2096
        record_map = self._record_map
2097
        # raw_record_map is key:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2098
        # Have read and parsed records at this point.
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2099
        for key in self.keys:
2100
            if key in self.nonlocal_keys:
2101
                # already handled
2102
                continue
2103
            components = []
2104
            cursor = key
2105
            while cursor is not None:
2106
                try:
2107
                    record, record_details, digest, next = record_map[cursor]
2108
                except KeyError:
2109
                    raise RevisionNotPresent(cursor, self)
2110
                components.append((cursor, record, record_details, digest))
2111
                cursor = next
2112
                if cursor in self._contents_map:
2113
                    # no need to plan further back
2114
                    components.append((cursor, None, None, None))
2115
                    break
2116
2117
            content = None
2118
            for (component_id, record, record_details,
2119
                 digest) in reversed(components):
2120
                if component_id in self._contents_map:
2121
                    content = self._contents_map[component_id]
2122
                else:
2123
                    content, delta = self._factory.parse_record(key[-1],
2124
                        record, record_details, content,
2125
                        copy_base_content=multiple_versions)
2126
                    if multiple_versions:
2127
                        self._contents_map[component_id] = content
2128
2129
            # digest here is the digest from the last applied component.
2130
            text = content.text()
2131
            actual_sha = sha_strings(text)
2132
            if actual_sha != digest:
2133
                raise SHA1KnitCorrupt(self, actual_sha, digest, key, text)
2134
        if multiple_versions:
2135
            return self._contents_map[requested_key]
2136
        else:
2137
            return content
2138
2139
    def _wire_bytes(self):
2140
        """Get the bytes to put on the wire for 'key'.
2141
2142
        The first collection of bytes asked for returns the serialised
2143
        raw_record_map and the additional details (key, parent) for key.
2144
        Subsequent calls return just the additional details (key, parent).
2145
        The wire storage_kind given for the first key is 'knit-delta-closure',
2146
        For subsequent keys it is 'knit-delta-closure-ref'.
2147
2148
        :param key: A key from the content generator.
2149
        :return: Bytes to put on the wire.
2150
        """
2151
        lines = []
2152
        # kind marker for dispatch on the far side,
2153
        lines.append('knit-delta-closure')
2154
        # Annotated or not
2155
        if self.vf._factory.annotated:
2156
            lines.append('annotated')
2157
        else:
2158
            lines.append('')
2159
        # then the list of keys
2160
        lines.append('\t'.join(['\x00'.join(key) for key in self.keys
2161
            if key not in self.nonlocal_keys]))
2162
        # then the _raw_record_map in serialised form:
2163
        map_byte_list = []
2164
        # for each item in the map:
2165
        # 1 line with key
2166
        # 1 line with parents if the key is to be yielded (None: for None, '' for ())
2167
        # one line with method
2168
        # one line with noeol
2169
        # one line with next ('' for None)
2170
        # one line with byte count of the record bytes
2171
        # the record bytes
2172
        for key, (record_bytes, (method, noeol), next) in \
2173
            self._raw_record_map.iteritems():
2174
            key_bytes = '\x00'.join(key)
2175
            parents = self.global_map.get(key, None)
2176
            if parents is None:
2177
                parent_bytes = 'None:'
2178
            else:
2179
                parent_bytes = '\t'.join('\x00'.join(key) for key in parents)
2180
            method_bytes = method
2181
            if noeol:
2182
                noeol_bytes = "T"
2183
            else:
2184
                noeol_bytes = "F"
2185
            if next:
2186
                next_bytes = '\x00'.join(next)
2187
            else:
2188
                next_bytes = ''
2189
            map_byte_list.append('%s\n%s\n%s\n%s\n%s\n%d\n%s' % (
2190
                key_bytes, parent_bytes, method_bytes, noeol_bytes, next_bytes,
2191
                len(record_bytes), record_bytes))
2192
        map_bytes = ''.join(map_byte_list)
2193
        lines.append(map_bytes)
2194
        bytes = '\n'.join(lines)
2195
        return bytes
2196
2197
2198
class _VFContentMapGenerator(_ContentMapGenerator):
2199
    """Content map generator reading from a VersionedFiles object."""
2200
2201
    def __init__(self, versioned_files, keys, nonlocal_keys=None,
4537.3.1 by John Arbash Meinel
Start working on tests that get_record_stream gives reasonable results w/ stacking.
2202
        global_map=None, raw_record_map=None, ordering='unordered'):
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2203
        """Create a _ContentMapGenerator.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2204
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2205
        :param versioned_files: The versioned files that the texts are being
2206
            extracted from.
2207
        :param keys: The keys to produce content maps for.
2208
        :param nonlocal_keys: An iterable of keys(possibly intersecting keys)
2209
            which are known to not be in this knit, but rather in one of the
2210
            fallback knits.
2211
        :param global_map: The result of get_parent_map(keys) (or a supermap).
2212
            This is required if get_record_stream() is to be used.
2213
        :param raw_record_map: A unparsed raw record map to use for answering
2214
            contents.
2215
        """
4537.3.1 by John Arbash Meinel
Start working on tests that get_record_stream gives reasonable results w/ stacking.
2216
        _ContentMapGenerator.__init__(self, ordering=ordering)
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2217
        # The vf to source data from
2218
        self.vf = versioned_files
2219
        # The keys desired
2220
        self.keys = list(keys)
2221
        # Keys known to be in fallback vfs objects
2222
        if nonlocal_keys is None:
2223
            self.nonlocal_keys = set()
2224
        else:
2225
            self.nonlocal_keys = frozenset(nonlocal_keys)
2226
        # Parents data for keys to be returned in get_record_stream
2227
        self.global_map = global_map
2228
        # The chunked lists for self.keys in text form
2229
        self._text_map = {}
2230
        # A cache of KnitContent objects used in extracting texts.
2231
        self._contents_map = {}
2232
        # All the knit records needed to assemble the requested keys as full
2233
        # texts.
2234
        self._record_map = None
2235
        if raw_record_map is None:
2236
            self._raw_record_map = self.vf._get_record_map_unparsed(keys,
2237
                allow_missing=True)
2238
        else:
2239
            self._raw_record_map = raw_record_map
2240
        # the factory for parsing records
2241
        self._factory = self.vf._factory
2242
2243
2244
class _NetworkContentMapGenerator(_ContentMapGenerator):
2245
    """Content map generator sourced from a network stream."""
2246
2247
    def __init__(self, bytes, line_end):
2248
        """Construct a _NetworkContentMapGenerator from a bytes block."""
2249
        self._bytes = bytes
2250
        self.global_map = {}
2251
        self._raw_record_map = {}
2252
        self._contents_map = {}
2253
        self._record_map = None
2254
        self.nonlocal_keys = []
2255
        # Get access to record parsing facilities
2256
        self.vf = KnitVersionedFiles(None, None)
2257
        start = line_end
2258
        # Annotated or not
2259
        line_end = bytes.find('\n', start)
2260
        line = bytes[start:line_end]
2261
        start = line_end + 1
2262
        if line == 'annotated':
2263
            self._factory = KnitAnnotateFactory()
2264
        else:
2265
            self._factory = KnitPlainFactory()
2266
        # list of keys to emit in get_record_stream
2267
        line_end = bytes.find('\n', start)
2268
        line = bytes[start:line_end]
2269
        start = line_end + 1
2270
        self.keys = [
2271
            tuple(segment.split('\x00')) for segment in line.split('\t')
2272
            if segment]
2273
        # now a loop until the end. XXX: It would be nice if this was just a
2274
        # bunch of the same records as get_record_stream(..., False) gives, but
2275
        # there is a decent sized gap stopping that at the moment.
2276
        end = len(bytes)
2277
        while start < end:
2278
            # 1 line with key
2279
            line_end = bytes.find('\n', start)
2280
            key = tuple(bytes[start:line_end].split('\x00'))
2281
            start = line_end + 1
2282
            # 1 line with parents (None: for None, '' for ())
2283
            line_end = bytes.find('\n', start)
2284
            line = bytes[start:line_end]
2285
            if line == 'None:':
2286
                parents = None
2287
            else:
2288
                parents = tuple(
2289
                    [tuple(segment.split('\x00')) for segment in line.split('\t')
2290
                     if segment])
2291
            self.global_map[key] = parents
2292
            start = line_end + 1
2293
            # one line with method
2294
            line_end = bytes.find('\n', start)
2295
            line = bytes[start:line_end]
2296
            method = line
2297
            start = line_end + 1
2298
            # one line with noeol
2299
            line_end = bytes.find('\n', start)
2300
            line = bytes[start:line_end]
2301
            noeol = line == "T"
2302
            start = line_end + 1
2303
            # one line with next ('' for None)
2304
            line_end = bytes.find('\n', start)
2305
            line = bytes[start:line_end]
2306
            if not line:
2307
                next = None
2308
            else:
2309
                next = tuple(bytes[start:line_end].split('\x00'))
2310
            start = line_end + 1
2311
            # one line with byte count of the record bytes
2312
            line_end = bytes.find('\n', start)
2313
            line = bytes[start:line_end]
2314
            count = int(line)
2315
            start = line_end + 1
2316
            # the record bytes
2317
            record_bytes = bytes[start:start+count]
2318
            start = start + count
2319
            # put it in the map
2320
            self._raw_record_map[key] = (record_bytes, (method, noeol), next)
2321
2322
    def get_record_stream(self):
2323
        """Get a record stream for for keys requested by the bytestream."""
2324
        first = True
2325
        for key in self.keys:
2326
            yield LazyKnitContentFactory(key, self.global_map[key], self, first)
2327
            first = False
2328
2329
    def _wire_bytes(self):
2330
        return self._bytes
2331
2332
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2333
class _KndxIndex(object):
2334
    """Manages knit index files
2335
3350.6.10 by Martin Pool
VersionedFiles review cleanups
2336
    The index is kept in memory and read on startup, to enable
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2337
    fast lookups of revision information.  The cursor of the index
2338
    file is always pointing to the end, making it easy to append
2339
    entries.
2340
2341
    _cache is a cache for fast mapping from version id to a Index
2342
    object.
2343
2344
    _history is a cache for fast mapping from indexes to version ids.
2345
2346
    The index data format is dictionary compressed when it comes to
2347
    parent references; a index entry may only have parents that with a
2348
    lover index number.  As a result, the index is topological sorted.
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
2349
2350
    Duplicate entries may be written to the index for a single version id
2351
    if this is done then the latter one completely replaces the former:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2352
    this allows updates to correct version and parent information.
1563.2.11 by Robert Collins
Consolidate reweave and join as we have no separate usage, make reweave tests apply to all versionedfile implementations and deprecate the old reweave apis.
2353
    Note that the two entries may share the delta, and that successive
2354
    annotations and references MUST point to the first entry.
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
2355
2356
    The index file on disc contains a header, followed by one line per knit
2357
    record. The same revision can be present in an index file more than once.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2358
    The first occurrence gets assigned a sequence number starting from 0.
2359
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
2360
    The format of a single line is
2361
    REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
2362
    REVISION_ID is a utf8-encoded revision id
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2363
    FLAGS is a comma separated list of flags about the record. Values include
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
2364
        no-eol, line-delta, fulltext.
2365
    BYTE_OFFSET is the ascii representation of the byte offset in the data file
4775.1.1 by Martin Pool
Remove several 'the the' typos
2366
        that the compressed data starts at.
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
2367
    LENGTH is the ascii representation of the length of the data file.
2368
    PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
2369
        REVISION_ID.
2370
    PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
2371
        revision id already in the knit that is a parent of REVISION_ID.
2372
    The ' :' marker is the end of record marker.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2373
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
2374
    partial writes:
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
2375
    when a write is interrupted to the index file, it will result in a line
2376
    that does not end in ' :'. If the ' :' is not present at the end of a line,
2377
    or at the end of the file, then the record that is missing it will be
2378
    ignored by the parser.
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
2379
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
2380
    When writing new records to the index file, the data is preceded by '\n'
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
2381
    to ensure that records always start on new lines even if the last write was
2382
    interrupted. As a result its normal for the last line in the index to be
2383
    missing a trailing newline. One can be added with no harmful effects.
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
2384
2385
    :ivar _kndx_cache: dict from prefix to the old state of KnitIndex objects,
2386
        where prefix is e.g. the (fileid,) for .texts instances or () for
2387
        constant-mapped things like .revisions, and the old state is
2388
        tuple(history_vector, cache_dict).  This is used to prevent having an
2389
        ABI change with the C extension that reads .kndx files.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2390
    """
2391
1666.1.6 by Robert Collins
Make knit the default format.
2392
    HEADER = "# bzr knit index 8\n"
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2393
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2394
    def __init__(self, transport, mapper, get_scope, allow_writes, is_locked):
2395
        """Create a _KndxIndex on transport using mapper."""
2396
        self._transport = transport
2397
        self._mapper = mapper
2398
        self._get_scope = get_scope
2399
        self._allow_writes = allow_writes
2400
        self._is_locked = is_locked
2401
        self._reset_cache()
2402
        self.has_graph = True
2403
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2404
    def add_records(self, records, random_id=False, missing_compression_parents=False):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2405
        """Add multiple records to the index.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2406
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2407
        :param records: a list of tuples:
2408
                         (key, options, access_memo, parents).
2409
        :param random_id: If True the ids being added were randomly generated
2410
            and no check for existence will be performed.
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2411
        :param missing_compression_parents: If True the records being added are
2412
            only compressed against texts already in the index (or inside
2413
            records). If False the records all refer to unavailable texts (or
2414
            texts inside records) as compression parents.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2415
        """
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2416
        if missing_compression_parents:
2417
            # It might be nice to get the edge of the records. But keys isn't
2418
            # _wrong_.
2419
            keys = sorted(record[0] for record in records)
2420
            raise errors.RevisionNotPresent(keys, self)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2421
        paths = {}
2422
        for record in records:
2423
            key = record[0]
2424
            prefix = key[:-1]
2425
            path = self._mapper.map(key) + '.kndx'
2426
            path_keys = paths.setdefault(path, (prefix, []))
2427
            path_keys[1].append(record)
2428
        for path in sorted(paths):
2429
            prefix, path_keys = paths[path]
2430
            self._load_prefixes([prefix])
2431
            lines = []
2432
            orig_history = self._kndx_cache[prefix][1][:]
2433
            orig_cache = self._kndx_cache[prefix][0].copy()
2434
2435
            try:
2436
                for key, options, (_, pos, size), parents in path_keys:
2437
                    if parents is None:
2438
                        # kndx indices cannot be parentless.
2439
                        parents = ()
2440
                    line = "\n%s %s %s %s %s :" % (
2441
                        key[-1], ','.join(options), pos, size,
2442
                        self._dictionary_compress(parents))
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
2443
                    if type(line) is not str:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2444
                        raise AssertionError(
2445
                            'data must be utf8 was %s' % type(line))
2446
                    lines.append(line)
2447
                    self._cache_key(key, options, pos, size, parents)
2448
                if len(orig_history):
2449
                    self._transport.append_bytes(path, ''.join(lines))
2450
                else:
2451
                    self._init_index(path, lines)
2452
            except:
2453
                # If any problems happen, restore the original values and re-raise
2454
                self._kndx_cache[prefix] = (orig_cache, orig_history)
2455
                raise
2456
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
2457
    def scan_unvalidated_index(self, graph_index):
2458
        """See _KnitGraphIndex.scan_unvalidated_index."""
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
2459
        # Because kndx files do not support atomic insertion via separate index
2460
        # files, they do not support this method.
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
2461
        raise NotImplementedError(self.scan_unvalidated_index)
2462
2463
    def get_missing_compression_parents(self):
2464
        """See _KnitGraphIndex.get_missing_compression_parents."""
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
2465
        # Because kndx files do not support atomic insertion via separate index
2466
        # files, they do not support this method.
2467
        raise NotImplementedError(self.get_missing_compression_parents)
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2468
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2469
    def _cache_key(self, key, options, pos, size, parent_keys):
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
2470
        """Cache a version record in the history array and index cache.
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
2471
2472
        This is inlined into _load_data for performance. KEEP IN SYNC.
1596.2.18 by Robert Collins
More microopimisations on index reading, now down to 16000 records/seconds.
2473
        (It saves 60ms, 25% of the __init__ overhead on local 4000 record
2474
         indexes).
2475
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2476
        prefix = key[:-1]
2477
        version_id = key[-1]
2478
        # last-element only for compatibilty with the C load_data.
2479
        parents = tuple(parent[-1] for parent in parent_keys)
2480
        for parent in parent_keys:
2481
            if parent[:-1] != prefix:
2482
                raise ValueError("mismatched prefixes for %r, %r" % (
2483
                    key, parent_keys))
2484
        cache, history = self._kndx_cache[prefix]
1596.2.14 by Robert Collins
Make knit parsing non quadratic?
2485
        # only want the _history index to reference the 1st index entry
2486
        # for version_id
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2487
        if version_id not in cache:
2488
            index = len(history)
2489
            history.append(version_id)
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
2490
        else:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2491
            index = cache[version_id][5]
2492
        cache[version_id] = (version_id,
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
2493
                                   options,
2494
                                   pos,
2495
                                   size,
2496
                                   parents,
2497
                                   index)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2498
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2499
    def check_header(self, fp):
2500
        line = fp.readline()
2501
        if line == '':
2502
            # An empty file can actually be treated as though the file doesn't
2503
            # exist yet.
2504
            raise errors.NoSuchFile(self)
2505
        if line != self.HEADER:
2506
            raise KnitHeaderError(badline=line, filename=self)
2507
2508
    def _check_read(self):
2509
        if not self._is_locked():
2510
            raise errors.ObjectNotLocked(self)
2511
        if self._get_scope() != self._scope:
2512
            self._reset_cache()
2513
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
2514
    def _check_write_ok(self):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2515
        """Assert if not writes are permitted."""
2516
        if not self._is_locked():
2517
            raise errors.ObjectNotLocked(self)
3316.2.5 by Robert Collins
Review feedback.
2518
        if self._get_scope() != self._scope:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2519
            self._reset_cache()
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
2520
        if self._mode != 'w':
2521
            raise errors.ReadOnlyObjectDirtiedError(self)
2522
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2523
    def get_build_details(self, keys):
2524
        """Get the method, index_memo and compression parent for keys.
3218.1.1 by Robert Collins
Reduce index query pressure for text construction by batching the individual queries into single batch queries.
2525
3224.1.29 by John Arbash Meinel
Properly handle annotating when ghosts are present.
2526
        Ghosts are omitted from the result.
2527
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2528
        :param keys: An iterable of keys.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
2529
        :return: A dict of key:(index_memo, compression_parent, parents,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2530
            record_details).
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
2531
            index_memo
2532
                opaque structure to pass to read_records to extract the raw
2533
                data
2534
            compression_parent
2535
                Content that this record is built upon, may be None
2536
            parents
2537
                Logical parents of this node
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2538
            record_details
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
2539
                extra information about the content which needs to be passed to
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2540
                Factory.parse_record
3218.1.1 by Robert Collins
Reduce index query pressure for text construction by batching the individual queries into single batch queries.
2541
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2542
        parent_map = self.get_parent_map(keys)
3218.1.1 by Robert Collins
Reduce index query pressure for text construction by batching the individual queries into single batch queries.
2543
        result = {}
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2544
        for key in keys:
2545
            if key not in parent_map:
2546
                continue # Ghost
2547
            method = self.get_method(key)
2548
            parents = parent_map[key]
3218.1.1 by Robert Collins
Reduce index query pressure for text construction by batching the individual queries into single batch queries.
2549
            if method == 'fulltext':
2550
                compression_parent = None
2551
            else:
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2552
                compression_parent = parents[0]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2553
            noeol = 'no-eol' in self.get_options(key)
2554
            index_memo = self.get_position(key)
2555
            result[key] = (index_memo, compression_parent,
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
2556
                                  parents, (method, noeol))
3218.1.1 by Robert Collins
Reduce index query pressure for text construction by batching the individual queries into single batch queries.
2557
        return result
2558
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2559
    def get_method(self, key):
2560
        """Return compression method of specified key."""
2561
        options = self.get_options(key)
2562
        if 'fulltext' in options:
2563
            return 'fulltext'
2564
        elif 'line-delta' in options:
2565
            return 'line-delta'
2566
        else:
2567
            raise errors.KnitIndexUnknownMethod(self, options)
2568
2569
    def get_options(self, key):
2570
        """Return a list representing options.
2571
2572
        e.g. ['foo', 'bar']
2573
        """
2574
        prefix, suffix = self._split_key(key)
2575
        self._load_prefixes([prefix])
3350.8.9 by Robert Collins
define behaviour for add_lines with stacked storage.
2576
        try:
2577
            return self._kndx_cache[prefix][0][suffix][1]
2578
        except KeyError:
2579
            raise RevisionNotPresent(key, self)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2580
4593.5.35 by John Arbash Meinel
Start working on a per-vf implementation test of find_ancestry.
2581
    def find_ancestry(self, keys):
2582
        """See CombinedGraphIndex.find_ancestry()"""
2583
        prefixes = set(key[:-1] for key in keys)
2584
        self._load_prefixes(prefixes)
2585
        result = {}
2586
        parent_map = {}
2587
        missing_keys = set()
2588
        pending_keys = list(keys)
2589
        # This assumes that keys will not reference parents in a different
2590
        # prefix, which is accurate so far.
2591
        while pending_keys:
2592
            key = pending_keys.pop()
2593
            if key in parent_map:
2594
                continue
2595
            prefix = key[:-1]
2596
            try:
2597
                suffix_parents = self._kndx_cache[prefix][0][key[-1]][4]
2598
            except KeyError:
2599
                missing_keys.add(key)
2600
            else:
2601
                parent_keys = tuple([prefix + (suffix,)
2602
                                     for suffix in suffix_parents])
2603
                parent_map[key] = parent_keys
2604
                pending_keys.extend([p for p in parent_keys
2605
                                        if p not in parent_map])
2606
        return parent_map, missing_keys
2607
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2608
    def get_parent_map(self, keys):
2609
        """Get a map of the parents of keys.
2610
2611
        :param keys: The keys to look up parents for.
2612
        :return: A mapping from keys to parents. Absent keys are absent from
2613
            the mapping.
2614
        """
2615
        # Parse what we need to up front, this potentially trades off I/O
2616
        # locality (.kndx and .knit in the same block group for the same file
2617
        # id) for less checking in inner loops.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
2618
        prefixes = set(key[:-1] for key in keys)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2619
        self._load_prefixes(prefixes)
2620
        result = {}
2621
        for key in keys:
2622
            prefix = key[:-1]
2623
            try:
2624
                suffix_parents = self._kndx_cache[prefix][0][key[-1]][4]
2625
            except KeyError:
2626
                pass
2627
            else:
2628
                result[key] = tuple(prefix + (suffix,) for
2629
                    suffix in suffix_parents)
2630
        return result
2631
2632
    def get_position(self, key):
2633
        """Return details needed to access the version.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2634
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2635
        :return: a tuple (key, data position, size) to hand to the access
2636
            logic to get the record.
2637
        """
2638
        prefix, suffix = self._split_key(key)
2639
        self._load_prefixes([prefix])
2640
        entry = self._kndx_cache[prefix][0][suffix]
2641
        return key, entry[2], entry[3]
2642
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
2643
    has_key = _mod_index._has_key_from_parent_map
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2644
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2645
    def _init_index(self, path, extra_lines=[]):
2646
        """Initialize an index."""
2647
        sio = StringIO()
2648
        sio.write(self.HEADER)
2649
        sio.writelines(extra_lines)
2650
        sio.seek(0)
2651
        self._transport.put_file_non_atomic(path, sio,
2652
                            create_parent_dir=True)
2653
                           # self._create_parent_dir)
2654
                           # mode=self._file_mode,
2655
                           # dir_mode=self._dir_mode)
2656
2657
    def keys(self):
2658
        """Get all the keys in the collection.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2659
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2660
        The keys are not ordered.
2661
        """
2662
        result = set()
2663
        # Identify all key prefixes.
2664
        # XXX: A bit hacky, needs polish.
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
2665
        if type(self._mapper) is ConstantMapper:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2666
            prefixes = [()]
2667
        else:
2668
            relpaths = set()
2669
            for quoted_relpath in self._transport.iter_files_recursive():
2670
                path, ext = os.path.splitext(quoted_relpath)
2671
                relpaths.add(path)
2672
            prefixes = [self._mapper.unmap(path) for path in relpaths]
2673
        self._load_prefixes(prefixes)
2674
        for prefix in prefixes:
2675
            for suffix in self._kndx_cache[prefix][1]:
2676
                result.add(prefix + (suffix,))
2677
        return result
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2678
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2679
    def _load_prefixes(self, prefixes):
2680
        """Load the indices for prefixes."""
2681
        self._check_read()
2682
        for prefix in prefixes:
2683
            if prefix not in self._kndx_cache:
2684
                # the load_data interface writes to these variables.
2685
                self._cache = {}
2686
                self._history = []
2687
                self._filename = prefix
2688
                try:
2689
                    path = self._mapper.map(prefix) + '.kndx'
2690
                    fp = self._transport.get(path)
2691
                    try:
2692
                        # _load_data may raise NoSuchFile if the target knit is
2693
                        # completely empty.
2694
                        _load_data(self, fp)
2695
                    finally:
2696
                        fp.close()
2697
                    self._kndx_cache[prefix] = (self._cache, self._history)
2698
                    del self._cache
2699
                    del self._filename
2700
                    del self._history
2701
                except NoSuchFile:
2702
                    self._kndx_cache[prefix] = ({}, [])
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
2703
                    if type(self._mapper) is ConstantMapper:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2704
                        # preserve behaviour for revisions.kndx etc.
2705
                        self._init_index(path)
2706
                    del self._cache
2707
                    del self._filename
2708
                    del self._history
2709
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
2710
    missing_keys = _mod_index._missing_keys_from_parent_map
2711
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2712
    def _partition_keys(self, keys):
2713
        """Turn keys into a dict of prefix:suffix_list."""
2714
        result = {}
2715
        for key in keys:
2716
            prefix_keys = result.setdefault(key[:-1], [])
2717
            prefix_keys.append(key[-1])
2718
        return result
2719
2720
    def _dictionary_compress(self, keys):
2721
        """Dictionary compress keys.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2722
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2723
        :param keys: The keys to generate references to.
2724
        :return: A string representation of keys. keys which are present are
2725
            dictionary compressed, and others are emitted as fulltext with a
2726
            '.' prefix.
2727
        """
2728
        if not keys:
2729
            return ''
1594.2.8 by Robert Collins
add ghost aware apis to knits.
2730
        result_list = []
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2731
        prefix = keys[0][:-1]
2732
        cache = self._kndx_cache[prefix][0]
2733
        for key in keys:
2734
            if key[:-1] != prefix:
2735
                # kndx indices cannot refer across partitioned storage.
2736
                raise ValueError("mismatched prefixes for %r" % keys)
2737
            if key[-1] in cache:
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
2738
                # -- inlined lookup() --
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2739
                result_list.append(str(cache[key[-1]][5]))
1628.1.1 by Robert Collins
Cache the index number of versions in the knit index's self._cache so that
2740
                # -- end lookup () --
1594.2.8 by Robert Collins
add ghost aware apis to knits.
2741
            else:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2742
                result_list.append('.' + key[-1])
1594.2.8 by Robert Collins
add ghost aware apis to knits.
2743
        return ' '.join(result_list)
2744
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2745
    def _reset_cache(self):
2746
        # Possibly this should be a LRU cache. A dictionary from key_prefix to
2747
        # (cache_dict, history_vector) for parsed kndx files.
2748
        self._kndx_cache = {}
2749
        self._scope = self._get_scope()
2750
        allow_writes = self._allow_writes()
2751
        if allow_writes:
2752
            self._mode = 'w'
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2753
        else:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2754
            self._mode = 'r'
2755
3878.1.2 by John Arbash Meinel
Move the sorting into each index, and customize it for Kndx access.
2756
    def _sort_keys_by_io(self, keys, positions):
2757
        """Figure out an optimal order to read the records for the given keys.
2758
2759
        Sort keys, grouped by index and sorted by position.
2760
2761
        :param keys: A list of keys whose records we want to read. This will be
2762
            sorted 'in-place'.
2763
        :param positions: A dict, such as the one returned by
2764
            _get_components_positions()
2765
        :return: None
2766
        """
3878.1.3 by John Arbash Meinel
Add a comment about what data we are sorting by.
2767
        def get_sort_key(key):
3878.1.2 by John Arbash Meinel
Move the sorting into each index, and customize it for Kndx access.
2768
            index_memo = positions[key][1]
2769
            # Group by prefix and position. index_memo[0] is the key, so it is
2770
            # (file_id, revision_id) and we don't want to sort on revision_id,
2771
            # index_memo[1] is the position, and index_memo[2] is the size,
2772
            # which doesn't matter for the sort
2773
            return index_memo[0][:-1], index_memo[1]
3878.1.3 by John Arbash Meinel
Add a comment about what data we are sorting by.
2774
        return keys.sort(key=get_sort_key)
3878.1.2 by John Arbash Meinel
Move the sorting into each index, and customize it for Kndx access.
2775
4039.3.5 by John Arbash Meinel
Add direct tests for _get_total_build_size.
2776
    _get_total_build_size = _get_total_build_size
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
2777
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2778
    def _split_key(self, key):
2779
        """Split key into a prefix and suffix."""
2780
        return key[:-1], key[-1]
2781
2782
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2783
class _KeyRefs(object):
2784
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2785
    def __init__(self, track_new_keys=False):
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2786
        # dict mapping 'key' to 'set of keys referring to that key'
2787
        self.refs = {}
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2788
        if track_new_keys:
4634.29.16 by Andrew Bennetts
Fix buggy TestKeyDependencies test, tweak error string and comment.
2789
            # set remembering all new keys
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2790
            self.new_keys = set()
2791
        else:
2792
            self.new_keys = None
2793
2794
    def clear(self):
2795
        if self.refs:
2796
            self.refs.clear()
2797
        if self.new_keys:
2798
            self.new_keys.clear()
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2799
2800
    def add_references(self, key, refs):
2801
        # Record the new references
2802
        for referenced in refs:
2803
            try:
2804
                needed_by = self.refs[referenced]
2805
            except KeyError:
2806
                needed_by = self.refs[referenced] = set()
2807
            needed_by.add(key)
2808
        # Discard references satisfied by the new key
2809
        self.add_key(key)
2810
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2811
    def get_new_keys(self):
2812
        return self.new_keys
2813
    
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2814
    def get_unsatisfied_refs(self):
2815
        return self.refs.iterkeys()
2816
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2817
    def _satisfy_refs_for_key(self, key):
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2818
        try:
2819
            del self.refs[key]
2820
        except KeyError:
2821
            # No keys depended on this key.  That's ok.
2822
            pass
2823
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2824
    def add_key(self, key):
2825
        # satisfy refs for key, and remember that we've seen this key.
2826
        self._satisfy_refs_for_key(key)
2827
        if self.new_keys is not None:
2828
            self.new_keys.add(key)
2829
2830
    def satisfy_refs_for_keys(self, keys):
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2831
        for key in keys:
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
2832
            self._satisfy_refs_for_key(key)
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2833
4309.1.2 by Andrew Bennetts
Tentative fix for bug 368418: only fail the missing parent inventories check if there are missing texts that appear to be altered by the inventories with missing parents.
2834
    def get_referrers(self):
2835
        result = set()
2836
        for referrers in self.refs.itervalues():
2837
            result.update(referrers)
2838
        return result
2839
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2840
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2841
class _KnitGraphIndex(object):
2842
    """A KnitVersionedFiles index layered on GraphIndex."""
2843
2844
    def __init__(self, graph_index, is_locked, deltas=False, parents=True,
4634.29.3 by Andrew Bennetts
Simplify further.
2845
        add_callback=None, track_external_parent_refs=False):
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
2846
        """Construct a KnitGraphIndex on a graph_index.
2847
2848
        :param graph_index: An implementation of bzrlib.index.GraphIndex.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2849
        :param is_locked: A callback to check whether the object should answer
2850
            queries.
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2851
        :param deltas: Allow delta-compressed records.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2852
        :param parents: If True, record knits parents, if not do not record
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2853
            parents.
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2854
        :param add_callback: If not None, allow additions to the index and call
2855
            this callback with a list of added GraphIndex nodes:
2592.3.33 by Robert Collins
Change the order of index refs and values to make the no-graph knit index easier.
2856
            [(node, value, node_refs), ...]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2857
        :param is_locked: A callback, returns True if the index is locked and
2858
            thus usable.
4257.4.11 by Andrew Bennetts
Polish the patch.
2859
        :param track_external_parent_refs: If True, record all external parent
2860
            references parents from added records.  These can be retrieved
2861
            later by calling get_missing_parents().
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
2862
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2863
        self._add_callback = add_callback
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
2864
        self._graph_index = graph_index
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2865
        self._deltas = deltas
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2866
        self._parents = parents
2867
        if deltas and not parents:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2868
            # XXX: TODO: Delta tree and parent graph should be conceptually
2869
            # separate.
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2870
            raise KnitCorrupt(self, "Cannot do delta compression without "
2871
                "parent tracking.")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2872
        self.has_graph = parents
2873
        self._is_locked = is_locked
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
2874
        self._missing_compression_parents = set()
4257.4.11 by Andrew Bennetts
Polish the patch.
2875
        if track_external_parent_refs:
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2876
            self._key_dependencies = _KeyRefs()
4257.4.10 by Andrew Bennetts
Observe new revisions in _KnitGraphIndex.add_record rather than iterating all the uncommitted packs' indices.
2877
        else:
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2878
            self._key_dependencies = None
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2879
3517.4.13 by Martin Pool
Add repr methods
2880
    def __repr__(self):
2881
        return "%s(%r)" % (self.__class__.__name__, self._graph_index)
2882
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2883
    def add_records(self, records, random_id=False,
2884
        missing_compression_parents=False):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2885
        """Add multiple records to the index.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2886
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2887
        This function does not insert data into the Immutable GraphIndex
2888
        backing the KnitGraphIndex, instead it prepares data for insertion by
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2889
        the caller and checks that it is safe to insert then calls
2890
        self._add_callback with the prepared GraphIndex nodes.
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2891
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2892
        :param records: a list of tuples:
2893
                         (key, options, access_memo, parents).
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
2894
        :param random_id: If True the ids being added were randomly generated
2895
            and no check for existence will be performed.
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2896
        :param missing_compression_parents: If True the records being added are
2897
            only compressed against texts already in the index (or inside
2898
            records). If False the records all refer to unavailable texts (or
2899
            texts inside records) as compression parents.
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2900
        """
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2901
        if not self._add_callback:
2902
            raise errors.ReadOnlyError(self)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2903
        # we hope there are no repositories with inconsistent parentage
2904
        # anymore.
2905
2906
        keys = {}
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2907
        compression_parents = set()
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2908
        key_dependencies = self._key_dependencies
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2909
        for (key, options, access_memo, parents) in records:
2910
            if self._parents:
2911
                parents = tuple(parents)
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2912
                if key_dependencies is not None:
2913
                    key_dependencies.add_references(key, parents)
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2914
            index, pos, size = access_memo
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2915
            if 'no-eol' in options:
2916
                value = 'N'
2917
            else:
2918
                value = ' '
2919
            value += "%d %d" % (pos, size)
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2920
            if not self._deltas:
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2921
                if 'line-delta' in options:
2922
                    raise KnitCorrupt(self, "attempt to add line-delta in non-delta knit")
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2923
            if self._parents:
2924
                if self._deltas:
2925
                    if 'line-delta' in options:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2926
                        node_refs = (parents, (parents[0],))
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2927
                        if missing_compression_parents:
2928
                            compression_parents.add(parents[0])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2929
                    else:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2930
                        node_refs = (parents, ())
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2931
                else:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2932
                    node_refs = (parents, )
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2933
            else:
2934
                if parents:
2935
                    raise KnitCorrupt(self, "attempt to add node with parents "
2936
                        "in parentless index.")
2937
                node_refs = ()
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2938
            keys[key] = (value, node_refs)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2939
        # check for dups
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
2940
        if not random_id:
2941
            present_nodes = self._get_entries(keys)
2942
            for (index, key, value, node_refs) in present_nodes:
4789.28.3 by John Arbash Meinel
Add a static_tuple.as_tuples() helper.
2943
                parents = node_refs[:1]
2944
                # Sometimes these are passed as a list rather than a tuple
2945
                passed = static_tuple.as_tuples(keys[key])
4789.28.4 by John Arbash Meinel
Fix a small typo
2946
                passed_parents = passed[1][:1]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2947
                if (value[0] != keys[key][0][0] or
4789.28.3 by John Arbash Meinel
Add a static_tuple.as_tuples() helper.
2948
                    parents != passed_parents):
2949
                    node_refs = static_tuple.as_tuples(node_refs)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2950
                    raise KnitCorrupt(self, "inconsistent details in add_records"
4789.28.3 by John Arbash Meinel
Add a static_tuple.as_tuples() helper.
2951
                        ": %s %s" % ((value, node_refs), passed))
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
2952
                del keys[key]
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2953
        result = []
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2954
        if self._parents:
2955
            for key, (value, node_refs) in keys.iteritems():
2956
                result.append((key, value, node_refs))
2957
        else:
2958
            for key, (value, node_refs) in keys.iteritems():
2959
                result.append((key, value))
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2960
        self._add_callback(result)
2961
        if missing_compression_parents:
2962
            # This may appear to be incorrect (it does not check for
2963
            # compression parents that are in the existing graph index),
2964
            # but such records won't have been buffered, so this is
2965
            # actually correct: every entry when
2966
            # missing_compression_parents==True either has a missing parent, or
2967
            # a parent that is one of the keys in records.
2968
            compression_parents.difference_update(keys)
2969
            self._missing_compression_parents.update(compression_parents)
2970
        # Adding records may have satisfied missing compression parents.
4009.3.7 by Andrew Bennetts
Most tests passing.
2971
        self._missing_compression_parents.difference_update(keys)
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2972
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
2973
    def scan_unvalidated_index(self, graph_index):
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
2974
        """Inform this _KnitGraphIndex that there is an unvalidated index.
2975
2976
        This allows this _KnitGraphIndex to keep track of any missing
2977
        compression parents we may want to have filled in to make those
2978
        indices valid.
2979
2980
        :param graph_index: A GraphIndex
2981
        """
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
2982
        if self._deltas:
2983
            new_missing = graph_index.external_references(ref_list_num=1)
2984
            new_missing.difference_update(self.get_parent_map(new_missing))
2985
            self._missing_compression_parents.update(new_missing)
4634.29.3 by Andrew Bennetts
Simplify further.
2986
        if self._key_dependencies is not None:
2987
            # Add parent refs from graph_index (and discard parent refs that
2988
            # the graph_index has).
2989
            for node in graph_index.iter_all_entries():
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
2990
                self._key_dependencies.add_references(node[1], node[3][0])
4009.3.7 by Andrew Bennetts
Most tests passing.
2991
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
2992
    def get_missing_compression_parents(self):
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2993
        """Return the keys of missing compression parents.
2994
2995
        Missing compression parents occur when a record stream was missing
2996
        basis texts, or a index was scanned that had missing basis texts.
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
2997
        """
2998
        return frozenset(self._missing_compression_parents)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2999
4257.4.11 by Andrew Bennetts
Polish the patch.
3000
    def get_missing_parents(self):
3001
        """Return the keys of missing parents."""
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
3002
        # If updating this, you should also update
3003
        # groupcompress._GCGraphIndex.get_missing_parents
4257.4.11 by Andrew Bennetts
Polish the patch.
3004
        # We may have false positives, so filter those out.
4634.29.6 by Andrew Bennetts
Put new key tracking in _KeyRefs rather than alongside it.
3005
        self._key_dependencies.satisfy_refs_for_keys(
4309.1.1 by Andrew Bennetts
Track which keys referenced the missing parents.
3006
            self.get_parent_map(self._key_dependencies.get_unsatisfied_refs()))
3007
        return frozenset(self._key_dependencies.get_unsatisfied_refs())
4257.4.11 by Andrew Bennetts
Polish the patch.
3008
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3009
    def _check_read(self):
3010
        """raise if reads are not permitted."""
3011
        if not self._is_locked():
3012
            raise errors.ObjectNotLocked(self)
3013
3014
    def _check_write_ok(self):
3015
        """Assert if writes are not permitted."""
3016
        if not self._is_locked():
3017
            raise errors.ObjectNotLocked(self)
3018
3019
    def _compression_parent(self, an_entry):
3020
        # return the key that an_entry is compressed against, or None
3021
        # Grab the second parent list (as deltas implies parents currently)
3022
        compression_parents = an_entry[3][1]
3023
        if not compression_parents:
3024
            return None
3025
        if len(compression_parents) != 1:
3026
            raise AssertionError(
3027
                "Too many compression parents: %r" % compression_parents)
3028
        return compression_parents[0]
3029
3030
    def get_build_details(self, keys):
3031
        """Get the method, index_memo and compression parent for version_ids.
3032
3033
        Ghosts are omitted from the result.
3034
3035
        :param keys: An iterable of keys.
3036
        :return: A dict of key:
3037
            (index_memo, compression_parent, parents, record_details).
3038
            index_memo
3039
                opaque structure to pass to read_records to extract the raw
3040
                data
3041
            compression_parent
3042
                Content that this record is built upon, may be None
3043
            parents
3044
                Logical parents of this node
3045
            record_details
3046
                extra information about the content which needs to be passed to
3047
                Factory.parse_record
3048
        """
3049
        self._check_read()
3050
        result = {}
3051
        entries = self._get_entries(keys, False)
3052
        for entry in entries:
3053
            key = entry[1]
3054
            if not self._parents:
3055
                parents = ()
3056
            else:
3057
                parents = entry[3][0]
3058
            if not self._deltas:
3059
                compression_parent_key = None
3060
            else:
3061
                compression_parent_key = self._compression_parent(entry)
3062
            noeol = (entry[2][0] == 'N')
3063
            if compression_parent_key:
3064
                method = 'line-delta'
3065
            else:
3066
                method = 'fulltext'
3067
            result[key] = (self._node_to_position(entry),
3068
                                  compression_parent_key, parents,
3069
                                  (method, noeol))
3070
        return result
3071
3072
    def _get_entries(self, keys, check_present=False):
3073
        """Get the entries for keys.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3074
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3075
        :param keys: An iterable of index key tuples.
3076
        """
3077
        keys = set(keys)
3078
        found_keys = set()
3079
        if self._parents:
3080
            for node in self._graph_index.iter_entries(keys):
3081
                yield node
3082
                found_keys.add(node[1])
3083
        else:
3084
            # adapt parentless index to the rest of the code.
3085
            for node in self._graph_index.iter_entries(keys):
3086
                yield node[0], node[1], node[2], ()
3087
                found_keys.add(node[1])
3088
        if check_present:
3089
            missing_keys = keys.difference(found_keys)
3090
            if missing_keys:
3091
                raise RevisionNotPresent(missing_keys.pop(), self)
3092
3093
    def get_method(self, key):
3094
        """Return compression method of specified key."""
3095
        return self._get_method(self._get_node(key))
3096
3097
    def _get_method(self, node):
3098
        if not self._deltas:
3099
            return 'fulltext'
3100
        if self._compression_parent(node):
3101
            return 'line-delta'
3102
        else:
3103
            return 'fulltext'
3104
3105
    def _get_node(self, key):
3106
        try:
3107
            return list(self._get_entries([key]))[0]
3108
        except IndexError:
3109
            raise RevisionNotPresent(key, self)
3110
3111
    def get_options(self, key):
3112
        """Return a list representing options.
3113
3114
        e.g. ['foo', 'bar']
3115
        """
3116
        node = self._get_node(key)
3117
        options = [self._get_method(node)]
3118
        if node[2][0] == 'N':
3119
            options.append('no-eol')
3120
        return options
3121
4593.5.35 by John Arbash Meinel
Start working on a per-vf implementation test of find_ancestry.
3122
    def find_ancestry(self, keys):
3123
        """See CombinedGraphIndex.find_ancestry()"""
3124
        return self._graph_index.find_ancestry(keys, 0)
3125
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3126
    def get_parent_map(self, keys):
3127
        """Get a map of the parents of keys.
3128
3129
        :param keys: The keys to look up parents for.
3130
        :return: A mapping from keys to parents. Absent keys are absent from
3131
            the mapping.
3132
        """
3133
        self._check_read()
3134
        nodes = self._get_entries(keys)
3135
        result = {}
3136
        if self._parents:
3137
            for node in nodes:
3138
                result[node[1]] = node[3][0]
3139
        else:
3140
            for node in nodes:
3141
                result[node[1]] = None
3142
        return result
3143
3144
    def get_position(self, key):
3145
        """Return details needed to access the version.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3146
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3147
        :return: a tuple (index, data position, size) to hand to the access
3148
            logic to get the record.
3149
        """
3150
        node = self._get_node(key)
3151
        return self._node_to_position(node)
3152
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
3153
    has_key = _mod_index._has_key_from_parent_map
3830.3.9 by Martin Pool
Simplify kvf insert_record_stream; add has_key shorthand methods; update stacking effort tests
3154
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3155
    def keys(self):
3156
        """Get all the keys in the collection.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3157
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3158
        The keys are not ordered.
3159
        """
3160
        self._check_read()
3161
        return [node[1] for node in self._graph_index.iter_all_entries()]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3162
3830.3.12 by Martin Pool
Review cleanups: unify has_key impls, add missing_keys(), clean up exception blocks
3163
    missing_keys = _mod_index._missing_keys_from_parent_map
3164
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3165
    def _node_to_position(self, node):
3166
        """Convert an index value to position details."""
3167
        bits = node[2][1:].split(' ')
3168
        return node[0], int(bits[0]), int(bits[1])
3169
3878.1.2 by John Arbash Meinel
Move the sorting into each index, and customize it for Kndx access.
3170
    def _sort_keys_by_io(self, keys, positions):
3171
        """Figure out an optimal order to read the records for the given keys.
3172
3173
        Sort keys, grouped by index and sorted by position.
3174
3175
        :param keys: A list of keys whose records we want to read. This will be
3176
            sorted 'in-place'.
3177
        :param positions: A dict, such as the one returned by
3178
            _get_components_positions()
3179
        :return: None
3180
        """
3181
        def get_index_memo(key):
3878.1.3 by John Arbash Meinel
Add a comment about what data we are sorting by.
3182
            # index_memo is at offset [1]. It is made up of (GraphIndex,
3183
            # position, size). GI is an object, which will be unique for each
3184
            # pack file. This causes us to group by pack file, then sort by
3185
            # position. Size doesn't matter, but it isn't worth breaking up the
3186
            # tuple.
3878.1.2 by John Arbash Meinel
Move the sorting into each index, and customize it for Kndx access.
3187
            return positions[key][1]
3188
        return keys.sort(key=get_index_memo)
3189
4039.3.5 by John Arbash Meinel
Add direct tests for _get_total_build_size.
3190
    _get_total_build_size = _get_total_build_size
4039.3.2 by John Arbash Meinel
Batch get_record_stream(fulltexts) into 5MB requests.
3191
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3192
3193
class _KnitKeyAccess(object):
3194
    """Access to records in .knit files."""
3195
3196
    def __init__(self, transport, mapper):
3197
        """Create a _KnitKeyAccess with transport and mapper.
3198
3199
        :param transport: The transport the access object is rooted at.
3200
        :param mapper: The mapper used to map keys to .knit files.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3201
        """
3202
        self._transport = transport
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3203
        self._mapper = mapper
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3204
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3205
    def add_raw_records(self, key_sizes, raw_data):
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3206
        """Add raw knit bytes to a storage area.
3207
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3208
        The data is spooled to the container writer in one bytes-record per
3209
        raw data item.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3210
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3211
        :param sizes: An iterable of tuples containing the key and size of each
3212
            raw data segment.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3213
        :param raw_data: A bytestring containing the data.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3214
        :return: A list of memos to retrieve the record later. Each memo is an
3215
            opaque index memo. For _KnitKeyAccess the memo is (key, pos,
3216
            length), where the key is the record key.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3217
        """
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
3218
        if type(raw_data) is not str:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3219
            raise AssertionError(
3220
                'data must be plain bytes was %s' % type(raw_data))
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3221
        result = []
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3222
        offset = 0
3223
        # TODO: This can be tuned for writing to sftp and other servers where
3224
        # append() is relatively expensive by grouping the writes to each key
3225
        # prefix.
3226
        for key, size in key_sizes:
3227
            path = self._mapper.map(key)
3228
            try:
3229
                base = self._transport.append_bytes(path + '.knit',
3230
                    raw_data[offset:offset+size])
3231
            except errors.NoSuchFile:
3232
                self._transport.mkdir(osutils.dirname(path))
3233
                base = self._transport.append_bytes(path + '.knit',
3234
                    raw_data[offset:offset+size])
3235
            # if base == 0:
3236
            # chmod.
3237
            offset += size
3238
            result.append((key, base, size))
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3239
        return result
3240
4187.3.3 by Andrew Bennetts
In KnitVersionedFiles.insert_record_stream, flush the access object before expanding a delta into a fulltext.
3241
    def flush(self):
4187.3.4 by Andrew Bennetts
Better docstrings and comments.
3242
        """Flush pending writes on this access object.
3243
        
3244
        For .knit files this is a no-op.
3245
        """
4187.3.3 by Andrew Bennetts
In KnitVersionedFiles.insert_record_stream, flush the access object before expanding a delta into a fulltext.
3246
        pass
3247
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3248
    def get_raw_records(self, memos_for_retrieval):
3249
        """Get the raw bytes for a records.
3250
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3251
        :param memos_for_retrieval: An iterable containing the access memo for
3252
            retrieving the bytes.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
3253
        :return: An iterator over the bytes of the records.
3254
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3255
        # first pass, group into same-index request to minimise readv's issued.
3256
        request_lists = []
3257
        current_prefix = None
3258
        for (key, offset, length) in memos_for_retrieval:
3259
            if current_prefix == key[:-1]:
3260
                current_list.append((offset, length))
3261
            else:
3262
                if current_prefix is not None:
3263
                    request_lists.append((current_prefix, current_list))
3264
                current_prefix = key[:-1]
3265
                current_list = [(offset, length)]
3266
        # handle the last entry
3267
        if current_prefix is not None:
3268
            request_lists.append((current_prefix, current_list))
3269
        for prefix, read_vector in request_lists:
3270
            path = self._mapper.map(prefix) + '.knit'
3271
            for pos, data in self._transport.readv(path, read_vector):
3272
                yield data
3273
3274
5757.1.3 by Jelmer Vernooij
Revert noknit branch for the moment.
3275
class _DirectPackAccess(object):
3276
    """Access to data in one or more packs with less translation."""
3277
3278
    def __init__(self, index_to_packs, reload_func=None, flush_func=None):
3279
        """Create a _DirectPackAccess object.
3280
3281
        :param index_to_packs: A dict mapping index objects to the transport
3282
            and file names for obtaining data.
3283
        :param reload_func: A function to call if we determine that the pack
3284
            files have moved and we need to reload our caches. See
3285
            bzrlib.repo_fmt.pack_repo.AggregateIndex for more details.
3286
        """
3287
        self._container_writer = None
3288
        self._write_index = None
3289
        self._indices = index_to_packs
3290
        self._reload_func = reload_func
3291
        self._flush_func = flush_func
3292
3293
    def add_raw_records(self, key_sizes, raw_data):
3294
        """Add raw knit bytes to a storage area.
3295
3296
        The data is spooled to the container writer in one bytes-record per
3297
        raw data item.
3298
3299
        :param sizes: An iterable of tuples containing the key and size of each
3300
            raw data segment.
3301
        :param raw_data: A bytestring containing the data.
3302
        :return: A list of memos to retrieve the record later. Each memo is an
3303
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
3304
            length), where the index field is the write_index object supplied
3305
            to the PackAccess object.
3306
        """
3307
        if type(raw_data) is not str:
3308
            raise AssertionError(
3309
                'data must be plain bytes was %s' % type(raw_data))
3310
        result = []
3311
        offset = 0
3312
        for key, size in key_sizes:
3313
            p_offset, p_length = self._container_writer.add_bytes_record(
3314
                raw_data[offset:offset+size], [])
3315
            offset += size
3316
            result.append((self._write_index, p_offset, p_length))
3317
        return result
3318
3319
    def flush(self):
3320
        """Flush pending writes on this access object.
3321
3322
        This will flush any buffered writes to a NewPack.
3323
        """
3324
        if self._flush_func is not None:
3325
            self._flush_func()
3326
            
3327
    def get_raw_records(self, memos_for_retrieval):
3328
        """Get the raw bytes for a records.
3329
3330
        :param memos_for_retrieval: An iterable containing the (index, pos,
3331
            length) memo for retrieving the bytes. The Pack access method
3332
            looks up the pack to use for a given record in its index_to_pack
3333
            map.
3334
        :return: An iterator over the bytes of the records.
3335
        """
3336
        # first pass, group into same-index requests
3337
        request_lists = []
3338
        current_index = None
3339
        for (index, offset, length) in memos_for_retrieval:
3340
            if current_index == index:
3341
                current_list.append((offset, length))
3342
            else:
3343
                if current_index is not None:
3344
                    request_lists.append((current_index, current_list))
3345
                current_index = index
3346
                current_list = [(offset, length)]
3347
        # handle the last entry
3348
        if current_index is not None:
3349
            request_lists.append((current_index, current_list))
3350
        for index, offsets in request_lists:
3351
            try:
3352
                transport, path = self._indices[index]
3353
            except KeyError:
3354
                # A KeyError here indicates that someone has triggered an index
3355
                # reload, and this index has gone missing, we need to start
3356
                # over.
3357
                if self._reload_func is None:
3358
                    # If we don't have a _reload_func there is nothing that can
3359
                    # be done
3360
                    raise
3361
                raise errors.RetryWithNewPacks(index,
3362
                                               reload_occurred=True,
3363
                                               exc_info=sys.exc_info())
3364
            try:
3365
                reader = pack.make_readv_reader(transport, path, offsets)
3366
                for names, read_func in reader.iter_records():
3367
                    yield read_func(None)
3368
            except errors.NoSuchFile:
3369
                # A NoSuchFile error indicates that a pack file has gone
3370
                # missing on disk, we need to trigger a reload, and start over.
3371
                if self._reload_func is None:
3372
                    raise
3373
                raise errors.RetryWithNewPacks(transport.abspath(path),
3374
                                               reload_occurred=False,
3375
                                               exc_info=sys.exc_info())
3376
3377
    def set_writer(self, writer, index, transport_packname):
3378
        """Set a writer to use for adding data."""
3379
        if index is not None:
3380
            self._indices[index] = transport_packname
3381
        self._container_writer = writer
3382
        self._write_index = index
3383
3384
    def reload_or_raise(self, retry_exc):
3385
        """Try calling the reload function, or re-raise the original exception.
3386
3387
        This should be called after _DirectPackAccess raises a
3388
        RetryWithNewPacks exception. This function will handle the common logic
3389
        of determining when the error is fatal versus being temporary.
3390
        It will also make sure that the original exception is raised, rather
3391
        than the RetryWithNewPacks exception.
3392
3393
        If this function returns, then the calling function should retry
3394
        whatever operation was being performed. Otherwise an exception will
3395
        be raised.
3396
3397
        :param retry_exc: A RetryWithNewPacks exception.
3398
        """
3399
        is_error = False
3400
        if self._reload_func is None:
3401
            is_error = True
3402
        elif not self._reload_func():
3403
            # The reload claimed that nothing changed
3404
            if not retry_exc.reload_occurred:
3405
                # If there wasn't an earlier reload, then we really were
3406
                # expecting to find changes. We didn't find them, so this is a
3407
                # hard error
3408
                is_error = True
3409
        if is_error:
3410
            exc_class, exc_value, exc_traceback = retry_exc.exc_info
3411
            raise exc_class, exc_value, exc_traceback
3412
3413
2770.1.2 by Aaron Bentley
Convert to knit-only annotation
3414
def annotate_knit(knit, revision_id):
3415
    """Annotate a knit with no cached annotations.
3416
3417
    This implementation is for knits with no cached annotations.
3418
    It will work for knits with cached annotations, but this is not
3419
    recommended.
3420
    """
3224.1.7 by John Arbash Meinel
_StreamIndex also needs to return the proper values for get_build_details.
3421
    annotator = _KnitAnnotator(knit)
4454.3.26 by John Arbash Meinel
The new _KnitAnnotator based on Annotator seems to pass the test suite.
3422
    return iter(annotator.annotate_flat(revision_id))
3224.1.7 by John Arbash Meinel
_StreamIndex also needs to return the proper values for get_build_details.
3423
3424
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3425
class _KnitAnnotator(annotate.Annotator):
3224.1.5 by John Arbash Meinel
Start using a helper class for doing the knit-pack annotations.
3426
    """Build up the annotations for a text."""
3427
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3428
    def __init__(self, vf):
3429
        annotate.Annotator.__init__(self, vf)
3430
3431
        # TODO: handle Nodes which cannot be extracted
3432
        # self._ghosts = set()
3433
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
3434
        # Map from (key, parent_key) => matching_blocks, should be 'use once'
3435
        self._matching_blocks = {}
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3436
3437
        # KnitContent objects
3438
        self._content_objects = {}
3439
        # The number of children that depend on this fulltext content object
3440
        self._num_compression_children = {}
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3441
        # Delta records that need their compression parent before they can be
3442
        # expanded
3443
        self._pending_deltas = {}
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
3444
        # Fulltext records that are waiting for their parents fulltexts before
3445
        # they can be yielded for annotation
3446
        self._pending_annotation = {}
3224.1.19 by John Arbash Meinel
Work on removing nodes from the working set once they aren't needed.
3447
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3448
        self._all_build_details = {}
3449
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3450
    def _get_build_graph(self, key):
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3451
        """Get the graphs for building texts and annotations.
3452
3453
        The data you need for creating a full text may be different than the
3454
        data you need to annotate that text. (At a minimum, you need both
3455
        parents to create an annotation, but only need 1 parent to generate the
3456
        fulltext.)
3457
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3458
        :return: A list of (key, index_memo) records, suitable for
4371.2.1 by Vincent Ladeuil
Start fixing annotate for gc.
3459
            passing to read_records_iter to start reading in the raw data from
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3460
            the pack file.
3461
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3462
        pending = set([key])
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3463
        records = []
4454.3.64 by John Arbash Meinel
Ensure that _KnitAnnotator also supports add_special_text.
3464
        ann_keys = set()
4454.3.26 by John Arbash Meinel
The new _KnitAnnotator based on Annotator seems to pass the test suite.
3465
        self._num_needed_children[key] = 1
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3466
        while pending:
3467
            # get all pending nodes
3468
            this_iteration = pending
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3469
            build_details = self._vf._index.get_build_details(this_iteration)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3470
            self._all_build_details.update(build_details)
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3471
            # new_nodes = self._vf._index._get_entries(this_iteration)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3472
            pending = set()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3473
            for key, details in build_details.iteritems():
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3474
                (index_memo, compression_parent, parent_keys,
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
3475
                 record_details) = details
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3476
                self._parent_map[key] = parent_keys
4454.3.41 by John Arbash Meinel
Cache the heads provider as long as we know that the parent_map hasn't changed.
3477
                self._heads_provider = None
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
3478
                records.append((key, index_memo))
3224.1.19 by John Arbash Meinel
Work on removing nodes from the working set once they aren't needed.
3479
                # Do we actually need to check _annotated_lines?
4454.3.64 by John Arbash Meinel
Ensure that _KnitAnnotator also supports add_special_text.
3480
                pending.update([p for p in parent_keys
3481
                                   if p not in self._all_build_details])
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3482
                if parent_keys:
3483
                    for parent_key in parent_keys:
3484
                        if parent_key in self._num_needed_children:
3485
                            self._num_needed_children[parent_key] += 1
3486
                        else:
3487
                            self._num_needed_children[parent_key] = 1
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3488
                if compression_parent:
3489
                    if compression_parent in self._num_compression_children:
3490
                        self._num_compression_children[compression_parent] += 1
3491
                    else:
3492
                        self._num_compression_children[compression_parent] = 1
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3493
3494
            missing_versions = this_iteration.difference(build_details.keys())
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3495
            if missing_versions:
4454.3.64 by John Arbash Meinel
Ensure that _KnitAnnotator also supports add_special_text.
3496
                for key in missing_versions:
3497
                    if key in self._parent_map and key in self._text_cache:
3498
                        # We already have this text ready, we just need to
3499
                        # yield it later so we get it annotated
3500
                        ann_keys.add(key)
3501
                        parent_keys = self._parent_map[key]
3502
                        for parent_key in parent_keys:
3503
                            if parent_key in self._num_needed_children:
3504
                                self._num_needed_children[parent_key] += 1
3505
                            else:
3506
                                self._num_needed_children[parent_key] = 1
3507
                        pending.update([p for p in parent_keys
3508
                                           if p not in self._all_build_details])
3509
                    else:
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
3510
                        raise errors.RevisionNotPresent(key, self._vf)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3511
        # Generally we will want to read the records in reverse order, because
3512
        # we find the parent nodes after the children
3513
        records.reverse()
4454.3.64 by John Arbash Meinel
Ensure that _KnitAnnotator also supports add_special_text.
3514
        return records, ann_keys
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3515
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3516
    def _get_needed_texts(self, key, pb=None):
5652.2.4 by Martin Pool
Rename to _immediate_fallback_vfs
3517
        # if True or len(self._vf._immediate_fallback_vfs) > 0:
3518
        if len(self._vf._immediate_fallback_vfs) > 0:
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3519
            # If we have fallbacks, go to the generic path
4454.3.43 by John Arbash Meinel
Initial implementation of a Pyrex annotator.
3520
            for v in annotate.Annotator._get_needed_texts(self, key, pb=pb):
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3521
                yield v
4454.3.26 by John Arbash Meinel
The new _KnitAnnotator based on Annotator seems to pass the test suite.
3522
            return
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3523
        while True:
3524
            try:
4454.3.64 by John Arbash Meinel
Ensure that _KnitAnnotator also supports add_special_text.
3525
                records, ann_keys = self._get_build_graph(key)
4454.3.59 by John Arbash Meinel
Track down why the annotate retry code was failing.
3526
                for idx, (sub_key, text, num_lines) in enumerate(
4454.3.42 by John Arbash Meinel
Make use of the passed in progress bar.
3527
                                                self._extract_texts(records)):
3528
                    if pb is not None:
3529
                        pb.update('annotating', idx, len(records))
4454.3.59 by John Arbash Meinel
Track down why the annotate retry code was failing.
3530
                    yield sub_key, text, num_lines
4454.3.64 by John Arbash Meinel
Ensure that _KnitAnnotator also supports add_special_text.
3531
                for sub_key in ann_keys:
3532
                    text = self._text_cache[sub_key]
3533
                    num_lines = len(text) # bad assumption
3534
                    yield sub_key, text, num_lines
4454.3.26 by John Arbash Meinel
The new _KnitAnnotator based on Annotator seems to pass the test suite.
3535
                return
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3536
            except errors.RetryWithNewPacks, e:
3537
                self._vf._access.reload_or_raise(e)
3538
                # The cached build_details are no longer valid
3539
                self._all_build_details.clear()
3540
4454.3.37 by John Arbash Meinel
Add tests tha left-matching-blocks gets populated.
3541
    def _cache_delta_blocks(self, key, compression_parent, delta, lines):
3542
        parent_lines = self._text_cache[compression_parent]
3543
        blocks = list(KnitContent.get_line_delta_blocks(delta, parent_lines, lines))
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
3544
        self._matching_blocks[(key, compression_parent)] = blocks
4454.3.37 by John Arbash Meinel
Add tests tha left-matching-blocks gets populated.
3545
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3546
    def _expand_record(self, key, parent_keys, compression_parent, record,
3547
                       record_details):
4454.3.37 by John Arbash Meinel
Add tests tha left-matching-blocks gets populated.
3548
        delta = None
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3549
        if compression_parent:
3550
            if compression_parent not in self._content_objects:
3551
                # Waiting for the parent
3552
                self._pending_deltas.setdefault(compression_parent, []).append(
3553
                    (key, parent_keys, record, record_details))
3554
                return None
3555
            # We have the basis parent, so expand the delta
4454.3.33 by John Arbash Meinel
Change the _expand_record code to pop out old content objects.
3556
            num = self._num_compression_children[compression_parent]
3557
            num -= 1
3558
            if num == 0:
3559
                base_content = self._content_objects.pop(compression_parent)
3560
                self._num_compression_children.pop(compression_parent)
3561
            else:
3562
                self._num_compression_children[compression_parent] = num
3563
                base_content = self._content_objects[compression_parent]
4454.3.35 by John Arbash Meinel
Figure out why we don't want to copy_base_content=False.
3564
            # It is tempting to want to copy_base_content=False for the last
3565
            # child object. However, whenever noeol=False,
3566
            # self._text_cache[parent_key] is content._lines. So mutating it
3567
            # gives very bad results.
4454.3.36 by John Arbash Meinel
Only cache the content objects that we will reuse.
3568
            # The alternative is to copy the lines into text cache, but then we
3569
            # are copying anyway, so just do it here.
4454.3.37 by John Arbash Meinel
Add tests tha left-matching-blocks gets populated.
3570
            content, delta = self._vf._factory.parse_record(
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
3571
                key, record, record_details, base_content,
3572
                copy_base_content=True)
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3573
        else:
3574
            # Fulltext record
3575
            content, _ = self._vf._factory.parse_record(
3576
                key, record, record_details, None)
4454.3.36 by John Arbash Meinel
Only cache the content objects that we will reuse.
3577
        if self._num_compression_children.get(key, 0) > 0:
3578
            self._content_objects[key] = content
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3579
        lines = content.text()
3580
        self._text_cache[key] = lines
4454.3.37 by John Arbash Meinel
Add tests tha left-matching-blocks gets populated.
3581
        if delta is not None:
3582
            self._cache_delta_blocks(key, compression_parent, delta, lines)
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3583
        return lines
3584
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
3585
    def _get_parent_annotations_and_matches(self, key, text, parent_key):
3586
        """Get the list of annotations for the parent, and the matching lines.
3587
3588
        :param text: The opaque value given by _get_needed_texts
3589
        :param parent_key: The key for the parent text
3590
        :return: (parent_annotations, matching_blocks)
3591
            parent_annotations is a list as long as the number of lines in
3592
                parent
3593
            matching_blocks is a list of (parent_idx, text_idx, len) tuples
3594
                indicating which lines match between the two texts
3595
        """
3596
        block_key = (key, parent_key)
3597
        if block_key in self._matching_blocks:
3598
            blocks = self._matching_blocks.pop(block_key)
3599
            parent_annotations = self._annotations_cache[parent_key]
3600
            return parent_annotations, blocks
4454.3.43 by John Arbash Meinel
Initial implementation of a Pyrex annotator.
3601
        return annotate.Annotator._get_parent_annotations_and_matches(self,
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
3602
            key, text, parent_key)
3603
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
3604
    def _process_pending(self, key):
3605
        """The content for 'key' was just processed.
3606
3607
        Determine if there is any more pending work to be processed.
3608
        """
3609
        to_return = []
4454.3.31 by John Arbash Meinel
Change the processing lines to now handle fallbacks properly.
3610
        if key in self._pending_deltas:
3611
            compression_parent = key
3612
            children = self._pending_deltas.pop(key)
3613
            for child_key, parent_keys, record, record_details in children:
3614
                lines = self._expand_record(child_key, parent_keys,
3615
                                            compression_parent,
3616
                                            record, record_details)
3617
                if self._check_ready_for_annotations(child_key, parent_keys):
3618
                    to_return.append(child_key)
3619
        # Also check any children that are waiting for this parent to be
3620
        # annotation ready
3621
        if key in self._pending_annotation:
3622
            children = self._pending_annotation.pop(key)
3623
            to_return.extend([c for c, p_keys in children
3624
                              if self._check_ready_for_annotations(c, p_keys)])
3625
        return to_return
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
3626
3627
    def _check_ready_for_annotations(self, key, parent_keys):
3628
        """return true if this text is ready to be yielded.
3629
3630
        Otherwise, this will return False, and queue the text into
3631
        self._pending_annotation
3632
        """
3633
        for parent_key in parent_keys:
3634
            if parent_key not in self._annotations_cache:
3635
                # still waiting on at least one parent text, so queue it up
3636
                # Note that if there are multiple parents, we need to wait
3637
                # for all of them.
3638
                self._pending_annotation.setdefault(parent_key,
3639
                    []).append((key, parent_keys))
3640
                return False
3641
        return True
3642
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3643
    def _extract_texts(self, records):
3644
        """Extract the various texts needed based on records"""
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
3645
        # We iterate in the order read, rather than a strict order requested
3224.1.22 by John Arbash Meinel
Cleanup the extra debugging info, and some >80 char lines.
3646
        # However, process what we can, and put off to the side things that
3647
        # still need parents, cleaning them up when those parents are
3648
        # processed.
4454.3.29 by John Arbash Meinel
Some code comments about what needs to happen.
3649
        # Basic data flow:
3650
        #   1) As 'records' are read, see if we can expand these records into
3651
        #      Content objects (and thus lines)
3652
        #   2) If a given line-delta is waiting on its compression parent, it
3653
        #      gets queued up into self._pending_deltas, otherwise we expand
3654
        #      it, and put it into self._text_cache and self._content_objects
3655
        #   3) If we expanded the text, we will then check to see if all
3656
        #      parents have also been processed. If so, this text gets yielded,
3657
        #      else this record gets set aside into pending_annotation
3658
        #   4) Further, if we expanded the text in (2), we will then check to
3659
        #      see if there are any children in self._pending_deltas waiting to
3660
        #      also be processed. If so, we go back to (2) for those
3661
        #   5) Further again, if we yielded the text, we can then check if that
3662
        #      'unlocks' any of the texts in pending_annotations, which should
3663
        #      then get yielded as well
3664
        # Note that both steps 4 and 5 are 'recursive' in that unlocking one
3665
        # compression child could unlock yet another, and yielding a fulltext
3666
        # will also 'unlock' the children that are waiting on that annotation.
3667
        # (Though also, unlocking 1 parent's fulltext, does not unlock a child
3668
        # if other parents are also waiting.)
3669
        # We want to yield content before expanding child content objects, so
3670
        # that we know when we can re-use the content lines, and the annotation
3671
        # code can know when it can stop caching fulltexts, as well.
3672
4454.3.23 by John Arbash Meinel
Initial attempt at refactoring _KnitAnnotator to derive from Annotator.
3673
        # Children that are missing their compression parent
3674
        pending_deltas = {}
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3675
        for (key, record, digest) in self._vf._read_records_iter(records):
3676
            # ghosts?
4454.3.26 by John Arbash Meinel
The new _KnitAnnotator based on Annotator seems to pass the test suite.
3677
            details = self._all_build_details[key]
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3678
            (_, compression_parent, parent_keys, record_details) = details
3679
            lines = self._expand_record(key, parent_keys, compression_parent,
3680
                                        record, record_details)
3681
            if lines is None:
3682
                # Pending delta should be queued up
3683
                continue
3684
            # At this point, we may be able to yield this content, if all
3685
            # parents are also finished
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
3686
            yield_this_text = self._check_ready_for_annotations(key,
3687
                                                                parent_keys)
4454.3.29 by John Arbash Meinel
Some code comments about what needs to happen.
3688
            if yield_this_text:
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
3689
                # All parents present
3690
                yield key, lines, len(lines)
4454.3.31 by John Arbash Meinel
Change the processing lines to now handle fallbacks properly.
3691
            to_process = self._process_pending(key)
3692
            while to_process:
3693
                this_process = to_process
3694
                to_process = []
3695
                for key in this_process:
3696
                    lines = self._text_cache[key]
3697
                    yield key, lines, len(lines)
3698
                    to_process.extend(self._process_pending(key))
3224.1.10 by John Arbash Meinel
Introduce the heads_provider for reannotate.
3699
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
3700
try:
4573.1.1 by Andrew Bennetts
Fix imports for _knit_load_data_pyx, which was recently renamed.
3701
    from bzrlib._knit_load_data_pyx import _load_data_c as _load_data
4574.3.6 by Martin Pool
More warnings when failing to load extensions
3702
except ImportError, e:
4574.3.8 by Martin Pool
Only mutter extension load errors when they occur, and record for later
3703
    osutils.failed_to_load_extension(e)
2484.1.12 by John Arbash Meinel
Switch the layout to use a matching _knit_load_data_py.py and _knit_load_data_c.pyx
3704
    from bzrlib._knit_load_data_py import _load_data_py as _load_data