/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
1
# Copyright (C) 2007 Canonical Ltd
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
"""Indexing facilities."""
18
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
19
__all__ = [
20
    'CombinedGraphIndex',
21
    'GraphIndex',
22
    'GraphIndexBuilder',
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
23
    'GraphIndexPrefixAdapter',
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
24
    'InMemoryGraphIndex',
25
    ]
2592.1.32 by Robert Collins
Add __all__ to index.
26
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
27
from bisect import bisect_right
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
28
from cStringIO import StringIO
2592.1.12 by Robert Collins
Handle basic node adds.
29
import re
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
30
2624.2.15 by Robert Collins
Add useful -Dindex flag.
31
from bzrlib.lazy_import import lazy_import
32
lazy_import(globals(), """
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.
33
from bzrlib import trace
2890.2.7 by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a
34
from bzrlib.bisect_multi import bisect_multi_bytes
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.
35
from bzrlib.trace import mutter
2624.2.15 by Robert Collins
Add useful -Dindex flag.
36
""")
37
from bzrlib import debug, errors
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
38
2624.2.8 by Robert Collins
Explicitly mark the number of keys elements in use in GraphIndex files.
39
_OPTION_KEY_ELEMENTS = "key_elements="
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
40
_OPTION_LEN = "len="
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
41
_OPTION_NODE_REFS = "node_ref_lists="
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
42
_SIGNATURE = "Bazaar Graph Index 1\n"
43
44
2592.1.14 by Robert Collins
Detect bad reference key values.
45
_whitespace_re = re.compile('[\t\n\x0b\x0c\r\x00 ]')
2592.1.12 by Robert Collins
Handle basic node adds.
46
_newline_null_re = re.compile('[\n\0]')
47
48
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
49
class GraphIndexBuilder(object):
2592.1.18 by Robert Collins
Add space to mark absent nodes.
50
    """A builder that can build a GraphIndex.
51
    
52
    The resulting graph has the structure:
53
    
54
    _SIGNATURE OPTIONS NODES NEWLINE
55
    _SIGNATURE     := 'Bazaar Graph Index 1' NEWLINE
56
    OPTIONS        := 'node_ref_lists=' DIGITS NEWLINE
57
    NODES          := NODE*
58
    NODE           := KEY NULL ABSENT? NULL REFERENCES NULL VALUE NEWLINE
59
    KEY            := Not-whitespace-utf8
60
    ABSENT         := 'a'
2592.1.19 by Robert Collins
Node references are tab separated.
61
    REFERENCES     := REFERENCE_LIST (TAB REFERENCE_LIST){node_ref_lists - 1}
62
    REFERENCE_LIST := (REFERENCE (CR REFERENCE)*)?
63
    REFERENCE      := DIGITS  ; digits is the byte offset in the index of the
64
                              ; referenced key.
2592.1.18 by Robert Collins
Add space to mark absent nodes.
65
    VALUE          := no-newline-no-null-bytes
66
    """
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
67
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
68
    def __init__(self, reference_lists=0, key_elements=1):
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
69
        """Create a GraphIndex builder.
70
71
        :param reference_lists: The number of node references lists for each
72
            entry.
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
73
        :param key_elements: The number of bytestrings in each key.
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
74
        """
75
        self.reference_lists = reference_lists
2592.3.62 by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration.
76
        self._keys = set()
2592.1.15 by Robert Collins
Detect duplicate key insertion.
77
        self._nodes = {}
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
78
        self._nodes_by_key = {}
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
79
        self._key_length = key_elements
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
80
81
    def _check_key(self, key):
82
        """Raise BadIndexKey if key is not a valid key for this index."""
83
        if type(key) != tuple:
84
            raise errors.BadIndexKey(key)
85
        if self._key_length != len(key):
86
            raise errors.BadIndexKey(key)
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
87
        for element in key:
88
            if not element or _whitespace_re.search(element) is not None:
89
                raise errors.BadIndexKey(element)
2592.1.12 by Robert Collins
Handle basic node adds.
90
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
91
    def add_node(self, key, value, references=()):
2592.1.12 by Robert Collins
Handle basic node adds.
92
        """Add a node to the index.
93
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
94
        :param key: The key. keys are non-empty tuples containing
95
            as many whitespace-free utf8 bytestrings as the key length
96
            defined for this index.
2592.1.12 by Robert Collins
Handle basic node adds.
97
        :param references: An iterable of iterables of keys. Each is a
98
            reference to another key.
99
        :param value: The value to associate with the key. It may be any
100
            bytes as long as it does not contain \0 or \n.
101
        """
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
102
        self._check_key(key)
2592.1.12 by Robert Collins
Handle basic node adds.
103
        if _newline_null_re.search(value) is not None:
104
            raise errors.BadIndexValue(value)
2592.1.13 by Robert Collins
Handle mismatched numbers of reference lists.
105
        if len(references) != self.reference_lists:
106
            raise errors.BadIndexValue(references)
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
107
        node_refs = []
2592.1.14 by Robert Collins
Detect bad reference key values.
108
        for reference_list in references:
109
            for reference in reference_list:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
110
                self._check_key(reference)
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
111
                if reference not in self._nodes:
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
112
                    self._nodes[reference] = ('a', (), '')
113
            node_refs.append(tuple(reference_list))
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
114
        if key in self._nodes and self._nodes[key][0] == '':
2592.1.15 by Robert Collins
Detect duplicate key insertion.
115
            raise errors.BadIndexDuplicateKey(key, self)
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
116
        self._nodes[key] = ('', tuple(node_refs), value)
2592.3.62 by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration.
117
        self._keys.add(key)
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
118
        if self._key_length > 1:
119
            key_dict = self._nodes_by_key
120
            if self.reference_lists:
121
                key_value = key, value, tuple(node_refs)
122
            else:
123
                key_value = key, value
124
            # possibly should do this on-demand, but it seems likely it is 
125
            # always wanted
2624.2.11 by Robert Collins
Review comments.
126
            # For a key of (foo, bar, baz) create
127
            # _nodes_by_key[foo][bar][baz] = key_value
128
            for subkey in key[:-1]:
129
                key_dict = key_dict.setdefault(subkey, {})
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
130
            key_dict[key[-1]] = key_value
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
131
2592.1.4 by Robert Collins
Create a GraphIndexBuilder.
132
    def finish(self):
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
133
        lines = [_SIGNATURE]
134
        lines.append(_OPTION_NODE_REFS + str(self.reference_lists) + '\n')
2624.2.8 by Robert Collins
Explicitly mark the number of keys elements in use in GraphIndex files.
135
        lines.append(_OPTION_KEY_ELEMENTS + str(self._key_length) + '\n')
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
136
        lines.append(_OPTION_LEN + str(len(self._keys)) + '\n')
2624.2.11 by Robert Collins
Review comments.
137
        prefix_length = sum(len(x) for x in lines)
2592.1.22 by Robert Collins
Node references are byte offsets.
138
        # references are byte offsets. To avoid having to do nasty
139
        # polynomial work to resolve offsets (references to later in the 
140
        # file cannot be determined until all the inbetween references have
141
        # been calculated too) we pad the offsets with 0's to make them be
142
        # of consistent length. Using binary offsets would break the trivial
143
        # file parsing.
144
        # to calculate the width of zero's needed we do three passes:
145
        # one to gather all the non-reference data and the number of references.
146
        # one to pad all the data with reference-length and determine entry
147
        # addresses.
148
        # One to serialise.
2592.1.40 by Robert Collins
Reverse index ordering - we do not have date prefixed revids.
149
        
150
        # forward sorted by key. In future we may consider topological sorting,
151
        # at the cost of table scans for direct lookup, or a second index for
152
        # direct lookup
153
        nodes = sorted(self._nodes.items())
2592.1.42 by Robert Collins
Check the index length is as expected, when we have done preprocessing.
154
        # if we do not prepass, we don't know how long it will be up front.
155
        expected_bytes = None
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
156
        # we only need to pre-pass if we have reference lists at all.
157
        if self.reference_lists:
2592.1.41 by Robert Collins
Remove duplication in the index serialisation logic with John's suggestion.
158
            key_offset_info = []
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
159
            non_ref_bytes = prefix_length
160
            total_references = 0
161
            # TODO use simple multiplication for the constants in this loop.
162
            for key, (absent, references, value) in nodes:
2592.1.41 by Robert Collins
Remove duplication in the index serialisation logic with John's suggestion.
163
                # record the offset known *so far* for this key:
164
                # the non reference bytes to date, and the total references to
165
                # date - saves reaccumulating on the second pass
166
                key_offset_info.append((key, non_ref_bytes, total_references))
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
167
                # key is literal, value is literal, there are 3 null's, 1 NL
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
168
                # key is variable length tuple, \x00 between elements
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
169
                non_ref_bytes += sum(len(element) for element in key)
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
170
                if self._key_length > 1:
171
                    non_ref_bytes += self._key_length - 1
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
172
                # value is literal bytes, there are 3 null's, 1 NL.
173
                non_ref_bytes += len(value) + 3 + 1
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
174
                # one byte for absent if set.
175
                if absent:
176
                    non_ref_bytes += 1
2592.1.36 by Robert Collins
Bugfix incorrect offset generation when an absent record is before a referenced record.
177
                elif self.reference_lists:
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
178
                    # (ref_lists -1) tabs
179
                    non_ref_bytes += self.reference_lists - 1
180
                    # (ref-1 cr's per ref_list)
181
                    for ref_list in references:
182
                        # how many references across the whole file?
183
                        total_references += len(ref_list)
184
                        # accrue reference separators
185
                        if ref_list:
186
                            non_ref_bytes += len(ref_list) - 1
187
            # how many digits are needed to represent the total byte count?
188
            digits = 1
2592.1.22 by Robert Collins
Node references are byte offsets.
189
            possible_total_bytes = non_ref_bytes + total_references*digits
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
190
            while 10 ** digits < possible_total_bytes:
191
                digits += 1
192
                possible_total_bytes = non_ref_bytes + total_references*digits
2592.1.42 by Robert Collins
Check the index length is as expected, when we have done preprocessing.
193
            expected_bytes = possible_total_bytes + 1 # terminating newline
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
194
            # resolve key addresses.
195
            key_addresses = {}
2592.1.41 by Robert Collins
Remove duplication in the index serialisation logic with John's suggestion.
196
            for key, non_ref_bytes, total_references in key_offset_info:
197
                key_addresses[key] = non_ref_bytes + total_references*digits
2592.1.25 by Robert Collins
Fix and tune node offset calculation.
198
            # serialise
199
            format_string = '%%0%sd' % digits
200
        for key, (absent, references, value) in nodes:
2592.1.19 by Robert Collins
Node references are tab separated.
201
            flattened_references = []
202
            for ref_list in references:
2592.1.22 by Robert Collins
Node references are byte offsets.
203
                ref_addresses = []
204
                for reference in ref_list:
205
                    ref_addresses.append(format_string % key_addresses[reference])
206
                flattened_references.append('\r'.join(ref_addresses))
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
207
            string_key = '\x00'.join(key)
2624.2.11 by Robert Collins
Review comments.
208
            lines.append("%s\x00%s\x00%s\x00%s\n" % (string_key, absent,
2592.1.19 by Robert Collins
Node references are tab separated.
209
                '\t'.join(flattened_references), value))
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
210
        lines.append('\n')
2592.1.42 by Robert Collins
Check the index length is as expected, when we have done preprocessing.
211
        result = StringIO(''.join(lines))
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
212
        if expected_bytes and len(result.getvalue()) != expected_bytes:
213
            raise errors.BzrError('Failed index creation. Internal error:'
214
                ' mismatched output length and expected length: %d %d' %
215
                (len(result.getvalue()), expected_bytes))
2592.1.6 by Robert Collins
Record the number of node reference lists a particular index has.
216
        return StringIO(''.join(lines))
2592.1.5 by Robert Collins
Trivial index reading.
217
218
219
class GraphIndex(object):
220
    """An index for data with embedded graphs.
2592.1.10 by Robert Collins
Make validate detect node reference parsing errors.
221
 
222
    The index maps keys to a list of key reference lists, and a value.
223
    Each node has the same number of key reference lists. Each key reference
224
    list can be empty or an arbitrary length. The value is an opaque NULL
2592.1.45 by Robert Collins
Tweak documentation as per Aaron's review.
225
    terminated string without any newlines. The storage of the index is 
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
226
    hidden in the interface: keys and key references are always tuples of
227
    bytestrings, never the internal representation (e.g. dictionary offsets).
2592.1.30 by Robert Collins
Absent entries are not yeilded.
228
229
    It is presumed that the index will not be mutated - it is static data.
2592.1.34 by Robert Collins
Cleanup docs.
230
2592.1.44 by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review.
231
    Successive iter_all_entries calls will read the entire index each time.
232
    Additionally, iter_entries calls will read the index linearly until the
233
    desired keys are found. XXX: This must be fixed before the index is
2592.1.34 by Robert Collins
Cleanup docs.
234
    suitable for production use. :XXX
2592.1.5 by Robert Collins
Trivial index reading.
235
    """
236
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
237
    def __init__(self, transport, name, size):
2592.1.5 by Robert Collins
Trivial index reading.
238
        """Open an index called name on transport.
239
240
        :param transport: A bzrlib.transport.Transport.
241
        :param name: A path to provide to transport API calls.
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
242
        :param size: The size of the index in bytes. This is used for bisection
243
            logic to perform partial index reads. While the size could be
244
            obtained by statting the file this introduced an additional round
2890.2.8 by Robert Collins
Make the size of the index optionally None for the pack-names index.
245
            trip as well as requiring stat'able transports, both of which are
246
            avoided by having it supplied. If size is None, then bisection
247
            support will be disabled and accessing the index will just stream
248
            all the data.
2592.1.5 by Robert Collins
Trivial index reading.
249
        """
250
        self._transport = transport
251
        self._name = name
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
252
        # becomes a dict of key:(value, reference-list-byte-locations) 
253
        # used by the bisection interface to store parsed but not resolved
254
        # keys.
255
        self._bisect_nodes = None
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
256
        self._nodes = None
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
257
        # a sorted list of slice-addresses for the parsed bytes of the file.
258
        # e.g. (0,1) would mean that byte 0 is parsed.
2890.2.2 by Robert Collins
Opening an index creates a map for the parsed bytes.
259
        self._parsed_byte_map = []
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
260
        # a sorted list of keys matching each slice address for parsed bytes
261
        # e.g. (None, 'foo@bar') would mean that the first byte contained no
262
        # key, and the end byte of the slice is the of the data for 'foo@bar'
263
        self._parsed_key_map = []
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
264
        self._key_count = None
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
265
        self._keys_by_offset = None
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
266
        self._nodes_by_key = None
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
267
        self._size = size
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
268
269
    def _buffer_all(self):
270
        """Buffer all the index data.
271
272
        Mutates self._nodes and self.keys_by_offset.
2592.1.5 by Robert Collins
Trivial index reading.
273
        """
2624.2.15 by Robert Collins
Add useful -Dindex flag.
274
        if 'index' in debug.debug_flags:
275
            mutter('Reading entire index %s', self._transport.abspath(self._name))
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
276
        stream = self._transport.get(self._name)
277
        self._read_prefix(stream)
2624.2.11 by Robert Collins
Review comments.
278
        expected_elements = 3 + self._key_length
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
279
        line_count = 0
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
280
        # raw data keyed by offset
281
        self._keys_by_offset = {}
282
        # ready-to-return key:value or key:value, node_ref_lists
283
        self._nodes = {}
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
284
        self._nodes_by_key = {}
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
285
        trailers = 0
286
        pos = stream.tell()
287
        for line in stream.readlines():
288
            if line == '\n':
289
                trailers += 1
290
                continue
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
291
            elements = line.split('\0')
2624.2.11 by Robert Collins
Review comments.
292
            if len(elements) != expected_elements:
293
                raise errors.BadIndexData(self)
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
294
            # keys are tuples
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
295
            key = tuple(elements[:self._key_length])
296
            absent, references, value = elements[-3:]
2592.1.43 by Robert Collins
Various index tweaks and test clarity from John's review.
297
            value = value[:-1] # remove the newline
2592.1.28 by Robert Collins
Basic two pass iter_all_entries.
298
            ref_lists = []
299
            for ref_string in references.split('\t'):
300
                ref_lists.append(tuple([
301
                    int(ref) for ref in ref_string.split('\r') if ref
302
                    ]))
303
            ref_lists = tuple(ref_lists)
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
304
            self._keys_by_offset[pos] = (key, absent, ref_lists, value)
2592.1.28 by Robert Collins
Basic two pass iter_all_entries.
305
            pos += len(line)
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
306
        for key, absent, references, value in self._keys_by_offset.itervalues():
2592.1.30 by Robert Collins
Absent entries are not yeilded.
307
            if absent:
308
                continue
2592.1.28 by Robert Collins
Basic two pass iter_all_entries.
309
            # resolve references:
310
            if self.node_ref_lists:
311
                node_refs = []
312
                for ref_list in references:
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
313
                    node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list]))
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
314
                node_value = (value, tuple(node_refs))
2592.1.28 by Robert Collins
Basic two pass iter_all_entries.
315
            else:
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
316
                node_value = value
317
            self._nodes[key] = node_value
318
            if self._key_length > 1:
319
                subkey = list(reversed(key[:-1]))
320
                key_dict = self._nodes_by_key
321
                if self.node_ref_lists:
322
                    key_value = key, node_value[0], node_value[1]
323
                else:
324
                    key_value = key, node_value
325
                # possibly should do this on-demand, but it seems likely it is 
326
                # always wanted
2624.2.11 by Robert Collins
Review comments.
327
                # For a key of (foo, bar, baz) create
328
                # _nodes_by_key[foo][bar][baz] = key_value
329
                for subkey in key[:-1]:
330
                    key_dict = key_dict.setdefault(subkey, {})
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
331
                key_dict[key[-1]] = key_value
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
332
        # cache the keys for quick set intersections
2592.3.54 by Robert Collins
Fix remaining performance discrepancy with regular repositories.
333
        self._keys = set(self._nodes)
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
334
        if trailers != 1:
335
            # there must be one line - the empty trailer line.
336
            raise errors.BadIndexData(self)
337
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
338
    def iter_all_entries(self):
339
        """Iterate over all keys within the index.
340
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
341
        :return: An iterable of (index, key, value) or (index, key, value, reference_lists).
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
342
            The former tuple is used when there are no reference lists in the
343
            index, making the API compatible with simple key:value index types.
344
            There is no defined order for the result iteration - it will be in
345
            the most efficient order for the index.
346
        """
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
347
        if 'evil' in debug.debug_flags:
2592.3.112 by Robert Collins
Various fixups found dogfooding.
348
            trace.mutter_callsite(3,
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.
349
                "iter_all_entries scales with size of history.")
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
350
        if self._nodes is None:
351
            self._buffer_all()
352
        if self.node_ref_lists:
353
            for key, (value, node_ref_lists) in self._nodes.iteritems():
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
354
                yield self, key, value, node_ref_lists
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
355
        else:
356
            for key, value in self._nodes.iteritems():
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
357
                yield self, key, value
2624.2.2 by Robert Collins
Temporary performance hack for GraphIndex : load the entire index once and only once into ram.
358
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
359
    def _read_prefix(self, stream):
360
        signature = stream.read(len(self._signature()))
361
        if not signature == self._signature():
362
            raise errors.BadIndexFormatSignature(self._name, GraphIndex)
363
        options_line = stream.readline()
364
        if not options_line.startswith(_OPTION_NODE_REFS):
365
            raise errors.BadIndexOptions(self)
366
        try:
367
            self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):-1])
368
        except ValueError:
369
            raise errors.BadIndexOptions(self)
2624.2.8 by Robert Collins
Explicitly mark the number of keys elements in use in GraphIndex files.
370
        options_line = stream.readline()
371
        if not options_line.startswith(_OPTION_KEY_ELEMENTS):
372
            raise errors.BadIndexOptions(self)
373
        try:
374
            self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):-1])
375
        except ValueError:
376
            raise errors.BadIndexOptions(self)
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
377
        options_line = stream.readline()
378
        if not options_line.startswith(_OPTION_LEN):
379
            raise errors.BadIndexOptions(self)
380
        try:
381
            self._key_count = int(options_line[len(_OPTION_LEN):-1])
382
        except ValueError:
383
            raise errors.BadIndexOptions(self)
2592.1.5 by Robert Collins
Trivial index reading.
384
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
385
    def _resolve_references(self, references):
386
        """Return the resolved key references for references."""
387
        node_refs = []
388
        for ref_list in references:
389
            node_refs.append(tuple([self._keys_by_offset[ref][0] for ref in ref_list]))
390
        return tuple(node_refs)
391
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
392
    def _find_index(self, range_map, key):
393
        """Helper for the _parsed_*_index calls.
394
395
        Given a range map - [(start, end), ...], finds the index of the range
396
        in the map for key if it is in the map, and if it is not there, the
397
        immediately preceeding range in the map.
398
        """
399
        result = bisect_right(range_map, key) - 1
400
        if result + 1 < len(range_map):
401
            # check the border condition, it may be in result + 1
402
            if range_map[result + 1][0] == key[0]:
403
                return result + 1
404
        return result
405
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
406
    def _parsed_byte_index(self, offset):
407
        """Return the index of the entry immediately before offset.
408
409
        e.g. if the parsed map has regions 0,10 and 11,12 parsed, meaning that
410
        there is one unparsed byte (the 11th, addressed as[10]). then:
411
        asking for 0 will return 0
412
        asking for 10 will return 0
413
        asking for 11 will return 1
414
        asking for 12 will return 1
415
        """
416
        key = (offset, 0)
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
417
        return self._find_index(self._parsed_byte_map, key)
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
418
419
    def _parsed_key_index(self, key):
420
        """Return the index of the entry immediately before key.
421
422
        e.g. if the parsed map has regions (None, 'a') and ('b','c') parsed,
423
        meaning that keys from None to 'a' inclusive, and 'b' to 'c' inclusive
424
        have been parsed, then:
425
        asking for '' will return 0
426
        asking for 'a' will return 0
427
        asking for 'b' will return 1
428
        asking for 'e' will return 1
429
        """
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
430
        search_key = (key, None)
431
        return self._find_index(self._parsed_key_map, search_key)
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
432
433
    def _is_parsed(self, offset):
434
        """Returns True if offset has been parsed."""
435
        index = self._parsed_byte_index(offset)
436
        if index == len(self._parsed_byte_map):
437
            return offset < self._parsed_byte_map[index - 1][1]
438
        start, end = self._parsed_byte_map[index]
439
        return offset >= start and offset < end
440
2890.2.7 by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a
441
    def _iter_entries_from_total_buffer(self, keys):
442
        """Iterate over keys when the entire index is parsed."""
2592.3.54 by Robert Collins
Fix remaining performance discrepancy with regular repositories.
443
        keys = keys.intersection(self._keys)
2624.2.3 by Robert Collins
Make GraphIndex.iter_entries do hash lookups rather than table scans.
444
        if self.node_ref_lists:
445
            for key in keys:
446
                value, node_refs = self._nodes[key]
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
447
                yield self, key, value, node_refs
2624.2.3 by Robert Collins
Make GraphIndex.iter_entries do hash lookups rather than table scans.
448
        else:
449
            for key in keys:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
450
                yield self, key, self._nodes[key]
2592.1.7 by Robert Collins
A validate that goes boom.
451
2890.2.7 by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a
452
    def iter_entries(self, keys):
453
        """Iterate over keys within the index.
454
455
        :param keys: An iterable providing the keys to be retrieved.
456
        :return: An iterable as per iter_all_entries, but restricted to the
457
            keys supplied. No additional keys will be returned, and every
458
            key supplied that is in the index will be returned.
459
        """
460
        keys = set(keys)
461
        if not keys:
462
            return []
2890.2.8 by Robert Collins
Make the size of the index optionally None for the pack-names index.
463
        if self._size is None and self._nodes is None:
464
            self._buffer_all()
2890.2.7 by Robert Collins
* Pack indices are now partially parsed for specific key lookup using a
465
        if self._nodes is not None:
466
            return self._iter_entries_from_total_buffer(keys)
467
        else:
468
            return (result[1] for result in bisect_multi_bytes(
469
                self.lookup_keys_via_location, self._size, keys))
470
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
471
    def iter_entries_prefix(self, keys):
472
        """Iterate over keys within the index using prefix matching.
473
474
        Prefix matching is applied within the tuple of a key, not to within
475
        the bytestring of each key element. e.g. if you have the keys ('foo',
476
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
477
        only the former key is returned.
478
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
479
        WARNING: Note that this method currently causes a full index parse
480
        unconditionally (which is reasonably appropriate as it is a means for
481
        thunking many small indices into one larger one and still supplies
482
        iter_all_entries at the thunk layer).
483
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
484
        :param keys: An iterable providing the key prefixes to be retrieved.
485
            Each key prefix takes the form of a tuple the length of a key, but
486
            with the last N elements 'None' rather than a regular bytestring.
487
            The first element cannot be 'None'.
488
        :return: An iterable as per iter_all_entries, but restricted to the
489
            keys with a matching prefix to those supplied. No additional keys
490
            will be returned, and every match that is in the index will be
491
            returned.
492
        """
493
        keys = set(keys)
494
        if not keys:
495
            return
496
        # load data - also finds key lengths
497
        if self._nodes is None:
498
            self._buffer_all()
499
        if self._key_length == 1:
500
            for key in keys:
501
                # sanity check
502
                if key[0] is None:
503
                    raise errors.BadIndexKey(key)
504
                if len(key) != self._key_length:
505
                    raise errors.BadIndexKey(key)
506
                if self.node_ref_lists:
507
                    value, node_refs = self._nodes[key]
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
508
                    yield self, key, value, node_refs
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
509
                else:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
510
                    yield self, key, self._nodes[key]
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
511
            return
512
        for key in keys:
513
            # sanity check
514
            if key[0] is None:
515
                raise errors.BadIndexKey(key)
516
            if len(key) != self._key_length:
517
                raise errors.BadIndexKey(key)
518
            # find what it refers to:
519
            key_dict = self._nodes_by_key
520
            elements = list(key)
2624.2.11 by Robert Collins
Review comments.
521
            # find the subdict whose contents should be returned.
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
522
            try:
523
                while len(elements) and elements[0] is not None:
524
                    key_dict = key_dict[elements[0]]
525
                    elements.pop(0)
526
            except KeyError:
527
                # a non-existant lookup.
528
                continue
529
            if len(elements):
530
                dicts = [key_dict]
531
                while dicts:
532
                    key_dict = dicts.pop(-1)
533
                    # can't be empty or would not exist
534
                    item, value = key_dict.iteritems().next()
535
                    if type(value) == dict:
536
                        # push keys 
537
                        dicts.extend(key_dict.itervalues())
538
                    else:
539
                        # yield keys
540
                        for value in key_dict.itervalues():
2624.2.11 by Robert Collins
Review comments.
541
                            # each value is the key:value:node refs tuple
542
                            # ready to yield.
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
543
                            yield (self, ) + value
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
544
            else:
2624.2.11 by Robert Collins
Review comments.
545
                # the last thing looked up was a terminal element
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
546
                yield (self, ) + key_dict
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
547
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
548
    def key_count(self):
549
        """Return an estimate of the number of keys in this index.
550
        
551
        For GraphIndex the estimate is exact.
552
        """
553
        if self._key_count is None:
554
            # really this should just read the prefix
555
            self._buffer_all()
556
        return self._key_count
557
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
558
    def lookup_keys_via_location(self, location_keys):
559
        """Public interface for implementing bisection.
560
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
561
        If _buffer_all has been called, then all the data for the index is in
562
        memory, and this method should not be called, as it uses a separate
563
        cache because it cannot pre-resolve all indices, which buffer_all does
564
        for performance.
565
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
566
        :param location_keys: A list of location, key tuples.
567
        :return: A list of (location_key, result) tuples as expected by
568
            bzrlib.bisect_multi.bisect_multi_bytes.
569
        """
570
        # Possible improvements:
571
        #  - only bisect lookup each key once
572
        #  - sort the keys first, and use that to reduce the bisection window
573
        # ----- 
574
        # this progresses in three parts:
575
        # read data
576
        # parse it
577
        # attempt to answer the question from the now in memory data.
578
        # build the readv request
579
        # for each location, ask for 800 bytes - much more than rows we've seen
580
        # anywhere.
581
        readv_ranges = []
582
        for location, key in location_keys:
583
            # can we answer from cache?
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
584
            # - if we know the answer - yes
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
585
            index = self._parsed_key_index(key)
586
            if (len(self._parsed_key_map) and 
587
                self._parsed_key_map[index][0] <= key and
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
588
                (self._parsed_key_map[index][1] > key or
589
                 # end of the file has been parsed
590
                 self._parsed_byte_map[index][1] == self._size)):
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
591
                # the key has been parsed, so no lookup is needed
592
                continue
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
593
            # - if we have examined this part of the file already - yes
594
            index = self._parsed_byte_index(location)
595
            if (len(self._parsed_byte_map) and 
596
                self._parsed_byte_map[index][0] <= location and
597
                self._parsed_byte_map[index][1] > location):
598
                # the byte region has been parsed, so no read is needed.
599
                continue
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
600
            length = 800
601
            if location + length > self._size:
602
                length = self._size - location
603
            # todo, trim out parsed locations.
604
            if length > 0:
605
                readv_ranges.append((location, length))
606
        # read the header if needed
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
607
        if self._bisect_nodes is None:
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
608
            readv_ranges.append((0, 200))
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
609
        self._read_and_parse(readv_ranges)
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
610
        # generate results:
611
        #  - figure out <, >, missing, present
612
        #  - result present references so we can return them.
613
        result = []
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
614
        # keys that we cannot answer until we resolve references
615
        pending_references = []
616
        pending_locations = set()
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
617
        for location, key in location_keys:
618
            # can we answer from cache?
619
            index = self._parsed_key_index(key)
620
            if (self._parsed_key_map[index][0] <= key and
621
                (self._parsed_key_map[index][1] > key or
622
                 # end of the file has been parsed
623
                 self._parsed_byte_map[index][1] == self._size)):
624
                # the key has been parsed, so no lookup is needed
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
625
                if key in self._bisect_nodes:
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
626
                    if self.node_ref_lists:
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
627
                        # the references may not have been all parsed.
628
                        value, refs = self._bisect_nodes[key]
629
                        wanted_locations = []
630
                        for ref_list in refs:
631
                            for ref in ref_list:
632
                                if ref not in self._keys_by_offset:
633
                                    wanted_locations.append(ref)
634
                        if wanted_locations:
635
                            pending_locations.update(wanted_locations)
636
                            pending_references.append((location, key))
637
                            continue
638
                        result.append(((location, key), (self, key,
639
                            value, self._resolve_references(refs))))
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
640
                    else:
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
641
                        result.append(((location, key),
642
                            (self, key, self._bisect_nodes[key])))
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
643
                else:
644
                    result.append(((location, key), False))
645
                continue
646
            # no, is the key above or below the probed location:
647
            # get the range of the probed & parsed location
648
            index = self._parsed_byte_index(location)
649
            # if the key is below the start of the range, its below
650
            if key < self._parsed_key_map[index][0]:
651
                direction = -1
652
            else:
653
                direction = +1
654
            result.append(((location, key), direction))
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
655
        readv_ranges = []
656
        # lookup data to resolve references
657
        for location in pending_locations:
658
            length = 800
659
            if location + length > self._size:
660
                length = self._size - location
661
            # TODO: trim out parsed locations (e.g. if the 800 is into the
662
            # parsed region trim it, and dont use the ajust_for_latency
663
            # facility)
664
            if length > 0:
665
                readv_ranges.append((location, length))
666
        self._read_and_parse(readv_ranges)
667
        for location, key in pending_references:
668
            # answer key references we had to look-up-late.
669
            index = self._parsed_key_index(key)
670
            value, refs = self._bisect_nodes[key]
671
            result.append(((location, key), (self, key,
672
                value, self._resolve_references(refs))))
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
673
        return result
674
675
    def _parse_header_from_bytes(self, bytes):
676
        """Parse the header from a region of bytes.
677
678
        :param bytes: The data to parse.
679
        :return: An offset, data tuple such as readv yields, for the unparsed
680
            data. (which may length 0).
681
        """
682
        signature = bytes[0:len(self._signature())]
683
        if not signature == self._signature():
684
            raise errors.BadIndexFormatSignature(self._name, GraphIndex)
685
        lines = bytes[len(self._signature()):].splitlines()
686
        options_line = lines[0]
687
        if not options_line.startswith(_OPTION_NODE_REFS):
688
            raise errors.BadIndexOptions(self)
689
        try:
690
            self.node_ref_lists = int(options_line[len(_OPTION_NODE_REFS):])
691
        except ValueError:
692
            raise errors.BadIndexOptions(self)
693
        options_line = lines[1]
694
        if not options_line.startswith(_OPTION_KEY_ELEMENTS):
695
            raise errors.BadIndexOptions(self)
696
        try:
697
            self._key_length = int(options_line[len(_OPTION_KEY_ELEMENTS):])
698
        except ValueError:
699
            raise errors.BadIndexOptions(self)
700
        options_line = lines[2]
701
        if not options_line.startswith(_OPTION_LEN):
702
            raise errors.BadIndexOptions(self)
703
        try:
704
            self._key_count = int(options_line[len(_OPTION_LEN):])
705
        except ValueError:
706
            raise errors.BadIndexOptions(self)
707
        # calculate the bytes we have processed
708
        header_end = (len(signature) + len(lines[0]) + len(lines[1]) +
709
            len(lines[2]) + 3)
710
        self._parsed_bytes(0, None, header_end, None)
711
        # setup parsing state
712
        self._expected_elements = 3 + self._key_length
713
        # raw data keyed by offset
714
        self._keys_by_offset = {}
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
715
        # keys with the value and node references
716
        self._bisect_nodes = {}
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
717
        return header_end, bytes[header_end:]
718
719
    def _parse_region(self, offset, data):
720
        """Parse node data returned from a readv operation.
721
722
        :param offset: The byte offset the data starts at.
723
        :param data: The data to parse.
724
        """
725
        # trim the data.
726
        # end first:
727
        end = offset + len(data)
728
        index = self._parsed_byte_index(offset)
729
        # default is to use all data
730
        trim_end = None
731
        # trivial check for entirely parsed data:
732
        if end < self._parsed_byte_map[index][1]:
733
            return
734
        # accomodate overlap with data before this.
735
        if offset < self._parsed_byte_map[index][1]:
736
            # overlaps the lower parsed region
737
            # skip the parsed data
738
            trim_start = self._parsed_byte_map[index][1] - offset
739
            # don't trim the start for \n
740
            start_adjacent = True
741
        elif offset == self._parsed_byte_map[index][1]:
742
            # abuts the lower parsed region
743
            # use all data
744
            trim_start = None
745
            # do not trim anything
746
            start_adjacent = True
747
        else:
748
            # does not overlap the lower parsed region
749
            # use all data
750
            trim_start = None
751
            # but trim the leading \n
752
            start_adjacent = False
753
        if end == self._size:
754
            # lines up to the end of all data:
755
            # use it all
756
            trim_end = None
757
            # do not strip to the last \n
758
            end_adjacent = True
759
        elif index + 1 == len(self._parsed_byte_map):
760
            # at the end of the parsed data
761
            # use it all
762
            trim_end = None
763
            # but strip to the last \n
764
            end_adjacent = False
765
        elif end == self._parsed_byte_map[index + 1][0]:
766
            # buts up against the next parsed region
767
            # use it all
768
            trim_end = None
769
            # do not strip to the last \n
770
            end_adjacent = True
771
        elif end > self._parsed_byte_map[index + 1][0]:
772
            # overlaps into the next parsed region
773
            # only consider the unparsed data
774
            trim_end = self._parsed_byte_map[index + 1][0] - offset
775
            # do not strip to the last \n as we know its an entire record
776
            end_adjacent = True
777
        else:
778
            # does not overlap into the next region
779
            # use it all
780
            trim_end = None
781
            # but strip to the last \n
782
            end_adjacent = False
783
        # now find bytes to discard if needed
784
        if not start_adjacent:
785
            # work around python bug in rfind
786
            if trim_start is None:
787
                trim_start = data.find('\n') + 1
788
            else:
789
                trim_start = data.find('\n', trim_start) + 1
790
            assert trim_start != 0, 'no \n was present'
791
            # print 'removing start', offset, trim_start, repr(data[:trim_start])
792
        if not end_adjacent:
793
            # work around python bug in rfind
794
            if trim_end is None:
795
                trim_end = data.rfind('\n') + 1
796
            else:
797
                trim_end = data.rfind('\n', None, trim_end) + 1
798
            assert trim_end != 0, 'no \n was present'
799
            # print 'removing end', offset, trim_end, repr(data[trim_end:])
800
        # adjust offset and data to the parseable data.
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
801
        trimmed_data = data[trim_start:trim_end]
802
        assert trimmed_data, 'read unneeded data'
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
803
        if trim_start:
804
            offset += trim_start
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
805
        # print "parsing", repr(trimmed_data)
2890.2.10 by Robert Collins
Add test coverage to ensure \r's are not mangled by bisection parsing.
806
        # splitlines mangles the \r delimiters.. don't use it.
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
807
        lines = trimmed_data.split('\n')
2890.2.9 by Robert Collins
Don't use splitlines for index data parsing, we embed \r.
808
        del lines[-1]
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
809
        pos = offset
810
        first_key = None
811
        key = None
812
        for line in lines:
813
            if line == '':
814
                # must be at the end
815
                assert self._size == pos + 1, "%s %s" % (self._size, pos)
816
                continue
817
            elements = line.split('\0')
818
            if len(elements) != self._expected_elements:
819
                raise errors.BadIndexData(self)
820
            # keys are tuples
821
            key = tuple(elements[:self._key_length])
822
            if first_key is None:
823
                first_key = key
824
            absent, references, value = elements[-3:]
825
            ref_lists = []
826
            for ref_string in references.split('\t'):
827
                ref_lists.append(tuple([
828
                    int(ref) for ref in ref_string.split('\r') if ref
829
                    ]))
830
            ref_lists = tuple(ref_lists)
831
            self._keys_by_offset[pos] = (key, absent, ref_lists, value)
832
            pos += len(line) + 1 # +1 for the \n
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
833
            if absent:
834
                continue
835
            if self.node_ref_lists:
836
                node_value = (value, ref_lists)
837
            else:
838
                node_value = value
839
            self._bisect_nodes[key] = node_value
840
            # print "parsed ", key
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
841
        self._parsed_bytes(offset, first_key, offset + len(trimmed_data), key)
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
842
843
    def _parsed_bytes(self, start, start_key, end, end_key):
844
        """Mark the bytes from start to end as parsed.
845
846
        Calling self._parsed_bytes(1,2) will mark one byte (the one at offset
847
        1) as parsed.
848
849
        :param start: The start of the parsed region.
850
        :param end: The end of the parsed region.
851
        """
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
852
        index = self._parsed_byte_index(start)
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
853
        new_value = (start, end)
854
        new_key = (start_key, end_key)
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
855
        if index == -1:
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
856
            # first range parsed is always the beginning.
857
            self._parsed_byte_map.insert(index, new_value)
858
            self._parsed_key_map.insert(index, new_key)
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
859
            return
860
        # four cases:
861
        # new region
862
        # extend lower region
863
        # extend higher region
864
        # combine two regions
865
        if (index + 1 < len(self._parsed_byte_map) and
866
            self._parsed_byte_map[index][1] == start and
867
            self._parsed_byte_map[index + 1][0] == end):
868
            # combine two regions
869
            self._parsed_byte_map[index] = (self._parsed_byte_map[index][0],
870
                self._parsed_byte_map[index + 1][1])
871
            self._parsed_key_map[index] = (self._parsed_key_map[index][0],
872
                self._parsed_key_map[index + 1][1])
873
        elif self._parsed_byte_map[index][1] == start:
874
            # extend the lower entry
875
            self._parsed_byte_map[index] = (
876
                self._parsed_byte_map[index][0], end)
877
            self._parsed_key_map[index] = (
878
                self._parsed_key_map[index][0], end_key)
879
        elif (index + 1 < len(self._parsed_byte_map) and
880
            self._parsed_byte_map[index + 1][0] == end):
881
            # extend the higher entry
882
            self._parsed_byte_map[index + 1] = (
883
                start, self._parsed_byte_map[index + 1][1])
884
            self._parsed_key_map[index + 1] = (
885
                start_key, self._parsed_key_map[index + 1][1])
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
886
        else:
2890.2.11 by Robert Collins
Bisection improvements after integrating with packs.
887
            # new entry
888
            self._parsed_byte_map.insert(index + 1, new_value)
889
            self._parsed_key_map.insert(index + 1, new_key)
890
        assert sorted(self._parsed_byte_map) == self._parsed_byte_map
891
        assert sorted(self._parsed_key_map) == self._parsed_key_map
2890.2.5 by Robert Collins
Create a content lookup function for bisection in GraphIndex.
892
2890.2.6 by Robert Collins
Add support for key references to the index lookup_keys_via_location bisection interface.
893
    def _read_and_parse(self, readv_ranges):
894
        """Read the the ranges and parse the resulting data.
895
896
        :param readv_ranges: A prepared readv range list.
897
        """
898
        if readv_ranges:
899
            readv_data = self._transport.readv(self._name, readv_ranges, True,
900
                self._size)
901
            # parse
902
            for offset, data in readv_data:
903
                if self._bisect_nodes is None:
904
                    # this must be the start
905
                    assert offset == 0
906
                    offset, data = self._parse_header_from_bytes(data)
907
                self._parse_region(offset, data)
908
                # print offset, len(data), data
909
2592.1.8 by Robert Collins
Empty files should validate ok.
910
    def _signature(self):
911
        """The file signature for this index type."""
912
        return _SIGNATURE
913
2592.1.7 by Robert Collins
A validate that goes boom.
914
    def validate(self):
915
        """Validate that everything in the index can be accessed."""
2592.1.27 by Robert Collins
Test missing end lines with non-empty indices.
916
        # iter_all validates completely at the moment, so just do that.
917
        for node in self.iter_all_entries():
918
            pass
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
919
920
921
class CombinedGraphIndex(object):
922
    """A GraphIndex made up from smaller GraphIndices.
923
    
924
    The backing indices must implement GraphIndex, and are presumed to be
925
    static data.
2592.1.45 by Robert Collins
Tweak documentation as per Aaron's review.
926
927
    Queries against the combined index will be made against the first index,
928
    and then the second and so on. The order of index's can thus influence
929
    performance significantly. For example, if one index is on local disk and a
930
    second on a remote server, the local disk index should be before the other
931
    in the index list.
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
932
    """
933
934
    def __init__(self, indices):
935
        """Create a CombinedGraphIndex backed by indices.
936
2592.1.45 by Robert Collins
Tweak documentation as per Aaron's review.
937
        :param indices: An ordered list of indices to query for data.
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
938
        """
939
        self._indices = indices
2592.1.37 by Robert Collins
Add CombinedGraphIndex.insert_index.
940
2592.5.4 by Martin Pool
Add CombinedGraphIndex repr
941
    def __repr__(self):
942
        return "%s(%s)" % (
943
                self.__class__.__name__,
944
                ', '.join(map(repr, self._indices)))
945
2592.1.37 by Robert Collins
Add CombinedGraphIndex.insert_index.
946
    def insert_index(self, pos, index):
947
        """Insert a new index in the list of indices to query.
948
949
        :param pos: The position to insert the index.
950
        :param index: The index to insert.
951
        """
952
        self._indices.insert(pos, index)
953
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
954
    def iter_all_entries(self):
955
        """Iterate over all keys within the index
956
2592.1.44 by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review.
957
        Duplicate keys across child indices are presumed to have the same
958
        value and are only reported once.
959
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
960
        :return: An iterable of (index, key, reference_lists, value).
961
            There is no defined order for the result iteration - it will be in
962
            the most efficient order for the index.
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
963
        """
964
        seen_keys = set()
965
        for index in self._indices:
966
            for node in index.iter_all_entries():
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
967
                if node[1] not in seen_keys:
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
968
                    yield node
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
969
                    seen_keys.add(node[1])
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
970
971
    def iter_entries(self, keys):
972
        """Iterate over keys within the index.
973
2592.1.44 by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review.
974
        Duplicate keys across child indices are presumed to have the same
975
        value and are only reported once.
976
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
977
        :param keys: An iterable providing the keys to be retrieved.
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
978
        :return: An iterable of (index, key, reference_lists, value). There is no
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
979
            defined order for the result iteration - it will be in the most
980
            efficient order for the index.
981
        """
982
        keys = set(keys)
2592.1.39 by Robert Collins
CombinedGraphIndex.iter_entries does not need to see all entries.
983
        for index in self._indices:
2592.1.44 by Robert Collins
Remove some unneeded index iteration by checking if we have found all keys, and grammar improvements from Aaron's review.
984
            if not keys:
985
                return
2592.1.39 by Robert Collins
CombinedGraphIndex.iter_entries does not need to see all entries.
986
            for node in index.iter_entries(keys):
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
987
                keys.remove(node[1])
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
988
                yield node
989
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
990
    def iter_entries_prefix(self, keys):
991
        """Iterate over keys within the index using prefix matching.
992
993
        Duplicate keys across child indices are presumed to have the same
994
        value and are only reported once.
995
996
        Prefix matching is applied within the tuple of a key, not to within
997
        the bytestring of each key element. e.g. if you have the keys ('foo',
998
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
999
        only the former key is returned.
1000
1001
        :param keys: An iterable providing the key prefixes to be retrieved.
1002
            Each key prefix takes the form of a tuple the length of a key, but
1003
            with the last N elements 'None' rather than a regular bytestring.
1004
            The first element cannot be 'None'.
1005
        :return: An iterable as per iter_all_entries, but restricted to the
1006
            keys with a matching prefix to those supplied. No additional keys
1007
            will be returned, and every match that is in the index will be
1008
            returned.
1009
        """
1010
        keys = set(keys)
1011
        if not keys:
1012
            return
1013
        seen_keys = set()
1014
        for index in self._indices:
1015
            for node in index.iter_entries_prefix(keys):
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1016
                if node[1] in seen_keys:
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
1017
                    continue
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1018
                seen_keys.add(node[1])
2624.2.9 by Robert Collins
Introduce multiple component keys, which is what is needed to combine multiple knit indices into one.
1019
                yield node
1020
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
1021
    def key_count(self):
1022
        """Return an estimate of the number of keys in this index.
1023
        
1024
        For CombinedGraphIndex this is approximated by the sum of the keys of
1025
        the child indices. As child indices may have duplicate keys this can
1026
        have a maximum error of the number of child indices * largest number of
1027
        keys in any index.
1028
        """
1029
        return sum((index.key_count() for index in self._indices), 0)
1030
2592.1.31 by Robert Collins
Build a combined graph index to use multiple indices at once.
1031
    def validate(self):
1032
        """Validate that everything in the index can be accessed."""
1033
        for index in self._indices:
1034
            index.validate()
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1035
1036
1037
class InMemoryGraphIndex(GraphIndexBuilder):
1038
    """A GraphIndex which operates entirely out of memory and is mutable.
1039
1040
    This is designed to allow the accumulation of GraphIndex entries during a
1041
    single write operation, where the accumulated entries need to be immediately
1042
    available - for example via a CombinedGraphIndex.
1043
    """
1044
1045
    def add_nodes(self, nodes):
1046
        """Add nodes to the index.
1047
1048
        :param nodes: An iterable of (key, node_refs, value) entries to add.
1049
        """
2592.3.39 by Robert Collins
Fugly version to remove signatures.kndx
1050
        if self.reference_lists:
1051
            for (key, value, node_refs) in nodes:
1052
                self.add_node(key, value, node_refs)
1053
        else:
1054
            for (key, value) in nodes:
1055
                self.add_node(key, value)
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1056
1057
    def iter_all_entries(self):
1058
        """Iterate over all keys within the index
1059
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
1060
        :return: An iterable of (index, key, reference_lists, value). There is no
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1061
            defined order for the result iteration - it will be in the most
1062
            efficient order for the index (in this case dictionary hash order).
1063
        """
2745.1.1 by Robert Collins
Add a number of -Devil checkpoints.
1064
        if 'evil' in debug.debug_flags:
2592.3.112 by Robert Collins
Various fixups found dogfooding.
1065
            trace.mutter_callsite(3,
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.
1066
                "iter_all_entries scales with size of history.")
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1067
        if self.reference_lists:
1068
            for key, (absent, references, value) in self._nodes.iteritems():
1069
                if not absent:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1070
                    yield self, key, value, references
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1071
        else:
1072
            for key, (absent, references, value) in self._nodes.iteritems():
1073
                if not absent:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1074
                    yield self, key, value
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1075
1076
    def iter_entries(self, keys):
1077
        """Iterate over keys within the index.
1078
1079
        :param keys: An iterable providing the keys to be retrieved.
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
1080
        :return: An iterable of (index, key, reference_lists, value). There is no
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1081
            defined order for the result iteration - it will be in the most
1082
            efficient order for the index (keys iteration order in this case).
1083
        """
1084
        keys = set(keys)
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1085
        if self.reference_lists:
2592.3.62 by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration.
1086
            for key in keys.intersection(self._keys):
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1087
                node = self._nodes[key]
1088
                if not node[0]:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1089
                    yield self, key, node[2], node[1]
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1090
        else:
2592.3.62 by Robert Collins
Performance tweak - use a set for InMemoryGraph key iteration.
1091
            for key in keys.intersection(self._keys):
2592.1.46 by Robert Collins
Make GraphIndex accept nodes as key, value, references, so that the method
1092
                node = self._nodes[key]
1093
                if not node[0]:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1094
                    yield self, key, node[2]
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1095
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1096
    def iter_entries_prefix(self, keys):
1097
        """Iterate over keys within the index using prefix matching.
1098
1099
        Prefix matching is applied within the tuple of a key, not to within
1100
        the bytestring of each key element. e.g. if you have the keys ('foo',
1101
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
1102
        only the former key is returned.
1103
1104
        :param keys: An iterable providing the key prefixes to be retrieved.
1105
            Each key prefix takes the form of a tuple the length of a key, but
1106
            with the last N elements 'None' rather than a regular bytestring.
1107
            The first element cannot be 'None'.
1108
        :return: An iterable as per iter_all_entries, but restricted to the
1109
            keys with a matching prefix to those supplied. No additional keys
1110
            will be returned, and every match that is in the index will be
1111
            returned.
1112
        """
1113
        # XXX: To much duplication with the GraphIndex class; consider finding
1114
        # a good place to pull out the actual common logic.
1115
        keys = set(keys)
1116
        if not keys:
1117
            return
1118
        if self._key_length == 1:
1119
            for key in keys:
1120
                # sanity check
1121
                if key[0] is None:
1122
                    raise errors.BadIndexKey(key)
1123
                if len(key) != self._key_length:
1124
                    raise errors.BadIndexKey(key)
1125
                node = self._nodes[key]
1126
                if node[0]:
1127
                    continue 
1128
                if self.reference_lists:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1129
                    yield self, key, node[2], node[1]
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1130
                else:
2624.2.17 by Robert Collins
Review feedback.
1131
                    yield self, key, node[2]
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1132
            return
1133
        for key in keys:
1134
            # sanity check
1135
            if key[0] is None:
1136
                raise errors.BadIndexKey(key)
1137
            if len(key) != self._key_length:
1138
                raise errors.BadIndexKey(key)
1139
            # find what it refers to:
1140
            key_dict = self._nodes_by_key
1141
            elements = list(key)
1142
            # find the subdict to return
1143
            try:
1144
                while len(elements) and elements[0] is not None:
1145
                    key_dict = key_dict[elements[0]]
1146
                    elements.pop(0)
1147
            except KeyError:
1148
                # a non-existant lookup.
1149
                continue
1150
            if len(elements):
1151
                dicts = [key_dict]
1152
                while dicts:
1153
                    key_dict = dicts.pop(-1)
1154
                    # can't be empty or would not exist
1155
                    item, value = key_dict.iteritems().next()
1156
                    if type(value) == dict:
1157
                        # push keys 
1158
                        dicts.extend(key_dict.itervalues())
1159
                    else:
1160
                        # yield keys
1161
                        for value in key_dict.itervalues():
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1162
                            yield (self, ) + value
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1163
            else:
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1164
                yield (self, ) + key_dict
2624.2.10 by Robert Collins
Also add iter_key_prefix support to InMemoryGraphIndex.
1165
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
1166
    def key_count(self):
1167
        """Return an estimate of the number of keys in this index.
1168
        
1169
        For InMemoryGraphIndex the estimate is exact.
1170
        """
1171
        return len(self._keys)
1172
2592.1.38 by Robert Collins
Create an InMemoryGraphIndex for temporary indexing.
1173
    def validate(self):
1174
        """In memory index's have no known corruption at the moment."""
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1175
1176
1177
class GraphIndexPrefixAdapter(object):
1178
    """An adapter between GraphIndex with different key lengths.
1179
1180
    Queries against this will emit queries against the adapted Graph with the
1181
    prefix added, queries for all items use iter_entries_prefix. The returned
1182
    nodes will have their keys and node references adjusted to remove the 
1183
    prefix. Finally, an add_nodes_callback can be supplied - when called the
1184
    nodes and references being added will have prefix prepended.
1185
    """
1186
2624.2.17 by Robert Collins
Review feedback.
1187
    def __init__(self, adapted, prefix, missing_key_length,
1188
        add_nodes_callback=None):
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1189
        """Construct an adapter against adapted with prefix."""
1190
        self.adapted = adapted
2624.2.19 by Robert Collins
Why we should always test before committing.
1191
        self.prefix_key = prefix + (None,)*missing_key_length
2624.2.17 by Robert Collins
Review feedback.
1192
        self.prefix = prefix
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1193
        self.prefix_len = len(prefix)
1194
        self.add_nodes_callback = add_nodes_callback
1195
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1196
    def add_nodes(self, nodes):
1197
        """Add nodes to the index.
1198
1199
        :param nodes: An iterable of (key, node_refs, value) entries to add.
1200
        """
1201
        # save nodes in case its an iterator
1202
        nodes = tuple(nodes)
1203
        translated_nodes = []
1204
        try:
2624.2.17 by Robert Collins
Review feedback.
1205
            # Add prefix_key to each reference node_refs is a tuple of tuples,
1206
            # so split it apart, and add prefix_key to the internal reference
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1207
            for (key, value, node_refs) in nodes:
1208
                adjusted_references = (
2624.2.17 by Robert Collins
Review feedback.
1209
                    tuple(tuple(self.prefix + ref_node for ref_node in ref_list)
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1210
                        for ref_list in node_refs))
2624.2.17 by Robert Collins
Review feedback.
1211
                translated_nodes.append((self.prefix + key, value,
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1212
                    adjusted_references))
1213
        except ValueError:
1214
            # XXX: TODO add an explicit interface for getting the reference list
1215
            # status, to handle this bit of user-friendliness in the API more 
1216
            # explicitly.
1217
            for (key, value) in nodes:
2624.2.17 by Robert Collins
Review feedback.
1218
                translated_nodes.append((self.prefix + key, value))
2624.2.13 by Robert Collins
Implement add_node/add_nodes to the GraphIndexPrefixAdapter.
1219
        self.add_nodes_callback(translated_nodes)
1220
1221
    def add_node(self, key, value, references=()):
1222
        """Add a node to the index.
1223
1224
        :param key: The key. keys are non-empty tuples containing
1225
            as many whitespace-free utf8 bytestrings as the key length
1226
            defined for this index.
1227
        :param references: An iterable of iterables of keys. Each is a
1228
            reference to another key.
1229
        :param value: The value to associate with the key. It may be any
1230
            bytes as long as it does not contain \0 or \n.
1231
        """
1232
        self.add_nodes(((key, value, references), ))
1233
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1234
    def _strip_prefix(self, an_iter):
1235
        """Strip prefix data from nodes and return it."""
1236
        for node in an_iter:
1237
            # cross checks
2624.2.17 by Robert Collins
Review feedback.
1238
            if node[1][:self.prefix_len] != self.prefix:
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1239
                raise errors.BadIndexData(self)
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1240
            for ref_list in node[3]:
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1241
                for ref_node in ref_list:
2624.2.17 by Robert Collins
Review feedback.
1242
                    if ref_node[:self.prefix_len] != self.prefix:
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1243
                        raise errors.BadIndexData(self)
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1244
            yield node[0], node[1][self.prefix_len:], node[2], (
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1245
                tuple(tuple(ref_node[self.prefix_len:] for ref_node in ref_list)
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1246
                for ref_list in node[3]))
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1247
1248
    def iter_all_entries(self):
1249
        """Iterate over all keys within the index
1250
1251
        iter_all_entries is implemented against the adapted index using
1252
        iter_entries_prefix.
1253
2592.5.1 by Martin Pool
Fix docstrings for Index.iter_entries etc
1254
        :return: An iterable of (index, key, reference_lists, value). There is no
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1255
            defined order for the result iteration - it will be in the most
1256
            efficient order for the index (in this case dictionary hash order).
1257
        """
2624.2.19 by Robert Collins
Why we should always test before committing.
1258
        return self._strip_prefix(self.adapted.iter_entries_prefix([self.prefix_key]))
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1259
1260
    def iter_entries(self, keys):
1261
        """Iterate over keys within the index.
1262
1263
        :param keys: An iterable providing the keys to be retrieved.
1264
        :return: An iterable of (key, reference_lists, value). There is no
1265
            defined order for the result iteration - it will be in the most
1266
            efficient order for the index (keys iteration order in this case).
1267
        """
1268
        return self._strip_prefix(self.adapted.iter_entries(
2624.2.17 by Robert Collins
Review feedback.
1269
            self.prefix + key for key in keys))
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1270
1271
    def iter_entries_prefix(self, keys):
1272
        """Iterate over keys within the index using prefix matching.
1273
1274
        Prefix matching is applied within the tuple of a key, not to within
1275
        the bytestring of each key element. e.g. if you have the keys ('foo',
1276
        'bar'), ('foobar', 'gam') and do a prefix search for ('foo', None) then
1277
        only the former key is returned.
1278
1279
        :param keys: An iterable providing the key prefixes to be retrieved.
1280
            Each key prefix takes the form of a tuple the length of a key, but
1281
            with the last N elements 'None' rather than a regular bytestring.
1282
            The first element cannot be 'None'.
1283
        :return: An iterable as per iter_all_entries, but restricted to the
1284
            keys with a matching prefix to those supplied. No additional keys
1285
            will be returned, and every match that is in the index will be
1286
            returned.
1287
        """
1288
        return self._strip_prefix(self.adapted.iter_entries_prefix(
2624.2.17 by Robert Collins
Review feedback.
1289
            self.prefix + key for key in keys))
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1290
2624.2.16 by Robert Collins
Add a key_count method to GraphIndex and friends, allowing optimisation of length calculations by the index.
1291
    def key_count(self):
1292
        """Return an estimate of the number of keys in this index.
1293
        
1294
        For GraphIndexPrefixAdapter this is relatively expensive - key
1295
        iteration with the prefix is done.
1296
        """
1297
        return len(list(self.iter_all_entries()))
1298
2624.2.12 by Robert Collins
Create an adapter between indices with differing key lengths.
1299
    def validate(self):
1300
        """Call the adapted's validate."""
1301
        self.adapted.validate()