/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1
# Copyright (C) 2005, 2006, 2007 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 = {}
773
        # Do a single query to ascertain parent presence.
774
        present_parent_map = self.get_parent_map(parents)
775
        for parent in parents:
776
            if parent in present_parent_map:
777
                present_parents.append(parent)
778
779
        # Currently we can only compress against the left most present parent.
780
        if (len(present_parents) == 0 or
781
            present_parents[0] != parents[0]):
782
            delta = False
783
        else:
784
            # To speed the extract of texts the delta chain is limited
785
            # to a fixed number of deltas.  This should minimize both
786
            # I/O and the time spend applying deltas.
787
            delta = self._check_should_delta(present_parents[0])
788
789
        text_length = len(line_bytes)
790
        options = []
791
        if lines:
792
            if lines[-1][-1] != '\n':
793
                # copy the contents of lines.
794
                lines = lines[:]
795
                options.append('no-eol')
796
                lines[-1] = lines[-1] + '\n'
797
                line_bytes += '\n'
798
799
        for element in key:
800
            if type(element) != str:
801
                raise TypeError("key contains non-strings: %r" % (key,))
802
        # Knit hunks are still last-element only
803
        version_id = key[-1]
804
        content = self._factory.make(lines, version_id)
805
        if 'no-eol' in options:
806
            # Hint to the content object that its text() call should strip the
807
            # EOL.
808
            content._should_strip_eol = True
809
        if delta or (self._factory.annotated and len(present_parents) > 0):
810
            # Merge annotations from parent texts if needed.
811
            delta_hunks = self._merge_annotations(content, present_parents,
812
                parent_texts, delta, self._factory.annotated,
813
                left_matching_blocks)
814
815
        if delta:
816
            options.append('line-delta')
817
            store_lines = self._factory.lower_line_delta(delta_hunks)
818
            size, bytes = self._record_to_data(key, digest,
819
                store_lines)
820
        else:
821
            options.append('fulltext')
822
            # isinstance is slower and we have no hierarchy.
823
            if self._factory.__class__ == KnitPlainFactory:
824
                # Use the already joined bytes saving iteration time in
825
                # _record_to_data.
826
                size, bytes = self._record_to_data(key, digest,
827
                    lines, [line_bytes])
828
            else:
829
                # get mixed annotation + content and feed it into the
830
                # serialiser.
831
                store_lines = self._factory.lower_fulltext(content)
832
                size, bytes = self._record_to_data(key, digest,
833
                    store_lines)
834
835
        access_memo = self._access.add_raw_records([(key, size)], bytes)[0]
836
        self._index.add_records(
837
            ((key, options, access_memo, parents),),
838
            random_id=random_id)
839
        return digest, text_length, content
840
841
    def annotate(self, key):
842
        """See VersionedFiles.annotate."""
843
        return self._factory.annotate(self, key)
844
845
    def check(self, progress_bar=None):
846
        """See VersionedFiles.check()."""
847
        # This doesn't actually test extraction of everything, but that will
848
        # impact 'bzr check' substantially, and needs to be integrated with
849
        # care. However, it does check for the obvious problem of a delta with
850
        # no basis.
3517.4.14 by Martin Pool
KnitVersionedFiles.check should just check its own keys then recurse into fallbacks
851
        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.
852
        parent_map = self.get_parent_map(keys)
853
        for key in keys:
854
            if self._index.get_method(key) != 'fulltext':
855
                compression_parent = parent_map[key][0]
856
                if compression_parent not in parent_map:
857
                    raise errors.KnitCorrupt(self,
858
                        "Missing basis parent %s for %s" % (
859
                        compression_parent, key))
3517.4.14 by Martin Pool
KnitVersionedFiles.check should just check its own keys then recurse into fallbacks
860
        for fallback_vfs in self._fallback_vfs:
861
            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.
862
863
    def _check_add(self, key, lines, random_id, check_content):
864
        """check that version_id and lines are safe to add."""
3350.6.10 by Martin Pool
VersionedFiles review cleanups
865
        version_id = key[-1]
866
        if contains_whitespace(version_id):
3517.3.1 by Andrew Bennetts
Fix error in error path.
867
            raise InvalidRevisionId(version_id, self)
3350.6.10 by Martin Pool
VersionedFiles review cleanups
868
        self.check_not_reserved_id(version_id)
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
869
        # TODO: If random_id==False and the key is already present, we should
870
        # probably check that the existing content is identical to what is
871
        # being inserted, and otherwise raise an exception.  This would make
872
        # 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.
873
        if check_content:
874
            self._check_lines_not_unicode(lines)
875
            self._check_lines_are_lines(lines)
876
877
    def _check_header(self, key, line):
878
        rec = self._split_header(line)
879
        self._check_header_version(rec, key[-1])
880
        return rec
881
882
    def _check_header_version(self, rec, version_id):
883
        """Checks the header version on original format knit records.
884
        
885
        These have the last component of the key embedded in the record.
886
        """
887
        if rec[1] != version_id:
888
            raise KnitCorrupt(self,
889
                'unexpected version, wanted %r, got %r' % (version_id, rec[1]))
890
891
    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
892
        """Iterate back through the parent listing, looking for a fulltext.
893
894
        This is used when we want to decide whether to add a delta or a new
895
        fulltext. It searches for _max_delta_chain parents. When it finds a
896
        fulltext parent, it sees if the total size of the deltas leading up to
897
        it is large enough to indicate that we want a new full text anyway.
898
899
        Return True if we should create a new delta, False if we should use a
900
        full text.
901
        """
902
        delta_size = 0
903
        fulltext_size = None
2147.1.2 by John Arbash Meinel
Simplify the knit max-chain detection code.
904
        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.
905
            # XXX: Collapse these two queries:
3350.8.9 by Robert Collins
define behaviour for add_lines with stacked storage.
906
            try:
3582.1.14 by Martin Pool
Clearer comments about KnitVersionedFile stacking
907
                # Note that this only looks in the index of this particular
908
                # KnitVersionedFiles, not in the fallbacks.  This ensures that
909
                # we won't store a delta spanning physical repository
910
                # boundaries.
3350.8.9 by Robert Collins
define behaviour for add_lines with stacked storage.
911
                method = self._index.get_method(parent)
912
            except RevisionNotPresent:
913
                # Some basis is not locally present: always delta
914
                return False
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
915
            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
916
            if method == 'fulltext':
917
                fulltext_size = size
918
                break
919
            delta_size += size
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
920
            # We don't explicitly check for presence because this is in an
921
            # 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.
922
            # TODO: This should be asking for compression parent, not graph
923
            # parent.
924
            parent = self._index.get_parent_map([parent])[parent][0]
2147.1.2 by John Arbash Meinel
Simplify the knit max-chain detection code.
925
        else:
926
            # 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
927
            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.
928
        # Simple heuristic - if the total I/O wold be greater as a delta than
929
        # the originally installed fulltext, we create a new fulltext.
2147.1.2 by John Arbash Meinel
Simplify the knit max-chain detection code.
930
        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
931
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
932
    def _build_details_to_components(self, build_details):
933
        """Convert a build_details tuple to a position tuple."""
934
        # record_details, access_memo, compression_parent
935
        return build_details[3], build_details[0], build_details[1]
936
3350.6.10 by Martin Pool
VersionedFiles review cleanups
937
    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.
938
        """Produce a map of position data for the components of keys.
939
940
        This data is intended to be used for retrieving the knit records.
941
942
        A dict of key to (record_details, index_memo, next, parents) is
943
        returned.
944
        method is the way referenced data should be applied.
945
        index_memo is the handle to pass to the data access to actually get the
946
            data
947
        next is the build-parent of the version, or None for fulltexts.
948
        parents is the version_ids of the parents of this version
949
3350.6.10 by Martin Pool
VersionedFiles review cleanups
950
        :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.
951
            just ignore it.
952
        """
953
        component_data = {}
954
        pending_components = keys
955
        while pending_components:
956
            build_details = self._index.get_build_details(pending_components)
957
            current_components = set(pending_components)
958
            pending_components = set()
959
            for key, details in build_details.iteritems():
960
                (index_memo, compression_parent, parents,
961
                 record_details) = details
962
                method = record_details[0]
963
                if compression_parent is not None:
964
                    pending_components.add(compression_parent)
965
                component_data[key] = self._build_details_to_components(details)
966
            missing = current_components.difference(build_details)
3350.6.10 by Martin Pool
VersionedFiles review cleanups
967
            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.
968
                raise errors.RevisionNotPresent(missing.pop(), self)
969
        return component_data
970
       
971
    def _get_content(self, key, parent_texts={}):
972
        """Returns a content object that makes up the specified
973
        version."""
974
        cached_version = parent_texts.get(key, None)
975
        if cached_version is not None:
976
            # Ensure the cache dict is valid.
977
            if not self.get_parent_map([key]):
978
                raise RevisionNotPresent(key, self)
979
            return cached_version
980
        text_map, contents_map = self._get_content_maps([key])
981
        return contents_map[key]
982
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
983
    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.
984
        """Produce maps of text and KnitContents
985
        
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
986
        :param keys: The keys to produce content maps for.
987
        :param nonlocal_keys: An iterable of keys(possibly intersecting keys)
988
            which are known to not be in this knit, but rather in one of the
989
            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.
990
        :return: (text_map, content_map) where text_map contains the texts for
3350.6.10 by Martin Pool
VersionedFiles review cleanups
991
            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.
992
        """
993
        # FUTURE: This function could be improved for the 'extract many' case
994
        # by tracking each component and only doing the copy when the number of
995
        # children than need to apply delta's to it is > 1 or it is part of the
996
        # final output.
997
        keys = list(keys)
998
        multiple_versions = len(keys) != 1
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
999
        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.
1000
1001
        text_map = {}
1002
        content_map = {}
1003
        final_content = {}
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
1004
        if nonlocal_keys is None:
1005
            nonlocal_keys = set()
1006
        else:
1007
            nonlocal_keys = frozenset(nonlocal_keys)
1008
        missing_keys = set(nonlocal_keys)
1009
        for source in self._fallback_vfs:
1010
            if not missing_keys:
1011
                break
1012
            for record in source.get_record_stream(missing_keys,
1013
                'unordered', True):
1014
                if record.storage_kind == 'absent':
1015
                    continue
1016
                missing_keys.remove(record.key)
1017
                lines = split_lines(record.get_bytes_as('fulltext'))
1018
                text_map[record.key] = lines
3350.8.10 by Robert Collins
Stacked insert_record_stream.
1019
                content_map[record.key] = PlainKnitContent(lines, record.key)
1020
                if record.key in keys:
1021
                    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.
1022
        for key in keys:
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
1023
            if key in nonlocal_keys:
1024
                # already handled
1025
                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.
1026
            components = []
1027
            cursor = key
1028
            while cursor is not None:
3350.8.10 by Robert Collins
Stacked insert_record_stream.
1029
                try:
1030
                    record, record_details, digest, next = record_map[cursor]
1031
                except KeyError:
1032
                    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.
1033
                components.append((cursor, record, record_details, digest))
3350.8.10 by Robert Collins
Stacked insert_record_stream.
1034
                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.
1035
                if cursor in content_map:
3350.8.10 by Robert Collins
Stacked insert_record_stream.
1036
                    # no need to plan further back
1037
                    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.
1038
                    break
1039
1040
            content = None
1041
            for (component_id, record, record_details,
1042
                 digest) in reversed(components):
1043
                if component_id in content_map:
1044
                    content = content_map[component_id]
1045
                else:
1046
                    content, delta = self._factory.parse_record(key[-1],
1047
                        record, record_details, content,
1048
                        copy_base_content=multiple_versions)
1049
                    if multiple_versions:
1050
                        content_map[component_id] = content
1051
1052
            final_content[key] = content
1053
1054
            # digest here is the digest from the last applied component.
1055
            text = content.text()
1056
            actual_sha = sha_strings(text)
1057
            if actual_sha != digest:
3787.1.1 by Robert Collins
Embed the failed text in sha1 knit errors.
1058
                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.
1059
            text_map[key] = text
1060
        return text_map, final_content
1061
1062
    def get_parent_map(self, keys):
3517.4.17 by Martin Pool
Redo base Repository.get_parent_map to use .revisions graph
1063
        """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.
1064
1065
        :param keys: The keys to look up parents for.
1066
        :return: A mapping from keys to parents. Absent keys are absent from
1067
            the mapping.
1068
        """
3350.8.14 by Robert Collins
Review feedback.
1069
        return self._get_parent_map_with_sources(keys)[0]
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1070
3350.8.14 by Robert Collins
Review feedback.
1071
    def _get_parent_map_with_sources(self, keys):
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1072
        """Get a map of the parents of keys.
1073
1074
        :param keys: The keys to look up parents for.
1075
        :return: A tuple. The first element is a mapping from keys to parents.
1076
            Absent keys are absent from the mapping. The second element is a
1077
            list with the locations each key was found in. The first element
1078
            is the in-this-knit parents, the second the first fallback source,
1079
            and so on.
1080
        """
3350.8.2 by Robert Collins
stacked get_parent_map.
1081
        result = {}
1082
        sources = [self._index] + self._fallback_vfs
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1083
        source_results = []
3350.8.2 by Robert Collins
stacked get_parent_map.
1084
        missing = set(keys)
1085
        for source in sources:
1086
            if not missing:
1087
                break
1088
            new_result = source.get_parent_map(missing)
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1089
            source_results.append(new_result)
3350.8.2 by Robert Collins
stacked get_parent_map.
1090
            result.update(new_result)
1091
            missing.difference_update(set(new_result))
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1092
        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.
1093
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1094
    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.
1095
        """Produce a dictionary of knit records.
1096
        
1097
        :return: {key:(record, record_details, digest, next)}
1098
            record
1099
                data returned from read_records
1100
            record_details
1101
                opaque information to pass to parse_record
1102
            digest
1103
                SHA1 digest of the full text after all steps are done
1104
            next
1105
                build-parent of the version, i.e. the leftmost ancestor.
1106
                Will be None if the record is not a delta.
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1107
        :param keys: The keys to build a map for
1108
        :param allow_missing: If some records are missing, rather than 
1109
            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.
1110
        """
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1111
        position_map = self._get_components_positions(keys,
3350.8.13 by Robert Collins
Merge bzr.dev, fixing minor skew.
1112
            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.
1113
        # key = component_id, r = record_details, i_m = index_memo, n = next
1114
        records = [(key, i_m) for key, (r, i_m, n)
1115
                             in position_map.iteritems()]
1116
        record_map = {}
1117
        for key, record, digest in \
1118
                self._read_records_iter(records):
1119
            (record_details, index_memo, next) = position_map[key]
1120
            record_map[key] = record, record_details, digest, next
1121
        return record_map
1122
3763.4.1 by John Arbash Meinel
Possible fix for bug #269456.
1123
    def _split_by_prefix(self, keys):
1124
        """For the given keys, split them up based on their prefix.
1125
1126
        To keep memory pressure somewhat under control, split the
1127
        requests back into per-file-id requests, otherwise "bzr co"
1128
        extracts the full tree into memory before writing it to disk.
1129
        This should be revisited if _get_content_maps() can ever cross
1130
        file-id boundaries.
1131
1132
        :param keys: An iterable of key tuples
1133
        :return: A dict of {prefix: [key_list]}
1134
        """
1135
        split_by_prefix = {}
1136
        for key in keys:
1137
            if len(key) == 1:
1138
                split_by_prefix.setdefault('', []).append(key)
1139
            else:
1140
                split_by_prefix.setdefault(key[0], []).append(key)
1141
        return split_by_prefix
1142
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1143
    def get_record_stream(self, keys, ordering, include_delta_closure):
1144
        """Get a stream of records for keys.
1145
1146
        :param keys: The keys to include.
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
1147
        :param ordering: Either 'unordered' or 'topological'. A topologically
1148
            sorted stream has compression parents strictly before their
1149
            children.
1150
        :param include_delta_closure: If True then the closure across any
1151
            compression parents will be included (in the opaque data).
1152
        :return: An iterator of ContentFactory objects, each of which is only
1153
            valid until the iterator is advanced.
1154
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1155
        # keys might be a generator
1156
        keys = set(keys)
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1157
        if not keys:
1158
            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.
1159
        if not self._index.has_graph:
1160
            # Cannot topological order when no graph has been stored.
1161
            ordering = 'unordered'
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
1162
        if include_delta_closure:
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1163
            positions = self._get_components_positions(keys, allow_missing=True)
3350.3.3 by Robert Collins
Functional get_record_stream interface tests covering full interface.
1164
        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.
1165
            build_details = self._index.get_build_details(keys)
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
1166
            # map from key to
1167
            # (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.
1168
            positions = dict((key, self._build_details_to_components(details))
1169
                for key, details in build_details.iteritems())
1170
        absent_keys = keys.difference(set(positions))
1171
        # There may be more absent keys : if we're missing the basis component
1172
        # and are trying to include the delta closure.
1173
        if include_delta_closure:
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1174
            needed_from_fallback = set()
3350.6.11 by Martin Pool
Review cleanups and documentation from Robert's mail on 2080618
1175
            # Build up reconstructable_keys dict.  key:True in this dict means
1176
            # the key can be reconstructed.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1177
            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.
1178
            for key in keys:
1179
                # the delta chain
1180
                try:
1181
                    chain = [key, positions[key][2]]
1182
                except KeyError:
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1183
                    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.
1184
                    continue
1185
                result = True
1186
                while chain[-1] is not None:
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1187
                    if chain[-1] in reconstructable_keys:
1188
                        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.
1189
                        break
1190
                    else:
1191
                        try:
1192
                            chain.append(positions[chain[-1]][2])
1193
                        except KeyError:
1194
                            # missing basis component
3350.8.10 by Robert Collins
Stacked insert_record_stream.
1195
                            needed_from_fallback.add(chain[-1])
1196
                            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.
1197
                            break
1198
                for chain_key in chain[:-1]:
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1199
                    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.
1200
                if not result:
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1201
                    needed_from_fallback.add(key)
1202
        # Double index lookups here : need a unified api ?
3350.8.14 by Robert Collins
Review feedback.
1203
        global_map, parent_maps = self._get_parent_map_with_sources(keys)
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1204
        if ordering == 'topological':
1205
            # Global topological sort
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
1206
            present_keys = tsort.topo_sort(global_map)
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1207
            # Now group by source:
1208
            source_keys = []
1209
            current_source = None
1210
            for key in present_keys:
1211
                for parent_map in parent_maps:
1212
                    if key in parent_map:
1213
                        key_source = parent_map
1214
                        break
1215
                if current_source is not key_source:
1216
                    source_keys.append((key_source, []))
1217
                    current_source = key_source
1218
                source_keys[-1][1].append(key)
1219
        else:
3606.7.7 by John Arbash Meinel
Add tests for the fetching behavior.
1220
            if ordering != 'unordered':
1221
                raise AssertionError('valid values for ordering are:'
1222
                    ' "unordered" or "topological" not: %r'
1223
                    % (ordering,))
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1224
            # Just group by source; remote sources first.
1225
            present_keys = []
1226
            source_keys = []
1227
            for parent_map in reversed(parent_maps):
1228
                source_keys.append((parent_map, []))
1229
                for key in parent_map:
1230
                    present_keys.append(key)
1231
                    source_keys[-1][1].append(key)
1232
        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.
1233
        for key in absent_keys:
1234
            yield AbsentContentFactory(key)
1235
        # restrict our view to the keys we can answer.
1236
        # 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.
1237
        # XXX: At that point we need to consider the impact of double reads by
1238
        # 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.
1239
        if include_delta_closure:
1240
            # XXX: get_content_maps performs its own index queries; allow state
1241
            # to be passed in.
3763.4.1 by John Arbash Meinel
Possible fix for bug #269456.
1242
            non_local_keys = needed_from_fallback - absent_keys
1243
            prefix_split_keys = self._split_by_prefix(present_keys)
1244
            prefix_split_non_local_keys = self._split_by_prefix(non_local_keys)
1245
            for prefix, keys in prefix_split_keys.iteritems():
1246
                non_local = prefix_split_non_local_keys.get(prefix, [])
1247
                non_local = set(non_local)
1248
                text_map, _ = self._get_content_maps(keys, non_local)
1249
                for key in keys:
1250
                    lines = text_map.pop(key)
1251
                    text = ''.join(lines)
1252
                    yield FulltextContentFactory(key, global_map[key], None,
1253
                                                 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.
1254
        else:
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
1255
            for source, keys in source_keys:
1256
                if source is parent_maps[0]:
1257
                    # this KnitVersionedFiles
1258
                    records = [(key, positions[key][1]) for key in keys]
1259
                    for key, raw_data, sha1 in self._read_records_iter_raw(records):
1260
                        (record_details, index_memo, _) = positions[key]
1261
                        yield KnitContentFactory(key, global_map[key],
1262
                            record_details, sha1, raw_data, self._factory.annotated, None)
1263
                else:
1264
                    vf = self._fallback_vfs[parent_maps.index(source) - 1]
1265
                    for record in vf.get_record_stream(keys, ordering,
1266
                        include_delta_closure):
1267
                        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.
1268
1269
    def get_sha1s(self, keys):
1270
        """See VersionedFiles.get_sha1s()."""
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1271
        missing = set(keys)
1272
        record_map = self._get_record_map(missing, allow_missing=True)
1273
        result = {}
1274
        for key, details in record_map.iteritems():
1275
            if key not in missing:
1276
                continue
1277
            # record entry 2 is the 'digest'.
1278
            result[key] = details[2]
1279
        missing.difference_update(set(result))
1280
        for source in self._fallback_vfs:
1281
            if not missing:
1282
                break
1283
            new_result = source.get_sha1s(missing)
1284
            result.update(new_result)
1285
            missing.difference_update(set(new_result))
1286
        return result
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1287
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1288
    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.
1289
        """Insert a record stream into this container.
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1290
1291
        :param stream: A stream of records to insert. 
1292
        :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.
1293
        :seealso VersionedFiles.get_record_stream:
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1294
        """
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1295
        def get_adapter(adapter_key):
1296
            try:
1297
                return adapters[adapter_key]
1298
            except KeyError:
1299
                adapter_factory = adapter_registry.get(adapter_key)
1300
                adapter = adapter_factory(self)
1301
                adapters[adapter_key] = adapter
1302
                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.
1303
        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.
1304
            # 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.
1305
            annotated = "annotated-"
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
1306
            convertibles = []
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1307
        else:
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
1308
            # 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.
1309
            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.
1310
            convertibles = set(["knit-annotated-ft-gz"])
1311
            if self._max_delta_chain:
1312
                convertibles.add("knit-annotated-delta-gz")
3350.3.22 by Robert Collins
Review feedback.
1313
        # 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.
1314
        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.
1315
        if self._max_delta_chain:
1316
            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.
1317
        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.
1318
        knit_types = native_types.union(convertibles)
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1319
        adapters = {}
3350.3.22 by Robert Collins
Review feedback.
1320
        # 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.
1321
        # basis parent is missing. We don't buffer all because generating
1322
        # annotations may require access to some of the new records. However we
1323
        # can't generate annotations from new deltas until their basis parent
1324
        # is present anyway, so we get away with not needing an index that
3350.3.22 by Robert Collins
Review feedback.
1325
        # includes the new keys.
3350.3.17 by Robert Collins
Prevent corrupt knits being created when a stream is interrupted with basis parents not present.
1326
        # key = basis_parent, value = index entry to add
1327
        buffered_index_entries = {}
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1328
        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.
1329
            parents = record.parents
3350.3.15 by Robert Collins
Update the insert_record_stream contract to error if an absent record is provided.
1330
            # Raise an error when a record is missing.
1331
            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.
1332
                raise RevisionNotPresent([record.key], self)
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1333
            if record.storage_kind in knit_types:
1334
                if record.storage_kind not in native_types:
1335
                    try:
1336
                        adapter_key = (record.storage_kind, "knit-delta-gz")
1337
                        adapter = get_adapter(adapter_key)
1338
                    except KeyError:
1339
                        adapter_key = (record.storage_kind, "knit-ft-gz")
1340
                        adapter = get_adapter(adapter_key)
1341
                    bytes = adapter.get_bytes(
1342
                        record, record.get_bytes_as(record.storage_kind))
1343
                else:
1344
                    bytes = record.get_bytes_as(record.storage_kind)
1345
                options = [record._build_details[0]]
1346
                if record._build_details[1]:
1347
                    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.
1348
                # Just blat it across.
1349
                # Note: This does end up adding data on duplicate keys. As
1350
                # modern repositories use atomic insertions this should not
1351
                # lead to excessive growth in the event of interrupted fetches.
1352
                # 'knit' repositories may suffer excessive growth, but as a
1353
                # deprecated format this is tolerable. It can be fixed if
1354
                # needed by in the kndx index support raising on a duplicate
1355
                # 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.
1356
                access_memo = self._access.add_raw_records(
1357
                    [(record.key, len(bytes))], bytes)[0]
1358
                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.
1359
                buffered = False
1360
                if 'fulltext' not in options:
1361
                    basis_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.
1362
                    # Note that pack backed knits don't need to buffer here
1363
                    # because they buffer all writes to the transaction level,
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1364
                    # 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.
1365
                    # the query here has sufficient cost to show up in
1366
                    # profiling we should do that.
1367
                    if basis_parent not in self.get_parent_map([basis_parent]):
3350.3.17 by Robert Collins
Prevent corrupt knits being created when a stream is interrupted with basis parents not present.
1368
                        pending = buffered_index_entries.setdefault(
1369
                            basis_parent, [])
1370
                        pending.append(index_entry)
1371
                        buffered = True
1372
                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.
1373
                    self._index.add_records([index_entry])
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1374
            elif record.storage_kind == 'fulltext':
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1375
                self.add_lines(record.key, parents,
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1376
                    split_lines(record.get_bytes_as('fulltext')))
1377
            else:
1378
                adapter_key = record.storage_kind, 'fulltext'
3350.3.9 by Robert Collins
Avoid full text reconstruction when transferring knit to knit via record streams.
1379
                adapter = get_adapter(adapter_key)
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1380
                lines = split_lines(adapter.get_bytes(
1381
                    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.
1382
                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.
1383
                    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.
1384
                except errors.RevisionAlreadyPresent:
1385
                    pass
3350.3.17 by Robert Collins
Prevent corrupt knits being created when a stream is interrupted with basis parents not present.
1386
            # 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.
1387
            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.
1388
            while added_keys:
1389
                key = added_keys.pop(0)
1390
                if key in buffered_index_entries:
1391
                    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.
1392
                    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.
1393
                    added_keys.extend(
1394
                        [index_entry[0] for index_entry in index_entries])
1395
                    del buffered_index_entries[key]
1396
        # If there were any deltas which had a missing basis parent, error.
1397
        if buffered_index_entries:
1398
            raise errors.RevisionNotPresent(buffered_index_entries.keys()[0],
1399
                self)
3350.3.8 by Robert Collins
Basic stream insertion, no fast path yet for knit to knit.
1400
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1401
    def iter_lines_added_or_present_in_keys(self, keys, pb=None):
1402
        """Iterate over the lines in the versioned files from keys.
1403
1404
        This may return lines from other keys. Each item the returned
1405
        iterator yields is a tuple of a line and a text version that that line
1406
        is present in (not introduced in).
1407
1408
        Ordering of results is in whatever order is most suitable for the
1409
        underlying storage format.
1410
1411
        If a progress bar is supplied, it may be used to indicate progress.
1412
        The caller is responsible for cleaning up progress bars (because this
1413
        is an iterator).
1414
1415
        NOTES:
1416
         * Lines are normalised by the underlying store: they will all have \n
1417
           terminators.
1418
         * Lines are returned in arbitrary order.
1419
1420
        :return: An iterator over (line, key).
1421
        """
1422
        if pb is None:
1423
            pb = progress.DummyProgress()
1424
        keys = set(keys)
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
1425
        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.
1426
        # we don't care about inclusions, the caller cares.
1427
        # but we need to setup a list of records to visit.
1428
        # we need key, position, length
1429
        key_records = []
1430
        build_details = self._index.get_build_details(keys)
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
1431
        for key, details in build_details.iteritems():
1432
            if key in keys:
1433
                key_records.append((key, details[0]))
1434
                keys.remove(key)
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1435
        records_iter = enumerate(self._read_records_iter(key_records))
1436
        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.
1437
            pb.update('Walking content.', key_idx, total)
1438
            compression_parent = build_details[key][1]
1439
            if compression_parent is None:
1440
                # fulltext
1441
                line_iterator = self._factory.get_fulltext_content(data)
1442
            else:
1443
                # Delta 
1444
                line_iterator = self._factory.get_linedelta_content(data)
1445
            # XXX: It might be more efficient to yield (key,
1446
            # line_iterator) in the future. However for now, this is a simpler
1447
            # change to integrate into the rest of the codebase. RBC 20071110
1448
            for line in line_iterator:
1449
                yield line, key
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
1450
        for source in self._fallback_vfs:
1451
            if not keys:
1452
                break
1453
            source_keys = set()
1454
            for line, key in source.iter_lines_added_or_present_in_keys(keys):
1455
                source_keys.add(key)
1456
                yield line, key
1457
            keys.difference_update(source_keys)
1458
        if keys:
3749.1.1 by Martin Pool
Fix error construction in KnitVersionedFiles
1459
            # XXX: strictly the second parameter is meant to be the file id
1460
            # but it's not easily accessible here.
1461
            raise RevisionNotPresent(keys, repr(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.
1462
        pb.update('Walking content.', total, total)
1463
1464
    def _make_line_delta(self, delta_seq, new_content):
1465
        """Generate a line delta from delta_seq and new_content."""
1466
        diff_hunks = []
1467
        for op in delta_seq.get_opcodes():
1468
            if op[0] == 'equal':
1469
                continue
1470
            diff_hunks.append((op[1], op[2], op[4]-op[3], new_content._lines[op[3]:op[4]]))
1471
        return diff_hunks
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1472
1596.2.34 by Robert Collins
Optimise knit add to only diff once per parent, not once per parent + once for the delta generation.
1473
    def _merge_annotations(self, content, parents, parent_texts={},
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
1474
                           delta=None, annotated=None,
1475
                           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.
1476
        """Merge annotations for content and generate deltas.
1477
        
1478
        This is done by comparing the annotations based on changes to the text
1479
        and generating a delta on the resulting full texts. If annotations are
1480
        not being created then a simple delta is created.
1596.2.27 by Robert Collins
Note potential improvements in knit adds.
1481
        """
2520.4.146 by Aaron Bentley
Avoid get_matching_blocks for un-annotated text
1482
        if left_matching_blocks is not None:
1483
            delta_seq = diff._PrematchedMatcher(left_matching_blocks)
1484
        else:
1485
            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.
1486
        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.
1487
            for parent_key in parents:
1488
                merge_content = self._get_content(parent_key, parent_texts)
1489
                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
1490
                    seq = delta_seq
2520.4.140 by Aaron Bentley
Use matching blocks from mpdiff for knit delta creation
1491
                else:
1492
                    seq = patiencediff.PatienceSequenceMatcher(
1493
                        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.
1494
                for i, j, n in seq.get_matching_blocks():
1495
                    if n == 0:
1496
                        continue
3460.2.1 by Robert Collins
* Inserting a bundle which changes the contents of a file with no trailing
1497
                    # this copies (origin, text) pairs across to the new
1498
                    # content for any line that matches the last-checked
2520.4.146 by Aaron Bentley
Avoid get_matching_blocks for un-annotated text
1499
                    # 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.
1500
                    content._lines[j:j+n] = merge_content._lines[i:i+n]
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1501
            # XXX: Robert says the following block is a workaround for a
1502
            # 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.
1503
            if content._lines and content._lines[-1][1][-1] != '\n':
1504
                # The copied annotation was from a line without a trailing EOL,
1505
                # reinstate one for the content object, to ensure correct
1506
                # serialization.
1507
                line = content._lines[-1][1] + '\n'
1508
                content._lines[-1] = (content._lines[-1][0], line)
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
1509
        if delta:
2520.4.146 by Aaron Bentley
Avoid get_matching_blocks for un-annotated text
1510
            if delta_seq is None:
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
1511
                reference_content = self._get_content(parents[0], parent_texts)
1512
                new_texts = content.text()
1513
                old_texts = reference_content.text()
2104.4.2 by John Arbash Meinel
Small cleanup and NEWS entry about fixing bug #65714
1514
                delta_seq = patiencediff.PatienceSequenceMatcher(
2100.2.1 by wang
Replace python's difflib by patiencediff because the worst case
1515
                                                 None, old_texts, new_texts)
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
1516
            return self._make_line_delta(delta_seq, content)
1517
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1518
    def _parse_record(self, version_id, data):
1519
        """Parse an original format knit record.
1520
1521
        These have the last element of the key only present in the stored data.
1522
        """
1523
        rec, record_contents = self._parse_record_unchecked(data)
1524
        self._check_header_version(rec, version_id)
1525
        return record_contents, rec[3]
1526
1527
    def _parse_record_header(self, key, raw_data):
1528
        """Parse a record header for consistency.
1529
1530
        :return: the header and the decompressor stream.
1531
                 as (stream, header_record)
1532
        """
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
1533
        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.
1534
        try:
1535
            # Current serialise
1536
            rec = self._check_header(key, df.readline())
1537
        except Exception, e:
1538
            raise KnitCorrupt(self,
1539
                              "While reading {%s} got %s(%s)"
1540
                              % (key, e.__class__.__name__, str(e)))
1541
        return df, rec
1542
1543
    def _parse_record_unchecked(self, data):
1544
        # profiling notes:
1545
        # 4168 calls in 2880 217 internal
1546
        # 4168 calls to _parse_record_header in 2121
1547
        # 4168 calls to readlines in 330
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
1548
        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.
1549
        try:
1550
            record_contents = df.readlines()
1551
        except Exception, e:
1552
            raise KnitCorrupt(self, "Corrupt compressed record %r, got %s(%s)" %
1553
                (data, e.__class__.__name__, str(e)))
1554
        header = record_contents.pop(0)
1555
        rec = self._split_header(header)
1556
        last_line = record_contents.pop()
1557
        if len(record_contents) != int(rec[2]):
1558
            raise KnitCorrupt(self,
1559
                              'incorrect number of lines %s != %s'
1560
                              ' for version {%s} %s'
1561
                              % (len(record_contents), int(rec[2]),
1562
                                 rec[1], record_contents))
1563
        if last_line != 'end %s\n' % rec[1]:
1564
            raise KnitCorrupt(self,
1565
                              'unexpected version end line %r, wanted %r' 
1566
                              % (last_line, rec[1]))
1567
        df.close()
1568
        return rec, record_contents
1569
1570
    def _read_records_iter(self, records):
1571
        """Read text records from data file and yield result.
1572
1573
        The result will be returned in whatever is the fastest to read.
1574
        Not by the order requested. Also, multiple requests for the same
1575
        record will only yield 1 response.
1576
        :param records: A list of (key, access_memo) entries
1577
        :return: Yields (key, contents, digest) in the order
1578
                 read, not the order requested
1579
        """
1580
        if not records:
1581
            return
1582
1583
        # XXX: This smells wrong, IO may not be getting ordered right.
1584
        needed_records = sorted(set(records), key=operator.itemgetter(1))
1585
        if not needed_records:
1586
            return
1587
1588
        # The transport optimizes the fetching as well 
1589
        # (ie, reads continuous ranges.)
1590
        raw_data = self._access.get_raw_records(
1591
            [index_memo for key, index_memo in needed_records])
1592
1593
        for (key, index_memo), data in \
1594
                izip(iter(needed_records), raw_data):
1595
            content, digest = self._parse_record(key[-1], data)
1596
            yield key, content, digest
1597
1598
    def _read_records_iter_raw(self, records):
1599
        """Read text records from data file and yield raw data.
1600
1601
        This unpacks enough of the text record to validate the id is
1602
        as expected but thats all.
1603
1604
        Each item the iterator yields is (key, bytes, sha1_of_full_text).
1605
        """
1606
        # setup an iterator of the external records:
1607
        # uses readv so nice and fast we hope.
1608
        if len(records):
1609
            # grab the disk data needed.
1610
            needed_offsets = [index_memo for key, index_memo
1611
                                           in records]
1612
            raw_records = self._access.get_raw_records(needed_offsets)
1613
1614
        for key, index_memo in records:
1615
            data = raw_records.next()
1616
            # validate the header (note that we can only use the suffix in
1617
            # current knit records).
1618
            df, rec = self._parse_record_header(key, data)
1619
            df.close()
1620
            yield key, data, rec[3]
1621
1622
    def _record_to_data(self, key, digest, lines, dense_lines=None):
1623
        """Convert key, digest, lines into a raw data block.
1624
        
1625
        :param key: The key of the record. Currently keys are always serialised
1626
            using just the trailing component.
1627
        :param dense_lines: The bytes of lines but in a denser form. For
1628
            instance, if lines is a list of 1000 bytestrings each ending in \n,
1629
            dense_lines may be a list with one line in it, containing all the
1630
            1000's lines and their \n's. Using dense_lines if it is already
1631
            known is a win because the string join to create bytes in this
1632
            function spends less time resizing the final string.
1633
        :return: (len, a StringIO instance with the raw data ready to read.)
1634
        """
1635
        # Note: using a string copy here increases memory pressure with e.g.
1636
        # ISO's, but it is about 3 seconds faster on a 1.2Ghz intel machine
1637
        # when doing the initial commit of a mozilla tree. RBC 20070921
1638
        bytes = ''.join(chain(
1639
            ["version %s %d %s\n" % (key[-1],
1640
                                     len(lines),
1641
                                     digest)],
1642
            dense_lines or lines,
1643
            ["end %s\n" % key[-1]]))
1644
        if type(bytes) != str:
1645
            raise AssertionError(
1646
                'data must be plain bytes was %s' % type(bytes))
1647
        if lines and lines[-1][-1] != '\n':
1648
            raise ValueError('corrupt lines value %r' % lines)
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
1649
        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.
1650
        return len(compressed_bytes), compressed_bytes
1651
1652
    def _split_header(self, line):
1653
        rec = line.split()
1654
        if len(rec) != 4:
1655
            raise KnitCorrupt(self,
1656
                              'unexpected number of elements in record header')
1657
        return rec
1658
1659
    def keys(self):
1660
        """See VersionedFiles.keys."""
1661
        if 'evil' in debug.debug_flags:
1662
            trace.mutter_callsite(2, "keys scales with size of history")
3350.8.4 by Robert Collins
Vf.keys() stacking support.
1663
        sources = [self._index] + self._fallback_vfs
1664
        result = set()
1665
        for source in sources:
1666
            result.update(source.keys())
1667
        return result
1668
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1669
1670
class _KndxIndex(object):
1671
    """Manages knit index files
1672
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1673
    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.
1674
    fast lookups of revision information.  The cursor of the index
1675
    file is always pointing to the end, making it easy to append
1676
    entries.
1677
1678
    _cache is a cache for fast mapping from version id to a Index
1679
    object.
1680
1681
    _history is a cache for fast mapping from indexes to version ids.
1682
1683
    The index data format is dictionary compressed when it comes to
1684
    parent references; a index entry may only have parents that with a
1685
    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.
1686
1687
    Duplicate entries may be written to the index for a single version id
1688
    if this is done then the latter one completely replaces the former:
1689
    this allows updates to correct version and parent information. 
1690
    Note that the two entries may share the delta, and that successive
1691
    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.
1692
1693
    The index file on disc contains a header, followed by one line per knit
1694
    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).
1695
    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.
1696
    
1697
    The format of a single line is
1698
    REVISION_ID FLAGS BYTE_OFFSET LENGTH( PARENT_ID|PARENT_SEQUENCE_ID)* :\n
1699
    REVISION_ID is a utf8-encoded revision id
1700
    FLAGS is a comma separated list of flags about the record. Values include 
1701
        no-eol, line-delta, fulltext.
1702
    BYTE_OFFSET is the ascii representation of the byte offset in the data file
1703
        that the the compressed data starts at.
1704
    LENGTH is the ascii representation of the length of the data file.
1705
    PARENT_ID a utf-8 revision id prefixed by a '.' that is a parent of
1706
        REVISION_ID.
1707
    PARENT_SEQUENCE_ID the ascii representation of the sequence number of a
1708
        revision id already in the knit that is a parent of REVISION_ID.
1709
    The ' :' marker is the end of record marker.
1710
    
1711
    partial writes:
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1712
    when a write is interrupted to the index file, it will result in a line
1713
    that does not end in ' :'. If the ' :' is not present at the end of a line,
1714
    or at the end of the file, then the record that is missing it will be
1715
    ignored by the parser.
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1716
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
1717
    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.
1718
    to ensure that records always start on new lines even if the last write was
1719
    interrupted. As a result its normal for the last line in the index to be
1720
    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
1721
1722
    :ivar _kndx_cache: dict from prefix to the old state of KnitIndex objects,
1723
        where prefix is e.g. the (fileid,) for .texts instances or () for
1724
        constant-mapped things like .revisions, and the old state is
1725
        tuple(history_vector, cache_dict).  This is used to prevent having an
1726
        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.
1727
    """
1728
1666.1.6 by Robert Collins
Make knit the default format.
1729
    HEADER = "# bzr knit index 8\n"
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1730
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1731
    def __init__(self, transport, mapper, get_scope, allow_writes, is_locked):
1732
        """Create a _KndxIndex on transport using mapper."""
1733
        self._transport = transport
1734
        self._mapper = mapper
1735
        self._get_scope = get_scope
1736
        self._allow_writes = allow_writes
1737
        self._is_locked = is_locked
1738
        self._reset_cache()
1739
        self.has_graph = True
1740
1741
    def add_records(self, records, random_id=False):
1742
        """Add multiple records to the index.
1743
        
1744
        :param records: a list of tuples:
1745
                         (key, options, access_memo, parents).
1746
        :param random_id: If True the ids being added were randomly generated
1747
            and no check for existence will be performed.
1748
        """
1749
        paths = {}
1750
        for record in records:
1751
            key = record[0]
1752
            prefix = key[:-1]
1753
            path = self._mapper.map(key) + '.kndx'
1754
            path_keys = paths.setdefault(path, (prefix, []))
1755
            path_keys[1].append(record)
1756
        for path in sorted(paths):
1757
            prefix, path_keys = paths[path]
1758
            self._load_prefixes([prefix])
1759
            lines = []
1760
            orig_history = self._kndx_cache[prefix][1][:]
1761
            orig_cache = self._kndx_cache[prefix][0].copy()
1762
1763
            try:
1764
                for key, options, (_, pos, size), parents in path_keys:
1765
                    if parents is None:
1766
                        # kndx indices cannot be parentless.
1767
                        parents = ()
1768
                    line = "\n%s %s %s %s %s :" % (
1769
                        key[-1], ','.join(options), pos, size,
1770
                        self._dictionary_compress(parents))
1771
                    if type(line) != str:
1772
                        raise AssertionError(
1773
                            'data must be utf8 was %s' % type(line))
1774
                    lines.append(line)
1775
                    self._cache_key(key, options, pos, size, parents)
1776
                if len(orig_history):
1777
                    self._transport.append_bytes(path, ''.join(lines))
1778
                else:
1779
                    self._init_index(path, lines)
1780
            except:
1781
                # If any problems happen, restore the original values and re-raise
1782
                self._kndx_cache[prefix] = (orig_cache, orig_history)
1783
                raise
1784
1785
    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.
1786
        """Cache a version record in the history array and index cache.
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1787
1788
        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.
1789
        (It saves 60ms, 25% of the __init__ overhead on local 4000 record
1790
         indexes).
1791
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1792
        prefix = key[:-1]
1793
        version_id = key[-1]
1794
        # last-element only for compatibilty with the C load_data.
1795
        parents = tuple(parent[-1] for parent in parent_keys)
1796
        for parent in parent_keys:
1797
            if parent[:-1] != prefix:
1798
                raise ValueError("mismatched prefixes for %r, %r" % (
1799
                    key, parent_keys))
1800
        cache, history = self._kndx_cache[prefix]
1596.2.14 by Robert Collins
Make knit parsing non quadratic?
1801
        # only want the _history index to reference the 1st index entry
1802
        # 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.
1803
        if version_id not in cache:
1804
            index = len(history)
1805
            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
1806
        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.
1807
            index = cache[version_id][5]
1808
        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
1809
                                   options,
1810
                                   pos,
1811
                                   size,
1812
                                   parents,
1813
                                   index)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1814
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1815
    def check_header(self, fp):
1816
        line = fp.readline()
1817
        if line == '':
1818
            # An empty file can actually be treated as though the file doesn't
1819
            # exist yet.
1820
            raise errors.NoSuchFile(self)
1821
        if line != self.HEADER:
1822
            raise KnitHeaderError(badline=line, filename=self)
1823
1824
    def _check_read(self):
1825
        if not self._is_locked():
1826
            raise errors.ObjectNotLocked(self)
1827
        if self._get_scope() != self._scope:
1828
            self._reset_cache()
1829
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
1830
    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.
1831
        """Assert if not writes are permitted."""
1832
        if not self._is_locked():
1833
            raise errors.ObjectNotLocked(self)
3316.2.5 by Robert Collins
Review feedback.
1834
        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.
1835
            self._reset_cache()
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
1836
        if self._mode != 'w':
1837
            raise errors.ReadOnlyObjectDirtiedError(self)
1838
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1839
    def get_build_details(self, keys):
1840
        """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.
1841
3224.1.29 by John Arbash Meinel
Properly handle annotating when ghosts are present.
1842
        Ghosts are omitted from the result.
1843
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1844
        :param keys: An iterable of keys.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1845
        :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.
1846
            record_details).
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
1847
            index_memo
1848
                opaque structure to pass to read_records to extract the raw
1849
                data
1850
            compression_parent
1851
                Content that this record is built upon, may be None
1852
            parents
1853
                Logical parents of this node
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
1854
            record_details
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
1855
                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,
1856
                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.
1857
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1858
        prefixes = self._partition_keys(keys)
1859
        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.
1860
        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.
1861
        for key in keys:
1862
            if key not in parent_map:
1863
                continue # Ghost
1864
            method = self.get_method(key)
1865
            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.
1866
            if method == 'fulltext':
1867
                compression_parent = None
1868
            else:
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
1869
                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.
1870
            noeol = 'no-eol' in self.get_options(key)
1871
            index_memo = self.get_position(key)
1872
            result[key] = (index_memo, compression_parent,
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
1873
                                  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.
1874
        return result
1875
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1876
    def get_method(self, key):
1877
        """Return compression method of specified key."""
1878
        options = self.get_options(key)
1879
        if 'fulltext' in options:
1880
            return 'fulltext'
1881
        elif 'line-delta' in options:
1882
            return 'line-delta'
1883
        else:
1884
            raise errors.KnitIndexUnknownMethod(self, options)
1885
1886
    def get_options(self, key):
1887
        """Return a list representing options.
1888
1889
        e.g. ['foo', 'bar']
1890
        """
1891
        prefix, suffix = self._split_key(key)
1892
        self._load_prefixes([prefix])
3350.8.9 by Robert Collins
define behaviour for add_lines with stacked storage.
1893
        try:
1894
            return self._kndx_cache[prefix][0][suffix][1]
1895
        except KeyError:
1896
            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.
1897
1898
    def get_parent_map(self, keys):
1899
        """Get a map of the parents of keys.
1900
1901
        :param keys: The keys to look up parents for.
1902
        :return: A mapping from keys to parents. Absent keys are absent from
1903
            the mapping.
1904
        """
1905
        # Parse what we need to up front, this potentially trades off I/O
1906
        # locality (.kndx and .knit in the same block group for the same file
1907
        # id) for less checking in inner loops.
3350.6.10 by Martin Pool
VersionedFiles review cleanups
1908
        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.
1909
        self._load_prefixes(prefixes)
1910
        result = {}
1911
        for key in keys:
1912
            prefix = key[:-1]
1913
            try:
1914
                suffix_parents = self._kndx_cache[prefix][0][key[-1]][4]
1915
            except KeyError:
1916
                pass
1917
            else:
1918
                result[key] = tuple(prefix + (suffix,) for
1919
                    suffix in suffix_parents)
1920
        return result
1921
1922
    def get_position(self, key):
1923
        """Return details needed to access the version.
1924
        
1925
        :return: a tuple (key, data position, size) to hand to the access
1926
            logic to get the record.
1927
        """
1928
        prefix, suffix = self._split_key(key)
1929
        self._load_prefixes([prefix])
1930
        entry = self._kndx_cache[prefix][0][suffix]
1931
        return key, entry[2], entry[3]
1932
1933
    def _init_index(self, path, extra_lines=[]):
1934
        """Initialize an index."""
1935
        sio = StringIO()
1936
        sio.write(self.HEADER)
1937
        sio.writelines(extra_lines)
1938
        sio.seek(0)
1939
        self._transport.put_file_non_atomic(path, sio,
1940
                            create_parent_dir=True)
1941
                           # self._create_parent_dir)
1942
                           # mode=self._file_mode,
1943
                           # dir_mode=self._dir_mode)
1944
1945
    def keys(self):
1946
        """Get all the keys in the collection.
1947
        
1948
        The keys are not ordered.
1949
        """
1950
        result = set()
1951
        # Identify all key prefixes.
1952
        # XXX: A bit hacky, needs polish.
1953
        if type(self._mapper) == ConstantMapper:
1954
            prefixes = [()]
1955
        else:
1956
            relpaths = set()
1957
            for quoted_relpath in self._transport.iter_files_recursive():
1958
                path, ext = os.path.splitext(quoted_relpath)
1959
                relpaths.add(path)
1960
            prefixes = [self._mapper.unmap(path) for path in relpaths]
1961
        self._load_prefixes(prefixes)
1962
        for prefix in prefixes:
1963
            for suffix in self._kndx_cache[prefix][1]:
1964
                result.add(prefix + (suffix,))
1965
        return result
1966
    
1967
    def _load_prefixes(self, prefixes):
1968
        """Load the indices for prefixes."""
1969
        self._check_read()
1970
        for prefix in prefixes:
1971
            if prefix not in self._kndx_cache:
1972
                # the load_data interface writes to these variables.
1973
                self._cache = {}
1974
                self._history = []
1975
                self._filename = prefix
1976
                try:
1977
                    path = self._mapper.map(prefix) + '.kndx'
1978
                    fp = self._transport.get(path)
1979
                    try:
1980
                        # _load_data may raise NoSuchFile if the target knit is
1981
                        # completely empty.
1982
                        _load_data(self, fp)
1983
                    finally:
1984
                        fp.close()
1985
                    self._kndx_cache[prefix] = (self._cache, self._history)
1986
                    del self._cache
1987
                    del self._filename
1988
                    del self._history
1989
                except NoSuchFile:
1990
                    self._kndx_cache[prefix] = ({}, [])
1991
                    if type(self._mapper) == ConstantMapper:
1992
                        # preserve behaviour for revisions.kndx etc.
1993
                        self._init_index(path)
1994
                    del self._cache
1995
                    del self._filename
1996
                    del self._history
1997
1998
    def _partition_keys(self, keys):
1999
        """Turn keys into a dict of prefix:suffix_list."""
2000
        result = {}
2001
        for key in keys:
2002
            prefix_keys = result.setdefault(key[:-1], [])
2003
            prefix_keys.append(key[-1])
2004
        return result
2005
2006
    def _dictionary_compress(self, keys):
2007
        """Dictionary compress keys.
2008
        
2009
        :param keys: The keys to generate references to.
2010
        :return: A string representation of keys. keys which are present are
2011
            dictionary compressed, and others are emitted as fulltext with a
2012
            '.' prefix.
2013
        """
2014
        if not keys:
2015
            return ''
1594.2.8 by Robert Collins
add ghost aware apis to knits.
2016
        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.
2017
        prefix = keys[0][:-1]
2018
        cache = self._kndx_cache[prefix][0]
2019
        for key in keys:
2020
            if key[:-1] != prefix:
2021
                # kndx indices cannot refer across partitioned storage.
2022
                raise ValueError("mismatched prefixes for %r" % keys)
2023
            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
2024
                # -- 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.
2025
                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
2026
                # -- end lookup () --
1594.2.8 by Robert Collins
add ghost aware apis to knits.
2027
            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.
2028
                result_list.append('.' + key[-1])
1594.2.8 by Robert Collins
add ghost aware apis to knits.
2029
        return ' '.join(result_list)
2030
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2031
    def _reset_cache(self):
2032
        # Possibly this should be a LRU cache. A dictionary from key_prefix to
2033
        # (cache_dict, history_vector) for parsed kndx files.
2034
        self._kndx_cache = {}
2035
        self._scope = self._get_scope()
2036
        allow_writes = self._allow_writes()
2037
        if allow_writes:
2038
            self._mode = 'w'
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2039
        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.
2040
            self._mode = 'r'
2041
2042
    def _split_key(self, key):
2043
        """Split key into a prefix and suffix."""
2044
        return key[:-1], key[-1]
2045
2046
2047
class _KnitGraphIndex(object):
2048
    """A KnitVersionedFiles index layered on GraphIndex."""
2049
2050
    def __init__(self, graph_index, is_locked, deltas=False, parents=True,
2051
        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.
2052
        """Construct a KnitGraphIndex on a graph_index.
2053
2054
        :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.
2055
        :param is_locked: A callback to check whether the object should answer
2056
            queries.
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2057
        :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.
2058
        :param parents: If True, record knits parents, if not do not record 
2059
            parents.
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2060
        :param add_callback: If not None, allow additions to the index and call
2061
            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.
2062
            [(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.
2063
        :param is_locked: A callback, returns True if the index is locked and
2064
            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.
2065
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2066
        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.
2067
        self._graph_index = graph_index
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2068
        self._deltas = deltas
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2069
        self._parents = parents
2070
        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.
2071
            # XXX: TODO: Delta tree and parent graph should be conceptually
2072
            # separate.
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2073
            raise KnitCorrupt(self, "Cannot do delta compression without "
2074
                "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.
2075
        self.has_graph = parents
2076
        self._is_locked = is_locked
2077
3517.4.13 by Martin Pool
Add repr methods
2078
    def __repr__(self):
2079
        return "%s(%r)" % (self.__class__.__name__, self._graph_index)
2080
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2081
    def add_records(self, records, random_id=False):
2082
        """Add multiple records to the index.
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2083
        
2084
        This function does not insert data into the Immutable GraphIndex
2085
        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.
2086
        the caller and checks that it is safe to insert then calls
2087
        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.
2088
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2089
        :param records: a list of tuples:
2090
                         (key, options, access_memo, parents).
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
2091
        :param random_id: If True the ids being added were randomly generated
2092
            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.
2093
        """
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2094
        if not self._add_callback:
2095
            raise errors.ReadOnlyError(self)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2096
        # we hope there are no repositories with inconsistent parentage
2097
        # anymore.
2098
2099
        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.
2100
        for (key, options, access_memo, parents) in records:
2101
            if self._parents:
2102
                parents = tuple(parents)
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2103
            index, pos, size = access_memo
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2104
            if 'no-eol' in options:
2105
                value = 'N'
2106
            else:
2107
                value = ' '
2108
            value += "%d %d" % (pos, size)
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2109
            if not self._deltas:
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2110
                if 'line-delta' in options:
2111
                    raise KnitCorrupt(self, "attempt to add line-delta in non-delta knit")
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2112
            if self._parents:
2113
                if self._deltas:
2114
                    if 'line-delta' in options:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2115
                        node_refs = (parents, (parents[0],))
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2116
                    else:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2117
                        node_refs = (parents, ())
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2118
                else:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2119
                    node_refs = (parents, )
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2120
            else:
2121
                if parents:
2122
                    raise KnitCorrupt(self, "attempt to add node with parents "
2123
                        "in parentless index.")
2124
                node_refs = ()
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2125
            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.
2126
        # check for dups
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
2127
        if not random_id:
2128
            present_nodes = self._get_entries(keys)
2129
            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.
2130
                if (value[0] != keys[key][0][0] or
2131
                    node_refs != keys[key][1]):
2132
                    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
2133
                        ": %s %s" % ((value, node_refs), keys[key]))
2134
                del keys[key]
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2135
        result = []
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2136
        if self._parents:
2137
            for key, (value, node_refs) in keys.iteritems():
2138
                result.append((key, value, node_refs))
2139
        else:
2140
            for key, (value, node_refs) in keys.iteritems():
2141
                result.append((key, value))
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2142
        self._add_callback(result)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2143
        
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2144
    def _check_read(self):
2145
        """raise if reads are not permitted."""
2146
        if not self._is_locked():
2147
            raise errors.ObjectNotLocked(self)
2148
2149
    def _check_write_ok(self):
2150
        """Assert if writes are not permitted."""
2151
        if not self._is_locked():
2152
            raise errors.ObjectNotLocked(self)
2153
2154
    def _compression_parent(self, an_entry):
2155
        # return the key that an_entry is compressed against, or None
2156
        # Grab the second parent list (as deltas implies parents currently)
2157
        compression_parents = an_entry[3][1]
2158
        if not compression_parents:
2159
            return None
2160
        if len(compression_parents) != 1:
2161
            raise AssertionError(
2162
                "Too many compression parents: %r" % compression_parents)
2163
        return compression_parents[0]
2164
2165
    def get_build_details(self, keys):
2166
        """Get the method, index_memo and compression parent for version_ids.
2167
2168
        Ghosts are omitted from the result.
2169
2170
        :param keys: An iterable of keys.
2171
        :return: A dict of key:
2172
            (index_memo, compression_parent, parents, record_details).
2173
            index_memo
2174
                opaque structure to pass to read_records to extract the raw
2175
                data
2176
            compression_parent
2177
                Content that this record is built upon, may be None
2178
            parents
2179
                Logical parents of this node
2180
            record_details
2181
                extra information about the content which needs to be passed to
2182
                Factory.parse_record
2183
        """
2184
        self._check_read()
2185
        result = {}
2186
        entries = self._get_entries(keys, False)
2187
        for entry in entries:
2188
            key = entry[1]
2189
            if not self._parents:
2190
                parents = ()
2191
            else:
2192
                parents = entry[3][0]
2193
            if not self._deltas:
2194
                compression_parent_key = None
2195
            else:
2196
                compression_parent_key = self._compression_parent(entry)
2197
            noeol = (entry[2][0] == 'N')
2198
            if compression_parent_key:
2199
                method = 'line-delta'
2200
            else:
2201
                method = 'fulltext'
2202
            result[key] = (self._node_to_position(entry),
2203
                                  compression_parent_key, parents,
2204
                                  (method, noeol))
2205
        return result
2206
2207
    def _get_entries(self, keys, check_present=False):
2208
        """Get the entries for keys.
2209
        
2210
        :param keys: An iterable of index key tuples.
2211
        """
2212
        keys = set(keys)
2213
        found_keys = set()
2214
        if self._parents:
2215
            for node in self._graph_index.iter_entries(keys):
2216
                yield node
2217
                found_keys.add(node[1])
2218
        else:
2219
            # adapt parentless index to the rest of the code.
2220
            for node in self._graph_index.iter_entries(keys):
2221
                yield node[0], node[1], node[2], ()
2222
                found_keys.add(node[1])
2223
        if check_present:
2224
            missing_keys = keys.difference(found_keys)
2225
            if missing_keys:
2226
                raise RevisionNotPresent(missing_keys.pop(), self)
2227
2228
    def get_method(self, key):
2229
        """Return compression method of specified key."""
2230
        return self._get_method(self._get_node(key))
2231
2232
    def _get_method(self, node):
2233
        if not self._deltas:
2234
            return 'fulltext'
2235
        if self._compression_parent(node):
2236
            return 'line-delta'
2237
        else:
2238
            return 'fulltext'
2239
2240
    def _get_node(self, key):
2241
        try:
2242
            return list(self._get_entries([key]))[0]
2243
        except IndexError:
2244
            raise RevisionNotPresent(key, self)
2245
2246
    def get_options(self, key):
2247
        """Return a list representing options.
2248
2249
        e.g. ['foo', 'bar']
2250
        """
2251
        node = self._get_node(key)
2252
        options = [self._get_method(node)]
2253
        if node[2][0] == 'N':
2254
            options.append('no-eol')
2255
        return options
2256
2257
    def get_parent_map(self, keys):
2258
        """Get a map of the parents of keys.
2259
2260
        :param keys: The keys to look up parents for.
2261
        :return: A mapping from keys to parents. Absent keys are absent from
2262
            the mapping.
2263
        """
2264
        self._check_read()
2265
        nodes = self._get_entries(keys)
2266
        result = {}
2267
        if self._parents:
2268
            for node in nodes:
2269
                result[node[1]] = node[3][0]
2270
        else:
2271
            for node in nodes:
2272
                result[node[1]] = None
2273
        return result
2274
2275
    def get_position(self, key):
2276
        """Return details needed to access the version.
2277
        
2278
        :return: a tuple (index, data position, size) to hand to the access
2279
            logic to get the record.
2280
        """
2281
        node = self._get_node(key)
2282
        return self._node_to_position(node)
2283
2284
    def keys(self):
2285
        """Get all the keys in the collection.
2286
        
2287
        The keys are not ordered.
2288
        """
2289
        self._check_read()
2290
        return [node[1] for node in self._graph_index.iter_all_entries()]
2291
    
2292
    def _node_to_position(self, node):
2293
        """Convert an index value to position details."""
2294
        bits = node[2][1:].split(' ')
2295
        return node[0], int(bits[0]), int(bits[1])
2296
2297
2298
class _KnitKeyAccess(object):
2299
    """Access to records in .knit files."""
2300
2301
    def __init__(self, transport, mapper):
2302
        """Create a _KnitKeyAccess with transport and mapper.
2303
2304
        :param transport: The transport the access object is rooted at.
2305
        :param mapper: The mapper used to map keys to .knit files.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2306
        """
2307
        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.
2308
        self._mapper = mapper
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2309
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2310
    def add_raw_records(self, key_sizes, raw_data):
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2311
        """Add raw knit bytes to a storage area.
2312
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2313
        The data is spooled to the container writer in one bytes-record per
2314
        raw data item.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2315
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2316
        :param sizes: An iterable of tuples containing the key and size of each
2317
            raw data segment.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2318
        :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.
2319
        :return: A list of memos to retrieve the record later. Each memo is an
2320
            opaque index memo. For _KnitKeyAccess the memo is (key, pos,
2321
            length), where the key is the record key.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2322
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2323
        if type(raw_data) != str:
2324
            raise AssertionError(
2325
                'data must be plain bytes was %s' % type(raw_data))
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2326
        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.
2327
        offset = 0
2328
        # TODO: This can be tuned for writing to sftp and other servers where
2329
        # append() is relatively expensive by grouping the writes to each key
2330
        # prefix.
2331
        for key, size in key_sizes:
2332
            path = self._mapper.map(key)
2333
            try:
2334
                base = self._transport.append_bytes(path + '.knit',
2335
                    raw_data[offset:offset+size])
2336
            except errors.NoSuchFile:
2337
                self._transport.mkdir(osutils.dirname(path))
2338
                base = self._transport.append_bytes(path + '.knit',
2339
                    raw_data[offset:offset+size])
2340
            # if base == 0:
2341
            # chmod.
2342
            offset += size
2343
            result.append((key, base, size))
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2344
        return result
2345
2346
    def get_raw_records(self, memos_for_retrieval):
2347
        """Get the raw bytes for a records.
2348
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2349
        :param memos_for_retrieval: An iterable containing the access memo for
2350
            retrieving the bytes.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2351
        :return: An iterator over the bytes of the records.
2352
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2353
        # first pass, group into same-index request to minimise readv's issued.
2354
        request_lists = []
2355
        current_prefix = None
2356
        for (key, offset, length) in memos_for_retrieval:
2357
            if current_prefix == key[:-1]:
2358
                current_list.append((offset, length))
2359
            else:
2360
                if current_prefix is not None:
2361
                    request_lists.append((current_prefix, current_list))
2362
                current_prefix = key[:-1]
2363
                current_list = [(offset, length)]
2364
        # handle the last entry
2365
        if current_prefix is not None:
2366
            request_lists.append((current_prefix, current_list))
2367
        for prefix, read_vector in request_lists:
2368
            path = self._mapper.map(prefix) + '.knit'
2369
            for pos, data in self._transport.readv(path, read_vector):
2370
                yield data
2371
2372
2373
class _DirectPackAccess(object):
2374
    """Access to data in one or more packs with less translation."""
2375
2376
    def __init__(self, index_to_packs):
2377
        """Create a _DirectPackAccess object.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2378
2379
        :param index_to_packs: A dict mapping index objects to the transport
2380
            and file names for obtaining data.
2381
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2382
        self._container_writer = None
2383
        self._write_index = None
2384
        self._indices = index_to_packs
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2385
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2386
    def add_raw_records(self, key_sizes, raw_data):
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2387
        """Add raw knit bytes to a storage area.
2388
2670.2.3 by Robert Collins
Review feedback.
2389
        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.
2390
        raw data item.
2391
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2392
        :param sizes: An iterable of tuples containing the key and size of each
2393
            raw data segment.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2394
        :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.
2395
        :return: A list of memos to retrieve the record later. Each memo is an
2396
            opaque index memo. For _DirectPackAccess the memo is (index, pos,
2397
            length), where the index field is the write_index object supplied
2398
            to the PackAccess object.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2399
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2400
        if type(raw_data) != str:
2401
            raise AssertionError(
2402
                'data must be plain bytes was %s' % type(raw_data))
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2403
        result = []
2404
        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.
2405
        for key, size in key_sizes:
2406
            p_offset, p_length = self._container_writer.add_bytes_record(
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2407
                raw_data[offset:offset+size], [])
2408
            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.
2409
            result.append((self._write_index, p_offset, p_length))
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2410
        return result
2411
2412
    def get_raw_records(self, memos_for_retrieval):
2413
        """Get the raw bytes for a records.
2414
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2415
        :param memos_for_retrieval: An iterable containing the (index, pos, 
2416
            length) memo for retrieving the bytes. The Pack access method
2417
            looks up the pack to use for a given record in its index_to_pack
2418
            map.
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2419
        :return: An iterator over the bytes of the records.
2420
        """
2421
        # first pass, group into same-index requests
2422
        request_lists = []
2423
        current_index = None
2424
        for (index, offset, length) in memos_for_retrieval:
2425
            if current_index == index:
2426
                current_list.append((offset, length))
2427
            else:
2428
                if current_index is not None:
2429
                    request_lists.append((current_index, current_list))
2430
                current_index = index
2431
                current_list = [(offset, length)]
2432
        # handle the last entry
2433
        if current_index is not None:
2434
            request_lists.append((current_index, current_list))
2435
        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.
2436
            transport, path = self._indices[index]
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
2437
            reader = pack.make_readv_reader(transport, path, offsets)
2438
            for names, read_func in reader.iter_records():
2439
                yield read_func(None)
2440
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2441
    def set_writer(self, writer, index, transport_packname):
2592.3.70 by Robert Collins
Allow setting a writer after creating a knit._PackAccess object.
2442
        """Set a writer to use for adding data."""
2592.3.208 by Robert Collins
Start refactoring the knit-pack thunking to be clearer.
2443
        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.
2444
            self._indices[index] = transport_packname
2445
        self._container_writer = writer
2446
        self._write_index = index
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
2447
2448
2781.1.1 by Martin Pool
merge cpatiencediff from Lukas
2449
# Deprecated, use PatienceSequenceMatcher instead
2450
KnitSequenceMatcher = patiencediff.PatienceSequenceMatcher
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
2451
2452
2770.1.2 by Aaron Bentley
Convert to knit-only annotation
2453
def annotate_knit(knit, revision_id):
2454
    """Annotate a knit with no cached annotations.
2455
2456
    This implementation is for knits with no cached annotations.
2457
    It will work for knits with cached annotations, but this is not
2458
    recommended.
2459
    """
3224.1.7 by John Arbash Meinel
_StreamIndex also needs to return the proper values for get_build_details.
2460
    annotator = _KnitAnnotator(knit)
3224.1.25 by John Arbash Meinel
Quick change to the _KnitAnnotator api to use .annotate() instead of get_annotated_lines()
2461
    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.
2462
2463
2464
class _KnitAnnotator(object):
3224.1.5 by John Arbash Meinel
Start using a helper class for doing the knit-pack annotations.
2465
    """Build up the annotations for a text."""
2466
2467
    def __init__(self, knit):
2468
        self._knit = knit
2469
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2470
        # Content objects, differs from fulltexts because of how final newlines
2471
        # are treated by knits. the content objects here will always have a
2472
        # final newline
2473
        self._fulltext_contents = {}
2474
2475
        # Annotated lines of specific revisions
2476
        self._annotated_lines = {}
2477
2478
        # Track the raw data for nodes that we could not process yet.
2479
        # This maps the revision_id of the base to a list of children that will
2480
        # annotated from it.
2481
        self._pending_children = {}
2482
3224.1.29 by John Arbash Meinel
Properly handle annotating when ghosts are present.
2483
        # Nodes which cannot be extracted
2484
        self._ghosts = set()
2485
3224.1.19 by John Arbash Meinel
Work on removing nodes from the working set once they aren't needed.
2486
        # Track how many children this node has, so we know if we need to keep
2487
        # it
2488
        self._annotate_children = {}
2489
        self._compression_children = {}
2490
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2491
        self._all_build_details = {}
3224.1.10 by John Arbash Meinel
Introduce the heads_provider for reannotate.
2492
        # The children => parent revision_id graph
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2493
        self._revision_id_graph = {}
2494
3224.1.10 by John Arbash Meinel
Introduce the heads_provider for reannotate.
2495
        self._heads_provider = None
2496
3224.1.19 by John Arbash Meinel
Work on removing nodes from the working set once they aren't needed.
2497
        self._nodes_to_keep_annotations = set()
3224.1.22 by John Arbash Meinel
Cleanup the extra debugging info, and some >80 char lines.
2498
        self._generations_until_keep = 100
2499
2500
    def set_generations_until_keep(self, value):
2501
        """Set the number of generations before caching a node.
2502
2503
        Setting this to -1 will cache every merge node, setting this higher
2504
        will cache fewer nodes.
2505
        """
2506
        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.
2507
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2508
    def _add_fulltext_content(self, revision_id, content_obj):
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2509
        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.
2510
        # 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.
2511
        return content_obj.text()
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2512
2513
    def _check_parents(self, child, nodes_to_annotate):
2514
        """Check if all parents have been processed.
2515
2516
        :param child: A tuple of (rev_id, parents, raw_content)
2517
        :param nodes_to_annotate: If child is ready, add it to
2518
            nodes_to_annotate, otherwise put it back in self._pending_children
2519
        """
2520
        for parent_id in child[1]:
3224.1.29 by John Arbash Meinel
Properly handle annotating when ghosts are present.
2521
            if (parent_id not in self._annotated_lines):
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2522
                # This parent is present, but another parent is missing
2523
                self._pending_children.setdefault(parent_id,
2524
                                                  []).append(child)
2525
                break
2526
        else:
2527
            # This one is ready to be processed
2528
            nodes_to_annotate.append(child)
2529
2530
    def _add_annotation(self, revision_id, fulltext, parent_ids,
2531
                        left_matching_blocks=None):
2532
        """Add an annotation entry.
2533
2534
        All parents should already have been annotated.
2535
        :return: A list of children that now have their parents satisfied.
2536
        """
2537
        a = self._annotated_lines
2538
        annotated_parent_lines = [a[p] for p in parent_ids]
2539
        annotated_lines = list(annotate.reannotate(annotated_parent_lines,
3224.1.10 by John Arbash Meinel
Introduce the heads_provider for reannotate.
2540
            fulltext, revision_id, left_matching_blocks,
2541
            heads_provider=self._get_heads_provider()))
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2542
        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.
2543
        for p in parent_ids:
2544
            ann_children = self._annotate_children[p]
2545
            ann_children.remove(revision_id)
2546
            if (not ann_children
2547
                and p not in self._nodes_to_keep_annotations):
2548
                del self._annotated_lines[p]
2549
                del self._all_build_details[p]
2550
                if p in self._fulltext_contents:
2551
                    del self._fulltext_contents[p]
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2552
        # Now that we've added this one, see if there are any pending
2553
        # deltas to be done, certainly this parent is finished
2554
        nodes_to_annotate = []
2555
        for child in self._pending_children.pop(revision_id, []):
2556
            self._check_parents(child, nodes_to_annotate)
2557
        return nodes_to_annotate
2558
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2559
    def _get_build_graph(self, key):
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2560
        """Get the graphs for building texts and annotations.
2561
2562
        The data you need for creating a full text may be different than the
2563
        data you need to annotate that text. (At a minimum, you need both
2564
        parents to create an annotation, but only need 1 parent to generate the
2565
        fulltext.)
2566
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2567
        :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.
2568
            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.
2569
            the pack file.
2570
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2571
        if key in self._annotated_lines:
3224.1.10 by John Arbash Meinel
Introduce the heads_provider for reannotate.
2572
            # Nothing to do
2573
            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.
2574
        pending = set([key])
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2575
        records = []
3224.1.19 by John Arbash Meinel
Work on removing nodes from the working set once they aren't needed.
2576
        generation = 0
3224.1.22 by John Arbash Meinel
Cleanup the extra debugging info, and some >80 char lines.
2577
        kept_generation = 0
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2578
        while pending:
2579
            # get all pending nodes
3224.1.19 by John Arbash Meinel
Work on removing nodes from the working set once they aren't needed.
2580
            generation += 1
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2581
            this_iteration = pending
2582
            build_details = self._knit._index.get_build_details(this_iteration)
2583
            self._all_build_details.update(build_details)
2584
            # new_nodes = self._knit._index._get_entries(this_iteration)
2585
            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.
2586
            for key, details in build_details.iteritems():
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
2587
                (index_memo, compression_parent, parents,
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2588
                 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.
2589
                self._revision_id_graph[key] = parents
2590
                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.
2591
                # Do we actually need to check _annotated_lines?
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2592
                pending.update(p for p in parents
2593
                                 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.
2594
                if compression_parent:
2595
                    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.
2596
                        []).append(key)
3224.1.19 by John Arbash Meinel
Work on removing nodes from the working set once they aren't needed.
2597
                if parents:
2598
                    for parent in parents:
3224.1.22 by John Arbash Meinel
Cleanup the extra debugging info, and some >80 char lines.
2599
                        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.
2600
                            []).append(key)
3224.1.22 by John Arbash Meinel
Cleanup the extra debugging info, and some >80 char lines.
2601
                    num_gens = generation - kept_generation
2602
                    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.
2603
                        and len(parents) > 1):
3224.1.22 by John Arbash Meinel
Cleanup the extra debugging info, and some >80 char lines.
2604
                        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.
2605
                        self._nodes_to_keep_annotations.add(key)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2606
2607
            missing_versions = this_iteration.difference(build_details.keys())
3224.1.29 by John Arbash Meinel
Properly handle annotating when ghosts are present.
2608
            self._ghosts.update(missing_versions)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2609
            for missing_version in missing_versions:
2610
                # add a key, no parents
3224.1.29 by John Arbash Meinel
Properly handle annotating when ghosts are present.
2611
                self._revision_id_graph[missing_version] = ()
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2612
                pending.discard(missing_version) # don't look for it
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2613
        if self._ghosts.intersection(self._compression_children):
2614
            raise KnitCorrupt(
2615
                "We cannot have nodes which have a ghost compression parent:\n"
2616
                "ghosts: %r\n"
2617
                "compression children: %r"
2618
                % (self._ghosts, self._compression_children))
3224.1.29 by John Arbash Meinel
Properly handle annotating when ghosts are present.
2619
        # Cleanout anything that depends on a ghost so that we don't wait for
2620
        # the ghost to show up
2621
        for node in self._ghosts:
2622
            if node in self._annotate_children:
2623
                # We won't be building this node
2624
                del self._annotate_children[node]
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2625
        # Generally we will want to read the records in reverse order, because
2626
        # we find the parent nodes after the children
2627
        records.reverse()
2628
        return records
2629
2630
    def _annotate_records(self, records):
2631
        """Build the annotations for the listed records."""
2632
        # 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.
2633
        # However, process what we can, and put off to the side things that
2634
        # still need parents, cleaning them up when those parents are
2635
        # processed.
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2636
        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.
2637
             digest) in self._knit._read_records_iter(records):
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2638
            if rev_id in self._annotated_lines:
2639
                continue
2640
            parent_ids = self._revision_id_graph[rev_id]
3224.1.29 by John Arbash Meinel
Properly handle annotating when ghosts are present.
2641
            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.
2642
            details = self._all_build_details[rev_id]
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
2643
            (index_memo, compression_parent, parents,
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2644
             record_details) = details
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2645
            nodes_to_annotate = []
2646
            # TODO: Remove the punning between compression parents, and
2647
            #       parent_ids, we should be able to do this without assuming
2648
            #       the build order
2649
            if len(parent_ids) == 0:
2650
                # There are no parents for this node, so just add it
2651
                # 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.
2652
                fulltext_content, delta = self._knit._factory.parse_record(
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2653
                    rev_id, record, record_details, None)
2654
                fulltext = self._add_fulltext_content(rev_id, fulltext_content)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2655
                nodes_to_annotate.extend(self._add_annotation(rev_id, fulltext,
2656
                    parent_ids, left_matching_blocks=None))
2657
            else:
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2658
                child = (rev_id, parent_ids, record)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2659
                # Check if all the parents are present
2660
                self._check_parents(child, nodes_to_annotate)
2661
            while nodes_to_annotate:
2662
                # 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,
2663
                (rev_id, parent_ids, record) = nodes_to_annotate.pop()
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
2664
                (index_memo, compression_parent, parents,
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2665
                 record_details) = self._all_build_details[rev_id]
3777.4.1 by John Arbash Meinel
Two fixes for annotate code.
2666
                blocks = None
3224.1.14 by John Arbash Meinel
Switch to making content_details opaque, step 1
2667
                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.
2668
                    comp_children = self._compression_children[compression_parent]
3376.2.4 by Martin Pool
Remove every assert statement from bzrlib!
2669
                    if rev_id not in comp_children:
2670
                        raise AssertionError("%r not in compression children %r"
2671
                            % (rev_id, comp_children))
3224.1.19 by John Arbash Meinel
Work on removing nodes from the working set once they aren't needed.
2672
                    # If there is only 1 child, it is safe to reuse this
2673
                    # content
2674
                    reuse_content = (len(comp_children) == 1
2675
                        and compression_parent not in
2676
                            self._nodes_to_keep_annotations)
2677
                    if reuse_content:
2678
                        # Remove it from the cache since it will be changing
2679
                        parent_fulltext_content = self._fulltext_contents.pop(compression_parent)
2680
                        # Make sure to copy the fulltext since it might be
2681
                        # modified
3224.1.22 by John Arbash Meinel
Cleanup the extra debugging info, and some >80 char lines.
2682
                        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.
2683
                    else:
2684
                        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.
2685
                        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.
2686
                    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.
2687
                    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.
2688
                        rev_id, record, record_details,
2689
                        parent_fulltext_content,
3224.1.19 by John Arbash Meinel
Work on removing nodes from the working set once they aren't needed.
2690
                        copy_base_content=(not reuse_content))
3224.1.22 by John Arbash Meinel
Cleanup the extra debugging info, and some >80 char lines.
2691
                    fulltext = self._add_fulltext_content(rev_id,
2692
                                                          fulltext_content)
3777.4.1 by John Arbash Meinel
Two fixes for annotate code.
2693
                    if compression_parent == parent_ids[0]:
2694
                        # the compression_parent is the left parent, so we can
2695
                        # re-use the delta
2696
                        blocks = KnitContent.get_line_delta_blocks(delta,
2697
                                parent_fulltext, fulltext)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2698
                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.
2699
                    fulltext_content = self._knit._factory.parse_fulltext(
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2700
                        record, rev_id)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2701
                    fulltext = self._add_fulltext_content(rev_id,
3224.1.15 by John Arbash Meinel
Finish removing method and noeol from general knowledge,
2702
                        fulltext_content)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2703
                nodes_to_annotate.extend(
2704
                    self._add_annotation(rev_id, fulltext, parent_ids,
2705
                                     left_matching_blocks=blocks))
2706
3224.1.10 by John Arbash Meinel
Introduce the heads_provider for reannotate.
2707
    def _get_heads_provider(self):
2708
        """Create a heads provider for resolving ancestry issues."""
2709
        if self._heads_provider is not None:
2710
            return self._heads_provider
2711
        parent_provider = _mod_graph.DictParentsProvider(
2712
            self._revision_id_graph)
2713
        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
2714
        head_cache = _mod_graph.FrozenHeadsCache(graph_obj)
3224.1.10 by John Arbash Meinel
Introduce the heads_provider for reannotate.
2715
        self._heads_provider = head_cache
2716
        return head_cache
2717
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2718
    def annotate(self, key):
2719
        """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.
2720
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2721
        :param key: The key to annotate.
3224.1.5 by John Arbash Meinel
Start using a helper class for doing the knit-pack annotations.
2722
        """
3777.4.1 by John Arbash Meinel
Two fixes for annotate code.
2723
        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
2724
            # stacked knits can't use the fast path at present.
2725
            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.
2726
        records = self._get_build_graph(key)
2727
        if key in self._ghosts:
2728
            raise errors.RevisionNotPresent(key, self._knit)
3224.1.6 by John Arbash Meinel
Refactor the annotation logic into a helper class.
2729
        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.
2730
        return self._annotated_lines[key]
3224.1.5 by John Arbash Meinel
Start using a helper class for doing the knit-pack annotations.
2731
3517.4.1 by Martin Pool
Merge unoptimized annotate code for stacking, and only use it when needed
2732
    def _simple_annotate(self, key):
2733
        """Return annotated fulltext, rediffing from the full texts.
2734
2735
        This is slow but makes no assumptions about the repository
2736
        being able to produce line deltas.
2737
        """
2738
        # TODO: this code generates a parent maps of present ancestors; it
2739
        # could be split out into a separate method, and probably should use
2740
        # iter_ancestry instead. -- mbp and robertc 20080704
3535.5.1 by John Arbash Meinel
cleanup a few imports to be lazily loaded.
2741
        graph = _mod_graph.Graph(self._knit)
3350.9.1 by Robert Collins
Redo annotate more simply, using just the public interfaces for VersionedFiles.
2742
        head_cache = _mod_graph.FrozenHeadsCache(graph)
2743
        search = graph._make_breadth_first_searcher([key])
2744
        keys = set()
2745
        while True:
2746
            try:
2747
                present, ghosts = search.next_with_ghosts()
2748
            except StopIteration:
2749
                break
2750
            keys.update(present)
2751
        parent_map = self._knit.get_parent_map(keys)
2752
        parent_cache = {}
2753
        reannotate = annotate.reannotate
2754
        for record in self._knit.get_record_stream(keys, 'topological', True):
2755
            key = record.key
2756
            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
2757
            parents = parent_map[key]
2758
            if parents is not None:
2759
                parent_lines = [parent_cache[parent] for parent in parent_map[key]]
2760
            else:
2761
                parent_lines = []
3350.9.1 by Robert Collins
Redo annotate more simply, using just the public interfaces for VersionedFiles.
2762
            parent_cache[key] = list(
2763
                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
2764
        try:
2765
            return parent_cache[key]
2766
        except KeyError, e:
2767
            raise errors.RevisionNotPresent(key, self._knit)
3224.1.5 by John Arbash Meinel
Start using a helper class for doing the knit-pack annotations.
2768
2769
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
2770
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
2771
    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.
2772
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
2773
    from bzrlib._knit_load_data_py import _load_data_py as _load_data