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