/brz/remove-bazaar

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