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