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